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
71 * Known problems with 2.0[.x] kernels:
73 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
74 * if we use PF_PACKET, we can filter out the transmitted version
75 * of the packet by using data in the "sockaddr_ll" returned by
76 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
77 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
78 * "sockaddr_pkt" which doesn't give us enough information to let
81 * - We have to set the interface's IFF_PROMISC flag ourselves, if
82 * we're to run in promiscuous mode, which means we have to turn
83 * it off ourselves when we're done; the kernel doesn't keep track
84 * of how many sockets are listening promiscuously, which means
85 * it won't get turned off automatically when no sockets are
86 * listening promiscuously. We catch "pcap_close()" and, for
87 * interfaces we put into promiscuous mode, take them out of
88 * promiscuous mode - which isn't necessarily the right thing to
89 * do, if another socket also requested promiscuous mode between
90 * the time when we opened the socket and the time when we close
93 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
94 * return the amount of data that you could have read, rather than
95 * the amount that was returned, so we can't just allocate a buffer
96 * whose size is the snapshot length and pass the snapshot length
97 * as the byte count, and also pass MSG_TRUNC, so that the return
98 * value tells us how long the packet was on the wire.
100 * This means that, if we want to get the actual size of the packet,
101 * so we can return it in the "len" field of the packet header,
102 * we have to read the entire packet, not just the part that fits
103 * within the snapshot length, and thus waste CPU time copying data
104 * from the kernel that our caller won't see.
106 * We have to get the actual size, and supply it in "len", because
107 * otherwise, the IP dissector in tcpdump, for example, will complain
108 * about "truncated-ip", as the packet will appear to have been
109 * shorter, on the wire, than the IP header said it should have been.
127 #include <sys/stat.h>
128 #include <sys/socket.h>
129 #include <sys/ioctl.h>
130 #include <sys/utsname.h>
131 #include <sys/mman.h>
132 #include <linux/if.h>
133 #include <linux/if_packet.h>
134 #include <linux/sockios.h>
135 #include <netinet/in.h>
136 #include <linux/if_ether.h>
137 #include <net/if_arp.h>
141 #include "pcap-int.h"
142 #include "pcap/sll.h"
143 #include "pcap/vlan.h"
146 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
147 * sockets rather than SOCK_PACKET sockets.
149 * To use them, we include <linux/if_packet.h> rather than
150 * <netpacket/packet.h>; we do so because
152 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
153 * later kernels and libc5, and don't provide a <netpacket/packet.h>
156 * not all versions of glibc2 have a <netpacket/packet.h> file
157 * that defines stuff needed for some of the 2.4-or-later-kernel
158 * features, so if the system has a 2.4 or later kernel, we
159 * still can't use those features.
161 * We're already including a number of other <linux/XXX.h> headers, and
162 * this code is Linux-specific (no other OS has PF_PACKET sockets as
163 * a raw packet capture mechanism), so it's not as if you gain any
164 * useful portability by using <netpacket/packet.h>
166 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
167 * isn't defined? It only defines one data structure in 2.0.x, so
168 * it shouldn't cause any problems.
171 # include <linux/if_packet.h>
174 * On at least some Linux distributions (for example, Red Hat 5.2),
175 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
176 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
177 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
178 * the PACKET_xxx stuff.
180 * So we check whether PACKET_HOST is defined, and assume that we have
181 * PF_PACKET sockets only if it is defined.
184 # define HAVE_PF_PACKET_SOCKETS
185 # ifdef PACKET_AUXDATA
186 # define HAVE_PACKET_AUXDATA
187 # endif /* PACKET_AUXDATA */
188 # endif /* PACKET_HOST */
191 /* check for memory mapped access avaibility. We assume every needed
192 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
193 * uses many ring related structs and macros */
194 # ifdef PCAP_SUPPORT_PACKET_RING
195 # ifdef TPACKET_HDRLEN
196 # define HAVE_PACKET_RING
197 # ifdef TPACKET3_HDRLEN
198 # define HAVE_TPACKET3
199 # endif /* TPACKET3_HDRLEN */
200 # ifdef TPACKET2_HDRLEN
201 # define HAVE_TPACKET2
202 # else /* TPACKET2_HDRLEN */
203 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
204 # endif /* TPACKET2_HDRLEN */
205 # endif /* TPACKET_HDRLEN */
206 # endif /* PCAP_SUPPORT_PACKET_RING */
207 #endif /* PF_PACKET */
209 #ifdef SO_ATTACH_FILTER
210 #include <linux/types.h>
211 #include <linux/filter.h>
214 #ifdef HAVE_LINUX_NET_TSTAMP_H
215 #include <linux/net_tstamp.h>
218 #ifdef HAVE_LINUX_SOCKIOS_H
219 #include <linux/sockios.h>
222 #ifdef HAVE_LINUX_IF_BONDING_H
223 #include <linux/if_bonding.h>
226 * The ioctl code to use to check whether a device is a bonding device.
228 #if defined(SIOCBONDINFOQUERY)
229 #define BOND_INFO_QUERY_IOCTL SIOCBONDINFOQUERY
230 #elif defined(BOND_INFO_QUERY_OLD)
231 #define BOND_INFO_QUERY_IOCTL BOND_INFO_QUERY_OLD
233 #endif /* HAVE_LINUX_IF_BONDING_H */
236 * Got Wireless Extensions?
238 #ifdef HAVE_LINUX_WIRELESS_H
239 #include <linux/wireless.h>
240 #endif /* HAVE_LINUX_WIRELESS_H */
246 #include <linux/nl80211.h>
248 #include <netlink/genl/genl.h>
249 #include <netlink/genl/family.h>
250 #include <netlink/genl/ctrl.h>
251 #include <netlink/msg.h>
252 #include <netlink/attr.h>
253 #endif /* HAVE_LIBNL */
256 * Got ethtool support?
258 #ifdef HAVE_LINUX_ETHTOOL_H
259 #include <linux/ethtool.h>
262 #ifndef HAVE_SOCKLEN_T
263 typedef int socklen_t;
268 * This is being compiled on a system that lacks MSG_TRUNC; define it
269 * with the value it has in the 2.2 and later kernels, so that, on
270 * those kernels, when we pass it in the flags argument to "recvfrom()"
271 * we're passing the right value and thus get the MSG_TRUNC behavior
272 * we want. (We don't get that behavior on 2.0[.x] kernels, because
273 * they didn't support MSG_TRUNC.)
275 #define MSG_TRUNC 0x20
280 * This is being compiled on a system that lacks SOL_PACKET; define it
281 * with the value it has in the 2.2 and later kernels, so that we can
282 * set promiscuous mode in the good modern way rather than the old
283 * 2.0-kernel crappy way.
285 #define SOL_PACKET 263
288 #define MAX_LINKHEADER_SIZE 256
291 * When capturing on all interfaces we use this as the buffer size.
292 * Should be bigger then all MTUs that occur in real life.
293 * 64kB should be enough for now.
295 #define BIGGER_THAN_ALL_MTUS (64*1024)
298 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
301 u_int packets_read; /* count of packets read with recvfrom() */
302 long proc_dropped; /* packets reported dropped by /proc/net/dev */
303 struct pcap_stat stat;
305 char *device; /* device name */
306 int filter_in_userland; /* must filter in userland */
307 int blocks_to_filter_in_userland;
308 int must_do_on_close; /* stuff we must do when we close */
309 int timeout; /* timeout for buffering */
310 int sock_packet; /* using Linux 2.0 compatible interface */
311 int cooked; /* using SOCK_DGRAM rather than SOCK_RAW */
312 int ifindex; /* interface index of device we're bound to */
313 int lo_ifindex; /* interface index of the loopback device */
314 bpf_u_int32 oldmode; /* mode to restore when turning monitor mode off */
315 char *mondevice; /* mac80211 monitor device we created */
316 u_char *mmapbuf; /* memory-mapped region pointer */
317 size_t mmapbuflen; /* size of region */
318 int vlan_offset; /* offset at which to insert vlan tags; if -1, don't insert */
319 u_int tp_version; /* version of tpacket_hdr for mmaped ring */
320 u_int tp_hdrlen; /* hdrlen of tpacket_hdr for mmaped ring */
321 u_char *oneshot_buffer; /* buffer for copy of packet */
322 int poll_timeout; /* timeout to use in poll() */
324 unsigned char *current_packet; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
325 int packets_left; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
330 * Stuff to do when we close.
332 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
333 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
334 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
337 * Prototypes for internal functions and methods.
339 static int get_if_flags(const char *, bpf_u_int32 *, char *);
340 static int is_wifi(int, const char *);
341 static void map_arphrd_to_dlt(pcap_t *, int, int, const char *, int);
342 static int pcap_activate_linux(pcap_t *);
343 static int activate_old(pcap_t *);
344 static int activate_new(pcap_t *);
345 static int activate_mmap(pcap_t *, int *);
346 static int pcap_can_set_rfmon_linux(pcap_t *);
347 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
348 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
349 static int pcap_inject_linux(pcap_t *, const void *, size_t);
350 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
351 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
352 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
353 static int pcap_set_datalink_linux(pcap_t *, int);
354 static void pcap_cleanup_linux(pcap_t *);
357 * This is what the header structure looks like in a 64-bit kernel;
358 * we use this, rather than struct tpacket_hdr, if we're using
359 * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
361 struct tpacket_hdr_64 {
364 unsigned int tp_snaplen;
365 unsigned short tp_mac;
366 unsigned short tp_net;
368 unsigned int tp_usec;
372 * We use this internally as the tpacket version for TPACKET_V1 in
373 * 32-bit code on a 64-bit kernel.
375 #define TPACKET_V1_64 99
378 struct tpacket_hdr *h1;
379 struct tpacket_hdr_64 *h1_64;
381 struct tpacket2_hdr *h2;
384 struct tpacket_block_desc *h3;
389 #ifdef HAVE_PACKET_RING
390 #define RING_GET_FRAME_AT(h, offset) (((union thdr **)h->buffer)[(offset)])
391 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
393 static void destroy_ring(pcap_t *handle);
394 static int create_ring(pcap_t *handle, int *status);
395 static int prepare_tpacket_socket(pcap_t *handle);
396 static void pcap_cleanup_linux_mmap(pcap_t *);
397 static int pcap_read_linux_mmap_v1(pcap_t *, int, pcap_handler , u_char *);
398 static int pcap_read_linux_mmap_v1_64(pcap_t *, int, pcap_handler , u_char *);
400 static int pcap_read_linux_mmap_v2(pcap_t *, int, pcap_handler , u_char *);
403 static int pcap_read_linux_mmap_v3(pcap_t *, int, pcap_handler , u_char *);
405 static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
406 static int pcap_setnonblock_mmap(pcap_t *p, int nonblock);
407 static int pcap_getnonblock_mmap(pcap_t *p);
408 static void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
409 const u_char *bytes);
413 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
414 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
415 * or "on VLAN 0". There is no flag set in the tp_status field to
416 * distinguish between them.
418 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
419 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
420 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
421 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
423 * With a pre-3.0 kernel, we cannot distinguish between packets with no
424 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
425 * there's nothing we can do about that.
427 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
428 * continue the behavior of earlier libpcaps, wherein we treated packets
429 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
430 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
431 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
432 * VLAN tags. This does the right thing on 3.0 and later kernels, and
433 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
435 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
436 * has that value in 3.0 and later kernels.
438 #ifdef TP_STATUS_VLAN_VALID
439 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
442 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
443 * so we testwith the value it has in the 3.0 and later kernels, so
444 * we can test it if we're running on a system that has it. (If we're
445 * running on a system that doesn't have it, it won't be set in the
446 * tp_status field, so the tests of it will always fail; that means
447 * we behave the way we did before we introduced this macro.)
449 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
452 #ifdef TP_STATUS_VLAN_TPID_VALID
453 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
455 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
459 * Wrap some ioctl calls
461 #ifdef HAVE_PF_PACKET_SOCKETS
462 static int iface_get_id(int fd, const char *device, char *ebuf);
463 #endif /* HAVE_PF_PACKET_SOCKETS */
464 static int iface_get_mtu(int fd, const char *device, char *ebuf);
465 static int iface_get_arptype(int fd, const char *device, char *ebuf);
466 #ifdef HAVE_PF_PACKET_SOCKETS
467 static int iface_bind(int fd, int ifindex, char *ebuf, int protocol);
468 #ifdef IW_MODE_MONITOR
469 static int has_wext(int sock_fd, const char *device, char *ebuf);
470 #endif /* IW_MODE_MONITOR */
471 static int enter_rfmon_mode(pcap_t *handle, int sock_fd,
473 #endif /* HAVE_PF_PACKET_SOCKETS */
474 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
475 static int iface_ethtool_get_ts_info(const char *device, pcap_t *handle,
478 #ifdef HAVE_PACKET_RING
479 static int iface_get_offload(pcap_t *handle);
481 static int iface_bind_old(int fd, const char *device, char *ebuf);
483 #ifdef SO_ATTACH_FILTER
484 static int fix_program(pcap_t *handle, struct sock_fprog *fcode,
486 static int fix_offset(pcap_t *handle, struct bpf_insn *p);
487 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
488 static int reset_kernel_filter(pcap_t *handle);
490 static struct sock_filter total_insn
491 = BPF_STMT(BPF_RET | BPF_K, 0);
492 static struct sock_fprog total_fcode
493 = { 1, &total_insn };
494 #endif /* SO_ATTACH_FILTER */
497 pcap_create_interface(const char *device, char *ebuf)
501 handle = pcap_create_common(ebuf, sizeof (struct pcap_linux));
505 handle->activate_op = pcap_activate_linux;
506 handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
508 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
510 * See what time stamp types we support.
512 if (iface_ethtool_get_ts_info(device, handle, ebuf) == -1) {
518 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
520 * We claim that we support microsecond and nanosecond time
523 * XXX - with adapter-supplied time stamps, can we choose
524 * microsecond or nanosecond time stamps on arbitrary
527 handle->tstamp_precision_count = 2;
528 handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
529 if (handle->tstamp_precision_list == NULL) {
530 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
535 handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
536 handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
537 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
544 * If interface {if} is a mac80211 driver, the file
545 * /sys/class/net/{if}/phy80211 is a symlink to
546 * /sys/class/ieee80211/{phydev}, for some {phydev}.
548 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
549 * least, has a "wmaster0" device and a "wlan0" device; the
550 * latter is the one with the IP address. Both show up in
551 * "tcpdump -D" output. Capturing on the wmaster0 device
552 * captures with 802.11 headers.
554 * airmon-ng searches through /sys/class/net for devices named
555 * monN, starting with mon0; as soon as one *doesn't* exist,
556 * it chooses that as the monitor device name. If the "iw"
557 * command exists, it does "iw dev {if} interface add {monif}
558 * type monitor", where {monif} is the monitor device. It
559 * then (sigh) sleeps .1 second, and then configures the
560 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
561 * is a file, it writes {mondev}, without a newline, to that file,
562 * and again (sigh) sleeps .1 second, and then iwconfig's that
563 * device into monitor mode and configures it up. Otherwise,
564 * you can't do monitor mode.
566 * All these devices are "glued" together by having the
567 * /sys/class/net/{device}/phy80211 links pointing to the same
568 * place, so, given a wmaster, wlan, or mon device, you can
569 * find the other devices by looking for devices with
570 * the same phy80211 link.
572 * To turn monitor mode off, delete the monitor interface,
573 * either with "iw dev {monif} interface del" or by sending
574 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
576 * Note: if you try to create a monitor device named "monN", and
577 * there's already a "monN" device, it fails, as least with
578 * the netlink interface (which is what iw uses), with a return
579 * value of -ENFILE. (Return values are negative errnos.) We
580 * could probably use that to find an unused device.
582 * Yes, you can have multiple monitor devices for a given
587 * Is this a mac80211 device? If so, fill in the physical device path and
588 * return 1; if not, return 0. On an error, fill in handle->errbuf and
592 get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
593 size_t phydev_max_pathlen)
599 * Generate the path string for the symlink to the physical device.
601 if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
602 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
603 "%s: Can't generate path name string for /sys/class/net device",
607 bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
608 if (bytes_read == -1) {
609 if (errno == ENOENT || errno == EINVAL) {
611 * Doesn't exist, or not a symlink; assume that
612 * means it's not a mac80211 device.
617 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
618 errno, "%s: Can't readlink %s", device, pathstr);
623 phydev_path[bytes_read] = '\0';
627 #ifdef HAVE_LIBNL_SOCKETS
628 #define get_nl_errmsg nl_geterror
630 /* libnl 2.x compatibility code */
632 #define nl_sock nl_handle
634 static inline struct nl_handle *
635 nl_socket_alloc(void)
637 return nl_handle_alloc();
641 nl_socket_free(struct nl_handle *h)
643 nl_handle_destroy(h);
646 #define get_nl_errmsg strerror
649 __genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
651 struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
657 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
658 #endif /* !HAVE_LIBNL_SOCKETS */
660 struct nl80211_state {
661 struct nl_sock *nl_sock;
662 struct nl_cache *nl_cache;
663 struct genl_family *nl80211;
667 nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
671 state->nl_sock = nl_socket_alloc();
672 if (!state->nl_sock) {
673 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
674 "%s: failed to allocate netlink handle", device);
678 if (genl_connect(state->nl_sock)) {
679 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
680 "%s: failed to connect to generic netlink", device);
681 goto out_handle_destroy;
684 err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
686 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
687 "%s: failed to allocate generic netlink cache: %s",
688 device, get_nl_errmsg(-err));
689 goto out_handle_destroy;
692 state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
693 if (!state->nl80211) {
694 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
695 "%s: nl80211 not found", device);
702 nl_cache_free(state->nl_cache);
704 nl_socket_free(state->nl_sock);
709 nl80211_cleanup(struct nl80211_state *state)
711 genl_family_put(state->nl80211);
712 nl_cache_free(state->nl_cache);
713 nl_socket_free(state->nl_sock);
717 del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
718 const char *device, const char *mondevice);
721 add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
722 const char *device, const char *mondevice)
724 struct pcap_linux *handlep = handle->priv;
729 ifindex = iface_get_id(sock_fd, device, handle->errbuf);
735 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
736 "%s: failed to allocate netlink msg", device);
740 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
741 0, NL80211_CMD_NEW_INTERFACE, 0);
742 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
743 NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
744 NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
746 err = nl_send_auto_complete(state->nl_sock, msg);
748 #if defined HAVE_LIBNL_NLE
749 if (err == -NLE_FAILURE) {
751 if (err == -ENFILE) {
754 * Device not available; our caller should just
755 * keep trying. (libnl 2.x maps ENFILE to
756 * NLE_FAILURE; it can also map other errors
757 * to that, but there's not much we can do
764 * Real failure, not just "that device is not
767 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
768 "%s: nl_send_auto_complete failed adding %s interface: %s",
769 device, mondevice, get_nl_errmsg(-err));
774 err = nl_wait_for_ack(state->nl_sock);
776 #if defined HAVE_LIBNL_NLE
777 if (err == -NLE_FAILURE) {
779 if (err == -ENFILE) {
782 * Device not available; our caller should just
783 * keep trying. (libnl 2.x maps ENFILE to
784 * NLE_FAILURE; it can also map other errors
785 * to that, but there's not much we can do
792 * Real failure, not just "that device is not
795 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
796 "%s: nl_wait_for_ack failed adding %s interface: %s",
797 device, mondevice, get_nl_errmsg(-err));
809 * Try to remember the monitor device.
811 handlep->mondevice = strdup(mondevice);
812 if (handlep->mondevice == NULL) {
813 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
816 * Get rid of the monitor device.
818 del_mon_if(handle, sock_fd, state, device, mondevice);
824 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
825 "%s: nl_put failed adding %s interface",
832 del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
833 const char *device, const char *mondevice)
839 ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
845 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
846 "%s: failed to allocate netlink msg", device);
850 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
851 0, NL80211_CMD_DEL_INTERFACE, 0);
852 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
854 err = nl_send_auto_complete(state->nl_sock, msg);
856 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
857 "%s: nl_send_auto_complete failed deleting %s interface: %s",
858 device, mondevice, get_nl_errmsg(-err));
862 err = nl_wait_for_ack(state->nl_sock);
864 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
865 "%s: nl_wait_for_ack failed adding %s interface: %s",
866 device, mondevice, get_nl_errmsg(-err));
878 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
879 "%s: nl_put failed deleting %s interface",
886 enter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
888 struct pcap_linux *handlep = handle->priv;
890 char phydev_path[PATH_MAX+1];
891 struct nl80211_state nlstate;
896 * Is this a mac80211 device?
898 ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
900 return ret; /* error */
902 return 0; /* no error, but not mac80211 device */
905 * XXX - is this already a monN device?
907 * Is that determined by old Wireless Extensions ioctls?
911 * OK, it's apparently a mac80211 device.
912 * Try to find an unused monN device for it.
914 ret = nl80211_init(handle, &nlstate, device);
917 for (n = 0; n < UINT_MAX; n++) {
921 char mondevice[3+10+1]; /* mon{UINT_MAX}\0 */
923 pcap_snprintf(mondevice, sizeof mondevice, "mon%u", n);
924 ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
927 * Success. We don't clean up the libnl state
928 * yet, as we'll be using it later.
934 * Hard failure. Just return ret; handle->errbuf
935 * has already been set.
937 nl80211_cleanup(&nlstate);
942 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
943 "%s: No free monN interfaces", device);
944 nl80211_cleanup(&nlstate);
951 * Sleep for .1 seconds.
954 delay.tv_nsec = 500000000;
955 nanosleep(&delay, NULL);
959 * If we haven't already done so, arrange to have
960 * "pcap_close_all()" called when we exit.
962 if (!pcap_do_addexit(handle)) {
964 * "atexit()" failed; don't put the interface
965 * in rfmon mode, just give up.
967 del_mon_if(handle, sock_fd, &nlstate, device,
969 nl80211_cleanup(&nlstate);
974 * Now configure the monitor interface up.
976 memset(&ifr, 0, sizeof(ifr));
977 pcap_strlcpy(ifr.ifr_name, handlep->mondevice, sizeof(ifr.ifr_name));
978 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
979 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
980 errno, "%s: Can't get flags for %s", device,
982 del_mon_if(handle, sock_fd, &nlstate, device,
984 nl80211_cleanup(&nlstate);
987 ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
988 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
989 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
990 errno, "%s: Can't set flags for %s", device,
992 del_mon_if(handle, sock_fd, &nlstate, device,
994 nl80211_cleanup(&nlstate);
999 * Success. Clean up the libnl state.
1001 nl80211_cleanup(&nlstate);
1004 * Note that we have to delete the monitor device when we close
1007 handlep->must_do_on_close |= MUST_DELETE_MONIF;
1010 * Add this to the list of pcaps to close when we exit.
1012 pcap_add_to_pcaps_to_close(handle);
1016 #endif /* HAVE_LIBNL */
1018 #ifdef IW_MODE_MONITOR
1020 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
1021 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
1022 * will fail with ENODEV if we try to do them on a bonding device,
1023 * making us return a "no such device" indication rather than just
1024 * saying "no Wireless Extensions".
1026 * So we check for bonding devices, if we can, before trying those
1027 * ioctls, by trying a bonding device information query ioctl to see
1028 * whether it succeeds.
1031 is_bonding_device(int fd, const char *device)
1033 #ifdef BOND_INFO_QUERY_IOCTL
1037 memset(&ifr, 0, sizeof ifr);
1038 pcap_strlcpy(ifr.ifr_name, device, sizeof ifr.ifr_name);
1039 memset(&ifb, 0, sizeof ifb);
1040 ifr.ifr_data = (caddr_t)&ifb;
1041 if (ioctl(fd, BOND_INFO_QUERY_IOCTL, &ifr) == 0)
1042 return 1; /* success, so it's a bonding device */
1043 #endif /* BOND_INFO_QUERY_IOCTL */
1045 return 0; /* no, it's not a bonding device */
1047 #endif /* IW_MODE_MONITOR */
1049 static int pcap_protocol(pcap_t *handle)
1053 protocol = handle->opt.protocol;
1055 protocol = ETH_P_ALL;
1057 return htons(protocol);
1061 pcap_can_set_rfmon_linux(pcap_t *handle)
1064 char phydev_path[PATH_MAX+1];
1067 #ifdef IW_MODE_MONITOR
1072 if (strcmp(handle->opt.device, "any") == 0) {
1074 * Monitor mode makes no sense on the "any" device.
1081 * Bleah. There doesn't seem to be a way to ask a mac80211
1082 * device, through libnl, whether it supports monitor mode;
1083 * we'll just check whether the device appears to be a
1084 * mac80211 device and, if so, assume the device supports
1087 * wmaster devices don't appear to support the Wireless
1088 * Extensions, but we can create a mon device for a
1089 * wmaster device, so we don't bother checking whether
1090 * a mac80211 device supports the Wireless Extensions.
1092 ret = get_mac80211_phydev(handle, handle->opt.device, phydev_path,
1095 return ret; /* error */
1097 return 1; /* mac80211 device */
1100 #ifdef IW_MODE_MONITOR
1102 * Bleah. There doesn't appear to be an ioctl to use to ask
1103 * whether a device supports monitor mode; we'll just do
1104 * SIOCGIWMODE and, if it succeeds, assume the device supports
1107 * Open a socket on which to attempt to get the mode.
1108 * (We assume that if we have Wireless Extensions support
1109 * we also have PF_PACKET support.)
1111 sock_fd = socket(PF_PACKET, SOCK_RAW, pcap_protocol(handle));
1112 if (sock_fd == -1) {
1113 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1118 if (is_bonding_device(sock_fd, handle->opt.device)) {
1119 /* It's a bonding device, so don't even try. */
1125 * Attempt to get the current mode.
1127 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, handle->opt.device,
1128 sizeof ireq.ifr_ifrn.ifrn_name);
1129 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
1131 * Well, we got the mode; assume we can set it.
1136 if (errno == ENODEV) {
1137 /* The device doesn't even exist. */
1138 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1139 errno, "SIOCGIWMODE failed");
1141 return PCAP_ERROR_NO_SUCH_DEVICE;
1149 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1151 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1152 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1154 * Or can we get them in binary form from netlink?
1157 linux_if_drops(const char * if_name)
1161 char *bufptr, *nameptr, *colonptr;
1162 int field_to_convert = 3;
1163 long int dropped_pkts = 0;
1165 file = fopen("/proc/net/dev", "r");
1169 while (fgets(buffer, sizeof(buffer), file) != NULL)
1171 /* search for 'bytes' -- if its in there, then
1172 that means we need to grab the fourth field. otherwise
1173 grab the third field. */
1174 if (field_to_convert != 4 && strstr(buffer, "bytes"))
1176 field_to_convert = 4;
1181 * See whether this line corresponds to this device.
1182 * The line should have zero or more leading blanks,
1183 * followed by a device name, followed by a colon,
1184 * followed by the statistics.
1187 /* Skip leading blanks */
1188 while (*bufptr == ' ')
1191 /* Look for the colon */
1192 colonptr = strchr(nameptr, ':');
1193 if (colonptr == NULL)
1196 * Not found; this could, for example, be the
1201 /* Null-terminate the interface name. */
1203 if (strcmp(if_name, nameptr) == 0)
1206 * OK, this line has the statistics for the interface.
1207 * Skip past the interface name.
1209 bufptr = colonptr + 1;
1211 /* grab the nth field from it */
1212 while (--field_to_convert && *bufptr != '\0')
1215 * This isn't the field we want.
1216 * First, skip any leading blanks before
1219 while (*bufptr == ' ')
1223 * Now skip the non-blank characters of
1226 while (*bufptr != '\0' && *bufptr != ' ')
1230 if (field_to_convert == 0)
1233 * We've found the field we want.
1234 * Skip any leading blanks before it.
1236 while (*bufptr == ' ')
1240 * Now extract the value, if we have one.
1242 if (*bufptr != '\0')
1243 dropped_pkts = strtol(bufptr, NULL, 10);
1250 return dropped_pkts;
1255 * With older kernels promiscuous mode is kind of interesting because we
1256 * have to reset the interface before exiting. The problem can't really
1257 * be solved without some daemon taking care of managing usage counts.
1258 * If we put the interface into promiscuous mode, we set a flag indicating
1259 * that we must take it out of that mode when the interface is closed,
1260 * and, when closing the interface, if that flag is set we take it out
1261 * of promiscuous mode.
1263 * Even with newer kernels, we have the same issue with rfmon mode.
1266 static void pcap_cleanup_linux( pcap_t *handle )
1268 struct pcap_linux *handlep = handle->priv;
1271 struct nl80211_state nlstate;
1273 #endif /* HAVE_LIBNL */
1274 #ifdef IW_MODE_MONITOR
1277 #endif /* IW_MODE_MONITOR */
1279 if (handlep->must_do_on_close != 0) {
1281 * There's something we have to do when closing this
1284 if (handlep->must_do_on_close & MUST_CLEAR_PROMISC) {
1286 * We put the interface into promiscuous mode;
1287 * take it out of promiscuous mode.
1289 * XXX - if somebody else wants it in promiscuous
1290 * mode, this code cannot know that, so it'll take
1291 * it out of promiscuous mode. That's not fixable
1292 * in 2.0[.x] kernels.
1294 memset(&ifr, 0, sizeof(ifr));
1295 pcap_strlcpy(ifr.ifr_name, handlep->device,
1296 sizeof(ifr.ifr_name));
1297 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1299 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1300 "Please adjust manually.\n"
1301 "Hint: This can't happen with Linux >= 2.2.0.\n",
1302 handlep->device, strerror(errno));
1304 if (ifr.ifr_flags & IFF_PROMISC) {
1306 * Promiscuous mode is currently on;
1309 ifr.ifr_flags &= ~IFF_PROMISC;
1310 if (ioctl(handle->fd, SIOCSIFFLAGS,
1313 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1314 "Please adjust manually.\n"
1315 "Hint: This can't happen with Linux >= 2.2.0.\n",
1324 if (handlep->must_do_on_close & MUST_DELETE_MONIF) {
1325 ret = nl80211_init(handle, &nlstate, handlep->device);
1327 ret = del_mon_if(handle, handle->fd, &nlstate,
1328 handlep->device, handlep->mondevice);
1329 nl80211_cleanup(&nlstate);
1333 "Can't delete monitor interface %s (%s).\n"
1334 "Please delete manually.\n",
1335 handlep->mondevice, handle->errbuf);
1338 #endif /* HAVE_LIBNL */
1340 #ifdef IW_MODE_MONITOR
1341 if (handlep->must_do_on_close & MUST_CLEAR_RFMON) {
1343 * We put the interface into rfmon mode;
1344 * take it out of rfmon mode.
1346 * XXX - if somebody else wants it in rfmon
1347 * mode, this code cannot know that, so it'll take
1348 * it out of rfmon mode.
1352 * First, take the interface down if it's up;
1353 * otherwise, we might get EBUSY.
1354 * If we get errors, just drive on and print
1355 * a warning if we can't restore the mode.
1358 memset(&ifr, 0, sizeof(ifr));
1359 pcap_strlcpy(ifr.ifr_name, handlep->device,
1360 sizeof(ifr.ifr_name));
1361 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
1362 if (ifr.ifr_flags & IFF_UP) {
1363 oldflags = ifr.ifr_flags;
1364 ifr.ifr_flags &= ~IFF_UP;
1365 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
1366 oldflags = 0; /* didn't set, don't restore */
1371 * Now restore the mode.
1373 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, handlep->device,
1374 sizeof ireq.ifr_ifrn.ifrn_name);
1375 ireq.u.mode = handlep->oldmode;
1376 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
1378 * Scientist, you've failed.
1381 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1382 "Please adjust manually.\n",
1383 handlep->device, strerror(errno));
1387 * Now bring the interface back up if we brought
1390 if (oldflags != 0) {
1391 ifr.ifr_flags = oldflags;
1392 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1394 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1395 "Please adjust manually.\n",
1396 handlep->device, strerror(errno));
1400 #endif /* IW_MODE_MONITOR */
1403 * Take this pcap out of the list of pcaps for which we
1404 * have to take the interface out of some mode.
1406 pcap_remove_from_pcaps_to_close(handle);
1409 if (handlep->mondevice != NULL) {
1410 free(handlep->mondevice);
1411 handlep->mondevice = NULL;
1413 if (handlep->device != NULL) {
1414 free(handlep->device);
1415 handlep->device = NULL;
1417 pcap_cleanup_live_common(handle);
1421 * Set the timeout to be used in poll() with memory-mapped packet capture.
1424 set_poll_timeout(struct pcap_linux *handlep)
1426 #ifdef HAVE_TPACKET3
1427 struct utsname utsname;
1428 char *version_component, *endp;
1430 int broken_tpacket_v3 = 1;
1433 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1434 * around which we have to work. Determine if we have those
1437 if (uname(&utsname) == 0) {
1439 * 3.19 is the first release with a fixed version of
1440 * TPACKET_V3. We treat anything before that as
1441 * not haveing a fixed version; that may really mean
1442 * it has *no* version.
1444 version_component = utsname.release;
1445 major = strtol(version_component, &endp, 10);
1446 if (endp != version_component && *endp == '.') {
1448 * OK, that was a valid major version.
1449 * Get the minor version.
1451 version_component = endp + 1;
1452 minor = strtol(version_component, &endp, 10);
1453 if (endp != version_component &&
1454 (*endp == '.' || *endp == '\0')) {
1456 * OK, that was a valid minor version.
1457 * Is this 3.19 or newer?
1459 if (major >= 4 || (major == 3 && minor >= 19)) {
1460 /* Yes. TPACKET_V3 works correctly. */
1461 broken_tpacket_v3 = 0;
1467 if (handlep->timeout == 0) {
1468 #ifdef HAVE_TPACKET3
1470 * XXX - due to a set of (mis)features in the TPACKET_V3
1471 * kernel code prior to the 3.19 kernel, blocking forever
1472 * with a TPACKET_V3 socket can, if few packets are
1473 * arriving and passing the socket filter, cause most
1474 * packets to be dropped. See libpcap issue #335 for the
1475 * full painful story.
1477 * The workaround is to have poll() time out very quickly,
1478 * so we grab the frames handed to us, and return them to
1481 if (handlep->tp_version == TPACKET_V3 && broken_tpacket_v3)
1482 handlep->poll_timeout = 1; /* don't block for very long */
1485 handlep->poll_timeout = -1; /* block forever */
1486 } else if (handlep->timeout > 0) {
1487 #ifdef HAVE_TPACKET3
1489 * For TPACKET_V3, the timeout is handled by the kernel,
1490 * so block forever; that way, we don't get extra timeouts.
1491 * Don't do that if we have a broken TPACKET_V3, though.
1493 if (handlep->tp_version == TPACKET_V3 && !broken_tpacket_v3)
1494 handlep->poll_timeout = -1; /* block forever, let TPACKET_V3 wake us up */
1497 handlep->poll_timeout = handlep->timeout; /* block for that amount of time */
1500 * Non-blocking mode; we call poll() to pick up error
1501 * indications, but we don't want it to wait for
1504 handlep->poll_timeout = 0;
1509 * Get a handle for a live capture from the given device. You can
1510 * pass NULL as device to get all packages (without link level
1511 * information of course). If you pass 1 as promisc the interface
1512 * will be set to promiscous mode (XXX: I think this usage should
1513 * be deprecated and functions be added to select that later allow
1514 * modification of that values -- Torsten).
1517 pcap_activate_linux(pcap_t *handle)
1519 struct pcap_linux *handlep = handle->priv;
1525 device = handle->opt.device;
1528 * Make sure the name we were handed will fit into the ioctls we
1529 * might perform on the device; if not, return a "No such device"
1530 * indication, as the Linux kernel shouldn't support creating
1531 * a device whose name won't fit into those ioctls.
1533 * "Will fit" means "will fit, complete with a null terminator",
1534 * so if the length, which does *not* include the null terminator,
1535 * is greater than *or equal to* the size of the field into which
1536 * we'll be copying it, that won't fit.
1538 if (strlen(device) >= sizeof(ifr.ifr_name)) {
1539 status = PCAP_ERROR_NO_SUCH_DEVICE;
1544 * Turn a negative snapshot value (invalid), a snapshot value of
1545 * 0 (unspecified), or a value bigger than the normal maximum
1546 * value, into the maximum allowed value.
1548 * If some application really *needs* a bigger snapshot
1549 * length, we should just increase MAXIMUM_SNAPLEN.
1551 if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
1552 handle->snapshot = MAXIMUM_SNAPLEN;
1554 handle->inject_op = pcap_inject_linux;
1555 handle->setfilter_op = pcap_setfilter_linux;
1556 handle->setdirection_op = pcap_setdirection_linux;
1557 handle->set_datalink_op = pcap_set_datalink_linux;
1558 handle->getnonblock_op = pcap_getnonblock_fd;
1559 handle->setnonblock_op = pcap_setnonblock_fd;
1560 handle->cleanup_op = pcap_cleanup_linux;
1561 handle->read_op = pcap_read_linux;
1562 handle->stats_op = pcap_stats_linux;
1565 * The "any" device is a special device which causes us not
1566 * to bind to a particular device and thus to look at all
1569 if (strcmp(device, "any") == 0) {
1570 if (handle->opt.promisc) {
1571 handle->opt.promisc = 0;
1572 /* Just a warning. */
1573 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1574 "Promiscuous mode not supported on the \"any\" device");
1575 status = PCAP_WARNING_PROMISC_NOTSUP;
1579 handlep->device = strdup(device);
1580 if (handlep->device == NULL) {
1581 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1583 status = PCAP_ERROR;
1587 /* copy timeout value */
1588 handlep->timeout = handle->opt.timeout;
1591 * If we're in promiscuous mode, then we probably want
1592 * to see when the interface drops packets too, so get an
1593 * initial count from /proc/net/dev
1595 if (handle->opt.promisc)
1596 handlep->proc_dropped = linux_if_drops(handlep->device);
1599 * Current Linux kernels use the protocol family PF_PACKET to
1600 * allow direct access to all packets on the network while
1601 * older kernels had a special socket type SOCK_PACKET to
1602 * implement this feature.
1603 * While this old implementation is kind of obsolete we need
1604 * to be compatible with older kernels for a while so we are
1605 * trying both methods with the newer method preferred.
1607 ret = activate_new(handle);
1610 * Fatal error with the new way; just fail.
1611 * ret has the error return; if it's PCAP_ERROR,
1612 * handle->errbuf has been set appropriately.
1620 * Try to use memory-mapped access.
1622 switch (activate_mmap(handle, &status)) {
1626 * We succeeded. status has been
1627 * set to the status to return,
1628 * which might be 0, or might be
1629 * a PCAP_WARNING_ value.
1631 * Set the timeout to use in poll() before
1634 set_poll_timeout(handlep);
1639 * Kernel doesn't support it - just continue
1640 * with non-memory-mapped access.
1646 * We failed to set up to use it, or the kernel
1647 * supports it, but we failed to enable it.
1648 * status has been set to the error status to
1649 * return and, if it's PCAP_ERROR, handle->errbuf
1650 * contains the error message.
1655 else if (ret == 0) {
1656 /* Non-fatal error; try old way */
1657 if ((ret = activate_old(handle)) != 1) {
1659 * Both methods to open the packet socket failed.
1660 * Tidy up and report our failure (handle->errbuf
1661 * is expected to be set by the functions above).
1669 * We set up the socket, but not with memory-mapped access.
1671 if (handle->opt.buffer_size != 0) {
1673 * Set the socket buffer size to the specified value.
1675 if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
1676 &handle->opt.buffer_size,
1677 sizeof(handle->opt.buffer_size)) == -1) {
1678 pcap_fmt_errmsg_for_errno(handle->errbuf,
1679 PCAP_ERRBUF_SIZE, errno, "SO_RCVBUF");
1680 status = PCAP_ERROR;
1685 /* Allocate the buffer */
1687 handle->buffer = malloc(handle->bufsize + handle->offset);
1688 if (!handle->buffer) {
1689 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1691 status = PCAP_ERROR;
1696 * "handle->fd" is a socket, so "select()" and "poll()"
1697 * should work on it.
1699 handle->selectable_fd = handle->fd;
1704 pcap_cleanup_linux(handle);
1709 * Read at most max_packets from the capture stream and call the callback
1710 * for each of them. Returns the number of packets handled or -1 if an
1714 pcap_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
1717 * Currently, on Linux only one packet is delivered per read,
1720 return pcap_read_packet(handle, callback, user);
1724 pcap_set_datalink_linux(pcap_t *handle, int dlt)
1726 handle->linktype = dlt;
1731 * linux_check_direction()
1733 * Do checks based on packet direction.
1736 linux_check_direction(const pcap_t *handle, const struct sockaddr_ll *sll)
1738 struct pcap_linux *handlep = handle->priv;
1740 if (sll->sll_pkttype == PACKET_OUTGOING) {
1743 * If this is from the loopback device, reject it;
1744 * we'll see the packet as an incoming packet as well,
1745 * and we don't want to see it twice.
1747 if (sll->sll_ifindex == handlep->lo_ifindex)
1751 * If this is an outgoing CAN or CAN FD frame, and
1752 * the user doesn't only want outgoing packets,
1753 * reject it; CAN devices and drivers, and the CAN
1754 * stack, always arrange to loop back transmitted
1755 * packets, so they also appear as incoming packets.
1756 * We don't want duplicate packets, and we can't
1757 * easily distinguish packets looped back by the CAN
1758 * layer than those received by the CAN layer, so we
1759 * eliminate this packet instead.
1761 if ((sll->sll_protocol == LINUX_SLL_P_CAN ||
1762 sll->sll_protocol == LINUX_SLL_P_CANFD) &&
1763 handle->direction != PCAP_D_OUT)
1767 * If the user only wants incoming packets, reject it.
1769 if (handle->direction == PCAP_D_IN)
1774 * If the user only wants outgoing packets, reject it.
1776 if (handle->direction == PCAP_D_OUT)
1783 * Read a packet from the socket calling the handler provided by
1784 * the user. Returns the number of packets received or -1 if an
1788 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
1790 struct pcap_linux *handlep = handle->priv;
1793 #ifdef HAVE_PF_PACKET_SOCKETS
1794 struct sockaddr_ll from;
1796 struct sockaddr from;
1798 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1801 struct cmsghdr *cmsg;
1803 struct cmsghdr cmsg;
1804 char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
1806 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1808 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1809 int packet_len, caplen;
1810 struct pcap_pkthdr pcap_header;
1812 struct bpf_aux_data aux_data;
1813 #ifdef HAVE_PF_PACKET_SOCKETS
1815 * If this is a cooked device, leave extra room for a
1816 * fake packet header.
1818 if (handlep->cooked) {
1819 if (handle->linktype == DLT_LINUX_SLL2)
1820 offset = SLL2_HDR_LEN;
1822 offset = SLL_HDR_LEN;
1827 * This system doesn't have PF_PACKET sockets, so it doesn't
1828 * support cooked devices.
1834 * Receive a single packet from the kernel.
1835 * We ignore EINTR, as that might just be due to a signal
1836 * being delivered - if the signal should interrupt the
1837 * loop, the signal handler should call pcap_breakloop()
1838 * to set handle->break_loop (we ignore it on other
1839 * platforms as well).
1840 * We also ignore ENETDOWN, so that we can continue to
1841 * capture traffic if the interface goes down and comes
1842 * back up again; comments in the kernel indicate that
1843 * we'll just block waiting for packets if we try to
1844 * receive from a socket that delivered ENETDOWN, and,
1845 * if we're using a memory-mapped buffer, we won't even
1846 * get notified of "network down" events.
1848 bp = (u_char *)handle->buffer + handle->offset;
1850 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1851 msg.msg_name = &from;
1852 msg.msg_namelen = sizeof(from);
1855 msg.msg_control = &cmsg_buf;
1856 msg.msg_controllen = sizeof(cmsg_buf);
1859 iov.iov_len = handle->bufsize - offset;
1860 iov.iov_base = bp + offset;
1861 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1865 * Has "pcap_breakloop()" been called?
1867 if (handle->break_loop) {
1869 * Yes - clear the flag that indicates that it has,
1870 * and return PCAP_ERROR_BREAK as an indication that
1871 * we were told to break out of the loop.
1873 handle->break_loop = 0;
1874 return PCAP_ERROR_BREAK;
1877 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1878 packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
1879 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1880 fromlen = sizeof(from);
1881 packet_len = recvfrom(
1882 handle->fd, bp + offset,
1883 handle->bufsize - offset, MSG_TRUNC,
1884 (struct sockaddr *) &from, &fromlen);
1885 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1886 } while (packet_len == -1 && errno == EINTR);
1888 /* Check if an error occured */
1890 if (packet_len == -1) {
1894 return 0; /* no packet there */
1898 * The device on which we're capturing went away.
1900 * XXX - we should really return
1901 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1902 * etc. aren't defined to return that.
1904 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1905 "The interface went down");
1909 pcap_fmt_errmsg_for_errno(handle->errbuf,
1910 PCAP_ERRBUF_SIZE, errno, "recvfrom");
1915 #ifdef HAVE_PF_PACKET_SOCKETS
1916 if (!handlep->sock_packet) {
1918 * Unfortunately, there is a window between socket() and
1919 * bind() where the kernel may queue packets from any
1920 * interface. If we're bound to a particular interface,
1921 * discard packets not from that interface.
1923 * (If socket filters are supported, we could do the
1924 * same thing we do when changing the filter; however,
1925 * that won't handle packet sockets without socket
1926 * filter support, and it's a bit more complicated.
1927 * It would save some instructions per packet, however.)
1929 if (handlep->ifindex != -1 &&
1930 from.sll_ifindex != handlep->ifindex)
1934 * Do checks based on packet direction.
1935 * We can only do this if we're using PF_PACKET; the
1936 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1937 * which lacks the relevant packet type information.
1939 if (!linux_check_direction(handle, &from))
1944 #ifdef HAVE_PF_PACKET_SOCKETS
1946 * If this is a cooked device, fill in the fake packet header.
1948 if (handlep->cooked) {
1950 * Add the length of the fake header to the length
1951 * of packet data we read.
1953 if (handle->linktype == DLT_LINUX_SLL2) {
1954 struct sll2_header *hdrp;
1956 packet_len += SLL2_HDR_LEN;
1958 hdrp = (struct sll2_header *)bp;
1959 hdrp->sll2_protocol = from.sll_protocol;
1960 hdrp->sll2_reserved_mbz = 0;
1961 hdrp->sll2_if_index = htonl(from.sll_ifindex);
1962 hdrp->sll2_hatype = htons(from.sll_hatype);
1963 hdrp->sll2_pkttype = from.sll_pkttype;
1964 hdrp->sll2_halen = from.sll_halen;
1965 memcpy(hdrp->sll2_addr, from.sll_addr,
1966 (from.sll_halen > SLL_ADDRLEN) ?
1970 struct sll_header *hdrp;
1972 packet_len += SLL_HDR_LEN;
1974 hdrp = (struct sll_header *)bp;
1975 hdrp->sll_pkttype = htons(from.sll_pkttype);
1976 hdrp->sll_hatype = htons(from.sll_hatype);
1977 hdrp->sll_halen = htons(from.sll_halen);
1978 memcpy(hdrp->sll_addr, from.sll_addr,
1979 (from.sll_halen > SLL_ADDRLEN) ?
1982 hdrp->sll_protocol = from.sll_protocol;
1987 * Start out with no VLAN information.
1989 aux_data.vlan_tag_present = 0;
1990 aux_data.vlan_tag = 0;
1991 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1992 if (handlep->vlan_offset != -1) {
1993 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1994 struct tpacket_auxdata *aux;
1996 struct vlan_tag *tag;
1998 if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
1999 cmsg->cmsg_level != SOL_PACKET ||
2000 cmsg->cmsg_type != PACKET_AUXDATA) {
2002 * This isn't a PACKET_AUXDATA auxiliary
2008 aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
2009 if (!VLAN_VALID(aux, aux)) {
2011 * There is no VLAN information in the
2017 len = (u_int)packet_len > iov.iov_len ? iov.iov_len : (u_int)packet_len;
2018 if (len < (u_int)handlep->vlan_offset)
2022 * Move everything in the header, except the
2023 * type field, down VLAN_TAG_LEN bytes, to
2024 * allow us to insert the VLAN tag between
2025 * that stuff and the type field.
2028 memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
2031 * Now insert the tag.
2033 tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
2034 tag->vlan_tpid = htons(VLAN_TPID(aux, aux));
2035 tag->vlan_tci = htons(aux->tp_vlan_tci);
2038 * Save a flag indicating that we have a VLAN tag,
2039 * and the VLAN TCI, to bpf_aux_data struct for
2040 * use by the BPF filter if we're doing the
2041 * filtering in userland.
2043 aux_data.vlan_tag_present = 1;
2044 aux_data.vlan_tag = htons(aux->tp_vlan_tci) & 0x0fff;
2047 * Add the tag to the packet lengths.
2049 packet_len += VLAN_TAG_LEN;
2052 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2053 #endif /* HAVE_PF_PACKET_SOCKETS */
2056 * XXX: According to the kernel source we should get the real
2057 * packet len if calling recvfrom with MSG_TRUNC set. It does
2058 * not seem to work here :(, but it is supported by this code
2060 * To be honest the code RELIES on that feature so this is really
2061 * broken with 2.2.x kernels.
2062 * I spend a day to figure out what's going on and I found out
2063 * that the following is happening:
2065 * The packet comes from a random interface and the packet_rcv
2066 * hook is called with a clone of the packet. That code inserts
2067 * the packet into the receive queue of the packet socket.
2068 * If a filter is attached to that socket that filter is run
2069 * first - and there lies the problem. The default filter always
2070 * cuts the packet at the snaplen:
2075 * So the packet filter cuts down the packet. The recvfrom call
2076 * says "hey, it's only 68 bytes, it fits into the buffer" with
2077 * the result that we don't get the real packet length. This
2078 * is valid at least until kernel 2.2.17pre6.
2080 * We currently handle this by making a copy of the filter
2081 * program, fixing all "ret" instructions with non-zero
2082 * operands to have an operand of MAXIMUM_SNAPLEN so that the
2083 * filter doesn't truncate the packet, and supplying that modified
2084 * filter to the kernel.
2087 caplen = packet_len;
2088 if (caplen > handle->snapshot)
2089 caplen = handle->snapshot;
2091 /* Run the packet filter if not using kernel filter */
2092 if (handlep->filter_in_userland && handle->fcode.bf_insns) {
2093 if (bpf_filter_with_aux_data(handle->fcode.bf_insns, bp,
2094 packet_len, caplen, &aux_data) == 0) {
2095 /* rejected by filter */
2100 /* Fill in our own header data */
2102 /* get timestamp for this packet */
2103 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
2104 if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
2105 if (ioctl(handle->fd, SIOCGSTAMPNS, &pcap_header.ts) == -1) {
2106 pcap_fmt_errmsg_for_errno(handle->errbuf,
2107 PCAP_ERRBUF_SIZE, errno, "SIOCGSTAMPNS");
2113 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
2114 pcap_fmt_errmsg_for_errno(handle->errbuf,
2115 PCAP_ERRBUF_SIZE, errno, "SIOCGSTAMP");
2120 pcap_header.caplen = caplen;
2121 pcap_header.len = packet_len;
2126 * Arguably, we should count them before we check the filter,
2127 * as on many other platforms "ps_recv" counts packets
2128 * handed to the filter rather than packets that passed
2129 * the filter, but if filtering is done in the kernel, we
2130 * can't get a count of packets that passed the filter,
2131 * and that would mean the meaning of "ps_recv" wouldn't
2132 * be the same on all Linux systems.
2134 * XXX - it's not the same on all systems in any case;
2135 * ideally, we should have a "get the statistics" call
2136 * that supplies more counts and indicates which of them
2137 * it supplies, so that we supply a count of packets
2138 * handed to the filter only on platforms where that
2139 * information is available.
2141 * We count them here even if we can get the packet count
2142 * from the kernel, as we can only determine at run time
2143 * whether we'll be able to get it from the kernel (if
2144 * HAVE_STRUCT_TPACKET_STATS isn't defined, we can't get it from
2145 * the kernel, but if it is defined, the library might
2146 * have been built with a 2.4 or later kernel, but we
2147 * might be running on a 2.2[.x] kernel without Alexey
2148 * Kuznetzov's turbopacket patches, and thus the kernel
2149 * might not be able to supply those statistics). We
2150 * could, I guess, try, when opening the socket, to get
2151 * the statistics, and if we can not increment the count
2152 * here, but it's not clear that always incrementing
2153 * the count is more expensive than always testing a flag
2156 * We keep the count in "handlep->packets_read", and use that
2157 * for "ps_recv" if we can't get the statistics from the kernel.
2158 * We do that because, if we *can* get the statistics from
2159 * the kernel, we use "handlep->stat.ps_recv" and
2160 * "handlep->stat.ps_drop" as running counts, as reading the
2161 * statistics from the kernel resets the kernel statistics,
2162 * and if we directly increment "handlep->stat.ps_recv" here,
2163 * that means it will count packets *twice* on systems where
2164 * we can get kernel statistics - once here, and once in
2165 * pcap_stats_linux().
2167 handlep->packets_read++;
2169 /* Call the user supplied callback function */
2170 callback(userdata, &pcap_header, bp);
2176 pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
2178 struct pcap_linux *handlep = handle->priv;
2181 #ifdef HAVE_PF_PACKET_SOCKETS
2182 if (!handlep->sock_packet) {
2183 /* PF_PACKET socket */
2184 if (handlep->ifindex == -1) {
2186 * We don't support sending on the "any" device.
2188 pcap_strlcpy(handle->errbuf,
2189 "Sending packets isn't supported on the \"any\" device",
2194 if (handlep->cooked) {
2196 * We don't support sending on cooked-mode sockets.
2198 * XXX - how do you send on a bound cooked-mode
2200 * Is a "sendto()" required there?
2202 pcap_strlcpy(handle->errbuf,
2203 "Sending packets isn't supported in cooked mode",
2210 ret = send(handle->fd, buf, size, 0);
2212 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
2220 * Get the statistics for the given packet capture handle.
2221 * Reports the number of dropped packets iff the kernel supports
2222 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2223 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2224 * patches); otherwise, that information isn't available, and we lie
2225 * and report 0 as the count of dropped packets.
2228 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
2230 struct pcap_linux *handlep = handle->priv;
2231 #ifdef HAVE_STRUCT_TPACKET_STATS
2232 #ifdef HAVE_TPACKET3
2234 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2235 * stuff at the end of a struct tpacket_stats_v3 will not
2236 * be filled in, and we don't look at it so this is OK even
2237 * for those sockets. In addition, the PF_PACKET socket
2238 * code in the kernel only uses the length parameter to
2239 * compute how much data to copy out and to indicate how
2240 * much data was copied out, so it's OK to base it on the
2241 * size of a struct tpacket_stats.
2243 * XXX - it's probably OK, in fact, to just use a
2244 * struct tpacket_stats for V3 sockets, as we don't
2245 * care about the tp_freeze_q_cnt stat.
2247 struct tpacket_stats_v3 kstats;
2248 #else /* HAVE_TPACKET3 */
2249 struct tpacket_stats kstats;
2250 #endif /* HAVE_TPACKET3 */
2251 socklen_t len = sizeof (struct tpacket_stats);
2252 #endif /* HAVE_STRUCT_TPACKET_STATS */
2254 long if_dropped = 0;
2257 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
2259 if (handle->opt.promisc)
2261 if_dropped = handlep->proc_dropped;
2262 handlep->proc_dropped = linux_if_drops(handlep->device);
2263 handlep->stat.ps_ifdrop += (handlep->proc_dropped - if_dropped);
2266 #ifdef HAVE_STRUCT_TPACKET_STATS
2268 * Try to get the packet counts from the kernel.
2270 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
2271 &kstats, &len) > -1) {
2273 * On systems where the PACKET_STATISTICS "getsockopt()"
2274 * argument is supported on PF_PACKET sockets:
2276 * "ps_recv" counts only packets that *passed* the
2277 * filter, not packets that didn't pass the filter.
2278 * This includes packets later dropped because we
2279 * ran out of buffer space.
2281 * "ps_drop" counts packets dropped because we ran
2282 * out of buffer space. It doesn't count packets
2283 * dropped by the interface driver. It counts only
2284 * packets that passed the filter.
2286 * See above for ps_ifdrop.
2288 * Both statistics include packets not yet read from
2289 * the kernel by libpcap, and thus not yet seen by
2292 * In "linux/net/packet/af_packet.c", at least in the
2293 * 2.4.9 kernel, "tp_packets" is incremented for every
2294 * packet that passes the packet filter *and* is
2295 * successfully queued on the socket; "tp_drops" is
2296 * incremented for every packet dropped because there's
2297 * not enough free space in the socket buffer.
2299 * When the statistics are returned for a PACKET_STATISTICS
2300 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2301 * so that "tp_packets" counts all packets handed to
2302 * the PF_PACKET socket, including packets dropped because
2303 * there wasn't room on the socket buffer - but not
2304 * including packets that didn't pass the filter.
2306 * In the BSD BPF, the count of received packets is
2307 * incremented for every packet handed to BPF, regardless
2308 * of whether it passed the filter.
2310 * We can't make "pcap_stats()" work the same on both
2311 * platforms, but the best approximation is to return
2312 * "tp_packets" as the count of packets and "tp_drops"
2313 * as the count of drops.
2315 * Keep a running total because each call to
2316 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2317 * resets the counters to zero.
2319 handlep->stat.ps_recv += kstats.tp_packets;
2320 handlep->stat.ps_drop += kstats.tp_drops;
2321 *stats = handlep->stat;
2327 * If the error was EOPNOTSUPP, fall through, so that
2328 * if you build the library on a system with
2329 * "struct tpacket_stats" and run it on a system
2330 * that doesn't, it works as it does if the library
2331 * is built on a system without "struct tpacket_stats".
2333 if (errno != EOPNOTSUPP) {
2334 pcap_fmt_errmsg_for_errno(handle->errbuf,
2335 PCAP_ERRBUF_SIZE, errno, "pcap_stats");
2341 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2342 * is not supported on PF_PACKET sockets:
2344 * "ps_recv" counts only packets that *passed* the filter,
2345 * not packets that didn't pass the filter. It does not
2346 * count packets dropped because we ran out of buffer
2349 * "ps_drop" is not supported.
2351 * "ps_ifdrop" is supported. It will return the number
2352 * of drops the interface reports in /proc/net/dev,
2353 * if that is available.
2355 * "ps_recv" doesn't include packets not yet read from
2356 * the kernel by libpcap.
2358 * We maintain the count of packets processed by libpcap in
2359 * "handlep->packets_read", for reasons described in the comment
2360 * at the end of pcap_read_packet(). We have no idea how many
2361 * packets were dropped by the kernel buffers -- but we know
2362 * how many the interface dropped, so we can return that.
2365 stats->ps_recv = handlep->packets_read;
2367 stats->ps_ifdrop = handlep->stat.ps_ifdrop;
2372 add_linux_if(pcap_if_list_t *devlistp, const char *ifname, int fd, char *errbuf)
2375 char name[512]; /* XXX - pick a size */
2377 struct ifreq ifrflags;
2380 * Get the interface name.
2384 while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2387 * This could be the separator between a
2388 * name and an alias number, or it could be
2389 * the separator between a name with no
2390 * alias number and the next field.
2392 * If there's a colon after digits, it
2393 * separates the name and the alias number,
2394 * otherwise it separates the name and the
2398 while (isascii(*p) && isdigit(*p))
2402 * That was the next field,
2403 * not the alias number.
2414 * Get the flags for this interface.
2416 pcap_strlcpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2417 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2418 if (errno == ENXIO || errno == ENODEV)
2419 return (0); /* device doesn't actually exist - ignore it */
2420 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2421 errno, "SIOCGIFFLAGS: %.*s",
2422 (int)sizeof(ifrflags.ifr_name),
2428 * Add an entry for this interface, with no addresses, if it's
2429 * not already in the list.
2431 if (find_or_add_if(devlistp, name, ifrflags.ifr_flags,
2432 get_if_flags, errbuf) == NULL) {
2443 * Get from "/sys/class/net" all interfaces listed there; if they're
2444 * already in the list of interfaces we have, that won't add another
2445 * instance, but if they're not, that'll add them.
2447 * We don't bother getting any addresses for them; it appears you can't
2448 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2449 * although some other types of addresses can be fetched with SIOCGIFADDR,
2450 * we don't bother with them for now.
2452 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2453 * the list of interfaces as is, and return 0, so that we can try
2454 * scanning /proc/net/dev.
2456 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2459 scan_sys_class_net(pcap_if_list_t *devlistp, char *errbuf)
2461 DIR *sys_class_net_d;
2464 char subsystem_path[PATH_MAX+1];
2468 sys_class_net_d = opendir("/sys/class/net");
2469 if (sys_class_net_d == NULL) {
2471 * Don't fail if it doesn't exist at all.
2473 if (errno == ENOENT)
2477 * Fail if we got some other error.
2479 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2480 errno, "Can't open /sys/class/net");
2485 * Create a socket from which to fetch interface information.
2487 fd = socket(PF_UNIX, SOCK_RAW, 0);
2489 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2491 (void)closedir(sys_class_net_d);
2497 ent = readdir(sys_class_net_d);
2500 * Error or EOF; if errno != 0, it's an error.
2506 * Ignore "." and "..".
2508 if (strcmp(ent->d_name, ".") == 0 ||
2509 strcmp(ent->d_name, "..") == 0)
2513 * Ignore plain files; they do not have subdirectories
2514 * and thus have no attributes.
2516 if (ent->d_type == DT_REG)
2520 * Is there an "ifindex" file under that name?
2521 * (We don't care whether it's a directory or
2522 * a symlink; older kernels have directories
2523 * for devices, newer kernels have symlinks to
2526 pcap_snprintf(subsystem_path, sizeof subsystem_path,
2527 "/sys/class/net/%s/ifindex", ent->d_name);
2528 if (lstat(subsystem_path, &statb) != 0) {
2530 * Stat failed. Either there was an error
2531 * other than ENOENT, and we don't know if
2532 * this is an interface, or it's ENOENT,
2533 * and either some part of "/sys/class/net/{if}"
2534 * disappeared, in which case it probably means
2535 * the interface disappeared, or there's no
2536 * "ifindex" file, which means it's not a
2537 * network interface.
2543 * Attempt to add the interface.
2545 if (add_linux_if(devlistp, &ent->d_name[0], fd, errbuf) == -1) {
2553 * Well, we didn't fail for any other reason; did we
2554 * fail due to an error reading the directory?
2557 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2558 errno, "Error reading /sys/class/net");
2564 (void)closedir(sys_class_net_d);
2569 * Get from "/proc/net/dev" all interfaces listed there; if they're
2570 * already in the list of interfaces we have, that won't add another
2571 * instance, but if they're not, that'll add them.
2573 * See comments from scan_sys_class_net().
2576 scan_proc_net_dev(pcap_if_list_t *devlistp, char *errbuf)
2585 proc_net_f = fopen("/proc/net/dev", "r");
2586 if (proc_net_f == NULL) {
2588 * Don't fail if it doesn't exist at all.
2590 if (errno == ENOENT)
2594 * Fail if we got some other error.
2596 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2597 errno, "Can't open /proc/net/dev");
2602 * Create a socket from which to fetch interface information.
2604 fd = socket(PF_UNIX, SOCK_RAW, 0);
2606 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2608 (void)fclose(proc_net_f);
2613 fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
2615 * Skip the first two lines - they're headers.
2623 * Skip leading white space.
2625 while (*p != '\0' && isascii(*p) && isspace(*p))
2627 if (*p == '\0' || *p == '\n')
2628 continue; /* blank line */
2631 * Attempt to add the interface.
2633 if (add_linux_if(devlistp, p, fd, errbuf) == -1) {
2641 * Well, we didn't fail for any other reason; did we
2642 * fail due to an error reading the file?
2644 if (ferror(proc_net_f)) {
2645 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2646 errno, "Error reading /proc/net/dev");
2652 (void)fclose(proc_net_f);
2657 * Description string for the "any" device.
2659 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
2662 * A SOCK_PACKET or PF_PACKET socket can be bound to any network interface.
2665 can_be_bound(const char *name _U_)
2671 * Get additional flags for a device, using SIOCGIFMEDIA.
2674 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
2678 unsigned int arptype;
2680 struct ethtool_value info;
2682 if (*flags & PCAP_IF_LOOPBACK) {
2684 * Loopback devices aren't wireless, and "connected"/
2685 * "disconnected" doesn't apply to them.
2687 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2691 sock = socket(AF_INET, SOCK_DGRAM, 0);
2693 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
2694 "Can't create socket to get ethtool information for %s",
2700 * OK, what type of network is this?
2701 * In particular, is it wired or wireless?
2703 if (is_wifi(sock, name)) {
2705 * Wi-Fi, hence wireless.
2707 *flags |= PCAP_IF_WIRELESS;
2710 * OK, what does /sys/class/net/{if}/type contain?
2711 * (We don't use that for Wi-Fi, as it'll report
2712 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
2717 if (asprintf(&pathstr, "/sys/class/net/%s/type", name) == -1) {
2718 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
2719 "%s: Can't generate path name string for /sys/class/net device",
2724 fh = fopen(pathstr, "r");
2726 if (fscanf(fh, "%u", &arptype) == 1) {
2728 * OK, we got an ARPHRD_ type; what is it?
2732 #ifdef ARPHRD_LOOPBACK
2733 case ARPHRD_LOOPBACK:
2735 * These are types to which
2736 * "connected" and "disconnected"
2737 * don't apply, so don't bother
2740 * XXX - add other types?
2749 case ARPHRD_IEEE80211:
2750 case ARPHRD_IEEE80211_PRISM:
2751 case ARPHRD_IEEE80211_RADIOTAP:
2752 #ifdef ARPHRD_IEEE802154
2753 case ARPHRD_IEEE802154:
2755 #ifdef ARPHRD_IEEE802154_MONITOR
2756 case ARPHRD_IEEE802154_MONITOR:
2758 #ifdef ARPHRD_6LOWPAN
2759 case ARPHRD_6LOWPAN:
2762 * Various wireless types.
2764 *flags |= PCAP_IF_WIRELESS;
2773 #ifdef ETHTOOL_GLINK
2774 memset(&ifr, 0, sizeof(ifr));
2775 pcap_strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
2776 info.cmd = ETHTOOL_GLINK;
2777 ifr.ifr_data = (caddr_t)&info;
2778 if (ioctl(sock, SIOCETHTOOL, &ifr) == -1) {
2779 int save_errno = errno;
2781 switch (save_errno) {
2786 * OK, this OS version or driver doesn't support
2787 * asking for this information.
2788 * XXX - distinguish between "this doesn't
2789 * support ethtool at all because it's not
2790 * that type of device" vs. "this doesn't
2791 * support ethtool even though it's that
2792 * type of device", and return "unknown".
2794 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2800 * OK, no such device.
2801 * The user will find that out when they try to
2802 * activate the device; just say "OK" and
2803 * don't set anything.
2812 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2814 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
2828 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2831 * It's disconnected.
2833 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2842 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2847 * Get the list of regular interfaces first.
2849 if (pcap_findalldevs_interfaces(devlistp, errbuf, can_be_bound,
2850 get_if_flags) == -1)
2851 return (-1); /* failure */
2854 * Read "/sys/class/net", and add to the list of interfaces all
2855 * interfaces listed there that we don't already have, because,
2856 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2857 * and even getifaddrs() won't return information about
2858 * interfaces with no addresses, so you need to read "/sys/class/net"
2859 * to get the names of the rest of the interfaces.
2861 ret = scan_sys_class_net(devlistp, errbuf);
2863 return (-1); /* failed */
2866 * No /sys/class/net; try reading /proc/net/dev instead.
2868 if (scan_proc_net_dev(devlistp, errbuf) == -1)
2873 * Add the "any" device.
2874 * As it refers to all network devices, not to any particular
2875 * network device, the notion of "connected" vs. "disconnected"
2878 if (add_dev(devlistp, "any",
2879 PCAP_IF_UP|PCAP_IF_RUNNING|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
2880 any_descr, errbuf) == NULL)
2887 * Attach the given BPF code to the packet capture device.
2890 pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
2893 struct pcap_linux *handlep;
2894 #ifdef SO_ATTACH_FILTER
2895 struct sock_fprog fcode;
2896 int can_filter_in_kernel;
2903 pcap_strlcpy(handle->errbuf, "setfilter: No filter specified",
2908 handlep = handle->priv;
2910 /* Make our private copy of the filter */
2912 if (install_bpf_program(handle, filter) < 0)
2913 /* install_bpf_program() filled in errbuf */
2917 * Run user level packet filter by default. Will be overriden if
2918 * installing a kernel filter succeeds.
2920 handlep->filter_in_userland = 1;
2922 /* Install kernel level filter if possible */
2924 #ifdef SO_ATTACH_FILTER
2926 if (handle->fcode.bf_len > USHRT_MAX) {
2928 * fcode.len is an unsigned short for current kernel.
2929 * I have yet to see BPF-Code with that much
2930 * instructions but still it is possible. So for the
2931 * sake of correctness I added this check.
2933 fprintf(stderr, "Warning: Filter too complex for kernel\n");
2935 fcode.filter = NULL;
2936 can_filter_in_kernel = 0;
2938 #endif /* USHRT_MAX */
2941 * Oh joy, the Linux kernel uses struct sock_fprog instead
2942 * of struct bpf_program and of course the length field is
2943 * of different size. Pointed out by Sebastian
2945 * Oh, and we also need to fix it up so that all "ret"
2946 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2947 * as the operand if we're not capturing in memory-mapped
2948 * mode, and so that, if we're in cooked mode, all memory-
2949 * reference instructions use special magic offsets in
2950 * references to the link-layer header and assume that the
2951 * link-layer payload begins at 0; "fix_program()" will do
2954 switch (fix_program(handle, &fcode, is_mmapped)) {
2959 * Fatal error; just quit.
2960 * (The "default" case shouldn't happen; we
2961 * return -1 for that reason.)
2967 * The program performed checks that we can't make
2968 * work in the kernel.
2970 can_filter_in_kernel = 0;
2975 * We have a filter that'll work in the kernel.
2977 can_filter_in_kernel = 1;
2983 * NOTE: at this point, we've set both the "len" and "filter"
2984 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2985 * those are the only members of the "sock_fprog" structure,
2986 * so we initialize every member of that structure.
2988 * If there is anything in "fcode" that is not initialized,
2989 * it is either a field added in a later kernel, or it's
2992 * If a new field is added, this code needs to be updated
2993 * to set it correctly.
2995 * If there are no other fields, then:
2997 * if the Linux kernel looks at the padding, it's
3000 * if the Linux kernel doesn't look at the padding,
3001 * then if some tool complains that we're passing
3002 * uninitialized data to the kernel, then the tool
3003 * is buggy and needs to understand that it's just
3006 if (can_filter_in_kernel) {
3007 if ((err = set_kernel_filter(handle, &fcode)) == 0)
3010 * Installation succeded - using kernel filter,
3011 * so userland filtering not needed.
3013 handlep->filter_in_userland = 0;
3015 else if (err == -1) /* Non-fatal error */
3018 * Print a warning if we weren't able to install
3019 * the filter for a reason other than "this kernel
3020 * isn't configured to support socket filters.
3022 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
3024 "Warning: Kernel filter failed: %s\n",
3025 pcap_strerror(errno));
3031 * If we're not using the kernel filter, get rid of any kernel
3032 * filter that might've been there before, e.g. because the
3033 * previous filter could work in the kernel, or because some other
3034 * code attached a filter to the socket by some means other than
3035 * calling "pcap_setfilter()". Otherwise, the kernel filter may
3036 * filter out packets that would pass the new userland filter.
3038 if (handlep->filter_in_userland) {
3039 if (reset_kernel_filter(handle) == -1) {
3040 pcap_fmt_errmsg_for_errno(handle->errbuf,
3041 PCAP_ERRBUF_SIZE, errno,
3042 "can't remove kernel filter");
3043 err = -2; /* fatal error */
3048 * Free up the copy of the filter that was made by "fix_program()".
3050 if (fcode.filter != NULL)
3056 #endif /* SO_ATTACH_FILTER */
3062 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
3064 return pcap_setfilter_linux_common(handle, filter, 0);
3069 * Set direction flag: Which packets do we accept on a forwarding
3070 * single device? IN, OUT or both?
3073 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
3075 #ifdef HAVE_PF_PACKET_SOCKETS
3076 struct pcap_linux *handlep = handle->priv;
3078 if (!handlep->sock_packet) {
3079 handle->direction = d;
3084 * We're not using PF_PACKET sockets, so we can't determine
3085 * the direction of the packet.
3087 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3088 "Setting direction is not supported on SOCK_PACKET sockets");
3094 #ifndef IW_MODE_MONITOR
3097 , const char *device)
3101 #ifdef IW_MODE_MONITOR
3102 char errbuf[PCAP_ERRBUF_SIZE];
3106 * See if there's a sysfs wireless directory for it.
3107 * If so, it's a wireless interface.
3109 if (asprintf(&pathstr, "/sys/class/net/%s/wireless", device) == -1) {
3111 * Just give up here.
3115 if (stat(pathstr, &statb) == 0) {
3121 #ifdef IW_MODE_MONITOR
3123 * OK, maybe it's not wireless, or maybe this kernel doesn't
3124 * support sysfs. Try the wireless extensions.
3126 if (has_wext(sock_fd, device, errbuf) == 1) {
3128 * It supports the wireless extensions, so it's a Wi-Fi
3138 * Linux uses the ARP hardware type to identify the type of an
3139 * interface. pcap uses the DLT_xxx constants for this. This
3140 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
3141 * constant, as arguments, and sets "handle->linktype" to the
3142 * appropriate DLT_XXX constant and sets "handle->offset" to
3143 * the appropriate value (to make "handle->offset" plus link-layer
3144 * header length be a multiple of 4, so that the link-layer payload
3145 * will be aligned on a 4-byte boundary when capturing packets).
3146 * (If the offset isn't set here, it'll be 0; add code as appropriate
3147 * for cases where it shouldn't be 0.)
3149 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
3150 * in cooked mode; otherwise, we can't use cooked mode, so we have
3151 * to pick some type that works in raw mode, or fail.
3153 * Sets the link type to -1 if unable to map the type.
3155 static void map_arphrd_to_dlt(pcap_t *handle, int sock_fd, int arptype,
3156 const char *device, int cooked_ok)
3158 static const char cdma_rmnet[] = "cdma_rmnet";
3164 * For various annoying reasons having to do with DHCP
3165 * software, some versions of Android give the mobile-
3166 * phone-network interface an ARPHRD_ value of
3167 * ARPHRD_ETHER, even though the packets supplied by
3168 * that interface have no link-layer header, and begin
3169 * with an IP header, so that the ARPHRD_ value should
3172 * Detect those devices by checking the device name, and
3173 * use DLT_RAW for them.
3175 if (strncmp(device, cdma_rmnet, sizeof cdma_rmnet - 1) == 0) {
3176 handle->linktype = DLT_RAW;
3181 * Is this a real Ethernet device? If so, give it a
3182 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
3183 * that an application can let you choose it, in case you're
3184 * capturing DOCSIS traffic that a Cisco Cable Modem
3185 * Termination System is putting out onto an Ethernet (it
3186 * doesn't put an Ethernet header onto the wire, it puts raw
3187 * DOCSIS frames out on the wire inside the low-level
3188 * Ethernet framing).
3190 * XXX - are there any other sorts of "fake Ethernet" that
3191 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
3192 * a Cisco CMTS won't put traffic onto it or get traffic
3193 * bridged onto it? ISDN is handled in "activate_new()",
3194 * as we fall back on cooked mode there, and we use
3195 * is_wifi() to check for 802.11 devices; are there any
3198 if (!is_wifi(sock_fd, device)) {
3200 * It's not a Wi-Fi device; offer DOCSIS.
3202 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
3204 * If that fails, just leave the list empty.
3206 if (handle->dlt_list != NULL) {
3207 handle->dlt_list[0] = DLT_EN10MB;
3208 handle->dlt_list[1] = DLT_DOCSIS;
3209 handle->dlt_count = 2;
3214 case ARPHRD_METRICOM:
3215 case ARPHRD_LOOPBACK:
3216 handle->linktype = DLT_EN10MB;
3221 handle->linktype = DLT_EN3MB;
3225 handle->linktype = DLT_AX25_KISS;
3229 handle->linktype = DLT_PRONET;
3233 handle->linktype = DLT_CHAOS;
3236 #define ARPHRD_CAN 280
3240 * Map this to DLT_LINUX_SLL; that way, CAN frames will
3241 * have ETH_P_CAN/LINUX_SLL_P_CAN as the protocol and
3242 * CAN FD frames will have ETH_P_CANFD/LINUX_SLL_P_CANFD
3243 * as the protocol, so they can be distinguished by the
3244 * protocol in the SLL header.
3246 handle->linktype = DLT_LINUX_SLL;
3249 #ifndef ARPHRD_IEEE802_TR
3250 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
3252 case ARPHRD_IEEE802_TR:
3253 case ARPHRD_IEEE802:
3254 handle->linktype = DLT_IEEE802;
3259 handle->linktype = DLT_ARCNET_LINUX;
3262 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
3263 #define ARPHRD_FDDI 774
3266 handle->linktype = DLT_FDDI;
3270 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
3271 #define ARPHRD_ATM 19
3275 * The Classical IP implementation in ATM for Linux
3276 * supports both what RFC 1483 calls "LLC Encapsulation",
3277 * in which each packet has an LLC header, possibly
3278 * with a SNAP header as well, prepended to it, and
3279 * what RFC 1483 calls "VC Based Multiplexing", in which
3280 * different virtual circuits carry different network
3281 * layer protocols, and no header is prepended to packets.
3283 * They both have an ARPHRD_ type of ARPHRD_ATM, so
3284 * you can't use the ARPHRD_ type to find out whether
3285 * captured packets will have an LLC header, and,
3286 * while there's a socket ioctl to *set* the encapsulation
3287 * type, there's no ioctl to *get* the encapsulation type.
3291 * programs that dissect Linux Classical IP frames
3292 * would have to check for an LLC header and,
3293 * depending on whether they see one or not, dissect
3294 * the frame as LLC-encapsulated or as raw IP (I
3295 * don't know whether there's any traffic other than
3296 * IP that would show up on the socket, or whether
3297 * there's any support for IPv6 in the Linux
3298 * Classical IP code);
3300 * filter expressions would have to compile into
3301 * code that checks for an LLC header and does
3304 * Both of those are a nuisance - and, at least on systems
3305 * that support PF_PACKET sockets, we don't have to put
3306 * up with those nuisances; instead, we can just capture
3307 * in cooked mode. That's what we'll do, if we can.
3308 * Otherwise, we'll just fail.
3311 handle->linktype = DLT_LINUX_SLL;
3313 handle->linktype = -1;
3316 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
3317 #define ARPHRD_IEEE80211 801
3319 case ARPHRD_IEEE80211:
3320 handle->linktype = DLT_IEEE802_11;
3323 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
3324 #define ARPHRD_IEEE80211_PRISM 802
3326 case ARPHRD_IEEE80211_PRISM:
3327 handle->linktype = DLT_PRISM_HEADER;
3330 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
3331 #define ARPHRD_IEEE80211_RADIOTAP 803
3333 case ARPHRD_IEEE80211_RADIOTAP:
3334 handle->linktype = DLT_IEEE802_11_RADIO;
3339 * Some PPP code in the kernel supplies no link-layer
3340 * header whatsoever to PF_PACKET sockets; other PPP
3341 * code supplies PPP link-layer headers ("syncppp.c");
3342 * some PPP code might supply random link-layer
3343 * headers (PPP over ISDN - there's code in Ethereal,
3344 * for example, to cope with PPP-over-ISDN captures
3345 * with which the Ethereal developers have had to cope,
3346 * heuristically trying to determine which of the
3347 * oddball link-layer headers particular packets have).
3349 * As such, we just punt, and run all PPP interfaces
3350 * in cooked mode, if we can; otherwise, we just treat
3351 * it as DLT_RAW, for now - if somebody needs to capture,
3352 * on a 2.0[.x] kernel, on PPP devices that supply a
3353 * link-layer header, they'll have to add code here to
3354 * map to the appropriate DLT_ type (possibly adding a
3355 * new DLT_ type, if necessary).
3358 handle->linktype = DLT_LINUX_SLL;
3361 * XXX - handle ISDN types here? We can't fall
3362 * back on cooked sockets, so we'd have to
3363 * figure out from the device name what type of
3364 * link-layer encapsulation it's using, and map
3365 * that to an appropriate DLT_ value, meaning
3366 * we'd map "isdnN" devices to DLT_RAW (they
3367 * supply raw IP packets with no link-layer
3368 * header) and "isdY" devices to a new DLT_I4L_IP
3369 * type that has only an Ethernet packet type as
3370 * a link-layer header.
3372 * But sometimes we seem to get random crap
3373 * in the link-layer header when capturing on
3376 handle->linktype = DLT_RAW;
3380 #ifndef ARPHRD_CISCO
3381 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3384 handle->linktype = DLT_C_HDLC;
3387 /* Not sure if this is correct for all tunnels, but it
3391 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3399 #ifndef ARPHRD_RAWHDLC
3400 #define ARPHRD_RAWHDLC 518
3402 case ARPHRD_RAWHDLC:
3404 #define ARPHRD_DLCI 15
3408 * XXX - should some of those be mapped to DLT_LINUX_SLL
3409 * instead? Should we just map all of them to DLT_LINUX_SLL?
3411 handle->linktype = DLT_RAW;
3415 #define ARPHRD_FRAD 770
3418 handle->linktype = DLT_FRELAY;
3421 case ARPHRD_LOCALTLK:
3422 handle->linktype = DLT_LTALK;
3427 * RFC 4338 defines an encapsulation for IP and ARP
3428 * packets that's compatible with the RFC 2625
3429 * encapsulation, but that uses a different ARP
3430 * hardware type and hardware addresses. That
3431 * ARP hardware type is 18; Linux doesn't define
3432 * any ARPHRD_ value as 18, but if it ever officially
3433 * supports RFC 4338-style IP-over-FC, it should define
3436 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3437 * that this will encourage its use in the future,
3438 * should Linux ever officially support RFC 4338-style
3441 handle->linktype = DLT_IP_OVER_FC;
3445 #define ARPHRD_FCPP 784
3449 #define ARPHRD_FCAL 785
3453 #define ARPHRD_FCPL 786
3456 #ifndef ARPHRD_FCFABRIC
3457 #define ARPHRD_FCFABRIC 787
3459 case ARPHRD_FCFABRIC:
3461 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3464 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3466 * and one was assigned.
3468 * In a later private discussion (spun off from a message
3469 * on the ethereal-users list) on how to get that DLT_
3470 * value in libpcap on Linux, I ended up deciding that
3471 * the best thing to do would be to have him tweak the
3472 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3473 * type, and map all those types to DLT_IP_OVER_FC:
3475 * I've checked into the libpcap and tcpdump CVS tree
3476 * support for DLT_IP_OVER_FC. In order to use that,
3477 * you'd have to modify your modified driver to return
3478 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3479 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3480 * example (the exact value doesn't matter, it can be
3481 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3484 * 11 years later, Christian Svensson wanted to map
3485 * various ARPHRD_ values to DLT_FC_2 and
3486 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3489 * https://github.com/mcr/libpcap/pull/29
3491 * There doesn't seem to be any network drivers that uses
3492 * any of the ARPHRD_FC* values for IP-over-FC, and
3493 * it's not exactly clear what the "Dummy types for non
3494 * ARP hardware" are supposed to mean (link-layer
3495 * header type? Physical network type?), so it's
3496 * not exactly clear why the ARPHRD_FC* types exist
3497 * in the first place.
3499 * For now, we map them to DLT_FC_2, and provide an
3500 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3501 * DLT_IP_OVER_FC just in case there's some old
3502 * driver out there that uses one of those types for
3503 * IP-over-FC on which somebody wants to capture
3506 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 3);
3508 * If that fails, just leave the list empty.
3510 if (handle->dlt_list != NULL) {
3511 handle->dlt_list[0] = DLT_FC_2;
3512 handle->dlt_list[1] = DLT_FC_2_WITH_FRAME_DELIMS;
3513 handle->dlt_list[2] = DLT_IP_OVER_FC;
3514 handle->dlt_count = 3;
3516 handle->linktype = DLT_FC_2;
3520 #define ARPHRD_IRDA 783
3523 /* Don't expect IP packet out of this interfaces... */
3524 handle->linktype = DLT_LINUX_IRDA;
3525 /* We need to save packet direction for IrDA decoding,
3526 * so let's use "Linux-cooked" mode. Jean II
3528 * XXX - this is handled in activate_new(). */
3529 /* handlep->cooked = 1; */
3532 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3533 * is needed, please report it to <daniele@orlandi.com> */
3535 #define ARPHRD_LAPD 8445
3538 /* Don't expect IP packet out of this interfaces... */
3539 handle->linktype = DLT_LINUX_LAPD;
3543 #define ARPHRD_NONE 0xFFFE
3547 * No link-layer header; packets are just IP
3548 * packets, so use DLT_RAW.
3550 handle->linktype = DLT_RAW;
3553 #ifndef ARPHRD_IEEE802154
3554 #define ARPHRD_IEEE802154 804
3556 case ARPHRD_IEEE802154:
3557 handle->linktype = DLT_IEEE802_15_4_NOFCS;
3560 #ifndef ARPHRD_NETLINK
3561 #define ARPHRD_NETLINK 824
3563 case ARPHRD_NETLINK:
3564 handle->linktype = DLT_NETLINK;
3566 * We need to use cooked mode, so that in sll_protocol we
3567 * pick up the netlink protocol type such as NETLINK_ROUTE,
3568 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3570 * XXX - this is handled in activate_new().
3572 /* handlep->cooked = 1; */
3575 #ifndef ARPHRD_VSOCKMON
3576 #define ARPHRD_VSOCKMON 826
3578 case ARPHRD_VSOCKMON:
3579 handle->linktype = DLT_VSOCK;
3583 handle->linktype = -1;
3588 /* ===== Functions to interface to the newer kernels ================== */
3590 #ifdef PACKET_RESERVE
3592 set_dlt_list_cooked(pcap_t *handle, int sock_fd)
3595 unsigned int tp_reserve;
3598 * If we can't do PACKET_RESERVE, we can't reserve extra space
3599 * for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3601 len = sizeof(tp_reserve);
3602 if (getsockopt(sock_fd, SOL_PACKET, PACKET_RESERVE, &tp_reserve,
3605 * Yes, we can do DLL_LINUX_SLL2.
3607 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
3609 * If that fails, just leave the list empty.
3611 if (handle->dlt_list != NULL) {
3612 handle->dlt_list[0] = DLT_LINUX_SLL;
3613 handle->dlt_list[1] = DLT_LINUX_SLL2;
3614 handle->dlt_count = 2;
3620 * The build environment doesn't define PACKET_RESERVE, so we can't reserve
3621 * extra space for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3624 set_dlt_list_cooked(pcap_t *handle _U_, int sock_fd _U_)
3630 * Try to open a packet socket using the new kernel PF_PACKET interface.
3631 * Returns 1 on success, 0 on an error that means the new interface isn't
3632 * present (so the old SOCK_PACKET interface should be tried), and a
3633 * PCAP_ERROR_ value on an error that means that the old mechanism won't
3634 * work either (so it shouldn't be tried).
3637 activate_new(pcap_t *handle)
3639 #ifdef HAVE_PF_PACKET_SOCKETS
3640 struct pcap_linux *handlep = handle->priv;
3641 const char *device = handle->opt.device;
3642 int is_any_device = (strcmp(device, "any") == 0);
3643 int protocol = pcap_protocol(handle);
3644 int sock_fd = -1, arptype, ret;
3645 #ifdef HAVE_PACKET_AUXDATA
3649 struct packet_mreq mr;
3650 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3652 socklen_t len = sizeof(bpf_extensions);
3656 * Open a socket with protocol family packet. If the
3657 * "any" device was specified, we open a SOCK_DGRAM
3658 * socket for the cooked interface, otherwise we first
3659 * try a SOCK_RAW socket for the raw interface.
3661 sock_fd = is_any_device ?
3662 socket(PF_PACKET, SOCK_DGRAM, protocol) :
3663 socket(PF_PACKET, SOCK_RAW, protocol);
3665 if (sock_fd == -1) {
3666 if (errno == EINVAL || errno == EAFNOSUPPORT) {
3668 * We don't support PF_PACKET/SOCK_whatever
3669 * sockets; try the old mechanism.
3673 if (errno == EPERM || errno == EACCES) {
3675 * You don't have permission to open the
3678 ret = PCAP_ERROR_PERM_DENIED;
3685 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
3690 /* It seems the kernel supports the new interface. */
3691 handlep->sock_packet = 0;
3694 * Get the interface index of the loopback device.
3695 * If the attempt fails, don't fail, just set the
3696 * "handlep->lo_ifindex" to -1.
3698 * XXX - can there be more than one device that loops
3699 * packets back, i.e. devices other than "lo"? If so,
3700 * we'd need to find them all, and have an array of
3701 * indices for them, and check all of them in
3702 * "pcap_read_packet()".
3704 handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
3707 * Default value for offset to align link-layer payload
3708 * on a 4-byte boundary.
3713 * What kind of frames do we have to deal with? Fall back
3714 * to cooked mode if we have an unknown interface type
3715 * or a type we know doesn't work well in raw mode.
3717 if (!is_any_device) {
3718 /* Assume for now we don't need cooked mode. */
3719 handlep->cooked = 0;
3721 if (handle->opt.rfmon) {
3723 * We were asked to turn on monitor mode.
3724 * Do so before we get the link-layer type,
3725 * because entering monitor mode could change
3726 * the link-layer type.
3728 err = enter_rfmon_mode(handle, sock_fd, device);
3736 * Nothing worked for turning monitor mode
3740 return PCAP_ERROR_RFMON_NOTSUP;
3744 * Either monitor mode has been turned on for
3745 * the device, or we've been given a different
3746 * device to open for monitor mode. If we've
3747 * been given a different device, use it.
3749 if (handlep->mondevice != NULL)
3750 device = handlep->mondevice;
3752 arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
3757 map_arphrd_to_dlt(handle, sock_fd, arptype, device, 1);
3758 if (handle->linktype == -1 ||
3759 handle->linktype == DLT_LINUX_SLL ||
3760 handle->linktype == DLT_LINUX_IRDA ||
3761 handle->linktype == DLT_LINUX_LAPD ||
3762 handle->linktype == DLT_NETLINK ||
3763 (handle->linktype == DLT_EN10MB &&
3764 (strncmp("isdn", device, 4) == 0 ||
3765 strncmp("isdY", device, 4) == 0))) {
3767 * Unknown interface type (-1), or a
3768 * device we explicitly chose to run
3769 * in cooked mode (e.g., PPP devices),
3770 * or an ISDN device (whose link-layer
3771 * type we can only determine by using
3772 * APIs that may be different on different
3773 * kernels) - reopen in cooked mode.
3775 if (close(sock_fd) == -1) {
3776 pcap_fmt_errmsg_for_errno(handle->errbuf,
3777 PCAP_ERRBUF_SIZE, errno, "close");
3780 sock_fd = socket(PF_PACKET, SOCK_DGRAM, protocol);
3781 if (sock_fd == -1) {
3782 if (errno == EPERM || errno == EACCES) {
3784 * You don't have permission to
3787 ret = PCAP_ERROR_PERM_DENIED;
3794 pcap_fmt_errmsg_for_errno(handle->errbuf,
3795 PCAP_ERRBUF_SIZE, errno, "socket");
3798 handlep->cooked = 1;
3801 * Get rid of any link-layer type list
3802 * we allocated - this only supports cooked
3805 if (handle->dlt_list != NULL) {
3806 free(handle->dlt_list);
3807 handle->dlt_list = NULL;
3808 handle->dlt_count = 0;
3809 set_dlt_list_cooked(handle, sock_fd);
3812 if (handle->linktype == -1) {
3814 * Warn that we're falling back on
3815 * cooked mode; we may want to
3816 * update "map_arphrd_to_dlt()"
3817 * to handle the new type.
3819 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3821 "supported by libpcap - "
3822 "falling back to cooked "
3828 * IrDA capture is not a real "cooked" capture,
3829 * it's IrLAP frames, not IP packets. The
3830 * same applies to LAPD capture.
3832 if (handle->linktype != DLT_LINUX_IRDA &&
3833 handle->linktype != DLT_LINUX_LAPD &&
3834 handle->linktype != DLT_NETLINK)
3835 handle->linktype = DLT_LINUX_SLL;
3838 handlep->ifindex = iface_get_id(sock_fd, device,
3840 if (handlep->ifindex == -1) {
3845 if ((err = iface_bind(sock_fd, handlep->ifindex,
3846 handle->errbuf, protocol)) != 1) {
3851 return 0; /* try old mechanism */
3857 if (handle->opt.rfmon) {
3859 * It doesn't support monitor mode.
3862 return PCAP_ERROR_RFMON_NOTSUP;
3866 * It uses cooked mode.
3868 handlep->cooked = 1;
3869 handle->linktype = DLT_LINUX_SLL;
3870 handle->dlt_list = NULL;
3871 handle->dlt_count = 0;
3872 set_dlt_list_cooked(handle, sock_fd);
3875 * We're not bound to a device.
3876 * For now, we're using this as an indication
3877 * that we can't transmit; stop doing that only
3878 * if we figure out how to transmit in cooked
3881 handlep->ifindex = -1;
3885 * Select promiscuous mode on if "promisc" is set.
3887 * Do not turn allmulti mode on if we don't select
3888 * promiscuous mode - on some devices (e.g., Orinoco
3889 * wireless interfaces), allmulti mode isn't supported
3890 * and the driver implements it by turning promiscuous
3891 * mode on, and that screws up the operation of the
3892 * card as a normal networking interface, and on no
3893 * other platform I know of does starting a non-
3894 * promiscuous capture affect which multicast packets
3895 * are received by the interface.
3899 * Hmm, how can we set promiscuous mode on all interfaces?
3900 * I am not sure if that is possible at all. For now, we
3901 * silently ignore attempts to turn promiscuous mode on
3902 * for the "any" device (so you don't have to explicitly
3903 * disable it in programs such as tcpdump).
3906 if (!is_any_device && handle->opt.promisc) {
3907 memset(&mr, 0, sizeof(mr));
3908 mr.mr_ifindex = handlep->ifindex;
3909 mr.mr_type = PACKET_MR_PROMISC;
3910 if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
3911 &mr, sizeof(mr)) == -1) {
3912 pcap_fmt_errmsg_for_errno(handle->errbuf,
3913 PCAP_ERRBUF_SIZE, errno, "setsockopt (PACKET_ADD_MEMBERSHIP)");
3919 /* Enable auxillary data if supported and reserve room for
3920 * reconstructing VLAN headers. */
3921 #ifdef HAVE_PACKET_AUXDATA
3923 if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
3924 sizeof(val)) == -1 && errno != ENOPROTOOPT) {
3925 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
3926 errno, "setsockopt (PACKET_AUXDATA)");
3930 handle->offset += VLAN_TAG_LEN;
3931 #endif /* HAVE_PACKET_AUXDATA */
3934 * This is a 2.2[.x] or later kernel (we know that
3935 * because we're not using a SOCK_PACKET socket -
3936 * PF_PACKET is supported only in 2.2 and later
3939 * We can safely pass "recvfrom()" a byte count
3940 * based on the snapshot length.
3942 * If we're in cooked mode, make the snapshot length
3943 * large enough to hold a "cooked mode" header plus
3944 * 1 byte of packet data (so we don't pass a byte
3945 * count of 0 to "recvfrom()").
3946 * XXX - we don't know whether this will be DLT_LINUX_SLL
3947 * or DLT_LINUX_SLL2, so make sure it's big enough for
3948 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
3949 * that small is silly anyway.
3951 if (handlep->cooked) {
3952 if (handle->snapshot < SLL2_HDR_LEN + 1)
3953 handle->snapshot = SLL2_HDR_LEN + 1;
3955 handle->bufsize = handle->snapshot;
3958 * Set the offset at which to insert VLAN tags.
3959 * That should be the offset of the type field.
3961 switch (handle->linktype) {
3965 * The type field is after the destination and source
3968 handlep->vlan_offset = 2 * ETH_ALEN;
3973 * The type field is in the last 2 bytes of the
3974 * DLT_LINUX_SLL header.
3976 handlep->vlan_offset = SLL_HDR_LEN - 2;
3980 handlep->vlan_offset = -1; /* unknown */
3984 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3985 if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
3986 int nsec_tstamps = 1;
3988 if (setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)) < 0) {
3989 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "setsockopt: unable to set SO_TIMESTAMPNS");
3994 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3997 * We've succeeded. Save the socket FD in the pcap structure.
3999 handle->fd = sock_fd;
4001 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
4003 * Can we generate special code for VLAN checks?
4004 * (XXX - what if we need the special code but it's not supported
4005 * by the OS? Is that possible?)
4007 if (getsockopt(sock_fd, SOL_SOCKET, SO_BPF_EXTENSIONS,
4008 &bpf_extensions, &len) == 0) {
4009 if (bpf_extensions >= SKF_AD_VLAN_TAG_PRESENT) {
4011 * Yes, we can. Request that we do so.
4013 handle->bpf_codegen_flags |= BPF_SPECIAL_VLAN_HANDLING;
4016 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
4019 #else /* HAVE_PF_PACKET_SOCKETS */
4021 "New packet capturing interface not supported by build "
4022 "environment", PCAP_ERRBUF_SIZE);
4024 #endif /* HAVE_PF_PACKET_SOCKETS */
4027 #ifdef HAVE_PACKET_RING
4029 * Attempt to activate with memory-mapped access.
4031 * On success, returns 1, and sets *status to 0 if there are no warnings
4032 * or to a PCAP_WARNING_ code if there is a warning.
4034 * On failure due to lack of support for memory-mapped capture, returns
4037 * On error, returns -1, and sets *status to the appropriate error code;
4038 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4041 activate_mmap(pcap_t *handle, int *status)
4043 struct pcap_linux *handlep = handle->priv;
4047 * Attempt to allocate a buffer to hold the contents of one
4048 * packet, for use by the oneshot callback.
4050 handlep->oneshot_buffer = malloc(handle->snapshot);
4051 if (handlep->oneshot_buffer == NULL) {
4052 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4053 errno, "can't allocate oneshot buffer");
4054 *status = PCAP_ERROR;
4058 if (handle->opt.buffer_size == 0) {
4059 /* by default request 2M for the ring buffer */
4060 handle->opt.buffer_size = 2*1024*1024;
4062 ret = prepare_tpacket_socket(handle);
4064 free(handlep->oneshot_buffer);
4065 *status = PCAP_ERROR;
4068 ret = create_ring(handle, status);
4071 * We don't support memory-mapped capture; our caller
4072 * will fall back on reading from the socket.
4074 free(handlep->oneshot_buffer);
4079 * Error attempting to enable memory-mapped capture;
4080 * fail. create_ring() has set *status.
4082 free(handlep->oneshot_buffer);
4087 * Success. *status has been set either to 0 if there are no
4088 * warnings or to a PCAP_WARNING_ value if there is a warning.
4090 * Override some defaults and inherit the other fields from
4092 * handle->offset is used to get the current position into the rx ring.
4093 * handle->cc is used to store the ring size.
4096 switch (handlep->tp_version) {
4098 handle->read_op = pcap_read_linux_mmap_v1;
4101 handle->read_op = pcap_read_linux_mmap_v1_64;
4103 #ifdef HAVE_TPACKET2
4105 handle->read_op = pcap_read_linux_mmap_v2;
4108 #ifdef HAVE_TPACKET3
4110 handle->read_op = pcap_read_linux_mmap_v3;
4114 handle->cleanup_op = pcap_cleanup_linux_mmap;
4115 handle->setfilter_op = pcap_setfilter_linux_mmap;
4116 handle->setnonblock_op = pcap_setnonblock_mmap;
4117 handle->getnonblock_op = pcap_getnonblock_mmap;
4118 handle->oneshot_callback = pcap_oneshot_mmap;
4119 handle->selectable_fd = handle->fd;
4122 #else /* HAVE_PACKET_RING */
4124 activate_mmap(pcap_t *handle _U_, int *status _U_)
4128 #endif /* HAVE_PACKET_RING */
4130 #ifdef HAVE_PACKET_RING
4132 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4134 * Attempt to set the socket to the specified version of the memory-mapped
4137 * Return 0 if we succeed; return 1 if we fail because that version isn't
4138 * supported; return -1 on any other error, and set handle->errbuf.
4141 init_tpacket(pcap_t *handle, int version, const char *version_str)
4143 struct pcap_linux *handlep = handle->priv;
4145 socklen_t len = sizeof(val);
4148 * Probe whether kernel supports the specified TPACKET version;
4149 * this also gets the length of the header for that version.
4151 * This socket option was introduced in 2.6.27, which was
4152 * also the first release with TPACKET_V2 support.
4154 if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
4155 if (errno == ENOPROTOOPT || errno == EINVAL) {
4157 * ENOPROTOOPT means the kernel is too old to
4158 * support PACKET_HDRLEN at all, which means
4159 * it either doesn't support TPACKET at all
4160 * or supports only TPACKET_V1.
4165 /* Failed to even find out; this is a fatal error. */
4166 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4167 errno, "can't get %s header len on packet socket",
4171 handlep->tp_hdrlen = val;
4174 if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
4176 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4177 errno, "can't activate %s on packet socket", version_str);
4180 handlep->tp_version = version;
4183 * Reserve space for VLAN tag reconstruction.
4184 * This option was also introduced in 2.6.27.
4187 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
4189 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4190 errno, "can't set up reserve on packet socket");
4196 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
4199 * If the instruction set for which we're compiling has both 32-bit
4200 * and 64-bit versions, and Linux support for the 64-bit version
4201 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
4202 * you get from uname() for the 64-bit version. Otherwise, leave
4203 * it undefined. (This includes ARM, which has a 64-bit version,
4204 * but Linux support for it appeared well after TPACKET_V2 support
4205 * did, so there should never be a case where 32-bit ARM code is
4206 * running o a 64-bit kernel that only supports TPACKET_V1.)
4208 * If we've omitted your favorite such architecture, please contribute
4209 * a patch. (No patch is needed for architectures that are 32-bit-only
4210 * or for which Linux has no support for 32-bit userland - or for which,
4211 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
4214 #if defined(__i386__)
4215 #define ISA_64_BIT "x86_64"
4216 #elif defined(__ppc__)
4217 #define ISA_64_BIT "ppc64"
4218 #elif defined(__sparc__)
4219 #define ISA_64_BIT "sparc64"
4220 #elif defined(__s390__)
4221 #define ISA_64_BIT "s390x"
4222 #elif defined(__mips__)
4223 #define ISA_64_BIT "mips64"
4224 #elif defined(__hppa__)
4225 #define ISA_64_BIT "parisc64"
4229 * Attempt to set the socket to version 3 of the memory-mapped header and,
4230 * if that fails because version 3 isn't supported, attempt to fall
4231 * back to version 2. If version 2 isn't supported, just leave it at
4234 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
4235 * supported; return -1 on any other error, and set handle->errbuf.
4238 prepare_tpacket_socket(pcap_t *handle)
4240 struct pcap_linux *handlep = handle->priv;
4241 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4245 #ifdef HAVE_TPACKET3
4247 * Try setting the version to TPACKET_V3.
4249 * The only mode in which buffering is done on PF_PACKET
4250 * sockets, so that packets might not be delivered
4251 * immediately, is TPACKET_V3 mode.
4253 * The buffering cannot be disabled in that mode, so
4254 * if the user has requested immediate mode, we don't
4257 if (!handle->opt.immediate) {
4258 ret = init_tpacket(handle, TPACKET_V3, "TPACKET_V3");
4267 * We failed for some reason other than "the
4268 * kernel doesn't support TPACKET_V3".
4273 #endif /* HAVE_TPACKET3 */
4275 #ifdef HAVE_TPACKET2
4277 * Try setting the version to TPACKET_V2.
4279 ret = init_tpacket(handle, TPACKET_V2, "TPACKET_V2");
4288 * We failed for some reason other than "the
4289 * kernel doesn't support TPACKET_V2".
4293 #endif /* HAVE_TPACKET2 */
4296 * OK, we're using TPACKET_V1, as either that's all the kernel
4297 * supports or it doesn't support TPACKET at all. In the latter
4298 * case, create_ring() will fail, and we'll fall back on non-
4299 * memory-mapped capture.
4301 handlep->tp_version = TPACKET_V1;
4302 handlep->tp_hdrlen = sizeof(struct tpacket_hdr);
4306 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
4307 * each other due to platform-dependent data type size differences.
4309 * If we have a 32-bit userland and a 64-bit kernel, use an
4310 * internally-defined TPACKET_V1_64, with which we use a 64-bit
4311 * version of the data structures.
4313 if (sizeof(long) == 4) {
4315 * This is 32-bit code.
4317 struct utsname utsname;
4319 if (uname(&utsname) == -1) {
4323 pcap_fmt_errmsg_for_errno(handle->errbuf,
4324 PCAP_ERRBUF_SIZE, errno, "uname failed");
4327 if (strcmp(utsname.machine, ISA_64_BIT) == 0) {
4329 * uname() tells us the machine is 64-bit,
4330 * so we presumably have a 64-bit kernel.
4332 * XXX - this presumes that uname() won't lie
4333 * in 32-bit code and claim that the machine
4334 * has the 32-bit version of the ISA.
4336 handlep->tp_version = TPACKET_V1_64;
4337 handlep->tp_hdrlen = sizeof(struct tpacket_hdr_64);
4345 #define MAX(a,b) ((a)>(b)?(a):(b))
4348 * Attempt to set up memory-mapped access.
4350 * On success, returns 1, and sets *status to 0 if there are no warnings
4351 * or to a PCAP_WARNING_ code if there is a warning.
4353 * On failure due to lack of support for memory-mapped capture, returns
4356 * On error, returns -1, and sets *status to the appropriate error code;
4357 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4360 create_ring(pcap_t *handle, int *status)
4362 struct pcap_linux *handlep = handle->priv;
4363 unsigned i, j, frames_per_block;
4364 #ifdef HAVE_TPACKET3
4366 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
4367 * stuff at the end of a struct tpacket_req3 will be
4368 * ignored, so this is OK even for those sockets.
4370 struct tpacket_req3 req;
4372 struct tpacket_req req;
4375 unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
4376 unsigned int frame_size;
4379 * Start out assuming no warnings or errors.
4383 switch (handlep->tp_version) {
4387 #ifdef HAVE_TPACKET2
4390 /* Note that with large snapshot length (say 256K, which is
4391 * the default for recent versions of tcpdump, Wireshark,
4392 * TShark, dumpcap or 64K, the value that "-s 0" has given for
4393 * a long time with tcpdump), if we use the snapshot
4394 * length to calculate the frame length, only a few frames
4395 * will be available in the ring even with pretty
4396 * large ring size (and a lot of memory will be unused).
4398 * Ideally, we should choose a frame length based on the
4399 * minimum of the specified snapshot length and the maximum
4400 * packet size. That's not as easy as it sounds; consider,
4401 * for example, an 802.11 interface in monitor mode, where
4402 * the frame would include a radiotap header, where the
4403 * maximum radiotap header length is device-dependent.
4405 * So, for now, we just do this for Ethernet devices, where
4406 * there's no metadata header, and the link-layer header is
4407 * fixed length. We can get the maximum packet size by
4408 * adding 18, the Ethernet header length plus the CRC length
4409 * (just in case we happen to get the CRC in the packet), to
4410 * the MTU of the interface; we fetch the MTU in the hopes
4411 * that it reflects support for jumbo frames. (Even if the
4412 * interface is just being used for passive snooping, the
4413 * driver might set the size of buffers in the receive ring
4414 * based on the MTU, so that the MTU limits the maximum size
4415 * of packets that we can receive.)
4417 * If segmentation/fragmentation or receive offload are
4418 * enabled, we can get reassembled/aggregated packets larger
4419 * than MTU, but bounded to 65535 plus the Ethernet overhead,
4420 * due to kernel and protocol constraints */
4421 frame_size = handle->snapshot;
4422 if (handle->linktype == DLT_EN10MB) {
4423 unsigned int max_frame_len;
4427 mtu = iface_get_mtu(handle->fd, handle->opt.device,
4430 *status = PCAP_ERROR;
4433 offload = iface_get_offload(handle);
4434 if (offload == -1) {
4435 *status = PCAP_ERROR;
4439 max_frame_len = MAX(mtu, 65535);
4441 max_frame_len = mtu;
4442 max_frame_len += 18;
4444 if (frame_size > max_frame_len)
4445 frame_size = max_frame_len;
4448 /* NOTE: calculus matching those in tpacket_rcv()
4449 * in linux-2.6/net/packet/af_packet.c
4451 len = sizeof(sk_type);
4452 if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type,
4454 pcap_fmt_errmsg_for_errno(handle->errbuf,
4455 PCAP_ERRBUF_SIZE, errno, "getsockopt (SO_TYPE)");
4456 *status = PCAP_ERROR;
4459 #ifdef PACKET_RESERVE
4460 len = sizeof(tp_reserve);
4461 if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
4462 &tp_reserve, &len) < 0) {
4463 if (errno != ENOPROTOOPT) {
4465 * ENOPROTOOPT means "kernel doesn't support
4466 * PACKET_RESERVE", in which case we fall back
4469 pcap_fmt_errmsg_for_errno(handle->errbuf,
4470 PCAP_ERRBUF_SIZE, errno,
4471 "getsockopt (PACKET_RESERVE)");
4472 *status = PCAP_ERROR;
4476 * Older kernel, so we can't use PACKET_RESERVE;
4477 * this means we can't reserver extra space
4478 * for a DLT_LINUX_SLL2 header.
4483 * We can reserve extra space for a DLT_LINUX_SLL2
4486 * XXX - we assume that the kernel is still adding
4487 * 16 bytes of extra space; that happens to
4488 * correspond to SLL_HDR_LEN (whether intentionally
4489 * or not - the kernel code has a raw "16" in
4490 * the expression), so we subtract SLL_HDR_LEN
4491 * from SLL2_HDR_LEN to get the additional space
4494 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
4496 tp_reserve += SLL2_HDR_LEN - SLL_HDR_LEN;
4497 len = sizeof(tp_reserve);
4498 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
4499 &tp_reserve, len) < 0) {
4500 pcap_fmt_errmsg_for_errno(handle->errbuf,
4501 PCAP_ERRBUF_SIZE, errno,
4502 "setsockopt (PACKET_RESERVE)");
4503 *status = PCAP_ERROR;
4509 * Build environment for an older kernel, so we can't
4510 * use PACKET_RESERVE; this means we can't reserve
4511 * extra space for a DLT_LINUX_SLL2 header.
4515 maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
4516 /* XXX: in the kernel maclen is calculated from
4517 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4518 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4519 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4520 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4521 * but I see no way to get those sizes in userspace,
4522 * like for instance with an ifreq ioctl();
4523 * the best thing I've found so far is MAX_HEADER in
4524 * the kernel part of linux-2.6/include/linux/netdevice.h
4525 * which goes up to 128+48=176; since pcap-linux.c
4526 * defines a MAX_LINKHEADER_SIZE of 256 which is
4527 * greater than that, let's use it.. maybe is it even
4528 * large enough to directly replace macoff..
4530 tp_hdrlen = TPACKET_ALIGN(handlep->tp_hdrlen) + sizeof(struct sockaddr_ll) ;
4531 netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
4532 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4533 * of netoff, which contradicts
4534 * linux-2.6/Documentation/networking/packet_mmap.txt
4536 * "- Gap, chosen so that packet data (Start+tp_net)
4537 * aligns to TPACKET_ALIGNMENT=16"
4539 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4540 * "CPUs often take a performance hit
4541 * when accessing unaligned memory locations"
4543 macoff = netoff - maclen;
4544 req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
4546 * Round the buffer size up to a multiple of the
4547 * frame size (rather than rounding down, which
4548 * would give a buffer smaller than our caller asked
4549 * for, and possibly give zero frames if the requested
4550 * buffer size is too small for one frame).
4552 req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
4555 #ifdef HAVE_TPACKET3
4558 * If we have TPACKET_V3, we have PACKET_RESERVE.
4560 len = sizeof(tp_reserve);
4561 if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
4562 &tp_reserve, &len) < 0) {
4564 * Even ENOPROTOOPT is an error - we wouldn't
4565 * be here if the kernel didn't support
4566 * TPACKET_V3, which means it supports
4569 pcap_fmt_errmsg_for_errno(handle->errbuf,
4570 PCAP_ERRBUF_SIZE, errno,
4571 "getsockopt (PACKET_RESERVE)");
4572 *status = PCAP_ERROR;
4576 * We can reserve extra space for a DLT_LINUX_SLL2
4579 * XXX - we assume that the kernel is still adding
4580 * 16 bytes of extra space; that happens to
4581 * correspond to SLL_HDR_LEN (whether intentionally
4582 * or not - the kernel code has a raw "16" in
4583 * the expression), so we subtract SLL_HDR_LEN
4584 * from SLL2_HDR_LEN to get the additional space
4587 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
4589 tp_reserve += SLL2_HDR_LEN - SLL_HDR_LEN;
4590 len = sizeof(tp_reserve);
4591 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
4592 &tp_reserve, len) < 0) {
4593 pcap_fmt_errmsg_for_errno(handle->errbuf,
4594 PCAP_ERRBUF_SIZE, errno,
4595 "setsockopt (PACKET_RESERVE)");
4596 *status = PCAP_ERROR;
4600 /* The "frames" for this are actually buffers that
4601 * contain multiple variable-sized frames.
4603 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
4604 * enough room for at least one reasonably-sized packet
4605 * in the "frame". */
4606 req.tp_frame_size = MAXIMUM_SNAPLEN;
4608 * Round the buffer size up to a multiple of the
4609 * "frame" size (rather than rounding down, which
4610 * would give a buffer smaller than our caller asked
4611 * for, and possibly give zero "frames" if the requested
4612 * buffer size is too small for one "frame").
4614 req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
4618 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4619 "Internal error: unknown TPACKET_ value %u",
4620 handlep->tp_version);
4621 *status = PCAP_ERROR;
4625 /* compute the minumum block size that will handle this frame.
4626 * The block has to be page size aligned.
4627 * The max block size allowed by the kernel is arch-dependent and
4628 * it's not explicitly checked here. */
4629 req.tp_block_size = getpagesize();
4630 while (req.tp_block_size < req.tp_frame_size)
4631 req.tp_block_size <<= 1;
4633 frames_per_block = req.tp_block_size/req.tp_frame_size;
4636 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4637 * so we check for PACKET_TIMESTAMP. We check for
4638 * linux/net_tstamp.h just in case a system somehow has
4639 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4642 * SIOCSHWTSTAMP was introduced in the patch that introduced
4643 * linux/net_tstamp.h, so we don't bother checking whether
4644 * SIOCSHWTSTAMP is defined (if your Linux system has
4645 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4646 * Linux system is badly broken).
4648 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4650 * If we were told to do so, ask the kernel and the driver
4651 * to use hardware timestamps.
4653 * Hardware timestamps are only supported with mmapped
4656 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
4657 handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
4658 struct hwtstamp_config hwconfig;
4663 * Ask for hardware time stamps on all packets,
4664 * including transmitted packets.
4666 memset(&hwconfig, 0, sizeof(hwconfig));
4667 hwconfig.tx_type = HWTSTAMP_TX_ON;
4668 hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
4670 memset(&ifr, 0, sizeof(ifr));
4671 pcap_strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
4672 ifr.ifr_data = (void *)&hwconfig;
4674 if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
4679 * Treat this as an error, as the
4680 * user should try to run this
4681 * with the appropriate privileges -
4682 * and, if they can't, shouldn't
4683 * try requesting hardware time stamps.
4685 *status = PCAP_ERROR_PERM_DENIED;
4691 * Treat this as a warning, as the
4692 * only way to fix the warning is to
4693 * get an adapter that supports hardware
4694 * time stamps for *all* packets.
4695 * (ERANGE means "we support hardware
4696 * time stamps, but for packets matching
4697 * that particular filter", so it means
4698 * "we don't support hardware time stamps
4699 * for all incoming packets" here.)
4701 * We'll just fall back on the standard
4704 *status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
4708 pcap_fmt_errmsg_for_errno(handle->errbuf,
4709 PCAP_ERRBUF_SIZE, errno,
4710 "SIOCSHWTSTAMP failed");
4711 *status = PCAP_ERROR;
4716 * Well, that worked. Now specify the type of
4717 * hardware time stamp we want for this
4720 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
4722 * Hardware timestamp, synchronized
4723 * with the system clock.
4725 timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
4728 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4729 * timestamp, not synchronized with the
4732 timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
4734 if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
4735 (void *)×ource, sizeof(timesource))) {
4736 pcap_fmt_errmsg_for_errno(handle->errbuf,
4737 PCAP_ERRBUF_SIZE, errno,
4738 "can't set PACKET_TIMESTAMP");
4739 *status = PCAP_ERROR;
4744 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4746 /* ask the kernel to create the ring */
4748 req.tp_block_nr = req.tp_frame_nr / frames_per_block;
4750 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4751 req.tp_frame_nr = req.tp_block_nr * frames_per_block;
4753 #ifdef HAVE_TPACKET3
4754 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4755 if (handlep->timeout > 0) {
4756 /* Use the user specified timeout as the block timeout */
4757 req.tp_retire_blk_tov = handlep->timeout;
4758 } else if (handlep->timeout == 0) {
4760 * In pcap, this means "infinite timeout"; TPACKET_V3
4761 * doesn't support that, so just set it to UINT_MAX
4762 * milliseconds. In the TPACKET_V3 loop, if the
4763 * timeout is 0, and we haven't yet seen any packets,
4764 * and we block and still don't have any packets, we
4765 * keep blocking until we do.
4767 req.tp_retire_blk_tov = UINT_MAX;
4770 * XXX - this is not valid; use 0, meaning "have the
4771 * kernel pick a default", for now.
4773 req.tp_retire_blk_tov = 0;
4775 /* private data not used */
4776 req.tp_sizeof_priv = 0;
4777 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4778 req.tp_feature_req_word = 0;
4781 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
4782 (void *) &req, sizeof(req))) {
4783 if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
4785 * Memory failure; try to reduce the requested ring
4788 * We used to reduce this by half -- do 5% instead.
4789 * That may result in more iterations and a longer
4790 * startup, but the user will be much happier with
4791 * the resulting buffer size.
4793 if (req.tp_frame_nr < 20)
4794 req.tp_frame_nr -= 1;
4796 req.tp_frame_nr -= req.tp_frame_nr/20;
4799 if (errno == ENOPROTOOPT) {
4801 * We don't have ring buffer support in this kernel.
4805 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4806 errno, "can't create rx ring on packet socket");
4807 *status = PCAP_ERROR;
4811 /* memory map the rx ring */
4812 handlep->mmapbuflen = req.tp_block_nr * req.tp_block_size;
4813 handlep->mmapbuf = mmap(0, handlep->mmapbuflen,
4814 PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
4815 if (handlep->mmapbuf == MAP_FAILED) {
4816 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4817 errno, "can't mmap rx ring");
4819 /* clear the allocated ring on error*/
4820 destroy_ring(handle);
4821 *status = PCAP_ERROR;
4825 /* allocate a ring for each frame header pointer*/
4826 handle->cc = req.tp_frame_nr;
4827 handle->buffer = malloc(handle->cc * sizeof(union thdr *));
4828 if (!handle->buffer) {
4829 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4830 errno, "can't allocate ring of frame headers");
4832 destroy_ring(handle);
4833 *status = PCAP_ERROR;
4837 /* fill the header ring with proper frame ptr*/
4839 for (i=0; i<req.tp_block_nr; ++i) {
4840 void *base = &handlep->mmapbuf[i*req.tp_block_size];
4841 for (j=0; j<frames_per_block; ++j, ++handle->offset) {
4842 RING_GET_CURRENT_FRAME(handle) = base;
4843 base += req.tp_frame_size;
4847 handle->bufsize = req.tp_frame_size;
4852 /* free all ring related resources*/
4854 destroy_ring(pcap_t *handle)
4856 struct pcap_linux *handlep = handle->priv;
4858 /* tell the kernel to destroy the ring*/
4859 struct tpacket_req req;
4860 memset(&req, 0, sizeof(req));
4861 /* do not test for setsockopt failure, as we can't recover from any error */
4862 (void)setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
4863 (void *) &req, sizeof(req));
4865 /* if ring is mapped, unmap it*/
4866 if (handlep->mmapbuf) {
4867 /* do not test for mmap failure, as we can't recover from any error */
4868 (void)munmap(handlep->mmapbuf, handlep->mmapbuflen);
4869 handlep->mmapbuf = NULL;
4874 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4875 * for Linux mmapped capture.
4877 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4878 * data handed to the callback to be valid after the callback returns,
4879 * but pcap_read_linux_mmap() has to release that packet as soon as
4880 * the callback returns (otherwise, the kernel thinks there's still
4881 * at least one unprocessed packet available in the ring, so a select()
4882 * will immediately return indicating that there's data to process), so,
4883 * in the callback, we have to make a copy of the packet.
4885 * Yes, this means that, if the capture is using the ring buffer, using
4886 * pcap_next() or pcap_next_ex() requires more copies than using
4887 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4888 * pcap_next() or pcap_next_ex().
4891 pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
4892 const u_char *bytes)
4894 struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
4895 pcap_t *handle = sp->pd;
4896 struct pcap_linux *handlep = handle->priv;
4899 memcpy(handlep->oneshot_buffer, bytes, h->caplen);
4900 *sp->pkt = handlep->oneshot_buffer;
4904 pcap_cleanup_linux_mmap( pcap_t *handle )
4906 struct pcap_linux *handlep = handle->priv;
4908 destroy_ring(handle);
4909 if (handlep->oneshot_buffer != NULL) {
4910 free(handlep->oneshot_buffer);
4911 handlep->oneshot_buffer = NULL;
4913 pcap_cleanup_linux(handle);
4918 pcap_getnonblock_mmap(pcap_t *handle)
4920 struct pcap_linux *handlep = handle->priv;
4922 /* use negative value of timeout to indicate non blocking ops */
4923 return (handlep->timeout<0);
4927 pcap_setnonblock_mmap(pcap_t *handle, int nonblock)
4929 struct pcap_linux *handlep = handle->priv;
4932 * Set the file descriptor to non-blocking mode, as we use
4933 * it for sending packets.
4935 if (pcap_setnonblock_fd(handle, nonblock) == -1)
4939 * Map each value to their corresponding negation to
4940 * preserve the timeout value provided with pcap_set_timeout.
4943 if (handlep->timeout >= 0) {
4945 * Indicate that we're switching to
4946 * non-blocking mode.
4948 handlep->timeout = ~handlep->timeout;
4951 if (handlep->timeout < 0) {
4952 handlep->timeout = ~handlep->timeout;
4955 /* Update the timeout to use in poll(). */
4956 set_poll_timeout(handlep);
4961 * Get the status field of the ring buffer frame at a specified offset.
4964 pcap_get_ring_frame_status(pcap_t *handle, int offset)
4966 struct pcap_linux *handlep = handle->priv;
4969 h.raw = RING_GET_FRAME_AT(handle, offset);
4970 switch (handlep->tp_version) {
4972 return (h.h1->tp_status);
4975 return (h.h1_64->tp_status);
4977 #ifdef HAVE_TPACKET2
4979 return (h.h2->tp_status);
4982 #ifdef HAVE_TPACKET3
4984 return (h.h3->hdr.bh1.block_status);
4988 /* This should not happen. */
4997 * Block waiting for frames to be available.
4999 static int pcap_wait_for_frames_mmap(pcap_t *handle)
5001 struct pcap_linux *handlep = handle->priv;
5003 struct pollfd pollinfo;
5006 pollinfo.fd = handle->fd;
5007 pollinfo.events = POLLIN;
5011 * Yes, we do this even in non-blocking mode, as it's
5012 * the only way to get error indications from a
5015 * The timeout is 0 in non-blocking mode, so poll()
5016 * returns immediately.
5018 ret = poll(&pollinfo, 1, handlep->poll_timeout);
5019 if (ret < 0 && errno != EINTR) {
5020 pcap_fmt_errmsg_for_errno(handle->errbuf,
5021 PCAP_ERRBUF_SIZE, errno,
5022 "can't poll on packet socket");
5024 } else if (ret > 0 &&
5025 (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
5027 * There's some indication other than
5028 * "you can read on this descriptor" on
5031 if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
5032 pcap_snprintf(handle->errbuf,
5034 "Hangup on packet socket");
5037 if (pollinfo.revents & POLLERR) {
5039 * A recv() will give us the actual error code.
5041 * XXX - make the socket non-blocking?
5043 if (recv(handle->fd, &c, sizeof c,
5045 continue; /* what, no error? */
5046 if (errno == ENETDOWN) {
5048 * The device on which we're
5049 * capturing went away.
5051 * XXX - we should really return
5052 * PCAP_ERROR_IFACE_NOT_UP, but
5053 * pcap_dispatch() etc. aren't
5054 * defined to return that.
5056 pcap_snprintf(handle->errbuf,
5058 "The interface went down");
5060 pcap_fmt_errmsg_for_errno(handle->errbuf,
5061 PCAP_ERRBUF_SIZE, errno,
5062 "Error condition on packet socket");
5066 if (pollinfo.revents & POLLNVAL) {
5067 pcap_snprintf(handle->errbuf,
5069 "Invalid polling request on packet socket");
5073 /* check for break loop condition on interrupted syscall*/
5074 if (handle->break_loop) {
5075 handle->break_loop = 0;
5076 return PCAP_ERROR_BREAK;
5082 /* handle a single memory mapped packet */
5083 static int pcap_handle_packet_mmap(
5085 pcap_handler callback,
5087 unsigned char *frame,
5088 unsigned int tp_len,
5089 unsigned int tp_mac,
5090 unsigned int tp_snaplen,
5091 unsigned int tp_sec,
5092 unsigned int tp_usec,
5093 int tp_vlan_tci_valid,
5097 struct pcap_linux *handlep = handle->priv;
5099 struct sockaddr_ll *sll;
5100 struct pcap_pkthdr pcaphdr;
5101 unsigned int snaplen = tp_snaplen;
5102 struct utsname utsname;
5104 /* perform sanity check on internal offset. */
5105 if (tp_mac + tp_snaplen > handle->bufsize) {
5107 * Report some system information as a debugging aid.
5109 if (uname(&utsname) != -1) {
5110 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5111 "corrupted frame on kernel ring mac "
5112 "offset %u + caplen %u > frame len %d "
5113 "(kernel %.32s version %s, machine %.16s)",
5114 tp_mac, tp_snaplen, handle->bufsize,
5115 utsname.release, utsname.version,
5118 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5119 "corrupted frame on kernel ring mac "
5120 "offset %u + caplen %u > frame len %d",
5121 tp_mac, tp_snaplen, handle->bufsize);
5126 /* run filter on received packet
5127 * If the kernel filtering is enabled we need to run the
5128 * filter until all the frames present into the ring
5129 * at filter creation time are processed.
5130 * In this case, blocks_to_filter_in_userland is used
5131 * as a counter for the packet we need to filter.
5132 * Note: alternatively it could be possible to stop applying
5133 * the filter when the ring became empty, but it can possibly
5134 * happen a lot later... */
5135 bp = frame + tp_mac;
5137 /* if required build in place the sll header*/
5138 sll = (void *)frame + TPACKET_ALIGN(handlep->tp_hdrlen);
5139 if (handlep->cooked) {
5140 if (handle->linktype == DLT_LINUX_SLL2) {
5141 struct sll2_header *hdrp;
5144 * The kernel should have left us with enough
5145 * space for an sll header; back up the packet
5146 * data pointer into that space, as that'll be
5147 * the beginning of the packet we pass to the
5153 * Let's make sure that's past the end of
5154 * the tpacket header, i.e. >=
5155 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5156 * don't step on the header when we construct
5159 if (bp < (u_char *)frame +
5160 TPACKET_ALIGN(handlep->tp_hdrlen) +
5161 sizeof(struct sockaddr_ll)) {
5162 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5163 "cooked-mode frame doesn't have room for sll header");
5168 * OK, that worked; construct the sll header.
5170 hdrp = (struct sll2_header *)bp;
5171 hdrp->sll2_protocol = sll->sll_protocol;
5172 hdrp->sll2_reserved_mbz = 0;
5173 hdrp->sll2_if_index = htonl(sll->sll_ifindex);
5174 hdrp->sll2_hatype = htons(sll->sll_hatype);
5175 hdrp->sll2_pkttype = sll->sll_pkttype;
5176 hdrp->sll2_halen = sll->sll_halen;
5177 memcpy(hdrp->sll2_addr, sll->sll_addr, SLL_ADDRLEN);
5179 snaplen += sizeof(struct sll2_header);
5181 struct sll_header *hdrp;
5184 * The kernel should have left us with enough
5185 * space for an sll header; back up the packet
5186 * data pointer into that space, as that'll be
5187 * the beginning of the packet we pass to the
5193 * Let's make sure that's past the end of
5194 * the tpacket header, i.e. >=
5195 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5196 * don't step on the header when we construct
5199 if (bp < (u_char *)frame +
5200 TPACKET_ALIGN(handlep->tp_hdrlen) +
5201 sizeof(struct sockaddr_ll)) {
5202 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5203 "cooked-mode frame doesn't have room for sll header");
5208 * OK, that worked; construct the sll header.
5210 hdrp = (struct sll_header *)bp;
5211 hdrp->sll_pkttype = htons(sll->sll_pkttype);
5212 hdrp->sll_hatype = htons(sll->sll_hatype);
5213 hdrp->sll_halen = htons(sll->sll_halen);
5214 memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
5215 hdrp->sll_protocol = sll->sll_protocol;
5217 snaplen += sizeof(struct sll_header);
5221 if (handlep->filter_in_userland && handle->fcode.bf_insns) {
5222 struct bpf_aux_data aux_data;
5224 aux_data.vlan_tag_present = tp_vlan_tci_valid;
5225 aux_data.vlan_tag = tp_vlan_tci & 0x0fff;
5227 if (bpf_filter_with_aux_data(handle->fcode.bf_insns,
5235 if (!linux_check_direction(handle, sll))
5238 /* get required packet info from ring header */
5239 pcaphdr.ts.tv_sec = tp_sec;
5240 pcaphdr.ts.tv_usec = tp_usec;
5241 pcaphdr.caplen = tp_snaplen;
5242 pcaphdr.len = tp_len;
5244 /* if required build in place the sll header*/
5245 if (handlep->cooked) {
5246 /* update packet len */
5247 if (handle->linktype == DLT_LINUX_SLL2) {
5248 pcaphdr.caplen += SLL2_HDR_LEN;
5249 pcaphdr.len += SLL2_HDR_LEN;
5251 pcaphdr.caplen += SLL_HDR_LEN;
5252 pcaphdr.len += SLL_HDR_LEN;
5256 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
5257 if (tp_vlan_tci_valid &&
5258 handlep->vlan_offset != -1 &&
5259 tp_snaplen >= (unsigned int) handlep->vlan_offset)
5261 struct vlan_tag *tag;
5264 * Move everything in the header, except the type field,
5265 * down VLAN_TAG_LEN bytes, to allow us to insert the
5266 * VLAN tag between that stuff and the type field.
5269 memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
5272 * Now insert the tag.
5274 tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
5275 tag->vlan_tpid = htons(tp_vlan_tpid);
5276 tag->vlan_tci = htons(tp_vlan_tci);
5279 * Add the tag to the packet lengths.
5281 pcaphdr.caplen += VLAN_TAG_LEN;
5282 pcaphdr.len += VLAN_TAG_LEN;
5287 * The only way to tell the kernel to cut off the
5288 * packet at a snapshot length is with a filter program;
5289 * if there's no filter program, the kernel won't cut
5292 * Trim the snapshot length to be no longer than the
5293 * specified snapshot length.
5295 if (pcaphdr.caplen > (bpf_u_int32)handle->snapshot)
5296 pcaphdr.caplen = handle->snapshot;
5298 /* pass the packet to the user */
5299 callback(user, &pcaphdr, bp);
5305 pcap_read_linux_mmap_v1(pcap_t *handle, int max_packets, pcap_handler callback,
5308 struct pcap_linux *handlep = handle->priv;
5313 /* wait for frames availability.*/
5314 h.raw = RING_GET_CURRENT_FRAME(handle);
5315 if (h.h1->tp_status == TP_STATUS_KERNEL) {
5317 * The current frame is owned by the kernel; wait for
5318 * a frame to be handed to us.
5320 ret = pcap_wait_for_frames_mmap(handle);
5326 /* non-positive values of max_packets are used to require all
5327 * packets currently available in the ring */
5328 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5330 * Get the current ring buffer frame, and break if
5331 * it's still owned by the kernel.
5333 h.raw = RING_GET_CURRENT_FRAME(handle);
5334 if (h.h1->tp_status == TP_STATUS_KERNEL)
5337 ret = pcap_handle_packet_mmap(
5352 handlep->packets_read++;
5353 } else if (ret < 0) {
5358 * Hand this block back to the kernel, and, if we're
5359 * counting blocks that need to be filtered in userland
5360 * after having been filtered by the kernel, count
5361 * the one we've just processed.
5363 h.h1->tp_status = TP_STATUS_KERNEL;
5364 if (handlep->blocks_to_filter_in_userland > 0) {
5365 handlep->blocks_to_filter_in_userland--;
5366 if (handlep->blocks_to_filter_in_userland == 0) {
5368 * No more blocks need to be filtered
5371 handlep->filter_in_userland = 0;
5376 if (++handle->offset >= handle->cc)
5379 /* check for break loop condition*/
5380 if (handle->break_loop) {
5381 handle->break_loop = 0;
5382 return PCAP_ERROR_BREAK;
5389 pcap_read_linux_mmap_v1_64(pcap_t *handle, int max_packets, pcap_handler callback,
5392 struct pcap_linux *handlep = handle->priv;
5397 /* wait for frames availability.*/
5398 h.raw = RING_GET_CURRENT_FRAME(handle);
5399 if (h.h1_64->tp_status == TP_STATUS_KERNEL) {
5401 * The current frame is owned by the kernel; wait for
5402 * a frame to be handed to us.
5404 ret = pcap_wait_for_frames_mmap(handle);
5410 /* non-positive values of max_packets are used to require all
5411 * packets currently available in the ring */
5412 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5414 * Get the current ring buffer frame, and break if
5415 * it's still owned by the kernel.
5417 h.raw = RING_GET_CURRENT_FRAME(handle);
5418 if (h.h1_64->tp_status == TP_STATUS_KERNEL)
5421 ret = pcap_handle_packet_mmap(
5428 h.h1_64->tp_snaplen,
5436 handlep->packets_read++;
5437 } else if (ret < 0) {
5442 * Hand this block back to the kernel, and, if we're
5443 * counting blocks that need to be filtered in userland
5444 * after having been filtered by the kernel, count
5445 * the one we've just processed.
5447 h.h1_64->tp_status = TP_STATUS_KERNEL;
5448 if (handlep->blocks_to_filter_in_userland > 0) {
5449 handlep->blocks_to_filter_in_userland--;
5450 if (handlep->blocks_to_filter_in_userland == 0) {
5452 * No more blocks need to be filtered
5455 handlep->filter_in_userland = 0;
5460 if (++handle->offset >= handle->cc)
5463 /* check for break loop condition*/
5464 if (handle->break_loop) {
5465 handle->break_loop = 0;
5466 return PCAP_ERROR_BREAK;
5472 #ifdef HAVE_TPACKET2
5474 pcap_read_linux_mmap_v2(pcap_t *handle, int max_packets, pcap_handler callback,
5477 struct pcap_linux *handlep = handle->priv;
5482 /* wait for frames availability.*/
5483 h.raw = RING_GET_CURRENT_FRAME(handle);
5484 if (h.h2->tp_status == TP_STATUS_KERNEL) {
5486 * The current frame is owned by the kernel; wait for
5487 * a frame to be handed to us.
5489 ret = pcap_wait_for_frames_mmap(handle);
5495 /* non-positive values of max_packets are used to require all
5496 * packets currently available in the ring */
5497 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5499 * Get the current ring buffer frame, and break if
5500 * it's still owned by the kernel.
5502 h.raw = RING_GET_CURRENT_FRAME(handle);
5503 if (h.h2->tp_status == TP_STATUS_KERNEL)
5506 ret = pcap_handle_packet_mmap(
5515 handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? h.h2->tp_nsec : h.h2->tp_nsec / 1000,
5516 VLAN_VALID(h.h2, h.h2),
5518 VLAN_TPID(h.h2, h.h2));
5521 handlep->packets_read++;
5522 } else if (ret < 0) {
5527 * Hand this block back to the kernel, and, if we're
5528 * counting blocks that need to be filtered in userland
5529 * after having been filtered by the kernel, count
5530 * the one we've just processed.
5532 h.h2->tp_status = TP_STATUS_KERNEL;
5533 if (handlep->blocks_to_filter_in_userland > 0) {
5534 handlep->blocks_to_filter_in_userland--;
5535 if (handlep->blocks_to_filter_in_userland == 0) {
5537 * No more blocks need to be filtered
5540 handlep->filter_in_userland = 0;
5545 if (++handle->offset >= handle->cc)
5548 /* check for break loop condition*/
5549 if (handle->break_loop) {
5550 handle->break_loop = 0;
5551 return PCAP_ERROR_BREAK;
5556 #endif /* HAVE_TPACKET2 */
5558 #ifdef HAVE_TPACKET3
5560 pcap_read_linux_mmap_v3(pcap_t *handle, int max_packets, pcap_handler callback,
5563 struct pcap_linux *handlep = handle->priv;
5569 if (handlep->current_packet == NULL) {
5570 /* wait for frames availability.*/
5571 h.raw = RING_GET_CURRENT_FRAME(handle);
5572 if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL) {
5574 * The current frame is owned by the kernel; wait
5575 * for a frame to be handed to us.
5577 ret = pcap_wait_for_frames_mmap(handle);
5583 h.raw = RING_GET_CURRENT_FRAME(handle);
5584 if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL) {
5585 if (pkts == 0 && handlep->timeout == 0) {
5586 /* Block until we see a packet. */
5592 /* non-positive values of max_packets are used to require all
5593 * packets currently available in the ring */
5594 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5595 int packets_to_read;
5597 if (handlep->current_packet == NULL) {
5598 h.raw = RING_GET_CURRENT_FRAME(handle);
5599 if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL)
5602 handlep->current_packet = h.raw + h.h3->hdr.bh1.offset_to_first_pkt;
5603 handlep->packets_left = h.h3->hdr.bh1.num_pkts;
5605 packets_to_read = handlep->packets_left;
5607 if (!PACKET_COUNT_IS_UNLIMITED(max_packets) &&
5608 packets_to_read > (max_packets - pkts)) {
5610 * We've been given a maximum number of packets
5611 * to process, and there are more packets in
5612 * this buffer than that. Only process enough
5613 * of them to get us up to that maximum.
5615 packets_to_read = max_packets - pkts;
5618 while (packets_to_read-- && !handle->break_loop) {
5619 struct tpacket3_hdr* tp3_hdr = (struct tpacket3_hdr*) handlep->current_packet;
5620 ret = pcap_handle_packet_mmap(
5624 handlep->current_packet,
5627 tp3_hdr->tp_snaplen,
5629 handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? tp3_hdr->tp_nsec : tp3_hdr->tp_nsec / 1000,
5630 VLAN_VALID(tp3_hdr, &tp3_hdr->hv1),
5631 tp3_hdr->hv1.tp_vlan_tci,
5632 VLAN_TPID(tp3_hdr, &tp3_hdr->hv1));
5635 handlep->packets_read++;
5636 } else if (ret < 0) {
5637 handlep->current_packet = NULL;
5640 handlep->current_packet += tp3_hdr->tp_next_offset;
5641 handlep->packets_left--;
5644 if (handlep->packets_left <= 0) {
5646 * Hand this block back to the kernel, and, if
5647 * we're counting blocks that need to be
5648 * filtered in userland after having been
5649 * filtered by the kernel, count the one we've
5652 h.h3->hdr.bh1.block_status = TP_STATUS_KERNEL;
5653 if (handlep->blocks_to_filter_in_userland > 0) {
5654 handlep->blocks_to_filter_in_userland--;
5655 if (handlep->blocks_to_filter_in_userland == 0) {
5657 * No more blocks need to be filtered
5660 handlep->filter_in_userland = 0;
5665 if (++handle->offset >= handle->cc)
5668 handlep->current_packet = NULL;
5671 /* check for break loop condition*/
5672 if (handle->break_loop) {
5673 handle->break_loop = 0;
5674 return PCAP_ERROR_BREAK;
5677 if (pkts == 0 && handlep->timeout == 0) {
5678 /* Block until we see a packet. */
5683 #endif /* HAVE_TPACKET3 */
5686 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
5688 struct pcap_linux *handlep = handle->priv;
5693 * Don't rewrite "ret" instructions; we don't need to, as
5694 * we're not reading packets with recvmsg(), and we don't
5695 * want to, as, by not rewriting them, the kernel can avoid
5696 * copying extra data.
5698 ret = pcap_setfilter_linux_common(handle, filter, 1);
5703 * If we're filtering in userland, there's nothing to do;
5704 * the new filter will be used for the next packet.
5706 if (handlep->filter_in_userland)
5710 * We're filtering in the kernel; the packets present in
5711 * all blocks currently in the ring were already filtered
5712 * by the old filter, and so will need to be filtered in
5713 * userland by the new filter.
5715 * Get an upper bound for the number of such blocks; first,
5716 * walk the ring backward and count the free blocks.
5718 offset = handle->offset;
5720 offset = handle->cc - 1;
5721 for (n=0; n < handle->cc; ++n) {
5723 offset = handle->cc - 1;
5724 if (pcap_get_ring_frame_status(handle, offset) != TP_STATUS_KERNEL)
5729 * If we found free blocks, decrement the count of free
5730 * blocks by 1, just in case we lost a race with another
5731 * thread of control that was adding a packet while
5732 * we were counting and that had run the filter before
5735 * XXX - could there be more than one block added in
5738 * XXX - is there a way to avoid that race, e.g. somehow
5739 * wait for all packets that passed the old filter to
5740 * be added to the ring?
5746 * Set the count of blocks worth of packets to filter
5747 * in userland to the total number of blocks in the
5748 * ring minus the number of free blocks we found, and
5749 * turn on userland filtering. (The count of blocks
5750 * worth of packets to filter in userland is guaranteed
5751 * not to be zero - n, above, couldn't be set to a
5752 * value > handle->cc, and if it were equal to
5753 * handle->cc, it wouldn't be zero, and thus would
5754 * be decremented to handle->cc - 1.)
5756 handlep->blocks_to_filter_in_userland = handle->cc - n;
5757 handlep->filter_in_userland = 1;
5761 #endif /* HAVE_PACKET_RING */
5764 #ifdef HAVE_PF_PACKET_SOCKETS
5766 * Return the index of the given device name. Fill ebuf and return
5770 iface_get_id(int fd, const char *device, char *ebuf)
5774 memset(&ifr, 0, sizeof(ifr));
5775 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5777 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
5778 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5779 errno, "SIOCGIFINDEX");
5783 return ifr.ifr_ifindex;
5787 * Bind the socket associated with FD to the given device.
5788 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
5789 * or a PCAP_ERROR_ value on a hard error.
5792 iface_bind(int fd, int ifindex, char *ebuf, int protocol)
5794 struct sockaddr_ll sll;
5796 socklen_t errlen = sizeof(err);
5798 memset(&sll, 0, sizeof(sll));
5799 sll.sll_family = AF_PACKET;
5800 sll.sll_ifindex = ifindex;
5801 sll.sll_protocol = protocol;
5803 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
5804 if (errno == ENETDOWN) {
5806 * Return a "network down" indication, so that
5807 * the application can report that rather than
5808 * saying we had a mysterious failure and
5809 * suggest that they report a problem to the
5810 * libpcap developers.
5812 return PCAP_ERROR_IFACE_NOT_UP;
5814 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5820 /* Any pending errors, e.g., network is down? */
5822 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
5823 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5824 errno, "getsockopt (SO_ERROR)");
5828 if (err == ENETDOWN) {
5830 * Return a "network down" indication, so that
5831 * the application can report that rather than
5832 * saying we had a mysterious failure and
5833 * suggest that they report a problem to the
5834 * libpcap developers.
5836 return PCAP_ERROR_IFACE_NOT_UP;
5837 } else if (err > 0) {
5838 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5846 #ifdef IW_MODE_MONITOR
5848 * Check whether the device supports the Wireless Extensions.
5849 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5850 * if the device doesn't even exist.
5853 has_wext(int sock_fd, const char *device, char *ebuf)
5858 if (is_bonding_device(sock_fd, device))
5859 return 0; /* bonding device, so don't even try */
5861 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5862 sizeof ireq.ifr_ifrn.ifrn_name);
5863 if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
5865 if (errno == ENODEV)
5866 ret = PCAP_ERROR_NO_SUCH_DEVICE;
5869 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno,
5870 "%s: SIOCGIWNAME", device);
5875 * Per me si va ne la citta dolente,
5876 * Per me si va ne l'etterno dolore,
5878 * Lasciate ogne speranza, voi ch'intrate.
5880 * XXX - airmon-ng does special stuff with the Orinoco driver and the
5896 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5897 * on if it's not already on.
5899 * Returns 1 on success, 0 if we don't support the Wireless Extensions
5900 * on this device, or a PCAP_ERROR_ value if we do support them but
5901 * we weren't able to turn monitor mode on.
5904 enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
5907 * XXX - at least some adapters require non-Wireless Extensions
5908 * mechanisms to turn monitor mode on.
5910 * Atheros cards might require that a separate "monitor virtual access
5911 * point" be created, with later versions of the madwifi driver.
5912 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
5913 * monitor -bssid", which apparently spits out a line "athN"
5914 * where "athN" is the monitor mode device. To leave monitor
5915 * mode, it destroys the monitor mode device.
5917 * Some Intel Centrino adapters might require private ioctls to get
5918 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5919 * configure a separate "rtapN" interface to capture in monitor
5920 * mode without preventing the adapter from operating normally.
5921 * (airmon-ng doesn't appear to use that, though.)
5923 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5924 * up, and if all drivers were converted to mac80211 drivers.
5926 * If interface {if} is a mac80211 driver, the file
5927 * /sys/class/net/{if}/phy80211 is a symlink to
5928 * /sys/class/ieee80211/{phydev}, for some {phydev}.
5930 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5931 * least, has a "wmaster0" device and a "wlan0" device; the
5932 * latter is the one with the IP address. Both show up in
5933 * "tcpdump -D" output. Capturing on the wmaster0 device
5934 * captures with 802.11 headers.
5936 * airmon-ng searches through /sys/class/net for devices named
5937 * monN, starting with mon0; as soon as one *doesn't* exist,
5938 * it chooses that as the monitor device name. If the "iw"
5939 * command exists, it does "iw dev {if} interface add {monif}
5940 * type monitor", where {monif} is the monitor device. It
5941 * then (sigh) sleeps .1 second, and then configures the
5942 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
5943 * is a file, it writes {mondev}, without a newline, to that file,
5944 * and again (sigh) sleeps .1 second, and then iwconfig's that
5945 * device into monitor mode and configures it up. Otherwise,
5946 * you can't do monitor mode.
5948 * All these devices are "glued" together by having the
5949 * /sys/class/net/{device}/phy80211 links pointing to the same
5950 * place, so, given a wmaster, wlan, or mon device, you can
5951 * find the other devices by looking for devices with
5952 * the same phy80211 link.
5954 * To turn monitor mode off, delete the monitor interface,
5955 * either with "iw dev {monif} interface del" or by sending
5956 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
5958 * Note: if you try to create a monitor device named "monN", and
5959 * there's already a "monN" device, it fails, as least with
5960 * the netlink interface (which is what iw uses), with a return
5961 * value of -ENFILE. (Return values are negative errnos.) We
5962 * could probably use that to find an unused device.
5964 struct pcap_linux *handlep = handle->priv;
5967 struct iw_priv_args *priv;
5968 monitor_type montype;
5977 * Does this device *support* the Wireless Extensions?
5979 err = has_wext(sock_fd, device, handle->errbuf);
5981 return err; /* either it doesn't or the device doesn't even exist */
5983 * Start out assuming we have no private extensions to control
5986 montype = MONITOR_WEXT;
5990 * Try to get all the Wireless Extensions private ioctls
5991 * supported by this device.
5993 * First, get the size of the buffer we need, by supplying no
5994 * buffer and a length of 0. If the device supports private
5995 * ioctls, it should return E2BIG, with ireq.u.data.length set
5996 * to the length we need. If it doesn't support them, it should
5997 * return EOPNOTSUPP.
5999 memset(&ireq, 0, sizeof ireq);
6000 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6001 sizeof ireq.ifr_ifrn.ifrn_name);
6002 ireq.u.data.pointer = (void *)args;
6003 ireq.u.data.length = 0;
6004 ireq.u.data.flags = 0;
6005 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
6006 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6007 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
6011 if (errno != EOPNOTSUPP) {
6013 * OK, it's not as if there are no private ioctls.
6015 if (errno != E2BIG) {
6019 pcap_fmt_errmsg_for_errno(handle->errbuf,
6020 PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWPRIV", device);
6025 * OK, try to get the list of private ioctls.
6027 priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
6029 pcap_fmt_errmsg_for_errno(handle->errbuf,
6030 PCAP_ERRBUF_SIZE, errno, "malloc");
6033 ireq.u.data.pointer = (void *)priv;
6034 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
6035 pcap_fmt_errmsg_for_errno(handle->errbuf,
6036 PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWPRIV", device);
6042 * Look for private ioctls to turn monitor mode on or, if
6043 * monitor mode is on, to set the header type.
6045 for (i = 0; i < ireq.u.data.length; i++) {
6046 if (strcmp(priv[i].name, "monitor_type") == 0) {
6048 * Hostap driver, use this one.
6049 * Set monitor mode first.
6050 * You can set it to 0 to get DLT_IEEE80211,
6051 * 1 to get DLT_PRISM, 2 to get
6052 * DLT_IEEE80211_RADIO_AVS, and, with more
6053 * recent versions of the driver, 3 to get
6054 * DLT_IEEE80211_RADIO.
6056 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6058 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6060 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6062 montype = MONITOR_HOSTAP;
6066 if (strcmp(priv[i].name, "set_prismhdr") == 0) {
6068 * Prism54 driver, use this one.
6069 * Set monitor mode first.
6070 * You can set it to 2 to get DLT_IEEE80211
6071 * or 3 or get DLT_PRISM.
6073 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6075 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6077 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6079 montype = MONITOR_PRISM54;
6083 if (strcmp(priv[i].name, "forceprismheader") == 0) {
6085 * RT2570 driver, use this one.
6086 * Do this after turning monitor mode on.
6087 * You can set it to 1 to get DLT_PRISM or 2
6088 * to get DLT_IEEE80211.
6090 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6092 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6094 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6096 montype = MONITOR_RT2570;
6100 if (strcmp(priv[i].name, "forceprism") == 0) {
6102 * RT73 driver, use this one.
6103 * Do this after turning monitor mode on.
6104 * Its argument is a *string*; you can
6105 * set it to "1" to get DLT_PRISM or "2"
6106 * to get DLT_IEEE80211.
6108 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
6110 if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
6112 montype = MONITOR_RT73;
6116 if (strcmp(priv[i].name, "prismhdr") == 0) {
6118 * One of the RTL8xxx drivers, use this one.
6119 * It can only be done after monitor mode
6120 * has been turned on. You can set it to 1
6121 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
6123 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6125 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6127 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6129 montype = MONITOR_RTL8XXX;
6133 if (strcmp(priv[i].name, "rfmontx") == 0) {
6135 * RT2500 or RT61 driver, use this one.
6136 * It has one one-byte parameter; set
6137 * u.data.length to 1 and u.data.pointer to
6138 * point to the parameter.
6139 * It doesn't itself turn monitor mode on.
6140 * You can set it to 1 to allow transmitting
6141 * in monitor mode(?) and get DLT_IEEE80211,
6142 * or set it to 0 to disallow transmitting in
6143 * monitor mode(?) and get DLT_PRISM.
6145 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6147 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
6149 montype = MONITOR_RT2500;
6153 if (strcmp(priv[i].name, "monitor") == 0) {
6155 * Either ACX100 or hostap, use this one.
6156 * It turns monitor mode on.
6157 * If it takes two arguments, it's ACX100;
6158 * the first argument is 1 for DLT_PRISM
6159 * or 2 for DLT_IEEE80211, and the second
6160 * argument is the channel on which to
6161 * run. If it takes one argument, it's
6162 * HostAP, and the argument is 2 for
6163 * DLT_IEEE80211 and 3 for DLT_PRISM.
6165 * If we see this, we don't quit, as this
6166 * might be a version of the hostap driver
6167 * that also supports "monitor_type".
6169 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6171 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6173 switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
6176 montype = MONITOR_PRISM;
6181 montype = MONITOR_ACX100;
6194 * XXX - ipw3945? islism?
6200 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6201 sizeof ireq.ifr_ifrn.ifrn_name);
6202 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
6204 * We probably won't be able to set the mode, either.
6206 return PCAP_ERROR_RFMON_NOTSUP;
6210 * Is it currently in monitor mode?
6212 if (ireq.u.mode == IW_MODE_MONITOR) {
6214 * Yes. Just leave things as they are.
6215 * We don't offer multiple link-layer types, as
6216 * changing the link-layer type out from under
6217 * somebody else capturing in monitor mode would
6218 * be considered rude.
6223 * No. We have to put the adapter into rfmon mode.
6227 * If we haven't already done so, arrange to have
6228 * "pcap_close_all()" called when we exit.
6230 if (!pcap_do_addexit(handle)) {
6232 * "atexit()" failed; don't put the interface
6233 * in rfmon mode, just give up.
6235 return PCAP_ERROR_RFMON_NOTSUP;
6239 * Save the old mode.
6241 handlep->oldmode = ireq.u.mode;
6244 * Put the adapter in rfmon mode. How we do this depends
6245 * on whether we have a special private ioctl or not.
6247 if (montype == MONITOR_PRISM) {
6249 * We have the "monitor" private ioctl, but none of
6250 * the other private ioctls. Use this, and select
6253 * If it fails, just fall back on SIOCSIWMODE.
6255 memset(&ireq, 0, sizeof ireq);
6256 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6257 sizeof ireq.ifr_ifrn.ifrn_name);
6258 ireq.u.data.length = 1; /* 1 argument */
6259 args[0] = 3; /* request Prism header */
6260 memcpy(ireq.u.name, args, sizeof (int));
6261 if (ioctl(sock_fd, cmd, &ireq) != -1) {
6264 * Note that we have to put the old mode back
6265 * when we close the device.
6267 handlep->must_do_on_close |= MUST_CLEAR_RFMON;
6270 * Add this to the list of pcaps to close
6273 pcap_add_to_pcaps_to_close(handle);
6279 * Failure. Fall back on SIOCSIWMODE.
6284 * First, take the interface down if it's up; otherwise, we
6287 memset(&ifr, 0, sizeof(ifr));
6288 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6289 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
6290 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
6291 errno, "%s: Can't get flags", device);
6295 if (ifr.ifr_flags & IFF_UP) {
6296 oldflags = ifr.ifr_flags;
6297 ifr.ifr_flags &= ~IFF_UP;
6298 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
6299 pcap_fmt_errmsg_for_errno(handle->errbuf,
6300 PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
6307 * Then turn monitor mode on.
6309 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6310 sizeof ireq.ifr_ifrn.ifrn_name);
6311 ireq.u.mode = IW_MODE_MONITOR;
6312 if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
6314 * Scientist, you've failed.
6315 * Bring the interface back up if we shut it down.
6317 ifr.ifr_flags = oldflags;
6318 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
6319 pcap_fmt_errmsg_for_errno(handle->errbuf,
6320 PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
6324 return PCAP_ERROR_RFMON_NOTSUP;
6328 * XXX - airmon-ng does "iwconfig {if} key off" after setting
6329 * monitor mode and setting the channel, and then does
6334 * Now select the appropriate radio header.
6340 * We don't have any private ioctl to set the header.
6344 case MONITOR_HOSTAP:
6346 * Try to select the radiotap header.
6348 memset(&ireq, 0, sizeof ireq);
6349 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6350 sizeof ireq.ifr_ifrn.ifrn_name);
6351 args[0] = 3; /* request radiotap header */
6352 memcpy(ireq.u.name, args, sizeof (int));
6353 if (ioctl(sock_fd, cmd, &ireq) != -1)
6354 break; /* success */
6357 * That failed. Try to select the AVS header.
6359 memset(&ireq, 0, sizeof ireq);
6360 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6361 sizeof ireq.ifr_ifrn.ifrn_name);
6362 args[0] = 2; /* request AVS header */
6363 memcpy(ireq.u.name, args, sizeof (int));
6364 if (ioctl(sock_fd, cmd, &ireq) != -1)
6365 break; /* success */
6368 * That failed. Try to select the Prism header.
6370 memset(&ireq, 0, sizeof ireq);
6371 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6372 sizeof ireq.ifr_ifrn.ifrn_name);
6373 args[0] = 1; /* request Prism header */
6374 memcpy(ireq.u.name, args, sizeof (int));
6375 ioctl(sock_fd, cmd, &ireq);
6380 * The private ioctl failed.
6384 case MONITOR_PRISM54:
6386 * Select the Prism header.
6388 memset(&ireq, 0, sizeof ireq);
6389 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6390 sizeof ireq.ifr_ifrn.ifrn_name);
6391 args[0] = 3; /* request Prism header */
6392 memcpy(ireq.u.name, args, sizeof (int));
6393 ioctl(sock_fd, cmd, &ireq);
6396 case MONITOR_ACX100:
6398 * Get the current channel.
6400 memset(&ireq, 0, sizeof ireq);
6401 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6402 sizeof ireq.ifr_ifrn.ifrn_name);
6403 if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
6404 pcap_fmt_errmsg_for_errno(handle->errbuf,
6405 PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWFREQ", device);
6408 channel = ireq.u.freq.m;
6411 * Select the Prism header, and set the channel to the
6414 memset(&ireq, 0, sizeof ireq);
6415 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6416 sizeof ireq.ifr_ifrn.ifrn_name);
6417 args[0] = 1; /* request Prism header */
6418 args[1] = channel; /* set channel */
6419 memcpy(ireq.u.name, args, 2*sizeof (int));
6420 ioctl(sock_fd, cmd, &ireq);
6423 case MONITOR_RT2500:
6425 * Disallow transmission - that turns on the
6428 memset(&ireq, 0, sizeof ireq);
6429 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6430 sizeof ireq.ifr_ifrn.ifrn_name);
6431 args[0] = 0; /* disallow transmitting */
6432 memcpy(ireq.u.name, args, sizeof (int));
6433 ioctl(sock_fd, cmd, &ireq);
6436 case MONITOR_RT2570:
6438 * Force the Prism header.
6440 memset(&ireq, 0, sizeof ireq);
6441 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6442 sizeof ireq.ifr_ifrn.ifrn_name);
6443 args[0] = 1; /* request Prism header */
6444 memcpy(ireq.u.name, args, sizeof (int));
6445 ioctl(sock_fd, cmd, &ireq);
6450 * Force the Prism header.
6452 memset(&ireq, 0, sizeof ireq);
6453 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6454 sizeof ireq.ifr_ifrn.ifrn_name);
6455 ireq.u.data.length = 1; /* 1 argument */
6456 ireq.u.data.pointer = "1";
6457 ireq.u.data.flags = 0;
6458 ioctl(sock_fd, cmd, &ireq);
6461 case MONITOR_RTL8XXX:
6463 * Force the Prism header.
6465 memset(&ireq, 0, sizeof ireq);
6466 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6467 sizeof ireq.ifr_ifrn.ifrn_name);
6468 args[0] = 1; /* request Prism header */
6469 memcpy(ireq.u.name, args, sizeof (int));
6470 ioctl(sock_fd, cmd, &ireq);
6475 * Now bring the interface back up if we brought it down.
6477 if (oldflags != 0) {
6478 ifr.ifr_flags = oldflags;
6479 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
6480 pcap_fmt_errmsg_for_errno(handle->errbuf,
6481 PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
6485 * At least try to restore the old mode on the
6488 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
6490 * Scientist, you've failed.
6493 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
6494 "Please adjust manually.\n",
6502 * Note that we have to put the old mode back when we
6505 handlep->must_do_on_close |= MUST_CLEAR_RFMON;
6508 * Add this to the list of pcaps to close when we exit.
6510 pcap_add_to_pcaps_to_close(handle);
6514 #endif /* IW_MODE_MONITOR */
6517 * Try various mechanisms to enter monitor mode.
6520 enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
6522 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
6527 ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
6529 return ret; /* error attempting to do so */
6531 return 1; /* success */
6532 #endif /* HAVE_LIBNL */
6534 #ifdef IW_MODE_MONITOR
6535 ret = enter_rfmon_mode_wext(handle, sock_fd, device);
6537 return ret; /* error attempting to do so */
6539 return 1; /* success */
6540 #endif /* IW_MODE_MONITOR */
6543 * Either none of the mechanisms we know about work or none
6544 * of those mechanisms are available, so we can't do monitor
6550 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
6552 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
6554 static const struct {
6555 int soft_timestamping_val;
6556 int pcap_tstamp_val;
6557 } sof_ts_type_map[3] = {
6558 { SOF_TIMESTAMPING_SOFTWARE, PCAP_TSTAMP_HOST },
6559 { SOF_TIMESTAMPING_SYS_HARDWARE, PCAP_TSTAMP_ADAPTER },
6560 { SOF_TIMESTAMPING_RAW_HARDWARE, PCAP_TSTAMP_ADAPTER_UNSYNCED }
6562 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
6565 * Set the list of time stamping types to include all types.
6568 iface_set_all_ts_types(pcap_t *handle)
6572 handle->tstamp_type_count = NUM_SOF_TIMESTAMPING_TYPES;
6573 handle->tstamp_type_list = malloc(NUM_SOF_TIMESTAMPING_TYPES * sizeof(u_int));
6574 for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++)
6575 handle->tstamp_type_list[i] = sof_ts_type_map[i].pcap_tstamp_val;
6578 #ifdef ETHTOOL_GET_TS_INFO
6580 * Get a list of time stamping capabilities.
6583 iface_ethtool_get_ts_info(const char *device, pcap_t *handle, char *ebuf)
6587 struct ethtool_ts_info info;
6592 * This doesn't apply to the "any" device; you can't say "turn on
6593 * hardware time stamping for all devices that exist now and arrange
6594 * that it be turned on for any device that appears in the future",
6595 * and not all devices even necessarily *support* hardware time
6596 * stamping, so don't report any time stamp types.
6598 if (strcmp(device, "any") == 0) {
6599 handle->tstamp_type_list = NULL;
6604 * Create a socket from which to fetch time stamping capabilities.
6606 fd = socket(PF_UNIX, SOCK_RAW, 0);
6608 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
6609 errno, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
6613 memset(&ifr, 0, sizeof(ifr));
6614 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6615 memset(&info, 0, sizeof(info));
6616 info.cmd = ETHTOOL_GET_TS_INFO;
6617 ifr.ifr_data = (caddr_t)&info;
6618 if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) {
6619 int save_errno = errno;
6622 switch (save_errno) {
6627 * OK, this OS version or driver doesn't support
6628 * asking for the time stamping types, so let's
6629 * just return all the possible types.
6631 iface_set_all_ts_types(handle);
6636 * OK, no such device.
6637 * The user will find that out when they try to
6638 * activate the device; just return an empty
6639 * list of time stamp types.
6641 handle->tstamp_type_list = NULL;
6648 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
6650 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
6658 * Do we support hardware time stamping of *all* packets?
6660 if (!(info.rx_filters & (1 << HWTSTAMP_FILTER_ALL))) {
6662 * No, so don't report any time stamp types.
6664 * XXX - some devices either don't report
6665 * HWTSTAMP_FILTER_ALL when they do support it, or
6666 * report HWTSTAMP_FILTER_ALL but map it to only
6667 * time stamping a few PTP packets. See
6668 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
6670 handle->tstamp_type_list = NULL;
6675 for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
6676 if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val)
6679 handle->tstamp_type_count = num_ts_types;
6680 if (num_ts_types != 0) {
6681 handle->tstamp_type_list = malloc(num_ts_types * sizeof(u_int));
6682 for (i = 0, j = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
6683 if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val) {
6684 handle->tstamp_type_list[j] = sof_ts_type_map[i].pcap_tstamp_val;
6689 handle->tstamp_type_list = NULL;
6693 #else /* ETHTOOL_GET_TS_INFO */
6695 iface_ethtool_get_ts_info(const char *device, pcap_t *handle, char *ebuf _U_)
6698 * This doesn't apply to the "any" device; you can't say "turn on
6699 * hardware time stamping for all devices that exist now and arrange
6700 * that it be turned on for any device that appears in the future",
6701 * and not all devices even necessarily *support* hardware time
6702 * stamping, so don't report any time stamp types.
6704 if (strcmp(device, "any") == 0) {
6705 handle->tstamp_type_list = NULL;
6710 * We don't have an ioctl to use to ask what's supported,
6711 * so say we support everything.
6713 iface_set_all_ts_types(handle);
6716 #endif /* ETHTOOL_GET_TS_INFO */
6718 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6720 #ifdef HAVE_PACKET_RING
6722 * Find out if we have any form of fragmentation/reassembly offloading.
6724 * We do so using SIOCETHTOOL checking for various types of offloading;
6725 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6726 * of the types of offloading, there's nothing we can do to check, so
6727 * we just say "no, we don't".
6729 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
6730 * indications that the operation isn't supported. We do EPERM
6731 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
6732 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
6733 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
6734 * and 3) does the "is this permitted" check before doing the "is
6735 * this even supported" check, so it fails with "this is not permitted"
6736 * rather than "this is not even supported". To work around this
6737 * annoyance, we only treat EPERM as an error for the first feature,
6738 * and assume that they all do the same permission checks, so if the
6739 * first one is allowed all the others are allowed if supported.
6741 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6743 iface_ethtool_flag_ioctl(pcap_t *handle, int cmd, const char *cmdname,
6747 struct ethtool_value eval;
6749 memset(&ifr, 0, sizeof(ifr));
6750 pcap_strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
6753 ifr.ifr_data = (caddr_t)&eval;
6754 if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
6755 if (errno == EOPNOTSUPP || errno == EINVAL ||
6756 (errno == EPERM && eperm_ok)) {
6758 * OK, let's just return 0, which, in our
6759 * case, either means "no, what we're asking
6760 * about is not enabled" or "all the flags
6761 * are clear (i.e., nothing is enabled)".
6765 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
6766 errno, "%s: SIOCETHTOOL(%s) ioctl failed",
6767 handle->opt.device, cmdname);
6774 * XXX - it's annoying that we have to check for offloading at all, but,
6775 * given that we have to, it's still annoying that we have to check for
6776 * particular types of offloading, especially that shiny new types of
6777 * offloading may be added - and, worse, may not be checkable with
6778 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
6779 * theory, give those to you, but the actual flags being used are
6780 * opaque (defined in a non-uapi header), and there doesn't seem to
6781 * be any obvious way to ask the kernel what all the offloading flags
6782 * are - at best, you can ask for a set of strings(!) to get *names*
6783 * for various flags. (That whole mechanism appears to have been
6784 * designed for the sole purpose of letting ethtool report flags
6785 * by name and set flags by name, with the names having no semantics
6786 * ethtool understands.)
6789 iface_get_offload(pcap_t *handle)
6794 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO", 0);
6798 return 1; /* TCP segmentation offloading on */
6803 * XXX - will this cause large unsegmented packets to be
6804 * handed to PF_PACKET sockets on transmission? If not,
6805 * this need not be checked.
6807 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO", 0);
6811 return 1; /* generic segmentation offloading on */
6814 #ifdef ETHTOOL_GFLAGS
6815 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS", 0);
6818 if (ret & ETH_FLAG_LRO)
6819 return 1; /* large receive offloading on */
6824 * XXX - will this cause large reassembled packets to be
6825 * handed to PF_PACKET sockets on receipt? If not,
6826 * this need not be checked.
6828 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO", 0);
6832 return 1; /* generic (large) receive offloading on */
6837 * Do this one last, as support for it was removed in later
6838 * kernels, and it fails with EPERM on those kernels rather
6839 * than with EOPNOTSUPP (see explanation in comment for
6840 * iface_ethtool_flag_ioctl()).
6842 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO", 1);
6846 return 1; /* UDP fragmentation offloading on */
6851 #else /* SIOCETHTOOL */
6853 iface_get_offload(pcap_t *handle _U_)
6856 * XXX - do we need to get this information if we don't
6857 * have the ethtool ioctls? If so, how do we do that?
6861 #endif /* SIOCETHTOOL */
6863 #endif /* HAVE_PACKET_RING */
6865 #endif /* HAVE_PF_PACKET_SOCKETS */
6867 /* ===== Functions to interface to the older kernels ================== */
6870 * Try to open a packet socket using the old kernel interface.
6871 * Returns 1 on success and a PCAP_ERROR_ value on an error.
6874 activate_old(pcap_t *handle)
6876 struct pcap_linux *handlep = handle->priv;
6880 const char *device = handle->opt.device;
6881 struct utsname utsname;
6885 * PF_INET/SOCK_PACKET sockets must be bound to a device, so we
6886 * can't support the "any" device.
6888 if (strcmp(device, "any") == 0) {
6889 pcap_strlcpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
6894 /* Open the socket */
6895 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
6896 if (handle->fd == -1) {
6898 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
6900 if (err == EPERM || err == EACCES) {
6902 * You don't have permission to open the
6905 return PCAP_ERROR_PERM_DENIED;
6914 /* It worked - we are using the old interface */
6915 handlep->sock_packet = 1;
6917 /* ...which means we get the link-layer header. */
6918 handlep->cooked = 0;
6920 /* Bind to the given device */
6921 if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
6925 * Try to get the link-layer type.
6927 arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
6932 * Try to find the DLT_ type corresponding to that
6935 map_arphrd_to_dlt(handle, handle->fd, arptype, device, 0);
6936 if (handle->linktype == -1) {
6937 pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6938 "unknown arptype %d", arptype);
6942 /* Go to promisc mode if requested */
6944 if (handle->opt.promisc) {
6945 memset(&ifr, 0, sizeof(ifr));
6946 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6947 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
6948 pcap_fmt_errmsg_for_errno(handle->errbuf,
6949 PCAP_ERRBUF_SIZE, errno, "SIOCGIFFLAGS");
6952 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
6954 * Promiscuous mode isn't currently on,
6955 * so turn it on, and remember that
6956 * we should turn it off when the
6961 * If we haven't already done so, arrange
6962 * to have "pcap_close_all()" called when
6965 if (!pcap_do_addexit(handle)) {
6967 * "atexit()" failed; don't put
6968 * the interface in promiscuous
6969 * mode, just give up.
6974 ifr.ifr_flags |= IFF_PROMISC;
6975 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
6976 pcap_fmt_errmsg_for_errno(handle->errbuf,
6977 PCAP_ERRBUF_SIZE, errno, "SIOCSIFFLAGS");
6980 handlep->must_do_on_close |= MUST_CLEAR_PROMISC;
6983 * Add this to the list of pcaps
6984 * to close when we exit.
6986 pcap_add_to_pcaps_to_close(handle);
6991 * Compute the buffer size.
6993 * We're using SOCK_PACKET, so this might be a 2.0[.x]
6994 * kernel, and might require special handling - check.
6996 if (uname(&utsname) < 0 ||
6997 strncmp(utsname.release, "2.0", 3) == 0) {
6999 * Either we couldn't find out what kernel release
7000 * this is, or it's a 2.0[.x] kernel.
7002 * In the 2.0[.x] kernel, a "recvfrom()" on
7003 * a SOCK_PACKET socket, with MSG_TRUNC set, will
7004 * return the number of bytes read, so if we pass
7005 * a length based on the snapshot length, it'll
7006 * return the number of bytes from the packet
7007 * copied to userland, not the actual length
7010 * This means that, for example, the IP dissector
7011 * in tcpdump will get handed a packet length less
7012 * than the length in the IP header, and will
7013 * complain about "truncated-ip".
7015 * So we don't bother trying to copy from the
7016 * kernel only the bytes in which we're interested,
7017 * but instead copy them all, just as the older
7018 * versions of libpcap for Linux did.
7020 * The buffer therefore needs to be big enough to
7021 * hold the largest packet we can get from this
7022 * device. Unfortunately, we can't get the MRU
7023 * of the network; we can only get the MTU. The
7024 * MTU may be too small, in which case a packet larger
7025 * than the buffer size will be truncated *and* we
7026 * won't get the actual packet size.
7028 * However, if the snapshot length is larger than
7029 * the buffer size based on the MTU, we use the
7030 * snapshot length as the buffer size, instead;
7031 * this means that with a sufficiently large snapshot
7032 * length we won't artificially truncate packets
7033 * to the MTU-based size.
7035 * This mess just one of many problems with packet
7036 * capture on 2.0[.x] kernels; you really want a
7037 * 2.2[.x] or later kernel if you want packet capture
7040 mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
7043 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
7044 if (handle->bufsize < (u_int)handle->snapshot)
7045 handle->bufsize = (u_int)handle->snapshot;
7048 * This is a 2.2[.x] or later kernel.
7050 * We can safely pass "recvfrom()" a byte count
7051 * based on the snapshot length.
7053 * XXX - this "should not happen", as 2.2[.x]
7054 * kernels all have PF_PACKET sockets, and there's
7055 * no configuration option to disable them without
7056 * disabling SOCK_PACKET sockets, because
7057 * SOCK_PACKET sockets are implemented in the same
7058 * source file, net/packet/af_packet.c. There *is*
7059 * an option to disable SOCK_PACKET sockets so that
7060 * you only have PF_PACKET sockets, and the kernel
7061 * will log warning messages for code that uses
7062 * "obsolete (PF_INET,SOCK_PACKET)".
7064 handle->bufsize = (u_int)handle->snapshot;
7068 * Default value for offset to align link-layer payload
7069 * on a 4-byte boundary.
7074 * SOCK_PACKET sockets don't supply information from
7075 * stripped VLAN tags.
7077 handlep->vlan_offset = -1; /* unknown */
7083 * Bind the socket associated with FD to the given device using the
7084 * interface of the old kernels.
7087 iface_bind_old(int fd, const char *device, char *ebuf)
7089 struct sockaddr saddr;
7091 socklen_t errlen = sizeof(err);
7093 memset(&saddr, 0, sizeof(saddr));
7094 pcap_strlcpy(saddr.sa_data, device, sizeof(saddr.sa_data));
7095 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
7096 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7101 /* Any pending errors, e.g., network is down? */
7103 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
7104 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7105 errno, "getsockopt (SO_ERROR)");
7110 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7119 /* ===== System calls available on all supported kernels ============== */
7122 * Query the kernel for the MTU of the given interface.
7125 iface_get_mtu(int fd, const char *device, char *ebuf)
7130 return BIGGER_THAN_ALL_MTUS;
7132 memset(&ifr, 0, sizeof(ifr));
7133 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
7135 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
7136 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7137 errno, "SIOCGIFMTU");
7145 * Get the hardware type of the given interface as ARPHRD_xxx constant.
7148 iface_get_arptype(int fd, const char *device, char *ebuf)
7153 memset(&ifr, 0, sizeof(ifr));
7154 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
7156 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
7157 if (errno == ENODEV) {
7161 ret = PCAP_ERROR_NO_SUCH_DEVICE;
7164 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7165 errno, "SIOCGIFHWADDR");
7169 return ifr.ifr_hwaddr.sa_family;
7172 #ifdef SO_ATTACH_FILTER
7174 fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
7176 struct pcap_linux *handlep = handle->priv;
7179 register struct bpf_insn *p;
7184 * Make a copy of the filter, and modify that copy if
7187 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
7188 len = handle->fcode.bf_len;
7189 f = (struct bpf_insn *)malloc(prog_size);
7191 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
7195 memcpy(f, handle->fcode.bf_insns, prog_size);
7197 fcode->filter = (struct sock_filter *) f;
7199 for (i = 0; i < len; ++i) {
7202 * What type of instruction is this?
7204 switch (BPF_CLASS(p->code)) {
7208 * It's a return instruction; are we capturing
7209 * in memory-mapped mode?
7213 * No; is the snapshot length a constant,
7214 * rather than the contents of the
7217 if (BPF_MODE(p->code) == BPF_K) {
7219 * Yes - if the value to be returned,
7220 * i.e. the snapshot length, is
7221 * anything other than 0, make it
7222 * MAXIMUM_SNAPLEN, so that the packet
7223 * is truncated by "recvfrom()",
7224 * not by the filter.
7226 * XXX - there's nothing we can
7227 * easily do if it's getting the
7228 * value from the accumulator; we'd
7229 * have to insert code to force
7230 * non-zero values to be
7234 p->k = MAXIMUM_SNAPLEN;
7242 * It's a load instruction; is it loading
7245 switch (BPF_MODE(p->code)) {
7251 * Yes; are we in cooked mode?
7253 if (handlep->cooked) {
7255 * Yes, so we need to fix this
7258 if (fix_offset(handle, p) < 0) {
7260 * We failed to do so.
7261 * Return 0, so our caller
7262 * knows to punt to userland.
7272 return 1; /* we succeeded */
7276 fix_offset(pcap_t *handle, struct bpf_insn *p)
7279 * Existing references to auxiliary data shouldn't be adjusted.
7281 * Note that SKF_AD_OFF is negative, but p->k is unsigned, so
7282 * we use >= and cast SKF_AD_OFF to unsigned.
7284 if (p->k >= (bpf_u_int32)SKF_AD_OFF)
7286 if (handle->linktype == DLT_LINUX_SLL2) {
7288 * What's the offset?
7290 if (p->k >= SLL2_HDR_LEN) {
7292 * It's within the link-layer payload; that starts
7293 * at an offset of 0, as far as the kernel packet
7294 * filter is concerned, so subtract the length of
7295 * the link-layer header.
7297 p->k -= SLL2_HDR_LEN;
7298 } else if (p->k == 0) {
7300 * It's the protocol field; map it to the
7301 * special magic kernel offset for that field.
7303 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
7304 } else if (p->k == 10) {
7306 * It's the packet type field; map it to the
7307 * special magic kernel offset for that field.
7309 p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
7310 } else if ((bpf_int32)(p->k) > 0) {
7312 * It's within the header, but it's not one of
7313 * those fields; we can't do that in the kernel,
7314 * so punt to userland.
7320 * What's the offset?
7322 if (p->k >= SLL_HDR_LEN) {
7324 * It's within the link-layer payload; that starts
7325 * at an offset of 0, as far as the kernel packet
7326 * filter is concerned, so subtract the length of
7327 * the link-layer header.
7329 p->k -= SLL_HDR_LEN;
7330 } else if (p->k == 0) {
7332 * It's the packet type field; map it to the
7333 * special magic kernel offset for that field.
7335 p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
7336 } else if (p->k == 14) {
7338 * It's the protocol field; map it to the
7339 * special magic kernel offset for that field.
7341 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
7342 } else if ((bpf_int32)(p->k) > 0) {
7344 * It's within the header, but it's not one of
7345 * those fields; we can't do that in the kernel,
7346 * so punt to userland.
7355 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
7357 int total_filter_on = 0;
7363 * The socket filter code doesn't discard all packets queued
7364 * up on the socket when the filter is changed; this means
7365 * that packets that don't match the new filter may show up
7366 * after the new filter is put onto the socket, if those
7367 * packets haven't yet been read.
7369 * This means, for example, that if you do a tcpdump capture
7370 * with a filter, the first few packets in the capture might
7371 * be packets that wouldn't have passed the filter.
7373 * We therefore discard all packets queued up on the socket
7374 * when setting a kernel filter. (This isn't an issue for
7375 * userland filters, as the userland filtering is done after
7376 * packets are queued up.)
7378 * To flush those packets, we put the socket in read-only mode,
7379 * and read packets from the socket until there are no more to
7382 * In order to keep that from being an infinite loop - i.e.,
7383 * to keep more packets from arriving while we're draining
7384 * the queue - we put the "total filter", which is a filter
7385 * that rejects all packets, onto the socket before draining
7388 * This code deliberately ignores any errors, so that you may
7389 * get bogus packets if an error occurs, rather than having
7390 * the filtering done in userland even if it could have been
7391 * done in the kernel.
7393 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
7394 &total_fcode, sizeof(total_fcode)) == 0) {
7398 * Note that we've put the total filter onto the socket.
7400 total_filter_on = 1;
7403 * Save the socket's current mode, and put it in
7404 * non-blocking mode; we drain it by reading packets
7405 * until we get an error (which is normally a
7406 * "nothing more to be read" error).
7408 save_mode = fcntl(handle->fd, F_GETFL, 0);
7409 if (save_mode == -1) {
7410 pcap_fmt_errmsg_for_errno(handle->errbuf,
7411 PCAP_ERRBUF_SIZE, errno,
7412 "can't get FD flags when changing filter");
7415 if (fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) < 0) {
7416 pcap_fmt_errmsg_for_errno(handle->errbuf,
7417 PCAP_ERRBUF_SIZE, errno,
7418 "can't set nonblocking mode when changing filter");
7421 while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0)
7424 if (save_errno != EAGAIN) {
7428 * If we can't restore the mode or reset the
7429 * kernel filter, there's nothing we can do.
7431 (void)fcntl(handle->fd, F_SETFL, save_mode);
7432 (void)reset_kernel_filter(handle);
7433 pcap_fmt_errmsg_for_errno(handle->errbuf,
7434 PCAP_ERRBUF_SIZE, save_errno,
7435 "recv failed when changing filter");
7438 if (fcntl(handle->fd, F_SETFL, save_mode) == -1) {
7439 pcap_fmt_errmsg_for_errno(handle->errbuf,
7440 PCAP_ERRBUF_SIZE, errno,
7441 "can't restore FD flags when changing filter");
7447 * Now attach the new filter.
7449 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
7450 fcode, sizeof(*fcode));
7451 if (ret == -1 && total_filter_on) {
7453 * Well, we couldn't set that filter on the socket,
7454 * but we could set the total filter on the socket.
7456 * This could, for example, mean that the filter was
7457 * too big to put into the kernel, so we'll have to
7458 * filter in userland; in any case, we'll be doing
7459 * filtering in userland, so we need to remove the
7460 * total filter so we see packets.
7465 * If this fails, we're really screwed; we have the
7466 * total filter on the socket, and it won't come off.
7467 * Report it as a fatal error.
7469 if (reset_kernel_filter(handle) == -1) {
7470 pcap_fmt_errmsg_for_errno(handle->errbuf,
7471 PCAP_ERRBUF_SIZE, errno,
7472 "can't remove kernel total filter");
7473 return -2; /* fatal error */
7482 reset_kernel_filter(pcap_t *handle)
7486 * setsockopt() barfs unless it get a dummy parameter.
7487 * valgrind whines unless the value is initialized,
7488 * as it has no idea that setsockopt() ignores its
7493 ret = setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
7494 &dummy, sizeof(dummy));
7496 * Ignore ENOENT - it means "we don't have a filter", so there
7497 * was no filter to remove, and there's still no filter.
7499 * Also ignore ENONET, as a lot of kernel versions had a
7500 * typo where ENONET, rather than ENOENT, was returned.
7502 if (ret == -1 && errno != ENOENT && errno != ENONET)
7509 pcap_set_protocol_linux(pcap_t *p, int protocol)
7511 if (pcap_check_activated(p))
7512 return (PCAP_ERROR_ACTIVATED);
7513 p->opt.protocol = protocol;
7518 * Libpcap version string.
7521 pcap_lib_version(void)
7523 #ifdef HAVE_PACKET_RING
7524 #if defined(HAVE_TPACKET3)
7525 return (PCAP_VERSION_STRING " (with TPACKET_V3)");
7526 #elif defined(HAVE_TPACKET2)
7527 return (PCAP_VERSION_STRING " (with TPACKET_V2)");
7529 return (PCAP_VERSION_STRING " (with TPACKET_V1)");
7532 return (PCAP_VERSION_STRING " (without TPACKET)");