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"
104 #include "diag-control.h"
107 * We require TPACKET_V2 support.
109 #ifndef TPACKET2_HDRLEN
110 #error "Libpcap will only work if TPACKET_V2 is supported; you must build for a 2.6.27 or later kernel"
113 /* check for memory mapped access avaibility. We assume every needed
114 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
115 * uses many ring related structs and macros */
116 #ifdef TPACKET3_HDRLEN
117 # define HAVE_TPACKET3
118 #endif /* TPACKET3_HDRLEN */
120 #include <linux/types.h>
121 #include <linux/filter.h>
123 #ifdef HAVE_LINUX_NET_TSTAMP_H
124 #include <linux/net_tstamp.h>
128 * For checking whether a device is a bonding device.
130 #include <linux/if_bonding.h>
133 * Got Wireless Extensions?
135 #ifdef HAVE_LINUX_WIRELESS_H
136 #include <linux/wireless.h>
137 #endif /* HAVE_LINUX_WIRELESS_H */
143 #include <linux/nl80211.h>
145 #include <netlink/genl/genl.h>
146 #include <netlink/genl/family.h>
147 #include <netlink/genl/ctrl.h>
148 #include <netlink/msg.h>
149 #include <netlink/attr.h>
150 #endif /* HAVE_LIBNL */
152 #ifndef HAVE_SOCKLEN_T
153 typedef int socklen_t
;
156 #define MAX_LINKHEADER_SIZE 256
159 * When capturing on all interfaces we use this as the buffer size.
160 * Should be bigger then all MTUs that occur in real life.
161 * 64kB should be enough for now.
163 #define BIGGER_THAN_ALL_MTUS (64*1024)
166 * Private data for capturing on Linux PF_PACKET sockets.
169 long long sysfs_dropped
; /* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */
170 struct pcap_stat stat
;
172 char *device
; /* device name */
173 int filter_in_userland
; /* must filter in userland */
174 int blocks_to_filter_in_userland
;
175 int must_do_on_close
; /* stuff we must do when we close */
176 int timeout
; /* timeout for buffering */
177 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
178 int ifindex
; /* interface index of device we're bound to */
179 int lo_ifindex
; /* interface index of the loopback device */
180 int netdown
; /* we got an ENETDOWN and haven't resolved it */
181 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
182 char *mondevice
; /* mac80211 monitor device we created */
183 u_char
*mmapbuf
; /* memory-mapped region pointer */
184 size_t mmapbuflen
; /* size of region */
185 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
186 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
187 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
188 u_char
*oneshot_buffer
; /* buffer for copy of packet */
189 int poll_timeout
; /* timeout to use in poll() */
191 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
192 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
194 int poll_breakloop_fd
; /* fd to an eventfd to break from blocking operations */
198 * Stuff to do when we close.
200 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
201 #define MUST_DELETE_MONIF 0x00000002 /* delete monitor-mode interface */
204 * Prototypes for internal functions and methods.
206 static int get_if_flags(const char *, bpf_u_int32
*, char *);
207 static int is_wifi(int, const char *);
208 static void map_arphrd_to_dlt(pcap_t
*, int, int, const char *, int);
209 static int pcap_activate_linux(pcap_t
*);
210 static int activate_pf_packet(pcap_t
*, int);
211 static int setup_mmapped(pcap_t
*, int *);
212 static int pcap_can_set_rfmon_linux(pcap_t
*);
213 static int pcap_inject_linux(pcap_t
*, const void *, int);
214 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
215 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
216 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
217 static int pcap_set_datalink_linux(pcap_t
*, int);
218 static void pcap_cleanup_linux(pcap_t
*);
221 struct tpacket2_hdr
*h2
;
223 struct tpacket_block_desc
*h3
;
228 #define RING_GET_FRAME_AT(h, offset) (((u_char **)h->buffer)[(offset)])
229 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
231 static void destroy_ring(pcap_t
*handle
);
232 static int create_ring(pcap_t
*handle
, int *status
);
233 static int prepare_tpacket_socket(pcap_t
*handle
);
234 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
236 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
238 static int pcap_setnonblock_linux(pcap_t
*p
, int nonblock
);
239 static int pcap_getnonblock_linux(pcap_t
*p
);
240 static void pcap_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
241 const u_char
*bytes
);
244 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
245 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
246 * or "on VLAN 0". There is no flag set in the tp_status field to
247 * distinguish between them.
249 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
250 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
251 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
252 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
254 * With a pre-3.0 kernel, we cannot distinguish between packets with no
255 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
256 * there's nothing we can do about that.
258 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
259 * continue the behavior of earlier libpcaps, wherein we treated packets
260 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
261 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
262 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
263 * VLAN tags. This does the right thing on 3.0 and later kernels, and
264 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
266 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
267 * has that value in 3.0 and later kernels.
269 #ifdef TP_STATUS_VLAN_VALID
270 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
273 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
274 * so we testwith the value it has in the 3.0 and later kernels, so
275 * we can test it if we're running on a system that has it. (If we're
276 * running on a system that doesn't have it, it won't be set in the
277 * tp_status field, so the tests of it will always fail; that means
278 * we behave the way we did before we introduced this macro.)
280 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
283 #ifdef TP_STATUS_VLAN_TPID_VALID
284 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
286 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
290 * Required select timeout if we're polling for an "interface disappeared"
291 * indication - 1 millisecond.
293 static const struct timeval netdown_timeout
= {
294 0, 1000 /* 1000 microseconds = 1 millisecond */
298 * Wrap some ioctl calls
300 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
301 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
302 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
303 static int iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
);
304 #ifdef IW_MODE_MONITOR
305 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
306 #endif /* IW_MODE_MONITOR */
307 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
309 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
310 static int iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
,
313 static int iface_get_offload(pcap_t
*handle
);
315 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
316 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
317 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
318 static int reset_kernel_filter(pcap_t
*handle
);
320 static struct sock_filter total_insn
321 = BPF_STMT(BPF_RET
| BPF_K
, 0);
322 static struct sock_fprog total_fcode
323 = { 1, &total_insn
};
325 static int iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
);
328 pcap_create_interface(const char *device
, char *ebuf
)
332 handle
= pcap_create_common(ebuf
, sizeof (struct pcap_linux
));
336 handle
->activate_op
= pcap_activate_linux
;
337 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
339 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
341 * See what time stamp types we support.
343 if (iface_ethtool_get_ts_info(device
, handle
, ebuf
) == -1) {
349 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
351 * We claim that we support microsecond and nanosecond time
354 * XXX - with adapter-supplied time stamps, can we choose
355 * microsecond or nanosecond time stamps on arbitrary
358 handle
->tstamp_precision_count
= 2;
359 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
360 if (handle
->tstamp_precision_list
== NULL
) {
361 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
366 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
367 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
368 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
370 struct pcap_linux
*handlep
= handle
->priv
;
371 handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
);
378 * If interface {if_name} is a mac80211 driver, the file
379 * /sys/class/net/{if_name}/phy80211 is a symlink to
380 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
382 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
383 * least, has a "wmaster0" device and a "wlan0" device; the
384 * latter is the one with the IP address. Both show up in
385 * "tcpdump -D" output. Capturing on the wmaster0 device
386 * captures with 802.11 headers.
388 * airmon-ng searches through /sys/class/net for devices named
389 * monN, starting with mon0; as soon as one *doesn't* exist,
390 * it chooses that as the monitor device name. If the "iw"
391 * command exists, it does
393 * iw dev {if_name} interface add {monif_name} type monitor
395 * where {monif_name} is the monitor device. It then (sigh) sleeps
396 * .1 second, and then configures the device up. Otherwise, if
397 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
398 * {mondev_name}, without a newline, to that file, and again (sigh)
399 * sleeps .1 second, and then iwconfig's that device into monitor
400 * mode and configures it up. Otherwise, you can't do monitor mode.
402 * All these devices are "glued" together by having the
403 * /sys/class/net/{if_name}/phy80211 links pointing to the same
404 * place, so, given a wmaster, wlan, or mon device, you can
405 * find the other devices by looking for devices with
406 * the same phy80211 link.
408 * To turn monitor mode off, delete the monitor interface,
411 * iw dev {monif_name} interface del
413 * or by sending {monif_name}, with no NL, down
414 * /sys/class/ieee80211/{phydev_name}/remove_iface
416 * Note: if you try to create a monitor device named "monN", and
417 * there's already a "monN" device, it fails, as least with
418 * the netlink interface (which is what iw uses), with a return
419 * value of -ENFILE. (Return values are negative errnos.) We
420 * could probably use that to find an unused device.
422 * Yes, you can have multiple monitor devices for a given
427 * Is this a mac80211 device? If so, fill in the physical device path and
428 * return 1; if not, return 0. On an error, fill in handle->errbuf and
432 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
433 size_t phydev_max_pathlen
)
439 * Generate the path string for the symlink to the physical device.
441 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
442 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
443 "%s: Can't generate path name string for /sys/class/net device",
447 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
448 if (bytes_read
== -1) {
449 if (errno
== ENOENT
|| errno
== EINVAL
) {
451 * Doesn't exist, or not a symlink; assume that
452 * means it's not a mac80211 device.
457 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
458 errno
, "%s: Can't readlink %s", device
, pathstr
);
463 phydev_path
[bytes_read
] = '\0';
467 #ifdef HAVE_LIBNL_SOCKETS
468 #define get_nl_errmsg nl_geterror
470 /* libnl 2.x compatibility code */
472 #define nl_sock nl_handle
474 static inline struct nl_handle
*
475 nl_socket_alloc(void)
477 return nl_handle_alloc();
481 nl_socket_free(struct nl_handle
*h
)
483 nl_handle_destroy(h
);
486 #define get_nl_errmsg strerror
489 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
491 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
497 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
498 #endif /* !HAVE_LIBNL_SOCKETS */
500 struct nl80211_state
{
501 struct nl_sock
*nl_sock
;
502 struct nl_cache
*nl_cache
;
503 struct genl_family
*nl80211
;
507 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
511 state
->nl_sock
= nl_socket_alloc();
512 if (!state
->nl_sock
) {
513 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
514 "%s: failed to allocate netlink handle", device
);
518 if (genl_connect(state
->nl_sock
)) {
519 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
520 "%s: failed to connect to generic netlink", device
);
521 goto out_handle_destroy
;
524 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
526 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
527 "%s: failed to allocate generic netlink cache: %s",
528 device
, get_nl_errmsg(-err
));
529 goto out_handle_destroy
;
532 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
533 if (!state
->nl80211
) {
534 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
535 "%s: nl80211 not found", device
);
542 nl_cache_free(state
->nl_cache
);
544 nl_socket_free(state
->nl_sock
);
549 nl80211_cleanup(struct nl80211_state
*state
)
551 genl_family_put(state
->nl80211
);
552 nl_cache_free(state
->nl_cache
);
553 nl_socket_free(state
->nl_sock
);
557 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
558 const char *device
, const char *mondevice
);
561 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
562 const char *device
, const char *mondevice
)
564 struct pcap_linux
*handlep
= handle
->priv
;
569 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
575 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
576 "%s: failed to allocate netlink msg", device
);
580 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
581 0, NL80211_CMD_NEW_INTERFACE
, 0);
582 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
584 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
586 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
588 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
590 #if defined HAVE_LIBNL_NLE
591 if (err
== -NLE_FAILURE
) {
593 if (err
== -ENFILE
) {
596 * Device not available; our caller should just
597 * keep trying. (libnl 2.x maps ENFILE to
598 * NLE_FAILURE; it can also map other errors
599 * to that, but there's not much we can do
606 * Real failure, not just "that device is not
609 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
610 "%s: nl_send_auto_complete failed adding %s interface: %s",
611 device
, mondevice
, get_nl_errmsg(-err
));
616 err
= nl_wait_for_ack(state
->nl_sock
);
618 #if defined HAVE_LIBNL_NLE
619 if (err
== -NLE_FAILURE
) {
621 if (err
== -ENFILE
) {
624 * Device not available; our caller should just
625 * keep trying. (libnl 2.x maps ENFILE to
626 * NLE_FAILURE; it can also map other errors
627 * to that, but there's not much we can do
634 * Real failure, not just "that device is not
637 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
638 "%s: nl_wait_for_ack failed adding %s interface: %s",
639 device
, mondevice
, get_nl_errmsg(-err
));
651 * Try to remember the monitor device.
653 handlep
->mondevice
= strdup(mondevice
);
654 if (handlep
->mondevice
== NULL
) {
655 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
658 * Get rid of the monitor device.
660 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
666 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
667 "%s: nl_put failed adding %s interface",
674 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
675 const char *device
, const char *mondevice
)
681 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
687 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
688 "%s: failed to allocate netlink msg", device
);
692 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
693 0, NL80211_CMD_DEL_INTERFACE
, 0);
694 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
696 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
698 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
699 "%s: nl_send_auto_complete failed deleting %s interface: %s",
700 device
, mondevice
, get_nl_errmsg(-err
));
704 err
= nl_wait_for_ack(state
->nl_sock
);
706 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
707 "%s: nl_wait_for_ack failed adding %s interface: %s",
708 device
, mondevice
, get_nl_errmsg(-err
));
720 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
721 "%s: nl_put failed deleting %s interface",
728 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
730 struct pcap_linux
*handlep
= handle
->priv
;
732 char phydev_path
[PATH_MAX
+1];
733 struct nl80211_state nlstate
;
738 * Is this a mac80211 device?
740 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
742 return ret
; /* error */
744 return 0; /* no error, but not mac80211 device */
747 * XXX - is this already a monN device?
749 * Is that determined by old Wireless Extensions ioctls?
753 * OK, it's apparently a mac80211 device.
754 * Try to find an unused monN device for it.
756 ret
= nl80211_init(handle
, &nlstate
, device
);
759 for (n
= 0; n
< UINT_MAX
; n
++) {
763 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
765 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
766 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
769 * Success. We don't clean up the libnl state
770 * yet, as we'll be using it later.
776 * Hard failure. Just return ret; handle->errbuf
777 * has already been set.
779 nl80211_cleanup(&nlstate
);
784 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
785 "%s: No free monN interfaces", device
);
786 nl80211_cleanup(&nlstate
);
793 * Sleep for .1 seconds.
796 delay
.tv_nsec
= 500000000;
797 nanosleep(&delay
, NULL
);
801 * If we haven't already done so, arrange to have
802 * "pcap_close_all()" called when we exit.
804 if (!pcap_do_addexit(handle
)) {
806 * "atexit()" failed; don't put the interface
807 * in rfmon mode, just give up.
809 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
811 nl80211_cleanup(&nlstate
);
816 * Now configure the monitor interface up.
818 memset(&ifr
, 0, sizeof(ifr
));
819 pcap_strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
820 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
821 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
822 errno
, "%s: Can't get flags for %s", device
,
824 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
826 nl80211_cleanup(&nlstate
);
829 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
830 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
831 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
832 errno
, "%s: Can't set flags for %s", device
,
834 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
836 nl80211_cleanup(&nlstate
);
841 * Success. Clean up the libnl state.
843 nl80211_cleanup(&nlstate
);
846 * Note that we have to delete the monitor device when we close
849 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
852 * Add this to the list of pcaps to close when we exit.
854 pcap_add_to_pcaps_to_close(handle
);
858 #endif /* HAVE_LIBNL */
860 #ifdef IW_MODE_MONITOR
862 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
863 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
864 * will fail with ENODEV if we try to do them on a bonding device,
865 * making us return a "no such device" indication rather than just
866 * saying "no Wireless Extensions".
868 * So we check for bonding devices, if we can, before trying those
869 * ioctls, by trying a bonding device information query ioctl to see
870 * whether it succeeds.
873 is_bonding_device(int fd
, const char *device
)
878 memset(&ifr
, 0, sizeof ifr
);
879 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof ifr
.ifr_name
);
880 memset(&ifb
, 0, sizeof ifb
);
881 ifr
.ifr_data
= (caddr_t
)&ifb
;
882 if (ioctl(fd
, SIOCBONDINFOQUERY
, &ifr
) == 0)
883 return 1; /* success, so it's a bonding device */
885 return 0; /* no, it's not a bonding device */
887 #endif /* IW_MODE_MONITOR */
889 static int pcap_protocol(pcap_t
*handle
)
893 protocol
= handle
->opt
.protocol
;
895 protocol
= ETH_P_ALL
;
897 return htons(protocol
);
901 pcap_can_set_rfmon_linux(pcap_t
*handle
)
904 char phydev_path
[PATH_MAX
+1];
907 #ifdef IW_MODE_MONITOR
912 if (strcmp(handle
->opt
.device
, "any") == 0) {
914 * Monitor mode makes no sense on the "any" device.
921 * Bleah. There doesn't seem to be a way to ask a mac80211
922 * device, through libnl, whether it supports monitor mode;
923 * we'll just check whether the device appears to be a
924 * mac80211 device and, if so, assume the device supports
927 * wmaster devices don't appear to support the Wireless
928 * Extensions, but we can create a mon device for a
929 * wmaster device, so we don't bother checking whether
930 * a mac80211 device supports the Wireless Extensions.
932 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
935 return ret
; /* error */
937 return 1; /* mac80211 device */
940 #ifdef IW_MODE_MONITOR
942 * Bleah. There doesn't appear to be an ioctl to use to ask
943 * whether a device supports monitor mode; we'll just do
944 * SIOCGIWMODE and, if it succeeds, assume the device supports
947 * Open a socket on which to attempt to get the mode.
948 * (We assume that if we have Wireless Extensions support
949 * we also have PF_PACKET support.)
951 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, pcap_protocol(handle
));
953 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
958 if (is_bonding_device(sock_fd
, handle
->opt
.device
)) {
959 /* It's a bonding device, so don't even try. */
965 * Attempt to get the current mode.
967 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.device
,
968 sizeof ireq
.ifr_ifrn
.ifrn_name
);
969 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
971 * Well, we got the mode; assume we can set it.
976 if (errno
== ENODEV
) {
977 /* The device doesn't even exist. */
978 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
979 errno
, "SIOCGIWMODE failed");
981 return PCAP_ERROR_NO_SUCH_DEVICE
;
989 * Grabs the number of missed packets by the interface from
990 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors.
992 * Compared to /proc/net/dev this avoids counting software drops,
993 * but may be unimplemented and just return 0.
994 * The author has found no straigthforward way to check for support.
997 linux_get_stat(const char * if_name
, const char * stat
) {
1000 char buffer
[PATH_MAX
];
1002 snprintf(buffer
, sizeof(buffer
), "/sys/class/net/%s/statistics/%s", if_name
, stat
);
1003 fd
= open(buffer
, O_RDONLY
);
1007 bytes_read
= read(fd
, buffer
, sizeof(buffer
) - 1);
1009 if (bytes_read
== -1)
1011 buffer
[bytes_read
] = '\0';
1013 return strtoll(buffer
, NULL
, 10);
1016 static long long int
1017 linux_if_drops(const char * if_name
)
1019 long long int missed
= linux_get_stat(if_name
, "rx_missed_errors");
1020 long long int fifo
= linux_get_stat(if_name
, "rx_fifo_errors");
1021 return missed
+ fifo
;
1026 * Monitor mode is kind of interesting because we have to reset the
1027 * interface before exiting. The problem can't really be solved without
1028 * some daemon taking care of managing usage counts. If we put the
1029 * interface into monitor mode, we set a flag indicating that we must
1030 * take it out of that mode when the interface is closed, and, when
1031 * closing the interface, if that flag is set we take it out of monitor
1035 static void pcap_cleanup_linux( pcap_t
*handle
)
1037 struct pcap_linux
*handlep
= handle
->priv
;
1040 struct nl80211_state nlstate
;
1042 #endif /* HAVE_LIBNL */
1043 #ifdef IW_MODE_MONITOR
1046 #endif /* IW_MODE_MONITOR */
1048 if (handlep
->must_do_on_close
!= 0) {
1050 * There's something we have to do when closing this
1054 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1055 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1057 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1058 handlep
->device
, handlep
->mondevice
);
1059 nl80211_cleanup(&nlstate
);
1063 "Can't delete monitor interface %s (%s).\n"
1064 "Please delete manually.\n",
1065 handlep
->mondevice
, handle
->errbuf
);
1068 #endif /* HAVE_LIBNL */
1070 #ifdef IW_MODE_MONITOR
1071 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1073 * We put the interface into rfmon mode;
1074 * take it out of rfmon mode.
1076 * XXX - if somebody else wants it in rfmon
1077 * mode, this code cannot know that, so it'll take
1078 * it out of rfmon mode.
1082 * First, take the interface down if it's up;
1083 * otherwise, we might get EBUSY.
1084 * If we get errors, just drive on and print
1085 * a warning if we can't restore the mode.
1088 memset(&ifr
, 0, sizeof(ifr
));
1089 pcap_strlcpy(ifr
.ifr_name
, handlep
->device
,
1090 sizeof(ifr
.ifr_name
));
1091 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1092 if (ifr
.ifr_flags
& IFF_UP
) {
1093 oldflags
= ifr
.ifr_flags
;
1094 ifr
.ifr_flags
&= ~IFF_UP
;
1095 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1096 oldflags
= 0; /* didn't set, don't restore */
1101 * Now restore the mode.
1103 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1104 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1105 ireq
.u
.mode
= handlep
->oldmode
;
1106 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1108 * Scientist, you've failed.
1111 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1112 "Please adjust manually.\n",
1113 handlep
->device
, strerror(errno
));
1117 * Now bring the interface back up if we brought
1120 if (oldflags
!= 0) {
1121 ifr
.ifr_flags
= oldflags
;
1122 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1124 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1125 "Please adjust manually.\n",
1126 handlep
->device
, strerror(errno
));
1130 #endif /* IW_MODE_MONITOR */
1133 * Take this pcap out of the list of pcaps for which we
1134 * have to take the interface out of some mode.
1136 pcap_remove_from_pcaps_to_close(handle
);
1139 if (handle
->fd
!= -1) {
1141 * Destroy the ring buffer (assuming we've set it up),
1142 * and unmap it if it's mapped.
1144 destroy_ring(handle
);
1147 if (handlep
->oneshot_buffer
!= NULL
) {
1148 free(handlep
->oneshot_buffer
);
1149 handlep
->oneshot_buffer
= NULL
;
1152 if (handlep
->mondevice
!= NULL
) {
1153 free(handlep
->mondevice
);
1154 handlep
->mondevice
= NULL
;
1156 if (handlep
->device
!= NULL
) {
1157 free(handlep
->device
);
1158 handlep
->device
= NULL
;
1161 close(handlep
->poll_breakloop_fd
);
1162 pcap_cleanup_live_common(handle
);
1166 * Set the timeout to be used in poll() with memory-mapped packet capture.
1169 set_poll_timeout(struct pcap_linux
*handlep
)
1171 #ifdef HAVE_TPACKET3
1172 struct utsname utsname
;
1173 char *version_component
, *endp
;
1175 int broken_tpacket_v3
= 1;
1178 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1179 * around which we have to work. Determine if we have those
1182 if (uname(&utsname
) == 0) {
1184 * 3.19 is the first release with a fixed version of
1185 * TPACKET_V3. We treat anything before that as
1186 * not haveing a fixed version; that may really mean
1187 * it has *no* version.
1189 version_component
= utsname
.release
;
1190 major
= strtol(version_component
, &endp
, 10);
1191 if (endp
!= version_component
&& *endp
== '.') {
1193 * OK, that was a valid major version.
1194 * Get the minor version.
1196 version_component
= endp
+ 1;
1197 minor
= strtol(version_component
, &endp
, 10);
1198 if (endp
!= version_component
&&
1199 (*endp
== '.' || *endp
== '\0')) {
1201 * OK, that was a valid minor version.
1202 * Is this 3.19 or newer?
1204 if (major
>= 4 || (major
== 3 && minor
>= 19)) {
1205 /* Yes. TPACKET_V3 works correctly. */
1206 broken_tpacket_v3
= 0;
1212 if (handlep
->timeout
== 0) {
1213 #ifdef HAVE_TPACKET3
1215 * XXX - due to a set of (mis)features in the TPACKET_V3
1216 * kernel code prior to the 3.19 kernel, blocking forever
1217 * with a TPACKET_V3 socket can, if few packets are
1218 * arriving and passing the socket filter, cause most
1219 * packets to be dropped. See libpcap issue #335 for the
1220 * full painful story.
1222 * The workaround is to have poll() time out very quickly,
1223 * so we grab the frames handed to us, and return them to
1226 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1227 handlep
->poll_timeout
= 1; /* don't block for very long */
1230 handlep
->poll_timeout
= -1; /* block forever */
1231 } else if (handlep
->timeout
> 0) {
1232 #ifdef HAVE_TPACKET3
1234 * For TPACKET_V3, the timeout is handled by the kernel,
1235 * so block forever; that way, we don't get extra timeouts.
1236 * Don't do that if we have a broken TPACKET_V3, though.
1238 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1239 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1242 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1245 * Non-blocking mode; we call poll() to pick up error
1246 * indications, but we don't want it to wait for
1249 handlep
->poll_timeout
= 0;
1253 static void pcap_breakloop_linux(pcap_t
*handle
)
1255 pcap_breakloop_common(handle
);
1256 struct pcap_linux
*handlep
= handle
->priv
;
1259 /* XXX - what if this fails? */
1260 (void)write(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
1264 * Get a handle for a live capture from the given device. You can
1265 * pass NULL as device to get all packages (without link level
1266 * information of course). If you pass 1 as promisc the interface
1267 * will be set to promiscuous mode (XXX: I think this usage should
1268 * be deprecated and functions be added to select that later allow
1269 * modification of that values -- Torsten).
1272 pcap_activate_linux(pcap_t
*handle
)
1274 struct pcap_linux
*handlep
= handle
->priv
;
1282 device
= handle
->opt
.device
;
1285 * Make sure the name we were handed will fit into the ioctls we
1286 * might perform on the device; if not, return a "No such device"
1287 * indication, as the Linux kernel shouldn't support creating
1288 * a device whose name won't fit into those ioctls.
1290 * "Will fit" means "will fit, complete with a null terminator",
1291 * so if the length, which does *not* include the null terminator,
1292 * is greater than *or equal to* the size of the field into which
1293 * we'll be copying it, that won't fit.
1295 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1296 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1301 * Turn a negative snapshot value (invalid), a snapshot value of
1302 * 0 (unspecified), or a value bigger than the normal maximum
1303 * value, into the maximum allowed value.
1305 * If some application really *needs* a bigger snapshot
1306 * length, we should just increase MAXIMUM_SNAPLEN.
1308 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
1309 handle
->snapshot
= MAXIMUM_SNAPLEN
;
1311 handlep
->device
= strdup(device
);
1312 if (handlep
->device
== NULL
) {
1313 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1315 status
= PCAP_ERROR
;
1320 * The "any" device is a special device which causes us not
1321 * to bind to a particular device and thus to look at all
1324 is_any_device
= (strcmp(device
, "any") == 0);
1325 if (is_any_device
) {
1326 if (handle
->opt
.promisc
) {
1327 handle
->opt
.promisc
= 0;
1328 /* Just a warning. */
1329 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1330 "Promiscuous mode not supported on the \"any\" device");
1331 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1335 /* copy timeout value */
1336 handlep
->timeout
= handle
->opt
.timeout
;
1339 * If we're in promiscuous mode, then we probably want
1340 * to see when the interface drops packets too, so get an
1341 * initial count from
1342 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1344 if (handle
->opt
.promisc
)
1345 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1348 * If the "any" device is specified, try to open a SOCK_DGRAM.
1349 * Otherwise, open a SOCK_RAW.
1351 ret
= activate_pf_packet(handle
, is_any_device
);
1354 * Fatal error; the return value is the error code,
1355 * and handle->errbuf has been set to an appropriate
1363 * Try to set up memory-mapped access.
1365 ret
= setup_mmapped(handle
, &status
);
1368 * We failed to set up to use it, or the
1369 * kernel supports it, but we failed to
1370 * enable it. status has been set to the
1371 * error status to return and, if it's
1372 * PCAP_ERROR, handle->errbuf contains
1373 * the error message.
1379 * We succeeded. status has been set to the status to return,
1380 * which might be 0, or might be a PCAP_WARNING_ value.
1383 * Now that we have activated the mmap ring, we can
1384 * set the correct protocol.
1386 if ((status2
= iface_bind(handle
->fd
, handlep
->ifindex
,
1387 handle
->errbuf
, pcap_protocol(handle
))) != 0) {
1392 handle
->inject_op
= pcap_inject_linux
;
1393 handle
->setfilter_op
= pcap_setfilter_linux
;
1394 handle
->setdirection_op
= pcap_setdirection_linux
;
1395 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1396 handle
->setnonblock_op
= pcap_setnonblock_linux
;
1397 handle
->getnonblock_op
= pcap_getnonblock_linux
;
1398 handle
->cleanup_op
= pcap_cleanup_linux
;
1399 handle
->stats_op
= pcap_stats_linux
;
1400 handle
->breakloop_op
= pcap_breakloop_linux
;
1402 switch (handlep
->tp_version
) {
1405 handle
->read_op
= pcap_read_linux_mmap_v2
;
1407 #ifdef HAVE_TPACKET3
1409 handle
->read_op
= pcap_read_linux_mmap_v3
;
1413 handle
->oneshot_callback
= pcap_oneshot_linux
;
1414 handle
->selectable_fd
= handle
->fd
;
1419 pcap_cleanup_linux(handle
);
1424 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1426 handle
->linktype
= dlt
;
1431 * linux_check_direction()
1433 * Do checks based on packet direction.
1436 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1438 struct pcap_linux
*handlep
= handle
->priv
;
1440 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1443 * If this is from the loopback device, reject it;
1444 * we'll see the packet as an incoming packet as well,
1445 * and we don't want to see it twice.
1447 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1451 * If this is an outgoing CAN or CAN FD frame, and
1452 * the user doesn't only want outgoing packets,
1453 * reject it; CAN devices and drivers, and the CAN
1454 * stack, always arrange to loop back transmitted
1455 * packets, so they also appear as incoming packets.
1456 * We don't want duplicate packets, and we can't
1457 * easily distinguish packets looped back by the CAN
1458 * layer than those received by the CAN layer, so we
1459 * eliminate this packet instead.
1461 if ((sll
->sll_protocol
== LINUX_SLL_P_CAN
||
1462 sll
->sll_protocol
== LINUX_SLL_P_CANFD
) &&
1463 handle
->direction
!= PCAP_D_OUT
)
1467 * If the user only wants incoming packets, reject it.
1469 if (handle
->direction
== PCAP_D_IN
)
1474 * If the user only wants outgoing packets, reject it.
1476 if (handle
->direction
== PCAP_D_OUT
)
1483 * Check whether the device to which the pcap_t is bound still exists.
1484 * We do so by asking what address the socket is bound to, and checking
1485 * whether the ifindex in the address is -1, meaning "that device is gone",
1486 * or some other value, meaning "that device still exists".
1489 device_still_exists(pcap_t
*handle
)
1491 struct pcap_linux
*handlep
= handle
->priv
;
1492 struct sockaddr_ll addr
;
1496 * If handlep->ifindex is -1, the socket isn't bound, meaning
1497 * we're capturing on the "any" device; that device never
1498 * disappears. (It should also never be configured down, so
1499 * we shouldn't even get here, but let's make sure.)
1501 if (handlep
->ifindex
== -1)
1502 return (1); /* it's still here */
1505 * OK, now try to get the address for the socket.
1507 addr_len
= sizeof (addr
);
1508 if (getsockname(handle
->fd
, (struct sockaddr
*) &addr
, &addr_len
) == -1) {
1510 * Error - report an error and return -1.
1512 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1513 errno
, "getsockname failed");
1516 if (addr
.sll_ifindex
== -1) {
1518 * This means the device went away.
1524 * The device presumably just went down.
1530 pcap_inject_linux(pcap_t
*handle
, const void *buf
, int size
)
1532 struct pcap_linux
*handlep
= handle
->priv
;
1535 if (handlep
->ifindex
== -1) {
1537 * We don't support sending on the "any" device.
1539 pcap_strlcpy(handle
->errbuf
,
1540 "Sending packets isn't supported on the \"any\" device",
1545 if (handlep
->cooked
) {
1547 * We don't support sending on cooked-mode sockets.
1549 * XXX - how do you send on a bound cooked-mode
1551 * Is a "sendto()" required there?
1553 pcap_strlcpy(handle
->errbuf
,
1554 "Sending packets isn't supported in cooked mode",
1559 ret
= (int)send(handle
->fd
, buf
, size
, 0);
1561 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1569 * Get the statistics for the given packet capture handle.
1572 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1574 struct pcap_linux
*handlep
= handle
->priv
;
1575 #ifdef HAVE_TPACKET3
1577 * For sockets using TPACKET_V2, the extra stuff at the end
1578 * of a struct tpacket_stats_v3 will not be filled in, and
1579 * we don't look at it so this is OK even for those sockets.
1580 * In addition, the PF_PACKET socket code in the kernel only
1581 * uses the length parameter to compute how much data to
1582 * copy out and to indicate how much data was copied out, so
1583 * it's OK to base it on the size of a struct tpacket_stats.
1585 * XXX - it's probably OK, in fact, to just use a
1586 * struct tpacket_stats for V3 sockets, as we don't
1587 * care about the tp_freeze_q_cnt stat.
1589 struct tpacket_stats_v3 kstats
;
1590 #else /* HAVE_TPACKET3 */
1591 struct tpacket_stats kstats
;
1592 #endif /* HAVE_TPACKET3 */
1593 socklen_t len
= sizeof (struct tpacket_stats
);
1595 long long if_dropped
= 0;
1598 * To fill in ps_ifdrop, we parse
1599 * /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors
1602 if (handle
->opt
.promisc
)
1605 * XXX - is there any reason to do this by remembering
1606 * the last counts value, subtracting it from the
1607 * current counts value, and adding that to stat.ps_ifdrop,
1608 * maintaining stat.ps_ifdrop as a count, rather than just
1609 * saving the *initial* counts value and setting
1610 * stat.ps_ifdrop to the difference between the current
1611 * value and the initial value?
1613 * One reason might be to handle the count wrapping
1614 * around, on platforms where the count is 32 bits
1615 * and where you might get more than 2^32 dropped
1616 * packets; is there any other reason?
1618 * (We maintain the count as a long long int so that,
1619 * if the kernel maintains the counts as 64-bit even
1620 * on 32-bit platforms, we can handle the real count.
1622 * Unfortunately, we can't report 64-bit counts; we
1623 * need a better API for reporting statistics, such as
1624 * one that reports them in a style similar to the
1625 * pcapng Interface Statistics Block, so that 1) the
1626 * counts are 64-bit, 2) it's easier to add new statistics
1627 * without breaking the ABI, and 3) it's easier to
1628 * indicate to a caller that wants one particular
1629 * statistic that it's not available by just not supplying
1632 if_dropped
= handlep
->sysfs_dropped
;
1633 handlep
->sysfs_dropped
= linux_if_drops(handlep
->device
);
1634 handlep
->stat
.ps_ifdrop
+= (u_int
)(handlep
->sysfs_dropped
- if_dropped
);
1638 * Try to get the packet counts from the kernel.
1640 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1641 &kstats
, &len
) > -1) {
1643 * "ps_recv" counts only packets that *passed* the
1644 * filter, not packets that didn't pass the filter.
1645 * This includes packets later dropped because we
1646 * ran out of buffer space.
1648 * "ps_drop" counts packets dropped because we ran
1649 * out of buffer space. It doesn't count packets
1650 * dropped by the interface driver. It counts only
1651 * packets that passed the filter.
1653 * See above for ps_ifdrop.
1655 * Both statistics include packets not yet read from
1656 * the kernel by libpcap, and thus not yet seen by
1659 * In "linux/net/packet/af_packet.c", at least in 2.6.27
1660 * through 5.6 kernels, "tp_packets" is incremented for
1661 * every packet that passes the packet filter *and* is
1662 * successfully copied to the ring buffer; "tp_drops" is
1663 * incremented for every packet dropped because there's
1664 * not enough free space in the ring buffer.
1666 * When the statistics are returned for a PACKET_STATISTICS
1667 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1668 * so that "tp_packets" counts all packets handed to
1669 * the PF_PACKET socket, including packets dropped because
1670 * there wasn't room on the socket buffer - but not
1671 * including packets that didn't pass the filter.
1673 * In the BSD BPF, the count of received packets is
1674 * incremented for every packet handed to BPF, regardless
1675 * of whether it passed the filter.
1677 * We can't make "pcap_stats()" work the same on both
1678 * platforms, but the best approximation is to return
1679 * "tp_packets" as the count of packets and "tp_drops"
1680 * as the count of drops.
1682 * Keep a running total because each call to
1683 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1684 * resets the counters to zero.
1686 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1687 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1688 *stats
= handlep
->stat
;
1692 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1693 "failed to get statistics from socket");
1698 * Description string for the "any" device.
1700 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1703 * A PF_PACKET socket can be bound to any network interface.
1706 can_be_bound(const char *name _U_
)
1712 * Get additional flags for a device, using SIOCGIFMEDIA.
1715 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1719 unsigned int arptype
;
1721 struct ethtool_value info
;
1723 if (*flags
& PCAP_IF_LOOPBACK
) {
1725 * Loopback devices aren't wireless, and "connected"/
1726 * "disconnected" doesn't apply to them.
1728 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1732 sock
= socket(AF_INET
, SOCK_DGRAM
, 0);
1734 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
1735 "Can't create socket to get ethtool information for %s",
1741 * OK, what type of network is this?
1742 * In particular, is it wired or wireless?
1744 if (is_wifi(sock
, name
)) {
1746 * Wi-Fi, hence wireless.
1748 *flags
|= PCAP_IF_WIRELESS
;
1751 * OK, what does /sys/class/net/{if_name}/type contain?
1752 * (We don't use that for Wi-Fi, as it'll report
1753 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
1758 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
1759 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1760 "%s: Can't generate path name string for /sys/class/net device",
1765 fh
= fopen(pathstr
, "r");
1767 if (fscanf(fh
, "%u", &arptype
) == 1) {
1769 * OK, we got an ARPHRD_ type; what is it?
1773 case ARPHRD_LOOPBACK
:
1775 * These are types to which
1776 * "connected" and "disconnected"
1777 * don't apply, so don't bother
1780 * XXX - add other types?
1788 case ARPHRD_IEEE80211
:
1789 case ARPHRD_IEEE80211_PRISM
:
1790 case ARPHRD_IEEE80211_RADIOTAP
:
1791 #ifdef ARPHRD_IEEE802154
1792 case ARPHRD_IEEE802154
:
1794 #ifdef ARPHRD_IEEE802154_MONITOR
1795 case ARPHRD_IEEE802154_MONITOR
:
1797 #ifdef ARPHRD_6LOWPAN
1798 case ARPHRD_6LOWPAN
:
1801 * Various wireless types.
1803 *flags
|= PCAP_IF_WIRELESS
;
1812 #ifdef ETHTOOL_GLINK
1813 memset(&ifr
, 0, sizeof(ifr
));
1814 pcap_strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
1815 info
.cmd
= ETHTOOL_GLINK
;
1816 ifr
.ifr_data
= (caddr_t
)&info
;
1817 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
1818 int save_errno
= errno
;
1820 switch (save_errno
) {
1825 * OK, this OS version or driver doesn't support
1826 * asking for this information.
1827 * XXX - distinguish between "this doesn't
1828 * support ethtool at all because it's not
1829 * that type of device" vs. "this doesn't
1830 * support ethtool even though it's that
1831 * type of device", and return "unknown".
1833 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1839 * OK, no such device.
1840 * The user will find that out when they try to
1841 * activate the device; just say "OK" and
1842 * don't set anything.
1851 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1853 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
1867 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1870 * It's disconnected.
1872 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1881 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1884 * Get the list of regular interfaces first.
1886 if (pcap_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
1887 get_if_flags
) == -1)
1888 return (-1); /* failure */
1891 * Add the "any" device.
1892 * As it refers to all network devices, not to any particular
1893 * network device, the notion of "connected" vs. "disconnected"
1896 if (add_dev(devlistp
, "any",
1897 PCAP_IF_UP
|PCAP_IF_RUNNING
|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
1898 any_descr
, errbuf
) == NULL
)
1905 * Set direction flag: Which packets do we accept on a forwarding
1906 * single device? IN, OUT or both?
1909 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1912 * It's guaranteed, at this point, that d is a valid
1915 handle
->direction
= d
;
1921 #ifndef IW_MODE_MONITOR
1924 , const char *device
)
1928 #ifdef IW_MODE_MONITOR
1929 char errbuf
[PCAP_ERRBUF_SIZE
];
1933 * See if there's a sysfs wireless directory for it.
1934 * If so, it's a wireless interface.
1936 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
1938 * Just give up here.
1942 if (stat(pathstr
, &statb
) == 0) {
1948 #ifdef IW_MODE_MONITOR
1950 * OK, maybe it's not wireless, or maybe this kernel doesn't
1951 * support sysfs. Try the wireless extensions.
1953 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
1955 * It supports the wireless extensions, so it's a Wi-Fi
1965 * Linux uses the ARP hardware type to identify the type of an
1966 * interface. pcap uses the DLT_xxx constants for this. This
1967 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1968 * constant, as arguments, and sets "handle->linktype" to the
1969 * appropriate DLT_XXX constant and sets "handle->offset" to
1970 * the appropriate value (to make "handle->offset" plus link-layer
1971 * header length be a multiple of 4, so that the link-layer payload
1972 * will be aligned on a 4-byte boundary when capturing packets).
1973 * (If the offset isn't set here, it'll be 0; add code as appropriate
1974 * for cases where it shouldn't be 0.)
1976 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1977 * in cooked mode; otherwise, we can't use cooked mode, so we have
1978 * to pick some type that works in raw mode, or fail.
1980 * Sets the link type to -1 if unable to map the type.
1982 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
1983 const char *device
, int cooked_ok
)
1985 static const char cdma_rmnet
[] = "cdma_rmnet";
1991 * For various annoying reasons having to do with DHCP
1992 * software, some versions of Android give the mobile-
1993 * phone-network interface an ARPHRD_ value of
1994 * ARPHRD_ETHER, even though the packets supplied by
1995 * that interface have no link-layer header, and begin
1996 * with an IP header, so that the ARPHRD_ value should
1999 * Detect those devices by checking the device name, and
2000 * use DLT_RAW for them.
2002 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2003 handle
->linktype
= DLT_RAW
;
2008 * Is this a real Ethernet device? If so, give it a
2009 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2010 * that an application can let you choose it, in case you're
2011 * capturing DOCSIS traffic that a Cisco Cable Modem
2012 * Termination System is putting out onto an Ethernet (it
2013 * doesn't put an Ethernet header onto the wire, it puts raw
2014 * DOCSIS frames out on the wire inside the low-level
2015 * Ethernet framing).
2017 * XXX - are there any other sorts of "fake Ethernet" that
2018 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2019 * a Cisco CMTS won't put traffic onto it or get traffic
2020 * bridged onto it? ISDN is handled in "activate_pf_packet()",
2021 * as we fall back on cooked mode there, and we use
2022 * is_wifi() to check for 802.11 devices; are there any
2025 if (!is_wifi(sock_fd
, device
)) {
2029 * This is not a Wi-Fi device but it could be
2030 * a DSA master/management network device.
2032 ret
= iface_dsa_get_proto_info(device
, handle
);
2038 * This is a DSA master/management network
2039 * device linktype is already set by
2040 * iface_dsa_get_proto_info() set an
2041 * appropriate offset here.
2048 * It's not a Wi-Fi device; offer DOCSIS.
2050 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2052 * If that fails, just leave the list empty.
2054 if (handle
->dlt_list
!= NULL
) {
2055 handle
->dlt_list
[0] = DLT_EN10MB
;
2056 handle
->dlt_list
[1] = DLT_DOCSIS
;
2057 handle
->dlt_count
= 2;
2062 case ARPHRD_METRICOM
:
2063 case ARPHRD_LOOPBACK
:
2064 handle
->linktype
= DLT_EN10MB
;
2069 handle
->linktype
= DLT_EN3MB
;
2073 handle
->linktype
= DLT_AX25_KISS
;
2077 handle
->linktype
= DLT_PRONET
;
2081 handle
->linktype
= DLT_CHAOS
;
2084 #define ARPHRD_CAN 280
2088 * Map this to DLT_LINUX_SLL; that way, CAN frames will
2089 * have ETH_P_CAN/LINUX_SLL_P_CAN as the protocol and
2090 * CAN FD frames will have ETH_P_CANFD/LINUX_SLL_P_CANFD
2091 * as the protocol, so they can be distinguished by the
2092 * protocol in the SLL header.
2094 handle
->linktype
= DLT_LINUX_SLL
;
2097 #ifndef ARPHRD_IEEE802_TR
2098 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2100 case ARPHRD_IEEE802_TR
:
2101 case ARPHRD_IEEE802
:
2102 handle
->linktype
= DLT_IEEE802
;
2107 handle
->linktype
= DLT_ARCNET_LINUX
;
2110 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2111 #define ARPHRD_FDDI 774
2114 handle
->linktype
= DLT_FDDI
;
2118 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2119 #define ARPHRD_ATM 19
2123 * The Classical IP implementation in ATM for Linux
2124 * supports both what RFC 1483 calls "LLC Encapsulation",
2125 * in which each packet has an LLC header, possibly
2126 * with a SNAP header as well, prepended to it, and
2127 * what RFC 1483 calls "VC Based Multiplexing", in which
2128 * different virtual circuits carry different network
2129 * layer protocols, and no header is prepended to packets.
2131 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2132 * you can't use the ARPHRD_ type to find out whether
2133 * captured packets will have an LLC header, and,
2134 * while there's a socket ioctl to *set* the encapsulation
2135 * type, there's no ioctl to *get* the encapsulation type.
2139 * programs that dissect Linux Classical IP frames
2140 * would have to check for an LLC header and,
2141 * depending on whether they see one or not, dissect
2142 * the frame as LLC-encapsulated or as raw IP (I
2143 * don't know whether there's any traffic other than
2144 * IP that would show up on the socket, or whether
2145 * there's any support for IPv6 in the Linux
2146 * Classical IP code);
2148 * filter expressions would have to compile into
2149 * code that checks for an LLC header and does
2152 * Both of those are a nuisance - and, at least on systems
2153 * that support PF_PACKET sockets, we don't have to put
2154 * up with those nuisances; instead, we can just capture
2155 * in cooked mode. That's what we'll do, if we can.
2156 * Otherwise, we'll just fail.
2159 handle
->linktype
= DLT_LINUX_SLL
;
2161 handle
->linktype
= -1;
2164 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2165 #define ARPHRD_IEEE80211 801
2167 case ARPHRD_IEEE80211
:
2168 handle
->linktype
= DLT_IEEE802_11
;
2171 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2172 #define ARPHRD_IEEE80211_PRISM 802
2174 case ARPHRD_IEEE80211_PRISM
:
2175 handle
->linktype
= DLT_PRISM_HEADER
;
2178 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2179 #define ARPHRD_IEEE80211_RADIOTAP 803
2181 case ARPHRD_IEEE80211_RADIOTAP
:
2182 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2187 * Some PPP code in the kernel supplies no link-layer
2188 * header whatsoever to PF_PACKET sockets; other PPP
2189 * code supplies PPP link-layer headers ("syncppp.c");
2190 * some PPP code might supply random link-layer
2191 * headers (PPP over ISDN - there's code in Ethereal,
2192 * for example, to cope with PPP-over-ISDN captures
2193 * with which the Ethereal developers have had to cope,
2194 * heuristically trying to determine which of the
2195 * oddball link-layer headers particular packets have).
2197 * As such, we just punt, and run all PPP interfaces
2198 * in cooked mode, if we can; otherwise, we just treat
2199 * it as DLT_RAW, for now - if somebody needs to capture,
2200 * on a 2.0[.x] kernel, on PPP devices that supply a
2201 * link-layer header, they'll have to add code here to
2202 * map to the appropriate DLT_ type (possibly adding a
2203 * new DLT_ type, if necessary).
2206 handle
->linktype
= DLT_LINUX_SLL
;
2209 * XXX - handle ISDN types here? We can't fall
2210 * back on cooked sockets, so we'd have to
2211 * figure out from the device name what type of
2212 * link-layer encapsulation it's using, and map
2213 * that to an appropriate DLT_ value, meaning
2214 * we'd map "isdnN" devices to DLT_RAW (they
2215 * supply raw IP packets with no link-layer
2216 * header) and "isdY" devices to a new DLT_I4L_IP
2217 * type that has only an Ethernet packet type as
2218 * a link-layer header.
2220 * But sometimes we seem to get random crap
2221 * in the link-layer header when capturing on
2224 handle
->linktype
= DLT_RAW
;
2228 #ifndef ARPHRD_CISCO
2229 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2232 handle
->linktype
= DLT_C_HDLC
;
2235 /* Not sure if this is correct for all tunnels, but it
2239 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2247 #ifndef ARPHRD_RAWHDLC
2248 #define ARPHRD_RAWHDLC 518
2250 case ARPHRD_RAWHDLC
:
2252 #define ARPHRD_DLCI 15
2256 * XXX - should some of those be mapped to DLT_LINUX_SLL
2257 * instead? Should we just map all of them to DLT_LINUX_SLL?
2259 handle
->linktype
= DLT_RAW
;
2263 #define ARPHRD_FRAD 770
2266 handle
->linktype
= DLT_FRELAY
;
2269 case ARPHRD_LOCALTLK
:
2270 handle
->linktype
= DLT_LTALK
;
2275 * RFC 4338 defines an encapsulation for IP and ARP
2276 * packets that's compatible with the RFC 2625
2277 * encapsulation, but that uses a different ARP
2278 * hardware type and hardware addresses. That
2279 * ARP hardware type is 18; Linux doesn't define
2280 * any ARPHRD_ value as 18, but if it ever officially
2281 * supports RFC 4338-style IP-over-FC, it should define
2284 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2285 * that this will encourage its use in the future,
2286 * should Linux ever officially support RFC 4338-style
2289 handle
->linktype
= DLT_IP_OVER_FC
;
2293 #define ARPHRD_FCPP 784
2297 #define ARPHRD_FCAL 785
2301 #define ARPHRD_FCPL 786
2304 #ifndef ARPHRD_FCFABRIC
2305 #define ARPHRD_FCFABRIC 787
2307 case ARPHRD_FCFABRIC
:
2309 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2312 * https://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2314 * and one was assigned.
2316 * In a later private discussion (spun off from a message
2317 * on the ethereal-users list) on how to get that DLT_
2318 * value in libpcap on Linux, I ended up deciding that
2319 * the best thing to do would be to have him tweak the
2320 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2321 * type, and map all those types to DLT_IP_OVER_FC:
2323 * I've checked into the libpcap and tcpdump CVS tree
2324 * support for DLT_IP_OVER_FC. In order to use that,
2325 * you'd have to modify your modified driver to return
2326 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2327 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2328 * example (the exact value doesn't matter, it can be
2329 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2332 * 11 years later, Christian Svensson wanted to map
2333 * various ARPHRD_ values to DLT_FC_2 and
2334 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2337 * https://github.com/mcr/libpcap/pull/29
2339 * There doesn't seem to be any network drivers that uses
2340 * any of the ARPHRD_FC* values for IP-over-FC, and
2341 * it's not exactly clear what the "Dummy types for non
2342 * ARP hardware" are supposed to mean (link-layer
2343 * header type? Physical network type?), so it's
2344 * not exactly clear why the ARPHRD_FC* types exist
2345 * in the first place.
2347 * For now, we map them to DLT_FC_2, and provide an
2348 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2349 * DLT_IP_OVER_FC just in case there's some old
2350 * driver out there that uses one of those types for
2351 * IP-over-FC on which somebody wants to capture
2354 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
2356 * If that fails, just leave the list empty.
2358 if (handle
->dlt_list
!= NULL
) {
2359 handle
->dlt_list
[0] = DLT_FC_2
;
2360 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2361 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2362 handle
->dlt_count
= 3;
2364 handle
->linktype
= DLT_FC_2
;
2368 #define ARPHRD_IRDA 783
2371 /* Don't expect IP packet out of this interfaces... */
2372 handle
->linktype
= DLT_LINUX_IRDA
;
2373 /* We need to save packet direction for IrDA decoding,
2374 * so let's use "Linux-cooked" mode. Jean II
2376 * XXX - this is handled in activate_pf_packet(). */
2377 /* handlep->cooked = 1; */
2380 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2381 * is needed, please report it to <daniele@orlandi.com> */
2383 #define ARPHRD_LAPD 8445
2386 /* Don't expect IP packet out of this interfaces... */
2387 handle
->linktype
= DLT_LINUX_LAPD
;
2391 #define ARPHRD_NONE 0xFFFE
2395 * No link-layer header; packets are just IP
2396 * packets, so use DLT_RAW.
2398 handle
->linktype
= DLT_RAW
;
2401 #ifndef ARPHRD_IEEE802154
2402 #define ARPHRD_IEEE802154 804
2404 case ARPHRD_IEEE802154
:
2405 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2408 #ifndef ARPHRD_NETLINK
2409 #define ARPHRD_NETLINK 824
2411 case ARPHRD_NETLINK
:
2412 handle
->linktype
= DLT_NETLINK
;
2414 * We need to use cooked mode, so that in sll_protocol we
2415 * pick up the netlink protocol type such as NETLINK_ROUTE,
2416 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2418 * XXX - this is handled in activate_pf_packet().
2420 /* handlep->cooked = 1; */
2423 #ifndef ARPHRD_VSOCKMON
2424 #define ARPHRD_VSOCKMON 826
2426 case ARPHRD_VSOCKMON
:
2427 handle
->linktype
= DLT_VSOCK
;
2431 handle
->linktype
= -1;
2436 #ifdef PACKET_RESERVE
2438 set_dlt_list_cooked(pcap_t
*handle
, int sock_fd
)
2441 unsigned int tp_reserve
;
2444 * If we can't do PACKET_RESERVE, we can't reserve extra space
2445 * for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
2447 len
= sizeof(tp_reserve
);
2448 if (getsockopt(sock_fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
,
2451 * Yes, we can do DLL_LINUX_SLL2.
2453 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2455 * If that fails, just leave the list empty.
2457 if (handle
->dlt_list
!= NULL
) {
2458 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
2459 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
2460 handle
->dlt_count
= 2;
2464 #else/* PACKET_RESERVE */
2466 * The build environment doesn't define PACKET_RESERVE, so we can't reserve
2467 * extra space for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
2470 set_dlt_list_cooked(pcap_t
*handle _U_
, int sock_fd _U_
)
2473 #endif /* PACKET_RESERVE */
2476 * Try to set up a PF_PACKET socket.
2477 * Returns 0 on success and a PCAP_ERROR_ value on failure.
2480 activate_pf_packet(pcap_t
*handle
, int is_any_device
)
2482 struct pcap_linux
*handlep
= handle
->priv
;
2483 const char *device
= handle
->opt
.device
;
2485 int sock_fd
, arptype
;
2486 #ifdef HAVE_PACKET_AUXDATA
2490 struct packet_mreq mr
;
2491 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2493 socklen_t len
= sizeof(bpf_extensions
);
2497 * Open a socket with protocol family packet. If cooked is true,
2498 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
2499 * we open a SOCK_RAW socket for the raw interface.
2501 * The protocol is set to 0. This means we will receive no
2502 * packets until we "bind" the socket with a non-zero
2503 * protocol. This allows us to setup the ring buffers without
2504 * dropping any packets.
2506 sock_fd
= is_any_device
?
2507 socket(PF_PACKET
, SOCK_DGRAM
, 0) :
2508 socket(PF_PACKET
, SOCK_RAW
, 0);
2510 if (sock_fd
== -1) {
2511 if (errno
== EPERM
|| errno
== EACCES
) {
2513 * You don't have permission to open the
2516 status
= PCAP_ERROR_PERM_DENIED
;
2521 status
= PCAP_ERROR
;
2523 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2529 * Get the interface index of the loopback device.
2530 * If the attempt fails, don't fail, just set the
2531 * "handlep->lo_ifindex" to -1.
2533 * XXX - can there be more than one device that loops
2534 * packets back, i.e. devices other than "lo"? If so,
2535 * we'd need to find them all, and have an array of
2536 * indices for them, and check all of them in
2537 * "pcap_read_packet()".
2539 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2542 * Default value for offset to align link-layer payload
2543 * on a 4-byte boundary.
2548 * What kind of frames do we have to deal with? Fall back
2549 * to cooked mode if we have an unknown interface type
2550 * or a type we know doesn't work well in raw mode.
2552 if (!is_any_device
) {
2553 /* Assume for now we don't need cooked mode. */
2554 handlep
->cooked
= 0;
2556 if (handle
->opt
.rfmon
) {
2558 * We were asked to turn on monitor mode.
2559 * Do so before we get the link-layer type,
2560 * because entering monitor mode could change
2561 * the link-layer type.
2563 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2571 * Nothing worked for turning monitor mode
2575 return PCAP_ERROR_RFMON_NOTSUP
;
2579 * Either monitor mode has been turned on for
2580 * the device, or we've been given a different
2581 * device to open for monitor mode. If we've
2582 * been given a different device, use it.
2584 if (handlep
->mondevice
!= NULL
)
2585 device
= handlep
->mondevice
;
2587 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2592 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
2593 if (handle
->linktype
== -1 ||
2594 handle
->linktype
== DLT_LINUX_SLL
||
2595 handle
->linktype
== DLT_LINUX_IRDA
||
2596 handle
->linktype
== DLT_LINUX_LAPD
||
2597 handle
->linktype
== DLT_NETLINK
||
2598 (handle
->linktype
== DLT_EN10MB
&&
2599 (strncmp("isdn", device
, 4) == 0 ||
2600 strncmp("isdY", device
, 4) == 0))) {
2602 * Unknown interface type (-1), or a
2603 * device we explicitly chose to run
2604 * in cooked mode (e.g., PPP devices),
2605 * or an ISDN device (whose link-layer
2606 * type we can only determine by using
2607 * APIs that may be different on different
2608 * kernels) - reopen in cooked mode.
2610 * If the type is unknown, return a warning;
2611 * map_arphrd_to_dlt() has already set the
2614 if (close(sock_fd
) == -1) {
2615 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2616 PCAP_ERRBUF_SIZE
, errno
, "close");
2619 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
, 0);
2622 * Fatal error. We treat this as
2623 * a generic error; we already know
2624 * that we were able to open a
2625 * PF_PACKET/SOCK_RAW socket, so
2626 * any failure is a "this shouldn't
2629 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2630 PCAP_ERRBUF_SIZE
, errno
, "socket");
2633 handlep
->cooked
= 1;
2636 * Get rid of any link-layer type list
2637 * we allocated - this only supports cooked
2640 if (handle
->dlt_list
!= NULL
) {
2641 free(handle
->dlt_list
);
2642 handle
->dlt_list
= NULL
;
2643 handle
->dlt_count
= 0;
2644 set_dlt_list_cooked(handle
, sock_fd
);
2647 if (handle
->linktype
== -1) {
2649 * Warn that we're falling back on
2650 * cooked mode; we may want to
2651 * update "map_arphrd_to_dlt()"
2652 * to handle the new type.
2654 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2656 "supported by libpcap - "
2657 "falling back to cooked "
2663 * IrDA capture is not a real "cooked" capture,
2664 * it's IrLAP frames, not IP packets. The
2665 * same applies to LAPD capture.
2667 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2668 handle
->linktype
!= DLT_LINUX_LAPD
&&
2669 handle
->linktype
!= DLT_NETLINK
)
2670 handle
->linktype
= DLT_LINUX_SLL
;
2671 if (handle
->linktype
== -1) {
2672 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2673 "unknown arptype %d, defaulting to cooked mode",
2675 status
= PCAP_WARNING
;
2679 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
2681 if (handlep
->ifindex
== -1) {
2686 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
2687 handle
->errbuf
, 0)) != 0) {
2695 if (handle
->opt
.rfmon
) {
2697 * It doesn't support monitor mode.
2700 return PCAP_ERROR_RFMON_NOTSUP
;
2704 * It uses cooked mode.
2706 handlep
->cooked
= 1;
2707 handle
->linktype
= DLT_LINUX_SLL
;
2708 handle
->dlt_list
= NULL
;
2709 handle
->dlt_count
= 0;
2710 set_dlt_list_cooked(handle
, sock_fd
);
2713 * We're not bound to a device.
2714 * For now, we're using this as an indication
2715 * that we can't transmit; stop doing that only
2716 * if we figure out how to transmit in cooked
2719 handlep
->ifindex
= -1;
2723 * Select promiscuous mode on if "promisc" is set.
2725 * Do not turn allmulti mode on if we don't select
2726 * promiscuous mode - on some devices (e.g., Orinoco
2727 * wireless interfaces), allmulti mode isn't supported
2728 * and the driver implements it by turning promiscuous
2729 * mode on, and that screws up the operation of the
2730 * card as a normal networking interface, and on no
2731 * other platform I know of does starting a non-
2732 * promiscuous capture affect which multicast packets
2733 * are received by the interface.
2737 * Hmm, how can we set promiscuous mode on all interfaces?
2738 * I am not sure if that is possible at all. For now, we
2739 * silently ignore attempts to turn promiscuous mode on
2740 * for the "any" device (so you don't have to explicitly
2741 * disable it in programs such as tcpdump).
2744 if (!is_any_device
&& handle
->opt
.promisc
) {
2745 memset(&mr
, 0, sizeof(mr
));
2746 mr
.mr_ifindex
= handlep
->ifindex
;
2747 mr
.mr_type
= PACKET_MR_PROMISC
;
2748 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2749 &mr
, sizeof(mr
)) == -1) {
2750 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2751 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
2757 /* Enable auxillary data if supported and reserve room for
2758 * reconstructing VLAN headers. */
2759 #ifdef HAVE_PACKET_AUXDATA
2761 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2762 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2763 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2764 errno
, "setsockopt (PACKET_AUXDATA)");
2768 handle
->offset
+= VLAN_TAG_LEN
;
2769 #endif /* HAVE_PACKET_AUXDATA */
2772 * If we're in cooked mode, make the snapshot length
2773 * large enough to hold a "cooked mode" header plus
2774 * 1 byte of packet data (so we don't pass a byte
2775 * count of 0 to "recvfrom()").
2776 * XXX - we don't know whether this will be DLT_LINUX_SLL
2777 * or DLT_LINUX_SLL2, so make sure it's big enough for
2778 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
2779 * that small is silly anyway.
2781 if (handlep
->cooked
) {
2782 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
2783 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
2785 handle
->bufsize
= handle
->snapshot
;
2788 * Set the offset at which to insert VLAN tags.
2789 * That should be the offset of the type field.
2791 switch (handle
->linktype
) {
2795 * The type field is after the destination and source
2798 handlep
->vlan_offset
= 2 * ETH_ALEN
;
2803 * The type field is in the last 2 bytes of the
2804 * DLT_LINUX_SLL header.
2806 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
2810 handlep
->vlan_offset
= -1; /* unknown */
2814 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
2815 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
2816 int nsec_tstamps
= 1;
2818 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
2819 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
2824 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
2827 * We've succeeded. Save the socket FD in the pcap structure.
2829 handle
->fd
= sock_fd
;
2831 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
2833 * Can we generate special code for VLAN checks?
2834 * (XXX - what if we need the special code but it's not supported
2835 * by the OS? Is that possible?)
2837 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
2838 &bpf_extensions
, &len
) == 0) {
2839 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
2841 * Yes, we can. Request that we do so.
2843 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
2846 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
2852 * Attempt to setup memory-mapped access.
2854 * On success, returns 1, and sets *status to 0 if there are no warnings
2855 * or to a PCAP_WARNING_ code if there is a warning.
2857 * On error, returns -1, and sets *status to the appropriate error code;
2858 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
2861 setup_mmapped(pcap_t
*handle
, int *status
)
2863 struct pcap_linux
*handlep
= handle
->priv
;
2867 * Attempt to allocate a buffer to hold the contents of one
2868 * packet, for use by the oneshot callback.
2870 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
2871 if (handlep
->oneshot_buffer
== NULL
) {
2872 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2873 errno
, "can't allocate oneshot buffer");
2874 *status
= PCAP_ERROR
;
2878 if (handle
->opt
.buffer_size
== 0) {
2879 /* by default request 2M for the ring buffer */
2880 handle
->opt
.buffer_size
= 2*1024*1024;
2882 ret
= prepare_tpacket_socket(handle
);
2884 free(handlep
->oneshot_buffer
);
2885 *status
= PCAP_ERROR
;
2888 ret
= create_ring(handle
, status
);
2891 * Error attempting to enable memory-mapped capture;
2892 * fail. create_ring() has set *status.
2894 free(handlep
->oneshot_buffer
);
2899 * Success. *status has been set either to 0 if there are no
2900 * warnings or to a PCAP_WARNING_ value if there is a warning.
2902 * handle->offset is used to get the current position into the rx ring.
2903 * handle->cc is used to store the ring size.
2907 * Set the timeout to use in poll() before returning.
2909 set_poll_timeout(handlep
);
2915 * Attempt to set the socket to the specified version of the memory-mapped
2918 * Return 0 if we succeed; return 1 if we fail because that version isn't
2919 * supported; return -1 on any other error, and set handle->errbuf.
2922 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
2924 struct pcap_linux
*handlep
= handle
->priv
;
2926 socklen_t len
= sizeof(val
);
2929 * Probe whether kernel supports the specified TPACKET version;
2930 * this also gets the length of the header for that version.
2932 * This socket option was introduced in 2.6.27, which was
2933 * also the first release with TPACKET_V2 support.
2935 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
2936 if (errno
== EINVAL
) {
2938 * EINVAL means this specific version of TPACKET
2939 * is not supported. Tell the caller they can try
2940 * with a different one; if they've run out of
2941 * others to try, let them set the error message
2948 * All other errors are fatal.
2950 if (errno
== ENOPROTOOPT
) {
2952 * PACKET_HDRLEN isn't supported, which means
2953 * that memory-mapped capture isn't supported.
2954 * Indicate that in the message.
2956 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2957 "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");
2960 * Some unexpected error.
2962 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2963 errno
, "can't get %s header len on packet socket",
2968 handlep
->tp_hdrlen
= val
;
2971 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
2973 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2974 errno
, "can't activate %s on packet socket", version_str
);
2977 handlep
->tp_version
= version
;
2983 * Attempt to set the socket to version 3 of the memory-mapped header and,
2984 * if that fails because version 3 isn't supported, attempt to fall
2985 * back to version 2. If version 2 isn't supported, just fail.
2987 * Return 0 if we succeed and -1 on any other error, and set handle->errbuf.
2990 prepare_tpacket_socket(pcap_t
*handle
)
2994 #ifdef HAVE_TPACKET3
2996 * Try setting the version to TPACKET_V3.
2998 * The only mode in which buffering is done on PF_PACKET
2999 * sockets, so that packets might not be delivered
3000 * immediately, is TPACKET_V3 mode.
3002 * The buffering cannot be disabled in that mode, so
3003 * if the user has requested immediate mode, we don't
3006 if (!handle
->opt
.immediate
) {
3007 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
3016 * We failed for some reason other than "the
3017 * kernel doesn't support TPACKET_V3".
3023 * This means it returned 1, which means "the kernel
3024 * doesn't support TPACKET_V3"; try TPACKET_V2.
3027 #endif /* HAVE_TPACKET3 */
3030 * Try setting the version to TPACKET_V2.
3032 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
3042 * OK, the kernel supports memory-mapped capture, but
3043 * not TPACKET_V2. Set the error message appropriately.
3045 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3046 "Kernel doesn't support TPACKET_V2; a 2.6.27 or later kernel is required");
3055 #define MAX(a,b) ((a)>(b)?(a):(b))
3058 * Attempt to set up memory-mapped access.
3060 * On success, returns 1, and sets *status to 0 if there are no warnings
3061 * or to a PCAP_WARNING_ code if there is a warning.
3063 * On error, returns -1, and sets *status to the appropriate error code;
3064 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3067 create_ring(pcap_t
*handle
, int *status
)
3069 struct pcap_linux
*handlep
= handle
->priv
;
3070 unsigned i
, j
, frames_per_block
;
3071 #ifdef HAVE_TPACKET3
3073 * For sockets using TPACKET_V2, the extra stuff at the end of a
3074 * struct tpacket_req3 will be ignored, so this is OK even for
3077 struct tpacket_req3 req
;
3079 struct tpacket_req req
;
3082 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3083 unsigned int frame_size
;
3086 * Start out assuming no warnings or errors.
3091 * Reserve space for VLAN tag reconstruction.
3093 tp_reserve
= VLAN_TAG_LEN
;
3096 * If we're using DLT_LINUX_SLL2, reserve space for a
3097 * DLT_LINUX_SLL2 header.
3099 * XXX - we assume that the kernel is still adding
3100 * 16 bytes of extra space; that happens to
3101 * correspond to SLL_HDR_LEN (whether intentionally
3102 * or not - the kernel code has a raw "16" in
3103 * the expression), so we subtract SLL_HDR_LEN
3104 * from SLL2_HDR_LEN to get the additional space
3105 * needed. That also means we don't bother reserving
3106 * any additional space if we're using DLT_LINUX_SLL.
3108 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
3110 if (handle
->linktype
== DLT_LINUX_SLL2
)
3111 tp_reserve
+= SLL2_HDR_LEN
- SLL_HDR_LEN
;
3114 * Try to request that amount of reserve space.
3115 * This must be done before creating the ring buffer.
3116 * If PACKET_RESERVE is supported, creating the ring
3117 * buffer should be, although if creating the ring
3118 * buffer fails, the PACKET_RESERVE call has no effect,
3119 * so falling back on read-from-the-socket capturing
3120 * won't be affected.
3122 len
= sizeof(tp_reserve
);
3123 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
3124 &tp_reserve
, len
) < 0) {
3126 * We treat ENOPROTOOPT as an error, as we
3127 * already determined that we support
3128 * TPACKET_V2 and later; see above.
3130 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3131 PCAP_ERRBUF_SIZE
, errno
,
3132 "setsockopt (PACKET_RESERVE)");
3133 *status
= PCAP_ERROR
;
3137 switch (handlep
->tp_version
) {
3140 /* Note that with large snapshot length (say 256K, which is
3141 * the default for recent versions of tcpdump, Wireshark,
3142 * TShark, dumpcap or 64K, the value that "-s 0" has given for
3143 * a long time with tcpdump), if we use the snapshot
3144 * length to calculate the frame length, only a few frames
3145 * will be available in the ring even with pretty
3146 * large ring size (and a lot of memory will be unused).
3148 * Ideally, we should choose a frame length based on the
3149 * minimum of the specified snapshot length and the maximum
3150 * packet size. That's not as easy as it sounds; consider,
3151 * for example, an 802.11 interface in monitor mode, where
3152 * the frame would include a radiotap header, where the
3153 * maximum radiotap header length is device-dependent.
3155 * So, for now, we just do this for Ethernet devices, where
3156 * there's no metadata header, and the link-layer header is
3157 * fixed length. We can get the maximum packet size by
3158 * adding 18, the Ethernet header length plus the CRC length
3159 * (just in case we happen to get the CRC in the packet), to
3160 * the MTU of the interface; we fetch the MTU in the hopes
3161 * that it reflects support for jumbo frames. (Even if the
3162 * interface is just being used for passive snooping, the
3163 * driver might set the size of buffers in the receive ring
3164 * based on the MTU, so that the MTU limits the maximum size
3165 * of packets that we can receive.)
3167 * If segmentation/fragmentation or receive offload are
3168 * enabled, we can get reassembled/aggregated packets larger
3169 * than MTU, but bounded to 65535 plus the Ethernet overhead,
3170 * due to kernel and protocol constraints */
3171 frame_size
= handle
->snapshot
;
3172 if (handle
->linktype
== DLT_EN10MB
) {
3173 unsigned int max_frame_len
;
3177 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
3180 *status
= PCAP_ERROR
;
3183 offload
= iface_get_offload(handle
);
3184 if (offload
== -1) {
3185 *status
= PCAP_ERROR
;
3189 max_frame_len
= MAX(mtu
, 65535);
3191 max_frame_len
= mtu
;
3192 max_frame_len
+= 18;
3194 if (frame_size
> max_frame_len
)
3195 frame_size
= max_frame_len
;
3198 /* NOTE: calculus matching those in tpacket_rcv()
3199 * in linux-2.6/net/packet/af_packet.c
3201 len
= sizeof(sk_type
);
3202 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
3204 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3205 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
3206 *status
= PCAP_ERROR
;
3209 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3210 /* XXX: in the kernel maclen is calculated from
3211 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3212 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3213 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3214 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3215 * but I see no way to get those sizes in userspace,
3216 * like for instance with an ifreq ioctl();
3217 * the best thing I've found so far is MAX_HEADER in
3218 * the kernel part of linux-2.6/include/linux/netdevice.h
3219 * which goes up to 128+48=176; since pcap-linux.c
3220 * defines a MAX_LINKHEADER_SIZE of 256 which is
3221 * greater than that, let's use it.. maybe is it even
3222 * large enough to directly replace macoff..
3224 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3225 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3226 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3227 * of netoff, which contradicts
3228 * linux-2.6/Documentation/networking/packet_mmap.txt
3230 * "- Gap, chosen so that packet data (Start+tp_net)
3231 * aligns to TPACKET_ALIGNMENT=16"
3233 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3234 * "CPUs often take a performance hit
3235 * when accessing unaligned memory locations"
3237 macoff
= netoff
- maclen
;
3238 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3240 * Round the buffer size up to a multiple of the
3241 * frame size (rather than rounding down, which
3242 * would give a buffer smaller than our caller asked
3243 * for, and possibly give zero frames if the requested
3244 * buffer size is too small for one frame).
3246 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3249 #ifdef HAVE_TPACKET3
3251 /* The "frames" for this are actually buffers that
3252 * contain multiple variable-sized frames.
3254 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
3255 * enough room for at least one reasonably-sized packet
3256 * in the "frame". */
3257 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
3259 * Round the buffer size up to a multiple of the
3260 * "frame" size (rather than rounding down, which
3261 * would give a buffer smaller than our caller asked
3262 * for, and possibly give zero "frames" if the requested
3263 * buffer size is too small for one "frame").
3265 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
3269 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3270 "Internal error: unknown TPACKET_ value %u",
3271 handlep
->tp_version
);
3272 *status
= PCAP_ERROR
;
3276 /* compute the minumum block size that will handle this frame.
3277 * The block has to be page size aligned.
3278 * The max block size allowed by the kernel is arch-dependent and
3279 * it's not explicitly checked here. */
3280 req
.tp_block_size
= getpagesize();
3281 while (req
.tp_block_size
< req
.tp_frame_size
)
3282 req
.tp_block_size
<<= 1;
3284 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3287 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3288 * so we check for PACKET_TIMESTAMP. We check for
3289 * linux/net_tstamp.h just in case a system somehow has
3290 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3293 * SIOCSHWTSTAMP was introduced in the patch that introduced
3294 * linux/net_tstamp.h, so we don't bother checking whether
3295 * SIOCSHWTSTAMP is defined (if your Linux system has
3296 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3297 * Linux system is badly broken).
3299 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3301 * If we were told to do so, ask the kernel and the driver
3302 * to use hardware timestamps.
3304 * Hardware timestamps are only supported with mmapped
3307 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3308 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3309 struct hwtstamp_config hwconfig
;
3314 * Ask for hardware time stamps on all packets,
3315 * including transmitted packets.
3317 memset(&hwconfig
, 0, sizeof(hwconfig
));
3318 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3319 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3321 memset(&ifr
, 0, sizeof(ifr
));
3322 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
3323 ifr
.ifr_data
= (void *)&hwconfig
;
3325 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3330 * Treat this as an error, as the
3331 * user should try to run this
3332 * with the appropriate privileges -
3333 * and, if they can't, shouldn't
3334 * try requesting hardware time stamps.
3336 *status
= PCAP_ERROR_PERM_DENIED
;
3342 * Treat this as a warning, as the
3343 * only way to fix the warning is to
3344 * get an adapter that supports hardware
3345 * time stamps for *all* packets.
3346 * (ERANGE means "we support hardware
3347 * time stamps, but for packets matching
3348 * that particular filter", so it means
3349 * "we don't support hardware time stamps
3350 * for all incoming packets" here.)
3352 * We'll just fall back on the standard
3355 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3359 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3360 PCAP_ERRBUF_SIZE
, errno
,
3361 "SIOCSHWTSTAMP failed");
3362 *status
= PCAP_ERROR
;
3367 * Well, that worked. Now specify the type of
3368 * hardware time stamp we want for this
3371 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3373 * Hardware timestamp, synchronized
3374 * with the system clock.
3376 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3379 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3380 * timestamp, not synchronized with the
3383 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3385 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3386 (void *)×ource
, sizeof(timesource
))) {
3387 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3388 PCAP_ERRBUF_SIZE
, errno
,
3389 "can't set PACKET_TIMESTAMP");
3390 *status
= PCAP_ERROR
;
3395 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3397 /* ask the kernel to create the ring */
3399 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3401 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3402 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3404 #ifdef HAVE_TPACKET3
3405 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3406 if (handlep
->timeout
> 0) {
3407 /* Use the user specified timeout as the block timeout */
3408 req
.tp_retire_blk_tov
= handlep
->timeout
;
3409 } else if (handlep
->timeout
== 0) {
3411 * In pcap, this means "infinite timeout"; TPACKET_V3
3412 * doesn't support that, so just set it to UINT_MAX
3413 * milliseconds. In the TPACKET_V3 loop, if the
3414 * timeout is 0, and we haven't yet seen any packets,
3415 * and we block and still don't have any packets, we
3416 * keep blocking until we do.
3418 req
.tp_retire_blk_tov
= UINT_MAX
;
3421 * XXX - this is not valid; use 0, meaning "have the
3422 * kernel pick a default", for now.
3424 req
.tp_retire_blk_tov
= 0;
3426 /* private data not used */
3427 req
.tp_sizeof_priv
= 0;
3428 /* Rx ring - feature request bits - none (rxhash will not be filled) */
3429 req
.tp_feature_req_word
= 0;
3432 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3433 (void *) &req
, sizeof(req
))) {
3434 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3436 * Memory failure; try to reduce the requested ring
3439 * We used to reduce this by half -- do 5% instead.
3440 * That may result in more iterations and a longer
3441 * startup, but the user will be much happier with
3442 * the resulting buffer size.
3444 if (req
.tp_frame_nr
< 20)
3445 req
.tp_frame_nr
-= 1;
3447 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3450 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3451 errno
, "can't create rx ring on packet socket");
3452 *status
= PCAP_ERROR
;
3456 /* memory map the rx ring */
3457 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3458 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
3459 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3460 if (handlep
->mmapbuf
== MAP_FAILED
) {
3461 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3462 errno
, "can't mmap rx ring");
3464 /* clear the allocated ring on error*/
3465 destroy_ring(handle
);
3466 *status
= PCAP_ERROR
;
3470 /* allocate a ring for each frame header pointer*/
3471 handle
->cc
= req
.tp_frame_nr
;
3472 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3473 if (!handle
->buffer
) {
3474 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3475 errno
, "can't allocate ring of frame headers");
3477 destroy_ring(handle
);
3478 *status
= PCAP_ERROR
;
3482 /* fill the header ring with proper frame ptr*/
3484 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3485 u_char
*base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3486 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3487 RING_GET_CURRENT_FRAME(handle
) = base
;
3488 base
+= req
.tp_frame_size
;
3492 handle
->bufsize
= req
.tp_frame_size
;
3497 /* free all ring related resources*/
3499 destroy_ring(pcap_t
*handle
)
3501 struct pcap_linux
*handlep
= handle
->priv
;
3504 * Tell the kernel to destroy the ring.
3505 * We don't check for setsockopt failure, as 1) we can't recover
3506 * from an error and 2) we might not yet have set it up in the
3509 struct tpacket_req req
;
3510 memset(&req
, 0, sizeof(req
));
3511 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3512 (void *) &req
, sizeof(req
));
3514 /* if ring is mapped, unmap it*/
3515 if (handlep
->mmapbuf
) {
3516 /* do not test for mmap failure, as we can't recover from any error */
3517 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3518 handlep
->mmapbuf
= NULL
;
3523 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3524 * for Linux mmapped capture.
3526 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3527 * data handed to the callback to be valid after the callback returns,
3528 * but pcap_read_linux_mmap() has to release that packet as soon as
3529 * the callback returns (otherwise, the kernel thinks there's still
3530 * at least one unprocessed packet available in the ring, so a select()
3531 * will immediately return indicating that there's data to process), so,
3532 * in the callback, we have to make a copy of the packet.
3534 * Yes, this means that, if the capture is using the ring buffer, using
3535 * pcap_next() or pcap_next_ex() requires more copies than using
3536 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3537 * pcap_next() or pcap_next_ex().
3540 pcap_oneshot_linux(u_char
*user
, const struct pcap_pkthdr
*h
,
3541 const u_char
*bytes
)
3543 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3544 pcap_t
*handle
= sp
->pd
;
3545 struct pcap_linux
*handlep
= handle
->priv
;
3548 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3549 *sp
->pkt
= handlep
->oneshot_buffer
;
3553 pcap_getnonblock_linux(pcap_t
*handle
)
3555 struct pcap_linux
*handlep
= handle
->priv
;
3557 /* use negative value of timeout to indicate non blocking ops */
3558 return (handlep
->timeout
<0);
3562 pcap_setnonblock_linux(pcap_t
*handle
, int nonblock
)
3564 struct pcap_linux
*handlep
= handle
->priv
;
3567 * Set the file descriptor to non-blocking mode, as we use
3568 * it for sending packets.
3570 if (pcap_setnonblock_fd(handle
, nonblock
) == -1)
3574 * Map each value to their corresponding negation to
3575 * preserve the timeout value provided with pcap_set_timeout.
3578 if (handlep
->timeout
>= 0) {
3580 * Indicate that we're switching to
3581 * non-blocking mode.
3583 handlep
->timeout
= ~handlep
->timeout
;
3586 if (handlep
->timeout
< 0) {
3587 handlep
->timeout
= ~handlep
->timeout
;
3590 /* Update the timeout to use in poll(). */
3591 set_poll_timeout(handlep
);
3596 * Get the status field of the ring buffer frame at a specified offset.
3599 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
3601 struct pcap_linux
*handlep
= handle
->priv
;
3604 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
3605 switch (handlep
->tp_version
) {
3607 return (h
.h2
->tp_status
);
3609 #ifdef HAVE_TPACKET3
3611 return (h
.h3
->hdr
.bh1
.block_status
);
3615 /* This should not happen. */
3624 * Block waiting for frames to be available.
3626 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
3628 struct pcap_linux
*handlep
= handle
->priv
;
3632 struct pollfd pollinfo
[2];
3633 pollinfo
[0].fd
= handle
->fd
;
3634 pollinfo
[0].events
= POLLIN
;
3635 pollinfo
[1].fd
= handlep
->poll_breakloop_fd
;
3636 pollinfo
[1].events
= POLLIN
;
3639 * Keep polling until we either get some packets to read, see
3640 * that we got told to break out of the loop, get a fatal error,
3641 * or discover that the device went away.
3643 * In non-blocking mode, we must still do one poll() to catch
3644 * any pending error indications, but the poll() has a timeout
3645 * of 0, so that it doesn't block, and we quit after that one
3648 * If we've seen an ENETDOWN, it might be the first indication
3649 * that the device went away, or it might just be that it was
3650 * configured down. Unfortunately, there's no guarantee that
3651 * the device has actually been removed as an interface, because:
3653 * 1) if, as appears to be the case at least some of the time,
3654 * the PF_PACKET socket code first gets a NETDEV_DOWN indication
3655 * for the device and then gets a NETDEV_UNREGISTER indication
3656 * for it, the first indication will cause a wakeup with ENETDOWN
3657 * but won't set the packet socket's field for the interface index
3658 * to -1, and the second indication won't cause a wakeup (because
3659 * the first indication also caused the protocol hook to be
3660 * unregistered) but will set the packet socket's field for the
3661 * interface index to -1;
3663 * 2) even if just a NETDEV_UNREGISTER indication is registered,
3664 * the packet socket's field for the interface index only gets
3665 * set to -1 after the wakeup, so there's a small but non-zero
3666 * risk that a thread blocked waiting for the wakeup will get
3667 * to the "fetch the socket name" code before the interface index
3668 * gets set to -1, so it'll get the old interface index.
3670 * Therefore, if we got an ENETDOWN and haven't seen a packet
3671 * since then, we assume that we might be waiting for the interface
3672 * to disappear, and poll with a timeout to try again in a short
3673 * period of time. If we *do* see a packet, the interface has
3674 * come back up again, and is *definitely* still there, so we
3675 * don't need to poll.
3679 * Yes, we do this even in non-blocking mode, as it's
3680 * the only way to get error indications from a
3683 * The timeout is 0 in non-blocking mode, so poll()
3684 * returns immediately.
3686 timeout
= handlep
->poll_timeout
;
3689 * If we got an ENETDOWN and haven't gotten an indication
3690 * that the device has gone away or that the device is up,
3691 * we don't yet know for certain whether the device has
3692 * gone away or not, do a poll() with a 1-millisecond timeout,
3693 * as we have to poll indefinitely for "device went away"
3694 * indications until we either get one or see that the
3697 if (handlep
->netdown
) {
3701 ret
= poll(pollinfo
, 2, timeout
);
3704 * Error. If it's not EINTR, report it.
3706 if (errno
!= EINTR
) {
3707 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3708 PCAP_ERRBUF_SIZE
, errno
,
3709 "can't poll on packet socket");
3714 * It's EINTR; if we were told to break out of
3717 if (handle
->break_loop
) {
3718 handle
->break_loop
= 0;
3719 return PCAP_ERROR_BREAK
;
3721 } else if (ret
> 0) {
3723 * OK, some descriptor is ready.
3724 * Check the socket descriptor first.
3726 * As I read the Linux man page, pollinfo[0].revents
3727 * will either be POLLIN, POLLERR, POLLHUP, or POLLNVAL.
3729 if (pollinfo
[0].revents
== POLLIN
) {
3731 * OK, we may have packets to
3736 if (pollinfo
[0].revents
!= 0) {
3738 * There's some indication other than
3739 * "you can read on this descriptor" on
3742 if (pollinfo
[0].revents
& POLLNVAL
) {
3743 snprintf(handle
->errbuf
,
3745 "Invalid polling request on packet socket");
3748 if (pollinfo
[0].revents
& (POLLHUP
| POLLRDHUP
)) {
3749 snprintf(handle
->errbuf
,
3751 "Hangup on packet socket");
3754 if (pollinfo
[0].revents
& POLLERR
) {
3761 errlen
= sizeof(err
);
3762 if (getsockopt(handle
->fd
, SOL_SOCKET
,
3763 SO_ERROR
, &err
, &errlen
) == -1) {
3765 * The call *itself* returned
3766 * an error; make *that*
3773 * OK, we have the error.
3775 if (err
== ENETDOWN
) {
3777 * The device on which we're
3778 * capturing went away or the
3779 * interface was taken down.
3781 * We don't know for certain
3782 * which happened, and the
3783 * next poll() may indicate
3784 * that there are packets
3785 * to be read, so just set
3786 * a flag to get us to do
3787 * checks later, and set
3788 * the required select
3789 * timeout to 1 millisecond
3790 * so that event loops that
3791 * check our socket descriptor
3792 * also time out so that
3793 * they can call us and we
3794 * can do the checks.
3796 handlep
->netdown
= 1;
3797 handle
->required_select_timeout
= &netdown_timeout
;
3798 } else if (err
== 0) {
3800 * This shouldn't happen, so
3801 * report a special indication
3804 snprintf(handle
->errbuf
,
3806 "Error condition on packet socket: Reported error was 0");
3809 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3812 "Error condition on packet socket");
3818 * Now check the event device.
3820 if (pollinfo
[1].revents
& POLLIN
) {
3822 (void)read(handlep
->poll_breakloop_fd
, &value
,
3826 * This event gets signaled by a
3827 * pcap_breakloop() call; if we were told
3828 * to break out of the loop, do so.
3830 if (handle
->break_loop
) {
3831 handle
->break_loop
= 0;
3832 return PCAP_ERROR_BREAK
;
3840 * 1) we got neither an error from poll() nor any
3841 * readable descriptors, in which case there
3842 * are no packets waiting to read
3846 * 2) We got readable descriptors but the PF_PACKET
3847 * socket wasn't one of them, in which case there
3848 * are no packets waiting to read
3850 * so, if we got an ENETDOWN, we've drained whatever
3851 * packets were available to read at the point of the
3854 * So, if we got an ENETDOWN and haven't gotten an indication
3855 * that the device has gone away or that the device is up,
3856 * we don't yet know for certain whether the device has
3857 * gone away or not, check whether the device exists and is
3860 if (handlep
->netdown
) {
3861 if (!device_still_exists(handle
)) {
3863 * The device doesn't exist any more;
3866 * XXX - we should really return an
3867 * appropriate error for that, but
3868 * pcap_dispatch() etc. aren't documented
3869 * as having error returns other than
3870 * PCAP_ERROR or PCAP_ERROR_BREAK.
3872 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3873 "The interface disappeared");
3878 * The device still exists; try to see if it's up.
3880 memset(&ifr
, 0, sizeof(ifr
));
3881 pcap_strlcpy(ifr
.ifr_name
, handlep
->device
,
3882 sizeof(ifr
.ifr_name
));
3883 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
3884 if (errno
== ENXIO
|| errno
== ENODEV
) {
3886 * OK, *now* it's gone.
3888 * XXX - see above comment.
3890 snprintf(handle
->errbuf
,
3892 "The interface disappeared");
3895 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3896 PCAP_ERRBUF_SIZE
, errno
,
3897 "%s: Can't get flags",
3902 if (ifr
.ifr_flags
& IFF_UP
) {
3904 * It's up, so it definitely still exists.
3905 * Cancel the ENETDOWN indication - we
3906 * presumably got it due to the interface
3907 * going down rather than the device going
3908 * away - and revert to "no required select
3911 handlep
->netdown
= 0;
3912 handle
->required_select_timeout
= NULL
;
3917 * If we're in non-blocking mode, just quit now, rather
3918 * than spinning in a loop doing poll()s that immediately
3919 * time out if there's no indication on any descriptor.
3921 if (handlep
->poll_timeout
== 0)
3927 /* handle a single memory mapped packet */
3928 static int pcap_handle_packet_mmap(
3930 pcap_handler callback
,
3932 unsigned char *frame
,
3933 unsigned int tp_len
,
3934 unsigned int tp_mac
,
3935 unsigned int tp_snaplen
,
3936 unsigned int tp_sec
,
3937 unsigned int tp_usec
,
3938 int tp_vlan_tci_valid
,
3942 struct pcap_linux
*handlep
= handle
->priv
;
3944 struct sockaddr_ll
*sll
;
3945 struct pcap_pkthdr pcaphdr
;
3946 unsigned int snaplen
= tp_snaplen
;
3947 struct utsname utsname
;
3949 /* perform sanity check on internal offset. */
3950 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3952 * Report some system information as a debugging aid.
3954 if (uname(&utsname
) != -1) {
3955 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3956 "corrupted frame on kernel ring mac "
3957 "offset %u + caplen %u > frame len %d "
3958 "(kernel %.32s version %s, machine %.16s)",
3959 tp_mac
, tp_snaplen
, handle
->bufsize
,
3960 utsname
.release
, utsname
.version
,
3963 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3964 "corrupted frame on kernel ring mac "
3965 "offset %u + caplen %u > frame len %d",
3966 tp_mac
, tp_snaplen
, handle
->bufsize
);
3971 /* run filter on received packet
3972 * If the kernel filtering is enabled we need to run the
3973 * filter until all the frames present into the ring
3974 * at filter creation time are processed.
3975 * In this case, blocks_to_filter_in_userland is used
3976 * as a counter for the packet we need to filter.
3977 * Note: alternatively it could be possible to stop applying
3978 * the filter when the ring became empty, but it can possibly
3979 * happen a lot later... */
3980 bp
= frame
+ tp_mac
;
3982 /* if required build in place the sll header*/
3983 sll
= (void *)(frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
));
3984 if (handlep
->cooked
) {
3985 if (handle
->linktype
== DLT_LINUX_SLL2
) {
3986 struct sll2_header
*hdrp
;
3989 * The kernel should have left us with enough
3990 * space for an sll header; back up the packet
3991 * data pointer into that space, as that'll be
3992 * the beginning of the packet we pass to the
3998 * Let's make sure that's past the end of
3999 * the tpacket header, i.e. >=
4000 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4001 * don't step on the header when we construct
4004 if (bp
< (u_char
*)frame
+
4005 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4006 sizeof(struct sockaddr_ll
)) {
4007 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4008 "cooked-mode frame doesn't have room for sll header");
4013 * OK, that worked; construct the sll header.
4015 hdrp
= (struct sll2_header
*)bp
;
4016 hdrp
->sll2_protocol
= sll
->sll_protocol
;
4017 hdrp
->sll2_reserved_mbz
= 0;
4018 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
4019 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
4020 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
4021 hdrp
->sll2_halen
= sll
->sll_halen
;
4022 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4024 snaplen
+= sizeof(struct sll2_header
);
4026 struct sll_header
*hdrp
;
4029 * The kernel should have left us with enough
4030 * space for an sll header; back up the packet
4031 * data pointer into that space, as that'll be
4032 * the beginning of the packet we pass to the
4038 * Let's make sure that's past the end of
4039 * the tpacket header, i.e. >=
4040 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4041 * don't step on the header when we construct
4044 if (bp
< (u_char
*)frame
+
4045 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4046 sizeof(struct sockaddr_ll
)) {
4047 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4048 "cooked-mode frame doesn't have room for sll header");
4053 * OK, that worked; construct the sll header.
4055 hdrp
= (struct sll_header
*)bp
;
4056 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
4057 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4058 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4059 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4060 hdrp
->sll_protocol
= sll
->sll_protocol
;
4062 snaplen
+= sizeof(struct sll_header
);
4066 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
4067 struct bpf_aux_data aux_data
;
4069 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
4070 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4072 if (pcap_filter_with_aux_data(handle
->fcode
.bf_insns
,
4080 if (!linux_check_direction(handle
, sll
))
4083 /* get required packet info from ring header */
4084 pcaphdr
.ts
.tv_sec
= tp_sec
;
4085 pcaphdr
.ts
.tv_usec
= tp_usec
;
4086 pcaphdr
.caplen
= tp_snaplen
;
4087 pcaphdr
.len
= tp_len
;
4089 /* if required build in place the sll header*/
4090 if (handlep
->cooked
) {
4091 /* update packet len */
4092 if (handle
->linktype
== DLT_LINUX_SLL2
) {
4093 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
4094 pcaphdr
.len
+= SLL2_HDR_LEN
;
4096 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4097 pcaphdr
.len
+= SLL_HDR_LEN
;
4101 if (tp_vlan_tci_valid
&&
4102 handlep
->vlan_offset
!= -1 &&
4103 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4105 struct vlan_tag
*tag
;
4108 * Move everything in the header, except the type field,
4109 * down VLAN_TAG_LEN bytes, to allow us to insert the
4110 * VLAN tag between that stuff and the type field.
4113 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4116 * Now insert the tag.
4118 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4119 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4120 tag
->vlan_tci
= htons(tp_vlan_tci
);
4123 * Add the tag to the packet lengths.
4125 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4126 pcaphdr
.len
+= VLAN_TAG_LEN
;
4130 * The only way to tell the kernel to cut off the
4131 * packet at a snapshot length is with a filter program;
4132 * if there's no filter program, the kernel won't cut
4135 * Trim the snapshot length to be no longer than the
4136 * specified snapshot length.
4138 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
4139 pcaphdr
.caplen
= handle
->snapshot
;
4141 /* pass the packet to the user */
4142 callback(user
, &pcaphdr
, bp
);
4148 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4151 struct pcap_linux
*handlep
= handle
->priv
;
4156 /* wait for frames availability.*/
4157 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4158 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
) {
4160 * The current frame is owned by the kernel; wait for
4161 * a frame to be handed to us.
4163 ret
= pcap_wait_for_frames_mmap(handle
);
4169 /* non-positive values of max_packets are used to require all
4170 * packets currently available in the ring */
4171 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4173 * Get the current ring buffer frame, and break if
4174 * it's still owned by the kernel.
4176 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4177 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
)
4180 ret
= pcap_handle_packet_mmap(
4189 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4190 VLAN_VALID(h
.h2
, h
.h2
),
4192 VLAN_TPID(h
.h2
, h
.h2
));
4195 } else if (ret
< 0) {
4200 * Hand this block back to the kernel, and, if we're
4201 * counting blocks that need to be filtered in userland
4202 * after having been filtered by the kernel, count
4203 * the one we've just processed.
4205 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4206 if (handlep
->blocks_to_filter_in_userland
> 0) {
4207 handlep
->blocks_to_filter_in_userland
--;
4208 if (handlep
->blocks_to_filter_in_userland
== 0) {
4210 * No more blocks need to be filtered
4213 handlep
->filter_in_userland
= 0;
4218 if (++handle
->offset
>= handle
->cc
)
4221 /* check for break loop condition*/
4222 if (handle
->break_loop
) {
4223 handle
->break_loop
= 0;
4224 return PCAP_ERROR_BREAK
;
4230 #ifdef HAVE_TPACKET3
4232 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4235 struct pcap_linux
*handlep
= handle
->priv
;
4241 if (handlep
->current_packet
== NULL
) {
4242 /* wait for frames availability.*/
4243 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4244 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4246 * The current frame is owned by the kernel; wait
4247 * for a frame to be handed to us.
4249 ret
= pcap_wait_for_frames_mmap(handle
);
4255 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4256 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4257 if (pkts
== 0 && handlep
->timeout
== 0) {
4258 /* Block until we see a packet. */
4264 /* non-positive values of max_packets are used to require all
4265 * packets currently available in the ring */
4266 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4267 int packets_to_read
;
4269 if (handlep
->current_packet
== NULL
) {
4270 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4271 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
)
4274 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4275 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4277 packets_to_read
= handlep
->packets_left
;
4279 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) &&
4280 packets_to_read
> (max_packets
- pkts
)) {
4282 * We've been given a maximum number of packets
4283 * to process, and there are more packets in
4284 * this buffer than that. Only process enough
4285 * of them to get us up to that maximum.
4287 packets_to_read
= max_packets
- pkts
;
4290 while (packets_to_read
-- && !handle
->break_loop
) {
4291 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4292 ret
= pcap_handle_packet_mmap(
4296 handlep
->current_packet
,
4299 tp3_hdr
->tp_snaplen
,
4301 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4302 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
4303 tp3_hdr
->hv1
.tp_vlan_tci
,
4304 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
4307 } else if (ret
< 0) {
4308 handlep
->current_packet
= NULL
;
4311 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4312 handlep
->packets_left
--;
4315 if (handlep
->packets_left
<= 0) {
4317 * Hand this block back to the kernel, and, if
4318 * we're counting blocks that need to be
4319 * filtered in userland after having been
4320 * filtered by the kernel, count the one we've
4323 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
4324 if (handlep
->blocks_to_filter_in_userland
> 0) {
4325 handlep
->blocks_to_filter_in_userland
--;
4326 if (handlep
->blocks_to_filter_in_userland
== 0) {
4328 * No more blocks need to be filtered
4331 handlep
->filter_in_userland
= 0;
4336 if (++handle
->offset
>= handle
->cc
)
4339 handlep
->current_packet
= NULL
;
4342 /* check for break loop condition*/
4343 if (handle
->break_loop
) {
4344 handle
->break_loop
= 0;
4345 return PCAP_ERROR_BREAK
;
4348 if (pkts
== 0 && handlep
->timeout
== 0) {
4349 /* Block until we see a packet. */
4354 #endif /* HAVE_TPACKET3 */
4357 * Attach the given BPF code to the packet capture device.
4360 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
4362 struct pcap_linux
*handlep
;
4363 struct sock_fprog fcode
;
4364 int can_filter_in_kernel
;
4371 pcap_strlcpy(handle
->errbuf
, "setfilter: No filter specified",
4376 handlep
= handle
->priv
;
4378 /* Make our private copy of the filter */
4380 if (install_bpf_program(handle
, filter
) < 0)
4381 /* install_bpf_program() filled in errbuf */
4385 * Run user level packet filter by default. Will be overriden if
4386 * installing a kernel filter succeeds.
4388 handlep
->filter_in_userland
= 1;
4390 /* Install kernel level filter if possible */
4393 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
4395 * fcode.len is an unsigned short for current kernel.
4396 * I have yet to see BPF-Code with that much
4397 * instructions but still it is possible. So for the
4398 * sake of correctness I added this check.
4400 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
4402 fcode
.filter
= NULL
;
4403 can_filter_in_kernel
= 0;
4405 #endif /* USHRT_MAX */
4408 * Oh joy, the Linux kernel uses struct sock_fprog instead
4409 * of struct bpf_program and of course the length field is
4410 * of different size. Pointed out by Sebastian
4412 * Oh, and we also need to fix it up so that all "ret"
4413 * instructions with non-zero operands have MAXIMUM_SNAPLEN
4414 * as the operand if we're not capturing in memory-mapped
4415 * mode, and so that, if we're in cooked mode, all memory-
4416 * reference instructions use special magic offsets in
4417 * references to the link-layer header and assume that the
4418 * link-layer payload begins at 0; "fix_program()" will do
4421 switch (fix_program(handle
, &fcode
)) {
4426 * Fatal error; just quit.
4427 * (The "default" case shouldn't happen; we
4428 * return -1 for that reason.)
4434 * The program performed checks that we can't make
4435 * work in the kernel.
4437 can_filter_in_kernel
= 0;
4442 * We have a filter that'll work in the kernel.
4444 can_filter_in_kernel
= 1;
4450 * NOTE: at this point, we've set both the "len" and "filter"
4451 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
4452 * those are the only members of the "sock_fprog" structure,
4453 * so we initialize every member of that structure.
4455 * If there is anything in "fcode" that is not initialized,
4456 * it is either a field added in a later kernel, or it's
4459 * If a new field is added, this code needs to be updated
4460 * to set it correctly.
4462 * If there are no other fields, then:
4464 * if the Linux kernel looks at the padding, it's
4467 * if the Linux kernel doesn't look at the padding,
4468 * then if some tool complains that we're passing
4469 * uninitialized data to the kernel, then the tool
4470 * is buggy and needs to understand that it's just
4473 if (can_filter_in_kernel
) {
4474 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
4477 * Installation succeded - using kernel filter,
4478 * so userland filtering not needed.
4480 handlep
->filter_in_userland
= 0;
4482 else if (err
== -1) /* Non-fatal error */
4485 * Print a warning if we weren't able to install
4486 * the filter for a reason other than "this kernel
4487 * isn't configured to support socket filters.
4489 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
4491 "Warning: Kernel filter failed: %s\n",
4492 pcap_strerror(errno
));
4498 * If we're not using the kernel filter, get rid of any kernel
4499 * filter that might've been there before, e.g. because the
4500 * previous filter could work in the kernel, or because some other
4501 * code attached a filter to the socket by some means other than
4502 * calling "pcap_setfilter()". Otherwise, the kernel filter may
4503 * filter out packets that would pass the new userland filter.
4505 if (handlep
->filter_in_userland
) {
4506 if (reset_kernel_filter(handle
) == -1) {
4507 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4508 PCAP_ERRBUF_SIZE
, errno
,
4509 "can't remove kernel filter");
4510 err
= -2; /* fatal error */
4515 * Free up the copy of the filter that was made by "fix_program()".
4517 if (fcode
.filter
!= NULL
)
4525 * If we're filtering in userland, there's nothing to do;
4526 * the new filter will be used for the next packet.
4528 if (handlep
->filter_in_userland
)
4532 * We're filtering in the kernel; the packets present in
4533 * all blocks currently in the ring were already filtered
4534 * by the old filter, and so will need to be filtered in
4535 * userland by the new filter.
4537 * Get an upper bound for the number of such blocks; first,
4538 * walk the ring backward and count the free blocks.
4540 offset
= handle
->offset
;
4542 offset
= handle
->cc
- 1;
4543 for (n
=0; n
< handle
->cc
; ++n
) {
4545 offset
= handle
->cc
- 1;
4546 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
4551 * If we found free blocks, decrement the count of free
4552 * blocks by 1, just in case we lost a race with another
4553 * thread of control that was adding a packet while
4554 * we were counting and that had run the filter before
4557 * XXX - could there be more than one block added in
4560 * XXX - is there a way to avoid that race, e.g. somehow
4561 * wait for all packets that passed the old filter to
4562 * be added to the ring?
4568 * Set the count of blocks worth of packets to filter
4569 * in userland to the total number of blocks in the
4570 * ring minus the number of free blocks we found, and
4571 * turn on userland filtering. (The count of blocks
4572 * worth of packets to filter in userland is guaranteed
4573 * not to be zero - n, above, couldn't be set to a
4574 * value > handle->cc, and if it were equal to
4575 * handle->cc, it wouldn't be zero, and thus would
4576 * be decremented to handle->cc - 1.)
4578 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4579 handlep
->filter_in_userland
= 1;
4585 * Return the index of the given device name. Fill ebuf and return
4589 iface_get_id(int fd
, const char *device
, char *ebuf
)
4593 memset(&ifr
, 0, sizeof(ifr
));
4594 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4596 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4597 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4598 errno
, "SIOCGIFINDEX");
4602 return ifr
.ifr_ifindex
;
4606 * Bind the socket associated with FD to the given device.
4607 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
4610 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
4612 struct sockaddr_ll sll
;
4614 socklen_t errlen
= sizeof(err
);
4616 memset(&sll
, 0, sizeof(sll
));
4617 sll
.sll_family
= AF_PACKET
;
4618 sll
.sll_ifindex
= ifindex
< 0 ? 0 : ifindex
;
4619 sll
.sll_protocol
= protocol
;
4621 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4622 if (errno
== ENETDOWN
) {
4624 * Return a "network down" indication, so that
4625 * the application can report that rather than
4626 * saying we had a mysterious failure and
4627 * suggest that they report a problem to the
4628 * libpcap developers.
4630 return PCAP_ERROR_IFACE_NOT_UP
;
4632 if (errno
== ENODEV
)
4633 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
4636 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4641 /* Any pending errors, e.g., network is down? */
4643 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4644 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4645 errno
, "getsockopt (SO_ERROR)");
4649 if (err
== ENETDOWN
) {
4651 * Return a "network down" indication, so that
4652 * the application can report that rather than
4653 * saying we had a mysterious failure and
4654 * suggest that they report a problem to the
4655 * libpcap developers.
4657 return PCAP_ERROR_IFACE_NOT_UP
;
4658 } else if (err
> 0) {
4659 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
4667 #ifdef IW_MODE_MONITOR
4669 * Check whether the device supports the Wireless Extensions.
4670 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4671 * if the device doesn't even exist.
4674 has_wext(int sock_fd
, const char *device
, char *ebuf
)
4679 if (is_bonding_device(sock_fd
, device
))
4680 return 0; /* bonding device, so don't even try */
4682 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4683 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4684 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
4686 if (errno
== ENODEV
)
4687 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
4690 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
,
4691 "%s: SIOCGIWNAME", device
);
4696 * Per me si va ne la citta dolente,
4697 * Per me si va ne l'etterno dolore,
4699 * Lasciate ogne speranza, voi ch'intrate.
4701 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4717 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4718 * on if it's not already on.
4720 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4721 * on this device, or a PCAP_ERROR_ value if we do support them but
4722 * we weren't able to turn monitor mode on.
4725 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
4728 * XXX - at least some adapters require non-Wireless Extensions
4729 * mechanisms to turn monitor mode on.
4731 * Atheros cards might require that a separate "monitor virtual access
4732 * point" be created, with later versions of the madwifi driver.
4735 * wlanconfig ath create wlandev {if_name} wlanmode monitor -bssid
4737 * which apparently spits out a line "athN" where "athN" is the
4738 * monitor mode device. To leave monitor mode, it destroys the
4739 * monitor mode device.
4741 * Some Intel Centrino adapters might require private ioctls to get
4742 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4743 * configure a separate "rtapN" interface to capture in monitor
4744 * mode without preventing the adapter from operating normally.
4745 * (airmon-ng doesn't appear to use that, though.)
4747 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4748 * up, and if all drivers were converted to mac80211 drivers.
4750 * If interface {if_name} is a mac80211 driver, the file
4751 * /sys/class/net/{if_name}/phy80211 is a symlink to
4752 * /sys/class/ieee80211/{phydev_name}, for some {phydev_name}.
4754 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4755 * least, has a "wmaster0" device and a "wlan0" device; the
4756 * latter is the one with the IP address. Both show up in
4757 * "tcpdump -D" output. Capturing on the wmaster0 device
4758 * captures with 802.11 headers.
4760 * airmon-ng searches through /sys/class/net for devices named
4761 * monN, starting with mon0; as soon as one *doesn't* exist,
4762 * it chooses that as the monitor device name. If the "iw"
4763 * command exists, it does
4765 * iw dev {if_name} interface add {monif_name} type monitor"
4767 * where {monif_name} is the monitor device. It then (sigh) sleeps
4768 * .1 second, and then configures the device up. Otherwise, if
4769 * /sys/class/ieee80211/{phydev_name}/add_iface is a file, it writes
4770 * {mondev_name}, without a newline, to that file, and again (sigh)
4771 * sleeps .1 second, and then iwconfig's that device into monitor
4772 * mode and configures it up. Otherwise, you can't do monitor mode.
4774 * All these devices are "glued" together by having the
4775 * /sys/class/net/{device_name}/phy80211 links pointing to the same
4776 * place, so, given a wmaster, wlan, or mon device, you can
4777 * find the other devices by looking for devices with
4778 * the same phy80211 link.
4780 * To turn monitor mode off, delete the monitor interface,
4783 * iw dev {monif_name} interface del
4785 * or by sending {monif_name}, with no NL, down
4786 * /sys/class/ieee80211/{phydev_name}/remove_iface
4788 * Note: if you try to create a monitor device named "monN", and
4789 * there's already a "monN" device, it fails, as least with
4790 * the netlink interface (which is what iw uses), with a return
4791 * value of -ENFILE. (Return values are negative errnos.) We
4792 * could probably use that to find an unused device.
4794 struct pcap_linux
*handlep
= handle
->priv
;
4797 struct iw_priv_args
*priv
;
4798 monitor_type montype
;
4807 * Does this device *support* the Wireless Extensions?
4809 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4811 return err
; /* either it doesn't or the device doesn't even exist */
4813 * Start out assuming we have no private extensions to control
4816 montype
= MONITOR_WEXT
;
4820 * Try to get all the Wireless Extensions private ioctls
4821 * supported by this device.
4823 * First, get the size of the buffer we need, by supplying no
4824 * buffer and a length of 0. If the device supports private
4825 * ioctls, it should return E2BIG, with ireq.u.data.length set
4826 * to the length we need. If it doesn't support them, it should
4827 * return EOPNOTSUPP.
4829 memset(&ireq
, 0, sizeof ireq
);
4830 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4831 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4832 ireq
.u
.data
.pointer
= (void *)args
;
4833 ireq
.u
.data
.length
= 0;
4834 ireq
.u
.data
.flags
= 0;
4835 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4836 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4837 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4841 if (errno
!= EOPNOTSUPP
) {
4843 * OK, it's not as if there are no private ioctls.
4845 if (errno
!= E2BIG
) {
4849 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4850 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
4855 * OK, try to get the list of private ioctls.
4857 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4859 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4860 PCAP_ERRBUF_SIZE
, errno
, "malloc");
4863 ireq
.u
.data
.pointer
= (void *)priv
;
4864 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4865 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4866 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
4872 * Look for private ioctls to turn monitor mode on or, if
4873 * monitor mode is on, to set the header type.
4875 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4876 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4878 * Hostap driver, use this one.
4879 * Set monitor mode first.
4880 * You can set it to 0 to get DLT_IEEE80211,
4881 * 1 to get DLT_PRISM, 2 to get
4882 * DLT_IEEE80211_RADIO_AVS, and, with more
4883 * recent versions of the driver, 3 to get
4884 * DLT_IEEE80211_RADIO.
4886 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4888 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4890 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4892 montype
= MONITOR_HOSTAP
;
4896 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4898 * Prism54 driver, use this one.
4899 * Set monitor mode first.
4900 * You can set it to 2 to get DLT_IEEE80211
4901 * or 3 or get DLT_PRISM.
4903 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4905 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4907 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4909 montype
= MONITOR_PRISM54
;
4913 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4915 * RT2570 driver, use this one.
4916 * Do this after turning monitor mode on.
4917 * You can set it to 1 to get DLT_PRISM or 2
4918 * to get DLT_IEEE80211.
4920 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4922 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4924 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4926 montype
= MONITOR_RT2570
;
4930 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
4932 * RT73 driver, use this one.
4933 * Do this after turning monitor mode on.
4934 * Its argument is a *string*; you can
4935 * set it to "1" to get DLT_PRISM or "2"
4936 * to get DLT_IEEE80211.
4938 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
4940 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
4942 montype
= MONITOR_RT73
;
4946 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
4948 * One of the RTL8xxx drivers, use this one.
4949 * It can only be done after monitor mode
4950 * has been turned on. You can set it to 1
4951 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4953 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4955 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4957 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4959 montype
= MONITOR_RTL8XXX
;
4963 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
4965 * RT2500 or RT61 driver, use this one.
4966 * It has one one-byte parameter; set
4967 * u.data.length to 1 and u.data.pointer to
4968 * point to the parameter.
4969 * It doesn't itself turn monitor mode on.
4970 * You can set it to 1 to allow transmitting
4971 * in monitor mode(?) and get DLT_IEEE80211,
4972 * or set it to 0 to disallow transmitting in
4973 * monitor mode(?) and get DLT_PRISM.
4975 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4977 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
4979 montype
= MONITOR_RT2500
;
4983 if (strcmp(priv
[i
].name
, "monitor") == 0) {
4985 * Either ACX100 or hostap, use this one.
4986 * It turns monitor mode on.
4987 * If it takes two arguments, it's ACX100;
4988 * the first argument is 1 for DLT_PRISM
4989 * or 2 for DLT_IEEE80211, and the second
4990 * argument is the channel on which to
4991 * run. If it takes one argument, it's
4992 * HostAP, and the argument is 2 for
4993 * DLT_IEEE80211 and 3 for DLT_PRISM.
4995 * If we see this, we don't quit, as this
4996 * might be a version of the hostap driver
4997 * that also supports "monitor_type".
4999 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5001 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5003 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5006 montype
= MONITOR_PRISM
;
5011 montype
= MONITOR_ACX100
;
5024 * XXX - ipw3945? islism?
5030 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5031 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5032 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
5034 * We probably won't be able to set the mode, either.
5036 return PCAP_ERROR_RFMON_NOTSUP
;
5040 * Is it currently in monitor mode?
5042 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
5044 * Yes. Just leave things as they are.
5045 * We don't offer multiple link-layer types, as
5046 * changing the link-layer type out from under
5047 * somebody else capturing in monitor mode would
5048 * be considered rude.
5053 * No. We have to put the adapter into rfmon mode.
5057 * If we haven't already done so, arrange to have
5058 * "pcap_close_all()" called when we exit.
5060 if (!pcap_do_addexit(handle
)) {
5062 * "atexit()" failed; don't put the interface
5063 * in rfmon mode, just give up.
5065 return PCAP_ERROR_RFMON_NOTSUP
;
5069 * Save the old mode.
5071 handlep
->oldmode
= ireq
.u
.mode
;
5074 * Put the adapter in rfmon mode. How we do this depends
5075 * on whether we have a special private ioctl or not.
5077 if (montype
== MONITOR_PRISM
) {
5079 * We have the "monitor" private ioctl, but none of
5080 * the other private ioctls. Use this, and select
5083 * If it fails, just fall back on SIOCSIWMODE.
5085 memset(&ireq
, 0, sizeof ireq
);
5086 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5087 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5088 ireq
.u
.data
.length
= 1; /* 1 argument */
5089 args
[0] = 3; /* request Prism header */
5090 memcpy(ireq
.u
.name
, args
, sizeof (int));
5091 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
5094 * Note that we have to put the old mode back
5095 * when we close the device.
5097 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5100 * Add this to the list of pcaps to close
5103 pcap_add_to_pcaps_to_close(handle
);
5109 * Failure. Fall back on SIOCSIWMODE.
5114 * First, take the interface down if it's up; otherwise, we
5117 memset(&ifr
, 0, sizeof(ifr
));
5118 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5119 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5120 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5121 errno
, "%s: Can't get flags", device
);
5125 if (ifr
.ifr_flags
& IFF_UP
) {
5126 oldflags
= ifr
.ifr_flags
;
5127 ifr
.ifr_flags
&= ~IFF_UP
;
5128 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5129 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5130 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
5137 * Then turn monitor mode on.
5139 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5140 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5141 ireq
.u
.mode
= IW_MODE_MONITOR
;
5142 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
5144 * Scientist, you've failed.
5145 * Bring the interface back up if we shut it down.
5147 ifr
.ifr_flags
= oldflags
;
5148 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5149 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5150 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
5154 return PCAP_ERROR_RFMON_NOTSUP
;
5158 * XXX - airmon-ng does "iwconfig {if_name} key off" after setting
5159 * monitor mode and setting the channel, and then does
5164 * Now select the appropriate radio header.
5170 * We don't have any private ioctl to set the header.
5174 case MONITOR_HOSTAP
:
5176 * Try to select the radiotap header.
5178 memset(&ireq
, 0, sizeof ireq
);
5179 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5180 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5181 args
[0] = 3; /* request radiotap header */
5182 memcpy(ireq
.u
.name
, args
, sizeof (int));
5183 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5184 break; /* success */
5187 * That failed. Try to select the AVS header.
5189 memset(&ireq
, 0, sizeof ireq
);
5190 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5191 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5192 args
[0] = 2; /* request AVS header */
5193 memcpy(ireq
.u
.name
, args
, sizeof (int));
5194 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5195 break; /* success */
5198 * That failed. Try to select the Prism header.
5200 memset(&ireq
, 0, sizeof ireq
);
5201 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5202 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5203 args
[0] = 1; /* request Prism header */
5204 memcpy(ireq
.u
.name
, args
, sizeof (int));
5205 ioctl(sock_fd
, cmd
, &ireq
);
5210 * The private ioctl failed.
5214 case MONITOR_PRISM54
:
5216 * Select the Prism header.
5218 memset(&ireq
, 0, sizeof ireq
);
5219 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5220 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5221 args
[0] = 3; /* request Prism header */
5222 memcpy(ireq
.u
.name
, args
, sizeof (int));
5223 ioctl(sock_fd
, cmd
, &ireq
);
5226 case MONITOR_ACX100
:
5228 * Get the current channel.
5230 memset(&ireq
, 0, sizeof ireq
);
5231 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5232 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5233 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
5234 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5235 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWFREQ", device
);
5238 channel
= ireq
.u
.freq
.m
;
5241 * Select the Prism header, and set the channel to the
5244 memset(&ireq
, 0, sizeof ireq
);
5245 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5246 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5247 args
[0] = 1; /* request Prism header */
5248 args
[1] = channel
; /* set channel */
5249 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
5250 ioctl(sock_fd
, cmd
, &ireq
);
5253 case MONITOR_RT2500
:
5255 * Disallow transmission - that turns on the
5258 memset(&ireq
, 0, sizeof ireq
);
5259 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5260 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5261 args
[0] = 0; /* disallow transmitting */
5262 memcpy(ireq
.u
.name
, args
, sizeof (int));
5263 ioctl(sock_fd
, cmd
, &ireq
);
5266 case MONITOR_RT2570
:
5268 * Force the Prism header.
5270 memset(&ireq
, 0, sizeof ireq
);
5271 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5272 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5273 args
[0] = 1; /* request Prism header */
5274 memcpy(ireq
.u
.name
, args
, sizeof (int));
5275 ioctl(sock_fd
, cmd
, &ireq
);
5280 * Force the Prism header.
5282 memset(&ireq
, 0, sizeof ireq
);
5283 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5284 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5285 ireq
.u
.data
.length
= 1; /* 1 argument */
5286 ireq
.u
.data
.pointer
= "1";
5287 ireq
.u
.data
.flags
= 0;
5288 ioctl(sock_fd
, cmd
, &ireq
);
5291 case MONITOR_RTL8XXX
:
5293 * Force the Prism header.
5295 memset(&ireq
, 0, sizeof ireq
);
5296 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5297 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5298 args
[0] = 1; /* request Prism header */
5299 memcpy(ireq
.u
.name
, args
, sizeof (int));
5300 ioctl(sock_fd
, cmd
, &ireq
);
5305 * Now bring the interface back up if we brought it down.
5307 if (oldflags
!= 0) {
5308 ifr
.ifr_flags
= oldflags
;
5309 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5310 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5311 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
5315 * At least try to restore the old mode on the
5318 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
5320 * Scientist, you've failed.
5323 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5324 "Please adjust manually.\n",
5332 * Note that we have to put the old mode back when we
5335 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5338 * Add this to the list of pcaps to close when we exit.
5340 pcap_add_to_pcaps_to_close(handle
);
5344 #endif /* IW_MODE_MONITOR */
5347 * Try various mechanisms to enter monitor mode.
5350 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
5352 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5357 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
5359 return ret
; /* error attempting to do so */
5361 return 1; /* success */
5362 #endif /* HAVE_LIBNL */
5364 #ifdef IW_MODE_MONITOR
5365 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
5367 return ret
; /* error attempting to do so */
5369 return 1; /* success */
5370 #endif /* IW_MODE_MONITOR */
5373 * Either none of the mechanisms we know about work or none
5374 * of those mechanisms are available, so we can't do monitor
5380 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5382 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5384 static const struct {
5385 int soft_timestamping_val
;
5386 int pcap_tstamp_val
;
5387 } sof_ts_type_map
[3] = {
5388 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5389 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5390 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5392 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5395 * Set the list of time stamping types to include all types.
5398 iface_set_all_ts_types(pcap_t
*handle
)
5402 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5403 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5404 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5405 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5408 #ifdef ETHTOOL_GET_TS_INFO
5410 * Get a list of time stamping capabilities.
5413 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf
)
5417 struct ethtool_ts_info info
;
5422 * This doesn't apply to the "any" device; you can't say "turn on
5423 * hardware time stamping for all devices that exist now and arrange
5424 * that it be turned on for any device that appears in the future",
5425 * and not all devices even necessarily *support* hardware time
5426 * stamping, so don't report any time stamp types.
5428 if (strcmp(device
, "any") == 0) {
5429 handle
->tstamp_type_list
= NULL
;
5434 * Create a socket from which to fetch time stamping capabilities.
5436 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
5438 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5439 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
5443 memset(&ifr
, 0, sizeof(ifr
));
5444 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5445 memset(&info
, 0, sizeof(info
));
5446 info
.cmd
= ETHTOOL_GET_TS_INFO
;
5447 ifr
.ifr_data
= (caddr_t
)&info
;
5448 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
5449 int save_errno
= errno
;
5452 switch (save_errno
) {
5457 * OK, this OS version or driver doesn't support
5458 * asking for the time stamping types, so let's
5459 * just return all the possible types.
5461 iface_set_all_ts_types(handle
);
5466 * OK, no such device.
5467 * The user will find that out when they try to
5468 * activate the device; just return an empty
5469 * list of time stamp types.
5471 handle
->tstamp_type_list
= NULL
;
5478 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5480 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
5488 * Do we support hardware time stamping of *all* packets?
5490 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
5492 * No, so don't report any time stamp types.
5494 * XXX - some devices either don't report
5495 * HWTSTAMP_FILTER_ALL when they do support it, or
5496 * report HWTSTAMP_FILTER_ALL but map it to only
5497 * time stamping a few PTP packets. See
5498 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
5500 handle
->tstamp_type_list
= NULL
;
5505 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5506 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
5509 handle
->tstamp_type_count
= num_ts_types
;
5510 if (num_ts_types
!= 0) {
5511 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
5512 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5513 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
5514 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5519 handle
->tstamp_type_list
= NULL
;
5523 #else /* ETHTOOL_GET_TS_INFO */
5525 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf _U_
)
5528 * This doesn't apply to the "any" device; you can't say "turn on
5529 * hardware time stamping for all devices that exist now and arrange
5530 * that it be turned on for any device that appears in the future",
5531 * and not all devices even necessarily *support* hardware time
5532 * stamping, so don't report any time stamp types.
5534 if (strcmp(device
, "any") == 0) {
5535 handle
->tstamp_type_list
= NULL
;
5540 * We don't have an ioctl to use to ask what's supported,
5541 * so say we support everything.
5543 iface_set_all_ts_types(handle
);
5546 #endif /* ETHTOOL_GET_TS_INFO */
5548 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5551 * Find out if we have any form of fragmentation/reassembly offloading.
5553 * We do so using SIOCETHTOOL checking for various types of offloading;
5554 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5555 * of the types of offloading, there's nothing we can do to check, so
5556 * we just say "no, we don't".
5558 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
5559 * indications that the operation isn't supported. We do EPERM
5560 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
5561 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
5562 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
5563 * and 3) does the "is this permitted" check before doing the "is
5564 * this even supported" check, so it fails with "this is not permitted"
5565 * rather than "this is not even supported". To work around this
5566 * annoyance, we only treat EPERM as an error for the first feature,
5567 * and assume that they all do the same permission checks, so if the
5568 * first one is allowed all the others are allowed if supported.
5570 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5572 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
,
5576 struct ethtool_value eval
;
5578 memset(&ifr
, 0, sizeof(ifr
));
5579 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
5582 ifr
.ifr_data
= (caddr_t
)&eval
;
5583 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5584 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
||
5585 (errno
== EPERM
&& eperm_ok
)) {
5587 * OK, let's just return 0, which, in our
5588 * case, either means "no, what we're asking
5589 * about is not enabled" or "all the flags
5590 * are clear (i.e., nothing is enabled)".
5594 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5595 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
5596 handle
->opt
.device
, cmdname
);
5603 * XXX - it's annoying that we have to check for offloading at all, but,
5604 * given that we have to, it's still annoying that we have to check for
5605 * particular types of offloading, especially that shiny new types of
5606 * offloading may be added - and, worse, may not be checkable with
5607 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
5608 * theory, give those to you, but the actual flags being used are
5609 * opaque (defined in a non-uapi header), and there doesn't seem to
5610 * be any obvious way to ask the kernel what all the offloading flags
5611 * are - at best, you can ask for a set of strings(!) to get *names*
5612 * for various flags. (That whole mechanism appears to have been
5613 * designed for the sole purpose of letting ethtool report flags
5614 * by name and set flags by name, with the names having no semantics
5615 * ethtool understands.)
5618 iface_get_offload(pcap_t
*handle
)
5623 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO", 0);
5627 return 1; /* TCP segmentation offloading on */
5632 * XXX - will this cause large unsegmented packets to be
5633 * handed to PF_PACKET sockets on transmission? If not,
5634 * this need not be checked.
5636 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO", 0);
5640 return 1; /* generic segmentation offloading on */
5643 #ifdef ETHTOOL_GFLAGS
5644 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS", 0);
5647 if (ret
& ETH_FLAG_LRO
)
5648 return 1; /* large receive offloading on */
5653 * XXX - will this cause large reassembled packets to be
5654 * handed to PF_PACKET sockets on receipt? If not,
5655 * this need not be checked.
5657 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO", 0);
5661 return 1; /* generic (large) receive offloading on */
5666 * Do this one last, as support for it was removed in later
5667 * kernels, and it fails with EPERM on those kernels rather
5668 * than with EOPNOTSUPP (see explanation in comment for
5669 * iface_ethtool_flag_ioctl()).
5671 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO", 1);
5675 return 1; /* UDP fragmentation offloading on */
5680 #else /* SIOCETHTOOL */
5682 iface_get_offload(pcap_t
*handle _U_
)
5685 * XXX - do we need to get this information if we don't
5686 * have the ethtool ioctls? If so, how do we do that?
5690 #endif /* SIOCETHTOOL */
5692 static struct dsa_proto
{
5694 bpf_u_int32 linktype
;
5697 * None is special and indicates that the interface does not have
5698 * any tagging protocol configured, and is therefore a standard
5699 * Ethernet interface.
5701 { "none", DLT_EN10MB
},
5702 { "brcm", DLT_DSA_TAG_BRCM
},
5703 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND
},
5704 { "dsa", DLT_DSA_TAG_DSA
},
5705 { "edsa", DLT_DSA_TAG_EDSA
},
5709 iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
)
5714 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
5715 * the tag *shouldn't* have some huge long name, and making
5716 * it smaller keeps newer versions of GCC from whining that
5717 * the error message if we don't support the tag could
5718 * overflow the error message buffer.
5724 fd
= asprintf(&pathstr
, "/sys/class/net/%s/dsa/tagging", device
);
5726 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5731 fd
= open(pathstr
, O_RDONLY
);
5734 * This is not fatal, kernel >= 4.20 *might* expose this attribute
5739 r
= read(fd
, buf
, sizeof(buf
) - 1);
5741 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5749 * Buffer should be LF terminated.
5751 if (buf
[r
- 1] == '\n')
5755 for (i
= 0; i
< sizeof(dsa_protos
) / sizeof(dsa_protos
[0]); i
++) {
5756 if (strlen(dsa_protos
[i
].name
) == (size_t)r
&&
5757 strcmp(buf
, dsa_protos
[i
].name
) == 0) {
5758 handle
->linktype
= dsa_protos
[i
].linktype
;
5759 switch (dsa_protos
[i
].linktype
) {
5768 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5769 "unsupported DSA tag: %s", buf
);
5775 * Query the kernel for the MTU of the given interface.
5778 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5783 return BIGGER_THAN_ALL_MTUS
;
5785 memset(&ifr
, 0, sizeof(ifr
));
5786 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5788 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5789 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5790 errno
, "SIOCGIFMTU");
5798 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5801 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5806 memset(&ifr
, 0, sizeof(ifr
));
5807 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5809 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5810 if (errno
== ENODEV
) {
5814 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5817 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5818 errno
, "SIOCGIFHWADDR");
5822 return ifr
.ifr_hwaddr
.sa_family
;
5826 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
5828 struct pcap_linux
*handlep
= handle
->priv
;
5831 register struct bpf_insn
*p
;
5836 * Make a copy of the filter, and modify that copy if
5839 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5840 len
= handle
->fcode
.bf_len
;
5841 f
= (struct bpf_insn
*)malloc(prog_size
);
5843 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5847 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5849 fcode
->filter
= (struct sock_filter
*) f
;
5851 for (i
= 0; i
< len
; ++i
) {
5854 * What type of instruction is this?
5856 switch (BPF_CLASS(p
->code
)) {
5861 * It's a load instruction; is it loading
5864 switch (BPF_MODE(p
->code
)) {
5870 * Yes; are we in cooked mode?
5872 if (handlep
->cooked
) {
5874 * Yes, so we need to fix this
5877 if (fix_offset(handle
, p
) < 0) {
5879 * We failed to do so.
5880 * Return 0, so our caller
5881 * knows to punt to userland.
5891 return 1; /* we succeeded */
5895 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
5898 * Existing references to auxiliary data shouldn't be adjusted.
5900 * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
5901 * we use >= and cast SKF_AD_OFF to unsigned.
5903 if (p
->k
>= (bpf_u_int32
)SKF_AD_OFF
)
5905 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5907 * What's the offset?
5909 if (p
->k
>= SLL2_HDR_LEN
) {
5911 * It's within the link-layer payload; that starts
5912 * at an offset of 0, as far as the kernel packet
5913 * filter is concerned, so subtract the length of
5914 * the link-layer header.
5916 p
->k
-= SLL2_HDR_LEN
;
5917 } else if (p
->k
== 0) {
5919 * It's the protocol field; map it to the
5920 * special magic kernel offset for that field.
5922 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5923 } else if (p
->k
== 10) {
5925 * It's the packet type field; map it to the
5926 * special magic kernel offset for that field.
5928 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5929 } else if ((bpf_int32
)(p
->k
) > 0) {
5931 * It's within the header, but it's not one of
5932 * those fields; we can't do that in the kernel,
5933 * so punt to userland.
5939 * What's the offset?
5941 if (p
->k
>= SLL_HDR_LEN
) {
5943 * It's within the link-layer payload; that starts
5944 * at an offset of 0, as far as the kernel packet
5945 * filter is concerned, so subtract the length of
5946 * the link-layer header.
5948 p
->k
-= SLL_HDR_LEN
;
5949 } else if (p
->k
== 0) {
5951 * It's the packet type field; map it to the
5952 * special magic kernel offset for that field.
5954 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5955 } else if (p
->k
== 14) {
5957 * It's the protocol field; map it to the
5958 * special magic kernel offset for that field.
5960 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5961 } else if ((bpf_int32
)(p
->k
) > 0) {
5963 * It's within the header, but it's not one of
5964 * those fields; we can't do that in the kernel,
5965 * so punt to userland.
5974 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5976 int total_filter_on
= 0;
5982 * The socket filter code doesn't discard all packets queued
5983 * up on the socket when the filter is changed; this means
5984 * that packets that don't match the new filter may show up
5985 * after the new filter is put onto the socket, if those
5986 * packets haven't yet been read.
5988 * This means, for example, that if you do a tcpdump capture
5989 * with a filter, the first few packets in the capture might
5990 * be packets that wouldn't have passed the filter.
5992 * We therefore discard all packets queued up on the socket
5993 * when setting a kernel filter. (This isn't an issue for
5994 * userland filters, as the userland filtering is done after
5995 * packets are queued up.)
5997 * To flush those packets, we put the socket in read-only mode,
5998 * and read packets from the socket until there are no more to
6001 * In order to keep that from being an infinite loop - i.e.,
6002 * to keep more packets from arriving while we're draining
6003 * the queue - we put the "total filter", which is a filter
6004 * that rejects all packets, onto the socket before draining
6007 * This code deliberately ignores any errors, so that you may
6008 * get bogus packets if an error occurs, rather than having
6009 * the filtering done in userland even if it could have been
6010 * done in the kernel.
6012 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6013 &total_fcode
, sizeof(total_fcode
)) == 0) {
6017 * Note that we've put the total filter onto the socket.
6019 total_filter_on
= 1;
6022 * Save the socket's current mode, and put it in
6023 * non-blocking mode; we drain it by reading packets
6024 * until we get an error (which is normally a
6025 * "nothing more to be read" error).
6027 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6028 if (save_mode
== -1) {
6029 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6030 PCAP_ERRBUF_SIZE
, errno
,
6031 "can't get FD flags when changing filter");
6034 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
6035 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6036 PCAP_ERRBUF_SIZE
, errno
,
6037 "can't set nonblocking mode when changing filter");
6040 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
6043 if (save_errno
!= EAGAIN
) {
6047 * If we can't restore the mode or reset the
6048 * kernel filter, there's nothing we can do.
6050 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
6051 (void)reset_kernel_filter(handle
);
6052 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6053 PCAP_ERRBUF_SIZE
, save_errno
,
6054 "recv failed when changing filter");
6057 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
6058 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6059 PCAP_ERRBUF_SIZE
, errno
,
6060 "can't restore FD flags when changing filter");
6066 * Now attach the new filter.
6068 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6069 fcode
, sizeof(*fcode
));
6070 if (ret
== -1 && total_filter_on
) {
6072 * Well, we couldn't set that filter on the socket,
6073 * but we could set the total filter on the socket.
6075 * This could, for example, mean that the filter was
6076 * too big to put into the kernel, so we'll have to
6077 * filter in userland; in any case, we'll be doing
6078 * filtering in userland, so we need to remove the
6079 * total filter so we see packets.
6084 * If this fails, we're really screwed; we have the
6085 * total filter on the socket, and it won't come off.
6086 * Report it as a fatal error.
6088 if (reset_kernel_filter(handle
) == -1) {
6089 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6090 PCAP_ERRBUF_SIZE
, errno
,
6091 "can't remove kernel total filter");
6092 return -2; /* fatal error */
6101 reset_kernel_filter(pcap_t
*handle
)
6105 * setsockopt() barfs unless it get a dummy parameter.
6106 * valgrind whines unless the value is initialized,
6107 * as it has no idea that setsockopt() ignores its
6112 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6113 &dummy
, sizeof(dummy
));
6115 * Ignore ENOENT - it means "we don't have a filter", so there
6116 * was no filter to remove, and there's still no filter.
6118 * Also ignore ENONET, as a lot of kernel versions had a
6119 * typo where ENONET, rather than ENOENT, was returned.
6121 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
6127 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
6129 if (pcap_check_activated(p
))
6130 return (PCAP_ERROR_ACTIVATED
);
6131 p
->opt
.protocol
= protocol
;
6136 * Libpcap version string.
6139 pcap_lib_version(void)
6141 #if defined(HAVE_TPACKET3)
6142 return (PCAP_VERSION_STRING
" (with TPACKET_V3)");
6144 return (PCAP_VERSION_STRING
" (with TPACKET_V2)");