2 * pcap-linux.c: Packet capture interface to the Linux kernel
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
23 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
29 * Added TPACKET_V3 support
30 * Gabor Tatarka <gabor.tatarka@ericsson.com>
32 * based on previous works of:
33 * Simon Patarin <patarin@cs.unibo.it>
34 * Phil Wood <cpw@lanl.gov>
36 * Monitor-mode support for mac80211 includes code taken from the iw
37 * command; the copyright notice for that code is
39 * Copyright (c) 2007, 2008 Johannes Berg
40 * Copyright (c) 2007 Andy Lutomirski
41 * Copyright (c) 2007 Mike Kershaw
42 * Copyright (c) 2008 Gábor Stefanik
44 * All rights reserved.
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
49 * 1. Redistributions of source code must retain the above copyright
50 * notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 * notice, this list of conditions and the following disclaimer in the
53 * documentation and/or other materials provided with the distribution.
54 * 3. The name of the author may not be used to endorse or promote products
55 * derived from this software without specific prior written permission.
57 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
58 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
60 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
61 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
62 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
63 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
64 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
65 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
85 #include <sys/socket.h>
86 #include <sys/ioctl.h>
87 #include <sys/utsname.h>
90 #include <linux/if_packet.h>
91 #include <linux/sockios.h>
92 #include <linux/ethtool.h>
93 #include <netinet/in.h>
94 #include <linux/if_ether.h>
95 #include <linux/if_arp.h>
98 #include <sys/eventfd.h>
100 #include "pcap-int.h"
101 #include "pcap/sll.h"
102 #include "pcap/vlan.h"
103 #include "pcap/can_socketcan.h"
105 #include "diag-control.h"
108 * We require TPACKET_V2 support.
110 #ifndef TPACKET2_HDRLEN
111 #error "Libpcap will only work if TPACKET_V2 is supported; you must build for a 2.6.27 or later kernel"
114 /* check for memory mapped access avaibility. We assume every needed
115 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
116 * uses many ring related structs and macros */
117 #ifdef TPACKET3_HDRLEN
118 # define HAVE_TPACKET3
119 #endif /* TPACKET3_HDRLEN */
122 * Not all compilers that are used to compile code to run on Linux have
123 * these builtins. For example, older versions of GCC don't, and at
124 * least some people are doing cross-builds for MIPS with older versions
127 #ifndef HAVE___ATOMIC_LOAD_N
128 #define __atomic_load_n(ptr, memory_model) (*(ptr))
130 #ifndef HAVE___ATOMIC_STORE_N
131 #define __atomic_store_n(ptr, val, memory_model) *(ptr) = (val)
134 #define packet_mmap_acquire(pkt) \
135 (__atomic_load_n(&pkt->tp_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
136 #define packet_mmap_release(pkt) \
137 (__atomic_store_n(&pkt->tp_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
138 #define packet_mmap_v3_acquire(pkt) \
139 (__atomic_load_n(&pkt->hdr.bh1.block_status, __ATOMIC_ACQUIRE) != TP_STATUS_KERNEL)
140 #define packet_mmap_v3_release(pkt) \
141 (__atomic_store_n(&pkt->hdr.bh1.block_status, TP_STATUS_KERNEL, __ATOMIC_RELEASE))
143 #include <linux/types.h>
144 #include <linux/filter.h>
146 #ifdef HAVE_LINUX_NET_TSTAMP_H
147 #include <linux/net_tstamp.h>
151 * For checking whether a device is a bonding device.
153 #include <linux/if_bonding.h>
159 #include <linux/nl80211.h>
161 #include <netlink/genl/genl.h>
162 #include <netlink/genl/family.h>
163 #include <netlink/genl/ctrl.h>
164 #include <netlink/msg.h>
165 #include <netlink/attr.h>
166 #endif /* HAVE_LIBNL */
168 #ifndef HAVE_SOCKLEN_T
169 typedef int socklen_t
;
172 #define MAX_LINKHEADER_SIZE 256
175 * When capturing on all interfaces we use this as the buffer size.
176 * Should be bigger then all MTUs that occur in real life.
177 * 64kB should be enough for now.
179 #define BIGGER_THAN_ALL_MTUS (64*1024)
182 * Private data for capturing on Linux PF_PACKET sockets.
185 long long sysfs_dropped
; /* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */
186 struct pcap_stat stat
;
188 char *device
; /* device name */
189 int filter_in_userland
; /* must filter in userland */
190 int blocks_to_filter_in_userland
;
191 int must_do_on_close
; /* stuff we must do when we close */
192 int timeout
; /* timeout for buffering */
193 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
194 int ifindex
; /* interface index of device we're bound to */
195 int lo_ifindex
; /* interface index of the loopback device */
196 int netdown
; /* we got an ENETDOWN and haven't resolved it */
197 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
198 char *mondevice
; /* mac80211 monitor device we created */
199 u_char
*mmapbuf
; /* memory-mapped region pointer */
200 size_t mmapbuflen
; /* size of region */
201 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
202 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
203 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
204 u_char
*oneshot_buffer
; /* buffer for copy of packet */
205 int poll_timeout
; /* timeout to use in poll() */
207 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
208 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
210 int poll_breakloop_fd
; /* fd to an eventfd to break from blocking operations */
214 * Stuff to do when we close.
216 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
217 #define MUST_DELETE_MONIF 0x00000002 /* delete monitor-mode interface */
220 * Prototypes for internal functions and methods.
222 static int get_if_flags(const char *, bpf_u_int32
*, char *);
223 static int is_wifi(const char *);
224 static void map_arphrd_to_dlt(pcap_t
*, int, const char *, int);
225 static int pcap_activate_linux(pcap_t
*);
226 static int setup_socket(pcap_t
*, int);
227 static int setup_mmapped(pcap_t
*, int *);
228 static int pcap_can_set_rfmon_linux(pcap_t
*);
229 static int pcap_inject_linux(pcap_t
*, const void *, int);
230 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
231 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
232 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
233 static int pcap_set_datalink_linux(pcap_t
*, int);
234 static void pcap_cleanup_linux(pcap_t
*);
237 struct tpacket2_hdr
*h2
;
239 struct tpacket_block_desc
*h3
;
244 #define RING_GET_FRAME_AT(h, offset) (((u_char **)h->buffer)[(offset)])
245 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
247 static void destroy_ring(pcap_t
*handle
);
248 static int create_ring(pcap_t
*handle
, int *status
);
249 static int prepare_tpacket_socket(pcap_t
*handle
);
250 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
252 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
254 static int pcap_setnonblock_linux(pcap_t
*p
, int nonblock
);
255 static int pcap_getnonblock_linux(pcap_t
*p
);
256 static void pcap_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
257 const u_char
*bytes
);
260 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
261 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
262 * or "on VLAN 0". There is no flag set in the tp_status field to
263 * distinguish between them.
265 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
266 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
267 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
268 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
270 * With a pre-3.0 kernel, we cannot distinguish between packets with no
271 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
272 * there's nothing we can do about that.
274 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
275 * continue the behavior of earlier libpcaps, wherein we treated packets
276 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
277 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
278 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
279 * VLAN tags. This does the right thing on 3.0 and later kernels, and
280 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
282 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
283 * has that value in 3.0 and later kernels.
285 #ifdef TP_STATUS_VLAN_VALID
286 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
289 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
290 * so we testwith the value it has in the 3.0 and later kernels, so
291 * we can test it if we're running on a system that has it. (If we're
292 * running on a system that doesn't have it, it won't be set in the
293 * tp_status field, so the tests of it will always fail; that means
294 * we behave the way we did before we introduced this macro.)
296 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
299 #ifdef TP_STATUS_VLAN_TPID_VALID
300 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
302 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
306 * Required select timeout if we're polling for an "interface disappeared"
307 * indication - 1 millisecond.
309 static const struct timeval netdown_timeout
= {
310 0, 1000 /* 1000 microseconds = 1 millisecond */
314 * Wrap some ioctl calls
316 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
317 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
318 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
319 static int iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
);
320 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
322 static int iface_get_ts_types(const char *device
, pcap_t
*handle
,
324 static int iface_get_offload(pcap_t
*handle
);
326 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
327 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
328 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
329 static int reset_kernel_filter(pcap_t
*handle
);
331 static struct sock_filter total_insn
332 = BPF_STMT(BPF_RET
| BPF_K
, 0);
333 static struct sock_fprog total_fcode
334 = { 1, &total_insn
};
336 static int iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
);
339 pcap_create_interface(const char *device
, char *ebuf
)
343 handle
= PCAP_CREATE_COMMON(ebuf
, struct pcap_linux
);
347 handle
->activate_op
= pcap_activate_linux
;
348 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
351 * See what time stamp types we support.
353 if (iface_get_ts_types(device
, handle
, ebuf
) == -1) {
359 * We claim that we support microsecond and nanosecond time
362 * XXX - with adapter-supplied time stamps, can we choose
363 * microsecond or nanosecond time stamps on arbitrary
366 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
367 if (handle
->tstamp_precision_list
== NULL
) {
368 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
373 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
374 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
375 handle
->tstamp_precision_count
= 2;
377 struct pcap_linux
*handlep
= handle
->priv
;
378 handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
);
385 * If interface {if_name} is a mac80211 driver, the file
386 * /sys/class/net/{if_name}/phy80211 is a symlink to
387 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
389 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
390 * least, has a "wmaster0" device and a "wlan0" device; the
391 * latter is the one with the IP address. Both show up in
392 * "tcpdump -D" output. Capturing on the wmaster0 device
393 * captures with 802.11 headers.
395 * airmon-ng searches through /sys/class/net for devices named
396 * monN, starting with mon0; as soon as one *doesn't* exist,
397 * it chooses that as the monitor device name. If the "iw"
398 * command exists, it does
400 * iw dev {if_name} interface add {monif_name} type monitor
402 * where {monif_name} is the monitor device. It then (sigh) sleeps
403 * .1 second, and then configures the device up. Otherwise, if
404 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
405 * {mondev_name}, without a newline, to that file, and again (sigh)
406 * sleeps .1 second, and then iwconfig's that device into monitor
407 * mode and configures it up. Otherwise, you can't do monitor mode.
409 * All these devices are "glued" together by having the
410 * /sys/class/net/{if_name}/phy80211 links pointing to the same
411 * place, so, given a wmaster, wlan, or mon device, you can
412 * find the other devices by looking for devices with
413 * the same phy80211 link.
415 * To turn monitor mode off, delete the monitor interface,
418 * iw dev {monif_name} interface del
420 * or by sending {monif_name}, with no NL, down
421 * /sys/class/ieee80211/{phydev_name}/remove_iface
423 * Note: if you try to create a monitor device named "monN", and
424 * there's already a "monN" device, it fails, as least with
425 * the netlink interface (which is what iw uses), with a return
426 * value of -ENFILE. (Return values are negative errnos.) We
427 * could probably use that to find an unused device.
429 * Yes, you can have multiple monitor devices for a given
434 * Is this a mac80211 device? If so, fill in the physical device path and
435 * return 1; if not, return 0. On an error, fill in handle->errbuf and
439 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
440 size_t phydev_max_pathlen
)
446 * Generate the path string for the symlink to the physical device.
448 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
449 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
450 "%s: Can't generate path name string for /sys/class/net device",
454 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
455 if (bytes_read
== -1) {
456 if (errno
== ENOENT
|| errno
== EINVAL
) {
458 * Doesn't exist, or not a symlink; assume that
459 * means it's not a mac80211 device.
464 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
465 errno
, "%s: Can't readlink %s", device
, pathstr
);
470 phydev_path
[bytes_read
] = '\0';
474 struct nl80211_state
{
475 struct nl_sock
*nl_sock
;
476 struct nl_cache
*nl_cache
;
477 struct genl_family
*nl80211
;
481 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
485 state
->nl_sock
= nl_socket_alloc();
486 if (!state
->nl_sock
) {
487 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
488 "%s: failed to allocate netlink handle", device
);
492 if (genl_connect(state
->nl_sock
)) {
493 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
494 "%s: failed to connect to generic netlink", device
);
495 goto out_handle_destroy
;
498 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
500 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
501 "%s: failed to allocate generic netlink cache: %s",
502 device
, nl_geterror(-err
));
503 goto out_handle_destroy
;
506 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
507 if (!state
->nl80211
) {
508 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
509 "%s: nl80211 not found", device
);
516 nl_cache_free(state
->nl_cache
);
518 nl_socket_free(state
->nl_sock
);
523 nl80211_cleanup(struct nl80211_state
*state
)
525 genl_family_put(state
->nl80211
);
526 nl_cache_free(state
->nl_cache
);
527 nl_socket_free(state
->nl_sock
);
531 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
532 const char *device
, const char *mondevice
);
535 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
536 const char *device
, const char *mondevice
)
538 struct pcap_linux
*handlep
= handle
->priv
;
543 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
549 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
550 "%s: failed to allocate netlink msg", device
);
554 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
555 0, NL80211_CMD_NEW_INTERFACE
, 0);
556 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
558 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
560 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
562 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
564 if (err
== -NLE_FAILURE
) {
566 * Device not available; our caller should just
567 * keep trying. (libnl 2.x maps ENFILE to
568 * NLE_FAILURE; it can also map other errors
569 * to that, but there's not much we can do
576 * Real failure, not just "that device is not
579 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
580 "%s: nl_send_auto_complete failed adding %s interface: %s",
581 device
, mondevice
, nl_geterror(-err
));
586 err
= nl_wait_for_ack(state
->nl_sock
);
588 if (err
== -NLE_FAILURE
) {
590 * Device not available; our caller should just
591 * keep trying. (libnl 2.x maps ENFILE to
592 * NLE_FAILURE; it can also map other errors
593 * to that, but there's not much we can do
600 * Real failure, not just "that device is not
603 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
604 "%s: nl_wait_for_ack failed adding %s interface: %s",
605 device
, mondevice
, nl_geterror(-err
));
617 * Try to remember the monitor device.
619 handlep
->mondevice
= strdup(mondevice
);
620 if (handlep
->mondevice
== NULL
) {
621 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
624 * Get rid of the monitor device.
626 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
632 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
633 "%s: nl_put failed adding %s interface",
640 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
641 const char *device
, const char *mondevice
)
647 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
653 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
654 "%s: failed to allocate netlink msg", device
);
658 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
659 0, NL80211_CMD_DEL_INTERFACE
, 0);
660 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
662 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
664 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
665 "%s: nl_send_auto_complete failed deleting %s interface: %s",
666 device
, mondevice
, nl_geterror(-err
));
670 err
= nl_wait_for_ack(state
->nl_sock
);
672 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
673 "%s: nl_wait_for_ack failed adding %s interface: %s",
674 device
, mondevice
, nl_geterror(-err
));
686 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
687 "%s: nl_put failed deleting %s interface",
692 #endif /* HAVE_LIBNL */
694 static int pcap_protocol(pcap_t
*handle
)
698 protocol
= handle
->opt
.protocol
;
700 protocol
= ETH_P_ALL
;
702 return htons(protocol
);
706 pcap_can_set_rfmon_linux(pcap_t
*handle
)
709 char phydev_path
[PATH_MAX
+1];
713 if (strcmp(handle
->opt
.device
, "any") == 0) {
715 * Monitor mode makes no sense on the "any" device.
722 * Bleah. There doesn't seem to be a way to ask a mac80211
723 * device, through libnl, whether it supports monitor mode;
724 * we'll just check whether the device appears to be a
725 * mac80211 device and, if so, assume the device supports
728 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
731 return ret
; /* error */
733 return 1; /* mac80211 device */
740 * Grabs the number of missed packets by the interface from
741 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
743 * Compared to /proc/net/dev this avoids counting software drops,
744 * but may be unimplemented and just return 0.
745 * The author has found no straigthforward way to check for support.
748 linux_get_stat(const char * if_name
, const char * stat
) {
751 char buffer
[PATH_MAX
];
753 snprintf(buffer
, sizeof(buffer
), "/sys/class/net/%s/statistics/%s", if_name
, stat
);
754 fd
= open(buffer
, O_RDONLY
);
758 bytes_read
= read(fd
, buffer
, sizeof(buffer
) - 1);
760 if (bytes_read
== -1)
762 buffer
[bytes_read
] = '\0';
764 return strtoll(buffer
, NULL
, 10);
768 linux_if_drops(const char * if_name
)
770 long long int missed
= linux_get_stat(if_name
, "rx_missed_errors");
771 long long int fifo
= linux_get_stat(if_name
, "rx_fifo_errors");
772 return missed
+ fifo
;
777 * Monitor mode is kind of interesting because we have to reset the
778 * interface before exiting. The problem can't really be solved without
779 * some daemon taking care of managing usage counts. If we put the
780 * interface into monitor mode, we set a flag indicating that we must
781 * take it out of that mode when the interface is closed, and, when
782 * closing the interface, if that flag is set we take it out of monitor
786 static void pcap_cleanup_linux( pcap_t
*handle
)
788 struct pcap_linux
*handlep
= handle
->priv
;
790 struct nl80211_state nlstate
;
792 #endif /* HAVE_LIBNL */
794 if (handlep
->must_do_on_close
!= 0) {
796 * There's something we have to do when closing this
800 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
801 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
803 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
804 handlep
->device
, handlep
->mondevice
);
805 nl80211_cleanup(&nlstate
);
809 "Can't delete monitor interface %s (%s).\n"
810 "Please delete manually.\n",
811 handlep
->mondevice
, handle
->errbuf
);
814 #endif /* HAVE_LIBNL */
817 * Take this pcap out of the list of pcaps for which we
818 * have to take the interface out of some mode.
820 pcap_remove_from_pcaps_to_close(handle
);
823 if (handle
->fd
!= -1) {
825 * Destroy the ring buffer (assuming we've set it up),
826 * and unmap it if it's mapped.
828 destroy_ring(handle
);
831 if (handlep
->oneshot_buffer
!= NULL
) {
832 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
833 handlep
->oneshot_buffer
= NULL
;
836 if (handlep
->mondevice
!= NULL
) {
837 free(handlep
->mondevice
);
838 handlep
->mondevice
= NULL
;
840 if (handlep
->device
!= NULL
) {
841 free(handlep
->device
);
842 handlep
->device
= NULL
;
845 if (handlep
->poll_breakloop_fd
!= -1) {
846 close(handlep
->poll_breakloop_fd
);
847 handlep
->poll_breakloop_fd
= -1;
849 pcap_cleanup_live_common(handle
);
854 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
855 * around which we have to work. Determine if we have those
857 * 3.19 is the first release with a fixed version of
858 * TPACKET_V3. We treat anything before that as
859 * not having a fixed version; that may really mean
860 * it has *no* version.
862 static int has_broken_tpacket_v3(void)
864 struct utsname utsname
;
869 /* No version information, assume broken. */
870 if (uname(&utsname
) == -1)
872 release
= utsname
.release
;
874 /* A malformed version, ditto. */
875 matches
= sscanf(release
, "%ld.%ld%n", &major
, &minor
, &verlen
);
878 if (release
[verlen
] != '.' && release
[verlen
] != '\0')
881 /* OK, a fixed version. */
882 if (major
> 3 || (major
== 3 && minor
>= 19))
891 * Set the timeout to be used in poll() with memory-mapped packet capture.
894 set_poll_timeout(struct pcap_linux
*handlep
)
897 int broken_tpacket_v3
= has_broken_tpacket_v3();
899 if (handlep
->timeout
== 0) {
902 * XXX - due to a set of (mis)features in the TPACKET_V3
903 * kernel code prior to the 3.19 kernel, blocking forever
904 * with a TPACKET_V3 socket can, if few packets are
905 * arriving and passing the socket filter, cause most
906 * packets to be dropped. See libpcap issue #335 for the
907 * full painful story.
909 * The workaround is to have poll() time out very quickly,
910 * so we grab the frames handed to us, and return them to
913 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
914 handlep
->poll_timeout
= 1; /* don't block for very long */
917 handlep
->poll_timeout
= -1; /* block forever */
918 } else if (handlep
->timeout
> 0) {
921 * For TPACKET_V3, the timeout is handled by the kernel,
922 * so block forever; that way, we don't get extra timeouts.
923 * Don't do that if we have a broken TPACKET_V3, though.
925 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
926 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
929 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
932 * Non-blocking mode; we call poll() to pick up error
933 * indications, but we don't want it to wait for
936 handlep
->poll_timeout
= 0;
940 static void pcap_breakloop_linux(pcap_t
*handle
)
942 pcap_breakloop_common(handle
);
943 struct pcap_linux
*handlep
= handle
->priv
;
946 /* XXX - what if this fails? */
947 if (handlep
->poll_breakloop_fd
!= -1)
948 (void)write(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
952 * Set the offset at which to insert VLAN tags.
953 * That should be the offset of the type field.
956 set_vlan_offset(pcap_t
*handle
)
958 struct pcap_linux
*handlep
= handle
->priv
;
960 switch (handle
->linktype
) {
964 * The type field is after the destination and source
967 handlep
->vlan_offset
= 2 * ETH_ALEN
;
972 * The type field is in the last 2 bytes of the
973 * DLT_LINUX_SLL header.
975 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
979 handlep
->vlan_offset
= -1; /* unknown */
985 * Get a handle for a live capture from the given device. You can
986 * pass NULL as device to get all packages (without link level
987 * information of course). If you pass 1 as promisc the interface
988 * will be set to promiscuous mode (XXX: I think this usage should
989 * be deprecated and functions be added to select that later allow
990 * modification of that values -- Torsten).
993 pcap_activate_linux(pcap_t
*handle
)
995 struct pcap_linux
*handlep
= handle
->priv
;
1003 device
= handle
->opt
.device
;
1006 * Make sure the name we were handed will fit into the ioctls we
1007 * might perform on the device; if not, return a "No such device"
1008 * indication, as the Linux kernel shouldn't support creating
1009 * a device whose name won't fit into those ioctls.
1011 * "Will fit" means "will fit, complete with a null terminator",
1012 * so if the length, which does *not* include the null terminator,
1013 * is greater than *or equal to* the size of the field into which
1014 * we'll be copying it, that won't fit.
1016 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1018 * There's nothing more to say, so clear the error
1021 handle
->errbuf
[0] = '\0';
1022 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1027 * Turn a negative snapshot value (invalid), a snapshot value of
1028 * 0 (unspecified), or a value bigger than the normal maximum
1029 * value, into the maximum allowed value.
1031 * If some application really *needs* a bigger snapshot
1032 * length, we should just increase MAXIMUM_SNAPLEN.
1034 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
1035 handle
->snapshot
= MAXIMUM_SNAPLEN
;
1037 handlep
->device
= strdup(device
);
1038 if (handlep
->device
== NULL
) {
1039 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1041 status
= PCAP_ERROR
;
1046 * The "any" device is a special device which causes us not
1047 * to bind to a particular device and thus to look at all
1050 is_any_device
= (strcmp(device
, "any") == 0);
1051 if (is_any_device
) {
1052 if (handle
->opt
.promisc
) {
1053 handle
->opt
.promisc
= 0;
1054 /* Just a warning. */
1055 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1056 "Promiscuous mode not supported on the \"any\" device");
1057 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1061 /* copy timeout value */
1062 handlep
->timeout
= handle
->opt
.timeout
;
1065 * If we're in promiscuous mode, then we probably want
1066 * to see when the interface drops packets too, so get an
1067 * initial count from
1068 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1070 if (handle
->opt
.promisc
)
1071 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1074 * If the "any" device is specified, try to open a SOCK_DGRAM.
1075 * Otherwise, open a SOCK_RAW.
1077 ret
= setup_socket(handle
, is_any_device
);
1080 * Fatal error; the return value is the error code,
1081 * and handle->errbuf has been set to an appropriate
1089 * Try to set up memory-mapped access.
1091 ret
= setup_mmapped(handle
, &status
);
1094 * We failed to set up to use it, or the
1095 * kernel supports it, but we failed to
1096 * enable it. status has been set to the
1097 * error status to return and, if it's
1098 * PCAP_ERROR, handle->errbuf contains
1099 * the error message.
1105 * We succeeded. status has been set to the status to return,
1106 * which might be 0, or might be a PCAP_WARNING_ value.
1109 * Now that we have activated the mmap ring, we can
1110 * set the correct protocol.
1112 if ((status2
= iface_bind(handle
->fd
, handlep
->ifindex
,
1113 handle
->errbuf
, pcap_protocol(handle
))) != 0) {
1118 handle
->inject_op
= pcap_inject_linux
;
1119 handle
->setfilter_op
= pcap_setfilter_linux
;
1120 handle
->setdirection_op
= pcap_setdirection_linux
;
1121 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1122 handle
->setnonblock_op
= pcap_setnonblock_linux
;
1123 handle
->getnonblock_op
= pcap_getnonblock_linux
;
1124 handle
->cleanup_op
= pcap_cleanup_linux
;
1125 handle
->stats_op
= pcap_stats_linux
;
1126 handle
->breakloop_op
= pcap_breakloop_linux
;
1128 switch (handlep
->tp_version
) {
1131 handle
->read_op
= pcap_read_linux_mmap_v2
;
1133 #ifdef HAVE_TPACKET3
1135 handle
->read_op
= pcap_read_linux_mmap_v3
;
1139 handle
->oneshot_callback
= pcap_oneshot_linux
;
1140 handle
->selectable_fd
= handle
->fd
;
1145 pcap_cleanup_linux(handle
);
1150 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1152 handle
->linktype
= dlt
;
1155 * Update the offset at which to insert VLAN tags for the
1156 * new link-layer type.
1158 set_vlan_offset(handle
);
1164 * linux_check_direction()
1166 * Do checks based on packet direction.
1169 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1171 struct pcap_linux
*handlep
= handle
->priv
;
1173 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1176 * If this is from the loopback device, reject it;
1177 * we'll see the packet as an incoming packet as well,
1178 * and we don't want to see it twice.
1180 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1184 * If this is an outgoing CAN or CAN FD frame, and
1185 * the user doesn't only want outgoing packets,
1186 * reject it; CAN devices and drivers, and the CAN
1187 * stack, always arrange to loop back transmitted
1188 * packets, so they also appear as incoming packets.
1189 * We don't want duplicate packets, and we can't
1190 * easily distinguish packets looped back by the CAN
1191 * layer than those received by the CAN layer, so we
1192 * eliminate this packet instead.
1194 * We check whether this is a CAN or CAN FD frame
1195 * by checking whether the device's hardware type
1198 if (sll
->sll_hatype
== ARPHRD_CAN
&&
1199 handle
->direction
!= PCAP_D_OUT
)
1203 * If the user only wants incoming packets, reject it.
1205 if (handle
->direction
== PCAP_D_IN
)
1210 * If the user only wants outgoing packets, reject it.
1212 if (handle
->direction
== PCAP_D_OUT
)
1219 * Check whether the device to which the pcap_t is bound still exists.
1220 * We do so by asking what address the socket is bound to, and checking
1221 * whether the ifindex in the address is -1, meaning "that device is gone",
1222 * or some other value, meaning "that device still exists".
1225 device_still_exists(pcap_t
*handle
)
1227 struct pcap_linux
*handlep
= handle
->priv
;
1228 struct sockaddr_ll addr
;
1232 * If handlep->ifindex is -1, the socket isn't bound, meaning
1233 * we're capturing on the "any" device; that device never
1234 * disappears. (It should also never be configured down, so
1235 * we shouldn't even get here, but let's make sure.)
1237 if (handlep
->ifindex
== -1)
1238 return (1); /* it's still here */
1241 * OK, now try to get the address for the socket.
1243 addr_len
= sizeof (addr
);
1244 if (getsockname(handle
->fd
, (struct sockaddr
*) &addr
, &addr_len
) == -1) {
1246 * Error - report an error and return -1.
1248 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1249 errno
, "getsockname failed");
1252 if (addr
.sll_ifindex
== -1) {
1254 * This means the device went away.
1260 * The device presumably just went down.
1266 pcap_inject_linux(pcap_t
*handle
, const void *buf
, int size
)
1268 struct pcap_linux
*handlep
= handle
->priv
;
1271 if (handlep
->ifindex
== -1) {
1273 * We don't support sending on the "any" device.
1275 pcap_strlcpy(handle
->errbuf
,
1276 "Sending packets isn't supported on the \"any\" device",
1281 if (handlep
->cooked
) {
1283 * We don't support sending on cooked-mode sockets.
1285 * XXX - how do you send on a bound cooked-mode
1287 * Is a "sendto()" required there?
1289 pcap_strlcpy(handle
->errbuf
,
1290 "Sending packets isn't supported in cooked mode",
1295 ret
= (int)send(handle
->fd
, buf
, size
, 0);
1297 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1305 * Get the statistics for the given packet capture handle.
1308 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1310 struct pcap_linux
*handlep
= handle
->priv
;
1311 #ifdef HAVE_TPACKET3
1313 * For sockets using TPACKET_V2, the extra stuff at the end
1314 * of a struct tpacket_stats_v3 will not be filled in, and
1315 * we don't look at it so this is OK even for those sockets.
1316 * In addition, the PF_PACKET socket code in the kernel only
1317 * uses the length parameter to compute how much data to
1318 * copy out and to indicate how much data was copied out, so
1319 * it's OK to base it on the size of a struct tpacket_stats.
1321 * XXX - it's probably OK, in fact, to just use a
1322 * struct tpacket_stats for V3 sockets, as we don't
1323 * care about the tp_freeze_q_cnt stat.
1325 struct tpacket_stats_v3 kstats
;
1326 #else /* HAVE_TPACKET3 */
1327 struct tpacket_stats kstats
;
1328 #endif /* HAVE_TPACKET3 */
1329 socklen_t len
= sizeof (struct tpacket_stats
);
1331 long long if_dropped
= 0;
1334 * To fill in ps_ifdrop, we parse
1335 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1338 if (handle
->opt
.promisc
)
1341 * XXX - is there any reason to do this by remembering
1342 * the last counts value, subtracting it from the
1343 * current counts value, and adding that to stat.ps_ifdrop,
1344 * maintaining stat.ps_ifdrop as a count, rather than just
1345 * saving the *initial* counts value and setting
1346 * stat.ps_ifdrop to the difference between the current
1347 * value and the initial value?
1349 * One reason might be to handle the count wrapping
1350 * around, on platforms where the count is 32 bits
1351 * and where you might get more than 2^32 dropped
1352 * packets; is there any other reason?
1354 * (We maintain the count as a long long int so that,
1355 * if the kernel maintains the counts as 64-bit even
1356 * on 32-bit platforms, we can handle the real count.
1358 * Unfortunately, we can't report 64-bit counts; we
1359 * need a better API for reporting statistics, such as
1360 * one that reports them in a style similar to the
1361 * pcapng Interface Statistics Block, so that 1) the
1362 * counts are 64-bit, 2) it's easier to add new statistics
1363 * without breaking the ABI, and 3) it's easier to
1364 * indicate to a caller that wants one particular
1365 * statistic that it's not available by just not supplying
1368 if_dropped
= handlep
->sysfs_dropped
;
1369 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1370 handlep
->stat
.ps_ifdrop
+= (u_int
)(handlep
->sysfs_dropped
- if_dropped
);
1374 * Try to get the packet counts from the kernel.
1376 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1377 &kstats
, &len
) > -1) {
1379 * "ps_recv" counts only packets that *passed* the
1380 * filter, not packets that didn't pass the filter.
1381 * This includes packets later dropped because we
1382 * ran out of buffer space.
1384 * "ps_drop" counts packets dropped because we ran
1385 * out of buffer space. It doesn't count packets
1386 * dropped by the interface driver. It counts only
1387 * packets that passed the filter.
1389 * See above for ps_ifdrop.
1391 * Both statistics include packets not yet read from
1392 * the kernel by libpcap, and thus not yet seen by
1395 * In "linux/net/packet/af_packet.c", at least in 2.6.27
1396 * through 5.6 kernels, "tp_packets" is incremented for
1397 * every packet that passes the packet filter *and* is
1398 * successfully copied to the ring buffer; "tp_drops" is
1399 * incremented for every packet dropped because there's
1400 * not enough free space in the ring buffer.
1402 * When the statistics are returned for a PACKET_STATISTICS
1403 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1404 * so that "tp_packets" counts all packets handed to
1405 * the PF_PACKET socket, including packets dropped because
1406 * there wasn't room on the socket buffer - but not
1407 * including packets that didn't pass the filter.
1409 * In the BSD BPF, the count of received packets is
1410 * incremented for every packet handed to BPF, regardless
1411 * of whether it passed the filter.
1413 * We can't make "pcap_stats()" work the same on both
1414 * platforms, but the best approximation is to return
1415 * "tp_packets" as the count of packets and "tp_drops"
1416 * as the count of drops.
1418 * Keep a running total because each call to
1419 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1420 * resets the counters to zero.
1422 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1423 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1424 *stats
= handlep
->stat
;
1428 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1429 "failed to get statistics from socket");
1434 * Description string for the "any" device.
1436 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1439 * A PF_PACKET socket can be bound to any network interface.
1442 can_be_bound(const char *name _U_
)
1448 * Get a socket to use with various interface ioctls.
1451 get_if_ioctl_socket(void)
1456 * This is a bit ugly.
1458 * There isn't a socket type that's guaranteed to work.
1460 * AF_NETLINK will work *if* you have Netlink configured into the
1461 * kernel (can it be configured out if you have any networking
1462 * support at all?) *and* if you're running a sufficiently recent
1463 * kernel, but not all the kernels we support are sufficiently
1464 * recent - that feature was introduced in Linux 4.6.
1466 * AF_UNIX will work *if* you have UNIX-domain sockets configured
1467 * into the kernel and *if* you're not on a system that doesn't
1468 * allow them - some SELinux systems don't allow you create them.
1469 * Most systems probably have them configured in, but not all systems
1470 * have them configured in and allow them to be created.
1472 * AF_INET will work *if* you have IPv4 configured into the kernel,
1473 * but, apparently, some systems have network adapters but have
1474 * kernels without IPv4 support.
1476 * AF_INET6 will work *if* you have IPv6 configured into the
1477 * kernel, but if you don't have AF_INET, you might not have
1478 * AF_INET6, either (that is, independently on its own grounds).
1480 * AF_PACKET would work, except that some of these calls should
1481 * work even if you *don't* have capture permission (you should be
1482 * able to enumerate interfaces and get information about them
1483 * without capture permission; you shouldn't get a failure until
1484 * you try pcap_activate()). (If you don't allow programs to
1485 * get as much information as possible about interfaces if you
1486 * don't have permission to capture, you run the risk of users
1487 * asking "why isn't it showing XXX" - or, worse, if you don't
1488 * show interfaces *at all* if you don't have permission to
1489 * capture on them, "why do no interfaces show up?" - when the
1490 * real problem is a permissions problem. Error reports of that
1491 * type require a lot more back-and-forth to debug, as evidenced
1492 * by many Wireshark bugs/mailing list questions/Q&A questions.)
1496 * we first try an AF_NETLINK socket, where "try" includes
1497 * "try to do a device ioctl on it", as, in the future, once
1498 * pre-4.6 kernels are sufficiently rare, that will probably
1499 * be the mechanism most likely to work;
1501 * if that fails, we try an AF_UNIX socket, as that's less
1502 * likely to be configured out on a networking-capable system
1505 * if that fails, we try an AF_INET6 socket;
1507 * if that fails, we try an AF_INET socket.
1509 fd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_GENERIC
);
1512 * OK, let's make sure we can do an SIOCGIFNAME
1517 memset(&ifr
, 0, sizeof(ifr
));
1518 if (ioctl(fd
, SIOCGIFNAME
, &ifr
) == 0 ||
1519 errno
!= EOPNOTSUPP
) {
1521 * It succeeded, or failed for some reason
1522 * other than "netlink sockets don't support
1523 * device ioctls". Go with the AF_NETLINK
1530 * OK, that didn't work, so it's as bad as "netlink
1531 * sockets aren't available". Close the socket and
1538 * Now try an AF_UNIX socket.
1540 fd
= socket(AF_UNIX
, SOCK_RAW
, 0);
1549 * Now try an AF_INET6 socket.
1551 fd
= socket(AF_INET6
, SOCK_DGRAM
, 0);
1557 * Now try an AF_INET socket.
1559 * XXX - if that fails, is there anything else we should try?
1560 * AF_CAN, for embedded systems in vehicles, in case they're
1561 * built without Internet protocol support? Any other socket
1562 * types popular in non-Internet embedded systems?
1564 return (socket(AF_INET
, SOCK_DGRAM
, 0));
1568 * Get additional flags for a device, using SIOCGIFMEDIA.
1571 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1575 unsigned int arptype
;
1577 struct ethtool_value info
;
1579 if (*flags
& PCAP_IF_LOOPBACK
) {
1581 * Loopback devices aren't wireless, and "connected"/
1582 * "disconnected" doesn't apply to them.
1584 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1588 sock
= get_if_ioctl_socket();
1590 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1591 "Can't create socket to get ethtool information for %s",
1597 * OK, what type of network is this?
1598 * In particular, is it wired or wireless?
1600 if (is_wifi(name
)) {
1602 * Wi-Fi, hence wireless.
1604 *flags
|= PCAP_IF_WIRELESS
;
1607 * OK, what does /sys/class/net/{if_name}/type contain?
1608 * (We don't use that for Wi-Fi, as it'll report
1609 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
1614 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
1615 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1616 "%s: Can't generate path name string for /sys/class/net device",
1621 fh
= fopen(pathstr
, "r");
1623 if (fscanf(fh
, "%u", &arptype
) == 1) {
1625 * OK, we got an ARPHRD_ type; what is it?
1629 case ARPHRD_LOOPBACK
:
1631 * These are types to which
1632 * "connected" and "disconnected"
1633 * don't apply, so don't bother
1636 * XXX - add other types?
1644 case ARPHRD_IEEE80211
:
1645 case ARPHRD_IEEE80211_PRISM
:
1646 case ARPHRD_IEEE80211_RADIOTAP
:
1647 #ifdef ARPHRD_IEEE802154
1648 case ARPHRD_IEEE802154
:
1650 #ifdef ARPHRD_IEEE802154_MONITOR
1651 case ARPHRD_IEEE802154_MONITOR
:
1653 #ifdef ARPHRD_6LOWPAN
1654 case ARPHRD_6LOWPAN
:
1657 * Various wireless types.
1659 *flags
|= PCAP_IF_WIRELESS
;
1668 #ifdef ETHTOOL_GLINK
1669 memset(&ifr
, 0, sizeof(ifr
));
1670 pcap_strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
1671 info
.cmd
= ETHTOOL_GLINK
;
1673 * XXX - while Valgrind handles SIOCETHTOOL and knows that
1674 * the ETHTOOL_GLINK command sets the .data member of the
1675 * structure, Memory Sanitizer doesn't yet do so:
1677 * https://bugs.llvm.org/show_bug.cgi?id=45814
1679 * For now, we zero it out to squelch warnings; if the bug
1680 * in question is fixed, we can remove this.
1683 ifr
.ifr_data
= (caddr_t
)&info
;
1684 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
1685 int save_errno
= errno
;
1687 switch (save_errno
) {
1692 * OK, this OS version or driver doesn't support
1693 * asking for this information.
1694 * XXX - distinguish between "this doesn't
1695 * support ethtool at all because it's not
1696 * that type of device" vs. "this doesn't
1697 * support ethtool even though it's that
1698 * type of device", and return "unknown".
1700 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1706 * OK, no such device.
1707 * The user will find that out when they try to
1708 * activate the device; just say "OK" and
1709 * don't set anything.
1718 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1720 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
1734 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1737 * It's disconnected.
1739 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1748 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1751 * Get the list of regular interfaces first.
1753 if (pcap_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
1754 get_if_flags
) == -1)
1755 return (-1); /* failure */
1758 * Add the "any" device.
1759 * As it refers to all network devices, not to any particular
1760 * network device, the notion of "connected" vs. "disconnected"
1763 if (pcap_add_dev(devlistp
, "any",
1764 PCAP_IF_UP
|PCAP_IF_RUNNING
|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
1765 any_descr
, errbuf
) == NULL
)
1772 * Set direction flag: Which packets do we accept on a forwarding
1773 * single device? IN, OUT or both?
1776 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1779 * It's guaranteed, at this point, that d is a valid
1782 handle
->direction
= d
;
1787 is_wifi(const char *device
)
1793 * See if there's a sysfs wireless directory for it.
1794 * If so, it's a wireless interface.
1796 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
1798 * Just give up here.
1802 if (stat(pathstr
, &statb
) == 0) {
1812 * Linux uses the ARP hardware type to identify the type of an
1813 * interface. pcap uses the DLT_xxx constants for this. This
1814 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1815 * constant, as arguments, and sets "handle->linktype" to the
1816 * appropriate DLT_XXX constant and sets "handle->offset" to
1817 * the appropriate value (to make "handle->offset" plus link-layer
1818 * header length be a multiple of 4, so that the link-layer payload
1819 * will be aligned on a 4-byte boundary when capturing packets).
1820 * (If the offset isn't set here, it'll be 0; add code as appropriate
1821 * for cases where it shouldn't be 0.)
1823 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1824 * in cooked mode; otherwise, we can't use cooked mode, so we have
1825 * to pick some type that works in raw mode, or fail.
1827 * Sets the link type to -1 if unable to map the type.
1829 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
,
1830 const char *device
, int cooked_ok
)
1832 static const char cdma_rmnet
[] = "cdma_rmnet";
1838 * For various annoying reasons having to do with DHCP
1839 * software, some versions of Android give the mobile-
1840 * phone-network interface an ARPHRD_ value of
1841 * ARPHRD_ETHER, even though the packets supplied by
1842 * that interface have no link-layer header, and begin
1843 * with an IP header, so that the ARPHRD_ value should
1846 * Detect those devices by checking the device name, and
1847 * use DLT_RAW for them.
1849 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
1850 handle
->linktype
= DLT_RAW
;
1855 * Is this a real Ethernet device? If so, give it a
1856 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1857 * that an application can let you choose it, in case you're
1858 * capturing DOCSIS traffic that a Cisco Cable Modem
1859 * Termination System is putting out onto an Ethernet (it
1860 * doesn't put an Ethernet header onto the wire, it puts raw
1861 * DOCSIS frames out on the wire inside the low-level
1862 * Ethernet framing).
1864 * XXX - are there any other sorts of "fake Ethernet" that
1865 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
1866 * a Cisco CMTS won't put traffic onto it or get traffic
1867 * bridged onto it? ISDN is handled in "setup_socket()",
1868 * as we fall back on cooked mode there, and we use
1869 * is_wifi() to check for 802.11 devices; are there any
1872 if (!is_wifi(device
)) {
1876 * This is not a Wi-Fi device but it could be
1877 * a DSA master/management network device.
1879 ret
= iface_dsa_get_proto_info(device
, handle
);
1885 * This is a DSA master/management network
1886 * device linktype is already set by
1887 * iface_dsa_get_proto_info() set an
1888 * appropriate offset here.
1895 * It's not a Wi-Fi device; offer DOCSIS.
1897 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1899 * If that fails, just leave the list empty.
1901 if (handle
->dlt_list
!= NULL
) {
1902 handle
->dlt_list
[0] = DLT_EN10MB
;
1903 handle
->dlt_list
[1] = DLT_DOCSIS
;
1904 handle
->dlt_count
= 2;
1909 case ARPHRD_METRICOM
:
1910 case ARPHRD_LOOPBACK
:
1911 handle
->linktype
= DLT_EN10MB
;
1916 handle
->linktype
= DLT_EN3MB
;
1920 handle
->linktype
= DLT_AX25_KISS
;
1924 handle
->linktype
= DLT_PRONET
;
1928 handle
->linktype
= DLT_CHAOS
;
1931 #define ARPHRD_CAN 280
1934 handle
->linktype
= DLT_CAN_SOCKETCAN
;
1937 #ifndef ARPHRD_IEEE802_TR
1938 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1940 case ARPHRD_IEEE802_TR
:
1941 case ARPHRD_IEEE802
:
1942 handle
->linktype
= DLT_IEEE802
;
1947 handle
->linktype
= DLT_ARCNET_LINUX
;
1950 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1951 #define ARPHRD_FDDI 774
1954 handle
->linktype
= DLT_FDDI
;
1958 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1959 #define ARPHRD_ATM 19
1963 * The Classical IP implementation in ATM for Linux
1964 * supports both what RFC 1483 calls "LLC Encapsulation",
1965 * in which each packet has an LLC header, possibly
1966 * with a SNAP header as well, prepended to it, and
1967 * what RFC 1483 calls "VC Based Multiplexing", in which
1968 * different virtual circuits carry different network
1969 * layer protocols, and no header is prepended to packets.
1971 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1972 * you can't use the ARPHRD_ type to find out whether
1973 * captured packets will have an LLC header, and,
1974 * while there's a socket ioctl to *set* the encapsulation
1975 * type, there's no ioctl to *get* the encapsulation type.
1979 * programs that dissect Linux Classical IP frames
1980 * would have to check for an LLC header and,
1981 * depending on whether they see one or not, dissect
1982 * the frame as LLC-encapsulated or as raw IP (I
1983 * don't know whether there's any traffic other than
1984 * IP that would show up on the socket, or whether
1985 * there's any support for IPv6 in the Linux
1986 * Classical IP code);
1988 * filter expressions would have to compile into
1989 * code that checks for an LLC header and does
1992 * Both of those are a nuisance - and, at least on systems
1993 * that support PF_PACKET sockets, we don't have to put
1994 * up with those nuisances; instead, we can just capture
1995 * in cooked mode. That's what we'll do, if we can.
1996 * Otherwise, we'll just fail.
1999 handle
->linktype
= DLT_LINUX_SLL
;
2001 handle
->linktype
= -1;
2004 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2005 #define ARPHRD_IEEE80211 801
2007 case ARPHRD_IEEE80211
:
2008 handle
->linktype
= DLT_IEEE802_11
;
2011 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2012 #define ARPHRD_IEEE80211_PRISM 802
2014 case ARPHRD_IEEE80211_PRISM
:
2015 handle
->linktype
= DLT_PRISM_HEADER
;
2018 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2019 #define ARPHRD_IEEE80211_RADIOTAP 803
2021 case ARPHRD_IEEE80211_RADIOTAP
:
2022 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2027 * Some PPP code in the kernel supplies no link-layer
2028 * header whatsoever to PF_PACKET sockets; other PPP
2029 * code supplies PPP link-layer headers ("syncppp.c");
2030 * some PPP code might supply random link-layer
2031 * headers (PPP over ISDN - there's code in Ethereal,
2032 * for example, to cope with PPP-over-ISDN captures
2033 * with which the Ethereal developers have had to cope,
2034 * heuristically trying to determine which of the
2035 * oddball link-layer headers particular packets have).
2037 * As such, we just punt, and run all PPP interfaces
2038 * in cooked mode, if we can; otherwise, we just treat
2039 * it as DLT_RAW, for now - if somebody needs to capture,
2040 * on a 2.0[.x] kernel, on PPP devices that supply a
2041 * link-layer header, they'll have to add code here to
2042 * map to the appropriate DLT_ type (possibly adding a
2043 * new DLT_ type, if necessary).
2046 handle
->linktype
= DLT_LINUX_SLL
;
2049 * XXX - handle ISDN types here? We can't fall
2050 * back on cooked sockets, so we'd have to
2051 * figure out from the device name what type of
2052 * link-layer encapsulation it's using, and map
2053 * that to an appropriate DLT_ value, meaning
2054 * we'd map "isdnN" devices to DLT_RAW (they
2055 * supply raw IP packets with no link-layer
2056 * header) and "isdY" devices to a new DLT_I4L_IP
2057 * type that has only an Ethernet packet type as
2058 * a link-layer header.
2060 * But sometimes we seem to get random crap
2061 * in the link-layer header when capturing on
2064 handle
->linktype
= DLT_RAW
;
2068 #ifndef ARPHRD_CISCO
2069 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2072 handle
->linktype
= DLT_C_HDLC
;
2075 /* Not sure if this is correct for all tunnels, but it
2079 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2087 #ifndef ARPHRD_RAWHDLC
2088 #define ARPHRD_RAWHDLC 518
2090 case ARPHRD_RAWHDLC
:
2092 #define ARPHRD_DLCI 15
2096 * XXX - should some of those be mapped to DLT_LINUX_SLL
2097 * instead? Should we just map all of them to DLT_LINUX_SLL?
2099 handle
->linktype
= DLT_RAW
;
2103 #define ARPHRD_FRAD 770
2106 handle
->linktype
= DLT_FRELAY
;
2109 case ARPHRD_LOCALTLK
:
2110 handle
->linktype
= DLT_LTALK
;
2115 * RFC 4338 defines an encapsulation for IP and ARP
2116 * packets that's compatible with the RFC 2625
2117 * encapsulation, but that uses a different ARP
2118 * hardware type and hardware addresses. That
2119 * ARP hardware type is 18; Linux doesn't define
2120 * any ARPHRD_ value as 18, but if it ever officially
2121 * supports RFC 4338-style IP-over-FC, it should define
2124 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2125 * that this will encourage its use in the future,
2126 * should Linux ever officially support RFC 4338-style
2129 handle
->linktype
= DLT_IP_OVER_FC
;
2133 #define ARPHRD_FCPP 784
2137 #define ARPHRD_FCAL 785
2141 #define ARPHRD_FCPL 786
2144 #ifndef ARPHRD_FCFABRIC
2145 #define ARPHRD_FCFABRIC 787
2147 case ARPHRD_FCFABRIC
:
2149 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2152 * https://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2154 * and one was assigned.
2156 * In a later private discussion (spun off from a message
2157 * on the ethereal-users list) on how to get that DLT_
2158 * value in libpcap on Linux, I ended up deciding that
2159 * the best thing to do would be to have him tweak the
2160 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2161 * type, and map all those types to DLT_IP_OVER_FC:
2163 * I've checked into the libpcap and tcpdump CVS tree
2164 * support for DLT_IP_OVER_FC. In order to use that,
2165 * you'd have to modify your modified driver to return
2166 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2167 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2168 * example (the exact value doesn't matter, it can be
2169 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2172 * 11 years later, Christian Svensson wanted to map
2173 * various ARPHRD_ values to DLT_FC_2 and
2174 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2177 * https://github.com/mcr/libpcap/pull/29
2179 * There doesn't seem to be any network drivers that uses
2180 * any of the ARPHRD_FC* values for IP-over-FC, and
2181 * it's not exactly clear what the "Dummy types for non
2182 * ARP hardware" are supposed to mean (link-layer
2183 * header type? Physical network type?), so it's
2184 * not exactly clear why the ARPHRD_FC* types exist
2185 * in the first place.
2187 * For now, we map them to DLT_FC_2, and provide an
2188 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2189 * DLT_IP_OVER_FC just in case there's some old
2190 * driver out there that uses one of those types for
2191 * IP-over-FC on which somebody wants to capture
2194 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
2196 * If that fails, just leave the list empty.
2198 if (handle
->dlt_list
!= NULL
) {
2199 handle
->dlt_list
[0] = DLT_FC_2
;
2200 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2201 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2202 handle
->dlt_count
= 3;
2204 handle
->linktype
= DLT_FC_2
;
2208 #define ARPHRD_IRDA 783
2211 /* Don't expect IP packet out of this interfaces... */
2212 handle
->linktype
= DLT_LINUX_IRDA
;
2213 /* We need to save packet direction for IrDA decoding,
2214 * so let's use "Linux-cooked" mode. Jean II
2216 * XXX - this is handled in setup_socket(). */
2217 /* handlep->cooked = 1; */
2220 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2221 * is needed, please report it to <daniele@orlandi.com> */
2223 #define ARPHRD_LAPD 8445
2226 /* Don't expect IP packet out of this interfaces... */
2227 handle
->linktype
= DLT_LINUX_LAPD
;
2231 #define ARPHRD_NONE 0xFFFE
2235 * No link-layer header; packets are just IP
2236 * packets, so use DLT_RAW.
2238 handle
->linktype
= DLT_RAW
;
2241 #ifndef ARPHRD_IEEE802154
2242 #define ARPHRD_IEEE802154 804
2244 case ARPHRD_IEEE802154
:
2245 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2248 #ifndef ARPHRD_NETLINK
2249 #define ARPHRD_NETLINK 824
2251 case ARPHRD_NETLINK
:
2252 handle
->linktype
= DLT_NETLINK
;
2254 * We need to use cooked mode, so that in sll_protocol we
2255 * pick up the netlink protocol type such as NETLINK_ROUTE,
2256 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2258 * XXX - this is handled in setup_socket().
2260 /* handlep->cooked = 1; */
2263 #ifndef ARPHRD_VSOCKMON
2264 #define ARPHRD_VSOCKMON 826
2266 case ARPHRD_VSOCKMON
:
2267 handle
->linktype
= DLT_VSOCK
;
2271 handle
->linktype
= -1;
2277 set_dlt_list_cooked(pcap_t
*handle
)
2280 * Support both DLT_LINUX_SLL and DLT_LINUX_SLL2.
2282 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2285 * If that failed, just leave the list empty.
2287 if (handle
->dlt_list
!= NULL
) {
2288 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
2289 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
2290 handle
->dlt_count
= 2;
2295 * Try to set up a PF_PACKET socket.
2296 * Returns 0 on success and a PCAP_ERROR_ value on failure.
2299 setup_socket(pcap_t
*handle
, int is_any_device
)
2301 struct pcap_linux
*handlep
= handle
->priv
;
2302 const char *device
= handle
->opt
.device
;
2304 int sock_fd
, arptype
;
2307 struct packet_mreq mr
;
2308 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2310 socklen_t len
= sizeof(bpf_extensions
);
2314 * Open a socket with protocol family packet. If cooked is true,
2315 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
2316 * we open a SOCK_RAW socket for the raw interface.
2318 * The protocol is set to 0. This means we will receive no
2319 * packets until we "bind" the socket with a non-zero
2320 * protocol. This allows us to setup the ring buffers without
2321 * dropping any packets.
2323 sock_fd
= is_any_device
?
2324 socket(PF_PACKET
, SOCK_DGRAM
, 0) :
2325 socket(PF_PACKET
, SOCK_RAW
, 0);
2327 if (sock_fd
== -1) {
2328 if (errno
== EPERM
|| errno
== EACCES
) {
2330 * You don't have permission to open the
2333 status
= PCAP_ERROR_PERM_DENIED
;
2334 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2335 "Attempt to create packet socket failed - CAP_NET_RAW may be required");
2340 status
= PCAP_ERROR
;
2342 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2348 * Get the interface index of the loopback device.
2349 * If the attempt fails, don't fail, just set the
2350 * "handlep->lo_ifindex" to -1.
2352 * XXX - can there be more than one device that loops
2353 * packets back, i.e. devices other than "lo"? If so,
2354 * we'd need to find them all, and have an array of
2355 * indices for them, and check all of them in
2356 * "pcap_read_packet()".
2358 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2361 * Default value for offset to align link-layer payload
2362 * on a 4-byte boundary.
2367 * What kind of frames do we have to deal with? Fall back
2368 * to cooked mode if we have an unknown interface type
2369 * or a type we know doesn't work well in raw mode.
2371 if (!is_any_device
) {
2372 /* Assume for now we don't need cooked mode. */
2373 handlep
->cooked
= 0;
2375 if (handle
->opt
.rfmon
) {
2377 * We were asked to turn on monitor mode.
2378 * Do so before we get the link-layer type,
2379 * because entering monitor mode could change
2380 * the link-layer type.
2382 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2390 * Nothing worked for turning monitor mode
2394 return PCAP_ERROR_RFMON_NOTSUP
;
2398 * Either monitor mode has been turned on for
2399 * the device, or we've been given a different
2400 * device to open for monitor mode. If we've
2401 * been given a different device, use it.
2403 if (handlep
->mondevice
!= NULL
)
2404 device
= handlep
->mondevice
;
2406 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2411 map_arphrd_to_dlt(handle
, arptype
, device
, 1);
2412 if (handle
->linktype
== -1 ||
2413 handle
->linktype
== DLT_LINUX_SLL
||
2414 handle
->linktype
== DLT_LINUX_IRDA
||
2415 handle
->linktype
== DLT_LINUX_LAPD
||
2416 handle
->linktype
== DLT_NETLINK
||
2417 (handle
->linktype
== DLT_EN10MB
&&
2418 (strncmp("isdn", device
, 4) == 0 ||
2419 strncmp("isdY", device
, 4) == 0))) {
2421 * Unknown interface type (-1), or a
2422 * device we explicitly chose to run
2423 * in cooked mode (e.g., PPP devices),
2424 * or an ISDN device (whose link-layer
2425 * type we can only determine by using
2426 * APIs that may be different on different
2427 * kernels) - reopen in cooked mode.
2429 * If the type is unknown, return a warning;
2430 * map_arphrd_to_dlt() has already set the
2433 if (close(sock_fd
) == -1) {
2434 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2435 PCAP_ERRBUF_SIZE
, errno
, "close");
2438 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
, 0);
2441 * Fatal error. We treat this as
2442 * a generic error; we already know
2443 * that we were able to open a
2444 * PF_PACKET/SOCK_RAW socket, so
2445 * any failure is a "this shouldn't
2448 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2449 PCAP_ERRBUF_SIZE
, errno
, "socket");
2452 handlep
->cooked
= 1;
2455 * Get rid of any link-layer type list
2456 * we allocated - this only supports cooked
2459 if (handle
->dlt_list
!= NULL
) {
2460 free(handle
->dlt_list
);
2461 handle
->dlt_list
= NULL
;
2462 handle
->dlt_count
= 0;
2463 set_dlt_list_cooked(handle
);
2466 if (handle
->linktype
== -1) {
2468 * Warn that we're falling back on
2469 * cooked mode; we may want to
2470 * update "map_arphrd_to_dlt()"
2471 * to handle the new type.
2473 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2475 "supported by libpcap - "
2476 "falling back to cooked "
2482 * IrDA capture is not a real "cooked" capture,
2483 * it's IrLAP frames, not IP packets. The
2484 * same applies to LAPD capture.
2486 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2487 handle
->linktype
!= DLT_LINUX_LAPD
&&
2488 handle
->linktype
!= DLT_NETLINK
)
2489 handle
->linktype
= DLT_LINUX_SLL
;
2490 if (handle
->linktype
== -1) {
2491 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2492 "unknown arptype %d, defaulting to cooked mode",
2494 status
= PCAP_WARNING
;
2498 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
2500 if (handlep
->ifindex
== -1) {
2505 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
2506 handle
->errbuf
, 0)) != 0) {
2514 if (handle
->opt
.rfmon
) {
2516 * It doesn't support monitor mode.
2519 return PCAP_ERROR_RFMON_NOTSUP
;
2523 * It uses cooked mode.
2525 handlep
->cooked
= 1;
2526 handle
->linktype
= DLT_LINUX_SLL
;
2527 handle
->dlt_list
= NULL
;
2528 handle
->dlt_count
= 0;
2529 set_dlt_list_cooked(handle
);
2532 * We're not bound to a device.
2533 * For now, we're using this as an indication
2534 * that we can't transmit; stop doing that only
2535 * if we figure out how to transmit in cooked
2538 handlep
->ifindex
= -1;
2542 * Select promiscuous mode on if "promisc" is set.
2544 * Do not turn allmulti mode on if we don't select
2545 * promiscuous mode - on some devices (e.g., Orinoco
2546 * wireless interfaces), allmulti mode isn't supported
2547 * and the driver implements it by turning promiscuous
2548 * mode on, and that screws up the operation of the
2549 * card as a normal networking interface, and on no
2550 * other platform I know of does starting a non-
2551 * promiscuous capture affect which multicast packets
2552 * are received by the interface.
2556 * Hmm, how can we set promiscuous mode on all interfaces?
2557 * I am not sure if that is possible at all. For now, we
2558 * silently ignore attempts to turn promiscuous mode on
2559 * for the "any" device (so you don't have to explicitly
2560 * disable it in programs such as tcpdump).
2563 if (!is_any_device
&& handle
->opt
.promisc
) {
2564 memset(&mr
, 0, sizeof(mr
));
2565 mr
.mr_ifindex
= handlep
->ifindex
;
2566 mr
.mr_type
= PACKET_MR_PROMISC
;
2567 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2568 &mr
, sizeof(mr
)) == -1) {
2569 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2570 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
2577 * Enable auxiliary data and reserve room for reconstructing
2580 * XXX - is enabling auxiliary data necessary, now that we
2581 * only support memory-mapped capture? The kernel's memory-mapped
2582 * capture code doesn't seem to check whether auxiliary data
2583 * is enabled, it seems to provide it whether it is or not.
2586 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2587 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2588 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2589 errno
, "setsockopt (PACKET_AUXDATA)");
2593 handle
->offset
+= VLAN_TAG_LEN
;
2596 * If we're in cooked mode, make the snapshot length
2597 * large enough to hold a "cooked mode" header plus
2598 * 1 byte of packet data (so we don't pass a byte
2599 * count of 0 to "recvfrom()").
2600 * XXX - we don't know whether this will be DLT_LINUX_SLL
2601 * or DLT_LINUX_SLL2, so make sure it's big enough for
2602 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
2603 * that small is silly anyway.
2605 if (handlep
->cooked
) {
2606 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
2607 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
2609 handle
->bufsize
= handle
->snapshot
;
2612 * Set the offset at which to insert VLAN tags.
2614 set_vlan_offset(handle
);
2616 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
2617 int nsec_tstamps
= 1;
2619 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
2620 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
2627 * We've succeeded. Save the socket FD in the pcap structure.
2629 handle
->fd
= sock_fd
;
2631 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2633 * Can we generate special code for VLAN checks?
2634 * (XXX - what if we need the special code but it's not supported
2635 * by the OS? Is that possible?)
2637 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
2638 &bpf_extensions
, &len
) == 0) {
2639 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
2641 * Yes, we can. Request that we do so.
2643 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
2646 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
2652 * Attempt to setup memory-mapped access.
2654 * On success, returns 1, and sets *status to 0 if there are no warnings
2655 * or to a PCAP_WARNING_ code if there is a warning.
2657 * On error, returns -1, and sets *status to the appropriate error code;
2658 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
2661 setup_mmapped(pcap_t
*handle
, int *status
)
2663 struct pcap_linux
*handlep
= handle
->priv
;
2664 int ret
, flags
= MAP_ANONYMOUS
| MAP_PRIVATE
;
2667 * Attempt to allocate a buffer to hold the contents of one
2668 * packet, for use by the oneshot callback.
2671 if (pcap_mmap_32bit
) flags
|= MAP_32BIT
;
2673 handlep
->oneshot_buffer
= mmap(0, handle
->snapshot
, PROT_READ
| PROT_WRITE
, flags
, -1, 0);
2674 if (handlep
->oneshot_buffer
== MAP_FAILED
) {
2675 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2676 errno
, "can't allocate oneshot buffer");
2677 *status
= PCAP_ERROR
;
2681 if (handle
->opt
.buffer_size
== 0) {
2682 /* by default request 2M for the ring buffer */
2683 handle
->opt
.buffer_size
= 2*1024*1024;
2685 ret
= prepare_tpacket_socket(handle
);
2687 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
2688 handlep
->oneshot_buffer
= NULL
;
2689 *status
= PCAP_ERROR
;
2692 ret
= create_ring(handle
, status
);
2695 * Error attempting to enable memory-mapped capture;
2696 * fail. create_ring() has set *status.
2698 munmap(handlep
->oneshot_buffer
, handle
->snapshot
);
2699 handlep
->oneshot_buffer
= NULL
;
2704 * Success. *status has been set either to 0 if there are no
2705 * warnings or to a PCAP_WARNING_ value if there is a warning.
2707 * handle->offset is used to get the current position into the rx ring.
2708 * handle->cc is used to store the ring size.
2712 * Set the timeout to use in poll() before returning.
2714 set_poll_timeout(handlep
);
2720 * Attempt to set the socket to the specified version of the memory-mapped
2723 * Return 0 if we succeed; return 1 if we fail because that version isn't
2724 * supported; return -1 on any other error, and set handle->errbuf.
2727 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
2729 struct pcap_linux
*handlep
= handle
->priv
;
2731 socklen_t len
= sizeof(val
);
2734 * Probe whether kernel supports the specified TPACKET version;
2735 * this also gets the length of the header for that version.
2737 * This socket option was introduced in 2.6.27, which was
2738 * also the first release with TPACKET_V2 support.
2740 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
2741 if (errno
== EINVAL
) {
2743 * EINVAL means this specific version of TPACKET
2744 * is not supported. Tell the caller they can try
2745 * with a different one; if they've run out of
2746 * others to try, let them set the error message
2753 * All other errors are fatal.
2755 if (errno
== ENOPROTOOPT
) {
2757 * PACKET_HDRLEN isn't supported, which means
2758 * that memory-mapped capture isn't supported.
2759 * Indicate that in the message.
2761 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2762 "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");
2765 * Some unexpected error.
2767 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2768 errno
, "can't get %s header len on packet socket",
2773 handlep
->tp_hdrlen
= val
;
2776 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
2778 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2779 errno
, "can't activate %s on packet socket", version_str
);
2782 handlep
->tp_version
= version
;
2788 * Attempt to set the socket to version 3 of the memory-mapped header and,
2789 * if that fails because version 3 isn't supported, attempt to fall
2790 * back to version 2. If version 2 isn't supported, just fail.
2792 * Return 0 if we succeed and -1 on any other error, and set handle->errbuf.
2795 prepare_tpacket_socket(pcap_t
*handle
)
2799 #ifdef HAVE_TPACKET3
2801 * Try setting the version to TPACKET_V3.
2803 * The only mode in which buffering is done on PF_PACKET
2804 * sockets, so that packets might not be delivered
2805 * immediately, is TPACKET_V3 mode.
2807 * The buffering cannot be disabled in that mode, so
2808 * if the user has requested immediate mode, we don't
2811 if (!handle
->opt
.immediate
) {
2812 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
2821 * We failed for some reason other than "the
2822 * kernel doesn't support TPACKET_V3".
2828 * This means it returned 1, which means "the kernel
2829 * doesn't support TPACKET_V3"; try TPACKET_V2.
2832 #endif /* HAVE_TPACKET3 */
2835 * Try setting the version to TPACKET_V2.
2837 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
2847 * OK, the kernel supports memory-mapped capture, but
2848 * not TPACKET_V2. Set the error message appropriately.
2850 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2851 "Kernel doesn't support TPACKET_V2; a 2.6.27 or later kernel is required");
2860 #define MAX(a,b) ((a)>(b)?(a):(b))
2863 * Attempt to set up memory-mapped access.
2865 * On success, returns 1, and sets *status to 0 if there are no warnings
2866 * or to a PCAP_WARNING_ code if there is a warning.
2868 * On error, returns -1, and sets *status to the appropriate error code;
2869 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
2872 create_ring(pcap_t
*handle
, int *status
)
2874 struct pcap_linux
*handlep
= handle
->priv
;
2875 unsigned i
, j
, frames_per_block
;
2876 int flags
= MAP_SHARED
;
2877 #ifdef HAVE_TPACKET3
2879 * For sockets using TPACKET_V2, the extra stuff at the end of a
2880 * struct tpacket_req3 will be ignored, so this is OK even for
2883 struct tpacket_req3 req
;
2885 struct tpacket_req req
;
2888 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
2889 unsigned int frame_size
;
2892 * Start out assuming no warnings or errors.
2897 * Reserve space for VLAN tag reconstruction.
2899 tp_reserve
= VLAN_TAG_LEN
;
2902 * If we're capturing in cooked mode, reserve space for
2903 * a DLT_LINUX_SLL2 header; we don't know yet whether
2904 * we'll be using DLT_LINUX_SLL or DLT_LINUX_SLL2, as
2905 * that can be changed on an open device, so we reserve
2906 * space for the larger of the two.
2908 * XXX - we assume that the kernel is still adding
2909 * 16 bytes of extra space, so we subtract 16 from
2910 * SLL2_HDR_LEN to get the additional space needed.
2911 * (Are they doing that for DLT_LINUX_SLL, the link-
2912 * layer header for which is 16 bytes?)
2914 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - 16)?
2916 if (handlep
->cooked
)
2917 tp_reserve
+= SLL2_HDR_LEN
- 16;
2920 * Try to request that amount of reserve space.
2921 * This must be done before creating the ring buffer.
2923 len
= sizeof(tp_reserve
);
2924 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
2925 &tp_reserve
, len
) < 0) {
2926 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2927 PCAP_ERRBUF_SIZE
, errno
,
2928 "setsockopt (PACKET_RESERVE)");
2929 *status
= PCAP_ERROR
;
2933 switch (handlep
->tp_version
) {
2936 /* Note that with large snapshot length (say 256K, which is
2937 * the default for recent versions of tcpdump, Wireshark,
2938 * TShark, dumpcap or 64K, the value that "-s 0" has given for
2939 * a long time with tcpdump), if we use the snapshot
2940 * length to calculate the frame length, only a few frames
2941 * will be available in the ring even with pretty
2942 * large ring size (and a lot of memory will be unused).
2944 * Ideally, we should choose a frame length based on the
2945 * minimum of the specified snapshot length and the maximum
2946 * packet size. That's not as easy as it sounds; consider,
2947 * for example, an 802.11 interface in monitor mode, where
2948 * the frame would include a radiotap header, where the
2949 * maximum radiotap header length is device-dependent.
2951 * So, for now, we just do this for Ethernet devices, where
2952 * there's no metadata header, and the link-layer header is
2953 * fixed length. We can get the maximum packet size by
2954 * adding 18, the Ethernet header length plus the CRC length
2955 * (just in case we happen to get the CRC in the packet), to
2956 * the MTU of the interface; we fetch the MTU in the hopes
2957 * that it reflects support for jumbo frames. (Even if the
2958 * interface is just being used for passive snooping, the
2959 * driver might set the size of buffers in the receive ring
2960 * based on the MTU, so that the MTU limits the maximum size
2961 * of packets that we can receive.)
2963 * If segmentation/fragmentation or receive offload are
2964 * enabled, we can get reassembled/aggregated packets larger
2965 * than MTU, but bounded to 65535 plus the Ethernet overhead,
2966 * due to kernel and protocol constraints */
2967 frame_size
= handle
->snapshot
;
2968 if (handle
->linktype
== DLT_EN10MB
) {
2969 unsigned int max_frame_len
;
2973 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
2976 *status
= PCAP_ERROR
;
2979 offload
= iface_get_offload(handle
);
2980 if (offload
== -1) {
2981 *status
= PCAP_ERROR
;
2985 max_frame_len
= MAX(mtu
, 65535);
2987 max_frame_len
= mtu
;
2988 max_frame_len
+= 18;
2990 if (frame_size
> max_frame_len
)
2991 frame_size
= max_frame_len
;
2994 /* NOTE: calculus matching those in tpacket_rcv()
2995 * in linux-2.6/net/packet/af_packet.c
2997 len
= sizeof(sk_type
);
2998 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
3000 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3001 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
3002 *status
= PCAP_ERROR
;
3005 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3006 /* XXX: in the kernel maclen is calculated from
3007 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3008 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3009 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3010 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3011 * but I see no way to get those sizes in userspace,
3012 * like for instance with an ifreq ioctl();
3013 * the best thing I've found so far is MAX_HEADER in
3014 * the kernel part of linux-2.6/include/linux/netdevice.h
3015 * which goes up to 128+48=176; since pcap-linux.c
3016 * defines a MAX_LINKHEADER_SIZE of 256 which is
3017 * greater than that, let's use it.. maybe is it even
3018 * large enough to directly replace macoff..
3020 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3021 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3022 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3023 * of netoff, which contradicts
3024 * linux-2.6/Documentation/networking/packet_mmap.txt
3026 * "- Gap, chosen so that packet data (Start+tp_net)
3027 * aligns to TPACKET_ALIGNMENT=16"
3029 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3030 * "CPUs often take a performance hit
3031 * when accessing unaligned memory locations"
3033 macoff
= netoff
- maclen
;
3034 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3036 * Round the buffer size up to a multiple of the
3037 * frame size (rather than rounding down, which
3038 * would give a buffer smaller than our caller asked
3039 * for, and possibly give zero frames if the requested
3040 * buffer size is too small for one frame).
3042 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3045 #ifdef HAVE_TPACKET3
3047 /* The "frames" for this are actually buffers that
3048 * contain multiple variable-sized frames.
3050 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
3051 * enough room for at least one reasonably-sized packet
3052 * in the "frame". */
3053 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
3055 * Round the buffer size up to a multiple of the
3056 * "frame" size (rather than rounding down, which
3057 * would give a buffer smaller than our caller asked
3058 * for, and possibly give zero "frames" if the requested
3059 * buffer size is too small for one "frame").
3061 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3065 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3066 "Internal error: unknown TPACKET_ value %u",
3067 handlep
->tp_version
);
3068 *status
= PCAP_ERROR
;
3072 /* compute the minimum block size that will handle this frame.
3073 * The block has to be page size aligned.
3074 * The max block size allowed by the kernel is arch-dependent and
3075 * it's not explicitly checked here. */
3076 req
.tp_block_size
= getpagesize();
3077 while (req
.tp_block_size
< req
.tp_frame_size
)
3078 req
.tp_block_size
<<= 1;
3080 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3083 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3084 * so we check for PACKET_TIMESTAMP. We check for
3085 * linux/net_tstamp.h just in case a system somehow has
3086 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3089 * SIOCSHWTSTAMP was introduced in the patch that introduced
3090 * linux/net_tstamp.h, so we don't bother checking whether
3091 * SIOCSHWTSTAMP is defined (if your Linux system has
3092 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3093 * Linux system is badly broken).
3095 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3097 * If we were told to do so, ask the kernel and the driver
3098 * to use hardware timestamps.
3100 * Hardware timestamps are only supported with mmapped
3103 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3104 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3105 struct hwtstamp_config hwconfig
;
3110 * Ask for hardware time stamps on all packets,
3111 * including transmitted packets.
3113 memset(&hwconfig
, 0, sizeof(hwconfig
));
3114 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3115 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3117 memset(&ifr
, 0, sizeof(ifr
));
3118 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
3119 ifr
.ifr_data
= (void *)&hwconfig
;
3122 * This may require CAP_NET_ADMIN.
3124 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3129 * Treat this as an error, as the
3130 * user should try to run this
3131 * with the appropriate privileges -
3132 * and, if they can't, shouldn't
3133 * try requesting hardware time stamps.
3135 *status
= PCAP_ERROR_PERM_DENIED
;
3136 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3137 "Attempt to set hardware timestamp failed - CAP_NET_ADMIN may be required");
3143 * Treat this as a warning, as the
3144 * only way to fix the warning is to
3145 * get an adapter that supports hardware
3146 * time stamps for *all* packets.
3147 * (ERANGE means "we support hardware
3148 * time stamps, but for packets matching
3149 * that particular filter", so it means
3150 * "we don't support hardware time stamps
3151 * for all incoming packets" here.)
3153 * We'll just fall back on the standard
3156 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3160 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3161 PCAP_ERRBUF_SIZE
, errno
,
3162 "SIOCSHWTSTAMP failed");
3163 *status
= PCAP_ERROR
;
3168 * Well, that worked. Now specify the type of
3169 * hardware time stamp we want for this
3172 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3174 * Hardware timestamp, synchronized
3175 * with the system clock.
3177 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3180 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3181 * timestamp, not synchronized with the
3184 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3186 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3187 (void *)×ource
, sizeof(timesource
))) {
3188 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3189 PCAP_ERRBUF_SIZE
, errno
,
3190 "can't set PACKET_TIMESTAMP");
3191 *status
= PCAP_ERROR
;
3196 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3198 /* ask the kernel to create the ring */
3200 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3202 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3203 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3205 #ifdef HAVE_TPACKET3
3206 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3207 if (handlep
->timeout
> 0) {
3208 /* Use the user specified timeout as the block timeout */
3209 req
.tp_retire_blk_tov
= handlep
->timeout
;
3210 } else if (handlep
->timeout
== 0) {
3212 * In pcap, this means "infinite timeout"; TPACKET_V3
3213 * doesn't support that, so just set it to UINT_MAX
3214 * milliseconds. In the TPACKET_V3 loop, if the
3215 * timeout is 0, and we haven't yet seen any packets,
3216 * and we block and still don't have any packets, we
3217 * keep blocking until we do.
3219 req
.tp_retire_blk_tov
= UINT_MAX
;
3222 * XXX - this is not valid; use 0, meaning "have the
3223 * kernel pick a default", for now.
3225 req
.tp_retire_blk_tov
= 0;
3227 /* private data not used */
3228 req
.tp_sizeof_priv
= 0;
3229 /* Rx ring - feature request bits - none (rxhash will not be filled) */
3230 req
.tp_feature_req_word
= 0;
3233 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3234 (void *) &req
, sizeof(req
))) {
3235 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3237 * Memory failure; try to reduce the requested ring
3240 * We used to reduce this by half -- do 5% instead.
3241 * That may result in more iterations and a longer
3242 * startup, but the user will be much happier with
3243 * the resulting buffer size.
3245 if (req
.tp_frame_nr
< 20)
3246 req
.tp_frame_nr
-= 1;
3248 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3251 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3252 errno
, "can't create rx ring on packet socket");
3253 *status
= PCAP_ERROR
;
3257 /* memory map the rx ring */
3258 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3260 if (pcap_mmap_32bit
) flags
|= MAP_32BIT
;
3262 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
, PROT_READ
| PROT_WRITE
, flags
, handle
->fd
, 0);
3263 if (handlep
->mmapbuf
== MAP_FAILED
) {
3264 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3265 errno
, "can't mmap rx ring");
3267 /* clear the allocated ring on error*/
3268 destroy_ring(handle
);
3269 *status
= PCAP_ERROR
;
3273 /* allocate a ring for each frame header pointer*/
3274 handle
->cc
= req
.tp_frame_nr
;
3275 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3276 if (!handle
->buffer
) {
3277 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3278 errno
, "can't allocate ring of frame headers");
3280 destroy_ring(handle
);
3281 *status
= PCAP_ERROR
;
3285 /* fill the header ring with proper frame ptr*/
3287 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3288 u_char
*base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3289 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3290 RING_GET_CURRENT_FRAME(handle
) = base
;
3291 base
+= req
.tp_frame_size
;
3295 handle
->bufsize
= req
.tp_frame_size
;
3300 /* free all ring related resources*/
3302 destroy_ring(pcap_t
*handle
)
3304 struct pcap_linux
*handlep
= handle
->priv
;
3307 * Tell the kernel to destroy the ring.
3308 * We don't check for setsockopt failure, as 1) we can't recover
3309 * from an error and 2) we might not yet have set it up in the
3312 struct tpacket_req req
;
3313 memset(&req
, 0, sizeof(req
));
3314 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3315 (void *) &req
, sizeof(req
));
3317 /* if ring is mapped, unmap it*/
3318 if (handlep
->mmapbuf
) {
3319 /* do not test for mmap failure, as we can't recover from any error */
3320 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3321 handlep
->mmapbuf
= NULL
;
3326 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3327 * for Linux mmapped capture.
3329 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3330 * data handed to the callback to be valid after the callback returns,
3331 * but pcap_read_linux_mmap() has to release that packet as soon as
3332 * the callback returns (otherwise, the kernel thinks there's still
3333 * at least one unprocessed packet available in the ring, so a select()
3334 * will immediately return indicating that there's data to process), so,
3335 * in the callback, we have to make a copy of the packet.
3337 * Yes, this means that, if the capture is using the ring buffer, using
3338 * pcap_next() or pcap_next_ex() requires more copies than using
3339 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3340 * pcap_next() or pcap_next_ex().
3343 pcap_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
3344 const u_char
*bytes
)
3346 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3347 pcap_t
*handle
= sp
->pd
;
3348 struct pcap_linux
*handlep
= handle
->priv
;
3351 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3352 *sp
->pkt
= handlep
->oneshot_buffer
;
3356 pcap_getnonblock_linux(pcap_t
*handle
)
3358 struct pcap_linux
*handlep
= handle
->priv
;
3360 /* use negative value of timeout to indicate non blocking ops */
3361 return (handlep
->timeout
<0);
3365 pcap_setnonblock_linux(pcap_t
*handle
, int nonblock
)
3367 struct pcap_linux
*handlep
= handle
->priv
;
3370 * Set the file descriptor to non-blocking mode, as we use
3371 * it for sending packets.
3373 if (pcap_setnonblock_fd(handle
, nonblock
) == -1)
3377 * Map each value to their corresponding negation to
3378 * preserve the timeout value provided with pcap_set_timeout.
3381 if (handlep
->timeout
>= 0) {
3383 * Indicate that we're switching to
3384 * non-blocking mode.
3386 handlep
->timeout
= ~handlep
->timeout
;
3388 if (handlep
->poll_breakloop_fd
!= -1) {
3389 /* Close the eventfd; we do not need it in nonblock mode. */
3390 close(handlep
->poll_breakloop_fd
);
3391 handlep
->poll_breakloop_fd
= -1;
3394 if (handlep
->poll_breakloop_fd
== -1) {
3395 /* If we did not have an eventfd, open one now that we are blocking. */
3396 if ( ( handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
) ) == -1 ) {
3397 int save_errno
= errno
;
3398 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3399 "Could not open eventfd: %s",
3405 if (handlep
->timeout
< 0) {
3406 handlep
->timeout
= ~handlep
->timeout
;
3409 /* Update the timeout to use in poll(). */
3410 set_poll_timeout(handlep
);
3415 * Get the status field of the ring buffer frame at a specified offset.
3418 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
3420 struct pcap_linux
*handlep
= handle
->priv
;
3423 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
3424 switch (handlep
->tp_version
) {
3426 return __atomic_load_n(&h
.h2
->tp_status
, __ATOMIC_ACQUIRE
);
3428 #ifdef HAVE_TPACKET3
3430 return __atomic_load_n(&h
.h3
->hdr
.bh1
.block_status
, __ATOMIC_ACQUIRE
);
3434 /* This should not happen. */
3439 * Block waiting for frames to be available.
3441 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
3443 struct pcap_linux
*handlep
= handle
->priv
;
3447 struct pollfd pollinfo
[2];
3449 pollinfo
[0].fd
= handle
->fd
;
3450 pollinfo
[0].events
= POLLIN
;
3451 if ( handlep
->poll_breakloop_fd
== -1 ) {
3453 pollinfo
[1].revents
= 0;
3455 * We set pollinfo[1].revents to zero, even though
3456 * numpollinfo = 1 meaning that poll() doesn't see
3457 * pollinfo[1], so that we do not have to add a
3458 * conditional of numpollinfo > 1 below when we
3459 * test pollinfo[1].revents.
3462 pollinfo
[1].fd
= handlep
->poll_breakloop_fd
;
3463 pollinfo
[1].events
= POLLIN
;
3468 * Keep polling until we either get some packets to read, see
3469 * that we got told to break out of the loop, get a fatal error,
3470 * or discover that the device went away.
3472 * In non-blocking mode, we must still do one poll() to catch
3473 * any pending error indications, but the poll() has a timeout
3474 * of 0, so that it doesn't block, and we quit after that one
3477 * If we've seen an ENETDOWN, it might be the first indication
3478 * that the device went away, or it might just be that it was
3479 * configured down. Unfortunately, there's no guarantee that
3480 * the device has actually been removed as an interface, because:
3482 * 1) if, as appears to be the case at least some of the time,
3483 * the PF_PACKET socket code first gets a NETDEV_DOWN indication
3484 * for the device and then gets a NETDEV_UNREGISTER indication
3485 * for it, the first indication will cause a wakeup with ENETDOWN
3486 * but won't set the packet socket's field for the interface index
3487 * to -1, and the second indication won't cause a wakeup (because
3488 * the first indication also caused the protocol hook to be
3489 * unregistered) but will set the packet socket's field for the
3490 * interface index to -1;
3492 * 2) even if just a NETDEV_UNREGISTER indication is registered,
3493 * the packet socket's field for the interface index only gets
3494 * set to -1 after the wakeup, so there's a small but non-zero
3495 * risk that a thread blocked waiting for the wakeup will get
3496 * to the "fetch the socket name" code before the interface index
3497 * gets set to -1, so it'll get the old interface index.
3499 * Therefore, if we got an ENETDOWN and haven't seen a packet
3500 * since then, we assume that we might be waiting for the interface
3501 * to disappear, and poll with a timeout to try again in a short
3502 * period of time. If we *do* see a packet, the interface has
3503 * come back up again, and is *definitely* still there, so we
3504 * don't need to poll.
3508 * Yes, we do this even in non-blocking mode, as it's
3509 * the only way to get error indications from a
3512 * The timeout is 0 in non-blocking mode, so poll()
3513 * returns immediately.
3515 timeout
= handlep
->poll_timeout
;
3518 * If we got an ENETDOWN and haven't gotten an indication
3519 * that the device has gone away or that the device is up,
3520 * we don't yet know for certain whether the device has
3521 * gone away or not, do a poll() with a 1-millisecond timeout,
3522 * as we have to poll indefinitely for "device went away"
3523 * indications until we either get one or see that the
3526 if (handlep
->netdown
) {
3530 ret
= poll(pollinfo
, numpollinfo
, timeout
);
3533 * Error. If it's not EINTR, report it.
3535 if (errno
!= EINTR
) {
3536 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3537 PCAP_ERRBUF_SIZE
, errno
,
3538 "can't poll on packet socket");
3543 * It's EINTR; if we were told to break out of
3546 if (handle
->break_loop
) {
3547 handle
->break_loop
= 0;
3548 return PCAP_ERROR_BREAK
;
3550 } else if (ret
> 0) {
3552 * OK, some descriptor is ready.
3553 * Check the socket descriptor first.
3555 * As I read the Linux man page, pollinfo[0].revents
3556 * will either be POLLIN, POLLERR, POLLHUP, or POLLNVAL.
3558 if (pollinfo
[0].revents
== POLLIN
) {
3560 * OK, we may have packets to
3565 if (pollinfo
[0].revents
!= 0) {
3567 * There's some indication other than
3568 * "you can read on this descriptor" on
3571 if (pollinfo
[0].revents
& POLLNVAL
) {
3572 snprintf(handle
->errbuf
,
3574 "Invalid polling request on packet socket");
3577 if (pollinfo
[0].revents
& (POLLHUP
| POLLRDHUP
)) {
3578 snprintf(handle
->errbuf
,
3580 "Hangup on packet socket");
3583 if (pollinfo
[0].revents
& POLLERR
) {
3590 errlen
= sizeof(err
);
3591 if (getsockopt(handle
->fd
, SOL_SOCKET
,
3592 SO_ERROR
, &err
, &errlen
) == -1) {
3594 * The call *itself* returned
3595 * an error; make *that*
3602 * OK, we have the error.
3604 if (err
== ENETDOWN
) {
3606 * The device on which we're
3607 * capturing went away or the
3608 * interface was taken down.
3610 * We don't know for certain
3611 * which happened, and the
3612 * next poll() may indicate
3613 * that there are packets
3614 * to be read, so just set
3615 * a flag to get us to do
3616 * checks later, and set
3617 * the required select
3618 * timeout to 1 millisecond
3619 * so that event loops that
3620 * check our socket descriptor
3621 * also time out so that
3622 * they can call us and we
3623 * can do the checks.
3625 handlep
->netdown
= 1;
3626 handle
->required_select_timeout
= &netdown_timeout
;
3627 } else if (err
== 0) {
3629 * This shouldn't happen, so
3630 * report a special indication
3633 snprintf(handle
->errbuf
,
3635 "Error condition on packet socket: Reported error was 0");
3638 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3641 "Error condition on packet socket");
3647 * Now check the event device.
3649 if (pollinfo
[1].revents
& POLLIN
) {
3654 * This should never fail, but, just
3657 nread
= read(handlep
->poll_breakloop_fd
, &value
,
3660 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3663 "Error reading from event FD");
3668 * According to the Linux read(2) man
3669 * page, read() will transfer at most
3670 * 2^31-1 bytes, so the return value is
3671 * either -1 or a value between 0
3672 * and 2^31-1, so it's non-negative.
3674 * Cast it to size_t to squelch
3675 * warnings from the compiler; add this
3676 * comment to squelch warnings from
3677 * humans reading the code. :-)
3679 * Don't treat an EOF as an error, but
3680 * *do* treat a short read as an error;
3681 * that "shouldn't happen", but....
3684 (size_t)nread
< sizeof(value
)) {
3685 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3686 "Short read from event FD: expected %zu, got %zd",
3687 sizeof(value
), nread
);
3692 * This event gets signaled by a
3693 * pcap_breakloop() call; if we were told
3694 * to break out of the loop, do so.
3696 if (handle
->break_loop
) {
3697 handle
->break_loop
= 0;
3698 return PCAP_ERROR_BREAK
;
3706 * 1) we got neither an error from poll() nor any
3707 * readable descriptors, in which case there
3708 * are no packets waiting to read
3712 * 2) We got readable descriptors but the PF_PACKET
3713 * socket wasn't one of them, in which case there
3714 * are no packets waiting to read
3716 * so, if we got an ENETDOWN, we've drained whatever
3717 * packets were available to read at the point of the
3720 * So, if we got an ENETDOWN and haven't gotten an indication
3721 * that the device has gone away or that the device is up,
3722 * we don't yet know for certain whether the device has
3723 * gone away or not, check whether the device exists and is
3726 if (handlep
->netdown
) {
3727 if (!device_still_exists(handle
)) {
3729 * The device doesn't exist any more;
3732 * XXX - we should really return an
3733 * appropriate error for that, but
3734 * pcap_dispatch() etc. aren't documented
3735 * as having error returns other than
3736 * PCAP_ERROR or PCAP_ERROR_BREAK.
3738 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3739 "The interface disappeared");
3744 * The device still exists; try to see if it's up.
3746 memset(&ifr
, 0, sizeof(ifr
));
3747 pcap_strlcpy(ifr
.ifr_name
, handlep
->device
,
3748 sizeof(ifr
.ifr_name
));
3749 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3750 if (errno
== ENXIO
|| errno
== ENODEV
) {
3752 * OK, *now* it's gone.
3754 * XXX - see above comment.
3756 snprintf(handle
->errbuf
,
3758 "The interface disappeared");
3761 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3762 PCAP_ERRBUF_SIZE
, errno
,
3763 "%s: Can't get flags",
3768 if (ifr
.ifr_flags
& IFF_UP
) {
3770 * It's up, so it definitely still exists.
3771 * Cancel the ENETDOWN indication - we
3772 * presumably got it due to the interface
3773 * going down rather than the device going
3774 * away - and revert to "no required select
3777 handlep
->netdown
= 0;
3778 handle
->required_select_timeout
= NULL
;
3783 * If we're in non-blocking mode, just quit now, rather
3784 * than spinning in a loop doing poll()s that immediately
3785 * time out if there's no indication on any descriptor.
3787 if (handlep
->poll_timeout
== 0)
3793 /* handle a single memory mapped packet */
3794 static int pcap_handle_packet_mmap(
3796 pcap_handler callback
,
3798 unsigned char *frame
,
3799 unsigned int tp_len
,
3800 unsigned int tp_mac
,
3801 unsigned int tp_snaplen
,
3802 unsigned int tp_sec
,
3803 unsigned int tp_usec
,
3804 int tp_vlan_tci_valid
,
3808 struct pcap_linux
*handlep
= handle
->priv
;
3810 struct sockaddr_ll
*sll
;
3811 struct pcap_pkthdr pcaphdr
;
3812 pcap_can_socketcan_hdr
*canhdr
;
3813 unsigned int snaplen
= tp_snaplen
;
3814 struct utsname utsname
;
3816 /* perform sanity check on internal offset. */
3817 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3819 * Report some system information as a debugging aid.
3821 if (uname(&utsname
) != -1) {
3822 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3823 "corrupted frame on kernel ring mac "
3824 "offset %u + caplen %u > frame len %d "
3825 "(kernel %.32s version %s, machine %.16s)",
3826 tp_mac
, tp_snaplen
, handle
->bufsize
,
3827 utsname
.release
, utsname
.version
,
3830 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3831 "corrupted frame on kernel ring mac "
3832 "offset %u + caplen %u > frame len %d",
3833 tp_mac
, tp_snaplen
, handle
->bufsize
);
3838 /* run filter on received packet
3839 * If the kernel filtering is enabled we need to run the
3840 * filter until all the frames present into the ring
3841 * at filter creation time are processed.
3842 * In this case, blocks_to_filter_in_userland is used
3843 * as a counter for the packet we need to filter.
3844 * Note: alternatively it could be possible to stop applying
3845 * the filter when the ring became empty, but it can possibly
3846 * happen a lot later... */
3847 bp
= frame
+ tp_mac
;
3849 /* if required build in place the sll header*/
3850 sll
= (void *)(frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
));
3851 if (handlep
->cooked
) {
3852 if (handle
->linktype
== DLT_LINUX_SLL2
) {
3853 struct sll2_header
*hdrp
;
3856 * The kernel should have left us with enough
3857 * space for an sll header; back up the packet
3858 * data pointer into that space, as that'll be
3859 * the beginning of the packet we pass to the
3865 * Let's make sure that's past the end of
3866 * the tpacket header, i.e. >=
3867 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3868 * don't step on the header when we construct
3871 if (bp
< (u_char
*)frame
+
3872 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
3873 sizeof(struct sockaddr_ll
)) {
3874 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3875 "cooked-mode frame doesn't have room for sll header");
3880 * OK, that worked; construct the sll header.
3882 hdrp
= (struct sll2_header
*)bp
;
3883 hdrp
->sll2_protocol
= sll
->sll_protocol
;
3884 hdrp
->sll2_reserved_mbz
= 0;
3885 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
3886 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
3887 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
3888 hdrp
->sll2_halen
= sll
->sll_halen
;
3889 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3891 snaplen
+= sizeof(struct sll2_header
);
3893 struct sll_header
*hdrp
;
3896 * The kernel should have left us with enough
3897 * space for an sll header; back up the packet
3898 * data pointer into that space, as that'll be
3899 * the beginning of the packet we pass to the
3905 * Let's make sure that's past the end of
3906 * the tpacket header, i.e. >=
3907 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3908 * don't step on the header when we construct
3911 if (bp
< (u_char
*)frame
+
3912 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
3913 sizeof(struct sockaddr_ll
)) {
3914 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3915 "cooked-mode frame doesn't have room for sll header");
3920 * OK, that worked; construct the sll header.
3922 hdrp
= (struct sll_header
*)bp
;
3923 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
3924 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3925 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3926 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3927 hdrp
->sll_protocol
= sll
->sll_protocol
;
3929 snaplen
+= sizeof(struct sll_header
);
3933 * If this is a packet from a CAN device, so that
3934 * sll->sll_hatype is ARPHRD_CAN, then, as we're
3935 * not capturing in cooked mode, its link-layer
3936 * type is DLT_CAN_SOCKETCAN. Fix up the header
3937 * provided by the code below us to match what
3938 * DLT_CAN_SOCKETCAN is expected to provide.
3940 if (sll
->sll_hatype
== ARPHRD_CAN
) {
3942 * DLT_CAN_SOCKETCAN is specified as having the
3943 * CAN ID and flags in network byte order, but
3944 * capturing on a CAN device provides it in host
3945 * byte order. Convert it to network byte order.
3947 canhdr
= (pcap_can_socketcan_hdr
*)bp
;
3948 canhdr
->can_id
= htonl(canhdr
->can_id
);
3951 * In addition, set the CANFD_FDF flag if
3952 * the protocol is LINUX_SLL_P_CANFD, as
3953 * the protocol field itself isn't in
3954 * the packet to indicate that it's a
3957 uint16_t protocol
= ntohs(sll
->sll_protocol
);
3958 if (protocol
== LINUX_SLL_P_CANFD
) {
3959 canhdr
->fd_flags
|= CANFD_FDF
;
3962 * Zero out all the unknown bits in
3963 * fd_flags and clear the reserved
3964 * fields, so that a program reading
3965 * this can assume that CANFD_FDF
3966 * is set because we set it, not
3967 * because some uninitialized crap
3968 * was provided in the fd_flags
3971 * (At least some LINKTYPE_CAN_SOCKETCAN
3972 * files attached to Wireshark bugs
3973 * had uninitialized junk there, so it
3976 * Update this if Linux adds more flag
3977 * bits to the fd_flags field or uses
3978 * either of the reserved fields for
3981 canhdr
->fd_flags
&= ~(CANFD_FDF
|CANFD_ESI
|CANFD_BRS
);
3982 canhdr
->reserved1
= 0;
3983 canhdr
->reserved2
= 0;
3986 * Clear CANFD_FDF if it's set (probably
3987 * again meaning that this field is
3988 * uninitialized junk).
3990 canhdr
->fd_flags
&= ~CANFD_FDF
;
3995 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
3996 struct pcap_bpf_aux_data aux_data
;
3998 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
3999 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4001 if (pcap_filter_with_aux_data(handle
->fcode
.bf_insns
,
4009 if (!linux_check_direction(handle
, sll
))
4012 /* get required packet info from ring header */
4013 pcaphdr
.ts
.tv_sec
= tp_sec
;
4014 pcaphdr
.ts
.tv_usec
= tp_usec
;
4015 pcaphdr
.caplen
= tp_snaplen
;
4016 pcaphdr
.len
= tp_len
;
4018 /* if required build in place the sll header*/
4019 if (handlep
->cooked
) {
4020 /* update packet len */
4021 if (handle
->linktype
== DLT_LINUX_SLL2
) {
4022 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
4023 pcaphdr
.len
+= SLL2_HDR_LEN
;
4025 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4026 pcaphdr
.len
+= SLL_HDR_LEN
;
4030 if (tp_vlan_tci_valid
&&
4031 handlep
->vlan_offset
!= -1 &&
4032 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4034 struct vlan_tag
*tag
;
4037 * Move everything in the header, except the type field,
4038 * down VLAN_TAG_LEN bytes, to allow us to insert the
4039 * VLAN tag between that stuff and the type field.
4042 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4045 * Now insert the tag.
4047 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4048 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4049 tag
->vlan_tci
= htons(tp_vlan_tci
);
4052 * Add the tag to the packet lengths.
4054 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4055 pcaphdr
.len
+= VLAN_TAG_LEN
;
4059 * The only way to tell the kernel to cut off the
4060 * packet at a snapshot length is with a filter program;
4061 * if there's no filter program, the kernel won't cut
4064 * Trim the snapshot length to be no longer than the
4065 * specified snapshot length.
4067 * XXX - an alternative is to put a filter, consisting
4068 * of a "ret <snaplen>" instruction, on the socket
4069 * in the activate routine, so that the truncation is
4070 * done in the kernel even if nobody specified a filter;
4071 * that means that less buffer space is consumed in
4072 * the memory-mapped buffer.
4074 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
4075 pcaphdr
.caplen
= handle
->snapshot
;
4077 /* pass the packet to the user */
4078 callback(user
, &pcaphdr
, bp
);
4084 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4087 struct pcap_linux
*handlep
= handle
->priv
;
4092 /* wait for frames availability.*/
4093 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4094 if (!packet_mmap_acquire(h
.h2
)) {
4096 * The current frame is owned by the kernel; wait for
4097 * a frame to be handed to us.
4099 ret
= pcap_wait_for_frames_mmap(handle
);
4106 * This can conceivably process more than INT_MAX packets,
4107 * which would overflow the packet count, causing it either
4108 * to look like a negative number, and thus cause us to
4109 * return a value that looks like an error, or overflow
4110 * back into positive territory, and thus cause us to
4111 * return a too-low count.
4113 * Therefore, if the packet count is unlimited, we clip
4114 * it at INT_MAX; this routine is not expected to
4115 * process packets indefinitely, so that's not an issue.
4117 if (PACKET_COUNT_IS_UNLIMITED(max_packets
))
4118 max_packets
= INT_MAX
;
4120 while (pkts
< max_packets
) {
4122 * Get the current ring buffer frame, and break if
4123 * it's still owned by the kernel.
4125 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4126 if (!packet_mmap_acquire(h
.h2
))
4129 ret
= pcap_handle_packet_mmap(
4138 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4139 VLAN_VALID(h
.h2
, h
.h2
),
4141 VLAN_TPID(h
.h2
, h
.h2
));
4144 } else if (ret
< 0) {
4149 * Hand this block back to the kernel, and, if we're
4150 * counting blocks that need to be filtered in userland
4151 * after having been filtered by the kernel, count
4152 * the one we've just processed.
4154 packet_mmap_release(h
.h2
);
4155 if (handlep
->blocks_to_filter_in_userland
> 0) {
4156 handlep
->blocks_to_filter_in_userland
--;
4157 if (handlep
->blocks_to_filter_in_userland
== 0) {
4159 * No more blocks need to be filtered
4162 handlep
->filter_in_userland
= 0;
4167 if (++handle
->offset
>= handle
->cc
)
4170 /* check for break loop condition*/
4171 if (handle
->break_loop
) {
4172 handle
->break_loop
= 0;
4173 return PCAP_ERROR_BREAK
;
4179 #ifdef HAVE_TPACKET3
4181 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4184 struct pcap_linux
*handlep
= handle
->priv
;
4190 if (handlep
->current_packet
== NULL
) {
4191 /* wait for frames availability.*/
4192 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4193 if (!packet_mmap_v3_acquire(h
.h3
)) {
4195 * The current frame is owned by the kernel; wait
4196 * for a frame to be handed to us.
4198 ret
= pcap_wait_for_frames_mmap(handle
);
4204 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4205 if (!packet_mmap_v3_acquire(h
.h3
)) {
4206 if (pkts
== 0 && handlep
->timeout
== 0) {
4207 /* Block until we see a packet. */
4214 * This can conceivably process more than INT_MAX packets,
4215 * which would overflow the packet count, causing it either
4216 * to look like a negative number, and thus cause us to
4217 * return a value that looks like an error, or overflow
4218 * back into positive territory, and thus cause us to
4219 * return a too-low count.
4221 * Therefore, if the packet count is unlimited, we clip
4222 * it at INT_MAX; this routine is not expected to
4223 * process packets indefinitely, so that's not an issue.
4225 if (PACKET_COUNT_IS_UNLIMITED(max_packets
))
4226 max_packets
= INT_MAX
;
4228 while (pkts
< max_packets
) {
4229 int packets_to_read
;
4231 if (handlep
->current_packet
== NULL
) {
4232 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4233 if (!packet_mmap_v3_acquire(h
.h3
))
4236 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4237 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4239 packets_to_read
= handlep
->packets_left
;
4241 if (packets_to_read
> (max_packets
- pkts
)) {
4243 * There are more packets in the buffer than
4244 * the number of packets we have left to
4245 * process to get up to the maximum number
4246 * of packets to process. Only process enough
4247 * of them to get us up to that maximum.
4249 packets_to_read
= max_packets
- pkts
;
4252 while (packets_to_read
-- && !handle
->break_loop
) {
4253 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4254 ret
= pcap_handle_packet_mmap(
4258 handlep
->current_packet
,
4261 tp3_hdr
->tp_snaplen
,
4263 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4264 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
4265 tp3_hdr
->hv1
.tp_vlan_tci
,
4266 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
4269 } else if (ret
< 0) {
4270 handlep
->current_packet
= NULL
;
4273 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4274 handlep
->packets_left
--;
4277 if (handlep
->packets_left
<= 0) {
4279 * Hand this block back to the kernel, and, if
4280 * we're counting blocks that need to be
4281 * filtered in userland after having been
4282 * filtered by the kernel, count the one we've
4285 packet_mmap_v3_release(h
.h3
);
4286 if (handlep
->blocks_to_filter_in_userland
> 0) {
4287 handlep
->blocks_to_filter_in_userland
--;
4288 if (handlep
->blocks_to_filter_in_userland
== 0) {
4290 * No more blocks need to be filtered
4293 handlep
->filter_in_userland
= 0;
4298 if (++handle
->offset
>= handle
->cc
)
4301 handlep
->current_packet
= NULL
;
4304 /* check for break loop condition*/
4305 if (handle
->break_loop
) {
4306 handle
->break_loop
= 0;
4307 return PCAP_ERROR_BREAK
;
4310 if (pkts
== 0 && handlep
->timeout
== 0) {
4311 /* Block until we see a packet. */
4316 #endif /* HAVE_TPACKET3 */
4319 * Attach the given BPF code to the packet capture device.
4322 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
4324 struct pcap_linux
*handlep
;
4325 struct sock_fprog fcode
;
4326 int can_filter_in_kernel
;
4333 pcap_strlcpy(handle
->errbuf
, "setfilter: No filter specified",
4338 handlep
= handle
->priv
;
4340 /* Make our private copy of the filter */
4342 if (pcap_install_bpf_program(handle
, filter
) < 0)
4343 /* pcap_install_bpf_program() filled in errbuf */
4347 * Run user level packet filter by default. Will be overridden if
4348 * installing a kernel filter succeeds.
4350 handlep
->filter_in_userland
= 1;
4352 /* Install kernel level filter if possible */
4355 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
4357 * fcode.len is an unsigned short for current kernel.
4358 * I have yet to see BPF-Code with that much
4359 * instructions but still it is possible. So for the
4360 * sake of correctness I added this check.
4362 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
4364 fcode
.filter
= NULL
;
4365 can_filter_in_kernel
= 0;
4367 #endif /* USHRT_MAX */
4370 * Oh joy, the Linux kernel uses struct sock_fprog instead
4371 * of struct bpf_program and of course the length field is
4372 * of different size. Pointed out by Sebastian
4374 * Oh, and we also need to fix it up so that all "ret"
4375 * instructions with non-zero operands have MAXIMUM_SNAPLEN
4376 * as the operand if we're not capturing in memory-mapped
4377 * mode, and so that, if we're in cooked mode, all memory-
4378 * reference instructions use special magic offsets in
4379 * references to the link-layer header and assume that the
4380 * link-layer payload begins at 0; "fix_program()" will do
4383 switch (fix_program(handle
, &fcode
)) {
4388 * Fatal error; just quit.
4389 * (The "default" case shouldn't happen; we
4390 * return -1 for that reason.)
4396 * The program performed checks that we can't make
4397 * work in the kernel.
4399 can_filter_in_kernel
= 0;
4404 * We have a filter that'll work in the kernel.
4406 can_filter_in_kernel
= 1;
4412 * NOTE: at this point, we've set both the "len" and "filter"
4413 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
4414 * those are the only members of the "sock_fprog" structure,
4415 * so we initialize every member of that structure.
4417 * If there is anything in "fcode" that is not initialized,
4418 * it is either a field added in a later kernel, or it's
4421 * If a new field is added, this code needs to be updated
4422 * to set it correctly.
4424 * If there are no other fields, then:
4426 * if the Linux kernel looks at the padding, it's
4429 * if the Linux kernel doesn't look at the padding,
4430 * then if some tool complains that we're passing
4431 * uninitialized data to the kernel, then the tool
4432 * is buggy and needs to understand that it's just
4435 if (can_filter_in_kernel
) {
4436 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
4439 * Installation succeeded - using kernel filter,
4440 * so userland filtering not needed.
4442 handlep
->filter_in_userland
= 0;
4444 else if (err
== -1) /* Non-fatal error */
4447 * Print a warning if we weren't able to install
4448 * the filter for a reason other than "this kernel
4449 * isn't configured to support socket filters.
4451 if (errno
== ENOMEM
) {
4453 * Either a kernel memory allocation
4454 * failure occurred, or there's too
4455 * much "other/option memory" allocated
4456 * for this socket. Suggest that they
4457 * increase the "other/option memory"
4461 "Warning: Couldn't allocate kernel memory for filter: try increasing net.core.optmem_max with sysctl\n");
4462 } else if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
4464 "Warning: Kernel filter failed: %s\n",
4465 pcap_strerror(errno
));
4471 * If we're not using the kernel filter, get rid of any kernel
4472 * filter that might've been there before, e.g. because the
4473 * previous filter could work in the kernel, or because some other
4474 * code attached a filter to the socket by some means other than
4475 * calling "pcap_setfilter()". Otherwise, the kernel filter may
4476 * filter out packets that would pass the new userland filter.
4478 if (handlep
->filter_in_userland
) {
4479 if (reset_kernel_filter(handle
) == -1) {
4480 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4481 PCAP_ERRBUF_SIZE
, errno
,
4482 "can't remove kernel filter");
4483 err
= -2; /* fatal error */
4488 * Free up the copy of the filter that was made by "fix_program()".
4490 if (fcode
.filter
!= NULL
)
4498 * If we're filtering in userland, there's nothing to do;
4499 * the new filter will be used for the next packet.
4501 if (handlep
->filter_in_userland
)
4505 * We're filtering in the kernel; the packets present in
4506 * all blocks currently in the ring were already filtered
4507 * by the old filter, and so will need to be filtered in
4508 * userland by the new filter.
4510 * Get an upper bound for the number of such blocks; first,
4511 * walk the ring backward and count the free blocks.
4513 offset
= handle
->offset
;
4515 offset
= handle
->cc
- 1;
4516 for (n
=0; n
< handle
->cc
; ++n
) {
4518 offset
= handle
->cc
- 1;
4519 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
4524 * If we found free blocks, decrement the count of free
4525 * blocks by 1, just in case we lost a race with another
4526 * thread of control that was adding a packet while
4527 * we were counting and that had run the filter before
4530 * XXX - could there be more than one block added in
4533 * XXX - is there a way to avoid that race, e.g. somehow
4534 * wait for all packets that passed the old filter to
4535 * be added to the ring?
4541 * Set the count of blocks worth of packets to filter
4542 * in userland to the total number of blocks in the
4543 * ring minus the number of free blocks we found, and
4544 * turn on userland filtering. (The count of blocks
4545 * worth of packets to filter in userland is guaranteed
4546 * not to be zero - n, above, couldn't be set to a
4547 * value > handle->cc, and if it were equal to
4548 * handle->cc, it wouldn't be zero, and thus would
4549 * be decremented to handle->cc - 1.)
4551 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4552 handlep
->filter_in_userland
= 1;
4558 * Return the index of the given device name. Fill ebuf and return
4562 iface_get_id(int fd
, const char *device
, char *ebuf
)
4566 memset(&ifr
, 0, sizeof(ifr
));
4567 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4569 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4570 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4571 errno
, "SIOCGIFINDEX");
4575 return ifr
.ifr_ifindex
;
4579 * Bind the socket associated with FD to the given device.
4580 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
4583 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
4585 struct sockaddr_ll sll
;
4587 socklen_t errlen
= sizeof(err
);
4589 memset(&sll
, 0, sizeof(sll
));
4590 sll
.sll_family
= AF_PACKET
;
4591 sll
.sll_ifindex
= ifindex
< 0 ? 0 : ifindex
;
4592 sll
.sll_protocol
= protocol
;
4594 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4595 if (errno
== ENETDOWN
) {
4597 * Return a "network down" indication, so that
4598 * the application can report that rather than
4599 * saying we had a mysterious failure and
4600 * suggest that they report a problem to the
4601 * libpcap developers.
4603 return PCAP_ERROR_IFACE_NOT_UP
;
4605 if (errno
== ENODEV
) {
4607 * There's nothing more to say, so clear the
4611 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
4614 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4620 /* Any pending errors, e.g., network is down? */
4622 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4623 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4624 errno
, "getsockopt (SO_ERROR)");
4628 if (err
== ENETDOWN
) {
4630 * Return a "network down" indication, so that
4631 * the application can report that rather than
4632 * saying we had a mysterious failure and
4633 * suggest that they report a problem to the
4634 * libpcap developers.
4636 return PCAP_ERROR_IFACE_NOT_UP
;
4637 } else if (err
> 0) {
4638 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4647 * Try to enter monitor mode.
4648 * If we have libnl, try to create a new monitor-mode device and
4649 * capture on that; otherwise, just say "not supported".
4653 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4655 struct pcap_linux
*handlep
= handle
->priv
;
4657 char phydev_path
[PATH_MAX
+1];
4658 struct nl80211_state nlstate
;
4663 * Is this a mac80211 device?
4665 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
4667 return ret
; /* error */
4669 return 0; /* no error, but not mac80211 device */
4672 * XXX - is this already a monN device?
4673 * If so, we're done.
4677 * OK, it's apparently a mac80211 device.
4678 * Try to find an unused monN device for it.
4680 ret
= nl80211_init(handle
, &nlstate
, device
);
4683 for (n
= 0; n
< UINT_MAX
; n
++) {
4687 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
4689 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
4690 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
4693 * Success. We don't clean up the libnl state
4694 * yet, as we'll be using it later.
4700 * Hard failure. Just return ret; handle->errbuf
4701 * has already been set.
4703 nl80211_cleanup(&nlstate
);
4708 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4709 "%s: No free monN interfaces", device
);
4710 nl80211_cleanup(&nlstate
);
4717 * Sleep for .1 seconds.
4720 delay
.tv_nsec
= 500000000;
4721 nanosleep(&delay
, NULL
);
4725 * If we haven't already done so, arrange to have
4726 * "pcap_close_all()" called when we exit.
4728 if (!pcap_do_addexit(handle
)) {
4730 * "atexit()" failed; don't put the interface
4731 * in rfmon mode, just give up.
4733 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
4734 handlep
->mondevice
);
4735 nl80211_cleanup(&nlstate
);
4740 * Now configure the monitor interface up.
4742 memset(&ifr
, 0, sizeof(ifr
));
4743 pcap_strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
4744 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4745 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4746 errno
, "%s: Can't get flags for %s", device
,
4747 handlep
->mondevice
);
4748 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
4749 handlep
->mondevice
);
4750 nl80211_cleanup(&nlstate
);
4753 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
4754 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4755 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4756 errno
, "%s: Can't set flags for %s", device
,
4757 handlep
->mondevice
);
4758 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
4759 handlep
->mondevice
);
4760 nl80211_cleanup(&nlstate
);
4765 * Success. Clean up the libnl state.
4767 nl80211_cleanup(&nlstate
);
4770 * Note that we have to delete the monitor device when we close
4773 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
4776 * Add this to the list of pcaps to close when we exit.
4778 pcap_add_to_pcaps_to_close(handle
);
4782 #else /* HAVE_LIBNL */
4784 enter_rfmon_mode(pcap_t
*handle _U_
, int sock_fd _U_
, const char *device _U_
)
4787 * We don't have libnl, so we can't do monitor mode.
4791 #endif /* HAVE_LIBNL */
4793 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4795 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
4797 static const struct {
4798 int soft_timestamping_val
;
4799 int pcap_tstamp_val
;
4800 } sof_ts_type_map
[3] = {
4801 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
4802 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
4803 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
4805 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
4808 * Set the list of time stamping types to include all types.
4811 iface_set_all_ts_types(pcap_t
*handle
, char *ebuf
)
4815 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
4816 if (handle
->tstamp_type_list
== NULL
) {
4817 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4821 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
4822 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
4823 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
4828 * Get a list of time stamp types.
4830 #ifdef ETHTOOL_GET_TS_INFO
4832 iface_get_ts_types(const char *device
, pcap_t
*handle
, char *ebuf
)
4836 struct ethtool_ts_info info
;
4841 * This doesn't apply to the "any" device; you can't say "turn on
4842 * hardware time stamping for all devices that exist now and arrange
4843 * that it be turned on for any device that appears in the future",
4844 * and not all devices even necessarily *support* hardware time
4845 * stamping, so don't report any time stamp types.
4847 if (strcmp(device
, "any") == 0) {
4848 handle
->tstamp_type_list
= NULL
;
4853 * Create a socket from which to fetch time stamping capabilities.
4855 fd
= get_if_ioctl_socket();
4857 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4858 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
4862 memset(&ifr
, 0, sizeof(ifr
));
4863 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4864 memset(&info
, 0, sizeof(info
));
4865 info
.cmd
= ETHTOOL_GET_TS_INFO
;
4866 ifr
.ifr_data
= (caddr_t
)&info
;
4867 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
4868 int save_errno
= errno
;
4871 switch (save_errno
) {
4876 * OK, this OS version or driver doesn't support
4877 * asking for the time stamping types, so let's
4878 * just return all the possible types.
4880 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
4886 * OK, no such device.
4887 * The user will find that out when they try to
4888 * activate the device; just return an empty
4889 * list of time stamp types.
4891 handle
->tstamp_type_list
= NULL
;
4898 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4900 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
4908 * Do we support hardware time stamping of *all* packets?
4910 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
4912 * No, so don't report any time stamp types.
4914 * XXX - some devices either don't report
4915 * HWTSTAMP_FILTER_ALL when they do support it, or
4916 * report HWTSTAMP_FILTER_ALL but map it to only
4917 * time stamping a few PTP packets. See
4918 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
4920 * Maybe that got fixed later.
4922 handle
->tstamp_type_list
= NULL
;
4927 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
4928 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
4931 if (num_ts_types
!= 0) {
4932 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
4933 if (handle
->tstamp_type_list
== NULL
) {
4934 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4938 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
4939 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
4940 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
4944 handle
->tstamp_type_count
= num_ts_types
;
4946 handle
->tstamp_type_list
= NULL
;
4950 #else /* ETHTOOL_GET_TS_INFO */
4952 iface_get_ts_types(const char *device
, pcap_t
*handle
, char *ebuf
)
4955 * This doesn't apply to the "any" device; you can't say "turn on
4956 * hardware time stamping for all devices that exist now and arrange
4957 * that it be turned on for any device that appears in the future",
4958 * and not all devices even necessarily *support* hardware time
4959 * stamping, so don't report any time stamp types.
4961 if (strcmp(device
, "any") == 0) {
4962 handle
->tstamp_type_list
= NULL
;
4967 * We don't have an ioctl to use to ask what's supported,
4968 * so say we support everything.
4970 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
4974 #endif /* ETHTOOL_GET_TS_INFO */
4975 #else /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
4977 iface_get_ts_types(const char *device _U_
, pcap_t
*p _U_
, char *ebuf _U_
)
4980 * Nothing to fetch, so it always "succeeds".
4984 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
4987 * Find out if we have any form of fragmentation/reassembly offloading.
4989 * We do so using SIOCETHTOOL checking for various types of offloading;
4990 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4991 * of the types of offloading, there's nothing we can do to check, so
4992 * we just say "no, we don't".
4994 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
4995 * indications that the operation isn't supported. We do EPERM
4996 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
4997 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
4998 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
4999 * and 3) does the "is this permitted" check before doing the "is
5000 * this even supported" check, so it fails with "this is not permitted"
5001 * rather than "this is not even supported". To work around this
5002 * annoyance, we only treat EPERM as an error for the first feature,
5003 * and assume that they all do the same permission checks, so if the
5004 * first one is allowed all the others are allowed if supported.
5006 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5008 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
,
5012 struct ethtool_value eval
;
5014 memset(&ifr
, 0, sizeof(ifr
));
5015 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
5018 ifr
.ifr_data
= (caddr_t
)&eval
;
5019 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5020 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
||
5021 (errno
== EPERM
&& eperm_ok
)) {
5023 * OK, let's just return 0, which, in our
5024 * case, either means "no, what we're asking
5025 * about is not enabled" or "all the flags
5026 * are clear (i.e., nothing is enabled)".
5030 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5031 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
5032 handle
->opt
.device
, cmdname
);
5039 * XXX - it's annoying that we have to check for offloading at all, but,
5040 * given that we have to, it's still annoying that we have to check for
5041 * particular types of offloading, especially that shiny new types of
5042 * offloading may be added - and, worse, may not be checkable with
5043 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
5044 * theory, give those to you, but the actual flags being used are
5045 * opaque (defined in a non-uapi header), and there doesn't seem to
5046 * be any obvious way to ask the kernel what all the offloading flags
5047 * are - at best, you can ask for a set of strings(!) to get *names*
5048 * for various flags. (That whole mechanism appears to have been
5049 * designed for the sole purpose of letting ethtool report flags
5050 * by name and set flags by name, with the names having no semantics
5051 * ethtool understands.)
5054 iface_get_offload(pcap_t
*handle
)
5059 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO", 0);
5063 return 1; /* TCP segmentation offloading on */
5068 * XXX - will this cause large unsegmented packets to be
5069 * handed to PF_PACKET sockets on transmission? If not,
5070 * this need not be checked.
5072 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO", 0);
5076 return 1; /* generic segmentation offloading on */
5079 #ifdef ETHTOOL_GFLAGS
5080 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS", 0);
5083 if (ret
& ETH_FLAG_LRO
)
5084 return 1; /* large receive offloading on */
5089 * XXX - will this cause large reassembled packets to be
5090 * handed to PF_PACKET sockets on receipt? If not,
5091 * this need not be checked.
5093 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO", 0);
5097 return 1; /* generic (large) receive offloading on */
5102 * Do this one last, as support for it was removed in later
5103 * kernels, and it fails with EPERM on those kernels rather
5104 * than with EOPNOTSUPP (see explanation in comment for
5105 * iface_ethtool_flag_ioctl()).
5107 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO", 1);
5111 return 1; /* UDP fragmentation offloading on */
5116 #else /* SIOCETHTOOL */
5118 iface_get_offload(pcap_t
*handle _U_
)
5121 * XXX - do we need to get this information if we don't
5122 * have the ethtool ioctls? If so, how do we do that?
5126 #endif /* SIOCETHTOOL */
5128 static struct dsa_proto
{
5130 bpf_u_int32 linktype
;
5133 * None is special and indicates that the interface does not have
5134 * any tagging protocol configured, and is therefore a standard
5135 * Ethernet interface.
5137 { "none", DLT_EN10MB
},
5138 { "brcm", DLT_DSA_TAG_BRCM
},
5139 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND
},
5140 { "dsa", DLT_DSA_TAG_DSA
},
5141 { "edsa", DLT_DSA_TAG_EDSA
},
5145 iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
)
5150 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
5151 * the tag *shouldn't* have some huge long name, and making
5152 * it smaller keeps newer versions of GCC from whining that
5153 * the error message if we don't support the tag could
5154 * overflow the error message buffer.
5160 fd
= asprintf(&pathstr
, "/sys/class/net/%s/dsa/tagging", device
);
5162 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5167 fd
= open(pathstr
, O_RDONLY
);
5170 * This is not fatal, kernel >= 4.20 *might* expose this attribute
5175 r
= read(fd
, buf
, sizeof(buf
) - 1);
5177 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5185 * Buffer should be LF terminated.
5187 if (buf
[r
- 1] == '\n')
5191 for (i
= 0; i
< sizeof(dsa_protos
) / sizeof(dsa_protos
[0]); i
++) {
5192 if (strlen(dsa_protos
[i
].name
) == (size_t)r
&&
5193 strcmp(buf
, dsa_protos
[i
].name
) == 0) {
5194 handle
->linktype
= dsa_protos
[i
].linktype
;
5195 switch (dsa_protos
[i
].linktype
) {
5204 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5205 "unsupported DSA tag: %s", buf
);
5211 * Query the kernel for the MTU of the given interface.
5214 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5219 return BIGGER_THAN_ALL_MTUS
;
5221 memset(&ifr
, 0, sizeof(ifr
));
5222 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5224 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5225 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5226 errno
, "SIOCGIFMTU");
5234 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5237 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5242 memset(&ifr
, 0, sizeof(ifr
));
5243 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5245 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5246 if (errno
== ENODEV
) {
5250 * There's nothing more to say, so clear
5251 * the error message.
5253 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5257 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5258 errno
, "SIOCGIFHWADDR");
5263 return ifr
.ifr_hwaddr
.sa_family
;
5267 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
5269 struct pcap_linux
*handlep
= handle
->priv
;
5272 register struct bpf_insn
*p
;
5277 * Make a copy of the filter, and modify that copy if
5280 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5281 len
= handle
->fcode
.bf_len
;
5282 f
= (struct bpf_insn
*)malloc(prog_size
);
5284 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5288 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5290 fcode
->filter
= (struct sock_filter
*) f
;
5292 for (i
= 0; i
< len
; ++i
) {
5295 * What type of instruction is this?
5297 switch (BPF_CLASS(p
->code
)) {
5302 * It's a load instruction; is it loading
5305 switch (BPF_MODE(p
->code
)) {
5311 * Yes; are we in cooked mode?
5313 if (handlep
->cooked
) {
5315 * Yes, so we need to fix this
5318 if (fix_offset(handle
, p
) < 0) {
5320 * We failed to do so.
5321 * Return 0, so our caller
5322 * knows to punt to userland.
5332 return 1; /* we succeeded */
5336 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
5339 * Existing references to auxiliary data shouldn't be adjusted.
5341 * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
5342 * we use >= and cast SKF_AD_OFF to unsigned.
5344 if (p
->k
>= (bpf_u_int32
)SKF_AD_OFF
)
5346 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5348 * What's the offset?
5350 if (p
->k
>= SLL2_HDR_LEN
) {
5352 * It's within the link-layer payload; that starts
5353 * at an offset of 0, as far as the kernel packet
5354 * filter is concerned, so subtract the length of
5355 * the link-layer header.
5357 p
->k
-= SLL2_HDR_LEN
;
5358 } else if (p
->k
== 0) {
5360 * It's the protocol field; map it to the
5361 * special magic kernel offset for that field.
5363 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5364 } else if (p
->k
== 4) {
5366 * It's the ifindex field; map it to the
5367 * special magic kernel offset for that field.
5369 p
->k
= SKF_AD_OFF
+ SKF_AD_IFINDEX
;
5370 } else if (p
->k
== 10) {
5372 * It's the packet type field; map it to the
5373 * special magic kernel offset for that field.
5375 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5376 } else if ((bpf_int32
)(p
->k
) > 0) {
5378 * It's within the header, but it's not one of
5379 * those fields; we can't do that in the kernel,
5380 * so punt to userland.
5386 * What's the offset?
5388 if (p
->k
>= SLL_HDR_LEN
) {
5390 * It's within the link-layer payload; that starts
5391 * at an offset of 0, as far as the kernel packet
5392 * filter is concerned, so subtract the length of
5393 * the link-layer header.
5395 p
->k
-= SLL_HDR_LEN
;
5396 } else if (p
->k
== 0) {
5398 * It's the packet type field; map it to the
5399 * special magic kernel offset for that field.
5401 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5402 } else if (p
->k
== 14) {
5404 * It's the protocol field; map it to the
5405 * special magic kernel offset for that field.
5407 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5408 } else if ((bpf_int32
)(p
->k
) > 0) {
5410 * It's within the header, but it's not one of
5411 * those fields; we can't do that in the kernel,
5412 * so punt to userland.
5421 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5423 int total_filter_on
= 0;
5429 * The socket filter code doesn't discard all packets queued
5430 * up on the socket when the filter is changed; this means
5431 * that packets that don't match the new filter may show up
5432 * after the new filter is put onto the socket, if those
5433 * packets haven't yet been read.
5435 * This means, for example, that if you do a tcpdump capture
5436 * with a filter, the first few packets in the capture might
5437 * be packets that wouldn't have passed the filter.
5439 * We therefore discard all packets queued up on the socket
5440 * when setting a kernel filter. (This isn't an issue for
5441 * userland filters, as the userland filtering is done after
5442 * packets are queued up.)
5444 * To flush those packets, we put the socket in read-only mode,
5445 * and read packets from the socket until there are no more to
5448 * In order to keep that from being an infinite loop - i.e.,
5449 * to keep more packets from arriving while we're draining
5450 * the queue - we put the "total filter", which is a filter
5451 * that rejects all packets, onto the socket before draining
5454 * This code deliberately ignores any errors, so that you may
5455 * get bogus packets if an error occurs, rather than having
5456 * the filtering done in userland even if it could have been
5457 * done in the kernel.
5459 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5460 &total_fcode
, sizeof(total_fcode
)) == 0) {
5464 * Note that we've put the total filter onto the socket.
5466 total_filter_on
= 1;
5469 * Save the socket's current mode, and put it in
5470 * non-blocking mode; we drain it by reading packets
5471 * until we get an error (which is normally a
5472 * "nothing more to be read" error).
5474 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5475 if (save_mode
== -1) {
5476 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5477 PCAP_ERRBUF_SIZE
, errno
,
5478 "can't get FD flags when changing filter");
5481 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
5482 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5483 PCAP_ERRBUF_SIZE
, errno
,
5484 "can't set nonblocking mode when changing filter");
5487 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
5490 if (save_errno
!= EAGAIN
) {
5494 * If we can't restore the mode or reset the
5495 * kernel filter, there's nothing we can do.
5497 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
5498 (void)reset_kernel_filter(handle
);
5499 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5500 PCAP_ERRBUF_SIZE
, save_errno
,
5501 "recv failed when changing filter");
5504 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
5505 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5506 PCAP_ERRBUF_SIZE
, errno
,
5507 "can't restore FD flags when changing filter");
5513 * Now attach the new filter.
5515 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5516 fcode
, sizeof(*fcode
));
5517 if (ret
== -1 && total_filter_on
) {
5519 * Well, we couldn't set that filter on the socket,
5520 * but we could set the total filter on the socket.
5522 * This could, for example, mean that the filter was
5523 * too big to put into the kernel, so we'll have to
5524 * filter in userland; in any case, we'll be doing
5525 * filtering in userland, so we need to remove the
5526 * total filter so we see packets.
5531 * If this fails, we're really screwed; we have the
5532 * total filter on the socket, and it won't come off.
5533 * Report it as a fatal error.
5535 if (reset_kernel_filter(handle
) == -1) {
5536 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5537 PCAP_ERRBUF_SIZE
, errno
,
5538 "can't remove kernel total filter");
5539 return -2; /* fatal error */
5548 reset_kernel_filter(pcap_t
*handle
)
5552 * setsockopt() barfs unless it get a dummy parameter.
5553 * valgrind whines unless the value is initialized,
5554 * as it has no idea that setsockopt() ignores its
5559 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5560 &dummy
, sizeof(dummy
));
5562 * Ignore ENOENT - it means "we don't have a filter", so there
5563 * was no filter to remove, and there's still no filter.
5565 * Also ignore ENONET, as a lot of kernel versions had a
5566 * typo where ENONET, rather than ENOENT, was returned.
5568 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
5574 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
5576 if (pcap_check_activated(p
))
5577 return (PCAP_ERROR_ACTIVATED
);
5578 p
->opt
.protocol
= protocol
;
5583 * Libpcap version string.
5586 pcap_lib_version(void)
5588 #if defined(HAVE_TPACKET3)
5589 return (PCAP_VERSION_STRING
" (with TPACKET_V3)");
5591 return (PCAP_VERSION_STRING
" (with TPACKET_V2)");