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 activate_pf_packet(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 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
323 static int iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
,
326 static int iface_get_offload(pcap_t
*handle
);
328 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
329 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
330 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
331 static int reset_kernel_filter(pcap_t
*handle
);
333 static struct sock_filter total_insn
334 = BPF_STMT(BPF_RET
| BPF_K
, 0);
335 static struct sock_fprog total_fcode
336 = { 1, &total_insn
};
338 static int iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
);
341 pcap_create_interface(const char *device
, char *ebuf
)
345 handle
= PCAP_CREATE_COMMON(ebuf
, struct pcap_linux
);
349 handle
->activate_op
= pcap_activate_linux
;
350 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
352 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
354 * See what time stamp types we support.
356 if (iface_ethtool_get_ts_info(device
, handle
, ebuf
) == -1) {
363 * We claim that we support microsecond and nanosecond time
366 * XXX - with adapter-supplied time stamps, can we choose
367 * microsecond or nanosecond time stamps on arbitrary
370 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
371 if (handle
->tstamp_precision_list
== NULL
) {
372 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
377 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
378 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
379 handle
->tstamp_precision_count
= 2;
381 struct pcap_linux
*handlep
= handle
->priv
;
382 handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
);
389 * If interface {if_name} is a mac80211 driver, the file
390 * /sys/class/net/{if_name}/phy80211 is a symlink to
391 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
393 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
394 * least, has a "wmaster0" device and a "wlan0" device; the
395 * latter is the one with the IP address. Both show up in
396 * "tcpdump -D" output. Capturing on the wmaster0 device
397 * captures with 802.11 headers.
399 * airmon-ng searches through /sys/class/net for devices named
400 * monN, starting with mon0; as soon as one *doesn't* exist,
401 * it chooses that as the monitor device name. If the "iw"
402 * command exists, it does
404 * iw dev {if_name} interface add {monif_name} type monitor
406 * where {monif_name} is the monitor device. It then (sigh) sleeps
407 * .1 second, and then configures the device up. Otherwise, if
408 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
409 * {mondev_name}, without a newline, to that file, and again (sigh)
410 * sleeps .1 second, and then iwconfig's that device into monitor
411 * mode and configures it up. Otherwise, you can't do monitor mode.
413 * All these devices are "glued" together by having the
414 * /sys/class/net/{if_name}/phy80211 links pointing to the same
415 * place, so, given a wmaster, wlan, or mon device, you can
416 * find the other devices by looking for devices with
417 * the same phy80211 link.
419 * To turn monitor mode off, delete the monitor interface,
422 * iw dev {monif_name} interface del
424 * or by sending {monif_name}, with no NL, down
425 * /sys/class/ieee80211/{phydev_name}/remove_iface
427 * Note: if you try to create a monitor device named "monN", and
428 * there's already a "monN" device, it fails, as least with
429 * the netlink interface (which is what iw uses), with a return
430 * value of -ENFILE. (Return values are negative errnos.) We
431 * could probably use that to find an unused device.
433 * Yes, you can have multiple monitor devices for a given
438 * Is this a mac80211 device? If so, fill in the physical device path and
439 * return 1; if not, return 0. On an error, fill in handle->errbuf and
443 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
444 size_t phydev_max_pathlen
)
450 * Generate the path string for the symlink to the physical device.
452 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
453 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
454 "%s: Can't generate path name string for /sys/class/net device",
458 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
459 if (bytes_read
== -1) {
460 if (errno
== ENOENT
|| errno
== EINVAL
) {
462 * Doesn't exist, or not a symlink; assume that
463 * means it's not a mac80211 device.
468 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
469 errno
, "%s: Can't readlink %s", device
, pathstr
);
474 phydev_path
[bytes_read
] = '\0';
478 struct nl80211_state
{
479 struct nl_sock
*nl_sock
;
480 struct nl_cache
*nl_cache
;
481 struct genl_family
*nl80211
;
485 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
489 state
->nl_sock
= nl_socket_alloc();
490 if (!state
->nl_sock
) {
491 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
492 "%s: failed to allocate netlink handle", device
);
496 if (genl_connect(state
->nl_sock
)) {
497 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
498 "%s: failed to connect to generic netlink", device
);
499 goto out_handle_destroy
;
502 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
504 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
505 "%s: failed to allocate generic netlink cache: %s",
506 device
, nl_geterror(-err
));
507 goto out_handle_destroy
;
510 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
511 if (!state
->nl80211
) {
512 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
513 "%s: nl80211 not found", device
);
520 nl_cache_free(state
->nl_cache
);
522 nl_socket_free(state
->nl_sock
);
527 nl80211_cleanup(struct nl80211_state
*state
)
529 genl_family_put(state
->nl80211
);
530 nl_cache_free(state
->nl_cache
);
531 nl_socket_free(state
->nl_sock
);
535 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
536 const char *device
, const char *mondevice
);
539 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
540 const char *device
, const char *mondevice
)
542 struct pcap_linux
*handlep
= handle
->priv
;
547 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
553 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
554 "%s: failed to allocate netlink msg", device
);
558 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
559 0, NL80211_CMD_NEW_INTERFACE
, 0);
560 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
562 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
564 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
566 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
568 if (err
== -NLE_FAILURE
) {
570 * Device not available; our caller should just
571 * keep trying. (libnl 2.x maps ENFILE to
572 * NLE_FAILURE; it can also map other errors
573 * to that, but there's not much we can do
580 * Real failure, not just "that device is not
583 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
584 "%s: nl_send_auto_complete failed adding %s interface: %s",
585 device
, mondevice
, nl_geterror(-err
));
590 err
= nl_wait_for_ack(state
->nl_sock
);
592 if (err
== -NLE_FAILURE
) {
594 * Device not available; our caller should just
595 * keep trying. (libnl 2.x maps ENFILE to
596 * NLE_FAILURE; it can also map other errors
597 * to that, but there's not much we can do
604 * Real failure, not just "that device is not
607 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
608 "%s: nl_wait_for_ack failed adding %s interface: %s",
609 device
, mondevice
, nl_geterror(-err
));
621 * Try to remember the monitor device.
623 handlep
->mondevice
= strdup(mondevice
);
624 if (handlep
->mondevice
== NULL
) {
625 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
628 * Get rid of the monitor device.
630 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
636 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
637 "%s: nl_put failed adding %s interface",
644 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
645 const char *device
, const char *mondevice
)
651 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
657 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
658 "%s: failed to allocate netlink msg", device
);
662 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
663 0, NL80211_CMD_DEL_INTERFACE
, 0);
664 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
666 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
668 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
669 "%s: nl_send_auto_complete failed deleting %s interface: %s",
670 device
, mondevice
, nl_geterror(-err
));
674 err
= nl_wait_for_ack(state
->nl_sock
);
676 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
677 "%s: nl_wait_for_ack failed adding %s interface: %s",
678 device
, mondevice
, nl_geterror(-err
));
690 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
691 "%s: nl_put failed deleting %s interface",
696 #endif /* HAVE_LIBNL */
698 static int pcap_protocol(pcap_t
*handle
)
702 protocol
= handle
->opt
.protocol
;
704 protocol
= ETH_P_ALL
;
706 return htons(protocol
);
710 pcap_can_set_rfmon_linux(pcap_t
*handle
)
713 char phydev_path
[PATH_MAX
+1];
717 if (strcmp(handle
->opt
.device
, "any") == 0) {
719 * Monitor mode makes no sense on the "any" device.
726 * Bleah. There doesn't seem to be a way to ask a mac80211
727 * device, through libnl, whether it supports monitor mode;
728 * we'll just check whether the device appears to be a
729 * mac80211 device and, if so, assume the device supports
732 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
735 return ret
; /* error */
737 return 1; /* mac80211 device */
744 * Grabs the number of missed packets by the interface from
745 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
747 * Compared to /proc/net/dev this avoids counting software drops,
748 * but may be unimplemented and just return 0.
749 * The author has found no straigthforward way to check for support.
752 linux_get_stat(const char * if_name
, const char * stat
) {
755 char buffer
[PATH_MAX
];
757 snprintf(buffer
, sizeof(buffer
), "/sys/class/net/%s/statistics/%s", if_name
, stat
);
758 fd
= open(buffer
, O_RDONLY
);
762 bytes_read
= read(fd
, buffer
, sizeof(buffer
) - 1);
764 if (bytes_read
== -1)
766 buffer
[bytes_read
] = '\0';
768 return strtoll(buffer
, NULL
, 10);
772 linux_if_drops(const char * if_name
)
774 long long int missed
= linux_get_stat(if_name
, "rx_missed_errors");
775 long long int fifo
= linux_get_stat(if_name
, "rx_fifo_errors");
776 return missed
+ fifo
;
781 * Monitor mode is kind of interesting because we have to reset the
782 * interface before exiting. The problem can't really be solved without
783 * some daemon taking care of managing usage counts. If we put the
784 * interface into monitor mode, we set a flag indicating that we must
785 * take it out of that mode when the interface is closed, and, when
786 * closing the interface, if that flag is set we take it out of monitor
790 static void pcap_cleanup_linux( pcap_t
*handle
)
792 struct pcap_linux
*handlep
= handle
->priv
;
794 struct nl80211_state nlstate
;
796 #endif /* HAVE_LIBNL */
798 if (handlep
->must_do_on_close
!= 0) {
800 * There's something we have to do when closing this
804 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
805 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
807 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
808 handlep
->device
, handlep
->mondevice
);
809 nl80211_cleanup(&nlstate
);
813 "Can't delete monitor interface %s (%s).\n"
814 "Please delete manually.\n",
815 handlep
->mondevice
, handle
->errbuf
);
818 #endif /* HAVE_LIBNL */
821 * Take this pcap out of the list of pcaps for which we
822 * have to take the interface out of some mode.
824 pcap_remove_from_pcaps_to_close(handle
);
827 if (handle
->fd
!= -1) {
829 * Destroy the ring buffer (assuming we've set it up),
830 * and unmap it if it's mapped.
832 destroy_ring(handle
);
835 if (handlep
->oneshot_buffer
!= NULL
) {
836 free(handlep
->oneshot_buffer
);
837 handlep
->oneshot_buffer
= NULL
;
840 if (handlep
->mondevice
!= NULL
) {
841 free(handlep
->mondevice
);
842 handlep
->mondevice
= NULL
;
844 if (handlep
->device
!= NULL
) {
845 free(handlep
->device
);
846 handlep
->device
= NULL
;
849 close(handlep
->poll_breakloop_fd
);
850 pcap_cleanup_live_common(handle
);
855 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
856 * around which we have to work. Determine if we have those
858 * 3.19 is the first release with a fixed version of
859 * TPACKET_V3. We treat anything before that as
860 * not having a fixed version; that may really mean
861 * it has *no* version.
863 static int has_broken_tpacket_v3(void)
865 struct utsname utsname
;
870 /* No version information, assume broken. */
871 if (uname(&utsname
) == -1)
873 release
= utsname
.release
;
875 /* A malformed version, ditto. */
876 matches
= sscanf(release
, "%ld.%ld%n", &major
, &minor
, &verlen
);
879 if (release
[verlen
] != '.' && release
[verlen
] != '\0')
882 /* OK, a fixed version. */
883 if (major
> 3 || (major
== 3 && minor
>= 19))
892 * Set the timeout to be used in poll() with memory-mapped packet capture.
895 set_poll_timeout(struct pcap_linux
*handlep
)
898 int broken_tpacket_v3
= has_broken_tpacket_v3();
900 if (handlep
->timeout
== 0) {
903 * XXX - due to a set of (mis)features in the TPACKET_V3
904 * kernel code prior to the 3.19 kernel, blocking forever
905 * with a TPACKET_V3 socket can, if few packets are
906 * arriving and passing the socket filter, cause most
907 * packets to be dropped. See libpcap issue #335 for the
908 * full painful story.
910 * The workaround is to have poll() time out very quickly,
911 * so we grab the frames handed to us, and return them to
914 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
915 handlep
->poll_timeout
= 1; /* don't block for very long */
918 handlep
->poll_timeout
= -1; /* block forever */
919 } else if (handlep
->timeout
> 0) {
922 * For TPACKET_V3, the timeout is handled by the kernel,
923 * so block forever; that way, we don't get extra timeouts.
924 * Don't do that if we have a broken TPACKET_V3, though.
926 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
927 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
930 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
933 * Non-blocking mode; we call poll() to pick up error
934 * indications, but we don't want it to wait for
937 handlep
->poll_timeout
= 0;
941 static void pcap_breakloop_linux(pcap_t
*handle
)
943 pcap_breakloop_common(handle
);
944 struct pcap_linux
*handlep
= handle
->priv
;
947 /* XXX - what if this fails? */
948 (void)write(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
952 * Get a handle for a live capture from the given device. You can
953 * pass NULL as device to get all packages (without link level
954 * information of course). If you pass 1 as promisc the interface
955 * will be set to promiscuous mode (XXX: I think this usage should
956 * be deprecated and functions be added to select that later allow
957 * modification of that values -- Torsten).
960 pcap_activate_linux(pcap_t
*handle
)
962 struct pcap_linux
*handlep
= handle
->priv
;
970 device
= handle
->opt
.device
;
973 * Make sure the name we were handed will fit into the ioctls we
974 * might perform on the device; if not, return a "No such device"
975 * indication, as the Linux kernel shouldn't support creating
976 * a device whose name won't fit into those ioctls.
978 * "Will fit" means "will fit, complete with a null terminator",
979 * so if the length, which does *not* include the null terminator,
980 * is greater than *or equal to* the size of the field into which
981 * we'll be copying it, that won't fit.
983 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
984 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
989 * Turn a negative snapshot value (invalid), a snapshot value of
990 * 0 (unspecified), or a value bigger than the normal maximum
991 * value, into the maximum allowed value.
993 * If some application really *needs* a bigger snapshot
994 * length, we should just increase MAXIMUM_SNAPLEN.
996 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
997 handle
->snapshot
= MAXIMUM_SNAPLEN
;
999 handlep
->device
= strdup(device
);
1000 if (handlep
->device
== NULL
) {
1001 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1003 status
= PCAP_ERROR
;
1008 * The "any" device is a special device which causes us not
1009 * to bind to a particular device and thus to look at all
1012 is_any_device
= (strcmp(device
, "any") == 0);
1013 if (is_any_device
) {
1014 if (handle
->opt
.promisc
) {
1015 handle
->opt
.promisc
= 0;
1016 /* Just a warning. */
1017 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1018 "Promiscuous mode not supported on the \"any\" device");
1019 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1023 /* copy timeout value */
1024 handlep
->timeout
= handle
->opt
.timeout
;
1027 * If we're in promiscuous mode, then we probably want
1028 * to see when the interface drops packets too, so get an
1029 * initial count from
1030 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1032 if (handle
->opt
.promisc
)
1033 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1036 * If the "any" device is specified, try to open a SOCK_DGRAM.
1037 * Otherwise, open a SOCK_RAW.
1039 ret
= activate_pf_packet(handle
, is_any_device
);
1042 * Fatal error; the return value is the error code,
1043 * and handle->errbuf has been set to an appropriate
1051 * Try to set up memory-mapped access.
1053 ret
= setup_mmapped(handle
, &status
);
1056 * We failed to set up to use it, or the
1057 * kernel supports it, but we failed to
1058 * enable it. status has been set to the
1059 * error status to return and, if it's
1060 * PCAP_ERROR, handle->errbuf contains
1061 * the error message.
1067 * We succeeded. status has been set to the status to return,
1068 * which might be 0, or might be a PCAP_WARNING_ value.
1071 * Now that we have activated the mmap ring, we can
1072 * set the correct protocol.
1074 if ((status2
= iface_bind(handle
->fd
, handlep
->ifindex
,
1075 handle
->errbuf
, pcap_protocol(handle
))) != 0) {
1080 handle
->inject_op
= pcap_inject_linux
;
1081 handle
->setfilter_op
= pcap_setfilter_linux
;
1082 handle
->setdirection_op
= pcap_setdirection_linux
;
1083 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1084 handle
->setnonblock_op
= pcap_setnonblock_linux
;
1085 handle
->getnonblock_op
= pcap_getnonblock_linux
;
1086 handle
->cleanup_op
= pcap_cleanup_linux
;
1087 handle
->stats_op
= pcap_stats_linux
;
1088 handle
->breakloop_op
= pcap_breakloop_linux
;
1090 switch (handlep
->tp_version
) {
1093 handle
->read_op
= pcap_read_linux_mmap_v2
;
1095 #ifdef HAVE_TPACKET3
1097 handle
->read_op
= pcap_read_linux_mmap_v3
;
1101 handle
->oneshot_callback
= pcap_oneshot_linux
;
1102 handle
->selectable_fd
= handle
->fd
;
1107 pcap_cleanup_linux(handle
);
1112 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1114 handle
->linktype
= dlt
;
1119 * linux_check_direction()
1121 * Do checks based on packet direction.
1124 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1126 struct pcap_linux
*handlep
= handle
->priv
;
1128 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1131 * If this is from the loopback device, reject it;
1132 * we'll see the packet as an incoming packet as well,
1133 * and we don't want to see it twice.
1135 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1139 * If this is an outgoing CAN or CAN FD frame, and
1140 * the user doesn't only want outgoing packets,
1141 * reject it; CAN devices and drivers, and the CAN
1142 * stack, always arrange to loop back transmitted
1143 * packets, so they also appear as incoming packets.
1144 * We don't want duplicate packets, and we can't
1145 * easily distinguish packets looped back by the CAN
1146 * layer than those received by the CAN layer, so we
1147 * eliminate this packet instead.
1149 * We check whether this is a CAN or CAN FD frame
1150 * by checking whether the device's hardware type
1153 if (sll
->sll_hatype
== ARPHRD_CAN
&&
1154 handle
->direction
!= PCAP_D_OUT
)
1158 * If the user only wants incoming packets, reject it.
1160 if (handle
->direction
== PCAP_D_IN
)
1165 * If the user only wants outgoing packets, reject it.
1167 if (handle
->direction
== PCAP_D_OUT
)
1174 * Check whether the device to which the pcap_t is bound still exists.
1175 * We do so by asking what address the socket is bound to, and checking
1176 * whether the ifindex in the address is -1, meaning "that device is gone",
1177 * or some other value, meaning "that device still exists".
1180 device_still_exists(pcap_t
*handle
)
1182 struct pcap_linux
*handlep
= handle
->priv
;
1183 struct sockaddr_ll addr
;
1187 * If handlep->ifindex is -1, the socket isn't bound, meaning
1188 * we're capturing on the "any" device; that device never
1189 * disappears. (It should also never be configured down, so
1190 * we shouldn't even get here, but let's make sure.)
1192 if (handlep
->ifindex
== -1)
1193 return (1); /* it's still here */
1196 * OK, now try to get the address for the socket.
1198 addr_len
= sizeof (addr
);
1199 if (getsockname(handle
->fd
, (struct sockaddr
*) &addr
, &addr_len
) == -1) {
1201 * Error - report an error and return -1.
1203 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1204 errno
, "getsockname failed");
1207 if (addr
.sll_ifindex
== -1) {
1209 * This means the device went away.
1215 * The device presumably just went down.
1221 pcap_inject_linux(pcap_t
*handle
, const void *buf
, int size
)
1223 struct pcap_linux
*handlep
= handle
->priv
;
1226 if (handlep
->ifindex
== -1) {
1228 * We don't support sending on the "any" device.
1230 pcap_strlcpy(handle
->errbuf
,
1231 "Sending packets isn't supported on the \"any\" device",
1236 if (handlep
->cooked
) {
1238 * We don't support sending on cooked-mode sockets.
1240 * XXX - how do you send on a bound cooked-mode
1242 * Is a "sendto()" required there?
1244 pcap_strlcpy(handle
->errbuf
,
1245 "Sending packets isn't supported in cooked mode",
1250 ret
= (int)send(handle
->fd
, buf
, size
, 0);
1252 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1260 * Get the statistics for the given packet capture handle.
1263 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1265 struct pcap_linux
*handlep
= handle
->priv
;
1266 #ifdef HAVE_TPACKET3
1268 * For sockets using TPACKET_V2, the extra stuff at the end
1269 * of a struct tpacket_stats_v3 will not be filled in, and
1270 * we don't look at it so this is OK even for those sockets.
1271 * In addition, the PF_PACKET socket code in the kernel only
1272 * uses the length parameter to compute how much data to
1273 * copy out and to indicate how much data was copied out, so
1274 * it's OK to base it on the size of a struct tpacket_stats.
1276 * XXX - it's probably OK, in fact, to just use a
1277 * struct tpacket_stats for V3 sockets, as we don't
1278 * care about the tp_freeze_q_cnt stat.
1280 struct tpacket_stats_v3 kstats
;
1281 #else /* HAVE_TPACKET3 */
1282 struct tpacket_stats kstats
;
1283 #endif /* HAVE_TPACKET3 */
1284 socklen_t len
= sizeof (struct tpacket_stats
);
1286 long long if_dropped
= 0;
1289 * To fill in ps_ifdrop, we parse
1290 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1293 if (handle
->opt
.promisc
)
1296 * XXX - is there any reason to do this by remembering
1297 * the last counts value, subtracting it from the
1298 * current counts value, and adding that to stat.ps_ifdrop,
1299 * maintaining stat.ps_ifdrop as a count, rather than just
1300 * saving the *initial* counts value and setting
1301 * stat.ps_ifdrop to the difference between the current
1302 * value and the initial value?
1304 * One reason might be to handle the count wrapping
1305 * around, on platforms where the count is 32 bits
1306 * and where you might get more than 2^32 dropped
1307 * packets; is there any other reason?
1309 * (We maintain the count as a long long int so that,
1310 * if the kernel maintains the counts as 64-bit even
1311 * on 32-bit platforms, we can handle the real count.
1313 * Unfortunately, we can't report 64-bit counts; we
1314 * need a better API for reporting statistics, such as
1315 * one that reports them in a style similar to the
1316 * pcapng Interface Statistics Block, so that 1) the
1317 * counts are 64-bit, 2) it's easier to add new statistics
1318 * without breaking the ABI, and 3) it's easier to
1319 * indicate to a caller that wants one particular
1320 * statistic that it's not available by just not supplying
1323 if_dropped
= handlep
->sysfs_dropped
;
1324 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1325 handlep
->stat
.ps_ifdrop
+= (u_int
)(handlep
->sysfs_dropped
- if_dropped
);
1329 * Try to get the packet counts from the kernel.
1331 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1332 &kstats
, &len
) > -1) {
1334 * "ps_recv" counts only packets that *passed* the
1335 * filter, not packets that didn't pass the filter.
1336 * This includes packets later dropped because we
1337 * ran out of buffer space.
1339 * "ps_drop" counts packets dropped because we ran
1340 * out of buffer space. It doesn't count packets
1341 * dropped by the interface driver. It counts only
1342 * packets that passed the filter.
1344 * See above for ps_ifdrop.
1346 * Both statistics include packets not yet read from
1347 * the kernel by libpcap, and thus not yet seen by
1350 * In "linux/net/packet/af_packet.c", at least in 2.6.27
1351 * through 5.6 kernels, "tp_packets" is incremented for
1352 * every packet that passes the packet filter *and* is
1353 * successfully copied to the ring buffer; "tp_drops" is
1354 * incremented for every packet dropped because there's
1355 * not enough free space in the ring buffer.
1357 * When the statistics are returned for a PACKET_STATISTICS
1358 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1359 * so that "tp_packets" counts all packets handed to
1360 * the PF_PACKET socket, including packets dropped because
1361 * there wasn't room on the socket buffer - but not
1362 * including packets that didn't pass the filter.
1364 * In the BSD BPF, the count of received packets is
1365 * incremented for every packet handed to BPF, regardless
1366 * of whether it passed the filter.
1368 * We can't make "pcap_stats()" work the same on both
1369 * platforms, but the best approximation is to return
1370 * "tp_packets" as the count of packets and "tp_drops"
1371 * as the count of drops.
1373 * Keep a running total because each call to
1374 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1375 * resets the counters to zero.
1377 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1378 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1379 *stats
= handlep
->stat
;
1383 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1384 "failed to get statistics from socket");
1389 * Description string for the "any" device.
1391 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1394 * A PF_PACKET socket can be bound to any network interface.
1397 can_be_bound(const char *name _U_
)
1403 * Get a socket to use with various interface ioctls.
1406 get_if_ioctl_socket(void)
1411 * This is a bit ugly.
1413 * There isn't a socket type that's guaranteed to work.
1415 * AF_NETLINK will work *if* you have Netlink configured into the
1416 * kernel (can it be configured out if you have any networking
1417 * support at all?) *and* if you're running a sufficiently recent
1418 * kernel, but not all the kernels we support are sufficiently
1419 * recent - that feature was introduced in Linux 4.6.
1421 * AF_UNIX will work *if* you have UNIX-domain sockets configured
1422 * into the kernel and *if* you're not on a system that doesn't
1423 * allow them - some SELinux systems don't allow you create them.
1424 * Most systems probably have them configured in, but not all systems
1425 * have them configured in and allow them to be created.
1427 * AF_INET will work *if* you have IPv4 configured into the kernel,
1428 * but, apparently, some systems have network adapters but have
1429 * kernels without IPv4 support.
1431 * AF_INET6 will work *if* you have IPv6 configured into the
1432 * kernel, but if you don't have AF_INET, you might not have
1433 * AF_INET6, either (that is, independently on its own grounds).
1435 * AF_PACKET would work, except that some of these calls should
1436 * work even if you *don't* have capture permission (you should be
1437 * able to enumerate interfaces and get information about them
1438 * without capture permission; you shouldn't get a failure until
1439 * you try pcap_activate()). (If you don't allow programs to
1440 * get as much information as possible about interfaces if you
1441 * don't have permission to capture, you run the risk of users
1442 * asking "why isn't it showing XXX" - or, worse, if you don't
1443 * show interfaces *at all* if you don't have permission to
1444 * capture on them, "why do no interfaces show up?" - when the
1445 * real problem is a permissions problem. Error reports of that
1446 * type require a lot more back-and-forth to debug, as evidenced
1447 * by many Wireshark bugs/mailing list questions/Q&A questoins.)
1451 * we first try an AF_NETLINK socket, where "try" includes
1452 * "try to do a device ioctl on it", as, in the future, once
1453 * pre-4.6 kernels are sufficiently rare, that will probably
1454 * be the mechanism most likely to work;
1456 * if that fails, we try an AF_UNIX socket, as that's less
1457 * likely to be configured out on a networking-capable system
1460 * if that fails, we try an AF_INET6 socket;
1462 * if that fails, we try an AF_INET socket.
1464 fd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_GENERIC
);
1467 * OK, let's make sure we can do an SIOCGIFNAME
1472 memset(&ifr
, 0, sizeof(ifr
));
1473 if (ioctl(fd
, SIOCGIFNAME
, &ifr
) == 0 ||
1474 errno
!= EOPNOTSUPP
) {
1476 * It succeeded, or failed for some reason
1477 * other than "netlink sockets don't support
1478 * device ioctls". Go with the AF_NETLINK
1485 * OK, that didn't work, so it's as bad as "netlink
1486 * sockets aren't available". Close the socket and
1493 * Now try an AF_UNIX socket.
1495 fd
= socket(AF_UNIX
, SOCK_RAW
, 0);
1504 * Now try an AF_INET6 socket.
1506 fd
= socket(AF_INET6
, SOCK_DGRAM
, 0);
1512 * Now try an AF_INET socket.
1514 * XXX - if that fails, is there anything else we should try?
1515 * AF_CAN, for embedded systems in vehicles, in case they're
1516 * built without Internet protocol support? Any other socket
1517 * types popular in non-Internet embedded systems?
1519 return (socket(AF_INET
, SOCK_DGRAM
, 0));
1523 * Get additional flags for a device, using SIOCGIFMEDIA.
1526 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1530 unsigned int arptype
;
1532 struct ethtool_value info
;
1534 if (*flags
& PCAP_IF_LOOPBACK
) {
1536 * Loopback devices aren't wireless, and "connected"/
1537 * "disconnected" doesn't apply to them.
1539 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1543 sock
= get_if_ioctl_socket();
1545 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1546 "Can't create socket to get ethtool information for %s",
1552 * OK, what type of network is this?
1553 * In particular, is it wired or wireless?
1555 if (is_wifi(name
)) {
1557 * Wi-Fi, hence wireless.
1559 *flags
|= PCAP_IF_WIRELESS
;
1562 * OK, what does /sys/class/net/{if_name}/type contain?
1563 * (We don't use that for Wi-Fi, as it'll report
1564 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
1569 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
1570 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1571 "%s: Can't generate path name string for /sys/class/net device",
1576 fh
= fopen(pathstr
, "r");
1578 if (fscanf(fh
, "%u", &arptype
) == 1) {
1580 * OK, we got an ARPHRD_ type; what is it?
1584 case ARPHRD_LOOPBACK
:
1586 * These are types to which
1587 * "connected" and "disconnected"
1588 * don't apply, so don't bother
1591 * XXX - add other types?
1599 case ARPHRD_IEEE80211
:
1600 case ARPHRD_IEEE80211_PRISM
:
1601 case ARPHRD_IEEE80211_RADIOTAP
:
1602 #ifdef ARPHRD_IEEE802154
1603 case ARPHRD_IEEE802154
:
1605 #ifdef ARPHRD_IEEE802154_MONITOR
1606 case ARPHRD_IEEE802154_MONITOR
:
1608 #ifdef ARPHRD_6LOWPAN
1609 case ARPHRD_6LOWPAN
:
1612 * Various wireless types.
1614 *flags
|= PCAP_IF_WIRELESS
;
1623 #ifdef ETHTOOL_GLINK
1624 memset(&ifr
, 0, sizeof(ifr
));
1625 pcap_strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
1626 info
.cmd
= ETHTOOL_GLINK
;
1628 * XXX - while Valgrind handles SIOCETHTOOL and knows that
1629 * the ETHTOOL_GLINK command sets the .data member of the
1630 * structure, Memory Sanitizer doesn't yet do so:
1632 * https://bugs.llvm.org/show_bug.cgi?id=45814
1634 * For now, we zero it out to squelch warnings; if the bug
1635 * in question is fixed, we can remove this.
1638 ifr
.ifr_data
= (caddr_t
)&info
;
1639 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
1640 int save_errno
= errno
;
1642 switch (save_errno
) {
1647 * OK, this OS version or driver doesn't support
1648 * asking for this information.
1649 * XXX - distinguish between "this doesn't
1650 * support ethtool at all because it's not
1651 * that type of device" vs. "this doesn't
1652 * support ethtool even though it's that
1653 * type of device", and return "unknown".
1655 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1661 * OK, no such device.
1662 * The user will find that out when they try to
1663 * activate the device; just say "OK" and
1664 * don't set anything.
1673 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1675 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
1689 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1692 * It's disconnected.
1694 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1703 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1706 * Get the list of regular interfaces first.
1708 if (pcap_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
1709 get_if_flags
) == -1)
1710 return (-1); /* failure */
1713 * Add the "any" device.
1714 * As it refers to all network devices, not to any particular
1715 * network device, the notion of "connected" vs. "disconnected"
1718 if (add_dev(devlistp
, "any",
1719 PCAP_IF_UP
|PCAP_IF_RUNNING
|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
1720 any_descr
, errbuf
) == NULL
)
1727 * Set direction flag: Which packets do we accept on a forwarding
1728 * single device? IN, OUT or both?
1731 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1734 * It's guaranteed, at this point, that d is a valid
1737 handle
->direction
= d
;
1742 is_wifi(const char *device
)
1748 * See if there's a sysfs wireless directory for it.
1749 * If so, it's a wireless interface.
1751 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
1753 * Just give up here.
1757 if (stat(pathstr
, &statb
) == 0) {
1767 * Linux uses the ARP hardware type to identify the type of an
1768 * interface. pcap uses the DLT_xxx constants for this. This
1769 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1770 * constant, as arguments, and sets "handle->linktype" to the
1771 * appropriate DLT_XXX constant and sets "handle->offset" to
1772 * the appropriate value (to make "handle->offset" plus link-layer
1773 * header length be a multiple of 4, so that the link-layer payload
1774 * will be aligned on a 4-byte boundary when capturing packets).
1775 * (If the offset isn't set here, it'll be 0; add code as appropriate
1776 * for cases where it shouldn't be 0.)
1778 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1779 * in cooked mode; otherwise, we can't use cooked mode, so we have
1780 * to pick some type that works in raw mode, or fail.
1782 * Sets the link type to -1 if unable to map the type.
1784 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
,
1785 const char *device
, int cooked_ok
)
1787 static const char cdma_rmnet
[] = "cdma_rmnet";
1793 * For various annoying reasons having to do with DHCP
1794 * software, some versions of Android give the mobile-
1795 * phone-network interface an ARPHRD_ value of
1796 * ARPHRD_ETHER, even though the packets supplied by
1797 * that interface have no link-layer header, and begin
1798 * with an IP header, so that the ARPHRD_ value should
1801 * Detect those devices by checking the device name, and
1802 * use DLT_RAW for them.
1804 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
1805 handle
->linktype
= DLT_RAW
;
1810 * Is this a real Ethernet device? If so, give it a
1811 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1812 * that an application can let you choose it, in case you're
1813 * capturing DOCSIS traffic that a Cisco Cable Modem
1814 * Termination System is putting out onto an Ethernet (it
1815 * doesn't put an Ethernet header onto the wire, it puts raw
1816 * DOCSIS frames out on the wire inside the low-level
1817 * Ethernet framing).
1819 * XXX - are there any other sorts of "fake Ethernet" that
1820 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
1821 * a Cisco CMTS won't put traffic onto it or get traffic
1822 * bridged onto it? ISDN is handled in "activate_pf_packet()",
1823 * as we fall back on cooked mode there, and we use
1824 * is_wifi() to check for 802.11 devices; are there any
1827 if (!is_wifi(device
)) {
1831 * This is not a Wi-Fi device but it could be
1832 * a DSA master/management network device.
1834 ret
= iface_dsa_get_proto_info(device
, handle
);
1840 * This is a DSA master/management network
1841 * device linktype is already set by
1842 * iface_dsa_get_proto_info() set an
1843 * appropriate offset here.
1850 * It's not a Wi-Fi device; offer DOCSIS.
1852 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1854 * If that fails, just leave the list empty.
1856 if (handle
->dlt_list
!= NULL
) {
1857 handle
->dlt_list
[0] = DLT_EN10MB
;
1858 handle
->dlt_list
[1] = DLT_DOCSIS
;
1859 handle
->dlt_count
= 2;
1864 case ARPHRD_METRICOM
:
1865 case ARPHRD_LOOPBACK
:
1866 handle
->linktype
= DLT_EN10MB
;
1871 handle
->linktype
= DLT_EN3MB
;
1875 handle
->linktype
= DLT_AX25_KISS
;
1879 handle
->linktype
= DLT_PRONET
;
1883 handle
->linktype
= DLT_CHAOS
;
1886 #define ARPHRD_CAN 280
1889 handle
->linktype
= DLT_CAN_SOCKETCAN
;
1892 #ifndef ARPHRD_IEEE802_TR
1893 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1895 case ARPHRD_IEEE802_TR
:
1896 case ARPHRD_IEEE802
:
1897 handle
->linktype
= DLT_IEEE802
;
1902 handle
->linktype
= DLT_ARCNET_LINUX
;
1905 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1906 #define ARPHRD_FDDI 774
1909 handle
->linktype
= DLT_FDDI
;
1913 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1914 #define ARPHRD_ATM 19
1918 * The Classical IP implementation in ATM for Linux
1919 * supports both what RFC 1483 calls "LLC Encapsulation",
1920 * in which each packet has an LLC header, possibly
1921 * with a SNAP header as well, prepended to it, and
1922 * what RFC 1483 calls "VC Based Multiplexing", in which
1923 * different virtual circuits carry different network
1924 * layer protocols, and no header is prepended to packets.
1926 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1927 * you can't use the ARPHRD_ type to find out whether
1928 * captured packets will have an LLC header, and,
1929 * while there's a socket ioctl to *set* the encapsulation
1930 * type, there's no ioctl to *get* the encapsulation type.
1934 * programs that dissect Linux Classical IP frames
1935 * would have to check for an LLC header and,
1936 * depending on whether they see one or not, dissect
1937 * the frame as LLC-encapsulated or as raw IP (I
1938 * don't know whether there's any traffic other than
1939 * IP that would show up on the socket, or whether
1940 * there's any support for IPv6 in the Linux
1941 * Classical IP code);
1943 * filter expressions would have to compile into
1944 * code that checks for an LLC header and does
1947 * Both of those are a nuisance - and, at least on systems
1948 * that support PF_PACKET sockets, we don't have to put
1949 * up with those nuisances; instead, we can just capture
1950 * in cooked mode. That's what we'll do, if we can.
1951 * Otherwise, we'll just fail.
1954 handle
->linktype
= DLT_LINUX_SLL
;
1956 handle
->linktype
= -1;
1959 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1960 #define ARPHRD_IEEE80211 801
1962 case ARPHRD_IEEE80211
:
1963 handle
->linktype
= DLT_IEEE802_11
;
1966 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1967 #define ARPHRD_IEEE80211_PRISM 802
1969 case ARPHRD_IEEE80211_PRISM
:
1970 handle
->linktype
= DLT_PRISM_HEADER
;
1973 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1974 #define ARPHRD_IEEE80211_RADIOTAP 803
1976 case ARPHRD_IEEE80211_RADIOTAP
:
1977 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1982 * Some PPP code in the kernel supplies no link-layer
1983 * header whatsoever to PF_PACKET sockets; other PPP
1984 * code supplies PPP link-layer headers ("syncppp.c");
1985 * some PPP code might supply random link-layer
1986 * headers (PPP over ISDN - there's code in Ethereal,
1987 * for example, to cope with PPP-over-ISDN captures
1988 * with which the Ethereal developers have had to cope,
1989 * heuristically trying to determine which of the
1990 * oddball link-layer headers particular packets have).
1992 * As such, we just punt, and run all PPP interfaces
1993 * in cooked mode, if we can; otherwise, we just treat
1994 * it as DLT_RAW, for now - if somebody needs to capture,
1995 * on a 2.0[.x] kernel, on PPP devices that supply a
1996 * link-layer header, they'll have to add code here to
1997 * map to the appropriate DLT_ type (possibly adding a
1998 * new DLT_ type, if necessary).
2001 handle
->linktype
= DLT_LINUX_SLL
;
2004 * XXX - handle ISDN types here? We can't fall
2005 * back on cooked sockets, so we'd have to
2006 * figure out from the device name what type of
2007 * link-layer encapsulation it's using, and map
2008 * that to an appropriate DLT_ value, meaning
2009 * we'd map "isdnN" devices to DLT_RAW (they
2010 * supply raw IP packets with no link-layer
2011 * header) and "isdY" devices to a new DLT_I4L_IP
2012 * type that has only an Ethernet packet type as
2013 * a link-layer header.
2015 * But sometimes we seem to get random crap
2016 * in the link-layer header when capturing on
2019 handle
->linktype
= DLT_RAW
;
2023 #ifndef ARPHRD_CISCO
2024 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2027 handle
->linktype
= DLT_C_HDLC
;
2030 /* Not sure if this is correct for all tunnels, but it
2034 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2042 #ifndef ARPHRD_RAWHDLC
2043 #define ARPHRD_RAWHDLC 518
2045 case ARPHRD_RAWHDLC
:
2047 #define ARPHRD_DLCI 15
2051 * XXX - should some of those be mapped to DLT_LINUX_SLL
2052 * instead? Should we just map all of them to DLT_LINUX_SLL?
2054 handle
->linktype
= DLT_RAW
;
2058 #define ARPHRD_FRAD 770
2061 handle
->linktype
= DLT_FRELAY
;
2064 case ARPHRD_LOCALTLK
:
2065 handle
->linktype
= DLT_LTALK
;
2070 * RFC 4338 defines an encapsulation for IP and ARP
2071 * packets that's compatible with the RFC 2625
2072 * encapsulation, but that uses a different ARP
2073 * hardware type and hardware addresses. That
2074 * ARP hardware type is 18; Linux doesn't define
2075 * any ARPHRD_ value as 18, but if it ever officially
2076 * supports RFC 4338-style IP-over-FC, it should define
2079 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2080 * that this will encourage its use in the future,
2081 * should Linux ever officially support RFC 4338-style
2084 handle
->linktype
= DLT_IP_OVER_FC
;
2088 #define ARPHRD_FCPP 784
2092 #define ARPHRD_FCAL 785
2096 #define ARPHRD_FCPL 786
2099 #ifndef ARPHRD_FCFABRIC
2100 #define ARPHRD_FCFABRIC 787
2102 case ARPHRD_FCFABRIC
:
2104 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2107 * https://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2109 * and one was assigned.
2111 * In a later private discussion (spun off from a message
2112 * on the ethereal-users list) on how to get that DLT_
2113 * value in libpcap on Linux, I ended up deciding that
2114 * the best thing to do would be to have him tweak the
2115 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2116 * type, and map all those types to DLT_IP_OVER_FC:
2118 * I've checked into the libpcap and tcpdump CVS tree
2119 * support for DLT_IP_OVER_FC. In order to use that,
2120 * you'd have to modify your modified driver to return
2121 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2122 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2123 * example (the exact value doesn't matter, it can be
2124 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2127 * 11 years later, Christian Svensson wanted to map
2128 * various ARPHRD_ values to DLT_FC_2 and
2129 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2132 * https://github.com/mcr/libpcap/pull/29
2134 * There doesn't seem to be any network drivers that uses
2135 * any of the ARPHRD_FC* values for IP-over-FC, and
2136 * it's not exactly clear what the "Dummy types for non
2137 * ARP hardware" are supposed to mean (link-layer
2138 * header type? Physical network type?), so it's
2139 * not exactly clear why the ARPHRD_FC* types exist
2140 * in the first place.
2142 * For now, we map them to DLT_FC_2, and provide an
2143 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2144 * DLT_IP_OVER_FC just in case there's some old
2145 * driver out there that uses one of those types for
2146 * IP-over-FC on which somebody wants to capture
2149 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
2151 * If that fails, just leave the list empty.
2153 if (handle
->dlt_list
!= NULL
) {
2154 handle
->dlt_list
[0] = DLT_FC_2
;
2155 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2156 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2157 handle
->dlt_count
= 3;
2159 handle
->linktype
= DLT_FC_2
;
2163 #define ARPHRD_IRDA 783
2166 /* Don't expect IP packet out of this interfaces... */
2167 handle
->linktype
= DLT_LINUX_IRDA
;
2168 /* We need to save packet direction for IrDA decoding,
2169 * so let's use "Linux-cooked" mode. Jean II
2171 * XXX - this is handled in activate_pf_packet(). */
2172 /* handlep->cooked = 1; */
2175 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2176 * is needed, please report it to <daniele@orlandi.com> */
2178 #define ARPHRD_LAPD 8445
2181 /* Don't expect IP packet out of this interfaces... */
2182 handle
->linktype
= DLT_LINUX_LAPD
;
2186 #define ARPHRD_NONE 0xFFFE
2190 * No link-layer header; packets are just IP
2191 * packets, so use DLT_RAW.
2193 handle
->linktype
= DLT_RAW
;
2196 #ifndef ARPHRD_IEEE802154
2197 #define ARPHRD_IEEE802154 804
2199 case ARPHRD_IEEE802154
:
2200 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2203 #ifndef ARPHRD_NETLINK
2204 #define ARPHRD_NETLINK 824
2206 case ARPHRD_NETLINK
:
2207 handle
->linktype
= DLT_NETLINK
;
2209 * We need to use cooked mode, so that in sll_protocol we
2210 * pick up the netlink protocol type such as NETLINK_ROUTE,
2211 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2213 * XXX - this is handled in activate_pf_packet().
2215 /* handlep->cooked = 1; */
2218 #ifndef ARPHRD_VSOCKMON
2219 #define ARPHRD_VSOCKMON 826
2221 case ARPHRD_VSOCKMON
:
2222 handle
->linktype
= DLT_VSOCK
;
2226 handle
->linktype
= -1;
2231 #ifdef PACKET_RESERVE
2233 set_dlt_list_cooked(pcap_t
*handle
, int sock_fd
)
2236 unsigned int tp_reserve
;
2239 * If we can't do PACKET_RESERVE, we can't reserve extra space
2240 * for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
2242 len
= sizeof(tp_reserve
);
2243 if (getsockopt(sock_fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
,
2246 * Yes, we can do DLL_LINUX_SLL2.
2248 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2250 * If that fails, just leave the list empty.
2252 if (handle
->dlt_list
!= NULL
) {
2253 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
2254 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
2255 handle
->dlt_count
= 2;
2259 #else/* PACKET_RESERVE */
2261 * The build environment doesn't define PACKET_RESERVE, so we can't reserve
2262 * extra space for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
2265 set_dlt_list_cooked(pcap_t
*handle _U_
, int sock_fd _U_
)
2268 #endif /* PACKET_RESERVE */
2271 * Try to set up a PF_PACKET socket.
2272 * Returns 0 on success and a PCAP_ERROR_ value on failure.
2275 activate_pf_packet(pcap_t
*handle
, int is_any_device
)
2277 struct pcap_linux
*handlep
= handle
->priv
;
2278 const char *device
= handle
->opt
.device
;
2280 int sock_fd
, arptype
;
2281 #ifdef HAVE_PACKET_AUXDATA
2285 struct packet_mreq mr
;
2286 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2288 socklen_t len
= sizeof(bpf_extensions
);
2292 * Open a socket with protocol family packet. If cooked is true,
2293 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
2294 * we open a SOCK_RAW socket for the raw interface.
2296 * The protocol is set to 0. This means we will receive no
2297 * packets until we "bind" the socket with a non-zero
2298 * protocol. This allows us to setup the ring buffers without
2299 * dropping any packets.
2301 sock_fd
= is_any_device
?
2302 socket(PF_PACKET
, SOCK_DGRAM
, 0) :
2303 socket(PF_PACKET
, SOCK_RAW
, 0);
2305 if (sock_fd
== -1) {
2306 if (errno
== EPERM
|| errno
== EACCES
) {
2308 * You don't have permission to open the
2311 status
= PCAP_ERROR_PERM_DENIED
;
2316 status
= PCAP_ERROR
;
2318 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2324 * Get the interface index of the loopback device.
2325 * If the attempt fails, don't fail, just set the
2326 * "handlep->lo_ifindex" to -1.
2328 * XXX - can there be more than one device that loops
2329 * packets back, i.e. devices other than "lo"? If so,
2330 * we'd need to find them all, and have an array of
2331 * indices for them, and check all of them in
2332 * "pcap_read_packet()".
2334 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2337 * Default value for offset to align link-layer payload
2338 * on a 4-byte boundary.
2343 * What kind of frames do we have to deal with? Fall back
2344 * to cooked mode if we have an unknown interface type
2345 * or a type we know doesn't work well in raw mode.
2347 if (!is_any_device
) {
2348 /* Assume for now we don't need cooked mode. */
2349 handlep
->cooked
= 0;
2351 if (handle
->opt
.rfmon
) {
2353 * We were asked to turn on monitor mode.
2354 * Do so before we get the link-layer type,
2355 * because entering monitor mode could change
2356 * the link-layer type.
2358 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2366 * Nothing worked for turning monitor mode
2370 return PCAP_ERROR_RFMON_NOTSUP
;
2374 * Either monitor mode has been turned on for
2375 * the device, or we've been given a different
2376 * device to open for monitor mode. If we've
2377 * been given a different device, use it.
2379 if (handlep
->mondevice
!= NULL
)
2380 device
= handlep
->mondevice
;
2382 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2387 map_arphrd_to_dlt(handle
, arptype
, device
, 1);
2388 if (handle
->linktype
== -1 ||
2389 handle
->linktype
== DLT_LINUX_SLL
||
2390 handle
->linktype
== DLT_LINUX_IRDA
||
2391 handle
->linktype
== DLT_LINUX_LAPD
||
2392 handle
->linktype
== DLT_NETLINK
||
2393 (handle
->linktype
== DLT_EN10MB
&&
2394 (strncmp("isdn", device
, 4) == 0 ||
2395 strncmp("isdY", device
, 4) == 0))) {
2397 * Unknown interface type (-1), or a
2398 * device we explicitly chose to run
2399 * in cooked mode (e.g., PPP devices),
2400 * or an ISDN device (whose link-layer
2401 * type we can only determine by using
2402 * APIs that may be different on different
2403 * kernels) - reopen in cooked mode.
2405 * If the type is unknown, return a warning;
2406 * map_arphrd_to_dlt() has already set the
2409 if (close(sock_fd
) == -1) {
2410 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2411 PCAP_ERRBUF_SIZE
, errno
, "close");
2414 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
, 0);
2417 * Fatal error. We treat this as
2418 * a generic error; we already know
2419 * that we were able to open a
2420 * PF_PACKET/SOCK_RAW socket, so
2421 * any failure is a "this shouldn't
2424 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2425 PCAP_ERRBUF_SIZE
, errno
, "socket");
2428 handlep
->cooked
= 1;
2431 * Get rid of any link-layer type list
2432 * we allocated - this only supports cooked
2435 if (handle
->dlt_list
!= NULL
) {
2436 free(handle
->dlt_list
);
2437 handle
->dlt_list
= NULL
;
2438 handle
->dlt_count
= 0;
2439 set_dlt_list_cooked(handle
, sock_fd
);
2442 if (handle
->linktype
== -1) {
2444 * Warn that we're falling back on
2445 * cooked mode; we may want to
2446 * update "map_arphrd_to_dlt()"
2447 * to handle the new type.
2449 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2451 "supported by libpcap - "
2452 "falling back to cooked "
2458 * IrDA capture is not a real "cooked" capture,
2459 * it's IrLAP frames, not IP packets. The
2460 * same applies to LAPD capture.
2462 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2463 handle
->linktype
!= DLT_LINUX_LAPD
&&
2464 handle
->linktype
!= DLT_NETLINK
)
2465 handle
->linktype
= DLT_LINUX_SLL
;
2466 if (handle
->linktype
== -1) {
2467 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2468 "unknown arptype %d, defaulting to cooked mode",
2470 status
= PCAP_WARNING
;
2474 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
2476 if (handlep
->ifindex
== -1) {
2481 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
2482 handle
->errbuf
, 0)) != 0) {
2490 if (handle
->opt
.rfmon
) {
2492 * It doesn't support monitor mode.
2495 return PCAP_ERROR_RFMON_NOTSUP
;
2499 * It uses cooked mode.
2501 handlep
->cooked
= 1;
2502 handle
->linktype
= DLT_LINUX_SLL
;
2503 handle
->dlt_list
= NULL
;
2504 handle
->dlt_count
= 0;
2505 set_dlt_list_cooked(handle
, sock_fd
);
2508 * We're not bound to a device.
2509 * For now, we're using this as an indication
2510 * that we can't transmit; stop doing that only
2511 * if we figure out how to transmit in cooked
2514 handlep
->ifindex
= -1;
2518 * Select promiscuous mode on if "promisc" is set.
2520 * Do not turn allmulti mode on if we don't select
2521 * promiscuous mode - on some devices (e.g., Orinoco
2522 * wireless interfaces), allmulti mode isn't supported
2523 * and the driver implements it by turning promiscuous
2524 * mode on, and that screws up the operation of the
2525 * card as a normal networking interface, and on no
2526 * other platform I know of does starting a non-
2527 * promiscuous capture affect which multicast packets
2528 * are received by the interface.
2532 * Hmm, how can we set promiscuous mode on all interfaces?
2533 * I am not sure if that is possible at all. For now, we
2534 * silently ignore attempts to turn promiscuous mode on
2535 * for the "any" device (so you don't have to explicitly
2536 * disable it in programs such as tcpdump).
2539 if (!is_any_device
&& handle
->opt
.promisc
) {
2540 memset(&mr
, 0, sizeof(mr
));
2541 mr
.mr_ifindex
= handlep
->ifindex
;
2542 mr
.mr_type
= PACKET_MR_PROMISC
;
2543 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2544 &mr
, sizeof(mr
)) == -1) {
2545 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2546 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
2552 /* Enable auxiliary data if supported and reserve room for
2553 * reconstructing VLAN headers. */
2554 #ifdef HAVE_PACKET_AUXDATA
2556 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2557 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2558 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2559 errno
, "setsockopt (PACKET_AUXDATA)");
2563 handle
->offset
+= VLAN_TAG_LEN
;
2564 #endif /* HAVE_PACKET_AUXDATA */
2567 * If we're in cooked mode, make the snapshot length
2568 * large enough to hold a "cooked mode" header plus
2569 * 1 byte of packet data (so we don't pass a byte
2570 * count of 0 to "recvfrom()").
2571 * XXX - we don't know whether this will be DLT_LINUX_SLL
2572 * or DLT_LINUX_SLL2, so make sure it's big enough for
2573 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
2574 * that small is silly anyway.
2576 if (handlep
->cooked
) {
2577 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
2578 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
2580 handle
->bufsize
= handle
->snapshot
;
2583 * Set the offset at which to insert VLAN tags.
2584 * That should be the offset of the type field.
2586 switch (handle
->linktype
) {
2590 * The type field is after the destination and source
2593 handlep
->vlan_offset
= 2 * ETH_ALEN
;
2598 * The type field is in the last 2 bytes of the
2599 * DLT_LINUX_SLL header.
2601 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
2605 handlep
->vlan_offset
= -1; /* unknown */
2609 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
2610 int nsec_tstamps
= 1;
2612 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
2613 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
2620 * We've succeeded. Save the socket FD in the pcap structure.
2622 handle
->fd
= sock_fd
;
2624 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2626 * Can we generate special code for VLAN checks?
2627 * (XXX - what if we need the special code but it's not supported
2628 * by the OS? Is that possible?)
2630 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
2631 &bpf_extensions
, &len
) == 0) {
2632 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
2634 * Yes, we can. Request that we do so.
2636 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
2639 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
2645 * Attempt to setup memory-mapped access.
2647 * On success, returns 1, and sets *status to 0 if there are no warnings
2648 * or to a PCAP_WARNING_ code if there is a warning.
2650 * On error, returns -1, and sets *status to the appropriate error code;
2651 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
2654 setup_mmapped(pcap_t
*handle
, int *status
)
2656 struct pcap_linux
*handlep
= handle
->priv
;
2660 * Attempt to allocate a buffer to hold the contents of one
2661 * packet, for use by the oneshot callback.
2663 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
2664 if (handlep
->oneshot_buffer
== NULL
) {
2665 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2666 errno
, "can't allocate oneshot buffer");
2667 *status
= PCAP_ERROR
;
2671 if (handle
->opt
.buffer_size
== 0) {
2672 /* by default request 2M for the ring buffer */
2673 handle
->opt
.buffer_size
= 2*1024*1024;
2675 ret
= prepare_tpacket_socket(handle
);
2677 free(handlep
->oneshot_buffer
);
2678 handlep
->oneshot_buffer
= NULL
;
2679 *status
= PCAP_ERROR
;
2682 ret
= create_ring(handle
, status
);
2685 * Error attempting to enable memory-mapped capture;
2686 * fail. create_ring() has set *status.
2688 free(handlep
->oneshot_buffer
);
2689 handlep
->oneshot_buffer
= NULL
;
2694 * Success. *status has been set either to 0 if there are no
2695 * warnings or to a PCAP_WARNING_ value if there is a warning.
2697 * handle->offset is used to get the current position into the rx ring.
2698 * handle->cc is used to store the ring size.
2702 * Set the timeout to use in poll() before returning.
2704 set_poll_timeout(handlep
);
2710 * Attempt to set the socket to the specified version of the memory-mapped
2713 * Return 0 if we succeed; return 1 if we fail because that version isn't
2714 * supported; return -1 on any other error, and set handle->errbuf.
2717 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
2719 struct pcap_linux
*handlep
= handle
->priv
;
2721 socklen_t len
= sizeof(val
);
2724 * Probe whether kernel supports the specified TPACKET version;
2725 * this also gets the length of the header for that version.
2727 * This socket option was introduced in 2.6.27, which was
2728 * also the first release with TPACKET_V2 support.
2730 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
2731 if (errno
== EINVAL
) {
2733 * EINVAL means this specific version of TPACKET
2734 * is not supported. Tell the caller they can try
2735 * with a different one; if they've run out of
2736 * others to try, let them set the error message
2743 * All other errors are fatal.
2745 if (errno
== ENOPROTOOPT
) {
2747 * PACKET_HDRLEN isn't supported, which means
2748 * that memory-mapped capture isn't supported.
2749 * Indicate that in the message.
2751 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2752 "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");
2755 * Some unexpected error.
2757 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2758 errno
, "can't get %s header len on packet socket",
2763 handlep
->tp_hdrlen
= val
;
2766 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
2768 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2769 errno
, "can't activate %s on packet socket", version_str
);
2772 handlep
->tp_version
= version
;
2778 * Attempt to set the socket to version 3 of the memory-mapped header and,
2779 * if that fails because version 3 isn't supported, attempt to fall
2780 * back to version 2. If version 2 isn't supported, just fail.
2782 * Return 0 if we succeed and -1 on any other error, and set handle->errbuf.
2785 prepare_tpacket_socket(pcap_t
*handle
)
2789 #ifdef HAVE_TPACKET3
2791 * Try setting the version to TPACKET_V3.
2793 * The only mode in which buffering is done on PF_PACKET
2794 * sockets, so that packets might not be delivered
2795 * immediately, is TPACKET_V3 mode.
2797 * The buffering cannot be disabled in that mode, so
2798 * if the user has requested immediate mode, we don't
2801 if (!handle
->opt
.immediate
) {
2802 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
2811 * We failed for some reason other than "the
2812 * kernel doesn't support TPACKET_V3".
2818 * This means it returned 1, which means "the kernel
2819 * doesn't support TPACKET_V3"; try TPACKET_V2.
2822 #endif /* HAVE_TPACKET3 */
2825 * Try setting the version to TPACKET_V2.
2827 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
2837 * OK, the kernel supports memory-mapped capture, but
2838 * not TPACKET_V2. Set the error message appropriately.
2840 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2841 "Kernel doesn't support TPACKET_V2; a 2.6.27 or later kernel is required");
2850 #define MAX(a,b) ((a)>(b)?(a):(b))
2853 * Attempt to set up memory-mapped access.
2855 * On success, returns 1, and sets *status to 0 if there are no warnings
2856 * or to a PCAP_WARNING_ code if there is a warning.
2858 * On error, returns -1, and sets *status to the appropriate error code;
2859 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
2862 create_ring(pcap_t
*handle
, int *status
)
2864 struct pcap_linux
*handlep
= handle
->priv
;
2865 unsigned i
, j
, frames_per_block
;
2866 #ifdef HAVE_TPACKET3
2868 * For sockets using TPACKET_V2, the extra stuff at the end of a
2869 * struct tpacket_req3 will be ignored, so this is OK even for
2872 struct tpacket_req3 req
;
2874 struct tpacket_req req
;
2877 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
2878 unsigned int frame_size
;
2881 * Start out assuming no warnings or errors.
2886 * Reserve space for VLAN tag reconstruction.
2888 tp_reserve
= VLAN_TAG_LEN
;
2891 * If we're using DLT_LINUX_SLL2, reserve space for a
2892 * DLT_LINUX_SLL2 header.
2894 * XXX - we assume that the kernel is still adding
2895 * 16 bytes of extra space; that happens to
2896 * correspond to SLL_HDR_LEN (whether intentionally
2897 * or not - the kernel code has a raw "16" in
2898 * the expression), so we subtract SLL_HDR_LEN
2899 * from SLL2_HDR_LEN to get the additional space
2900 * needed. That also means we don't bother reserving
2901 * any additional space if we're using DLT_LINUX_SLL.
2903 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
2905 if (handle
->linktype
== DLT_LINUX_SLL2
)
2906 tp_reserve
+= SLL2_HDR_LEN
- SLL_HDR_LEN
;
2909 * Try to request that amount of reserve space.
2910 * This must be done before creating the ring buffer.
2911 * If PACKET_RESERVE is supported, creating the ring
2912 * buffer should be, although if creating the ring
2913 * buffer fails, the PACKET_RESERVE call has no effect,
2914 * so falling back on read-from-the-socket capturing
2915 * won't be affected.
2917 len
= sizeof(tp_reserve
);
2918 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
2919 &tp_reserve
, len
) < 0) {
2921 * We treat ENOPROTOOPT as an error, as we
2922 * already determined that we support
2923 * TPACKET_V2 and later; see above.
2925 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2926 PCAP_ERRBUF_SIZE
, errno
,
2927 "setsockopt (PACKET_RESERVE)");
2928 *status
= PCAP_ERROR
;
2932 switch (handlep
->tp_version
) {
2935 /* Note that with large snapshot length (say 256K, which is
2936 * the default for recent versions of tcpdump, Wireshark,
2937 * TShark, dumpcap or 64K, the value that "-s 0" has given for
2938 * a long time with tcpdump), if we use the snapshot
2939 * length to calculate the frame length, only a few frames
2940 * will be available in the ring even with pretty
2941 * large ring size (and a lot of memory will be unused).
2943 * Ideally, we should choose a frame length based on the
2944 * minimum of the specified snapshot length and the maximum
2945 * packet size. That's not as easy as it sounds; consider,
2946 * for example, an 802.11 interface in monitor mode, where
2947 * the frame would include a radiotap header, where the
2948 * maximum radiotap header length is device-dependent.
2950 * So, for now, we just do this for Ethernet devices, where
2951 * there's no metadata header, and the link-layer header is
2952 * fixed length. We can get the maximum packet size by
2953 * adding 18, the Ethernet header length plus the CRC length
2954 * (just in case we happen to get the CRC in the packet), to
2955 * the MTU of the interface; we fetch the MTU in the hopes
2956 * that it reflects support for jumbo frames. (Even if the
2957 * interface is just being used for passive snooping, the
2958 * driver might set the size of buffers in the receive ring
2959 * based on the MTU, so that the MTU limits the maximum size
2960 * of packets that we can receive.)
2962 * If segmentation/fragmentation or receive offload are
2963 * enabled, we can get reassembled/aggregated packets larger
2964 * than MTU, but bounded to 65535 plus the Ethernet overhead,
2965 * due to kernel and protocol constraints */
2966 frame_size
= handle
->snapshot
;
2967 if (handle
->linktype
== DLT_EN10MB
) {
2968 unsigned int max_frame_len
;
2972 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
2975 *status
= PCAP_ERROR
;
2978 offload
= iface_get_offload(handle
);
2979 if (offload
== -1) {
2980 *status
= PCAP_ERROR
;
2984 max_frame_len
= MAX(mtu
, 65535);
2986 max_frame_len
= mtu
;
2987 max_frame_len
+= 18;
2989 if (frame_size
> max_frame_len
)
2990 frame_size
= max_frame_len
;
2993 /* NOTE: calculus matching those in tpacket_rcv()
2994 * in linux-2.6/net/packet/af_packet.c
2996 len
= sizeof(sk_type
);
2997 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
2999 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3000 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
3001 *status
= PCAP_ERROR
;
3004 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3005 /* XXX: in the kernel maclen is calculated from
3006 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3007 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3008 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3009 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3010 * but I see no way to get those sizes in userspace,
3011 * like for instance with an ifreq ioctl();
3012 * the best thing I've found so far is MAX_HEADER in
3013 * the kernel part of linux-2.6/include/linux/netdevice.h
3014 * which goes up to 128+48=176; since pcap-linux.c
3015 * defines a MAX_LINKHEADER_SIZE of 256 which is
3016 * greater than that, let's use it.. maybe is it even
3017 * large enough to directly replace macoff..
3019 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3020 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3021 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3022 * of netoff, which contradicts
3023 * linux-2.6/Documentation/networking/packet_mmap.txt
3025 * "- Gap, chosen so that packet data (Start+tp_net)
3026 * aligns to TPACKET_ALIGNMENT=16"
3028 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3029 * "CPUs often take a performance hit
3030 * when accessing unaligned memory locations"
3032 macoff
= netoff
- maclen
;
3033 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3035 * Round the buffer size up to a multiple of the
3036 * frame size (rather than rounding down, which
3037 * would give a buffer smaller than our caller asked
3038 * for, and possibly give zero frames if the requested
3039 * buffer size is too small for one frame).
3041 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3044 #ifdef HAVE_TPACKET3
3046 /* The "frames" for this are actually buffers that
3047 * contain multiple variable-sized frames.
3049 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
3050 * enough room for at least one reasonably-sized packet
3051 * in the "frame". */
3052 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
3054 * Round the buffer size up to a multiple of the
3055 * "frame" size (rather than rounding down, which
3056 * would give a buffer smaller than our caller asked
3057 * for, and possibly give zero "frames" if the requested
3058 * buffer size is too small for one "frame").
3060 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3064 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3065 "Internal error: unknown TPACKET_ value %u",
3066 handlep
->tp_version
);
3067 *status
= PCAP_ERROR
;
3071 /* compute the minimum block size that will handle this frame.
3072 * The block has to be page size aligned.
3073 * The max block size allowed by the kernel is arch-dependent and
3074 * it's not explicitly checked here. */
3075 req
.tp_block_size
= getpagesize();
3076 while (req
.tp_block_size
< req
.tp_frame_size
)
3077 req
.tp_block_size
<<= 1;
3079 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3082 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3083 * so we check for PACKET_TIMESTAMP. We check for
3084 * linux/net_tstamp.h just in case a system somehow has
3085 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3088 * SIOCSHWTSTAMP was introduced in the patch that introduced
3089 * linux/net_tstamp.h, so we don't bother checking whether
3090 * SIOCSHWTSTAMP is defined (if your Linux system has
3091 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3092 * Linux system is badly broken).
3094 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3096 * If we were told to do so, ask the kernel and the driver
3097 * to use hardware timestamps.
3099 * Hardware timestamps are only supported with mmapped
3102 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3103 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3104 struct hwtstamp_config hwconfig
;
3109 * Ask for hardware time stamps on all packets,
3110 * including transmitted packets.
3112 memset(&hwconfig
, 0, sizeof(hwconfig
));
3113 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3114 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3116 memset(&ifr
, 0, sizeof(ifr
));
3117 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
3118 ifr
.ifr_data
= (void *)&hwconfig
;
3120 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3125 * Treat this as an error, as the
3126 * user should try to run this
3127 * with the appropriate privileges -
3128 * and, if they can't, shouldn't
3129 * try requesting hardware time stamps.
3131 *status
= PCAP_ERROR_PERM_DENIED
;
3137 * Treat this as a warning, as the
3138 * only way to fix the warning is to
3139 * get an adapter that supports hardware
3140 * time stamps for *all* packets.
3141 * (ERANGE means "we support hardware
3142 * time stamps, but for packets matching
3143 * that particular filter", so it means
3144 * "we don't support hardware time stamps
3145 * for all incoming packets" here.)
3147 * We'll just fall back on the standard
3150 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3154 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3155 PCAP_ERRBUF_SIZE
, errno
,
3156 "SIOCSHWTSTAMP failed");
3157 *status
= PCAP_ERROR
;
3162 * Well, that worked. Now specify the type of
3163 * hardware time stamp we want for this
3166 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3168 * Hardware timestamp, synchronized
3169 * with the system clock.
3171 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3174 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3175 * timestamp, not synchronized with the
3178 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3180 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3181 (void *)×ource
, sizeof(timesource
))) {
3182 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3183 PCAP_ERRBUF_SIZE
, errno
,
3184 "can't set PACKET_TIMESTAMP");
3185 *status
= PCAP_ERROR
;
3190 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3192 /* ask the kernel to create the ring */
3194 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3196 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3197 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3199 #ifdef HAVE_TPACKET3
3200 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3201 if (handlep
->timeout
> 0) {
3202 /* Use the user specified timeout as the block timeout */
3203 req
.tp_retire_blk_tov
= handlep
->timeout
;
3204 } else if (handlep
->timeout
== 0) {
3206 * In pcap, this means "infinite timeout"; TPACKET_V3
3207 * doesn't support that, so just set it to UINT_MAX
3208 * milliseconds. In the TPACKET_V3 loop, if the
3209 * timeout is 0, and we haven't yet seen any packets,
3210 * and we block and still don't have any packets, we
3211 * keep blocking until we do.
3213 req
.tp_retire_blk_tov
= UINT_MAX
;
3216 * XXX - this is not valid; use 0, meaning "have the
3217 * kernel pick a default", for now.
3219 req
.tp_retire_blk_tov
= 0;
3221 /* private data not used */
3222 req
.tp_sizeof_priv
= 0;
3223 /* Rx ring - feature request bits - none (rxhash will not be filled) */
3224 req
.tp_feature_req_word
= 0;
3227 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3228 (void *) &req
, sizeof(req
))) {
3229 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3231 * Memory failure; try to reduce the requested ring
3234 * We used to reduce this by half -- do 5% instead.
3235 * That may result in more iterations and a longer
3236 * startup, but the user will be much happier with
3237 * the resulting buffer size.
3239 if (req
.tp_frame_nr
< 20)
3240 req
.tp_frame_nr
-= 1;
3242 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3245 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3246 errno
, "can't create rx ring on packet socket");
3247 *status
= PCAP_ERROR
;
3251 /* memory map the rx ring */
3252 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3253 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
3254 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3255 if (handlep
->mmapbuf
== MAP_FAILED
) {
3256 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3257 errno
, "can't mmap rx ring");
3259 /* clear the allocated ring on error*/
3260 destroy_ring(handle
);
3261 *status
= PCAP_ERROR
;
3265 /* allocate a ring for each frame header pointer*/
3266 handle
->cc
= req
.tp_frame_nr
;
3267 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3268 if (!handle
->buffer
) {
3269 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3270 errno
, "can't allocate ring of frame headers");
3272 destroy_ring(handle
);
3273 *status
= PCAP_ERROR
;
3277 /* fill the header ring with proper frame ptr*/
3279 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3280 u_char
*base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3281 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3282 RING_GET_CURRENT_FRAME(handle
) = base
;
3283 base
+= req
.tp_frame_size
;
3287 handle
->bufsize
= req
.tp_frame_size
;
3292 /* free all ring related resources*/
3294 destroy_ring(pcap_t
*handle
)
3296 struct pcap_linux
*handlep
= handle
->priv
;
3299 * Tell the kernel to destroy the ring.
3300 * We don't check for setsockopt failure, as 1) we can't recover
3301 * from an error and 2) we might not yet have set it up in the
3304 struct tpacket_req req
;
3305 memset(&req
, 0, sizeof(req
));
3306 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3307 (void *) &req
, sizeof(req
));
3309 /* if ring is mapped, unmap it*/
3310 if (handlep
->mmapbuf
) {
3311 /* do not test for mmap failure, as we can't recover from any error */
3312 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3313 handlep
->mmapbuf
= NULL
;
3318 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3319 * for Linux mmapped capture.
3321 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3322 * data handed to the callback to be valid after the callback returns,
3323 * but pcap_read_linux_mmap() has to release that packet as soon as
3324 * the callback returns (otherwise, the kernel thinks there's still
3325 * at least one unprocessed packet available in the ring, so a select()
3326 * will immediately return indicating that there's data to process), so,
3327 * in the callback, we have to make a copy of the packet.
3329 * Yes, this means that, if the capture is using the ring buffer, using
3330 * pcap_next() or pcap_next_ex() requires more copies than using
3331 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3332 * pcap_next() or pcap_next_ex().
3335 pcap_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
3336 const u_char
*bytes
)
3338 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3339 pcap_t
*handle
= sp
->pd
;
3340 struct pcap_linux
*handlep
= handle
->priv
;
3343 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3344 *sp
->pkt
= handlep
->oneshot_buffer
;
3348 pcap_getnonblock_linux(pcap_t
*handle
)
3350 struct pcap_linux
*handlep
= handle
->priv
;
3352 /* use negative value of timeout to indicate non blocking ops */
3353 return (handlep
->timeout
<0);
3357 pcap_setnonblock_linux(pcap_t
*handle
, int nonblock
)
3359 struct pcap_linux
*handlep
= handle
->priv
;
3362 * Set the file descriptor to non-blocking mode, as we use
3363 * it for sending packets.
3365 if (pcap_setnonblock_fd(handle
, nonblock
) == -1)
3369 * Map each value to their corresponding negation to
3370 * preserve the timeout value provided with pcap_set_timeout.
3373 if (handlep
->timeout
>= 0) {
3375 * Indicate that we're switching to
3376 * non-blocking mode.
3378 handlep
->timeout
= ~handlep
->timeout
;
3381 if (handlep
->timeout
< 0) {
3382 handlep
->timeout
= ~handlep
->timeout
;
3385 /* Update the timeout to use in poll(). */
3386 set_poll_timeout(handlep
);
3391 * Get the status field of the ring buffer frame at a specified offset.
3394 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
3396 struct pcap_linux
*handlep
= handle
->priv
;
3399 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
3400 switch (handlep
->tp_version
) {
3402 return __atomic_load_n(&h
.h2
->tp_status
, __ATOMIC_ACQUIRE
);
3404 #ifdef HAVE_TPACKET3
3406 return __atomic_load_n(&h
.h3
->hdr
.bh1
.block_status
, __ATOMIC_ACQUIRE
);
3410 /* This should not happen. */
3415 * Block waiting for frames to be available.
3417 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
3419 struct pcap_linux
*handlep
= handle
->priv
;
3423 struct pollfd pollinfo
[2];
3424 pollinfo
[0].fd
= handle
->fd
;
3425 pollinfo
[0].events
= POLLIN
;
3426 pollinfo
[1].fd
= handlep
->poll_breakloop_fd
;
3427 pollinfo
[1].events
= POLLIN
;
3430 * Keep polling until we either get some packets to read, see
3431 * that we got told to break out of the loop, get a fatal error,
3432 * or discover that the device went away.
3434 * In non-blocking mode, we must still do one poll() to catch
3435 * any pending error indications, but the poll() has a timeout
3436 * of 0, so that it doesn't block, and we quit after that one
3439 * If we've seen an ENETDOWN, it might be the first indication
3440 * that the device went away, or it might just be that it was
3441 * configured down. Unfortunately, there's no guarantee that
3442 * the device has actually been removed as an interface, because:
3444 * 1) if, as appears to be the case at least some of the time,
3445 * the PF_PACKET socket code first gets a NETDEV_DOWN indication
3446 * for the device and then gets a NETDEV_UNREGISTER indication
3447 * for it, the first indication will cause a wakeup with ENETDOWN
3448 * but won't set the packet socket's field for the interface index
3449 * to -1, and the second indication won't cause a wakeup (because
3450 * the first indication also caused the protocol hook to be
3451 * unregistered) but will set the packet socket's field for the
3452 * interface index to -1;
3454 * 2) even if just a NETDEV_UNREGISTER indication is registered,
3455 * the packet socket's field for the interface index only gets
3456 * set to -1 after the wakeup, so there's a small but non-zero
3457 * risk that a thread blocked waiting for the wakeup will get
3458 * to the "fetch the socket name" code before the interface index
3459 * gets set to -1, so it'll get the old interface index.
3461 * Therefore, if we got an ENETDOWN and haven't seen a packet
3462 * since then, we assume that we might be waiting for the interface
3463 * to disappear, and poll with a timeout to try again in a short
3464 * period of time. If we *do* see a packet, the interface has
3465 * come back up again, and is *definitely* still there, so we
3466 * don't need to poll.
3470 * Yes, we do this even in non-blocking mode, as it's
3471 * the only way to get error indications from a
3474 * The timeout is 0 in non-blocking mode, so poll()
3475 * returns immediately.
3477 timeout
= handlep
->poll_timeout
;
3480 * If we got an ENETDOWN and haven't gotten an indication
3481 * that the device has gone away or that the device is up,
3482 * we don't yet know for certain whether the device has
3483 * gone away or not, do a poll() with a 1-millisecond timeout,
3484 * as we have to poll indefinitely for "device went away"
3485 * indications until we either get one or see that the
3488 if (handlep
->netdown
) {
3492 ret
= poll(pollinfo
, 2, timeout
);
3495 * Error. If it's not EINTR, report it.
3497 if (errno
!= EINTR
) {
3498 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3499 PCAP_ERRBUF_SIZE
, errno
,
3500 "can't poll on packet socket");
3505 * It's EINTR; if we were told to break out of
3508 if (handle
->break_loop
) {
3509 handle
->break_loop
= 0;
3510 return PCAP_ERROR_BREAK
;
3512 } else if (ret
> 0) {
3514 * OK, some descriptor is ready.
3515 * Check the socket descriptor first.
3517 * As I read the Linux man page, pollinfo[0].revents
3518 * will either be POLLIN, POLLERR, POLLHUP, or POLLNVAL.
3520 if (pollinfo
[0].revents
== POLLIN
) {
3522 * OK, we may have packets to
3527 if (pollinfo
[0].revents
!= 0) {
3529 * There's some indication other than
3530 * "you can read on this descriptor" on
3533 if (pollinfo
[0].revents
& POLLNVAL
) {
3534 snprintf(handle
->errbuf
,
3536 "Invalid polling request on packet socket");
3539 if (pollinfo
[0].revents
& (POLLHUP
| POLLRDHUP
)) {
3540 snprintf(handle
->errbuf
,
3542 "Hangup on packet socket");
3545 if (pollinfo
[0].revents
& POLLERR
) {
3552 errlen
= sizeof(err
);
3553 if (getsockopt(handle
->fd
, SOL_SOCKET
,
3554 SO_ERROR
, &err
, &errlen
) == -1) {
3556 * The call *itself* returned
3557 * an error; make *that*
3564 * OK, we have the error.
3566 if (err
== ENETDOWN
) {
3568 * The device on which we're
3569 * capturing went away or the
3570 * interface was taken down.
3572 * We don't know for certain
3573 * which happened, and the
3574 * next poll() may indicate
3575 * that there are packets
3576 * to be read, so just set
3577 * a flag to get us to do
3578 * checks later, and set
3579 * the required select
3580 * timeout to 1 millisecond
3581 * so that event loops that
3582 * check our socket descriptor
3583 * also time out so that
3584 * they can call us and we
3585 * can do the checks.
3587 handlep
->netdown
= 1;
3588 handle
->required_select_timeout
= &netdown_timeout
;
3589 } else if (err
== 0) {
3591 * This shouldn't happen, so
3592 * report a special indication
3595 snprintf(handle
->errbuf
,
3597 "Error condition on packet socket: Reported error was 0");
3600 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3603 "Error condition on packet socket");
3609 * Now check the event device.
3611 if (pollinfo
[1].revents
& POLLIN
) {
3616 * This should never fail, but, just
3619 nread
= read(handlep
->poll_breakloop_fd
, &value
,
3622 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3625 "Error reading from event FD");
3630 * According to the Linux read(2) man
3631 * page, read() will transfer at most
3632 * 2^31-1 bytes, so the return value is
3633 * either -1 or a value between 0
3634 * and 2^31-1, so it's non-negative.
3636 * Cast it to size_t to squelch
3637 * warnings from the compiler; add this
3638 * comment to squelch warnings from
3639 * humans reading the code. :-)
3641 * Don't treat an EOF as an error, but
3642 * *do* treat a short read as an error;
3643 * that "shouldn't happen", but....
3646 (size_t)nread
< sizeof(value
)) {
3647 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3648 "Short read from event FD: expected %zu, got %zd",
3649 sizeof(value
), nread
);
3654 * This event gets signaled by a
3655 * pcap_breakloop() call; if we were told
3656 * to break out of the loop, do so.
3658 if (handle
->break_loop
) {
3659 handle
->break_loop
= 0;
3660 return PCAP_ERROR_BREAK
;
3668 * 1) we got neither an error from poll() nor any
3669 * readable descriptors, in which case there
3670 * are no packets waiting to read
3674 * 2) We got readable descriptors but the PF_PACKET
3675 * socket wasn't one of them, in which case there
3676 * are no packets waiting to read
3678 * so, if we got an ENETDOWN, we've drained whatever
3679 * packets were available to read at the point of the
3682 * So, if we got an ENETDOWN and haven't gotten an indication
3683 * that the device has gone away or that the device is up,
3684 * we don't yet know for certain whether the device has
3685 * gone away or not, check whether the device exists and is
3688 if (handlep
->netdown
) {
3689 if (!device_still_exists(handle
)) {
3691 * The device doesn't exist any more;
3694 * XXX - we should really return an
3695 * appropriate error for that, but
3696 * pcap_dispatch() etc. aren't documented
3697 * as having error returns other than
3698 * PCAP_ERROR or PCAP_ERROR_BREAK.
3700 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3701 "The interface disappeared");
3706 * The device still exists; try to see if it's up.
3708 memset(&ifr
, 0, sizeof(ifr
));
3709 pcap_strlcpy(ifr
.ifr_name
, handlep
->device
,
3710 sizeof(ifr
.ifr_name
));
3711 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3712 if (errno
== ENXIO
|| errno
== ENODEV
) {
3714 * OK, *now* it's gone.
3716 * XXX - see above comment.
3718 snprintf(handle
->errbuf
,
3720 "The interface disappeared");
3723 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3724 PCAP_ERRBUF_SIZE
, errno
,
3725 "%s: Can't get flags",
3730 if (ifr
.ifr_flags
& IFF_UP
) {
3732 * It's up, so it definitely still exists.
3733 * Cancel the ENETDOWN indication - we
3734 * presumably got it due to the interface
3735 * going down rather than the device going
3736 * away - and revert to "no required select
3739 handlep
->netdown
= 0;
3740 handle
->required_select_timeout
= NULL
;
3745 * If we're in non-blocking mode, just quit now, rather
3746 * than spinning in a loop doing poll()s that immediately
3747 * time out if there's no indication on any descriptor.
3749 if (handlep
->poll_timeout
== 0)
3755 /* handle a single memory mapped packet */
3756 static int pcap_handle_packet_mmap(
3758 pcap_handler callback
,
3760 unsigned char *frame
,
3761 unsigned int tp_len
,
3762 unsigned int tp_mac
,
3763 unsigned int tp_snaplen
,
3764 unsigned int tp_sec
,
3765 unsigned int tp_usec
,
3766 int tp_vlan_tci_valid
,
3770 struct pcap_linux
*handlep
= handle
->priv
;
3772 struct sockaddr_ll
*sll
;
3773 struct pcap_pkthdr pcaphdr
;
3774 pcap_can_socketcan_hdr
*canhdr
;
3775 unsigned int snaplen
= tp_snaplen
;
3776 struct utsname utsname
;
3778 /* perform sanity check on internal offset. */
3779 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3781 * Report some system information as a debugging aid.
3783 if (uname(&utsname
) != -1) {
3784 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3785 "corrupted frame on kernel ring mac "
3786 "offset %u + caplen %u > frame len %d "
3787 "(kernel %.32s version %s, machine %.16s)",
3788 tp_mac
, tp_snaplen
, handle
->bufsize
,
3789 utsname
.release
, utsname
.version
,
3792 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3793 "corrupted frame on kernel ring mac "
3794 "offset %u + caplen %u > frame len %d",
3795 tp_mac
, tp_snaplen
, handle
->bufsize
);
3800 /* run filter on received packet
3801 * If the kernel filtering is enabled we need to run the
3802 * filter until all the frames present into the ring
3803 * at filter creation time are processed.
3804 * In this case, blocks_to_filter_in_userland is used
3805 * as a counter for the packet we need to filter.
3806 * Note: alternatively it could be possible to stop applying
3807 * the filter when the ring became empty, but it can possibly
3808 * happen a lot later... */
3809 bp
= frame
+ tp_mac
;
3811 /* if required build in place the sll header*/
3812 sll
= (void *)(frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
));
3813 if (handlep
->cooked
) {
3814 if (handle
->linktype
== DLT_LINUX_SLL2
) {
3815 struct sll2_header
*hdrp
;
3818 * The kernel should have left us with enough
3819 * space for an sll header; back up the packet
3820 * data pointer into that space, as that'll be
3821 * the beginning of the packet we pass to the
3827 * Let's make sure that's past the end of
3828 * the tpacket header, i.e. >=
3829 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3830 * don't step on the header when we construct
3833 if (bp
< (u_char
*)frame
+
3834 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
3835 sizeof(struct sockaddr_ll
)) {
3836 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3837 "cooked-mode frame doesn't have room for sll header");
3842 * OK, that worked; construct the sll header.
3844 hdrp
= (struct sll2_header
*)bp
;
3845 hdrp
->sll2_protocol
= sll
->sll_protocol
;
3846 hdrp
->sll2_reserved_mbz
= 0;
3847 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
3848 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
3849 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
3850 hdrp
->sll2_halen
= sll
->sll_halen
;
3851 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3853 snaplen
+= sizeof(struct sll2_header
);
3855 struct sll_header
*hdrp
;
3858 * The kernel should have left us with enough
3859 * space for an sll header; back up the packet
3860 * data pointer into that space, as that'll be
3861 * the beginning of the packet we pass to the
3867 * Let's make sure that's past the end of
3868 * the tpacket header, i.e. >=
3869 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3870 * don't step on the header when we construct
3873 if (bp
< (u_char
*)frame
+
3874 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
3875 sizeof(struct sockaddr_ll
)) {
3876 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3877 "cooked-mode frame doesn't have room for sll header");
3882 * OK, that worked; construct the sll header.
3884 hdrp
= (struct sll_header
*)bp
;
3885 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
3886 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3887 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3888 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3889 hdrp
->sll_protocol
= sll
->sll_protocol
;
3891 snaplen
+= sizeof(struct sll_header
);
3895 * If this is a packet from a CAN device, so that
3896 * sll->sll_hatype is ARPHRD_CAN, then, as we're
3897 * not capturing in cooked mode, its link-layer
3898 * type is DLT_CAN_SOCKETCAN. Fix up the header
3899 * provided by the code below us to match what
3900 * DLT_CAN_SOCKETCAN is expected to provide.
3902 if (sll
->sll_hatype
== ARPHRD_CAN
) {
3904 * DLT_CAN_SOCKETCAN is specified as having the
3905 * CAN ID and flags in network byte order, but
3906 * capturing on a CAN device provides it in host
3907 * byte order. Convert it to network byte order.
3909 canhdr
= (pcap_can_socketcan_hdr
*)bp
;
3910 canhdr
->can_id
= htonl(canhdr
->can_id
);
3913 * In addition, set the CANFD_FDF flag if
3914 * the protocol is LINUX_SLL_P_CANFD, as
3915 * the protocol field itself isn't in
3916 * the packet to indicate that it's a
3919 uint16_t protocol
= ntohs(sll
->sll_protocol
);
3920 if (protocol
== LINUX_SLL_P_CANFD
) {
3921 canhdr
->fd_flags
|= CANFD_FDF
;
3924 * Zero out all the unknown bits in
3925 * fd_flags and clear the reserved
3926 * fields, so that a program reading
3927 * this can assume that CANFD_FDF
3928 * is set because we set it, not
3929 * because some uninitialized crap
3930 * was provided in the fd_flags
3933 * (At least some LINKTYPE_CAN_SOCKETCAN
3934 * files attached to Wireshark bugs
3935 * had uninitialized junk there, so it
3938 * Update this if Linux adds more flag
3939 * bits to the fd_flags field or uses
3940 * either of the reserved fields for
3943 canhdr
->fd_flags
&= ~(CANFD_FDF
|CANFD_ESI
|CANFD_BRS
);
3944 canhdr
->reserved1
= 0;
3945 canhdr
->reserved2
= 0;
3948 * Clear CANFD_FDF if it's set (probably
3949 * again meaning that that field is
3950 * uninitialized junk).
3952 canhdr
->fd_flags
&= ~CANFD_FDF
;
3957 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
3958 struct pcap_bpf_aux_data aux_data
;
3960 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
3961 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
3963 if (pcap_filter_with_aux_data(handle
->fcode
.bf_insns
,
3971 if (!linux_check_direction(handle
, sll
))
3974 /* get required packet info from ring header */
3975 pcaphdr
.ts
.tv_sec
= tp_sec
;
3976 pcaphdr
.ts
.tv_usec
= tp_usec
;
3977 pcaphdr
.caplen
= tp_snaplen
;
3978 pcaphdr
.len
= tp_len
;
3980 /* if required build in place the sll header*/
3981 if (handlep
->cooked
) {
3982 /* update packet len */
3983 if (handle
->linktype
== DLT_LINUX_SLL2
) {
3984 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
3985 pcaphdr
.len
+= SLL2_HDR_LEN
;
3987 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3988 pcaphdr
.len
+= SLL_HDR_LEN
;
3992 if (tp_vlan_tci_valid
&&
3993 handlep
->vlan_offset
!= -1 &&
3994 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
3996 struct vlan_tag
*tag
;
3999 * Move everything in the header, except the type field,
4000 * down VLAN_TAG_LEN bytes, to allow us to insert the
4001 * VLAN tag between that stuff and the type field.
4004 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4007 * Now insert the tag.
4009 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4010 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4011 tag
->vlan_tci
= htons(tp_vlan_tci
);
4014 * Add the tag to the packet lengths.
4016 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4017 pcaphdr
.len
+= VLAN_TAG_LEN
;
4021 * The only way to tell the kernel to cut off the
4022 * packet at a snapshot length is with a filter program;
4023 * if there's no filter program, the kernel won't cut
4026 * Trim the snapshot length to be no longer than the
4027 * specified snapshot length.
4029 * XXX - an alternative is to put a filter, consisting
4030 * of a "ret <snaplen>" instruction, on the socket
4031 * in the activate routine, so that the truncation is
4032 * done in the kernel even if nobody specified a filter;
4033 * that means that less buffer space is consumed in
4034 * the memory-mapped buffer.
4036 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
4037 pcaphdr
.caplen
= handle
->snapshot
;
4039 /* pass the packet to the user */
4040 callback(user
, &pcaphdr
, bp
);
4046 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4049 struct pcap_linux
*handlep
= handle
->priv
;
4054 /* wait for frames availability.*/
4055 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4056 if (!packet_mmap_acquire(h
.h2
)) {
4058 * The current frame is owned by the kernel; wait for
4059 * a frame to be handed to us.
4061 ret
= pcap_wait_for_frames_mmap(handle
);
4067 /* non-positive values of max_packets are used to require all
4068 * packets currently available in the ring */
4069 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4071 * Get the current ring buffer frame, and break if
4072 * it's still owned by the kernel.
4074 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4075 if (!packet_mmap_acquire(h
.h2
))
4078 ret
= pcap_handle_packet_mmap(
4087 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4088 VLAN_VALID(h
.h2
, h
.h2
),
4090 VLAN_TPID(h
.h2
, h
.h2
));
4093 } else if (ret
< 0) {
4098 * Hand this block back to the kernel, and, if we're
4099 * counting blocks that need to be filtered in userland
4100 * after having been filtered by the kernel, count
4101 * the one we've just processed.
4103 packet_mmap_release(h
.h2
);
4104 if (handlep
->blocks_to_filter_in_userland
> 0) {
4105 handlep
->blocks_to_filter_in_userland
--;
4106 if (handlep
->blocks_to_filter_in_userland
== 0) {
4108 * No more blocks need to be filtered
4111 handlep
->filter_in_userland
= 0;
4116 if (++handle
->offset
>= handle
->cc
)
4119 /* check for break loop condition*/
4120 if (handle
->break_loop
) {
4121 handle
->break_loop
= 0;
4122 return PCAP_ERROR_BREAK
;
4128 #ifdef HAVE_TPACKET3
4130 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4133 struct pcap_linux
*handlep
= handle
->priv
;
4139 if (handlep
->current_packet
== NULL
) {
4140 /* wait for frames availability.*/
4141 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4142 if (!packet_mmap_v3_acquire(h
.h3
)) {
4144 * The current frame is owned by the kernel; wait
4145 * for a frame to be handed to us.
4147 ret
= pcap_wait_for_frames_mmap(handle
);
4153 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4154 if (!packet_mmap_v3_acquire(h
.h3
)) {
4155 if (pkts
== 0 && handlep
->timeout
== 0) {
4156 /* Block until we see a packet. */
4162 /* non-positive values of max_packets are used to require all
4163 * packets currently available in the ring */
4164 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4165 int packets_to_read
;
4167 if (handlep
->current_packet
== NULL
) {
4168 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4169 if (!packet_mmap_v3_acquire(h
.h3
))
4172 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4173 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4175 packets_to_read
= handlep
->packets_left
;
4177 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) &&
4178 packets_to_read
> (max_packets
- pkts
)) {
4180 * We've been given a maximum number of packets
4181 * to process, and there are more packets in
4182 * this buffer than that. Only process enough
4183 * of them to get us up to that maximum.
4185 packets_to_read
= max_packets
- pkts
;
4188 while (packets_to_read
-- && !handle
->break_loop
) {
4189 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4190 ret
= pcap_handle_packet_mmap(
4194 handlep
->current_packet
,
4197 tp3_hdr
->tp_snaplen
,
4199 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4200 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
4201 tp3_hdr
->hv1
.tp_vlan_tci
,
4202 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
4205 } else if (ret
< 0) {
4206 handlep
->current_packet
= NULL
;
4209 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4210 handlep
->packets_left
--;
4213 if (handlep
->packets_left
<= 0) {
4215 * Hand this block back to the kernel, and, if
4216 * we're counting blocks that need to be
4217 * filtered in userland after having been
4218 * filtered by the kernel, count the one we've
4221 packet_mmap_v3_release(h
.h3
);
4222 if (handlep
->blocks_to_filter_in_userland
> 0) {
4223 handlep
->blocks_to_filter_in_userland
--;
4224 if (handlep
->blocks_to_filter_in_userland
== 0) {
4226 * No more blocks need to be filtered
4229 handlep
->filter_in_userland
= 0;
4234 if (++handle
->offset
>= handle
->cc
)
4237 handlep
->current_packet
= NULL
;
4240 /* check for break loop condition*/
4241 if (handle
->break_loop
) {
4242 handle
->break_loop
= 0;
4243 return PCAP_ERROR_BREAK
;
4246 if (pkts
== 0 && handlep
->timeout
== 0) {
4247 /* Block until we see a packet. */
4252 #endif /* HAVE_TPACKET3 */
4255 * Attach the given BPF code to the packet capture device.
4258 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
4260 struct pcap_linux
*handlep
;
4261 struct sock_fprog fcode
;
4262 int can_filter_in_kernel
;
4269 pcap_strlcpy(handle
->errbuf
, "setfilter: No filter specified",
4274 handlep
= handle
->priv
;
4276 /* Make our private copy of the filter */
4278 if (install_bpf_program(handle
, filter
) < 0)
4279 /* install_bpf_program() filled in errbuf */
4283 * Run user level packet filter by default. Will be overridden if
4284 * installing a kernel filter succeeds.
4286 handlep
->filter_in_userland
= 1;
4288 /* Install kernel level filter if possible */
4291 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
4293 * fcode.len is an unsigned short for current kernel.
4294 * I have yet to see BPF-Code with that much
4295 * instructions but still it is possible. So for the
4296 * sake of correctness I added this check.
4298 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
4300 fcode
.filter
= NULL
;
4301 can_filter_in_kernel
= 0;
4303 #endif /* USHRT_MAX */
4306 * Oh joy, the Linux kernel uses struct sock_fprog instead
4307 * of struct bpf_program and of course the length field is
4308 * of different size. Pointed out by Sebastian
4310 * Oh, and we also need to fix it up so that all "ret"
4311 * instructions with non-zero operands have MAXIMUM_SNAPLEN
4312 * as the operand if we're not capturing in memory-mapped
4313 * mode, and so that, if we're in cooked mode, all memory-
4314 * reference instructions use special magic offsets in
4315 * references to the link-layer header and assume that the
4316 * link-layer payload begins at 0; "fix_program()" will do
4319 switch (fix_program(handle
, &fcode
)) {
4324 * Fatal error; just quit.
4325 * (The "default" case shouldn't happen; we
4326 * return -1 for that reason.)
4332 * The program performed checks that we can't make
4333 * work in the kernel.
4335 can_filter_in_kernel
= 0;
4340 * We have a filter that'll work in the kernel.
4342 can_filter_in_kernel
= 1;
4348 * NOTE: at this point, we've set both the "len" and "filter"
4349 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
4350 * those are the only members of the "sock_fprog" structure,
4351 * so we initialize every member of that structure.
4353 * If there is anything in "fcode" that is not initialized,
4354 * it is either a field added in a later kernel, or it's
4357 * If a new field is added, this code needs to be updated
4358 * to set it correctly.
4360 * If there are no other fields, then:
4362 * if the Linux kernel looks at the padding, it's
4365 * if the Linux kernel doesn't look at the padding,
4366 * then if some tool complains that we're passing
4367 * uninitialized data to the kernel, then the tool
4368 * is buggy and needs to understand that it's just
4371 if (can_filter_in_kernel
) {
4372 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
4375 * Installation succeeded - using kernel filter,
4376 * so userland filtering not needed.
4378 handlep
->filter_in_userland
= 0;
4380 else if (err
== -1) /* Non-fatal error */
4383 * Print a warning if we weren't able to install
4384 * the filter for a reason other than "this kernel
4385 * isn't configured to support socket filters.
4387 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
4389 "Warning: Kernel filter failed: %s\n",
4390 pcap_strerror(errno
));
4396 * If we're not using the kernel filter, get rid of any kernel
4397 * filter that might've been there before, e.g. because the
4398 * previous filter could work in the kernel, or because some other
4399 * code attached a filter to the socket by some means other than
4400 * calling "pcap_setfilter()". Otherwise, the kernel filter may
4401 * filter out packets that would pass the new userland filter.
4403 if (handlep
->filter_in_userland
) {
4404 if (reset_kernel_filter(handle
) == -1) {
4405 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4406 PCAP_ERRBUF_SIZE
, errno
,
4407 "can't remove kernel filter");
4408 err
= -2; /* fatal error */
4413 * Free up the copy of the filter that was made by "fix_program()".
4415 if (fcode
.filter
!= NULL
)
4423 * If we're filtering in userland, there's nothing to do;
4424 * the new filter will be used for the next packet.
4426 if (handlep
->filter_in_userland
)
4430 * We're filtering in the kernel; the packets present in
4431 * all blocks currently in the ring were already filtered
4432 * by the old filter, and so will need to be filtered in
4433 * userland by the new filter.
4435 * Get an upper bound for the number of such blocks; first,
4436 * walk the ring backward and count the free blocks.
4438 offset
= handle
->offset
;
4440 offset
= handle
->cc
- 1;
4441 for (n
=0; n
< handle
->cc
; ++n
) {
4443 offset
= handle
->cc
- 1;
4444 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
4449 * If we found free blocks, decrement the count of free
4450 * blocks by 1, just in case we lost a race with another
4451 * thread of control that was adding a packet while
4452 * we were counting and that had run the filter before
4455 * XXX - could there be more than one block added in
4458 * XXX - is there a way to avoid that race, e.g. somehow
4459 * wait for all packets that passed the old filter to
4460 * be added to the ring?
4466 * Set the count of blocks worth of packets to filter
4467 * in userland to the total number of blocks in the
4468 * ring minus the number of free blocks we found, and
4469 * turn on userland filtering. (The count of blocks
4470 * worth of packets to filter in userland is guaranteed
4471 * not to be zero - n, above, couldn't be set to a
4472 * value > handle->cc, and if it were equal to
4473 * handle->cc, it wouldn't be zero, and thus would
4474 * be decremented to handle->cc - 1.)
4476 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4477 handlep
->filter_in_userland
= 1;
4483 * Return the index of the given device name. Fill ebuf and return
4487 iface_get_id(int fd
, const char *device
, char *ebuf
)
4491 memset(&ifr
, 0, sizeof(ifr
));
4492 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4494 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4495 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4496 errno
, "SIOCGIFINDEX");
4500 return ifr
.ifr_ifindex
;
4504 * Bind the socket associated with FD to the given device.
4505 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
4508 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
4510 struct sockaddr_ll sll
;
4512 socklen_t errlen
= sizeof(err
);
4514 memset(&sll
, 0, sizeof(sll
));
4515 sll
.sll_family
= AF_PACKET
;
4516 sll
.sll_ifindex
= ifindex
< 0 ? 0 : ifindex
;
4517 sll
.sll_protocol
= protocol
;
4519 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4520 if (errno
== ENETDOWN
) {
4522 * Return a "network down" indication, so that
4523 * the application can report that rather than
4524 * saying we had a mysterious failure and
4525 * suggest that they report a problem to the
4526 * libpcap developers.
4528 return PCAP_ERROR_IFACE_NOT_UP
;
4530 if (errno
== ENODEV
)
4531 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
4534 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4539 /* Any pending errors, e.g., network is down? */
4541 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4542 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4543 errno
, "getsockopt (SO_ERROR)");
4547 if (err
== ENETDOWN
) {
4549 * Return a "network down" indication, so that
4550 * the application can report that rather than
4551 * saying we had a mysterious failure and
4552 * suggest that they report a problem to the
4553 * libpcap developers.
4555 return PCAP_ERROR_IFACE_NOT_UP
;
4556 } else if (err
> 0) {
4557 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4566 * Try to enter monitor mode.
4567 * If we have libnl, try to create a new monitor-mode device and
4568 * capture on that; otherwise, just say "not supported".
4572 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4574 struct pcap_linux
*handlep
= handle
->priv
;
4576 char phydev_path
[PATH_MAX
+1];
4577 struct nl80211_state nlstate
;
4582 * Is this a mac80211 device?
4584 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
4586 return ret
; /* error */
4588 return 0; /* no error, but not mac80211 device */
4591 * XXX - is this already a monN device?
4592 * If so, we're done.
4596 * OK, it's apparently a mac80211 device.
4597 * Try to find an unused monN device for it.
4599 ret
= nl80211_init(handle
, &nlstate
, device
);
4602 for (n
= 0; n
< UINT_MAX
; n
++) {
4606 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
4608 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
4609 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
4612 * Success. We don't clean up the libnl state
4613 * yet, as we'll be using it later.
4619 * Hard failure. Just return ret; handle->errbuf
4620 * has already been set.
4622 nl80211_cleanup(&nlstate
);
4627 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4628 "%s: No free monN interfaces", device
);
4629 nl80211_cleanup(&nlstate
);
4636 * Sleep for .1 seconds.
4639 delay
.tv_nsec
= 500000000;
4640 nanosleep(&delay
, NULL
);
4644 * If we haven't already done so, arrange to have
4645 * "pcap_close_all()" called when we exit.
4647 if (!pcap_do_addexit(handle
)) {
4649 * "atexit()" failed; don't put the interface
4650 * in rfmon mode, just give up.
4652 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
4653 handlep
->mondevice
);
4654 nl80211_cleanup(&nlstate
);
4659 * Now configure the monitor interface up.
4661 memset(&ifr
, 0, sizeof(ifr
));
4662 pcap_strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
4663 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4664 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4665 errno
, "%s: Can't get flags for %s", device
,
4666 handlep
->mondevice
);
4667 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
4668 handlep
->mondevice
);
4669 nl80211_cleanup(&nlstate
);
4672 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
4673 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4674 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4675 errno
, "%s: Can't set flags for %s", device
,
4676 handlep
->mondevice
);
4677 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
4678 handlep
->mondevice
);
4679 nl80211_cleanup(&nlstate
);
4684 * Success. Clean up the libnl state.
4686 nl80211_cleanup(&nlstate
);
4689 * Note that we have to delete the monitor device when we close
4692 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
4695 * Add this to the list of pcaps to close when we exit.
4697 pcap_add_to_pcaps_to_close(handle
);
4701 #else /* HAVE_LIBNL */
4703 enter_rfmon_mode(pcap_t
*handle _U_
, int sock_fd _U_
, const char *device _U_
)
4706 * We don't have libnl, so we can't do monitor mode.
4710 #endif /* HAVE_LIBNL */
4712 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4714 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
4716 static const struct {
4717 int soft_timestamping_val
;
4718 int pcap_tstamp_val
;
4719 } sof_ts_type_map
[3] = {
4720 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
4721 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
4722 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
4724 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
4727 * Set the list of time stamping types to include all types.
4730 iface_set_all_ts_types(pcap_t
*handle
, char *ebuf
)
4734 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
4735 if (handle
->tstamp_type_list
== NULL
) {
4736 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4740 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
4741 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
4742 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
4746 #ifdef ETHTOOL_GET_TS_INFO
4748 * Get a list of time stamping capabilities.
4751 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf
)
4755 struct ethtool_ts_info info
;
4760 * This doesn't apply to the "any" device; you can't say "turn on
4761 * hardware time stamping for all devices that exist now and arrange
4762 * that it be turned on for any device that appears in the future",
4763 * and not all devices even necessarily *support* hardware time
4764 * stamping, so don't report any time stamp types.
4766 if (strcmp(device
, "any") == 0) {
4767 handle
->tstamp_type_list
= NULL
;
4772 * Create a socket from which to fetch time stamping capabilities.
4774 fd
= get_if_ioctl_socket();
4776 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4777 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
4781 memset(&ifr
, 0, sizeof(ifr
));
4782 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4783 memset(&info
, 0, sizeof(info
));
4784 info
.cmd
= ETHTOOL_GET_TS_INFO
;
4785 ifr
.ifr_data
= (caddr_t
)&info
;
4786 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
4787 int save_errno
= errno
;
4790 switch (save_errno
) {
4795 * OK, this OS version or driver doesn't support
4796 * asking for the time stamping types, so let's
4797 * just return all the possible types.
4799 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
4805 * OK, no such device.
4806 * The user will find that out when they try to
4807 * activate the device; just return an empty
4808 * list of time stamp types.
4810 handle
->tstamp_type_list
= NULL
;
4817 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4819 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
4827 * Do we support hardware time stamping of *all* packets?
4829 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
4831 * No, so don't report any time stamp types.
4833 * XXX - some devices either don't report
4834 * HWTSTAMP_FILTER_ALL when they do support it, or
4835 * report HWTSTAMP_FILTER_ALL but map it to only
4836 * time stamping a few PTP packets. See
4837 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
4839 handle
->tstamp_type_list
= NULL
;
4844 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
4845 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
4848 if (num_ts_types
!= 0) {
4849 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
4850 if (handle
->tstamp_type_list
== NULL
) {
4851 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4855 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
4856 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
4857 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
4861 handle
->tstamp_type_count
= num_ts_types
;
4863 handle
->tstamp_type_list
= NULL
;
4867 #else /* ETHTOOL_GET_TS_INFO */
4869 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf
)
4872 * This doesn't apply to the "any" device; you can't say "turn on
4873 * hardware time stamping for all devices that exist now and arrange
4874 * that it be turned on for any device that appears in the future",
4875 * and not all devices even necessarily *support* hardware time
4876 * stamping, so don't report any time stamp types.
4878 if (strcmp(device
, "any") == 0) {
4879 handle
->tstamp_type_list
= NULL
;
4884 * We don't have an ioctl to use to ask what's supported,
4885 * so say we support everything.
4887 if (iface_set_all_ts_types(handle
, ebuf
) == -1)
4891 #endif /* ETHTOOL_GET_TS_INFO */
4893 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
4896 * Find out if we have any form of fragmentation/reassembly offloading.
4898 * We do so using SIOCETHTOOL checking for various types of offloading;
4899 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4900 * of the types of offloading, there's nothing we can do to check, so
4901 * we just say "no, we don't".
4903 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
4904 * indications that the operation isn't supported. We do EPERM
4905 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
4906 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
4907 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
4908 * and 3) does the "is this permitted" check before doing the "is
4909 * this even supported" check, so it fails with "this is not permitted"
4910 * rather than "this is not even supported". To work around this
4911 * annoyance, we only treat EPERM as an error for the first feature,
4912 * and assume that they all do the same permission checks, so if the
4913 * first one is allowed all the others are allowed if supported.
4915 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
4917 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
,
4921 struct ethtool_value eval
;
4923 memset(&ifr
, 0, sizeof(ifr
));
4924 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
4927 ifr
.ifr_data
= (caddr_t
)&eval
;
4928 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
4929 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
||
4930 (errno
== EPERM
&& eperm_ok
)) {
4932 * OK, let's just return 0, which, in our
4933 * case, either means "no, what we're asking
4934 * about is not enabled" or "all the flags
4935 * are clear (i.e., nothing is enabled)".
4939 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4940 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
4941 handle
->opt
.device
, cmdname
);
4948 * XXX - it's annoying that we have to check for offloading at all, but,
4949 * given that we have to, it's still annoying that we have to check for
4950 * particular types of offloading, especially that shiny new types of
4951 * offloading may be added - and, worse, may not be checkable with
4952 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
4953 * theory, give those to you, but the actual flags being used are
4954 * opaque (defined in a non-uapi header), and there doesn't seem to
4955 * be any obvious way to ask the kernel what all the offloading flags
4956 * are - at best, you can ask for a set of strings(!) to get *names*
4957 * for various flags. (That whole mechanism appears to have been
4958 * designed for the sole purpose of letting ethtool report flags
4959 * by name and set flags by name, with the names having no semantics
4960 * ethtool understands.)
4963 iface_get_offload(pcap_t
*handle
)
4968 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO", 0);
4972 return 1; /* TCP segmentation offloading on */
4977 * XXX - will this cause large unsegmented packets to be
4978 * handed to PF_PACKET sockets on transmission? If not,
4979 * this need not be checked.
4981 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO", 0);
4985 return 1; /* generic segmentation offloading on */
4988 #ifdef ETHTOOL_GFLAGS
4989 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS", 0);
4992 if (ret
& ETH_FLAG_LRO
)
4993 return 1; /* large receive offloading on */
4998 * XXX - will this cause large reassembled packets to be
4999 * handed to PF_PACKET sockets on receipt? If not,
5000 * this need not be checked.
5002 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO", 0);
5006 return 1; /* generic (large) receive offloading on */
5011 * Do this one last, as support for it was removed in later
5012 * kernels, and it fails with EPERM on those kernels rather
5013 * than with EOPNOTSUPP (see explanation in comment for
5014 * iface_ethtool_flag_ioctl()).
5016 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO", 1);
5020 return 1; /* UDP fragmentation offloading on */
5025 #else /* SIOCETHTOOL */
5027 iface_get_offload(pcap_t
*handle _U_
)
5030 * XXX - do we need to get this information if we don't
5031 * have the ethtool ioctls? If so, how do we do that?
5035 #endif /* SIOCETHTOOL */
5037 static struct dsa_proto
{
5039 bpf_u_int32 linktype
;
5042 * None is special and indicates that the interface does not have
5043 * any tagging protocol configured, and is therefore a standard
5044 * Ethernet interface.
5046 { "none", DLT_EN10MB
},
5047 { "brcm", DLT_DSA_TAG_BRCM
},
5048 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND
},
5049 { "dsa", DLT_DSA_TAG_DSA
},
5050 { "edsa", DLT_DSA_TAG_EDSA
},
5054 iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
)
5059 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
5060 * the tag *shouldn't* have some huge long name, and making
5061 * it smaller keeps newer versions of GCC from whining that
5062 * the error message if we don't support the tag could
5063 * overflow the error message buffer.
5069 fd
= asprintf(&pathstr
, "/sys/class/net/%s/dsa/tagging", device
);
5071 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5076 fd
= open(pathstr
, O_RDONLY
);
5079 * This is not fatal, kernel >= 4.20 *might* expose this attribute
5084 r
= read(fd
, buf
, sizeof(buf
) - 1);
5086 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5094 * Buffer should be LF terminated.
5096 if (buf
[r
- 1] == '\n')
5100 for (i
= 0; i
< sizeof(dsa_protos
) / sizeof(dsa_protos
[0]); i
++) {
5101 if (strlen(dsa_protos
[i
].name
) == (size_t)r
&&
5102 strcmp(buf
, dsa_protos
[i
].name
) == 0) {
5103 handle
->linktype
= dsa_protos
[i
].linktype
;
5104 switch (dsa_protos
[i
].linktype
) {
5113 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5114 "unsupported DSA tag: %s", buf
);
5120 * Query the kernel for the MTU of the given interface.
5123 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5128 return BIGGER_THAN_ALL_MTUS
;
5130 memset(&ifr
, 0, sizeof(ifr
));
5131 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5133 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5134 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5135 errno
, "SIOCGIFMTU");
5143 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5146 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5151 memset(&ifr
, 0, sizeof(ifr
));
5152 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5154 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5155 if (errno
== ENODEV
) {
5159 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5162 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5163 errno
, "SIOCGIFHWADDR");
5167 return ifr
.ifr_hwaddr
.sa_family
;
5171 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
5173 struct pcap_linux
*handlep
= handle
->priv
;
5176 register struct bpf_insn
*p
;
5181 * Make a copy of the filter, and modify that copy if
5184 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5185 len
= handle
->fcode
.bf_len
;
5186 f
= (struct bpf_insn
*)malloc(prog_size
);
5188 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5192 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5194 fcode
->filter
= (struct sock_filter
*) f
;
5196 for (i
= 0; i
< len
; ++i
) {
5199 * What type of instruction is this?
5201 switch (BPF_CLASS(p
->code
)) {
5206 * It's a load instruction; is it loading
5209 switch (BPF_MODE(p
->code
)) {
5215 * Yes; are we in cooked mode?
5217 if (handlep
->cooked
) {
5219 * Yes, so we need to fix this
5222 if (fix_offset(handle
, p
) < 0) {
5224 * We failed to do so.
5225 * Return 0, so our caller
5226 * knows to punt to userland.
5236 return 1; /* we succeeded */
5240 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
5243 * Existing references to auxiliary data shouldn't be adjusted.
5245 * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
5246 * we use >= and cast SKF_AD_OFF to unsigned.
5248 if (p
->k
>= (bpf_u_int32
)SKF_AD_OFF
)
5250 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5252 * What's the offset?
5254 if (p
->k
>= SLL2_HDR_LEN
) {
5256 * It's within the link-layer payload; that starts
5257 * at an offset of 0, as far as the kernel packet
5258 * filter is concerned, so subtract the length of
5259 * the link-layer header.
5261 p
->k
-= SLL2_HDR_LEN
;
5262 } else if (p
->k
== 0) {
5264 * It's the protocol field; map it to the
5265 * special magic kernel offset for that field.
5267 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5268 } else if (p
->k
== 4) {
5270 * It's the ifindex field; map it to the
5271 * special magic kernel offset for that field.
5273 p
->k
= SKF_AD_OFF
+ SKF_AD_IFINDEX
;
5274 } else if (p
->k
== 10) {
5276 * It's the packet type field; map it to the
5277 * special magic kernel offset for that field.
5279 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5280 } else if ((bpf_int32
)(p
->k
) > 0) {
5282 * It's within the header, but it's not one of
5283 * those fields; we can't do that in the kernel,
5284 * so punt to userland.
5290 * What's the offset?
5292 if (p
->k
>= SLL_HDR_LEN
) {
5294 * It's within the link-layer payload; that starts
5295 * at an offset of 0, as far as the kernel packet
5296 * filter is concerned, so subtract the length of
5297 * the link-layer header.
5299 p
->k
-= SLL_HDR_LEN
;
5300 } else if (p
->k
== 0) {
5302 * It's the packet type field; map it to the
5303 * special magic kernel offset for that field.
5305 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5306 } else if (p
->k
== 14) {
5308 * It's the protocol field; map it to the
5309 * special magic kernel offset for that field.
5311 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5312 } else if ((bpf_int32
)(p
->k
) > 0) {
5314 * It's within the header, but it's not one of
5315 * those fields; we can't do that in the kernel,
5316 * so punt to userland.
5325 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5327 int total_filter_on
= 0;
5333 * The socket filter code doesn't discard all packets queued
5334 * up on the socket when the filter is changed; this means
5335 * that packets that don't match the new filter may show up
5336 * after the new filter is put onto the socket, if those
5337 * packets haven't yet been read.
5339 * This means, for example, that if you do a tcpdump capture
5340 * with a filter, the first few packets in the capture might
5341 * be packets that wouldn't have passed the filter.
5343 * We therefore discard all packets queued up on the socket
5344 * when setting a kernel filter. (This isn't an issue for
5345 * userland filters, as the userland filtering is done after
5346 * packets are queued up.)
5348 * To flush those packets, we put the socket in read-only mode,
5349 * and read packets from the socket until there are no more to
5352 * In order to keep that from being an infinite loop - i.e.,
5353 * to keep more packets from arriving while we're draining
5354 * the queue - we put the "total filter", which is a filter
5355 * that rejects all packets, onto the socket before draining
5358 * This code deliberately ignores any errors, so that you may
5359 * get bogus packets if an error occurs, rather than having
5360 * the filtering done in userland even if it could have been
5361 * done in the kernel.
5363 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5364 &total_fcode
, sizeof(total_fcode
)) == 0) {
5368 * Note that we've put the total filter onto the socket.
5370 total_filter_on
= 1;
5373 * Save the socket's current mode, and put it in
5374 * non-blocking mode; we drain it by reading packets
5375 * until we get an error (which is normally a
5376 * "nothing more to be read" error).
5378 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5379 if (save_mode
== -1) {
5380 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5381 PCAP_ERRBUF_SIZE
, errno
,
5382 "can't get FD flags when changing filter");
5385 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
5386 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5387 PCAP_ERRBUF_SIZE
, errno
,
5388 "can't set nonblocking mode when changing filter");
5391 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
5394 if (save_errno
!= EAGAIN
) {
5398 * If we can't restore the mode or reset the
5399 * kernel filter, there's nothing we can do.
5401 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
5402 (void)reset_kernel_filter(handle
);
5403 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5404 PCAP_ERRBUF_SIZE
, save_errno
,
5405 "recv failed when changing filter");
5408 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
5409 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5410 PCAP_ERRBUF_SIZE
, errno
,
5411 "can't restore FD flags when changing filter");
5417 * Now attach the new filter.
5419 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5420 fcode
, sizeof(*fcode
));
5421 if (ret
== -1 && total_filter_on
) {
5423 * Well, we couldn't set that filter on the socket,
5424 * but we could set the total filter on the socket.
5426 * This could, for example, mean that the filter was
5427 * too big to put into the kernel, so we'll have to
5428 * filter in userland; in any case, we'll be doing
5429 * filtering in userland, so we need to remove the
5430 * total filter so we see packets.
5435 * If this fails, we're really screwed; we have the
5436 * total filter on the socket, and it won't come off.
5437 * Report it as a fatal error.
5439 if (reset_kernel_filter(handle
) == -1) {
5440 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5441 PCAP_ERRBUF_SIZE
, errno
,
5442 "can't remove kernel total filter");
5443 return -2; /* fatal error */
5452 reset_kernel_filter(pcap_t
*handle
)
5456 * setsockopt() barfs unless it get a dummy parameter.
5457 * valgrind whines unless the value is initialized,
5458 * as it has no idea that setsockopt() ignores its
5463 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5464 &dummy
, sizeof(dummy
));
5466 * Ignore ENOENT - it means "we don't have a filter", so there
5467 * was no filter to remove, and there's still no filter.
5469 * Also ignore ENONET, as a lot of kernel versions had a
5470 * typo where ENONET, rather than ENOENT, was returned.
5472 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
5478 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
5480 if (pcap_check_activated(p
))
5481 return (PCAP_ERROR_ACTIVATED
);
5482 p
->opt
.protocol
= protocol
;
5487 * Libpcap version string.
5490 pcap_lib_version(void)
5492 #if defined(HAVE_TPACKET3)
5493 return (PCAP_VERSION_STRING
" (with TPACKET_V3)");
5495 return (PCAP_VERSION_STRING
" (with TPACKET_V2)");