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>
96 #include <linux/netlink.h>
98 #include <linux/if_arp.h>
99 #ifndef ARPHRD_IEEE802154
100 // Linux before 2.6.31
101 #define ARPHRD_IEEE802154 804
103 #ifndef ARPHRD_IEEE802154_MONITOR
105 #define ARPHRD_IEEE802154_MONITOR 805
107 #ifndef ARPHRD_NETLINK
109 #define ARPHRD_NETLINK 824
111 #ifndef ARPHRD_6LOWPAN
113 #define ARPHRD_6LOWPAN 825
115 #ifndef ARPHRD_VSOCKMON
117 #define ARPHRD_VSOCKMON 826
121 * ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
122 * is needed, please report it to <daniele@orlandi.com>
124 #define ARPHRD_LAPD 8445
129 #include <sys/eventfd.h>
131 #include "pcap-int.h"
132 #include "pcap-util.h"
133 #include "pcap-snf.h"
134 #include "pcap/sll.h"
135 #include "pcap/vlan.h"
136 #include "pcap/can_socketcan.h"
138 #include "diag-control.h"
141 * We require TPACKET_V2 support.
143 #ifndef TPACKET2_HDRLEN
144 #error "Libpcap will only work if TPACKET_V2 is supported; you must build for a 2.6.27 or later kernel"
147 /* check for memory mapped access availability. We assume every needed
148 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
149 * uses many ring related structs and macros */
150 #ifdef TPACKET3_HDRLEN
151 # define HAVE_TPACKET3
152 #endif /* TPACKET3_HDRLEN */
155 * Not all compilers that are used to compile code to run on Linux have
156 * these builtins. For example, older versions of GCC don't, and at
157 * least some people are doing cross-builds for MIPS with older versions
160 #ifndef HAVE___ATOMIC_LOAD_N
161 #define __atomic_load_n(ptr, memory_model) (*(ptr))
163 #ifndef HAVE___ATOMIC_STORE_N
164 #define __atomic_store_n(ptr, val, memory_model) *(ptr) = (val)
167 #define packet_mmap_acquire(pkt) \
168 (__atomic_load_n(&pkt->tp_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
169 #define packet_mmap_release(pkt) \
170 (__atomic_store_n(&pkt->tp_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
171 #define packet_mmap_v3_acquire(pkt) \
172 (__atomic_load_n(&pkt->hdr.bh1.block_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
173 #define packet_mmap_v3_release(pkt) \
174 (__atomic_store_n(&pkt->hdr.bh1.block_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
176 #include <linux/types.h>
177 #include <linux/filter.h>
179 #ifdef HAVE_LINUX_NET_TSTAMP_H
180 #include <linux/net_tstamp.h>
184 * For checking whether a device is a bonding device.
186 #include <linux/if_bonding.h>
192 #include <linux/nl80211.h>
194 #include <netlink/genl/genl.h>
195 #include <netlink/genl/family.h>
196 #include <netlink/genl/ctrl.h>
197 #include <netlink/msg.h>
198 #include <netlink/attr.h>
199 #endif /* HAVE_LIBNL */
201 #ifndef HAVE_SOCKLEN_T
202 typedef int socklen_t
;
205 #define MAX_LINKHEADER_SIZE 256
208 * When capturing on all interfaces we use this as the buffer size.
209 * Should be bigger then all MTUs that occur in real life.
210 * 64kB should be enough for now.
212 #define BIGGER_THAN_ALL_MTUS (64*1024)
215 * Private data for capturing on Linux PF_PACKET sockets.
218 long long sysfs_dropped
; /* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */
219 struct pcap_stat stat
;
221 char *device
; /* device name */
222 int filter_in_userland
; /* must filter in userland */
223 u_int blocks_to_filter_in_userland
;
224 int must_do_on_close
; /* stuff we must do when we close */
225 int timeout
; /* timeout for buffering */
226 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
227 int ifindex
; /* interface index of device we're bound to */
228 int lo_ifindex
; /* interface index of the loopback device */
229 int netdown
; /* we got an ENETDOWN and haven't resolved it */
230 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
231 char *mondevice
; /* mac80211 monitor device we created */
232 u_char
*mmapbuf
; /* memory-mapped region pointer */
233 size_t mmapbuflen
; /* size of region */
234 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
235 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
236 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
237 u_char
*oneshot_buffer
; /* buffer for copy of packet */
238 int poll_timeout
; /* timeout to use in poll() */
240 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
241 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
243 int poll_breakloop_fd
; /* fd to an eventfd to break from blocking operations */
247 * Stuff to do when we close.
249 #define MUST_DELETE_MONIF 0x00000001 /* delete monitor-mode interface */
252 * Prototypes for internal functions and methods.
254 static int is_wifi(const char *);
255 static int pcap_activate_linux(pcap_t
*);
256 static int setup_socket(pcap_t
*, int);
257 static int setup_mmapped(pcap_t
*);
258 static int pcap_can_set_rfmon_linux(pcap_t
*);
259 static int pcap_inject_linux(pcap_t
*, const void *, int);
260 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
261 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
262 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
263 static int pcap_set_datalink_linux(pcap_t
*, int);
266 struct tpacket2_hdr
*h2
;
268 struct tpacket_block_desc
*h3
;
273 #define RING_GET_FRAME_AT(h, offset) (((u_char **)h->buffer)[(offset)])
274 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
276 static void destroy_ring(pcap_t
*handle
);
277 static int create_ring(pcap_t
*handle
);
278 static int prepare_tpacket_socket(pcap_t
*handle
);
279 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
281 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
283 static int pcap_setnonblock_linux(pcap_t
*p
, int nonblock
);
284 static int pcap_getnonblock_linux(pcap_t
*p
);
285 static void pcapint_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
286 const u_char
*bytes
);
289 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
290 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
291 * or "on VLAN 0". There is no flag set in the tp_status field to
292 * distinguish between them.
294 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
295 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
296 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
297 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
299 * With a pre-3.0 kernel, we cannot distinguish between packets with no
300 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
301 * there's nothing we can do about that.
303 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
304 * continue the behavior of earlier libpcaps, wherein we treated packets
305 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
306 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
307 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
308 * VLAN tags. This does the right thing on 3.0 and later kernels, and
309 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
311 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
312 * has that value in 3.0 and later kernels.
314 #ifdef TP_STATUS_VLAN_VALID
315 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
318 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
319 * so we test with the value it has in the 3.0 and later kernels, so
320 * we can test it if we're running on a system that has it. (If we're
321 * running on a system that doesn't have it, it won't be set in the
322 * tp_status field, so the tests of it will always fail; that means
323 * we behave the way we did before we introduced this macro.)
325 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
328 #ifdef TP_STATUS_VLAN_TPID_VALID
329 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
331 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
335 * Required select timeout if we're polling for an "interface disappeared"
336 * indication - 1 millisecond.
338 static const struct timeval netdown_timeout
= {
339 0, 1000 /* 1000 microseconds = 1 millisecond */
343 * Wrap some ioctl calls
345 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
346 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
347 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
348 static int iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
);
349 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
351 static int iface_get_ts_types(const char *device
, pcap_t
*handle
,
353 static int iface_get_offload(pcap_t
*handle
);
355 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
356 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
357 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
358 static int reset_kernel_filter(pcap_t
*handle
);
360 static struct sock_filter total_insn
361 = BPF_STMT(BPF_RET
| BPF_K
, 0);
362 static struct sock_fprog total_fcode
363 = { 1, &total_insn
};
365 static int iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
);
368 pcapint_create_interface(const char *device
, char *ebuf
)
372 handle
= PCAP_CREATE_COMMON(ebuf
, struct pcap_linux
);
376 handle
->activate_op
= pcap_activate_linux
;
377 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
380 * See what time stamp types we support.
382 if (iface_get_ts_types(device
, handle
, ebuf
) == -1) {
388 * We claim that we support microsecond and nanosecond time
391 * XXX - with adapter-supplied time stamps, can we choose
392 * microsecond or nanosecond time stamps on arbitrary
395 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
396 if (handle
->tstamp_precision_list
== NULL
) {
397 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
402 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
403 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
404 handle
->tstamp_precision_count
= 2;
407 * Start out with the breakloop handle not open; we don't
408 * need it until we're activated and ready to capture.
410 struct pcap_linux
*handlep
= handle
->priv
;
411 handlep
->poll_breakloop_fd
= -1;
418 * If interface {if_name} is a mac80211 driver, the file
419 * /sys/class/net/{if_name}/phy80211 is a symlink to
420 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
422 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
423 * least, has a "wmaster0" device and a "wlan0" device; the
424 * latter is the one with the IP address. Both show up in
425 * "tcpdump -D" output. Capturing on the wmaster0 device
426 * captures with 802.11 headers.
428 * airmon-ng searches through /sys/class/net for devices named
429 * monN, starting with mon0; as soon as one *doesn't* exist,
430 * it chooses that as the monitor device name. If the "iw"
431 * command exists, it does
433 * iw dev {if_name} interface add {monif_name} type monitor
435 * where {monif_name} is the monitor device. It then (sigh) sleeps
436 * .1 second, and then configures the device up. Otherwise, if
437 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
438 * {mondev_name}, without a newline, to that file, and again (sigh)
439 * sleeps .1 second, and then iwconfig's that device into monitor
440 * mode and configures it up. Otherwise, you can't do monitor mode.
442 * All these devices are "glued" together by having the
443 * /sys/class/net/{if_name}/phy80211 links pointing to the same
444 * place, so, given a wmaster, wlan, or mon device, you can
445 * find the other devices by looking for devices with
446 * the same phy80211 link.
448 * To turn monitor mode off, delete the monitor interface,
451 * iw dev {monif_name} interface del
453 * or by sending {monif_name}, with no NL, down
454 * /sys/class/ieee80211/{phydev_name}/remove_iface
456 * Note: if you try to create a monitor device named "monN", and
457 * there's already a "monN" device, it fails, as least with
458 * the netlink interface (which is what iw uses), with a return
459 * value of -ENFILE. (Return values are negative errnos.) We
460 * could probably use that to find an unused device.
462 * Yes, you can have multiple monitor devices for a given
467 * Is this a mac80211 device? If so, fill in the physical device path and
468 * return 1; if not, return 0. On an error, fill in handle->errbuf and
472 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
473 size_t phydev_max_pathlen
)
479 * Generate the path string for the symlink to the physical device.
481 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
482 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
483 "%s: Can't generate path name string for /sys/class/net device",
487 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
488 if (bytes_read
== -1) {
489 if (errno
== ENOENT
) {
491 * This either means that the directory
492 * /sys/class/net/{device} exists but doesn't
493 * have anything named "phy80211" in it,
494 * in which case it's not a mac80211 device,
495 * or that the directory doesn't exist,
496 * in which case the device doesn't exist.
498 * Directly check whether the directory
504 if (asprintf(&pathstr
, "/sys/class/net/%s", device
) == -1) {
505 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
506 "%s: Can't generate path name string for /sys/class/net device",
510 if (stat(pathstr
, &statb
) == -1) {
511 if (errno
== ENOENT
) {
515 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
516 "%s: %s doesn't exist",
519 return PCAP_ERROR_NO_SUCH_DEVICE
;
521 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
522 "%s: Can't stat %s: %s",
523 device
, pathstr
, strerror(errno
));
529 * Path to the directory that would contain
530 * "phy80211" exists, but "phy80211" doesn't
531 * exist; that means it's not a mac80211
537 if (errno
== EINVAL
) {
539 * Exists, but it's not a symlink; assume that
540 * means it's not a mac80211 device.
545 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
546 errno
, "%s: Can't readlink %s", device
, pathstr
);
551 phydev_path
[bytes_read
] = '\0';
555 struct nl80211_state
{
556 struct nl_sock
*nl_sock
;
557 struct nl_cache
*nl_cache
;
558 struct genl_family
*nl80211
;
562 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
566 state
->nl_sock
= nl_socket_alloc();
567 if (!state
->nl_sock
) {
568 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
569 "%s: failed to allocate netlink handle", device
);
573 if (genl_connect(state
->nl_sock
)) {
574 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
575 "%s: failed to connect to generic netlink", device
);
576 goto out_handle_destroy
;
579 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
581 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
582 "%s: failed to allocate generic netlink cache: %s",
583 device
, nl_geterror(-err
));
584 goto out_handle_destroy
;
587 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
588 if (!state
->nl80211
) {
589 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
590 "%s: nl80211 not found", device
);
597 nl_cache_free(state
->nl_cache
);
599 nl_socket_free(state
->nl_sock
);
604 nl80211_cleanup(struct nl80211_state
*state
)
606 genl_family_put(state
->nl80211
);
607 nl_cache_free(state
->nl_cache
);
608 nl_socket_free(state
->nl_sock
);
612 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
613 const char *device
, const char *mondevice
);
616 if_type_cb(struct nl_msg
*msg
, void* arg
)
618 struct nlmsghdr
* ret_hdr
= nlmsg_hdr(msg
);
619 struct nlattr
*tb_msg
[NL80211_ATTR_MAX
+ 1];
620 int *type
= (int*)arg
;
622 struct genlmsghdr
*gnlh
= (struct genlmsghdr
*) nlmsg_data(ret_hdr
);
624 nla_parse(tb_msg
, NL80211_ATTR_MAX
, genlmsg_attrdata(gnlh
, 0),
625 genlmsg_attrlen(gnlh
, 0), NULL
);
627 if (!tb_msg
[NL80211_ATTR_IFTYPE
]) {
631 *type
= nla_get_u32(tb_msg
[NL80211_ATTR_IFTYPE
]);
636 get_if_type(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
637 const char *device
, int *type
)
643 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
647 struct nl_cb
*cb
= nl_cb_alloc(NL_CB_DEFAULT
);
648 nl_cb_set(cb
, NL_CB_VALID
, NL_CB_CUSTOM
, if_type_cb
, (void*)type
);
652 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
653 "%s: failed to allocate netlink msg", device
);
657 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
658 0, NL80211_CMD_GET_INTERFACE
, 0);
659 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
661 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
663 if (err
== -NLE_FAILURE
) {
665 * Device not available; our caller should just
666 * keep trying. (libnl 2.x maps ENFILE to
667 * NLE_FAILURE; it can also map other errors
668 * to that, but there's not much we can do
675 * Real failure, not just "that device is not
678 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
679 "%s: nl_send_auto_complete failed getting interface type: %s",
680 device
, nl_geterror(-err
));
686 nl_recvmsgs(state
->nl_sock
, cb
);
696 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
697 "%s: nl_put failed getting interface type",
704 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
705 const char *device
, const char *mondevice
)
707 struct pcap_linux
*handlep
= handle
->priv
;
712 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
718 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
719 "%s: failed to allocate netlink msg", device
);
723 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
724 0, NL80211_CMD_NEW_INTERFACE
, 0);
725 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
727 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
729 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
731 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
733 if (err
== -NLE_FAILURE
) {
735 * Device not available; our caller should just
736 * keep trying. (libnl 2.x maps ENFILE to
737 * NLE_FAILURE; it can also map other errors
738 * to that, but there's not much we can do
745 * Real failure, not just "that device is not
748 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
749 "%s: nl_send_auto_complete failed adding %s interface: %s",
750 device
, mondevice
, nl_geterror(-err
));
755 err
= nl_wait_for_ack(state
->nl_sock
);
757 if (err
== -NLE_FAILURE
) {
759 * Device not available; our caller should just
760 * keep trying. (libnl 2.x maps ENFILE to
761 * NLE_FAILURE; it can also map other errors
762 * to that, but there's not much we can do
769 * Real failure, not just "that device is not
772 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
773 "%s: nl_wait_for_ack failed adding %s interface: %s",
774 device
, mondevice
, nl_geterror(-err
));
786 * Try to remember the monitor device.
788 handlep
->mondevice
= strdup(mondevice
);
789 if (handlep
->mondevice
== NULL
) {
790 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
793 * Get rid of the monitor device.
795 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
801 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
802 "%s: nl_put failed adding %s interface",
809 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
810 const char *device
, const char *mondevice
)
816 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
822 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
823 "%s: failed to allocate netlink msg", device
);
827 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
828 0, NL80211_CMD_DEL_INTERFACE
, 0);
829 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
831 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
833 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
834 "%s: nl_send_auto_complete failed deleting %s interface: %s",
835 device
, mondevice
, nl_geterror(-err
));
839 err
= nl_wait_for_ack(state
->nl_sock
);
841 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
842 "%s: nl_wait_for_ack failed deleting %s interface: %s",
843 device
, mondevice
, nl_geterror(-err
));
855 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
856 "%s: nl_put failed deleting %s interface",
861 #endif /* HAVE_LIBNL */
863 static int pcap_protocol(pcap_t
*handle
)
867 protocol
= handle
->opt
.protocol
;
869 protocol
= ETH_P_ALL
;
871 return htons(protocol
);
875 pcap_can_set_rfmon_linux(pcap_t
*handle
)
878 char phydev_path
[PATH_MAX
+1];
882 if (strcmp(handle
->opt
.device
, "any") == 0) {
884 * Monitor mode makes no sense on the "any" device.
891 * Bleah. There doesn't seem to be a way to ask a mac80211
892 * device, through libnl, whether it supports monitor mode;
893 * we'll just check whether the device appears to be a
894 * mac80211 device and, if so, assume the device supports
897 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
900 return ret
; /* error */
902 return 1; /* mac80211 device */
909 * Grabs the number of missed packets by the interface from
910 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
912 * Compared to /proc/net/dev this avoids counting software drops,
913 * but may be unimplemented and just return 0.
914 * The author has found no straightforward way to check for support.
917 linux_get_stat(const char * if_name
, const char * stat
) {
920 char buffer
[PATH_MAX
];
922 snprintf(buffer
, sizeof(buffer
), "/sys/class/net/%s/statistics/%s", if_name
, stat
);
923 fd
= open(buffer
, O_RDONLY
);
927 bytes_read
= read(fd
, buffer
, sizeof(buffer
) - 1);
929 if (bytes_read
== -1)
931 buffer
[bytes_read
] = '\0';
933 return strtoll(buffer
, NULL
, 10);
937 linux_if_drops(const char * if_name
)
939 long long int missed
= linux_get_stat(if_name
, "rx_missed_errors");
940 long long int fifo
= linux_get_stat(if_name
, "rx_fifo_errors");
941 return missed
+ fifo
;
946 * Monitor mode is kind of interesting because we have to reset the
947 * interface before exiting. The problem can't really be solved without
948 * some daemon taking care of managing usage counts. If we put the
949 * interface into monitor mode, we set a flag indicating that we must
950 * take it out of that mode when the interface is closed, and, when
951 * closing the interface, if that flag is set we take it out of monitor
955 static void pcap_cleanup_linux( pcap_t
*handle
)
957 struct pcap_linux
*handlep
= handle
->priv
;
959 struct nl80211_state nlstate
;
961 #endif /* HAVE_LIBNL */
963 if (handlep
->must_do_on_close
!= 0) {
965 * There's something we have to do when closing this
969 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
970 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
972 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
973 handlep
->device
, handlep
->mondevice
);
974 nl80211_cleanup(&nlstate
);
978 "Can't delete monitor interface %s (%s).\n"
979 "Please delete manually.\n",
980 handlep
->mondevice
, handle
->errbuf
);
983 #endif /* HAVE_LIBNL */
986 * Take this pcap out of the list of pcaps for which we
987 * have to take the interface out of some mode.
989 pcapint_remove_from_pcaps_to_close(handle
);
992 if (handle
->fd
!= -1) {
994 * Destroy the ring buffer (assuming we've set it up),
995 * and unmap it if it's mapped.
997 destroy_ring(handle
);
1000 if (handlep
->oneshot_buffer
!= NULL
) {
1001 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
1002 handlep
->oneshot_buffer
= NULL
;
1005 if (handlep
->mondevice
!= NULL
) {
1006 free(handlep
->mondevice
);
1007 handlep
->mondevice
= NULL
;
1009 if (handlep
->device
!= NULL
) {
1010 free(handlep
->device
);
1011 handlep
->device
= NULL
;
1014 if (handlep
->poll_breakloop_fd
!= -1) {
1015 close(handlep
->poll_breakloop_fd
);
1016 handlep
->poll_breakloop_fd
= -1;
1018 pcapint_cleanup_live_common(handle
);
1021 #ifdef HAVE_TPACKET3
1023 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1024 * around which we have to work. Determine if we have those
1026 * 3.19 is the first release with a fixed version of
1027 * TPACKET_V3. We treat anything before that as
1028 * not having a fixed version; that may really mean
1029 * it has *no* version.
1031 static int has_broken_tpacket_v3(void)
1033 struct utsname utsname
;
1034 const char *release
;
1036 int matches
, verlen
;
1038 /* No version information, assume broken. */
1039 if (uname(&utsname
) == -1)
1041 release
= utsname
.release
;
1043 /* A malformed version, ditto. */
1044 matches
= sscanf(release
, "%ld.%ld%n", &major
, &minor
, &verlen
);
1047 if (release
[verlen
] != '.' && release
[verlen
] != '\0')
1050 /* OK, a fixed version. */
1051 if (major
> 3 || (major
== 3 && minor
>= 19))
1060 * Set the timeout to be used in poll() with memory-mapped packet capture.
1063 set_poll_timeout(struct pcap_linux
*handlep
)
1065 #ifdef HAVE_TPACKET3
1066 int broken_tpacket_v3
= has_broken_tpacket_v3();
1068 if (handlep
->timeout
== 0) {
1069 #ifdef HAVE_TPACKET3
1071 * XXX - due to a set of (mis)features in the TPACKET_V3
1072 * kernel code prior to the 3.19 kernel, blocking forever
1073 * with a TPACKET_V3 socket can, if few packets are
1074 * arriving and passing the socket filter, cause most
1075 * packets to be dropped. See libpcap issue #335 for the
1076 * full painful story.
1078 * The workaround is to have poll() time out very quickly,
1079 * so we grab the frames handed to us, and return them to
1082 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1083 handlep
->poll_timeout
= 1; /* don't block for very long */
1086 handlep
->poll_timeout
= -1; /* block forever */
1087 } else if (handlep
->timeout
> 0) {
1088 #ifdef HAVE_TPACKET3
1090 * For TPACKET_V3, the timeout is handled by the kernel,
1091 * so block forever; that way, we don't get extra timeouts.
1092 * Don't do that if we have a broken TPACKET_V3, though.
1094 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1095 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1098 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1101 * Non-blocking mode; we call poll() to pick up error
1102 * indications, but we don't want it to wait for
1105 handlep
->poll_timeout
= 0;
1109 static void pcap_breakloop_linux(pcap_t
*handle
)
1111 pcapint_breakloop_common(handle
);
1112 struct pcap_linux
*handlep
= handle
->priv
;
1116 if (handlep
->poll_breakloop_fd
!= -1) {
1118 * XXX - pcap_breakloop() doesn't have a return value,
1119 * so we can't indicate an error.
1121 DIAG_OFF_WARN_UNUSED_RESULT
1122 (void)write(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
1123 DIAG_ON_WARN_UNUSED_RESULT
1128 * Set the offset at which to insert VLAN tags.
1129 * That should be the offset of the type field.
1132 set_vlan_offset(pcap_t
*handle
)
1134 struct pcap_linux
*handlep
= handle
->priv
;
1136 switch (handle
->linktype
) {
1140 * The type field is after the destination and source
1143 handlep
->vlan_offset
= 2 * ETH_ALEN
;
1148 * The type field is in the last 2 bytes of the
1149 * DLT_LINUX_SLL header.
1151 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
1155 handlep
->vlan_offset
= -1; /* unknown */
1161 pcap_activate_linux(pcap_t
*handle
)
1163 struct pcap_linux
*handlep
= handle
->priv
;
1170 device
= handle
->opt
.device
;
1173 * Start out assuming no warnings.
1178 * Make sure the name we were handed will fit into the ioctls we
1179 * might perform on the device; if not, return a "No such device"
1180 * indication, as the Linux kernel shouldn't support creating
1181 * a device whose name won't fit into those ioctls.
1183 * "Will fit" means "will fit, complete with a null terminator",
1184 * so if the length, which does *not* include the null terminator,
1185 * is greater than *or equal to* the size of the field into which
1186 * we'll be copying it, that won't fit.
1188 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1190 * There's nothing more to say, so clear the error
1193 handle
->errbuf
[0] = '\0';
1194 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1199 * Turn a negative snapshot value (invalid), a snapshot value of
1200 * 0 (unspecified), or a value bigger than the normal maximum
1201 * value, into the maximum allowed value.
1203 * If some application really *needs* a bigger snapshot
1204 * length, we should just increase MAXIMUM_SNAPLEN.
1206 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
1207 handle
->snapshot
= MAXIMUM_SNAPLEN
;
1209 handlep
->device
= strdup(device
);
1210 if (handlep
->device
== NULL
) {
1211 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1213 status
= PCAP_ERROR
;
1218 * The "any" device is a special device which causes us not
1219 * to bind to a particular device and thus to look at all
1222 is_any_device
= (strcmp(device
, "any") == 0);
1223 if (is_any_device
) {
1224 if (handle
->opt
.promisc
) {
1225 handle
->opt
.promisc
= 0;
1226 /* Just a warning. */
1227 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1228 "Promiscuous mode not supported on the \"any\" device");
1229 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1233 /* copy timeout value */
1234 handlep
->timeout
= handle
->opt
.timeout
;
1237 * If we're in promiscuous mode, then we probably want
1238 * to see when the interface drops packets too, so get an
1239 * initial count from
1240 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1242 if (handle
->opt
.promisc
)
1243 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1246 * If the "any" device is specified, try to open a SOCK_DGRAM.
1247 * Otherwise, open a SOCK_RAW.
1249 ret
= setup_socket(handle
, is_any_device
);
1252 * Fatal error; the return value is the error code,
1253 * and handle->errbuf has been set to an appropriate
1261 * We got a warning; return that, as handle->errbuf
1262 * might have been overwritten by this warning.
1268 * Success (possibly with a warning).
1270 * First, try to allocate an event FD for breakloop, if
1271 * we're not going to start in non-blocking mode.
1273 if (!handle
->opt
.nonblock
) {
1274 handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
);
1275 if (handlep
->poll_breakloop_fd
== -1) {
1279 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
1280 PCAP_ERRBUF_SIZE
, errno
, "could not open eventfd");
1281 status
= PCAP_ERROR
;
1288 * Try to set up memory-mapped access.
1290 ret
= setup_mmapped(handle
);
1293 * We failed to set up to use it, or the
1294 * kernel supports it, but we failed to
1295 * enable it. The return value is the
1296 * error status to return and, if it's
1297 * PCAP_ERROR, handle->errbuf contains
1298 * the error message.
1305 * We got a warning; return that, as handle->errbuf
1306 * might have been overwritten by this warning.
1312 * We succeeded. status has been set to the status to return,
1313 * which might be 0, or might be a PCAP_WARNING_ value.
1316 * Now that we have activated the mmap ring, we can
1317 * set the correct protocol.
1319 if ((ret
= iface_bind(handle
->fd
, handlep
->ifindex
,
1320 handle
->errbuf
, pcap_protocol(handle
))) != 0) {
1325 handle
->inject_op
= pcap_inject_linux
;
1326 handle
->setfilter_op
= pcap_setfilter_linux
;
1327 handle
->setdirection_op
= pcap_setdirection_linux
;
1328 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1329 handle
->setnonblock_op
= pcap_setnonblock_linux
;
1330 handle
->getnonblock_op
= pcap_getnonblock_linux
;
1331 handle
->cleanup_op
= pcap_cleanup_linux
;
1332 handle
->stats_op
= pcap_stats_linux
;
1333 handle
->breakloop_op
= pcap_breakloop_linux
;
1335 switch (handlep
->tp_version
) {
1338 handle
->read_op
= pcap_read_linux_mmap_v2
;
1340 #ifdef HAVE_TPACKET3
1342 handle
->read_op
= pcap_read_linux_mmap_v3
;
1346 handle
->oneshot_callback
= pcapint_oneshot_linux
;
1347 handle
->selectable_fd
= handle
->fd
;
1352 pcap_cleanup_linux(handle
);
1357 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1359 handle
->linktype
= dlt
;
1362 * Update the offset at which to insert VLAN tags for the
1363 * new link-layer type.
1365 set_vlan_offset(handle
);
1371 * linux_check_direction()
1373 * Do checks based on packet direction.
1376 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1378 struct pcap_linux
*handlep
= handle
->priv
;
1380 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1383 * If this is from the loopback device, reject it;
1384 * we'll see the packet as an incoming packet as well,
1385 * and we don't want to see it twice.
1387 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1391 * If this is an outgoing CAN frame, and the user doesn't
1392 * want only outgoing packets, reject it; CAN devices
1393 * and drivers, and the CAN stack, always arrange to
1394 * loop back transmitted packets, so they also appear
1395 * as incoming packets. We don't want duplicate packets,
1396 * and we can't easily distinguish packets looped back
1397 * by the CAN layer than those received by the CAN layer,
1398 * so we eliminate this packet instead.
1400 * We check whether this is a CAN frame by checking whether
1401 * the device's hardware type is ARPHRD_CAN.
1403 if (sll
->sll_hatype
== ARPHRD_CAN
&&
1404 handle
->direction
!= PCAP_D_OUT
)
1408 * If the user only wants incoming packets, reject it.
1410 if (handle
->direction
== PCAP_D_IN
)
1415 * If the user only wants outgoing packets, reject it.
1417 if (handle
->direction
== PCAP_D_OUT
)
1424 * Check whether the device to which the pcap_t is bound still exists.
1425 * We do so by asking what address the socket is bound to, and checking
1426 * whether the ifindex in the address is -1, meaning "that device is gone",
1427 * or some other value, meaning "that device still exists".
1430 device_still_exists(pcap_t
*handle
)
1432 struct pcap_linux
*handlep
= handle
->priv
;
1433 struct sockaddr_ll addr
;
1437 * If handlep->ifindex is -1, the socket isn't bound, meaning
1438 * we're capturing on the "any" device; that device never
1439 * disappears. (It should also never be configured down, so
1440 * we shouldn't even get here, but let's make sure.)
1442 if (handlep
->ifindex
== -1)
1443 return (1); /* it's still here */
1446 * OK, now try to get the address for the socket.
1448 addr_len
= sizeof (addr
);
1449 if (getsockname(handle
->fd
, (struct sockaddr
*) &addr
, &addr_len
) == -1) {
1451 * Error - report an error and return -1.
1453 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1454 errno
, "getsockname failed");
1457 if (addr
.sll_ifindex
== -1) {
1459 * This means the device went away.
1465 * The device presumably just went down.
1471 pcap_inject_linux(pcap_t
*handle
, const void *buf
, int size
)
1473 struct pcap_linux
*handlep
= handle
->priv
;
1476 if (handlep
->ifindex
== -1) {
1478 * We don't support sending on the "any" device.
1480 pcapint_strlcpy(handle
->errbuf
,
1481 "Sending packets isn't supported on the \"any\" device",
1486 if (handlep
->cooked
) {
1488 * We don't support sending on cooked-mode sockets.
1490 * XXX - how do you send on a bound cooked-mode
1492 * Is a "sendto()" required there?
1494 pcapint_strlcpy(handle
->errbuf
,
1495 "Sending packets isn't supported in cooked mode",
1500 ret
= (int)send(handle
->fd
, buf
, size
, 0);
1502 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1510 * Get the statistics for the given packet capture handle.
1513 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1515 struct pcap_linux
*handlep
= handle
->priv
;
1516 #ifdef HAVE_TPACKET3
1518 * For sockets using TPACKET_V2, the extra stuff at the end
1519 * of a struct tpacket_stats_v3 will not be filled in, and
1520 * we don't look at it so this is OK even for those sockets.
1521 * In addition, the PF_PACKET socket code in the kernel only
1522 * uses the length parameter to compute how much data to
1523 * copy out and to indicate how much data was copied out, so
1524 * it's OK to base it on the size of a struct tpacket_stats.
1526 * XXX - it's probably OK, in fact, to just use a
1527 * struct tpacket_stats for V3 sockets, as we don't
1528 * care about the tp_freeze_q_cnt stat.
1530 struct tpacket_stats_v3 kstats
;
1531 #else /* HAVE_TPACKET3 */
1532 struct tpacket_stats kstats
;
1533 #endif /* HAVE_TPACKET3 */
1534 socklen_t len
= sizeof (struct tpacket_stats
);
1536 long long if_dropped
= 0;
1539 * To fill in ps_ifdrop, we parse
1540 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1543 if (handle
->opt
.promisc
)
1546 * XXX - is there any reason to do this by remembering
1547 * the last counts value, subtracting it from the
1548 * current counts value, and adding that to stat.ps_ifdrop,
1549 * maintaining stat.ps_ifdrop as a count, rather than just
1550 * saving the *initial* counts value and setting
1551 * stat.ps_ifdrop to the difference between the current
1552 * value and the initial value?
1554 * One reason might be to handle the count wrapping
1555 * around, on platforms where the count is 32 bits
1556 * and where you might get more than 2^32 dropped
1557 * packets; is there any other reason?
1559 * (We maintain the count as a long long int so that,
1560 * if the kernel maintains the counts as 64-bit even
1561 * on 32-bit platforms, we can handle the real count.
1563 * Unfortunately, we can't report 64-bit counts; we
1564 * need a better API for reporting statistics, such as
1565 * one that reports them in a style similar to the
1566 * pcapng Interface Statistics Block, so that 1) the
1567 * counts are 64-bit, 2) it's easier to add new statistics
1568 * without breaking the ABI, and 3) it's easier to
1569 * indicate to a caller that wants one particular
1570 * statistic that it's not available by just not supplying
1573 if_dropped
= handlep
->sysfs_dropped
;
1574 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1575 handlep
->stat
.ps_ifdrop
+= (u_int
)(handlep
->sysfs_dropped
- if_dropped
);
1579 * Try to get the packet counts from the kernel.
1581 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1582 &kstats
, &len
) > -1) {
1584 * "ps_recv" counts only packets that *passed* the
1585 * filter, not packets that didn't pass the filter.
1586 * This includes packets later dropped because we
1587 * ran out of buffer space.
1589 * "ps_drop" counts packets dropped because we ran
1590 * out of buffer space. It doesn't count packets
1591 * dropped by the interface driver. It counts only
1592 * packets that passed the filter.
1594 * See above for ps_ifdrop.
1596 * Both statistics include packets not yet read from
1597 * the kernel by libpcap, and thus not yet seen by
1600 * In "linux/net/packet/af_packet.c", at least in 2.6.27
1601 * through 5.6 kernels, "tp_packets" is incremented for
1602 * every packet that passes the packet filter *and* is
1603 * successfully copied to the ring buffer; "tp_drops" is
1604 * incremented for every packet dropped because there's
1605 * not enough free space in the ring buffer.
1607 * When the statistics are returned for a PACKET_STATISTICS
1608 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1609 * so that "tp_packets" counts all packets handed to
1610 * the PF_PACKET socket, including packets dropped because
1611 * there wasn't room on the socket buffer - but not
1612 * including packets that didn't pass the filter.
1614 * In the BSD BPF, the count of received packets is
1615 * incremented for every packet handed to BPF, regardless
1616 * of whether it passed the filter.
1618 * We can't make "pcap_stats()" work the same on both
1619 * platforms, but the best approximation is to return
1620 * "tp_packets" as the count of packets and "tp_drops"
1621 * as the count of drops.
1623 * Keep a running total because each call to
1624 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1625 * resets the counters to zero.
1627 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1628 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1629 *stats
= handlep
->stat
;
1633 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1634 "failed to get statistics from socket");
1639 * A PF_PACKET socket can be bound to any network interface.
1642 can_be_bound(const char *name _U_
)
1648 * Get a socket to use with various interface ioctls.
1651 get_if_ioctl_socket(void)
1656 * This is a bit ugly.
1658 * There isn't a socket type that's guaranteed to work.
1660 * AF_NETLINK will work *if* you have Netlink configured into the
1661 * kernel (can it be configured out if you have any networking
1662 * support at all?) *and* if you're running a sufficiently recent
1663 * kernel, but not all the kernels we support are sufficiently
1664 * recent - that feature was introduced in Linux 4.6.
1666 * AF_UNIX will work *if* you have UNIX-domain sockets configured
1667 * into the kernel and *if* you're not on a system that doesn't
1668 * allow them - some SELinux systems don't allow you create them.
1669 * Most systems probably have them configured in, but not all systems
1670 * have them configured in and allow them to be created.
1672 * AF_INET will work *if* you have IPv4 configured into the kernel,
1673 * but, apparently, some systems have network adapters but have
1674 * kernels without IPv4 support.
1676 * AF_INET6 will work *if* you have IPv6 configured into the
1677 * kernel, but if you don't have AF_INET, you might not have
1678 * AF_INET6, either (that is, independently on its own grounds).
1680 * AF_PACKET would work, except that some of these calls should
1681 * work even if you *don't* have capture permission (you should be
1682 * able to enumerate interfaces and get information about them
1683 * without capture permission; you shouldn't get a failure until
1684 * you try pcap_activate()). (If you don't allow programs to
1685 * get as much information as possible about interfaces if you
1686 * don't have permission to capture, you run the risk of users
1687 * asking "why isn't it showing XXX" - or, worse, if you don't
1688 * show interfaces *at all* if you don't have permission to
1689 * capture on them, "why do no interfaces show up?" - when the
1690 * real problem is a permissions problem. Error reports of that
1691 * type require a lot more back-and-forth to debug, as evidenced
1692 * by many Wireshark bugs/mailing list questions/Q&A questions.)
1696 * we first try an AF_NETLINK socket, where "try" includes
1697 * "try to do a device ioctl on it", as, in the future, once
1698 * pre-4.6 kernels are sufficiently rare, that will probably
1699 * be the mechanism most likely to work;
1701 * if that fails, we try an AF_UNIX socket, as that's less
1702 * likely to be configured out on a networking-capable system
1705 * if that fails, we try an AF_INET6 socket;
1707 * if that fails, we try an AF_INET socket.
1709 fd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_GENERIC
);
1712 * OK, let's make sure we can do an SIOCGIFNAME
1717 memset(&ifr
, 0, sizeof(ifr
));
1718 if (ioctl(fd
, SIOCGIFNAME
, &ifr
) == 0 ||
1719 errno
!= EOPNOTSUPP
) {
1721 * It succeeded, or failed for some reason
1722 * other than "netlink sockets don't support
1723 * device ioctls". Go with the AF_NETLINK
1730 * OK, that didn't work, so it's as bad as "netlink
1731 * sockets aren't available". Close the socket and
1738 * Now try an AF_UNIX socket.
1740 fd
= socket(AF_UNIX
, SOCK_RAW
, 0);
1749 * Now try an AF_INET6 socket.
1751 fd
= socket(AF_INET6
, SOCK_DGRAM
, 0);
1757 * Now try an AF_INET socket.
1759 * XXX - if that fails, is there anything else we should try?
1760 * AF_CAN, for embedded systems in vehicles, in case they're
1761 * built without Internet protocol support? Any other socket
1762 * types popular in non-Internet embedded systems?
1764 return (socket(AF_INET
, SOCK_DGRAM
, 0));
1768 * Get additional flags for a device, using SIOCETHTOOL.
1771 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1775 unsigned int arptype
= ARPHRD_VOID
;
1777 struct ethtool_value info
;
1779 if (*flags
& PCAP_IF_LOOPBACK
) {
1781 * Loopback devices aren't wireless, and "connected"/
1782 * "disconnected" doesn't apply to them.
1784 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1788 sock
= get_if_ioctl_socket();
1790 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1791 "Can't create socket to get ethtool information for %s",
1797 * OK, what type of network is this?
1798 * In particular, is it wired or wireless?
1800 if (is_wifi(name
)) {
1802 * Wi-Fi, hence wireless.
1804 *flags
|= PCAP_IF_WIRELESS
;
1807 * OK, what does /sys/class/net/{if_name}/type contain?
1808 * (We don't use that for Wi-Fi, as it'll report
1809 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
1814 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
1815 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1816 "%s: Can't generate path name string for /sys/class/net device",
1821 fh
= fopen(pathstr
, "r");
1823 if (fscanf(fh
, "%u", &arptype
) == 1) {
1825 * OK, we got an ARPHRD_ type; what is it?
1829 case ARPHRD_LOOPBACK
:
1831 * These are types to which
1832 * "connected" and "disconnected"
1833 * don't apply, so don't bother
1836 * XXX - add other types?
1844 case ARPHRD_IEEE80211
:
1845 case ARPHRD_IEEE80211_PRISM
:
1846 case ARPHRD_IEEE80211_RADIOTAP
:
1847 case ARPHRD_IEEE802154
:
1848 case ARPHRD_IEEE802154_MONITOR
:
1849 case ARPHRD_6LOWPAN
:
1851 * Various wireless types.
1853 *flags
|= PCAP_IF_WIRELESS
;
1862 #ifdef ETHTOOL_GLINK
1863 memset(&ifr
, 0, sizeof(ifr
));
1864 pcapint_strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
1865 info
.cmd
= ETHTOOL_GLINK
;
1867 * XXX - while Valgrind handles SIOCETHTOOL and knows that
1868 * the ETHTOOL_GLINK command sets the .data member of the
1869 * structure, Memory Sanitizer doesn't yet do so:
1871 * https://bugs.llvm.org/show_bug.cgi?id=45814
1873 * For now, we zero it out to squelch warnings; if the bug
1874 * in question is fixed, we can remove this.
1877 ifr
.ifr_data
= (caddr_t
)&info
;
1878 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
1879 int save_errno
= errno
;
1881 switch (save_errno
) {
1886 * OK, this OS version or driver doesn't support
1887 * asking for this information.
1888 * XXX - distinguish between "this doesn't
1889 * support ethtool at all because it's not
1890 * that type of device" vs. "this doesn't
1891 * support ethtool even though it's that
1892 * type of device", and return "unknown".
1894 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1900 * OK, no such device.
1901 * The user will find that out when they try to
1902 * activate the device; just say "OK" and
1903 * don't set anything.
1912 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1914 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
1928 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1931 * It's disconnected.
1933 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1940 // For "down" SNF devices the SNF API makes the flags more relevant.
1941 if (arptype
== ARPHRD_ETHER
&&
1942 ! (*flags
& PCAP_IF_UP
) &&
1943 snf_get_if_flags(name
, flags
, errbuf
) < 0)
1945 #endif // HAVE_SNF_API
1951 pcapint_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1954 * Get the list of regular interfaces first.
1956 if (pcapint_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
1957 get_if_flags
) == -1)
1958 return (-1); /* failure */
1961 * Add the "any" device.
1963 if (pcapint_add_any_dev(devlistp
, errbuf
) == NULL
)
1970 * Set direction flag: Which packets do we accept on a forwarding
1971 * single device? IN, OUT or both?
1974 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1977 * It's guaranteed, at this point, that d is a valid
1980 handle
->direction
= d
;
1985 is_wifi(const char *device
)
1991 * See if there's a sysfs wireless directory for it.
1992 * If so, it's a wireless interface.
1994 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
1996 * Just give up here.
2000 if (stat(pathstr
, &statb
) == 0) {
2010 * Linux uses the ARP hardware type to identify the type of an
2011 * interface. pcap uses the DLT_xxx constants for this. This
2012 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2013 * constant, as arguments, and sets "handle->linktype" to the
2014 * appropriate DLT_XXX constant and sets "handle->offset" to
2015 * the appropriate value (to make "handle->offset" plus link-layer
2016 * header length be a multiple of 4, so that the link-layer payload
2017 * will be aligned on a 4-byte boundary when capturing packets).
2018 * (If the offset isn't set here, it'll be 0; add code as appropriate
2019 * for cases where it shouldn't be 0.)
2021 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2022 * in cooked mode; otherwise, we can't use cooked mode, so we have
2023 * to pick some type that works in raw mode, or fail.
2025 * Sets the link type to -1 if unable to map the type.
2027 * Returns 0 on success or a PCAP_ERROR_ value on error.
2029 static int map_arphrd_to_dlt(pcap_t
*handle
, int arptype
,
2030 const char *device
, int cooked_ok
)
2032 static const char cdma_rmnet
[] = "cdma_rmnet";
2038 * For various annoying reasons having to do with DHCP
2039 * software, some versions of Android give the mobile-
2040 * phone-network interface an ARPHRD_ value of
2041 * ARPHRD_ETHER, even though the packets supplied by
2042 * that interface have no link-layer header, and begin
2043 * with an IP header, so that the ARPHRD_ value should
2046 * Detect those devices by checking the device name, and
2047 * use DLT_RAW for them.
2049 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2050 handle
->linktype
= DLT_RAW
;
2055 * Is this a real Ethernet device? If so, give it a
2056 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2057 * that an application can let you choose it, in case you're
2058 * capturing DOCSIS traffic that a Cisco Cable Modem
2059 * Termination System is putting out onto an Ethernet (it
2060 * doesn't put an Ethernet header onto the wire, it puts raw
2061 * DOCSIS frames out on the wire inside the low-level
2062 * Ethernet framing).
2064 * XXX - are there any other sorts of "fake Ethernet" that
2065 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2066 * a Cisco CMTS won't put traffic onto it or get traffic
2067 * bridged onto it? ISDN is handled in "setup_socket()",
2068 * as we fall back on cooked mode there, and we use
2069 * is_wifi() to check for 802.11 devices; are there any
2072 if (!is_wifi(device
)) {
2076 * This is not a Wi-Fi device but it could be
2077 * a DSA master/management network device.
2079 ret
= iface_dsa_get_proto_info(device
, handle
);
2085 * This is a DSA master/management network
2086 * device, linktype is already set by
2087 * iface_dsa_get_proto_info(), set an
2088 * appropriate offset here.
2095 * It's not a Wi-Fi device; offer DOCSIS.
2097 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2098 if (handle
->dlt_list
== NULL
) {
2099 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2100 PCAP_ERRBUF_SIZE
, errno
, "malloc");
2101 return (PCAP_ERROR
);
2103 handle
->dlt_list
[0] = DLT_EN10MB
;
2104 handle
->dlt_list
[1] = DLT_DOCSIS
;
2105 handle
->dlt_count
= 2;
2109 case ARPHRD_METRICOM
:
2110 case ARPHRD_LOOPBACK
:
2111 handle
->linktype
= DLT_EN10MB
;
2116 handle
->linktype
= DLT_EN3MB
;
2120 handle
->linktype
= DLT_AX25_KISS
;
2124 handle
->linktype
= DLT_PRONET
;
2128 handle
->linktype
= DLT_CHAOS
;
2132 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2135 case ARPHRD_IEEE802_TR
:
2136 case ARPHRD_IEEE802
:
2137 handle
->linktype
= DLT_IEEE802
;
2142 handle
->linktype
= DLT_ARCNET_LINUX
;
2146 handle
->linktype
= DLT_FDDI
;
2152 * The Classical IP implementation in ATM for Linux
2153 * supports both what RFC 1483 calls "LLC Encapsulation",
2154 * in which each packet has an LLC header, possibly
2155 * with a SNAP header as well, prepended to it, and
2156 * what RFC 1483 calls "VC Based Multiplexing", in which
2157 * different virtual circuits carry different network
2158 * layer protocols, and no header is prepended to packets.
2160 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2161 * you can't use the ARPHRD_ type to find out whether
2162 * captured packets will have an LLC header, and,
2163 * while there's a socket ioctl to *set* the encapsulation
2164 * type, there's no ioctl to *get* the encapsulation type.
2168 * programs that dissect Linux Classical IP frames
2169 * would have to check for an LLC header and,
2170 * depending on whether they see one or not, dissect
2171 * the frame as LLC-encapsulated or as raw IP (I
2172 * don't know whether there's any traffic other than
2173 * IP that would show up on the socket, or whether
2174 * there's any support for IPv6 in the Linux
2175 * Classical IP code);
2177 * filter expressions would have to compile into
2178 * code that checks for an LLC header and does
2181 * Both of those are a nuisance - and, at least on systems
2182 * that support PF_PACKET sockets, we don't have to put
2183 * up with those nuisances; instead, we can just capture
2184 * in cooked mode. That's what we'll do, if we can.
2185 * Otherwise, we'll just fail.
2188 handle
->linktype
= DLT_LINUX_SLL
;
2190 handle
->linktype
= -1;
2193 case ARPHRD_IEEE80211
:
2194 handle
->linktype
= DLT_IEEE802_11
;
2197 case ARPHRD_IEEE80211_PRISM
:
2198 handle
->linktype
= DLT_PRISM_HEADER
;
2201 case ARPHRD_IEEE80211_RADIOTAP
:
2202 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2207 * Some PPP code in the kernel supplies no link-layer
2208 * header whatsoever to PF_PACKET sockets; other PPP
2209 * code supplies PPP link-layer headers ("syncppp.c");
2210 * some PPP code might supply random link-layer
2211 * headers (PPP over ISDN - there's code in Ethereal,
2212 * for example, to cope with PPP-over-ISDN captures
2213 * with which the Ethereal developers have had to cope,
2214 * heuristically trying to determine which of the
2215 * oddball link-layer headers particular packets have).
2217 * As such, we just punt, and run all PPP interfaces
2218 * in cooked mode, if we can; otherwise, we just treat
2219 * it as DLT_RAW, for now - if somebody needs to capture,
2220 * on a 2.0[.x] kernel, on PPP devices that supply a
2221 * link-layer header, they'll have to add code here to
2222 * map to the appropriate DLT_ type (possibly adding a
2223 * new DLT_ type, if necessary).
2226 handle
->linktype
= DLT_LINUX_SLL
;
2229 * XXX - handle ISDN types here? We can't fall
2230 * back on cooked sockets, so we'd have to
2231 * figure out from the device name what type of
2232 * link-layer encapsulation it's using, and map
2233 * that to an appropriate DLT_ value, meaning
2234 * we'd map "isdnN" devices to DLT_RAW (they
2235 * supply raw IP packets with no link-layer
2236 * header) and "isdY" devices to a new DLT_I4L_IP
2237 * type that has only an Ethernet packet type as
2238 * a link-layer header.
2240 * But sometimes we seem to get random crap
2241 * in the link-layer header when capturing on
2244 handle
->linktype
= DLT_RAW
;
2249 handle
->linktype
= DLT_C_HDLC
;
2252 /* Not sure if this is correct for all tunnels, but it
2261 case ARPHRD_RAWHDLC
:
2264 * XXX - should some of those be mapped to DLT_LINUX_SLL
2265 * instead? Should we just map all of them to DLT_LINUX_SLL?
2267 handle
->linktype
= DLT_RAW
;
2271 handle
->linktype
= DLT_FRELAY
;
2274 case ARPHRD_LOCALTLK
:
2275 handle
->linktype
= DLT_LTALK
;
2280 * RFC 4338 defines an encapsulation for IP and ARP
2281 * packets that's compatible with the RFC 2625
2282 * encapsulation, but that uses a different ARP
2283 * hardware type and hardware addresses. That
2284 * ARP hardware type is 18; Linux doesn't define
2285 * any ARPHRD_ value as 18, but if it ever officially
2286 * supports RFC 4338-style IP-over-FC, it should define
2289 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2290 * that this will encourage its use in the future,
2291 * should Linux ever officially support RFC 4338-style
2294 handle
->linktype
= DLT_IP_OVER_FC
;
2300 case ARPHRD_FCFABRIC
:
2302 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2305 * https://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2307 * and one was assigned.
2309 * In a later private discussion (spun off from a message
2310 * on the ethereal-users list) on how to get that DLT_
2311 * value in libpcap on Linux, I ended up deciding that
2312 * the best thing to do would be to have him tweak the
2313 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2314 * type, and map all those types to DLT_IP_OVER_FC:
2316 * I've checked into the libpcap and tcpdump CVS tree
2317 * support for DLT_IP_OVER_FC. In order to use that,
2318 * you'd have to modify your modified driver to return
2319 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2320 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2321 * example (the exact value doesn't matter, it can be
2322 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2325 * 11 years later, Christian Svensson wanted to map
2326 * various ARPHRD_ values to DLT_FC_2 and
2327 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2330 * https://github.com/mcr/libpcap/pull/29
2332 * There doesn't seem to be any network drivers that uses
2333 * any of the ARPHRD_FC* values for IP-over-FC, and
2334 * it's not exactly clear what the "Dummy types for non
2335 * ARP hardware" are supposed to mean (link-layer
2336 * header type? Physical network type?), so it's
2337 * not exactly clear why the ARPHRD_FC* types exist
2338 * in the first place.
2340 * For now, we map them to DLT_FC_2, and provide an
2341 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2342 * DLT_IP_OVER_FC just in case there's some old
2343 * driver out there that uses one of those types for
2344 * IP-over-FC on which somebody wants to capture
2347 handle
->linktype
= DLT_FC_2
;
2348 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
2349 if (handle
->dlt_list
== NULL
) {
2350 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2351 PCAP_ERRBUF_SIZE
, errno
, "malloc");
2352 return (PCAP_ERROR
);
2354 handle
->dlt_list
[0] = DLT_FC_2
;
2355 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2356 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2357 handle
->dlt_count
= 3;
2361 /* Don't expect IP packet out of this interfaces... */
2362 handle
->linktype
= DLT_LINUX_IRDA
;
2363 /* We need to save packet direction for IrDA decoding,
2364 * so let's use "Linux-cooked" mode. Jean II
2366 * XXX - this is handled in setup_socket(). */
2367 /* handlep->cooked = 1; */
2371 /* Don't expect IP packet out of this interfaces... */
2372 handle
->linktype
= DLT_LINUX_LAPD
;
2377 * No link-layer header; packets are just IP
2378 * packets, so use DLT_RAW.
2380 handle
->linktype
= DLT_RAW
;
2383 case ARPHRD_IEEE802154
:
2384 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2387 case ARPHRD_NETLINK
:
2388 handle
->linktype
= DLT_NETLINK
;
2390 * We need to use cooked mode, so that in sll_protocol we
2391 * pick up the netlink protocol type such as NETLINK_ROUTE,
2392 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2394 * XXX - this is handled in setup_socket().
2396 /* handlep->cooked = 1; */
2399 case ARPHRD_VSOCKMON
:
2400 handle
->linktype
= DLT_VSOCK
;
2404 handle
->linktype
= -1;
2411 * Try to set up a PF_PACKET socket.
2412 * Returns 0 or a PCAP_WARNING_ value on success and a PCAP_ERROR_ value
2416 setup_socket(pcap_t
*handle
, int is_any_device
)
2418 struct pcap_linux
*handlep
= handle
->priv
;
2419 const char *device
= handle
->opt
.device
;
2421 int sock_fd
, arptype
;
2424 struct packet_mreq mr
;
2427 * Open a socket with protocol family packet. If cooked is true,
2428 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
2429 * we open a SOCK_RAW socket for the raw interface.
2431 * The protocol is set to 0. This means we will receive no
2432 * packets until we "bind" the socket with a non-zero
2433 * protocol. This allows us to setup the ring buffers without
2434 * dropping any packets.
2436 sock_fd
= is_any_device
?
2437 socket(PF_PACKET
, SOCK_DGRAM
, 0) :
2438 socket(PF_PACKET
, SOCK_RAW
, 0);
2440 if (sock_fd
== -1) {
2441 if (errno
== EPERM
|| errno
== EACCES
) {
2443 * You don't have permission to open the
2446 status
= PCAP_ERROR_PERM_DENIED
;
2447 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2448 "Attempt to create packet socket failed - CAP_NET_RAW may be required");
2449 } else if (errno
== EAFNOSUPPORT
) {
2451 * PF_PACKET sockets not supported.
2452 * Perhaps we're running on the WSL1 module
2453 * in the Windows NT kernel rather than on
2454 * a real Linux kernel.
2456 status
= PCAP_ERROR_CAPTURE_NOTSUP
;
2457 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2458 "PF_PACKET sockets not supported - is this WSL1?");
2463 status
= PCAP_ERROR
;
2465 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2471 * Get the interface index of the loopback device.
2472 * If the attempt fails, don't fail, just set the
2473 * "handlep->lo_ifindex" to -1.
2475 * XXX - can there be more than one device that loops
2476 * packets back, i.e. devices other than "lo"? If so,
2477 * we'd need to find them all, and have an array of
2478 * indices for them, and check all of them in
2479 * "pcap_read_packet()".
2481 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2484 * Default value for offset to align link-layer payload
2485 * on a 4-byte boundary.
2490 * What kind of frames do we have to deal with? Fall back
2491 * to cooked mode if we have an unknown interface type
2492 * or a type we know doesn't work well in raw mode.
2494 if (!is_any_device
) {
2495 /* Assume for now we don't need cooked mode. */
2496 handlep
->cooked
= 0;
2498 if (handle
->opt
.rfmon
) {
2500 * We were asked to turn on monitor mode.
2501 * Do so before we get the link-layer type,
2502 * because entering monitor mode could change
2503 * the link-layer type.
2505 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2513 * Nothing worked for turning monitor mode
2518 return PCAP_ERROR_RFMON_NOTSUP
;
2522 * Either monitor mode has been turned on for
2523 * the device, or we've been given a different
2524 * device to open for monitor mode. If we've
2525 * been given a different device, use it.
2527 if (handlep
->mondevice
!= NULL
)
2528 device
= handlep
->mondevice
;
2530 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2535 status
= map_arphrd_to_dlt(handle
, arptype
, device
, 1);
2540 if (handle
->linktype
== -1 ||
2541 handle
->linktype
== DLT_LINUX_SLL
||
2542 handle
->linktype
== DLT_LINUX_IRDA
||
2543 handle
->linktype
== DLT_LINUX_LAPD
||
2544 handle
->linktype
== DLT_NETLINK
||
2545 (handle
->linktype
== DLT_EN10MB
&&
2546 (strncmp("isdn", device
, 4) == 0 ||
2547 strncmp("isdY", device
, 4) == 0))) {
2549 * Unknown interface type (-1), or a
2550 * device we explicitly chose to run
2551 * in cooked mode (e.g., PPP devices),
2552 * or an ISDN device (whose link-layer
2553 * type we can only determine by using
2554 * APIs that may be different on different
2555 * kernels) - reopen in cooked mode.
2557 * If the type is unknown, return a warning;
2558 * map_arphrd_to_dlt() has already set the
2561 if (close(sock_fd
) == -1) {
2562 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2563 PCAP_ERRBUF_SIZE
, errno
, "close");
2566 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
, 0);
2569 * Fatal error. We treat this as
2570 * a generic error; we already know
2571 * that we were able to open a
2572 * PF_PACKET/SOCK_RAW socket, so
2573 * any failure is a "this shouldn't
2576 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2577 PCAP_ERRBUF_SIZE
, errno
, "socket");
2580 handlep
->cooked
= 1;
2583 * Get rid of any link-layer type list
2584 * we allocated - this only supports cooked
2587 if (handle
->dlt_list
!= NULL
) {
2588 free(handle
->dlt_list
);
2589 handle
->dlt_list
= NULL
;
2590 handle
->dlt_count
= 0;
2593 if (handle
->linktype
== -1) {
2595 * Warn that we're falling back on
2596 * cooked mode; we may want to
2597 * update "map_arphrd_to_dlt()"
2598 * to handle the new type.
2600 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2602 "supported by libpcap - "
2603 "falling back to cooked "
2606 status
= PCAP_WARNING
;
2610 * IrDA capture is not a real "cooked" capture,
2611 * it's IrLAP frames, not IP packets. The
2612 * same applies to LAPD capture.
2614 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2615 handle
->linktype
!= DLT_LINUX_LAPD
&&
2616 handle
->linktype
!= DLT_NETLINK
)
2617 handle
->linktype
= DLT_LINUX_SLL
;
2620 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
2622 if (handlep
->ifindex
== -1) {
2627 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
2628 handle
->errbuf
, 0)) != 0) {
2636 if (handle
->opt
.rfmon
) {
2638 * It doesn't support monitor mode.
2641 return PCAP_ERROR_RFMON_NOTSUP
;
2645 * It uses cooked mode.
2646 * Support both DLT_LINUX_SLL and DLT_LINUX_SLL2.
2648 handlep
->cooked
= 1;
2649 handle
->linktype
= DLT_LINUX_SLL
;
2650 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2651 if (handle
->dlt_list
== NULL
) {
2652 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2653 PCAP_ERRBUF_SIZE
, errno
, "malloc");
2654 return (PCAP_ERROR
);
2656 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
2657 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
2658 handle
->dlt_count
= 2;
2661 * We're not bound to a device.
2662 * For now, we're using this as an indication
2663 * that we can't transmit; stop doing that only
2664 * if we figure out how to transmit in cooked
2667 handlep
->ifindex
= -1;
2671 * Select promiscuous mode on if "promisc" is set.
2673 * Do not turn allmulti mode on if we don't select
2674 * promiscuous mode - on some devices (e.g., Orinoco
2675 * wireless interfaces), allmulti mode isn't supported
2676 * and the driver implements it by turning promiscuous
2677 * mode on, and that screws up the operation of the
2678 * card as a normal networking interface, and on no
2679 * other platform I know of does starting a non-
2680 * promiscuous capture affect which multicast packets
2681 * are received by the interface.
2685 * Hmm, how can we set promiscuous mode on all interfaces?
2686 * I am not sure if that is possible at all. For now, we
2687 * silently ignore attempts to turn promiscuous mode on
2688 * for the "any" device (so you don't have to explicitly
2689 * disable it in programs such as tcpdump).
2692 if (!is_any_device
&& handle
->opt
.promisc
) {
2693 memset(&mr
, 0, sizeof(mr
));
2694 mr
.mr_ifindex
= handlep
->ifindex
;
2695 mr
.mr_type
= PACKET_MR_PROMISC
;
2696 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2697 &mr
, sizeof(mr
)) == -1) {
2698 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
2699 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
2706 * Enable auxiliary data and reserve room for reconstructing
2709 * XXX - is enabling auxiliary data necessary, now that we
2710 * only support memory-mapped capture? The kernel's memory-mapped
2711 * capture code doesn't seem to check whether auxiliary data
2712 * is enabled, it seems to provide it whether it is or not.
2715 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2716 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2717 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2718 errno
, "setsockopt (PACKET_AUXDATA)");
2722 handle
->offset
+= VLAN_TAG_LEN
;
2725 * If we're in cooked mode, make the snapshot length
2726 * large enough to hold a "cooked mode" header plus
2727 * 1 byte of packet data (so we don't pass a byte
2728 * count of 0 to "recvfrom()").
2729 * XXX - we don't know whether this will be DLT_LINUX_SLL
2730 * or DLT_LINUX_SLL2, so make sure it's big enough for
2731 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
2732 * that small is silly anyway.
2734 if (handlep
->cooked
) {
2735 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
2736 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
2738 handle
->bufsize
= handle
->snapshot
;
2741 * Set the offset at which to insert VLAN tags.
2743 set_vlan_offset(handle
);
2745 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
2746 int nsec_tstamps
= 1;
2748 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
2749 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
2756 * We've succeeded. Save the socket FD in the pcap structure.
2758 handle
->fd
= sock_fd
;
2761 * Any supported Linux version implements at least four auxiliary
2762 * data items (SKF_AD_PROTOCOL, SKF_AD_PKTTYPE, SKF_AD_IFINDEX and
2763 * SKF_AD_NLATTR). Set a flag so the code generator can use these
2764 * items if necessary.
2766 handle
->bpf_codegen_flags
|= BPF_SPECIAL_BASIC_HANDLING
;
2769 * Can we generate special code for VLAN checks?
2770 * (XXX - what if we need the special code but it's not supported
2771 * by the OS? Is that possible?)
2773 * This depends on both a runtime condition (the running Linux kernel
2774 * must support at least SKF_AD_VLAN_TAG_PRESENT in the auxiliary data
2775 * and must support SO_BPF_EXTENSIONS in order to tell the userland
2776 * process what it supports) and a compile-time condition (the OS
2777 * headers must define both constants in order to compile libpcap code
2778 * that asks the kernel about the support).
2780 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2782 socklen_t len
= sizeof(bpf_extensions
);
2783 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
2784 &bpf_extensions
, &len
) == 0) {
2785 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
2787 * Yes, we can. Request that we do so.
2789 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
2792 #endif // defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2798 * Attempt to setup memory-mapped access.
2800 * On success, returns 0 if there are no warnings or a PCAP_WARNING_ code
2801 * if there is a warning.
2803 * On error, returns the appropriate error code; if that is PCAP_ERROR,
2804 * sets handle->errbuf to the appropriate message.
2807 setup_mmapped(pcap_t
*handle
)
2809 struct pcap_linux
*handlep
= handle
->priv
;
2810 int flags
= MAP_ANONYMOUS
| MAP_PRIVATE
;
2814 * Attempt to allocate a buffer to hold the contents of one
2815 * packet, for use by the oneshot callback.
2818 if (pcapint_mmap_32bit
) flags
|= MAP_32BIT
;
2820 handlep
->oneshot_buffer
= mmap(0, handle
->snapshot
, PROT_READ
| PROT_WRITE
, flags
, -1, 0);
2821 if (handlep
->oneshot_buffer
== MAP_FAILED
) {
2822 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2823 errno
, "can't allocate oneshot buffer");
2827 if (handle
->opt
.buffer_size
== 0) {
2828 /* by default request 2M for the ring buffer */
2829 handle
->opt
.buffer_size
= 2*1024*1024;
2831 status
= prepare_tpacket_socket(handle
);
2833 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
2834 handlep
->oneshot_buffer
= NULL
;
2837 status
= create_ring(handle
);
2840 * Error attempting to enable memory-mapped capture;
2841 * fail. The return value is the status to return.
2843 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
2844 handlep
->oneshot_buffer
= NULL
;
2849 * Success. status has been set either to 0 if there are no
2850 * warnings or to a PCAP_WARNING_ value if there is a warning.
2852 * handle->offset is used to get the current position into the rx ring.
2853 * handle->cc is used to store the ring size.
2857 * Set the timeout to use in poll() before returning.
2859 set_poll_timeout(handlep
);
2865 * Attempt to set the socket to the specified version of the memory-mapped
2868 * Return 0 if we succeed; return 1 if we fail because that version isn't
2869 * supported; return -1 on any other error, and set handle->errbuf.
2872 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
2874 struct pcap_linux
*handlep
= handle
->priv
;
2876 socklen_t len
= sizeof(val
);
2879 * Probe whether kernel supports the specified TPACKET version;
2880 * this also gets the length of the header for that version.
2882 * This socket option was introduced in 2.6.27, which was
2883 * also the first release with TPACKET_V2 support.
2885 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
2886 if (errno
== EINVAL
) {
2888 * EINVAL means this specific version of TPACKET
2889 * is not supported. Tell the caller they can try
2890 * with a different one; if they've run out of
2891 * others to try, let them set the error message
2898 * All other errors are fatal.
2900 if (errno
== ENOPROTOOPT
) {
2902 * PACKET_HDRLEN isn't supported, which means
2903 * that memory-mapped capture isn't supported.
2904 * Indicate that in the message.
2906 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2907 "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");
2910 * Some unexpected error.
2912 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2913 errno
, "can't get %s header len on packet socket",
2918 handlep
->tp_hdrlen
= val
;
2921 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
2923 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2924 errno
, "can't activate %s on packet socket", version_str
);
2927 handlep
->tp_version
= version
;
2933 * Attempt to set the socket to version 3 of the memory-mapped header and,
2934 * if that fails because version 3 isn't supported, attempt to fall
2935 * back to version 2. If version 2 isn't supported, just fail.
2937 * Return 0 if we succeed and -1 on any other error, and set handle->errbuf.
2940 prepare_tpacket_socket(pcap_t
*handle
)
2944 #ifdef HAVE_TPACKET3
2946 * Try setting the version to TPACKET_V3.
2948 * The only mode in which buffering is done on PF_PACKET
2949 * sockets, so that packets might not be delivered
2950 * immediately, is TPACKET_V3 mode.
2952 * The buffering cannot be disabled in that mode, so
2953 * if the user has requested immediate mode, we don't
2956 if (!handle
->opt
.immediate
) {
2957 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
2966 * We failed for some reason other than "the
2967 * kernel doesn't support TPACKET_V3".
2973 * This means it returned 1, which means "the kernel
2974 * doesn't support TPACKET_V3"; try TPACKET_V2.
2977 #endif /* HAVE_TPACKET3 */
2980 * Try setting the version to TPACKET_V2.
2982 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
2992 * OK, the kernel supports memory-mapped capture, but
2993 * not TPACKET_V2. Set the error message appropriately.
2995 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2996 "Kernel doesn't support TPACKET_V2; a 2.6.27 or later kernel is required");
3005 #define MAX(a,b) ((a)>(b)?(a):(b))
3008 * Attempt to set up memory-mapped access.
3010 * On success, returns 0 if there are no warnings or to a PCAP_WARNING_ code
3011 * if there is a warning.
3013 * On error, returns the appropriate error code; if that is PCAP_ERROR,
3014 * sets handle->errbuf to the appropriate message.
3017 create_ring(pcap_t
*handle
)
3019 struct pcap_linux
*handlep
= handle
->priv
;
3020 unsigned i
, j
, frames_per_block
;
3021 int flags
= MAP_SHARED
;
3022 #ifdef HAVE_TPACKET3
3024 * For sockets using TPACKET_V2, the extra stuff at the end of a
3025 * struct tpacket_req3 will be ignored, so this is OK even for
3028 struct tpacket_req3 req
;
3030 struct tpacket_req req
;
3033 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3034 unsigned int frame_size
;
3038 * Start out assuming no warnings.
3043 * Reserve space for VLAN tag reconstruction.
3045 tp_reserve
= VLAN_TAG_LEN
;
3048 * If we're capturing in cooked mode, reserve space for
3049 * a DLT_LINUX_SLL2 header; we don't know yet whether
3050 * we'll be using DLT_LINUX_SLL or DLT_LINUX_SLL2, as
3051 * that can be changed on an open device, so we reserve
3052 * space for the larger of the two.
3054 * XXX - we assume that the kernel is still adding
3055 * 16 bytes of extra space, so we subtract 16 from
3056 * SLL2_HDR_LEN to get the additional space needed.
3057 * (Are they doing that for DLT_LINUX_SLL, the link-
3058 * layer header for which is 16 bytes?)
3060 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - 16)?
3062 if (handlep
->cooked
)
3063 tp_reserve
+= SLL2_HDR_LEN
- 16;
3066 * Try to request that amount of reserve space.
3067 * This must be done before creating the ring buffer.
3069 len
= sizeof(tp_reserve
);
3070 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
3071 &tp_reserve
, len
) < 0) {
3072 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3073 PCAP_ERRBUF_SIZE
, errno
,
3074 "setsockopt (PACKET_RESERVE)");
3078 switch (handlep
->tp_version
) {
3081 /* Note that with large snapshot length (say 256K, which is
3082 * the default for recent versions of tcpdump, Wireshark,
3083 * TShark, dumpcap or 64K, the value that "-s 0" has given for
3084 * a long time with tcpdump), if we use the snapshot
3085 * length to calculate the frame length, only a few frames
3086 * will be available in the ring even with pretty
3087 * large ring size (and a lot of memory will be unused).
3089 * Ideally, we should choose a frame length based on the
3090 * minimum of the specified snapshot length and the maximum
3091 * packet size. That's not as easy as it sounds; consider,
3092 * for example, an 802.11 interface in monitor mode, where
3093 * the frame would include a radiotap header, where the
3094 * maximum radiotap header length is device-dependent.
3096 * So, for now, we just do this for Ethernet devices, where
3097 * there's no metadata header, and the link-layer header is
3098 * fixed length. We can get the maximum packet size by
3099 * adding 18, the Ethernet header length plus the CRC length
3100 * (just in case we happen to get the CRC in the packet), to
3101 * the MTU of the interface; we fetch the MTU in the hopes
3102 * that it reflects support for jumbo frames. (Even if the
3103 * interface is just being used for passive snooping, the
3104 * driver might set the size of buffers in the receive ring
3105 * based on the MTU, so that the MTU limits the maximum size
3106 * of packets that we can receive.)
3108 * If segmentation/fragmentation or receive offload are
3109 * enabled, we can get reassembled/aggregated packets larger
3110 * than MTU, but bounded to 65535 plus the Ethernet overhead,
3111 * due to kernel and protocol constraints */
3112 frame_size
= handle
->snapshot
;
3113 if (handle
->linktype
== DLT_EN10MB
) {
3114 unsigned int max_frame_len
;
3118 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
3122 offload
= iface_get_offload(handle
);
3126 max_frame_len
= MAX(mtu
, 65535);
3128 max_frame_len
= mtu
;
3129 max_frame_len
+= 18;
3131 if (frame_size
> max_frame_len
)
3132 frame_size
= max_frame_len
;
3135 /* NOTE: calculus matching those in tpacket_rcv()
3136 * in linux-2.6/net/packet/af_packet.c
3138 len
= sizeof(sk_type
);
3139 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
3141 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3142 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
3145 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3146 /* XXX: in the kernel maclen is calculated from
3147 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3148 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3149 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3150 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3151 * but I see no way to get those sizes in userspace,
3152 * like for instance with an ifreq ioctl();
3153 * the best thing I've found so far is MAX_HEADER in
3154 * the kernel part of linux-2.6/include/linux/netdevice.h
3155 * which goes up to 128+48=176; since pcap-linux.c
3156 * defines a MAX_LINKHEADER_SIZE of 256 which is
3157 * greater than that, let's use it.. maybe is it even
3158 * large enough to directly replace macoff..
3160 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3161 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3162 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3163 * of netoff, which contradicts
3164 * linux-2.6/Documentation/networking/packet_mmap.txt
3166 * "- Gap, chosen so that packet data (Start+tp_net)
3167 * aligns to TPACKET_ALIGNMENT=16"
3169 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3170 * "CPUs often take a performance hit
3171 * when accessing unaligned memory locations"
3173 macoff
= netoff
- maclen
;
3174 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3176 * Round the buffer size up to a multiple of the
3177 * frame size (rather than rounding down, which
3178 * would give a buffer smaller than our caller asked
3179 * for, and possibly give zero frames if the requested
3180 * buffer size is too small for one frame).
3182 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3185 #ifdef HAVE_TPACKET3
3187 /* The "frames" for this are actually buffers that
3188 * contain multiple variable-sized frames.
3190 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
3191 * enough room for at least one reasonably-sized packet
3192 * in the "frame". */
3193 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
3195 * Round the buffer size up to a multiple of the
3196 * "frame" size (rather than rounding down, which
3197 * would give a buffer smaller than our caller asked
3198 * for, and possibly give zero "frames" if the requested
3199 * buffer size is too small for one "frame").
3201 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3205 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3206 "Internal error: unknown TPACKET_ value %u",
3207 handlep
->tp_version
);
3211 /* compute the minimum block size that will handle this frame.
3212 * The block has to be page size aligned.
3213 * The max block size allowed by the kernel is arch-dependent and
3214 * it's not explicitly checked here. */
3215 req
.tp_block_size
= getpagesize();
3216 while (req
.tp_block_size
< req
.tp_frame_size
)
3217 req
.tp_block_size
<<= 1;
3219 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3222 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3223 * so we check for PACKET_TIMESTAMP. We check for
3224 * linux/net_tstamp.h just in case a system somehow has
3225 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3228 * SIOCSHWTSTAMP was introduced in the patch that introduced
3229 * linux/net_tstamp.h, so we don't bother checking whether
3230 * SIOCSHWTSTAMP is defined (if your Linux system has
3231 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3232 * Linux system is badly broken).
3234 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3236 * If we were told to do so, ask the kernel and the driver
3237 * to use hardware timestamps.
3239 * Hardware timestamps are only supported with mmapped
3242 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3243 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3244 struct hwtstamp_config hwconfig
;
3249 * Ask for hardware time stamps on all packets,
3250 * including transmitted packets.
3252 memset(&hwconfig
, 0, sizeof(hwconfig
));
3253 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3254 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3256 memset(&ifr
, 0, sizeof(ifr
));
3257 pcapint_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
3258 ifr
.ifr_data
= (void *)&hwconfig
;
3261 * This may require CAP_NET_ADMIN.
3263 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3268 * Treat this as an error, as the
3269 * user should try to run this
3270 * with the appropriate privileges -
3271 * and, if they can't, shouldn't
3272 * try requesting hardware time stamps.
3274 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3275 "Attempt to set hardware timestamp failed - CAP_NET_ADMIN may be required");
3276 return PCAP_ERROR_PERM_DENIED
;
3281 * Treat this as a warning, as the
3282 * only way to fix the warning is to
3283 * get an adapter that supports hardware
3284 * time stamps for *all* packets.
3285 * (ERANGE means "we support hardware
3286 * time stamps, but for packets matching
3287 * that particular filter", so it means
3288 * "we don't support hardware time stamps
3289 * for all incoming packets" here.)
3291 * We'll just fall back on the standard
3294 status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3298 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3299 PCAP_ERRBUF_SIZE
, errno
,
3300 "SIOCSHWTSTAMP failed");
3305 * Well, that worked. Now specify the type of
3306 * hardware time stamp we want for this
3309 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3311 * Hardware timestamp, synchronized
3312 * with the system clock.
3314 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3317 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3318 * timestamp, not synchronized with the
3321 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3323 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3324 (void *)×ource
, sizeof(timesource
))) {
3325 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3326 PCAP_ERRBUF_SIZE
, errno
,
3327 "can't set PACKET_TIMESTAMP");
3332 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3334 /* ask the kernel to create the ring */
3336 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3338 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3339 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3341 #ifdef HAVE_TPACKET3
3342 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3343 if (handlep
->timeout
> 0) {
3344 /* Use the user specified timeout as the block timeout */
3345 req
.tp_retire_blk_tov
= handlep
->timeout
;
3346 } else if (handlep
->timeout
== 0) {
3348 * In pcap, this means "infinite timeout"; TPACKET_V3
3349 * doesn't support that, so just set it to UINT_MAX
3350 * milliseconds. In the TPACKET_V3 loop, if the
3351 * timeout is 0, and we haven't yet seen any packets,
3352 * and we block and still don't have any packets, we
3353 * keep blocking until we do.
3355 req
.tp_retire_blk_tov
= UINT_MAX
;
3358 * XXX - this is not valid; use 0, meaning "have the
3359 * kernel pick a default", for now.
3361 req
.tp_retire_blk_tov
= 0;
3363 /* private data not used */
3364 req
.tp_sizeof_priv
= 0;
3365 /* Rx ring - feature request bits - none (rxhash will not be filled) */
3366 req
.tp_feature_req_word
= 0;
3369 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3370 (void *) &req
, sizeof(req
))) {
3371 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3373 * Memory failure; try to reduce the requested ring
3376 * We used to reduce this by half -- do 5% instead.
3377 * That may result in more iterations and a longer
3378 * startup, but the user will be much happier with
3379 * the resulting buffer size.
3381 if (req
.tp_frame_nr
< 20)
3382 req
.tp_frame_nr
-= 1;
3384 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3387 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3388 errno
, "can't create rx ring on packet socket");
3392 /* memory map the rx ring */
3393 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3395 if (pcapint_mmap_32bit
) flags
|= MAP_32BIT
;
3397 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
, PROT_READ
| PROT_WRITE
, flags
, handle
->fd
, 0);
3398 if (handlep
->mmapbuf
== MAP_FAILED
) {
3399 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3400 errno
, "can't mmap rx ring");
3402 /* clear the allocated ring on error*/
3403 destroy_ring(handle
);
3407 /* allocate a ring for each frame header pointer*/
3408 handle
->cc
= req
.tp_frame_nr
;
3409 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3410 if (!handle
->buffer
) {
3411 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3412 errno
, "can't allocate ring of frame headers");
3414 destroy_ring(handle
);
3418 /* fill the header ring with proper frame ptr*/
3420 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3421 u_char
*base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3422 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3423 RING_GET_CURRENT_FRAME(handle
) = base
;
3424 base
+= req
.tp_frame_size
;
3428 handle
->bufsize
= req
.tp_frame_size
;
3433 /* free all ring related resources*/
3435 destroy_ring(pcap_t
*handle
)
3437 struct pcap_linux
*handlep
= handle
->priv
;
3440 * Tell the kernel to destroy the ring.
3441 * We don't check for setsockopt failure, as 1) we can't recover
3442 * from an error and 2) we might not yet have set it up in the
3445 struct tpacket_req req
;
3446 memset(&req
, 0, sizeof(req
));
3447 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3448 (void *) &req
, sizeof(req
));
3450 /* if ring is mapped, unmap it*/
3451 if (handlep
->mmapbuf
) {
3452 /* do not test for mmap failure, as we can't recover from any error */
3453 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3454 handlep
->mmapbuf
= NULL
;
3459 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3460 * for Linux mmapped capture.
3462 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3463 * data handed to the callback to be valid after the callback returns,
3464 * but pcap_read_linux_mmap() has to release that packet as soon as
3465 * the callback returns (otherwise, the kernel thinks there's still
3466 * at least one unprocessed packet available in the ring, so a select()
3467 * will immediately return indicating that there's data to process), so,
3468 * in the callback, we have to make a copy of the packet.
3470 * Yes, this means that, if the capture is using the ring buffer, using
3471 * pcap_next() or pcap_next_ex() requires more copies than using
3472 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3473 * pcap_next() or pcap_next_ex().
3476 pcapint_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
3477 const u_char
*bytes
)
3479 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3480 pcap_t
*handle
= sp
->pd
;
3481 struct pcap_linux
*handlep
= handle
->priv
;
3484 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3485 *sp
->pkt
= handlep
->oneshot_buffer
;
3489 pcap_getnonblock_linux(pcap_t
*handle
)
3491 struct pcap_linux
*handlep
= handle
->priv
;
3493 /* use negative value of timeout to indicate non blocking ops */
3494 return (handlep
->timeout
<0);
3498 pcap_setnonblock_linux(pcap_t
*handle
, int nonblock
)
3500 struct pcap_linux
*handlep
= handle
->priv
;
3503 * Set the file descriptor to the requested mode, as we use
3504 * it for sending packets.
3506 if (pcapint_setnonblock_fd(handle
, nonblock
) == -1)
3510 * Map each value to their corresponding negation to
3511 * preserve the timeout value provided with pcap_set_timeout.
3515 * We're setting the mode to non-blocking mode.
3517 if (handlep
->timeout
>= 0) {
3519 * Indicate that we're switching to
3520 * non-blocking mode.
3522 handlep
->timeout
= ~handlep
->timeout
;
3524 if (handlep
->poll_breakloop_fd
!= -1) {
3525 /* Close the eventfd; we do not need it in nonblock mode. */
3526 close(handlep
->poll_breakloop_fd
);
3527 handlep
->poll_breakloop_fd
= -1;
3531 * We're setting the mode to blocking mode.
3533 if (handlep
->poll_breakloop_fd
== -1) {
3534 /* If we did not have an eventfd, open one now that we are blocking. */
3535 if ( ( handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
) ) == -1 ) {
3536 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3537 PCAP_ERRBUF_SIZE
, errno
,
3538 "could not open eventfd");
3542 if (handlep
->timeout
< 0) {
3543 handlep
->timeout
= ~handlep
->timeout
;
3546 /* Update the timeout to use in poll(). */
3547 set_poll_timeout(handlep
);
3552 * Get the status field of the ring buffer frame at a specified offset.
3555 pcap_get_ring_frame_status(pcap_t
*handle
, u_int offset
)
3557 struct pcap_linux
*handlep
= handle
->priv
;
3560 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
3561 switch (handlep
->tp_version
) {
3563 return __atomic_load_n(&h
.h2
->tp_status
, __ATOMIC_ACQUIRE
);
3564 #ifdef HAVE_TPACKET3
3566 return __atomic_load_n(&h
.h3
->hdr
.bh1
.block_status
, __ATOMIC_ACQUIRE
);
3569 /* This should not happen. */
3574 * Block waiting for frames to be available.
3576 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
3578 struct pcap_linux
*handlep
= handle
->priv
;
3582 struct pollfd pollinfo
[2];
3584 pollinfo
[0].fd
= handle
->fd
;
3585 pollinfo
[0].events
= POLLIN
;
3586 if ( handlep
->poll_breakloop_fd
== -1 ) {
3588 pollinfo
[1].revents
= 0;
3590 * We set pollinfo[1].revents to zero, even though
3591 * numpollinfo = 1 meaning that poll() doesn't see
3592 * pollinfo[1], so that we do not have to add a
3593 * conditional of numpollinfo > 1 below when we
3594 * test pollinfo[1].revents.
3597 pollinfo
[1].fd
= handlep
->poll_breakloop_fd
;
3598 pollinfo
[1].events
= POLLIN
;
3603 * Keep polling until we either get some packets to read, see
3604 * that we got told to break out of the loop, get a fatal error,
3605 * or discover that the device went away.
3607 * In non-blocking mode, we must still do one poll() to catch
3608 * any pending error indications, but the poll() has a timeout
3609 * of 0, so that it doesn't block, and we quit after that one
3612 * If we've seen an ENETDOWN, it might be the first indication
3613 * that the device went away, or it might just be that it was
3614 * configured down. Unfortunately, there's no guarantee that
3615 * the device has actually been removed as an interface, because:
3617 * 1) if, as appears to be the case at least some of the time,
3618 * the PF_PACKET socket code first gets a NETDEV_DOWN indication
3619 * for the device and then gets a NETDEV_UNREGISTER indication
3620 * for it, the first indication will cause a wakeup with ENETDOWN
3621 * but won't set the packet socket's field for the interface index
3622 * to -1, and the second indication won't cause a wakeup (because
3623 * the first indication also caused the protocol hook to be
3624 * unregistered) but will set the packet socket's field for the
3625 * interface index to -1;
3627 * 2) even if just a NETDEV_UNREGISTER indication is registered,
3628 * the packet socket's field for the interface index only gets
3629 * set to -1 after the wakeup, so there's a small but non-zero
3630 * risk that a thread blocked waiting for the wakeup will get
3631 * to the "fetch the socket name" code before the interface index
3632 * gets set to -1, so it'll get the old interface index.
3634 * Therefore, if we got an ENETDOWN and haven't seen a packet
3635 * since then, we assume that we might be waiting for the interface
3636 * to disappear, and poll with a timeout to try again in a short
3637 * period of time. If we *do* see a packet, the interface has
3638 * come back up again, and is *definitely* still there, so we
3639 * don't need to poll.
3643 * Yes, we do this even in non-blocking mode, as it's
3644 * the only way to get error indications from a
3647 * The timeout is 0 in non-blocking mode, so poll()
3648 * returns immediately.
3650 timeout
= handlep
->poll_timeout
;
3653 * If we got an ENETDOWN and haven't gotten an indication
3654 * that the device has gone away or that the device is up,
3655 * we don't yet know for certain whether the device has
3656 * gone away or not, do a poll() with a 1-millisecond timeout,
3657 * as we have to poll indefinitely for "device went away"
3658 * indications until we either get one or see that the
3661 if (handlep
->netdown
) {
3665 ret
= poll(pollinfo
, numpollinfo
, timeout
);
3668 * Error. If it's not EINTR, report it.
3670 if (errno
!= EINTR
) {
3671 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3672 PCAP_ERRBUF_SIZE
, errno
,
3673 "can't poll on packet socket");
3678 * It's EINTR; if we were told to break out of
3681 if (handle
->break_loop
) {
3682 handle
->break_loop
= 0;
3683 return PCAP_ERROR_BREAK
;
3685 } else if (ret
> 0) {
3687 * OK, some descriptor is ready.
3688 * Check the socket descriptor first.
3690 * As I read the Linux man page, pollinfo[0].revents
3691 * will either be POLLIN, POLLERR, POLLHUP, or POLLNVAL.
3693 if (pollinfo
[0].revents
== POLLIN
) {
3695 * OK, we may have packets to
3700 if (pollinfo
[0].revents
!= 0) {
3702 * There's some indication other than
3703 * "you can read on this descriptor" on
3706 if (pollinfo
[0].revents
& POLLNVAL
) {
3707 snprintf(handle
->errbuf
,
3709 "Invalid polling request on packet socket");
3712 if (pollinfo
[0].revents
& (POLLHUP
| POLLRDHUP
)) {
3713 snprintf(handle
->errbuf
,
3715 "Hangup on packet socket");
3718 if (pollinfo
[0].revents
& POLLERR
) {
3725 errlen
= sizeof(err
);
3726 if (getsockopt(handle
->fd
, SOL_SOCKET
,
3727 SO_ERROR
, &err
, &errlen
) == -1) {
3729 * The call *itself* returned
3730 * an error; make *that*
3737 * OK, we have the error.
3739 if (err
== ENETDOWN
) {
3741 * The device on which we're
3742 * capturing went away or the
3743 * interface was taken down.
3745 * We don't know for certain
3746 * which happened, and the
3747 * next poll() may indicate
3748 * that there are packets
3749 * to be read, so just set
3750 * a flag to get us to do
3751 * checks later, and set
3752 * the required select
3753 * timeout to 1 millisecond
3754 * so that event loops that
3755 * check our socket descriptor
3756 * also time out so that
3757 * they can call us and we
3758 * can do the checks.
3760 handlep
->netdown
= 1;
3761 handle
->required_select_timeout
= &netdown_timeout
;
3762 } else if (err
== 0) {
3764 * This shouldn't happen, so
3765 * report a special indication
3768 snprintf(handle
->errbuf
,
3770 "Error condition on packet socket: Reported error was 0");
3773 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3776 "Error condition on packet socket");
3782 * Now check the event device.
3784 if (pollinfo
[1].revents
& POLLIN
) {
3789 * This should never fail, but, just
3792 nread
= read(handlep
->poll_breakloop_fd
, &value
,
3795 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3798 "Error reading from event FD");
3803 * According to the Linux read(2) man
3804 * page, read() will transfer at most
3805 * 2^31-1 bytes, so the return value is
3806 * either -1 or a value between 0
3807 * and 2^31-1, so it's non-negative.
3809 * Cast it to size_t to squelch
3810 * warnings from the compiler; add this
3811 * comment to squelch warnings from
3812 * humans reading the code. :-)
3814 * Don't treat an EOF as an error, but
3815 * *do* treat a short read as an error;
3816 * that "shouldn't happen", but....
3819 (size_t)nread
< sizeof(value
)) {
3820 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3821 "Short read from event FD: expected %zu, got %zd",
3822 sizeof(value
), nread
);
3827 * This event gets signaled by a
3828 * pcap_breakloop() call; if we were told
3829 * to break out of the loop, do so.
3831 if (handle
->break_loop
) {
3832 handle
->break_loop
= 0;
3833 return PCAP_ERROR_BREAK
;
3841 * 1) we got neither an error from poll() nor any
3842 * readable descriptors, in which case there
3843 * are no packets waiting to read
3847 * 2) We got readable descriptors but the PF_PACKET
3848 * socket wasn't one of them, in which case there
3849 * are no packets waiting to read
3851 * so, if we got an ENETDOWN, we've drained whatever
3852 * packets were available to read at the point of the
3855 * So, if we got an ENETDOWN and haven't gotten an indication
3856 * that the device has gone away or that the device is up,
3857 * we don't yet know for certain whether the device has
3858 * gone away or not, check whether the device exists and is
3861 if (handlep
->netdown
) {
3862 if (!device_still_exists(handle
)) {
3864 * The device doesn't exist any more;
3867 * XXX - we should really return an
3868 * appropriate error for that, but
3869 * pcap_dispatch() etc. aren't documented
3870 * as having error returns other than
3871 * PCAP_ERROR or PCAP_ERROR_BREAK.
3873 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3874 "The interface disappeared");
3879 * The device still exists; try to see if it's up.
3881 memset(&ifr
, 0, sizeof(ifr
));
3882 pcapint_strlcpy(ifr
.ifr_name
, handlep
->device
,
3883 sizeof(ifr
.ifr_name
));
3884 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3885 if (errno
== ENXIO
|| errno
== ENODEV
) {
3887 * OK, *now* it's gone.
3889 * XXX - see above comment.
3891 snprintf(handle
->errbuf
,
3893 "The interface disappeared");
3896 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
3897 PCAP_ERRBUF_SIZE
, errno
,
3898 "%s: Can't get flags",
3903 if (ifr
.ifr_flags
& IFF_UP
) {
3905 * It's up, so it definitely still exists.
3906 * Cancel the ENETDOWN indication - we
3907 * presumably got it due to the interface
3908 * going down rather than the device going
3909 * away - and revert to "no required select
3912 handlep
->netdown
= 0;
3913 handle
->required_select_timeout
= NULL
;
3918 * If we're in non-blocking mode, just quit now, rather
3919 * than spinning in a loop doing poll()s that immediately
3920 * time out if there's no indication on any descriptor.
3922 if (handlep
->poll_timeout
== 0)
3928 /* handle a single memory mapped packet */
3929 static int pcap_handle_packet_mmap(
3931 pcap_handler callback
,
3933 unsigned char *frame
,
3934 unsigned int tp_len
,
3935 unsigned int tp_mac
,
3936 unsigned int tp_snaplen
,
3937 unsigned int tp_sec
,
3938 unsigned int tp_usec
,
3939 int tp_vlan_tci_valid
,
3943 struct pcap_linux
*handlep
= handle
->priv
;
3945 struct sockaddr_ll
*sll
;
3946 struct pcap_pkthdr pcaphdr
;
3947 unsigned int snaplen
= tp_snaplen
;
3948 struct utsname utsname
;
3950 /* perform sanity check on internal offset. */
3951 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3953 * Report some system information as a debugging aid.
3955 if (uname(&utsname
) != -1) {
3956 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3957 "corrupted frame on kernel ring mac "
3958 "offset %u + caplen %u > frame len %d "
3959 "(kernel %.32s version %s, machine %.16s)",
3960 tp_mac
, tp_snaplen
, handle
->bufsize
,
3961 utsname
.release
, utsname
.version
,
3964 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3965 "corrupted frame on kernel ring mac "
3966 "offset %u + caplen %u > frame len %d",
3967 tp_mac
, tp_snaplen
, handle
->bufsize
);
3972 /* run filter on received packet
3973 * If the kernel filtering is enabled we need to run the
3974 * filter until all the frames present into the ring
3975 * at filter creation time are processed.
3976 * In this case, blocks_to_filter_in_userland is used
3977 * as a counter for the packet we need to filter.
3978 * Note: alternatively it could be possible to stop applying
3979 * the filter when the ring became empty, but it can possibly
3980 * happen a lot later... */
3981 bp
= frame
+ tp_mac
;
3983 /* if required build in place the sll header*/
3984 sll
= (void *)(frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
));
3985 if (handlep
->cooked
) {
3986 if (handle
->linktype
== DLT_LINUX_SLL2
) {
3987 struct sll2_header
*hdrp
;
3990 * The kernel should have left us with enough
3991 * space for an sll header; back up the packet
3992 * data pointer into that space, as that'll be
3993 * the beginning of the packet we pass to the
3999 * Let's make sure that's past the end of
4000 * the tpacket header, i.e. >=
4001 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4002 * don't step on the header when we construct
4005 if (bp
< (u_char
*)frame
+
4006 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4007 sizeof(struct sockaddr_ll
)) {
4008 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4009 "cooked-mode frame doesn't have room for sll header");
4014 * OK, that worked; construct the sll header.
4016 hdrp
= (struct sll2_header
*)bp
;
4017 hdrp
->sll2_protocol
= sll
->sll_protocol
;
4018 hdrp
->sll2_reserved_mbz
= 0;
4019 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
4020 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
4021 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
4022 hdrp
->sll2_halen
= sll
->sll_halen
;
4023 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4025 snaplen
+= sizeof(struct sll2_header
);
4027 struct sll_header
*hdrp
;
4030 * The kernel should have left us with enough
4031 * space for an sll header; back up the packet
4032 * data pointer into that space, as that'll be
4033 * the beginning of the packet we pass to the
4039 * Let's make sure that's past the end of
4040 * the tpacket header, i.e. >=
4041 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4042 * don't step on the header when we construct
4045 if (bp
< (u_char
*)frame
+
4046 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4047 sizeof(struct sockaddr_ll
)) {
4048 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4049 "cooked-mode frame doesn't have room for sll header");
4054 * OK, that worked; construct the sll header.
4056 hdrp
= (struct sll_header
*)bp
;
4057 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
4058 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4059 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4060 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4061 hdrp
->sll_protocol
= sll
->sll_protocol
;
4063 snaplen
+= sizeof(struct sll_header
);
4067 * If this is a packet from a CAN device, so that
4068 * sll->sll_hatype is ARPHRD_CAN, then, as we're
4069 * not capturing in cooked mode, its link-layer
4070 * type is DLT_CAN_SOCKETCAN. Fix up the header
4071 * provided by the code below us to match what
4072 * DLT_CAN_SOCKETCAN is expected to provide.
4074 if (sll
->sll_hatype
== ARPHRD_CAN
) {
4075 pcap_can_socketcan_hdr
*canhdr
= (pcap_can_socketcan_hdr
*)bp
;
4076 pcap_can_socketcan_xl_hdr
*canxl_hdr
= (pcap_can_socketcan_xl_hdr
*)bp
;
4077 uint16_t protocol
= ntohs(sll
->sll_protocol
);
4080 * Check the protocol field from the sll header.
4081 * If it's one of the known CAN protocol types,
4082 * make sure the appropriate flags are set, so
4083 * that a program can tell what type of frame
4086 * These operations should not have any effect
4087 * when reading proper CAN frames from Linux
4088 * CAN interfaces. Enforcing these bit values
4089 * ensures proper DLT_CAN_SOCKETCAN data even
4090 * with malformed PF_PACKET content.
4092 * The two flags are:
4094 * CANFD_FDF, which is in the fd_flags field
4095 * of the CAN CC/CAN FD header;
4097 * CANXL_XLF, which is in the flags field
4098 * of the CAN XL header, which overlaps
4099 * the payload_length field of the CAN CC/
4100 * CAN FD header. Setting CANXL_XLF in the
4101 * payload_length of CAN CC/FD frames would
4102 * intentionally break the payload length.
4106 case LINUX_SLL_P_CAN
:
4108 * CAN CC frame (aka Classical CAN, CAN 2.0B)
4110 * Zero out the CAN FD and CAN XL flags
4111 * so that this frame will be identified
4112 * as a CAN CC frame.
4114 canxl_hdr
->flags
&= ~CANXL_XLF
;
4115 canhdr
->fd_flags
&= ~CANFD_FDF
;
4118 case LINUX_SLL_P_CANFD
:
4122 * Set CANFD_FDF in the fd_flags field,
4123 * and clear the CANXL_XLF bit in the
4124 * CAN XL flags field, so that this frame
4125 * will be identified as a CAN FD frame.
4127 * The CANFD_FDF bit is not reliably
4128 * set by the Linux kernel. But setting
4129 * that bit for CAN FD is recommended.
4131 canxl_hdr
->flags
&= ~CANXL_XLF
;
4132 canhdr
->fd_flags
|= CANFD_FDF
;
4135 case LINUX_SLL_P_CANXL
:
4139 * Set CANXL_XLF bit in the CAN XL flags
4140 * field, so that this frame will appear
4141 * to be a CAN XL frame.
4143 canxl_hdr
->flags
|= CANXL_XLF
;
4148 * Put multi-byte header fields in a byte-order
4149 * -independent format.
4151 if (canxl_hdr
->flags
& CANXL_XLF
) {
4153 * This is a CAN XL frame.
4155 * DLT_CAN_SOCKETCAN is specified as having
4156 * the Priority ID/VCID field in big-
4157 * endian byte order, and the payload length
4158 * and Acceptance Field in little-endian byte
4159 * order, but capturing on a CAN device
4160 * provides them in host byte order.
4161 * Convert them to the appropriate byte
4164 * The reason we put the first field
4165 * into big-endian byte order is that
4166 * older libpcap code, ignorant of
4167 * CAN XL, treated it as the CAN ID
4168 * field and put it into big-endian
4169 * byte order, and we don't want to
4170 * break code that understands CAN XL
4171 * headers, and treats that field as
4174 * The reason other fields are put in little-
4175 * endian byte order is that older
4176 * libpcap code, ignorant of CAN XL,
4177 * left those fields alone, and the
4178 * processors on which the CAN XL
4179 * frames were captured are likely
4180 * to be little-endian processors.
4183 #if __BYTE_ORDER == __LITTLE_ENDIAN
4185 * We're capturing on a little-endian
4186 * machine, so we put the priority/VCID
4187 * field into big-endian byte order, and
4188 * leave the payload length and acceptance
4189 * field in little-endian byte order.
4191 /* Byte-swap priority/VCID. */
4192 canxl_hdr
->priority_vcid
= SWAPLONG(canxl_hdr
->priority_vcid
);
4193 #elif __BYTE_ORDER == __BIG_ENDIAN
4195 * We're capturing on a big-endian
4196 * machine, so we want to leave the
4197 * priority/VCID field alone, and byte-swap
4198 * the payload length and acceptance
4199 * fields to little-endian.
4201 /* Byte-swap the payload length */
4202 canxl_hdr
->payload_length
= SWAPSHORT(canxl_hdr
->payload_length
);
4205 * Byte-swap the acceptance field.
4207 * XXX - is it just a 4-octet string,
4208 * not in any byte order?
4210 canxl_hdr
->acceptance_field
= SWAPLONG(canxl_hdr
->acceptance_field
);
4212 #error "Unknown byte order"
4216 * CAN CC or CAN FD frame.
4218 * DLT_CAN_SOCKETCAN is specified as having
4219 * the CAN ID and flags in network byte
4220 * order, but capturing on a CAN device
4221 * provides it in host byte order. Convert
4222 * it to network byte order.
4224 canhdr
->can_id
= htonl(canhdr
->can_id
);
4229 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
4230 struct pcap_bpf_aux_data aux_data
;
4232 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
4233 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4235 if (pcapint_filter_with_aux_data(handle
->fcode
.bf_insns
,
4243 if (!linux_check_direction(handle
, sll
))
4247 * Get required packet info from ring header.
4249 * The seconds part of the time stamp is a 32-bit
4250 * unsigned integer; this will have a problem in 2106,
4253 * ts.tv_sec is a time_t, which is signed, and which
4254 * may be 32-bit or 64-bit. Pass it through; if we
4255 * have a 32-bit signed time_t, in which values >
4256 * 2^31-1 won't fit, then:
4258 * Writing the packet to a file will pass the bits
4259 * through. If the program reading the file can
4260 * handle 32-bit unsigned time stamps, including
4261 * any conversion to local time or UTC, it will
4262 * properly handle the time stamps.
4264 * Reporting the packet time stamp may give
4265 * an error or a pre-1970 time stamp on platforms
4266 * with signed 32-bit time stamps, but that
4267 * will happen even if it's captured on a
4268 * platform with a 64-bit time_t.
4270 pcaphdr
.ts
.tv_sec
= tp_sec
;
4271 pcaphdr
.ts
.tv_usec
= tp_usec
;
4272 pcaphdr
.caplen
= tp_snaplen
;
4273 pcaphdr
.len
= tp_len
;
4275 /* if required build in place the sll header*/
4276 if (handlep
->cooked
) {
4277 /* update packet len */
4278 if (handle
->linktype
== DLT_LINUX_SLL2
) {
4279 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
4280 pcaphdr
.len
+= SLL2_HDR_LEN
;
4282 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4283 pcaphdr
.len
+= SLL_HDR_LEN
;
4287 if (tp_vlan_tci_valid
&&
4288 handlep
->vlan_offset
!= -1 &&
4289 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4291 struct vlan_tag
*tag
;
4294 * Move everything in the header, except the type field,
4295 * down VLAN_TAG_LEN bytes, to allow us to insert the
4296 * VLAN tag between that stuff and the type field.
4299 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4302 * Now insert the tag.
4304 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4305 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4306 tag
->vlan_tci
= htons(tp_vlan_tci
);
4309 * Add the tag to the packet lengths.
4311 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4312 pcaphdr
.len
+= VLAN_TAG_LEN
;
4316 * The only way to tell the kernel to cut off the
4317 * packet at a snapshot length is with a filter program;
4318 * if there's no filter program, the kernel won't cut
4321 * Trim the snapshot length to be no longer than the
4322 * specified snapshot length.
4324 * XXX - an alternative is to put a filter, consisting
4325 * of a "ret <snaplen>" instruction, on the socket
4326 * in the activate routine, so that the truncation is
4327 * done in the kernel even if nobody specified a filter;
4328 * that means that less buffer space is consumed in
4329 * the memory-mapped buffer.
4331 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
4332 pcaphdr
.caplen
= handle
->snapshot
;
4334 /* pass the packet to the user */
4335 callback(user
, &pcaphdr
, bp
);
4341 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4344 struct pcap_linux
*handlep
= handle
->priv
;
4349 /* wait for frames availability.*/
4350 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4351 if (!packet_mmap_acquire(h
.h2
)) {
4353 * The current frame is owned by the kernel; wait for
4354 * a frame to be handed to us.
4356 ret
= pcap_wait_for_frames_mmap(handle
);
4363 * This can conceivably process more than INT_MAX packets,
4364 * which would overflow the packet count, causing it either
4365 * to look like a negative number, and thus cause us to
4366 * return a value that looks like an error, or overflow
4367 * back into positive territory, and thus cause us to
4368 * return a too-low count.
4370 * Therefore, if the packet count is unlimited, we clip
4371 * it at INT_MAX; this routine is not expected to
4372 * process packets indefinitely, so that's not an issue.
4374 if (PACKET_COUNT_IS_UNLIMITED(max_packets
))
4375 max_packets
= INT_MAX
;
4377 while (pkts
< max_packets
) {
4379 * Get the current ring buffer frame, and break if
4380 * it's still owned by the kernel.
4382 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4383 if (!packet_mmap_acquire(h
.h2
))
4386 ret
= pcap_handle_packet_mmap(
4395 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4396 VLAN_VALID(h
.h2
, h
.h2
),
4398 VLAN_TPID(h
.h2
, h
.h2
));
4401 } else if (ret
< 0) {
4406 * Hand this block back to the kernel, and, if we're
4407 * counting blocks that need to be filtered in userland
4408 * after having been filtered by the kernel, count
4409 * the one we've just processed.
4411 packet_mmap_release(h
.h2
);
4412 if (handlep
->blocks_to_filter_in_userland
!= 0) {
4413 handlep
->blocks_to_filter_in_userland
--;
4414 if (handlep
->blocks_to_filter_in_userland
== 0) {
4416 * No more blocks need to be filtered
4419 handlep
->filter_in_userland
= 0;
4424 if (++handle
->offset
>= handle
->cc
)
4427 /* check for break loop condition*/
4428 if (handle
->break_loop
) {
4429 handle
->break_loop
= 0;
4430 return PCAP_ERROR_BREAK
;
4436 #ifdef HAVE_TPACKET3
4438 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4441 struct pcap_linux
*handlep
= handle
->priv
;
4447 if (handlep
->current_packet
== NULL
) {
4448 /* wait for frames availability.*/
4449 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4450 if (!packet_mmap_v3_acquire(h
.h3
)) {
4452 * The current frame is owned by the kernel; wait
4453 * for a frame to be handed to us.
4455 ret
= pcap_wait_for_frames_mmap(handle
);
4461 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4462 if (!packet_mmap_v3_acquire(h
.h3
)) {
4463 if (pkts
== 0 && handlep
->timeout
== 0) {
4464 /* Block until we see a packet. */
4471 * This can conceivably process more than INT_MAX packets,
4472 * which would overflow the packet count, causing it either
4473 * to look like a negative number, and thus cause us to
4474 * return a value that looks like an error, or overflow
4475 * back into positive territory, and thus cause us to
4476 * return a too-low count.
4478 * Therefore, if the packet count is unlimited, we clip
4479 * it at INT_MAX; this routine is not expected to
4480 * process packets indefinitely, so that's not an issue.
4482 if (PACKET_COUNT_IS_UNLIMITED(max_packets
))
4483 max_packets
= INT_MAX
;
4485 while (pkts
< max_packets
) {
4486 int packets_to_read
;
4488 if (handlep
->current_packet
== NULL
) {
4489 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4490 if (!packet_mmap_v3_acquire(h
.h3
))
4493 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4494 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4496 packets_to_read
= handlep
->packets_left
;
4498 if (packets_to_read
> (max_packets
- pkts
)) {
4500 * There are more packets in the buffer than
4501 * the number of packets we have left to
4502 * process to get up to the maximum number
4503 * of packets to process. Only process enough
4504 * of them to get us up to that maximum.
4506 packets_to_read
= max_packets
- pkts
;
4509 while (packets_to_read
-- && !handle
->break_loop
) {
4510 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4511 ret
= pcap_handle_packet_mmap(
4515 handlep
->current_packet
,
4518 tp3_hdr
->tp_snaplen
,
4520 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4521 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
4522 tp3_hdr
->hv1
.tp_vlan_tci
,
4523 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
4526 } else if (ret
< 0) {
4527 handlep
->current_packet
= NULL
;
4530 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4531 handlep
->packets_left
--;
4534 if (handlep
->packets_left
<= 0) {
4536 * Hand this block back to the kernel, and, if
4537 * we're counting blocks that need to be
4538 * filtered in userland after having been
4539 * filtered by the kernel, count the one we've
4542 packet_mmap_v3_release(h
.h3
);
4543 if (handlep
->blocks_to_filter_in_userland
!= 0) {
4544 handlep
->blocks_to_filter_in_userland
--;
4545 if (handlep
->blocks_to_filter_in_userland
== 0) {
4547 * No more blocks need to be filtered
4550 handlep
->filter_in_userland
= 0;
4555 if (++handle
->offset
>= handle
->cc
)
4558 handlep
->current_packet
= NULL
;
4561 /* check for break loop condition*/
4562 if (handle
->break_loop
) {
4563 handle
->break_loop
= 0;
4564 return PCAP_ERROR_BREAK
;
4567 if (pkts
== 0 && handlep
->timeout
== 0) {
4568 /* Block until we see a packet. */
4573 #endif /* HAVE_TPACKET3 */
4576 * Attach the given BPF code to the packet capture device.
4579 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
4581 struct pcap_linux
*handlep
;
4582 struct sock_fprog fcode
;
4583 int can_filter_in_kernel
;
4590 pcapint_strlcpy(handle
->errbuf
, "setfilter: No filter specified",
4595 handlep
= handle
->priv
;
4597 /* Make our private copy of the filter */
4599 if (pcapint_install_bpf_program(handle
, filter
) < 0)
4600 /* pcapint_install_bpf_program() filled in errbuf */
4604 * Run user level packet filter by default. Will be overridden if
4605 * installing a kernel filter succeeds.
4607 handlep
->filter_in_userland
= 1;
4609 /* Install kernel level filter if possible */
4611 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
4613 * fcode.len is an unsigned short for current kernel.
4614 * I have yet to see BPF-Code with that much
4615 * instructions but still it is possible. So for the
4616 * sake of correctness I added this check.
4618 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
4620 fcode
.filter
= NULL
;
4621 can_filter_in_kernel
= 0;
4624 * Oh joy, the Linux kernel uses struct sock_fprog instead
4625 * of struct bpf_program and of course the length field is
4626 * of different size. Pointed out by Sebastian
4628 * Oh, and we also need to fix it up so that all "ret"
4629 * instructions with non-zero operands have MAXIMUM_SNAPLEN
4630 * as the operand if we're not capturing in memory-mapped
4631 * mode, and so that, if we're in cooked mode, all memory-
4632 * reference instructions use special magic offsets in
4633 * references to the link-layer header and assume that the
4634 * link-layer payload begins at 0; "fix_program()" will do
4637 switch (fix_program(handle
, &fcode
)) {
4642 * Fatal error; just quit.
4643 * (The "default" case shouldn't happen; we
4644 * return -1 for that reason.)
4650 * The program performed checks that we can't make
4651 * work in the kernel.
4653 can_filter_in_kernel
= 0;
4658 * We have a filter that'll work in the kernel.
4660 can_filter_in_kernel
= 1;
4666 * NOTE: at this point, we've set both the "len" and "filter"
4667 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
4668 * those are the only members of the "sock_fprog" structure,
4669 * so we initialize every member of that structure.
4671 * If there is anything in "fcode" that is not initialized,
4672 * it is either a field added in a later kernel, or it's
4675 * If a new field is added, this code needs to be updated
4676 * to set it correctly.
4678 * If there are no other fields, then:
4680 * if the Linux kernel looks at the padding, it's
4683 * if the Linux kernel doesn't look at the padding,
4684 * then if some tool complains that we're passing
4685 * uninitialized data to the kernel, then the tool
4686 * is buggy and needs to understand that it's just
4689 if (can_filter_in_kernel
) {
4690 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
4693 * Installation succeeded - using kernel filter,
4694 * so userland filtering not needed.
4696 handlep
->filter_in_userland
= 0;
4698 else if (err
== -1) /* Non-fatal error */
4701 * Print a warning if we weren't able to install
4702 * the filter for a reason other than "this kernel
4703 * isn't configured to support socket filters.
4705 if (errno
== ENOMEM
) {
4707 * Either a kernel memory allocation
4708 * failure occurred, or there's too
4709 * much "other/option memory" allocated
4710 * for this socket. Suggest that they
4711 * increase the "other/option memory"
4715 "Warning: Couldn't allocate kernel memory for filter: try increasing net.core.optmem_max with sysctl\n");
4716 } else if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
4718 "Warning: Kernel filter failed: %s\n",
4719 pcap_strerror(errno
));
4725 * If we're not using the kernel filter, get rid of any kernel
4726 * filter that might've been there before, e.g. because the
4727 * previous filter could work in the kernel, or because some other
4728 * code attached a filter to the socket by some means other than
4729 * calling "pcap_setfilter()". Otherwise, the kernel filter may
4730 * filter out packets that would pass the new userland filter.
4732 if (handlep
->filter_in_userland
) {
4733 if (reset_kernel_filter(handle
) == -1) {
4734 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
4735 PCAP_ERRBUF_SIZE
, errno
,
4736 "can't remove kernel filter");
4737 err
= -2; /* fatal error */
4742 * Free up the copy of the filter that was made by "fix_program()".
4744 if (fcode
.filter
!= NULL
)
4752 * If we're filtering in userland, there's nothing to do;
4753 * the new filter will be used for the next packet.
4755 if (handlep
->filter_in_userland
)
4759 * We're filtering in the kernel; the packets present in
4760 * all blocks currently in the ring were already filtered
4761 * by the old filter, and so will need to be filtered in
4762 * userland by the new filter.
4764 * Get an upper bound for the number of such blocks; first,
4765 * walk the ring backward and count the free blocks.
4767 offset
= handle
->offset
;
4769 offset
= handle
->cc
;
4771 for (n
=0; n
< handle
->cc
; ++n
) {
4773 offset
= handle
->cc
;
4775 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
4780 * If we found free blocks, decrement the count of free
4781 * blocks by 1, just in case we lost a race with another
4782 * thread of control that was adding a packet while
4783 * we were counting and that had run the filter before
4786 * XXX - could there be more than one block added in
4789 * XXX - is there a way to avoid that race, e.g. somehow
4790 * wait for all packets that passed the old filter to
4791 * be added to the ring?
4797 * Set the count of blocks worth of packets to filter
4798 * in userland to the total number of blocks in the
4799 * ring minus the number of free blocks we found, and
4800 * turn on userland filtering. (The count of blocks
4801 * worth of packets to filter in userland is guaranteed
4802 * not to be zero - n, above, couldn't be set to a
4803 * value > handle->cc, and if it were equal to
4804 * handle->cc, it wouldn't be zero, and thus would
4805 * be decremented to handle->cc - 1.)
4807 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4808 handlep
->filter_in_userland
= 1;
4814 * Return the index of the given device name. Fill ebuf and return
4818 iface_get_id(int fd
, const char *device
, char *ebuf
)
4822 memset(&ifr
, 0, sizeof(ifr
));
4823 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4825 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4826 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4827 errno
, "SIOCGIFINDEX");
4831 return ifr
.ifr_ifindex
;
4835 * Bind the socket associated with FD to the given device.
4836 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
4839 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
4841 struct sockaddr_ll sll
;
4843 socklen_t errlen
= sizeof(err
);
4845 memset(&sll
, 0, sizeof(sll
));
4846 sll
.sll_family
= AF_PACKET
;
4847 sll
.sll_ifindex
= ifindex
< 0 ? 0 : ifindex
;
4848 sll
.sll_protocol
= protocol
;
4850 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4851 if (errno
== ENETDOWN
) {
4853 * Return a "network down" indication, so that
4854 * the application can report that rather than
4855 * saying we had a mysterious failure and
4856 * suggest that they report a problem to the
4857 * libpcap developers.
4859 return PCAP_ERROR_IFACE_NOT_UP
;
4861 if (errno
== ENODEV
) {
4863 * There's nothing more to say, so clear the
4867 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
4870 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4876 /* Any pending errors, e.g., network is down? */
4878 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4879 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4880 errno
, "getsockopt (SO_ERROR)");
4884 if (err
== ENETDOWN
) {
4886 * Return a "network down" indication, so that
4887 * the application can report that rather than
4888 * saying we had a mysterious failure and
4889 * suggest that they report a problem to the
4890 * libpcap developers.
4892 return PCAP_ERROR_IFACE_NOT_UP
;
4893 } else if (err
> 0) {
4894 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4903 * Try to enter monitor mode.
4904 * If we have libnl, try to create a new monitor-mode device and
4905 * capture on that; otherwise, just say "not supported".
4909 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4911 struct pcap_linux
*handlep
= handle
->priv
;
4913 char phydev_path
[PATH_MAX
+1];
4914 struct nl80211_state nlstate
;
4919 * Is this a mac80211 device?
4921 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
4923 return ret
; /* error */
4925 return 0; /* no error, but not mac80211 device */
4927 ret
= nl80211_init(handle
, &nlstate
, device
);
4932 * Is this already a monN device?
4933 * If so, we're done.
4936 ret
= get_if_type(handle
, sock_fd
, &nlstate
, device
, &type
);
4939 * < 0 is a Hard failure. Just return ret; handle->errbuf
4940 * has already been set.
4942 * 0 is "device not available"; the caller should retry later.
4944 nl80211_cleanup(&nlstate
);
4947 if (type
== NL80211_IFTYPE_MONITOR
) {
4949 * OK, it's already a monitor mode device; just use it.
4950 * There's no point in creating another monitor device
4951 * that will have to be cleaned up.
4953 nl80211_cleanup(&nlstate
);
4958 * OK, it's apparently a mac80211 device but not a monitor device.
4959 * Try to find an unused monN device for it.
4961 for (n
= 0; n
< UINT_MAX
; n
++) {
4965 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
4967 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
4968 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
4971 * Success. We don't clean up the libnl state
4972 * yet, as we'll be using it later.
4978 * Hard failure. Just return ret; handle->errbuf
4979 * has already been set.
4981 nl80211_cleanup(&nlstate
);
4986 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4987 "%s: No free monN interfaces", device
);
4988 nl80211_cleanup(&nlstate
);
4995 * Sleep for .1 seconds.
4998 delay
.tv_nsec
= 500000000;
4999 nanosleep(&delay
, NULL
);
5003 * If we haven't already done so, arrange to have
5004 * "pcap_close_all()" called when we exit.
5006 if (!pcapint_do_addexit(handle
)) {
5008 * "atexit()" failed; don't put the interface
5009 * in rfmon mode, just give up.
5010 * handle->errbuf has already been filled.
5012 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
5013 handlep
->mondevice
);
5014 nl80211_cleanup(&nlstate
);
5019 * Now configure the monitor interface up.
5021 memset(&ifr
, 0, sizeof(ifr
));
5022 pcapint_strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
5023 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5024 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5025 errno
, "%s: Can't get flags for %s", device
,
5026 handlep
->mondevice
);
5027 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
5028 handlep
->mondevice
);
5029 nl80211_cleanup(&nlstate
);
5032 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
5033 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5034 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5035 errno
, "%s: Can't set flags for %s", device
,
5036 handlep
->mondevice
);
5037 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
5038 handlep
->mondevice
);
5039 nl80211_cleanup(&nlstate
);
5044 * Success. Clean up the libnl state.
5046 nl80211_cleanup(&nlstate
);
5049 * Note that we have to delete the monitor device when we close
5052 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
5055 * Add this to the list of pcaps to close when we exit.
5057 pcapint_add_to_pcaps_to_close(handle
);
5061 #else /* HAVE_LIBNL */
5063 enter_rfmon_mode(pcap_t
*handle _U_
, int sock_fd _U_
, const char *device _U_
)
5066 * We don't have libnl, so we can't do monitor mode.
5070 #endif /* HAVE_LIBNL */
5072 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5074 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5076 static const struct {
5077 int soft_timestamping_val
;
5078 int pcap_tstamp_val
;
5079 } sof_ts_type_map
[3] = {
5080 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5081 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5082 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5084 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5087 * Set the list of time stamping types to include all types.
5090 iface_set_all_ts_types(pcap_t
*handle
, char *ebuf
)
5094 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5095 if (handle
->tstamp_type_list
== NULL
) {
5096 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5100 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5101 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5102 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5107 * Get a list of time stamp types.
5109 #ifdef ETHTOOL_GET_TS_INFO
5111 iface_get_ts_types(const char *device
, pcap_t
*handle
, char *ebuf
)
5115 struct ethtool_ts_info info
;
5120 * This doesn't apply to the "any" device; you can't say "turn on
5121 * hardware time stamping for all devices that exist now and arrange
5122 * that it be turned on for any device that appears in the future",
5123 * and not all devices even necessarily *support* hardware time
5124 * stamping, so don't report any time stamp types.
5126 if (strcmp(device
, "any") == 0) {
5127 handle
->tstamp_type_list
= NULL
;
5132 * Create a socket from which to fetch time stamping capabilities.
5134 fd
= get_if_ioctl_socket();
5136 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5137 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
5141 memset(&ifr
, 0, sizeof(ifr
));
5142 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5143 memset(&info
, 0, sizeof(info
));
5144 info
.cmd
= ETHTOOL_GET_TS_INFO
;
5145 ifr
.ifr_data
= (caddr_t
)&info
;
5146 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
5147 int save_errno
= errno
;
5150 switch (save_errno
) {
5155 * OK, this OS version or driver doesn't support
5156 * asking for the time stamping types, so let's
5157 * just return all the possible types.
5159 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
5165 * OK, no such device.
5166 * The user will find that out when they try to
5167 * activate the device; just return an empty
5168 * list of time stamp types.
5170 handle
->tstamp_type_list
= NULL
;
5177 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5179 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
5187 * Do we support hardware time stamping of *all* packets?
5189 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
5191 * No, so don't report any time stamp types.
5193 * XXX - some devices either don't report
5194 * HWTSTAMP_FILTER_ALL when they do support it, or
5195 * report HWTSTAMP_FILTER_ALL but map it to only
5196 * time stamping a few PTP packets. See
5197 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
5199 * Maybe that got fixed later.
5201 handle
->tstamp_type_list
= NULL
;
5206 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5207 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
5210 if (num_ts_types
!= 0) {
5211 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
5212 if (handle
->tstamp_type_list
== NULL
) {
5213 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5217 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5218 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
5219 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5223 handle
->tstamp_type_count
= num_ts_types
;
5225 handle
->tstamp_type_list
= NULL
;
5229 #else /* ETHTOOL_GET_TS_INFO */
5231 iface_get_ts_types(const char *device
, pcap_t
*handle
, char *ebuf
)
5234 * This doesn't apply to the "any" device; you can't say "turn on
5235 * hardware time stamping for all devices that exist now and arrange
5236 * that it be turned on for any device that appears in the future",
5237 * and not all devices even necessarily *support* hardware time
5238 * stamping, so don't report any time stamp types.
5240 if (strcmp(device
, "any") == 0) {
5241 handle
->tstamp_type_list
= NULL
;
5246 * We don't have an ioctl to use to ask what's supported,
5247 * so say we support everything.
5249 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
5253 #endif /* ETHTOOL_GET_TS_INFO */
5254 #else /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5256 iface_get_ts_types(const char *device _U_
, pcap_t
*p _U_
, char *ebuf _U_
)
5259 * Nothing to fetch, so it always "succeeds".
5263 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5266 * Find out if we have any form of fragmentation/reassembly offloading.
5268 * We do so using SIOCETHTOOL checking for various types of offloading;
5269 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5270 * of the types of offloading, there's nothing we can do to check, so
5271 * we just say "no, we don't".
5273 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
5274 * indications that the operation isn't supported. We do EPERM
5275 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
5276 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
5277 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
5278 * and 3) does the "is this permitted" check before doing the "is
5279 * this even supported" check, so it fails with "this is not permitted"
5280 * rather than "this is not even supported". To work around this
5281 * annoyance, we only treat EPERM as an error for the first feature,
5282 * and assume that they all do the same permission checks, so if the
5283 * first one is allowed all the others are allowed if supported.
5285 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5287 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
,
5291 struct ethtool_value eval
;
5293 memset(&ifr
, 0, sizeof(ifr
));
5294 pcapint_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
5297 ifr
.ifr_data
= (caddr_t
)&eval
;
5298 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5299 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
||
5300 (errno
== EPERM
&& eperm_ok
)) {
5302 * OK, let's just return 0, which, in our
5303 * case, either means "no, what we're asking
5304 * about is not enabled" or "all the flags
5305 * are clear (i.e., nothing is enabled)".
5309 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5310 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
5311 handle
->opt
.device
, cmdname
);
5318 * XXX - it's annoying that we have to check for offloading at all, but,
5319 * given that we have to, it's still annoying that we have to check for
5320 * particular types of offloading, especially that shiny new types of
5321 * offloading may be added - and, worse, may not be checkable with
5322 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
5323 * theory, give those to you, but the actual flags being used are
5324 * opaque (defined in a non-uapi header), and there doesn't seem to
5325 * be any obvious way to ask the kernel what all the offloading flags
5326 * are - at best, you can ask for a set of strings(!) to get *names*
5327 * for various flags. (That whole mechanism appears to have been
5328 * designed for the sole purpose of letting ethtool report flags
5329 * by name and set flags by name, with the names having no semantics
5330 * ethtool understands.)
5333 iface_get_offload(pcap_t
*handle
)
5338 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO", 0);
5342 return 1; /* TCP segmentation offloading on */
5347 * XXX - will this cause large unsegmented packets to be
5348 * handed to PF_PACKET sockets on transmission? If not,
5349 * this need not be checked.
5351 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO", 0);
5355 return 1; /* generic segmentation offloading on */
5358 #ifdef ETHTOOL_GFLAGS
5359 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS", 0);
5362 if (ret
& ETH_FLAG_LRO
)
5363 return 1; /* large receive offloading on */
5368 * XXX - will this cause large reassembled packets to be
5369 * handed to PF_PACKET sockets on receipt? If not,
5370 * this need not be checked.
5372 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO", 0);
5376 return 1; /* generic (large) receive offloading on */
5381 * Do this one last, as support for it was removed in later
5382 * kernels, and it fails with EPERM on those kernels rather
5383 * than with EOPNOTSUPP (see explanation in comment for
5384 * iface_ethtool_flag_ioctl()).
5386 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO", 1);
5390 return 1; /* UDP fragmentation offloading on */
5395 #else /* SIOCETHTOOL */
5397 iface_get_offload(pcap_t
*handle _U_
)
5400 * XXX - do we need to get this information if we don't
5401 * have the ethtool ioctls? If so, how do we do that?
5405 #endif /* SIOCETHTOOL */
5410 * https://www.kernel.org/doc/html/latest/networking/dsa/dsa.html#switch-tagging-protocols
5412 * Type 1 means that the tag is prepended to the Ethernet packet.
5413 * LINKTYPE_ETHERNET/DLT_EN10MB doesn't work, as it would try to
5414 * dissect the tag data as the Ethernet header. These should get
5415 * their own LINKTYPE_DLT_ values.
5417 * Type 2 means that the tag is inserted into the Ethernet header
5418 * after the source address and before the type/length field.
5420 * Type 3 means that tag is a packet trailer. LINKTYPE_ETHERNET/DLT_EN10MB
5421 * works, unless the next-layer protocol has no length field of its own,
5422 * so that the tag might be treated as part of the payload. These should
5423 * get their own LINKTYPE_/DLT_ values.
5425 * If you get an "unsupported DSA tag" error, please add the tag to here,
5426 * complete with a full comment indicating whether it's type 1, 2, or 3,
5427 * and, for type 2, indicating whether it has an Ethertype and, if so
5428 * what that type is, and whether it's registered with the IEEE or is
5429 * self-assigned. Also, point to *something* that indicates the format
5432 static struct dsa_proto
{
5434 bpf_u_int32 linktype
;
5439 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ar9331.c
5441 { "ar9331", DLT_EN10MB
},
5444 * Type 2, without an EtherType at the beginning,
5445 * assigned a LINKTYPE_/DLT_ value.
5447 { "brcm", DLT_DSA_TAG_BRCM
},
5450 * Type 2, with EtherType 0x8874, assigned to Broadcom.
5452 * This does not require a LINKTYPE_/DLT_ value, it
5453 * just requires that Ethertype 0x8874 be dissected
5456 { "brcm-legacy", DLT_EN10MB
},
5461 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND
},
5464 * Type 2, without an EtherType at the beginning,
5465 * assigned a LINKTYPE_/DLT_ value.
5467 { "dsa", DLT_DSA_TAG_DSA
},
5470 * Type 2, with an Ethertype field, but without
5471 * an assigned EtherType value that can be relied
5472 * on; assigned a LINKTYPE_/DLT_ value.
5474 { "edsa", DLT_DSA_TAG_EDSA
},
5477 * Type 1, with different transmit and receive headers,
5478 * so can't really be handled well with the current
5479 * libpcap API and with pcap files. Use DLT_LINUX_SLL,
5480 * to get the direction?
5484 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_gswip.c
5486 { "gswip", DLT_EN10MB
},
5491 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_hellcreek.c
5493 { "hellcreek", DLT_EN10MB
},
5496 * Type 3, with different transmit and receive headers,
5497 * so can't really be handled well with the current
5498 * libpcap API and with pcap files. Use DLT_LINUX_SLL,
5499 * to get the direction?
5503 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L102
5505 { "ksz8795", DLT_EN10MB
},
5508 * Type 3, with different transmit and receive headers,
5509 * so can't really be handled well with the current
5510 * libpcap API and with pcap files. Use DLT_LINUX_SLL,
5511 * to get the direction?
5515 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L160
5517 { "ksz9477", DLT_EN10MB
},
5520 * Type 3, with different transmit and receive headers,
5521 * so can't really be handled well with the current
5522 * libpcap API and with pcap files. Use DLT_LINUX_SLL,
5523 * to get the direction?
5527 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L341
5529 { "ksz9893", DLT_EN10MB
},
5532 * Type 3, with different transmit and receive headers,
5533 * so can't really be handled well with the current
5534 * libpcap API and with pcap files. Use DLT_LINUX_SLL,
5535 * to get the direction?
5539 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ksz.c#L386
5541 { "lan937x", DLT_EN10MB
},
5544 * Type 2, with EtherType 0x8100; the VID can be interpreted
5547 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_lan9303.c#L24
5549 * so giving its own LINKTYPE_/DLT_ value would allow a
5550 * dissector to do so.
5552 { "lan9303", DLT_EN10MB
},
5555 * Type 2, without an EtherType at the beginning,
5556 * should be assigned a LINKTYPE_/DLT_ value.
5560 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_mtk.c#L15
5562 { "mtk", DLT_EN10MB
},
5565 * The string "none" indicates that the interface does not have
5566 * any tagging protocol configured, and is therefore a standard
5567 * Ethernet interface.
5569 { "none", DLT_EN10MB
},
5576 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ocelot.c
5578 { "ocelot", DLT_EN10MB
},
5585 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_ocelot.c
5587 { "seville", DLT_EN10MB
},
5590 * Type 2, with EtherType 0x8100; the VID can be interpreted
5593 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_8021q.c#L15
5595 * so giving its own LINKTYPE_/DLT_ value would allow a
5596 * dissector to do so.
5598 { "ocelot-8021q", DLT_EN10MB
},
5601 * Type 2, without an EtherType at the beginning,
5602 * should be assigned a LINKTYPE_/DLT_ value.
5606 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_qca.c
5608 { "qca", DLT_EN10MB
},
5611 * Type 2, with EtherType 0x8899, assigned to Realtek;
5612 * they use it for several on-the-Ethernet protocols
5613 * as well, but there are fields that allow the two
5614 * tag formats, and all the protocols in question,
5615 * to be distinguiished from one another.
5617 * This does not require a LINKTYPE_/DLT_ value, it
5618 * just requires that EtherType 0x8899 be dissected
5623 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_rtl4_a.c
5625 * http://realtek.info/pdf/rtl8306sd%28m%29_datasheet_1.1.pdf
5627 * and various pages in tcpdump's print-realtek.c and Wireshark's
5628 * epan/dissectors/packet-realtek.c for the other protocols.
5630 { "rtl4a", DLT_EN10MB
},
5633 * Type 2, with EtherType 0x8899, assigned to Realtek;
5636 { "rtl8_4", DLT_EN10MB
},
5639 * Type 3, with the same tag format as rtl8_4.
5641 { "rtl8_4t", DLT_EN10MB
},
5644 * Type 2, with EtherType 0xe001; that's probably
5645 * self-assigned, so this really should have its
5646 * own LINKTYPE_/DLT_ value.
5650 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_rzn1_a5psw.c
5652 { "a5psw", DLT_EN10MB
},
5655 * Type 2, with EtherType 0x8100 or the self-assigned
5656 * 0xdadb, so this really should have its own
5657 * LINKTYPE_/DLT_ value; that would also allow the
5658 * VID of the tag to be dissected as per
5660 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_8021q.c#L15
5662 { "sja1105", DLT_EN10MB
},
5665 * Type "none of the above", with both a header and trailer,
5666 * with different transmit and receive tags. Has
5667 * EtherType 0xdadc, which is probably self-assigned.
5668 * This should really have its own LINKTYPE_/DLT_ value.
5670 { "sja1110", DLT_EN10MB
},
5673 * Type 3, as the name suggests.
5677 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_trailer.c
5679 { "trailer", DLT_EN10MB
},
5682 * Type 2, with EtherType 0x8100; the VID can be interpreted
5685 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_8021q.c#L15
5687 * so giving its own LINKTYPE_/DLT_ value would allow a
5688 * dissector to do so.
5690 { "vsc73xx-8021q", DLT_EN10MB
},
5697 * https://elixir.bootlin.com/linux/v6.13.2/source/net/dsa/tag_xrs700x.c
5699 { "xrs700x", DLT_EN10MB
},
5703 iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
)
5708 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
5709 * the tag *shouldn't* have some huge long name, and making
5710 * it smaller keeps newer versions of GCC from whining that
5711 * the error message if we don't support the tag could
5712 * overflow the error message buffer.
5718 fd
= asprintf(&pathstr
, "/sys/class/net/%s/dsa/tagging", device
);
5720 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5725 fd
= open(pathstr
, O_RDONLY
);
5728 * This is not fatal, kernel >= 4.20 *might* expose this attribute
5733 r
= read(fd
, buf
, sizeof(buf
) - 1);
5735 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5743 * Buffer should be LF terminated.
5745 if (buf
[r
- 1] == '\n')
5749 for (i
= 0; i
< sizeof(dsa_protos
) / sizeof(dsa_protos
[0]); i
++) {
5750 if (strlen(dsa_protos
[i
].name
) == (size_t)r
&&
5751 strcmp(buf
, dsa_protos
[i
].name
) == 0) {
5752 handle
->linktype
= dsa_protos
[i
].linktype
;
5753 switch (dsa_protos
[i
].linktype
) {
5762 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5763 "unsupported DSA tag: %s", buf
);
5769 * Query the kernel for the MTU of the given interface.
5772 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5777 return BIGGER_THAN_ALL_MTUS
;
5779 memset(&ifr
, 0, sizeof(ifr
));
5780 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5782 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5783 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5784 errno
, "SIOCGIFMTU");
5792 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5795 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5800 memset(&ifr
, 0, sizeof(ifr
));
5801 pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5803 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5804 if (errno
== ENODEV
) {
5808 * There's nothing more to say, so clear
5809 * the error message.
5811 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5815 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5816 errno
, "SIOCGIFHWADDR");
5821 return ifr
.ifr_hwaddr
.sa_family
;
5825 * In a DLT_CAN_SOCKETCAN frame the first four bytes are a 32-bit integer
5826 * value in host byte order if the filter program is running in the kernel and
5827 * in network byte order if in userland. This applies to both CC, FD and XL
5828 * frames, see pcap_handle_packet_mmap() for the rationale. Return 1 iff the
5829 * [possibly modified] filter program can work correctly in the kernel.
5831 #if __BYTE_ORDER == __LITTLE_ENDIAN
5833 fix_dlt_can_socketcan(const u_int len
, struct bpf_insn insn
[])
5835 for (u_int i
= 0; i
< len
; ++i
) {
5836 switch (insn
[i
].code
) {
5837 case BPF_LD
|BPF_B
|BPF_ABS
: // ldb [k]
5838 case BPF_LDX
|BPF_MSH
|BPF_B
: // ldxb 4*([k]&0xf)
5840 insn
[i
].k
= 3 - insn
[i
].k
; // Fixed now.
5842 case BPF_LD
|BPF_H
|BPF_ABS
: // ldh [k]
5843 case BPF_LD
|BPF_W
|BPF_ABS
: // ld [k]
5845 * A halfword or a word load cannot be fixed by just
5846 * changing k, even if every required byte is within
5847 * the byte-swapped part of the frame, even if the
5848 * load is aligned. The fix would require either
5849 * rewriting the filter program extensively or
5850 * generating it differently in the first place.
5852 case BPF_LD
|BPF_B
|BPF_IND
: // ldb [x + k]
5853 case BPF_LD
|BPF_H
|BPF_IND
: // ldh [x + k]
5854 case BPF_LD
|BPF_W
|BPF_IND
: // ld [x + k]
5856 * In addition to the above, a variable offset load
5857 * cannot be fixed because x can have any value, thus
5858 * x + k can have any value, but only the first four
5859 * bytes are swapped. An easy way to demonstrate it
5860 * is to compile "link[link[4]] == 0", which will use
5861 * "ldb [x + 0]" to access one of the first four bytes
5862 * of the frame iff CAN CC/FD payload length is less
5866 return 0; // Userland filtering only.
5874 fix_dlt_can_socketcan(const u_int len _U_
, struct bpf_insn insn
[] _U_
)
5878 #endif // __BYTE_ORDER == __LITTLE_ENDIAN
5881 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
5883 struct pcap_linux
*handlep
= handle
->priv
;
5886 register struct bpf_insn
*p
;
5891 * Make a copy of the filter, and modify that copy if
5894 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5895 len
= handle
->fcode
.bf_len
;
5896 f
= (struct bpf_insn
*)malloc(prog_size
);
5898 pcapint_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5902 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5904 fcode
->filter
= (struct sock_filter
*) f
;
5906 switch (handle
->linktype
) {
5907 case DLT_CAN_SOCKETCAN
:
5909 * If a similar fix needs to be done for CAN frames that
5910 * appear on the "any" pseudo-interface, it needs to be done
5911 * differently because that would be within DLT_LINUX_SLL or
5914 return fix_dlt_can_socketcan(len
, f
);
5917 for (i
= 0; i
< len
; ++i
) {
5920 * What type of instruction is this?
5922 switch (BPF_CLASS(p
->code
)) {
5927 * It's a load instruction; is it loading
5930 switch (BPF_MODE(p
->code
)) {
5936 * Yes; are we in cooked mode?
5938 if (handlep
->cooked
) {
5940 * Yes, so we need to fix this
5943 if (fix_offset(handle
, p
) < 0) {
5945 * We failed to do so.
5946 * Return 0, so our caller
5947 * knows to punt to userland.
5957 return 1; /* we succeeded */
5961 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
5964 * Existing references to auxiliary data shouldn't be adjusted.
5966 * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
5967 * we use >= and cast SKF_AD_OFF to unsigned.
5969 if (p
->k
>= (bpf_u_int32
)SKF_AD_OFF
)
5971 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5973 * What's the offset?
5975 if (p
->k
>= SLL2_HDR_LEN
) {
5977 * It's within the link-layer payload; that starts
5978 * at an offset of 0, as far as the kernel packet
5979 * filter is concerned, so subtract the length of
5980 * the link-layer header.
5982 p
->k
-= SLL2_HDR_LEN
;
5983 } else if (p
->k
== 0) {
5985 * It's the protocol field; map it to the
5986 * special magic kernel offset for that field.
5988 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5989 } else if (p
->k
== 4) {
5991 * It's the ifindex field; map it to the
5992 * special magic kernel offset for that field.
5994 p
->k
= SKF_AD_OFF
+ SKF_AD_IFINDEX
;
5995 } else if (p
->k
== 10) {
5997 * It's the packet type field; map it to the
5998 * special magic kernel offset for that field.
6000 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6001 } else if ((bpf_int32
)(p
->k
) > 0) {
6003 * It's within the header, but it's not one of
6004 * those fields; we can't do that in the kernel,
6005 * so punt to userland.
6011 * What's the offset?
6013 if (p
->k
>= SLL_HDR_LEN
) {
6015 * It's within the link-layer payload; that starts
6016 * at an offset of 0, as far as the kernel packet
6017 * filter is concerned, so subtract the length of
6018 * the link-layer header.
6020 p
->k
-= SLL_HDR_LEN
;
6021 } else if (p
->k
== 0) {
6023 * It's the packet type field; map it to the
6024 * special magic kernel offset for that field.
6026 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6027 } else if (p
->k
== 14) {
6029 * It's the protocol field; map it to the
6030 * special magic kernel offset for that field.
6032 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6033 } else if ((bpf_int32
)(p
->k
) > 0) {
6035 * It's within the header, but it's not one of
6036 * those fields; we can't do that in the kernel,
6037 * so punt to userland.
6046 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
6048 int total_filter_on
= 0;
6054 * The socket filter code doesn't discard all packets queued
6055 * up on the socket when the filter is changed; this means
6056 * that packets that don't match the new filter may show up
6057 * after the new filter is put onto the socket, if those
6058 * packets haven't yet been read.
6060 * This means, for example, that if you do a tcpdump capture
6061 * with a filter, the first few packets in the capture might
6062 * be packets that wouldn't have passed the filter.
6064 * We therefore discard all packets queued up on the socket
6065 * when setting a kernel filter. (This isn't an issue for
6066 * userland filters, as the userland filtering is done after
6067 * packets are queued up.)
6069 * To flush those packets, we put the socket in read-only mode,
6070 * and read packets from the socket until there are no more to
6073 * In order to keep that from being an infinite loop - i.e.,
6074 * to keep more packets from arriving while we're draining
6075 * the queue - we put the "total filter", which is a filter
6076 * that rejects all packets, onto the socket before draining
6079 * This code deliberately ignores any errors, so that you may
6080 * get bogus packets if an error occurs, rather than having
6081 * the filtering done in userland even if it could have been
6082 * done in the kernel.
6084 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6085 &total_fcode
, sizeof(total_fcode
)) == 0) {
6089 * Note that we've put the total filter onto the socket.
6091 total_filter_on
= 1;
6094 * Save the socket's current mode, and put it in
6095 * non-blocking mode; we drain it by reading packets
6096 * until we get an error (which is normally a
6097 * "nothing more to be read" error).
6099 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6100 if (save_mode
== -1) {
6101 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
6102 PCAP_ERRBUF_SIZE
, errno
,
6103 "can't get FD flags when changing filter");
6106 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
6107 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
6108 PCAP_ERRBUF_SIZE
, errno
,
6109 "can't set nonblocking mode when changing filter");
6112 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
6115 if (save_errno
!= EAGAIN
) {
6119 * If we can't restore the mode or reset the
6120 * kernel filter, there's nothing we can do.
6122 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
6123 (void)reset_kernel_filter(handle
);
6124 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
6125 PCAP_ERRBUF_SIZE
, save_errno
,
6126 "recv failed when changing filter");
6129 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
6130 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
6131 PCAP_ERRBUF_SIZE
, errno
,
6132 "can't restore FD flags when changing filter");
6138 * Now attach the new filter.
6140 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6141 fcode
, sizeof(*fcode
));
6142 if (ret
== -1 && total_filter_on
) {
6144 * Well, we couldn't set that filter on the socket,
6145 * but we could set the total filter on the socket.
6147 * This could, for example, mean that the filter was
6148 * too big to put into the kernel, so we'll have to
6149 * filter in userland; in any case, we'll be doing
6150 * filtering in userland, so we need to remove the
6151 * total filter so we see packets.
6156 * If this fails, we're really screwed; we have the
6157 * total filter on the socket, and it won't come off.
6158 * Report it as a fatal error.
6160 if (reset_kernel_filter(handle
) == -1) {
6161 pcapint_fmt_errmsg_for_errno(handle
->errbuf
,
6162 PCAP_ERRBUF_SIZE
, errno
,
6163 "can't remove kernel total filter");
6164 return -2; /* fatal error */
6173 reset_kernel_filter(pcap_t
*handle
)
6177 * setsockopt() barfs unless it get a dummy parameter.
6178 * valgrind whines unless the value is initialized,
6179 * as it has no idea that setsockopt() ignores its
6184 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6185 &dummy
, sizeof(dummy
));
6187 * Ignore ENOENT - it means "we don't have a filter", so there
6188 * was no filter to remove, and there's still no filter.
6190 * Also ignore ENONET, as a lot of kernel versions had a
6191 * typo where ENONET, rather than ENOENT, was returned.
6193 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
6199 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
6201 if (pcapint_check_activated(p
))
6202 return (PCAP_ERROR_ACTIVATED
);
6203 p
->opt
.protocol
= protocol
;
6208 * Libpcap version string.
6211 pcap_lib_version(void)
6213 return (PCAP_VERSION_STRING
6214 #if defined(HAVE_TPACKET3) && defined(PCAP_SUPPORT_NETMAP)
6215 " (with TPACKET_V3 and netmap)"
6216 #elif defined(HAVE_TPACKET3)
6217 " (with TPACKET_V3)"
6218 #elif defined(PCAP_SUPPORT_NETMAP)
6219 " (with TPACKET_V2 and netmap)"
6221 " (with TPACKET_V2)"