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.
126 #include <sys/stat.h>
127 #include <sys/socket.h>
128 #include <sys/ioctl.h>
129 #include <sys/utsname.h>
130 #include <sys/mman.h>
131 #include <linux/if.h>
132 #include <linux/if_packet.h>
133 #include <linux/sockios.h>
134 #include <netinet/in.h>
135 #include <linux/if_ether.h>
136 #include <linux/if_arp.h>
139 #ifdef HAVE_SYS_EVENTFD_H
140 #include <sys/eventfd.h>
143 #include "pcap-int.h"
144 #include "pcap/sll.h"
145 #include "pcap/vlan.h"
147 #include "diag-control.h"
150 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
151 * sockets rather than SOCK_PACKET sockets.
153 * To use them, we include <linux/if_packet.h> rather than
154 * <netpacket/packet.h>; we do so because
156 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
157 * later kernels and libc5, and don't provide a <netpacket/packet.h>
160 * not all versions of glibc2 have a <netpacket/packet.h> file
161 * that defines stuff needed for some of the 2.4-or-later-kernel
162 * features, so if the system has a 2.4 or later kernel, we
163 * still can't use those features.
165 * We're already including a number of other <linux/XXX.h> headers, and
166 * this code is Linux-specific (no other OS has PF_PACKET sockets as
167 * a raw packet capture mechanism), so it's not as if you gain any
168 * useful portability by using <netpacket/packet.h>
170 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
171 * isn't defined? It only defines one data structure in 2.0.x, so
172 * it shouldn't cause any problems.
175 # include <linux/if_packet.h>
178 * On at least some Linux distributions (for example, Red Hat 5.2),
179 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
180 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
181 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
182 * the PACKET_xxx stuff.
184 * So we check whether PACKET_HOST is defined, and assume that we have
185 * PF_PACKET sockets only if it is defined.
188 # define HAVE_PF_PACKET_SOCKETS
189 # ifdef PACKET_AUXDATA
190 # define HAVE_PACKET_AUXDATA
191 # endif /* PACKET_AUXDATA */
192 # endif /* PACKET_HOST */
195 /* check for memory mapped access avaibility. We assume every needed
196 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
197 * uses many ring related structs and macros */
198 # ifdef PCAP_SUPPORT_PACKET_RING
199 # ifdef TPACKET_HDRLEN
200 # define HAVE_PACKET_RING
201 # ifdef TPACKET3_HDRLEN
202 # define HAVE_TPACKET3
203 # endif /* TPACKET3_HDRLEN */
204 # ifdef TPACKET2_HDRLEN
205 # define HAVE_TPACKET2
206 # else /* TPACKET2_HDRLEN */
207 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
208 # endif /* TPACKET2_HDRLEN */
209 # endif /* TPACKET_HDRLEN */
210 # endif /* PCAP_SUPPORT_PACKET_RING */
211 #endif /* PF_PACKET */
213 #ifdef SO_ATTACH_FILTER
214 #include <linux/types.h>
215 #include <linux/filter.h>
218 #ifdef HAVE_LINUX_NET_TSTAMP_H
219 #include <linux/net_tstamp.h>
222 #ifdef HAVE_LINUX_SOCKIOS_H
223 #include <linux/sockios.h>
226 #ifdef HAVE_LINUX_IF_BONDING_H
227 #include <linux/if_bonding.h>
230 * The ioctl code to use to check whether a device is a bonding device.
232 #if defined(SIOCBONDINFOQUERY)
233 #define BOND_INFO_QUERY_IOCTL SIOCBONDINFOQUERY
234 #elif defined(BOND_INFO_QUERY_OLD)
235 #define BOND_INFO_QUERY_IOCTL BOND_INFO_QUERY_OLD
237 #endif /* HAVE_LINUX_IF_BONDING_H */
240 * Got Wireless Extensions?
242 #ifdef HAVE_LINUX_WIRELESS_H
243 #include <linux/wireless.h>
244 #endif /* HAVE_LINUX_WIRELESS_H */
250 #include <linux/nl80211.h>
252 #include <netlink/genl/genl.h>
253 #include <netlink/genl/family.h>
254 #include <netlink/genl/ctrl.h>
255 #include <netlink/msg.h>
256 #include <netlink/attr.h>
257 #endif /* HAVE_LIBNL */
260 * Got ethtool support?
262 #ifdef HAVE_LINUX_ETHTOOL_H
263 #include <linux/ethtool.h>
266 #ifndef HAVE_SOCKLEN_T
267 typedef int socklen_t
;
272 * This is being compiled on a system that lacks MSG_TRUNC; define it
273 * with the value it has in the 2.2 and later kernels, so that, on
274 * those kernels, when we pass it in the flags argument to "recvfrom()"
275 * we're passing the right value and thus get the MSG_TRUNC behavior
276 * we want. (We don't get that behavior on 2.0[.x] kernels, because
277 * they didn't support MSG_TRUNC.)
279 #define MSG_TRUNC 0x20
284 * This is being compiled on a system that lacks SOL_PACKET; define it
285 * with the value it has in the 2.2 and later kernels, so that we can
286 * set promiscuous mode in the good modern way rather than the old
287 * 2.0-kernel crappy way.
289 #define SOL_PACKET 263
292 #define MAX_LINKHEADER_SIZE 256
295 * When capturing on all interfaces we use this as the buffer size.
296 * Should be bigger then all MTUs that occur in real life.
297 * 64kB should be enough for now.
299 #define BIGGER_THAN_ALL_MTUS (64*1024)
302 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
305 u_int packets_read
; /* count of packets read with recvfrom() */
306 long proc_dropped
; /* packets reported dropped by /proc/net/dev */
307 struct pcap_stat stat
;
309 char *device
; /* device name */
310 int filter_in_userland
; /* must filter in userland */
311 int blocks_to_filter_in_userland
;
312 int must_do_on_close
; /* stuff we must do when we close */
313 int timeout
; /* timeout for buffering */
314 int sock_packet
; /* using Linux 2.0 compatible interface */
315 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
316 int ifindex
; /* interface index of device we're bound to */
317 int lo_ifindex
; /* interface index of the loopback device */
318 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
319 char *mondevice
; /* mac80211 monitor device we created */
320 u_char
*mmapbuf
; /* memory-mapped region pointer */
321 size_t mmapbuflen
; /* size of region */
322 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
323 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
324 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
325 u_char
*oneshot_buffer
; /* buffer for copy of packet */
326 int poll_timeout
; /* timeout to use in poll() */
328 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
329 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
331 #ifdef HAVE_SYS_EVENTFD_H
332 int poll_breakloop_fd
; /* fd to an eventfd to break from blocking operations */
337 * Stuff to do when we close.
339 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
340 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
341 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
344 * Prototypes for internal functions and methods.
346 static int get_if_flags(const char *, bpf_u_int32
*, char *);
347 static int is_wifi(int, const char *);
348 static void map_arphrd_to_dlt(pcap_t
*, int, int, const char *, int);
349 static int pcap_activate_linux(pcap_t
*);
350 static int activate_old(pcap_t
*, int);
351 #ifdef HAVE_PF_PACKET_SOCKETS
352 static int activate_new(pcap_t
*, int);
353 #ifdef HAVE_PACKET_RING
354 static int activate_mmap(pcap_t
*, int *);
356 #endif /* HAVE_PF_PACKET_SOCKETS */
357 static int pcap_can_set_rfmon_linux(pcap_t
*);
358 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
359 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
360 static int pcap_inject_linux(pcap_t
*, const void *, int);
361 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
362 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
363 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
364 static int pcap_set_datalink_linux(pcap_t
*, int);
365 static void pcap_cleanup_linux(pcap_t
*);
368 * This is what the header structure looks like in a 64-bit kernel;
369 * we use this, rather than struct tpacket_hdr, if we're using
370 * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
372 struct tpacket_hdr_64
{
375 unsigned int tp_snaplen
;
376 unsigned short tp_mac
;
377 unsigned short tp_net
;
379 unsigned int tp_usec
;
383 * We use this internally as the tpacket version for TPACKET_V1 in
384 * 32-bit code on a 64-bit kernel.
386 #define TPACKET_V1_64 99
389 struct tpacket_hdr
*h1
;
390 struct tpacket_hdr_64
*h1_64
;
392 struct tpacket2_hdr
*h2
;
395 struct tpacket_block_desc
*h3
;
400 #ifdef HAVE_PACKET_RING
401 #define RING_GET_FRAME_AT(h, offset) (((union thdr **)h->buffer)[(offset)])
402 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
404 static void destroy_ring(pcap_t
*handle
);
405 static int create_ring(pcap_t
*handle
, int *status
);
406 static int prepare_tpacket_socket(pcap_t
*handle
);
407 static void pcap_cleanup_linux_mmap(pcap_t
*);
408 static int pcap_read_linux_mmap_v1(pcap_t
*, int, pcap_handler
, u_char
*);
409 static int pcap_read_linux_mmap_v1_64(pcap_t
*, int, pcap_handler
, u_char
*);
411 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
414 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
416 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
417 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
);
418 static int pcap_getnonblock_mmap(pcap_t
*p
);
419 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
420 const u_char
*bytes
);
424 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
425 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
426 * or "on VLAN 0". There is no flag set in the tp_status field to
427 * distinguish between them.
429 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
430 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
431 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
432 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
434 * With a pre-3.0 kernel, we cannot distinguish between packets with no
435 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
436 * there's nothing we can do about that.
438 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
439 * continue the behavior of earlier libpcaps, wherein we treated packets
440 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
441 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
442 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
443 * VLAN tags. This does the right thing on 3.0 and later kernels, and
444 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
446 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
447 * has that value in 3.0 and later kernels.
449 #ifdef TP_STATUS_VLAN_VALID
450 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
453 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
454 * so we testwith the value it has in the 3.0 and later kernels, so
455 * we can test it if we're running on a system that has it. (If we're
456 * running on a system that doesn't have it, it won't be set in the
457 * tp_status field, so the tests of it will always fail; that means
458 * we behave the way we did before we introduced this macro.)
460 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
463 #ifdef TP_STATUS_VLAN_TPID_VALID
464 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
466 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
470 * Wrap some ioctl calls
472 #ifdef HAVE_PF_PACKET_SOCKETS
473 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
474 #endif /* HAVE_PF_PACKET_SOCKETS */
475 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
476 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
477 #ifdef HAVE_PF_PACKET_SOCKETS
478 static int iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
);
479 #ifdef IW_MODE_MONITOR
480 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
481 #endif /* IW_MODE_MONITOR */
482 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
484 #endif /* HAVE_PF_PACKET_SOCKETS */
485 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
486 static int iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
,
489 #ifdef HAVE_PACKET_RING
490 static int iface_get_offload(pcap_t
*handle
);
492 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
494 #ifdef SO_ATTACH_FILTER
495 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
497 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
498 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
499 static int reset_kernel_filter(pcap_t
*handle
);
501 static struct sock_filter total_insn
502 = BPF_STMT(BPF_RET
| BPF_K
, 0);
503 static struct sock_fprog total_fcode
504 = { 1, &total_insn
};
505 #endif /* SO_ATTACH_FILTER */
507 static int iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
);
510 pcap_create_interface(const char *device
, char *ebuf
)
514 handle
= pcap_create_common(ebuf
, sizeof (struct pcap_linux
));
518 handle
->activate_op
= pcap_activate_linux
;
519 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
521 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
523 * See what time stamp types we support.
525 if (iface_ethtool_get_ts_info(device
, handle
, ebuf
) == -1) {
531 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
533 * We claim that we support microsecond and nanosecond time
536 * XXX - with adapter-supplied time stamps, can we choose
537 * microsecond or nanosecond time stamps on arbitrary
540 handle
->tstamp_precision_count
= 2;
541 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
542 if (handle
->tstamp_precision_list
== NULL
) {
543 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
548 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
549 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
550 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
552 #ifdef HAVE_SYS_EVENTFD_H
553 struct pcap_linux
*handlep
= handle
->priv
;
554 handlep
->poll_breakloop_fd
= eventfd(0, EFD_NONBLOCK
);
562 * If interface {if} is a mac80211 driver, the file
563 * /sys/class/net/{if}/phy80211 is a symlink to
564 * /sys/class/ieee80211/{phydev}, for some {phydev}.
566 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
567 * least, has a "wmaster0" device and a "wlan0" device; the
568 * latter is the one with the IP address. Both show up in
569 * "tcpdump -D" output. Capturing on the wmaster0 device
570 * captures with 802.11 headers.
572 * airmon-ng searches through /sys/class/net for devices named
573 * monN, starting with mon0; as soon as one *doesn't* exist,
574 * it chooses that as the monitor device name. If the "iw"
575 * command exists, it does "iw dev {if} interface add {monif}
576 * type monitor", where {monif} is the monitor device. It
577 * then (sigh) sleeps .1 second, and then configures the
578 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
579 * is a file, it writes {mondev}, without a newline, to that file,
580 * and again (sigh) sleeps .1 second, and then iwconfig's that
581 * device into monitor mode and configures it up. Otherwise,
582 * you can't do monitor mode.
584 * All these devices are "glued" together by having the
585 * /sys/class/net/{device}/phy80211 links pointing to the same
586 * place, so, given a wmaster, wlan, or mon device, you can
587 * find the other devices by looking for devices with
588 * the same phy80211 link.
590 * To turn monitor mode off, delete the monitor interface,
591 * either with "iw dev {monif} interface del" or by sending
592 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
594 * Note: if you try to create a monitor device named "monN", and
595 * there's already a "monN" device, it fails, as least with
596 * the netlink interface (which is what iw uses), with a return
597 * value of -ENFILE. (Return values are negative errnos.) We
598 * could probably use that to find an unused device.
600 * Yes, you can have multiple monitor devices for a given
605 * Is this a mac80211 device? If so, fill in the physical device path and
606 * return 1; if not, return 0. On an error, fill in handle->errbuf and
610 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
611 size_t phydev_max_pathlen
)
617 * Generate the path string for the symlink to the physical device.
619 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
620 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
621 "%s: Can't generate path name string for /sys/class/net device",
625 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
626 if (bytes_read
== -1) {
627 if (errno
== ENOENT
|| errno
== EINVAL
) {
629 * Doesn't exist, or not a symlink; assume that
630 * means it's not a mac80211 device.
635 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
636 errno
, "%s: Can't readlink %s", device
, pathstr
);
641 phydev_path
[bytes_read
] = '\0';
645 #ifdef HAVE_LIBNL_SOCKETS
646 #define get_nl_errmsg nl_geterror
648 /* libnl 2.x compatibility code */
650 #define nl_sock nl_handle
652 static inline struct nl_handle
*
653 nl_socket_alloc(void)
655 return nl_handle_alloc();
659 nl_socket_free(struct nl_handle
*h
)
661 nl_handle_destroy(h
);
664 #define get_nl_errmsg strerror
667 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
669 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
675 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
676 #endif /* !HAVE_LIBNL_SOCKETS */
678 struct nl80211_state
{
679 struct nl_sock
*nl_sock
;
680 struct nl_cache
*nl_cache
;
681 struct genl_family
*nl80211
;
685 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
689 state
->nl_sock
= nl_socket_alloc();
690 if (!state
->nl_sock
) {
691 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
692 "%s: failed to allocate netlink handle", device
);
696 if (genl_connect(state
->nl_sock
)) {
697 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
698 "%s: failed to connect to generic netlink", device
);
699 goto out_handle_destroy
;
702 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
704 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
705 "%s: failed to allocate generic netlink cache: %s",
706 device
, get_nl_errmsg(-err
));
707 goto out_handle_destroy
;
710 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
711 if (!state
->nl80211
) {
712 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
713 "%s: nl80211 not found", device
);
720 nl_cache_free(state
->nl_cache
);
722 nl_socket_free(state
->nl_sock
);
727 nl80211_cleanup(struct nl80211_state
*state
)
729 genl_family_put(state
->nl80211
);
730 nl_cache_free(state
->nl_cache
);
731 nl_socket_free(state
->nl_sock
);
735 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
736 const char *device
, const char *mondevice
);
739 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
740 const char *device
, const char *mondevice
)
742 struct pcap_linux
*handlep
= handle
->priv
;
747 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
753 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
754 "%s: failed to allocate netlink msg", device
);
758 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
759 0, NL80211_CMD_NEW_INTERFACE
, 0);
760 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
762 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
764 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
766 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
768 #if defined HAVE_LIBNL_NLE
769 if (err
== -NLE_FAILURE
) {
771 if (err
== -ENFILE
) {
774 * Device not available; our caller should just
775 * keep trying. (libnl 2.x maps ENFILE to
776 * NLE_FAILURE; it can also map other errors
777 * to that, but there's not much we can do
784 * Real failure, not just "that device is not
787 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
788 "%s: nl_send_auto_complete failed adding %s interface: %s",
789 device
, mondevice
, get_nl_errmsg(-err
));
794 err
= nl_wait_for_ack(state
->nl_sock
);
796 #if defined HAVE_LIBNL_NLE
797 if (err
== -NLE_FAILURE
) {
799 if (err
== -ENFILE
) {
802 * Device not available; our caller should just
803 * keep trying. (libnl 2.x maps ENFILE to
804 * NLE_FAILURE; it can also map other errors
805 * to that, but there's not much we can do
812 * Real failure, not just "that device is not
815 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
816 "%s: nl_wait_for_ack failed adding %s interface: %s",
817 device
, mondevice
, get_nl_errmsg(-err
));
829 * Try to remember the monitor device.
831 handlep
->mondevice
= strdup(mondevice
);
832 if (handlep
->mondevice
== NULL
) {
833 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
836 * Get rid of the monitor device.
838 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
844 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
845 "%s: nl_put failed adding %s interface",
852 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
853 const char *device
, const char *mondevice
)
859 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
865 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
866 "%s: failed to allocate netlink msg", device
);
870 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
871 0, NL80211_CMD_DEL_INTERFACE
, 0);
872 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
874 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
876 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
877 "%s: nl_send_auto_complete failed deleting %s interface: %s",
878 device
, mondevice
, get_nl_errmsg(-err
));
882 err
= nl_wait_for_ack(state
->nl_sock
);
884 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
885 "%s: nl_wait_for_ack failed adding %s interface: %s",
886 device
, mondevice
, get_nl_errmsg(-err
));
898 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
899 "%s: nl_put failed deleting %s interface",
906 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
908 struct pcap_linux
*handlep
= handle
->priv
;
910 char phydev_path
[PATH_MAX
+1];
911 struct nl80211_state nlstate
;
916 * Is this a mac80211 device?
918 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
920 return ret
; /* error */
922 return 0; /* no error, but not mac80211 device */
925 * XXX - is this already a monN device?
927 * Is that determined by old Wireless Extensions ioctls?
931 * OK, it's apparently a mac80211 device.
932 * Try to find an unused monN device for it.
934 ret
= nl80211_init(handle
, &nlstate
, device
);
937 for (n
= 0; n
< UINT_MAX
; n
++) {
941 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
943 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
944 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
947 * Success. We don't clean up the libnl state
948 * yet, as we'll be using it later.
954 * Hard failure. Just return ret; handle->errbuf
955 * has already been set.
957 nl80211_cleanup(&nlstate
);
962 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
963 "%s: No free monN interfaces", device
);
964 nl80211_cleanup(&nlstate
);
971 * Sleep for .1 seconds.
974 delay
.tv_nsec
= 500000000;
975 nanosleep(&delay
, NULL
);
979 * If we haven't already done so, arrange to have
980 * "pcap_close_all()" called when we exit.
982 if (!pcap_do_addexit(handle
)) {
984 * "atexit()" failed; don't put the interface
985 * in rfmon mode, just give up.
987 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
989 nl80211_cleanup(&nlstate
);
994 * Now configure the monitor interface up.
996 memset(&ifr
, 0, sizeof(ifr
));
997 pcap_strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
998 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
999 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1000 errno
, "%s: Can't get flags for %s", device
,
1001 handlep
->mondevice
);
1002 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
1003 handlep
->mondevice
);
1004 nl80211_cleanup(&nlstate
);
1007 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
1008 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1009 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1010 errno
, "%s: Can't set flags for %s", device
,
1011 handlep
->mondevice
);
1012 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
1013 handlep
->mondevice
);
1014 nl80211_cleanup(&nlstate
);
1019 * Success. Clean up the libnl state.
1021 nl80211_cleanup(&nlstate
);
1024 * Note that we have to delete the monitor device when we close
1027 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
1030 * Add this to the list of pcaps to close when we exit.
1032 pcap_add_to_pcaps_to_close(handle
);
1036 #endif /* HAVE_LIBNL */
1038 #ifdef IW_MODE_MONITOR
1040 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
1041 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
1042 * will fail with ENODEV if we try to do them on a bonding device,
1043 * making us return a "no such device" indication rather than just
1044 * saying "no Wireless Extensions".
1046 * So we check for bonding devices, if we can, before trying those
1047 * ioctls, by trying a bonding device information query ioctl to see
1048 * whether it succeeds.
1051 is_bonding_device(int fd
, const char *device
)
1053 #ifdef BOND_INFO_QUERY_IOCTL
1057 memset(&ifr
, 0, sizeof ifr
);
1058 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof ifr
.ifr_name
);
1059 memset(&ifb
, 0, sizeof ifb
);
1060 ifr
.ifr_data
= (caddr_t
)&ifb
;
1061 if (ioctl(fd
, BOND_INFO_QUERY_IOCTL
, &ifr
) == 0)
1062 return 1; /* success, so it's a bonding device */
1063 #endif /* BOND_INFO_QUERY_IOCTL */
1065 return 0; /* no, it's not a bonding device */
1067 #endif /* IW_MODE_MONITOR */
1069 static int pcap_protocol(pcap_t
*handle
)
1073 protocol
= handle
->opt
.protocol
;
1075 protocol
= ETH_P_ALL
;
1077 return htons(protocol
);
1081 pcap_can_set_rfmon_linux(pcap_t
*handle
)
1084 char phydev_path
[PATH_MAX
+1];
1087 #ifdef IW_MODE_MONITOR
1092 if (strcmp(handle
->opt
.device
, "any") == 0) {
1094 * Monitor mode makes no sense on the "any" device.
1101 * Bleah. There doesn't seem to be a way to ask a mac80211
1102 * device, through libnl, whether it supports monitor mode;
1103 * we'll just check whether the device appears to be a
1104 * mac80211 device and, if so, assume the device supports
1107 * wmaster devices don't appear to support the Wireless
1108 * Extensions, but we can create a mon device for a
1109 * wmaster device, so we don't bother checking whether
1110 * a mac80211 device supports the Wireless Extensions.
1112 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
1115 return ret
; /* error */
1117 return 1; /* mac80211 device */
1120 #ifdef IW_MODE_MONITOR
1122 * Bleah. There doesn't appear to be an ioctl to use to ask
1123 * whether a device supports monitor mode; we'll just do
1124 * SIOCGIWMODE and, if it succeeds, assume the device supports
1127 * Open a socket on which to attempt to get the mode.
1128 * (We assume that if we have Wireless Extensions support
1129 * we also have PF_PACKET support.)
1131 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, pcap_protocol(handle
));
1132 if (sock_fd
== -1) {
1133 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1138 if (is_bonding_device(sock_fd
, handle
->opt
.device
)) {
1139 /* It's a bonding device, so don't even try. */
1145 * Attempt to get the current mode.
1147 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.device
,
1148 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1149 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1151 * Well, we got the mode; assume we can set it.
1156 if (errno
== ENODEV
) {
1157 /* The device doesn't even exist. */
1158 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1159 errno
, "SIOCGIWMODE failed");
1161 return PCAP_ERROR_NO_SUCH_DEVICE
;
1169 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1171 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1172 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1174 * Or can we get them in binary form from netlink?
1177 linux_if_drops(const char * if_name
)
1181 char *bufptr
, *nameptr
, *colonptr
;
1182 int field_to_convert
= 3;
1183 long int dropped_pkts
= 0;
1185 file
= fopen("/proc/net/dev", "r");
1189 while (fgets(buffer
, sizeof(buffer
), file
) != NULL
)
1191 /* search for 'bytes' -- if its in there, then
1192 that means we need to grab the fourth field. otherwise
1193 grab the third field. */
1194 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1196 field_to_convert
= 4;
1201 * See whether this line corresponds to this device.
1202 * The line should have zero or more leading blanks,
1203 * followed by a device name, followed by a colon,
1204 * followed by the statistics.
1207 /* Skip leading blanks */
1208 while (*bufptr
== ' ')
1211 /* Look for the colon */
1212 colonptr
= strchr(nameptr
, ':');
1213 if (colonptr
== NULL
)
1216 * Not found; this could, for example, be the
1221 /* Null-terminate the interface name. */
1223 if (strcmp(if_name
, nameptr
) == 0)
1226 * OK, this line has the statistics for the interface.
1227 * Skip past the interface name.
1229 bufptr
= colonptr
+ 1;
1231 /* grab the nth field from it */
1232 while (--field_to_convert
&& *bufptr
!= '\0')
1235 * This isn't the field we want.
1236 * First, skip any leading blanks before
1239 while (*bufptr
== ' ')
1243 * Now skip the non-blank characters of
1246 while (*bufptr
!= '\0' && *bufptr
!= ' ')
1250 if (field_to_convert
== 0)
1253 * We've found the field we want.
1254 * Skip any leading blanks before it.
1256 while (*bufptr
== ' ')
1260 * Now extract the value, if we have one.
1262 if (*bufptr
!= '\0')
1263 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1270 return dropped_pkts
;
1275 * With older kernels promiscuous mode is kind of interesting because we
1276 * have to reset the interface before exiting. The problem can't really
1277 * be solved without some daemon taking care of managing usage counts.
1278 * If we put the interface into promiscuous mode, we set a flag indicating
1279 * that we must take it out of that mode when the interface is closed,
1280 * and, when closing the interface, if that flag is set we take it out
1281 * of promiscuous mode.
1283 * Even with newer kernels, we have the same issue with rfmon mode.
1286 static void pcap_cleanup_linux( pcap_t
*handle
)
1288 struct pcap_linux
*handlep
= handle
->priv
;
1291 struct nl80211_state nlstate
;
1293 #endif /* HAVE_LIBNL */
1294 #ifdef IW_MODE_MONITOR
1297 #endif /* IW_MODE_MONITOR */
1299 if (handlep
->must_do_on_close
!= 0) {
1301 * There's something we have to do when closing this
1304 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1306 * We put the interface into promiscuous mode;
1307 * take it out of promiscuous mode.
1309 * XXX - if somebody else wants it in promiscuous
1310 * mode, this code cannot know that, so it'll take
1311 * it out of promiscuous mode. That's not fixable
1312 * in 2.0[.x] kernels.
1314 memset(&ifr
, 0, sizeof(ifr
));
1315 pcap_strlcpy(ifr
.ifr_name
, handlep
->device
,
1316 sizeof(ifr
.ifr_name
));
1317 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1319 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1320 "Please adjust manually.\n"
1321 "Hint: This can't happen with Linux >= 2.2.0.\n",
1322 handlep
->device
, strerror(errno
));
1324 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1326 * Promiscuous mode is currently on;
1329 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1330 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1333 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1334 "Please adjust manually.\n"
1335 "Hint: This can't happen with Linux >= 2.2.0.\n",
1344 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1345 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1347 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1348 handlep
->device
, handlep
->mondevice
);
1349 nl80211_cleanup(&nlstate
);
1353 "Can't delete monitor interface %s (%s).\n"
1354 "Please delete manually.\n",
1355 handlep
->mondevice
, handle
->errbuf
);
1358 #endif /* HAVE_LIBNL */
1360 #ifdef IW_MODE_MONITOR
1361 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1363 * We put the interface into rfmon mode;
1364 * take it out of rfmon mode.
1366 * XXX - if somebody else wants it in rfmon
1367 * mode, this code cannot know that, so it'll take
1368 * it out of rfmon mode.
1372 * First, take the interface down if it's up;
1373 * otherwise, we might get EBUSY.
1374 * If we get errors, just drive on and print
1375 * a warning if we can't restore the mode.
1378 memset(&ifr
, 0, sizeof(ifr
));
1379 pcap_strlcpy(ifr
.ifr_name
, handlep
->device
,
1380 sizeof(ifr
.ifr_name
));
1381 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1382 if (ifr
.ifr_flags
& IFF_UP
) {
1383 oldflags
= ifr
.ifr_flags
;
1384 ifr
.ifr_flags
&= ~IFF_UP
;
1385 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1386 oldflags
= 0; /* didn't set, don't restore */
1391 * Now restore the mode.
1393 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1394 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1395 ireq
.u
.mode
= handlep
->oldmode
;
1396 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1398 * Scientist, you've failed.
1401 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1402 "Please adjust manually.\n",
1403 handlep
->device
, strerror(errno
));
1407 * Now bring the interface back up if we brought
1410 if (oldflags
!= 0) {
1411 ifr
.ifr_flags
= oldflags
;
1412 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1414 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1415 "Please adjust manually.\n",
1416 handlep
->device
, strerror(errno
));
1420 #endif /* IW_MODE_MONITOR */
1423 * Take this pcap out of the list of pcaps for which we
1424 * have to take the interface out of some mode.
1426 pcap_remove_from_pcaps_to_close(handle
);
1429 if (handlep
->mondevice
!= NULL
) {
1430 free(handlep
->mondevice
);
1431 handlep
->mondevice
= NULL
;
1433 if (handlep
->device
!= NULL
) {
1434 free(handlep
->device
);
1435 handlep
->device
= NULL
;
1438 #ifdef HAVE_SYS_EVENTFD_H
1439 close(handlep
->poll_breakloop_fd
);
1441 pcap_cleanup_live_common(handle
);
1445 * Set the timeout to be used in poll() with memory-mapped packet capture.
1448 set_poll_timeout(struct pcap_linux
*handlep
)
1450 #ifdef HAVE_TPACKET3
1451 struct utsname utsname
;
1452 char *version_component
, *endp
;
1454 int broken_tpacket_v3
= 1;
1457 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1458 * around which we have to work. Determine if we have those
1461 if (uname(&utsname
) == 0) {
1463 * 3.19 is the first release with a fixed version of
1464 * TPACKET_V3. We treat anything before that as
1465 * not haveing a fixed version; that may really mean
1466 * it has *no* version.
1468 version_component
= utsname
.release
;
1469 major
= strtol(version_component
, &endp
, 10);
1470 if (endp
!= version_component
&& *endp
== '.') {
1472 * OK, that was a valid major version.
1473 * Get the minor version.
1475 version_component
= endp
+ 1;
1476 minor
= strtol(version_component
, &endp
, 10);
1477 if (endp
!= version_component
&&
1478 (*endp
== '.' || *endp
== '\0')) {
1480 * OK, that was a valid minor version.
1481 * Is this 3.19 or newer?
1483 if (major
>= 4 || (major
== 3 && minor
>= 19)) {
1484 /* Yes. TPACKET_V3 works correctly. */
1485 broken_tpacket_v3
= 0;
1491 if (handlep
->timeout
== 0) {
1492 #ifdef HAVE_TPACKET3
1494 * XXX - due to a set of (mis)features in the TPACKET_V3
1495 * kernel code prior to the 3.19 kernel, blocking forever
1496 * with a TPACKET_V3 socket can, if few packets are
1497 * arriving and passing the socket filter, cause most
1498 * packets to be dropped. See libpcap issue #335 for the
1499 * full painful story.
1501 * The workaround is to have poll() time out very quickly,
1502 * so we grab the frames handed to us, and return them to
1505 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1506 handlep
->poll_timeout
= 1; /* don't block for very long */
1509 handlep
->poll_timeout
= -1; /* block forever */
1510 } else if (handlep
->timeout
> 0) {
1511 #ifdef HAVE_TPACKET3
1513 * For TPACKET_V3, the timeout is handled by the kernel,
1514 * so block forever; that way, we don't get extra timeouts.
1515 * Don't do that if we have a broken TPACKET_V3, though.
1517 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1518 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1521 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1524 * Non-blocking mode; we call poll() to pick up error
1525 * indications, but we don't want it to wait for
1528 handlep
->poll_timeout
= 0;
1532 #ifdef HAVE_SYS_EVENTFD_H
1533 static void pcap_breakloop_linux(pcap_t
*handle
)
1535 pcap_breakloop_common(handle
);
1536 struct pcap_linux
*handlep
= handle
->priv
;
1539 /* XXX - what if this fails? */
1540 (void)write(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
1544 #ifdef HAVE_PF_PACKET_SOCKETS
1546 * We need a special error return to indicate that PF_PACKET sockets
1547 * aren't supported; that's not a fatal error, it's just an indication
1548 * that we have a pre-2.2 kernel, and must fall back on PF_INET/SOCK_PACKET
1551 * We assume, for now, that we won't have so many PCAP_ERROR_ values that
1552 * -128 will be used, and use that as the error (it fits into a byte,
1553 * so comparison against it should be doable without too big an immediate
1554 * value - yeah, I know, premature optimization is the root of all evil...).
1556 #define PCAP_ERROR_NO_PF_PACKET_SOCKETS -128
1559 * Open a PF_PACKET socket.
1562 open_pf_packet_socket(pcap_t
*handle
, int cooked
)
1564 int protocol
= pcap_protocol(handle
);
1568 * Open a socket with protocol family packet. If cooked is true,
1569 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
1570 * we open a SOCK_RAW socket for the raw interface.
1573 socket(PF_PACKET
, SOCK_DGRAM
, protocol
) :
1574 socket(PF_PACKET
, SOCK_RAW
, protocol
);
1576 if (sock_fd
== -1) {
1577 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
1579 * PF_PACKET sockets aren't supported.
1581 * If this is the first attempt to open a PF_PACKET
1582 * socket, our caller will just want to try a
1583 * PF_INET/SOCK_PACKET socket; in other cases, we
1584 * already succeeded opening a PF_PACKET socket,
1585 * but are just switching to cooked from raw, in
1586 * which case this is a fatal error (and "can't
1587 * happen", because the kernel isn't going to
1588 * spontaneously drop its support for PF_PACKET
1591 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1592 "PF_PACKET sockets not supported (this \"can't happen\"!");
1593 return PCAP_ERROR_NO_PF_PACKET_SOCKETS
;
1595 if (errno
== EPERM
|| errno
== EACCES
) {
1597 * You don't have permission to open the
1600 ret
= PCAP_ERROR_PERM_DENIED
;
1607 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1616 * Get a handle for a live capture from the given device. You can
1617 * pass NULL as device to get all packages (without link level
1618 * information of course). If you pass 1 as promisc the interface
1619 * will be set to promiscous mode (XXX: I think this usage should
1620 * be deprecated and functions be added to select that later allow
1621 * modification of that values -- Torsten).
1624 pcap_activate_linux(pcap_t
*handle
)
1626 struct pcap_linux
*handlep
= handle
->priv
;
1633 device
= handle
->opt
.device
;
1636 * Make sure the name we were handed will fit into the ioctls we
1637 * might perform on the device; if not, return a "No such device"
1638 * indication, as the Linux kernel shouldn't support creating
1639 * a device whose name won't fit into those ioctls.
1641 * "Will fit" means "will fit, complete with a null terminator",
1642 * so if the length, which does *not* include the null terminator,
1643 * is greater than *or equal to* the size of the field into which
1644 * we'll be copying it, that won't fit.
1646 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1647 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1652 * Turn a negative snapshot value (invalid), a snapshot value of
1653 * 0 (unspecified), or a value bigger than the normal maximum
1654 * value, into the maximum allowed value.
1656 * If some application really *needs* a bigger snapshot
1657 * length, we should just increase MAXIMUM_SNAPLEN.
1659 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
1660 handle
->snapshot
= MAXIMUM_SNAPLEN
;
1662 handle
->inject_op
= pcap_inject_linux
;
1663 handle
->setfilter_op
= pcap_setfilter_linux
;
1664 handle
->setdirection_op
= pcap_setdirection_linux
;
1665 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1666 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1667 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1668 handle
->cleanup_op
= pcap_cleanup_linux
;
1669 handle
->read_op
= pcap_read_linux
;
1670 handle
->stats_op
= pcap_stats_linux
;
1671 #ifdef HAVE_SYS_EVENTFD_H
1672 handle
->breakloop_op
= pcap_breakloop_linux
;
1675 handlep
->device
= strdup(device
);
1676 if (handlep
->device
== NULL
) {
1677 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1679 status
= PCAP_ERROR
;
1684 * The "any" device is a special device which causes us not
1685 * to bind to a particular device and thus to look at all
1688 is_any_device
= (strcmp(device
, "any") == 0);
1689 if (is_any_device
) {
1690 if (handle
->opt
.promisc
) {
1691 handle
->opt
.promisc
= 0;
1692 /* Just a warning. */
1693 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1694 "Promiscuous mode not supported on the \"any\" device");
1695 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1699 /* copy timeout value */
1700 handlep
->timeout
= handle
->opt
.timeout
;
1703 * If we're in promiscuous mode, then we probably want
1704 * to see when the interface drops packets too, so get an
1705 * initial count from /proc/net/dev
1707 if (handle
->opt
.promisc
)
1708 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1710 #ifdef HAVE_PF_PACKET_SOCKETS
1712 * Current Linux kernels use the protocol family PF_PACKET to
1713 * allow direct access to all packets on the network while
1714 * older kernels had a special socket type SOCK_PACKET to
1715 * implement this feature.
1716 * While this old implementation is kind of obsolete we need
1717 * to be compatible with older kernels for a while so we are
1718 * trying both methods with the newer method preferred.
1720 * Try to activate with a PF_PACKET socket. If the "any" device
1721 * was specified, we open a SOCK_DGRAM socket for the cooked
1722 * interface, otherwise we first try a SOCK_RAW socket for
1723 * the raw interface.
1725 ret
= activate_new(handle
, is_any_device
);
1727 if (ret
!= PCAP_ERROR_NO_PF_PACKET_SOCKETS
) {
1729 * Fatal error; the return value is the error code,
1730 * and handle->errbuf has been set to an appropriate
1737 * We don't support PF_PACKET/SOCK_whatever
1738 * sockets; try the old mechanism.
1740 ret
= activate_old(handle
, is_any_device
);
1743 * Both methods to open the packet socket
1746 * Tidy up and report our failure
1747 * (handle->errbuf is expected to be set
1748 * by the functions above).
1754 #ifdef HAVE_PACKET_RING
1757 * Try to use memory-mapped access.
1759 switch (activate_mmap(handle
, &status
)) {
1763 * We succeeded. status has been
1764 * set to the status to return,
1765 * which might be 0, or might be
1766 * a PCAP_WARNING_ value.
1768 * Set the timeout to use in poll() before
1771 set_poll_timeout(handlep
);
1776 * Kernel doesn't support it - just continue
1777 * with non-memory-mapped access.
1783 * We failed to set up to use it, or the
1784 * kernel supports it, but we failed to
1785 * enable it. status has been set to the
1786 * error status to return and, if it's
1787 * PCAP_ERROR, handle->errbuf contains
1788 * the error message.
1792 #endif /* HAVE_PACKET_RING */
1794 #else /* HAVE_PF_PACKET_SOCKETS */
1796 * We don't support PF_PACKET/SOCK_whatever sockets, so we must
1797 * try the old mechanism.
1799 ret
= activate_old(handle
, is_any_device
);
1804 * Tidy up and report our failure
1805 * (handle->errbuf is expected to be set
1806 * by the functions above).
1811 #endif /* HAVE_PF_PACKET_SOCKETS */
1814 * We set up the socket, but not with memory-mapped access.
1816 if (handle
->opt
.buffer_size
!= 0) {
1818 * Set the socket buffer size to the specified value.
1820 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1821 &handle
->opt
.buffer_size
,
1822 sizeof(handle
->opt
.buffer_size
)) == -1) {
1823 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1824 PCAP_ERRBUF_SIZE
, errno
, "SO_RCVBUF");
1825 status
= PCAP_ERROR
;
1830 /* Allocate the buffer */
1832 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1833 if (!handle
->buffer
) {
1834 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1836 status
= PCAP_ERROR
;
1841 * "handle->fd" is a socket, so "select()" and "poll()"
1842 * should work on it.
1844 handle
->selectable_fd
= handle
->fd
;
1849 pcap_cleanup_linux(handle
);
1854 * Read at most max_packets from the capture stream and call the callback
1855 * for each of them. Returns the number of packets handled or -1 if an
1859 pcap_read_linux(pcap_t
*handle
, int max_packets _U_
, pcap_handler callback
, u_char
*user
)
1862 * Currently, on Linux only one packet is delivered per read,
1865 return pcap_read_packet(handle
, callback
, user
);
1869 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1871 handle
->linktype
= dlt
;
1876 * linux_check_direction()
1878 * Do checks based on packet direction.
1881 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1883 struct pcap_linux
*handlep
= handle
->priv
;
1885 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1888 * If this is from the loopback device, reject it;
1889 * we'll see the packet as an incoming packet as well,
1890 * and we don't want to see it twice.
1892 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1896 * If this is an outgoing CAN or CAN FD frame, and
1897 * the user doesn't only want outgoing packets,
1898 * reject it; CAN devices and drivers, and the CAN
1899 * stack, always arrange to loop back transmitted
1900 * packets, so they also appear as incoming packets.
1901 * We don't want duplicate packets, and we can't
1902 * easily distinguish packets looped back by the CAN
1903 * layer than those received by the CAN layer, so we
1904 * eliminate this packet instead.
1906 if ((sll
->sll_protocol
== LINUX_SLL_P_CAN
||
1907 sll
->sll_protocol
== LINUX_SLL_P_CANFD
) &&
1908 handle
->direction
!= PCAP_D_OUT
)
1912 * If the user only wants incoming packets, reject it.
1914 if (handle
->direction
== PCAP_D_IN
)
1919 * If the user only wants outgoing packets, reject it.
1921 if (handle
->direction
== PCAP_D_OUT
)
1928 * Read a packet from the socket calling the handler provided by
1929 * the user. Returns the number of packets received or -1 if an
1933 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1935 struct pcap_linux
*handlep
= handle
->priv
;
1938 #ifdef HAVE_PF_PACKET_SOCKETS
1939 struct sockaddr_ll from
;
1941 struct sockaddr from
;
1943 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1946 struct cmsghdr
*cmsg
;
1948 struct cmsghdr cmsg
;
1949 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1951 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1953 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1956 struct pcap_pkthdr pcap_header
;
1958 struct bpf_aux_data aux_data
;
1959 #ifdef HAVE_PF_PACKET_SOCKETS
1961 * If this is a cooked device, leave extra room for a
1962 * fake packet header.
1964 if (handlep
->cooked
) {
1965 if (handle
->linktype
== DLT_LINUX_SLL2
)
1966 offset
= SLL2_HDR_LEN
;
1968 offset
= SLL_HDR_LEN
;
1973 * This system doesn't have PF_PACKET sockets, so it doesn't
1974 * support cooked devices.
1980 * Receive a single packet from the kernel.
1981 * We ignore EINTR, as that might just be due to a signal
1982 * being delivered - if the signal should interrupt the
1983 * loop, the signal handler should call pcap_breakloop()
1984 * to set handle->break_loop (we ignore it on other
1985 * platforms as well).
1986 * We also ignore ENETDOWN, so that we can continue to
1987 * capture traffic if the interface goes down and comes
1988 * back up again; comments in the kernel indicate that
1989 * we'll just block waiting for packets if we try to
1990 * receive from a socket that delivered ENETDOWN, and,
1991 * if we're using a memory-mapped buffer, we won't even
1992 * get notified of "network down" events.
1994 bp
= (u_char
*)handle
->buffer
+ handle
->offset
;
1996 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1997 msg
.msg_name
= &from
;
1998 msg
.msg_namelen
= sizeof(from
);
2001 msg
.msg_control
= &cmsg_buf
;
2002 msg
.msg_controllen
= sizeof(cmsg_buf
);
2005 iov
.iov_len
= handle
->bufsize
- offset
;
2006 iov
.iov_base
= bp
+ offset
;
2007 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2011 * Has "pcap_breakloop()" been called?
2013 if (handle
->break_loop
) {
2015 * Yes - clear the flag that indicates that it has,
2016 * and return PCAP_ERROR_BREAK as an indication that
2017 * we were told to break out of the loop.
2019 handle
->break_loop
= 0;
2020 return PCAP_ERROR_BREAK
;
2023 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
2024 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
2025 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2026 fromlen
= sizeof(from
);
2027 packet_len
= recvfrom(
2028 handle
->fd
, bp
+ offset
,
2029 handle
->bufsize
- offset
, MSG_TRUNC
,
2030 (struct sockaddr
*) &from
, &fromlen
);
2031 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2032 } while (packet_len
== -1 && errno
== EINTR
);
2034 /* Check if an error occured */
2036 if (packet_len
== -1) {
2040 return 0; /* no packet there */
2044 * The device on which we're capturing went away.
2046 * XXX - we should really return
2047 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
2048 * etc. aren't defined to return that.
2050 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2051 "The interface went down");
2055 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2056 PCAP_ERRBUF_SIZE
, errno
, "recvfrom");
2061 #ifdef HAVE_PF_PACKET_SOCKETS
2062 if (!handlep
->sock_packet
) {
2064 * Unfortunately, there is a window between socket() and
2065 * bind() where the kernel may queue packets from any
2066 * interface. If we're bound to a particular interface,
2067 * discard packets not from that interface.
2069 * (If socket filters are supported, we could do the
2070 * same thing we do when changing the filter; however,
2071 * that won't handle packet sockets without socket
2072 * filter support, and it's a bit more complicated.
2073 * It would save some instructions per packet, however.)
2075 if (handlep
->ifindex
!= -1 &&
2076 from
.sll_ifindex
!= handlep
->ifindex
)
2080 * Do checks based on packet direction.
2081 * We can only do this if we're using PF_PACKET; the
2082 * address returned for SOCK_PACKET is a "sockaddr_pkt"
2083 * which lacks the relevant packet type information.
2085 if (!linux_check_direction(handle
, &from
))
2090 #ifdef HAVE_PF_PACKET_SOCKETS
2092 * If this is a cooked device, fill in the fake packet header.
2094 if (handlep
->cooked
) {
2096 * Add the length of the fake header to the length
2097 * of packet data we read.
2099 if (handle
->linktype
== DLT_LINUX_SLL2
) {
2100 struct sll2_header
*hdrp
;
2102 packet_len
+= SLL2_HDR_LEN
;
2104 hdrp
= (struct sll2_header
*)bp
;
2105 hdrp
->sll2_protocol
= from
.sll_protocol
;
2106 hdrp
->sll2_reserved_mbz
= 0;
2107 hdrp
->sll2_if_index
= htonl(from
.sll_ifindex
);
2108 hdrp
->sll2_hatype
= htons(from
.sll_hatype
);
2109 hdrp
->sll2_pkttype
= from
.sll_pkttype
;
2110 hdrp
->sll2_halen
= from
.sll_halen
;
2111 memcpy(hdrp
->sll2_addr
, from
.sll_addr
,
2112 (from
.sll_halen
> SLL_ADDRLEN
) ?
2116 struct sll_header
*hdrp
;
2118 packet_len
+= SLL_HDR_LEN
;
2120 hdrp
= (struct sll_header
*)bp
;
2121 hdrp
->sll_pkttype
= htons(from
.sll_pkttype
);
2122 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
2123 hdrp
->sll_halen
= htons(from
.sll_halen
);
2124 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
2125 (from
.sll_halen
> SLL_ADDRLEN
) ?
2128 hdrp
->sll_protocol
= from
.sll_protocol
;
2133 * Start out with no VLAN information.
2135 aux_data
.vlan_tag_present
= 0;
2136 aux_data
.vlan_tag
= 0;
2137 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
2138 if (handlep
->vlan_offset
!= -1) {
2139 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
2140 struct tpacket_auxdata
*aux
;
2142 struct vlan_tag
*tag
;
2144 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
2145 cmsg
->cmsg_level
!= SOL_PACKET
||
2146 cmsg
->cmsg_type
!= PACKET_AUXDATA
) {
2148 * This isn't a PACKET_AUXDATA auxiliary
2154 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
2155 if (!VLAN_VALID(aux
, aux
)) {
2157 * There is no VLAN information in the
2163 len
= (size_t)packet_len
> iov
.iov_len
? iov
.iov_len
: (u_int
)packet_len
;
2164 if (len
< (size_t)handlep
->vlan_offset
)
2168 * Move everything in the header, except the
2169 * type field, down VLAN_TAG_LEN bytes, to
2170 * allow us to insert the VLAN tag between
2171 * that stuff and the type field.
2174 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
2177 * Now insert the tag.
2179 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
2180 tag
->vlan_tpid
= htons(VLAN_TPID(aux
, aux
));
2181 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
2184 * Save a flag indicating that we have a VLAN tag,
2185 * and the VLAN TCI, to bpf_aux_data struct for
2186 * use by the BPF filter if we're doing the
2187 * filtering in userland.
2189 aux_data
.vlan_tag_present
= 1;
2190 aux_data
.vlan_tag
= htons(aux
->tp_vlan_tci
) & 0x0fff;
2193 * Add the tag to the packet lengths.
2195 packet_len
+= VLAN_TAG_LEN
;
2198 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2199 #endif /* HAVE_PF_PACKET_SOCKETS */
2202 * XXX: According to the kernel source we should get the real
2203 * packet len if calling recvfrom with MSG_TRUNC set. It does
2204 * not seem to work here :(, but it is supported by this code
2206 * To be honest the code RELIES on that feature so this is really
2207 * broken with 2.2.x kernels.
2208 * I spend a day to figure out what's going on and I found out
2209 * that the following is happening:
2211 * The packet comes from a random interface and the packet_rcv
2212 * hook is called with a clone of the packet. That code inserts
2213 * the packet into the receive queue of the packet socket.
2214 * If a filter is attached to that socket that filter is run
2215 * first - and there lies the problem. The default filter always
2216 * cuts the packet at the snaplen:
2221 * So the packet filter cuts down the packet. The recvfrom call
2222 * says "hey, it's only 68 bytes, it fits into the buffer" with
2223 * the result that we don't get the real packet length. This
2224 * is valid at least until kernel 2.2.17pre6.
2226 * We currently handle this by making a copy of the filter
2227 * program, fixing all "ret" instructions with non-zero
2228 * operands to have an operand of MAXIMUM_SNAPLEN so that the
2229 * filter doesn't truncate the packet, and supplying that modified
2230 * filter to the kernel.
2233 caplen
= (int)packet_len
;
2234 if (caplen
> handle
->snapshot
)
2235 caplen
= handle
->snapshot
;
2237 /* Run the packet filter if not using kernel filter */
2238 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
2239 if (pcap_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
2240 (int)packet_len
, caplen
, &aux_data
) == 0) {
2241 /* rejected by filter */
2246 /* Fill in our own header data */
2248 /* get timestamp for this packet */
2249 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
2250 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
2251 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
2252 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2253 PCAP_ERRBUF_SIZE
, errno
, "SIOCGSTAMPNS");
2259 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
2260 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2261 PCAP_ERRBUF_SIZE
, errno
, "SIOCGSTAMP");
2266 pcap_header
.caplen
= caplen
;
2267 pcap_header
.len
= (bpf_u_int32
)packet_len
;
2272 * Arguably, we should count them before we check the filter,
2273 * as on many other platforms "ps_recv" counts packets
2274 * handed to the filter rather than packets that passed
2275 * the filter, but if filtering is done in the kernel, we
2276 * can't get a count of packets that passed the filter,
2277 * and that would mean the meaning of "ps_recv" wouldn't
2278 * be the same on all Linux systems.
2280 * XXX - it's not the same on all systems in any case;
2281 * ideally, we should have a "get the statistics" call
2282 * that supplies more counts and indicates which of them
2283 * it supplies, so that we supply a count of packets
2284 * handed to the filter only on platforms where that
2285 * information is available.
2287 * We count them here even if we can get the packet count
2288 * from the kernel, as we can only determine at run time
2289 * whether we'll be able to get it from the kernel (if
2290 * HAVE_STRUCT_TPACKET_STATS isn't defined, we can't get it from
2291 * the kernel, but if it is defined, the library might
2292 * have been built with a 2.4 or later kernel, but we
2293 * might be running on a 2.2[.x] kernel without Alexey
2294 * Kuznetzov's turbopacket patches, and thus the kernel
2295 * might not be able to supply those statistics). We
2296 * could, I guess, try, when opening the socket, to get
2297 * the statistics, and if we can not increment the count
2298 * here, but it's not clear that always incrementing
2299 * the count is more expensive than always testing a flag
2302 * We keep the count in "handlep->packets_read", and use that
2303 * for "ps_recv" if we can't get the statistics from the kernel.
2304 * We do that because, if we *can* get the statistics from
2305 * the kernel, we use "handlep->stat.ps_recv" and
2306 * "handlep->stat.ps_drop" as running counts, as reading the
2307 * statistics from the kernel resets the kernel statistics,
2308 * and if we directly increment "handlep->stat.ps_recv" here,
2309 * that means it will count packets *twice* on systems where
2310 * we can get kernel statistics - once here, and once in
2311 * pcap_stats_linux().
2313 handlep
->packets_read
++;
2315 /* Call the user supplied callback function */
2316 callback(userdata
, &pcap_header
, bp
);
2322 pcap_inject_linux(pcap_t
*handle
, const void *buf
, int size
)
2324 struct pcap_linux
*handlep
= handle
->priv
;
2327 #ifdef HAVE_PF_PACKET_SOCKETS
2328 if (!handlep
->sock_packet
) {
2329 /* PF_PACKET socket */
2330 if (handlep
->ifindex
== -1) {
2332 * We don't support sending on the "any" device.
2334 pcap_strlcpy(handle
->errbuf
,
2335 "Sending packets isn't supported on the \"any\" device",
2340 if (handlep
->cooked
) {
2342 * We don't support sending on cooked-mode sockets.
2344 * XXX - how do you send on a bound cooked-mode
2346 * Is a "sendto()" required there?
2348 pcap_strlcpy(handle
->errbuf
,
2349 "Sending packets isn't supported in cooked mode",
2356 ret
= (int)send(handle
->fd
, buf
, size
, 0);
2358 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2366 * Get the statistics for the given packet capture handle.
2367 * Reports the number of dropped packets iff the kernel supports
2368 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2369 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2370 * patches); otherwise, that information isn't available, and we lie
2371 * and report 0 as the count of dropped packets.
2374 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
2376 struct pcap_linux
*handlep
= handle
->priv
;
2377 #ifdef HAVE_STRUCT_TPACKET_STATS
2378 #ifdef HAVE_TPACKET3
2380 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2381 * stuff at the end of a struct tpacket_stats_v3 will not
2382 * be filled in, and we don't look at it so this is OK even
2383 * for those sockets. In addition, the PF_PACKET socket
2384 * code in the kernel only uses the length parameter to
2385 * compute how much data to copy out and to indicate how
2386 * much data was copied out, so it's OK to base it on the
2387 * size of a struct tpacket_stats.
2389 * XXX - it's probably OK, in fact, to just use a
2390 * struct tpacket_stats for V3 sockets, as we don't
2391 * care about the tp_freeze_q_cnt stat.
2393 struct tpacket_stats_v3 kstats
;
2394 #else /* HAVE_TPACKET3 */
2395 struct tpacket_stats kstats
;
2396 #endif /* HAVE_TPACKET3 */
2397 socklen_t len
= sizeof (struct tpacket_stats
);
2398 #endif /* HAVE_STRUCT_TPACKET_STATS */
2400 long if_dropped
= 0;
2403 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
2405 if (handle
->opt
.promisc
)
2407 if_dropped
= handlep
->proc_dropped
;
2408 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
2409 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
2412 #ifdef HAVE_STRUCT_TPACKET_STATS
2414 * Try to get the packet counts from the kernel.
2416 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
2417 &kstats
, &len
) > -1) {
2419 * On systems where the PACKET_STATISTICS "getsockopt()"
2420 * argument is supported on PF_PACKET sockets:
2422 * "ps_recv" counts only packets that *passed* the
2423 * filter, not packets that didn't pass the filter.
2424 * This includes packets later dropped because we
2425 * ran out of buffer space.
2427 * "ps_drop" counts packets dropped because we ran
2428 * out of buffer space. It doesn't count packets
2429 * dropped by the interface driver. It counts only
2430 * packets that passed the filter.
2432 * See above for ps_ifdrop.
2434 * Both statistics include packets not yet read from
2435 * the kernel by libpcap, and thus not yet seen by
2438 * In "linux/net/packet/af_packet.c", at least in the
2439 * 2.4.9 kernel, "tp_packets" is incremented for every
2440 * packet that passes the packet filter *and* is
2441 * successfully queued on the socket; "tp_drops" is
2442 * incremented for every packet dropped because there's
2443 * not enough free space in the socket buffer.
2445 * When the statistics are returned for a PACKET_STATISTICS
2446 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2447 * so that "tp_packets" counts all packets handed to
2448 * the PF_PACKET socket, including packets dropped because
2449 * there wasn't room on the socket buffer - but not
2450 * including packets that didn't pass the filter.
2452 * In the BSD BPF, the count of received packets is
2453 * incremented for every packet handed to BPF, regardless
2454 * of whether it passed the filter.
2456 * We can't make "pcap_stats()" work the same on both
2457 * platforms, but the best approximation is to return
2458 * "tp_packets" as the count of packets and "tp_drops"
2459 * as the count of drops.
2461 * Keep a running total because each call to
2462 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2463 * resets the counters to zero.
2465 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
2466 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
2467 *stats
= handlep
->stat
;
2473 * If the error was EOPNOTSUPP, fall through, so that
2474 * if you build the library on a system with
2475 * "struct tpacket_stats" and run it on a system
2476 * that doesn't, it works as it does if the library
2477 * is built on a system without "struct tpacket_stats".
2479 if (errno
!= EOPNOTSUPP
) {
2480 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2481 PCAP_ERRBUF_SIZE
, errno
, "pcap_stats");
2487 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2488 * is not supported on PF_PACKET sockets:
2490 * "ps_recv" counts only packets that *passed* the filter,
2491 * not packets that didn't pass the filter. It does not
2492 * count packets dropped because we ran out of buffer
2495 * "ps_drop" is not supported.
2497 * "ps_ifdrop" is supported. It will return the number
2498 * of drops the interface reports in /proc/net/dev,
2499 * if that is available.
2501 * "ps_recv" doesn't include packets not yet read from
2502 * the kernel by libpcap.
2504 * We maintain the count of packets processed by libpcap in
2505 * "handlep->packets_read", for reasons described in the comment
2506 * at the end of pcap_read_packet(). We have no idea how many
2507 * packets were dropped by the kernel buffers -- but we know
2508 * how many the interface dropped, so we can return that.
2511 stats
->ps_recv
= handlep
->packets_read
;
2513 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2518 add_linux_if(pcap_if_list_t
*devlistp
, const char *ifname
, int fd
, char *errbuf
)
2521 char name
[512]; /* XXX - pick a size */
2523 struct ifreq ifrflags
;
2526 * Get the interface name.
2530 while (*p
!= '\0' && *p
!= ' ' && *p
!= '\t' && *p
!= '\n') {
2533 * This could be the separator between a
2534 * name and an alias number, or it could be
2535 * the separator between a name with no
2536 * alias number and the next field.
2538 * If there's a colon after digits, it
2539 * separates the name and the alias number,
2540 * otherwise it separates the name and the
2544 while (PCAP_ISDIGIT(*p
))
2548 * That was the next field,
2549 * not the alias number.
2560 * Get the flags for this interface.
2562 pcap_strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2563 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2564 if (errno
== ENXIO
|| errno
== ENODEV
)
2565 return (0); /* device doesn't actually exist - ignore it */
2566 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2567 errno
, "SIOCGIFFLAGS: %.*s",
2568 (int)sizeof(ifrflags
.ifr_name
),
2574 * Add an entry for this interface, with no addresses, if it's
2575 * not already in the list.
2577 if (find_or_add_if(devlistp
, name
, ifrflags
.ifr_flags
,
2578 get_if_flags
, errbuf
) == NULL
) {
2589 * Get from "/sys/class/net" all interfaces listed there; if they're
2590 * already in the list of interfaces we have, that won't add another
2591 * instance, but if they're not, that'll add them.
2593 * We don't bother getting any addresses for them; it appears you can't
2594 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2595 * although some other types of addresses can be fetched with SIOCGIFADDR,
2596 * we don't bother with them for now.
2598 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2599 * the list of interfaces as is, and return 0, so that we can try
2600 * scanning /proc/net/dev.
2602 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2605 scan_sys_class_net(pcap_if_list_t
*devlistp
, char *errbuf
)
2607 DIR *sys_class_net_d
;
2610 char subsystem_path
[PATH_MAX
+1];
2614 sys_class_net_d
= opendir("/sys/class/net");
2615 if (sys_class_net_d
== NULL
) {
2617 * Don't fail if it doesn't exist at all.
2619 if (errno
== ENOENT
)
2623 * Fail if we got some other error.
2625 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2626 errno
, "Can't open /sys/class/net");
2631 * Create a socket from which to fetch interface information.
2633 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
2635 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2637 (void)closedir(sys_class_net_d
);
2643 ent
= readdir(sys_class_net_d
);
2646 * Error or EOF; if errno != 0, it's an error.
2652 * Ignore "." and "..".
2654 if (strcmp(ent
->d_name
, ".") == 0 ||
2655 strcmp(ent
->d_name
, "..") == 0)
2659 * Ignore plain files; they do not have subdirectories
2660 * and thus have no attributes.
2662 if (ent
->d_type
== DT_REG
)
2666 * Is there an "ifindex" file under that name?
2667 * (We don't care whether it's a directory or
2668 * a symlink; older kernels have directories
2669 * for devices, newer kernels have symlinks to
2672 snprintf(subsystem_path
, sizeof subsystem_path
,
2673 "/sys/class/net/%s/ifindex", ent
->d_name
);
2674 if (lstat(subsystem_path
, &statb
) != 0) {
2676 * Stat failed. Either there was an error
2677 * other than ENOENT, and we don't know if
2678 * this is an interface, or it's ENOENT,
2679 * and either some part of "/sys/class/net/{if}"
2680 * disappeared, in which case it probably means
2681 * the interface disappeared, or there's no
2682 * "ifindex" file, which means it's not a
2683 * network interface.
2689 * Attempt to add the interface.
2691 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2699 * Well, we didn't fail for any other reason; did we
2700 * fail due to an error reading the directory?
2703 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2704 errno
, "Error reading /sys/class/net");
2710 (void)closedir(sys_class_net_d
);
2715 * Get from "/proc/net/dev" all interfaces listed there; if they're
2716 * already in the list of interfaces we have, that won't add another
2717 * instance, but if they're not, that'll add them.
2719 * See comments from scan_sys_class_net().
2722 scan_proc_net_dev(pcap_if_list_t
*devlistp
, char *errbuf
)
2731 proc_net_f
= fopen("/proc/net/dev", "r");
2732 if (proc_net_f
== NULL
) {
2734 * Don't fail if it doesn't exist at all.
2736 if (errno
== ENOENT
)
2740 * Fail if we got some other error.
2742 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2743 errno
, "Can't open /proc/net/dev");
2748 * Create a socket from which to fetch interface information.
2750 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
2752 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2754 (void)fclose(proc_net_f
);
2759 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2761 * Skip the first two lines - they're headers.
2769 * Skip leading white space.
2771 while (*p
== ' ' || *p
== '\t')
2773 if (*p
== '\0' || *p
== '\n')
2774 continue; /* blank line */
2777 * Attempt to add the interface.
2779 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2787 * Well, we didn't fail for any other reason; did we
2788 * fail due to an error reading the file?
2790 if (ferror(proc_net_f
)) {
2791 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2792 errno
, "Error reading /proc/net/dev");
2798 (void)fclose(proc_net_f
);
2803 * Description string for the "any" device.
2805 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2808 * A SOCK_PACKET or PF_PACKET socket can be bound to any network interface.
2811 can_be_bound(const char *name _U_
)
2817 * Get additional flags for a device, using SIOCGIFMEDIA.
2820 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
2824 unsigned int arptype
;
2826 struct ethtool_value info
;
2828 if (*flags
& PCAP_IF_LOOPBACK
) {
2830 * Loopback devices aren't wireless, and "connected"/
2831 * "disconnected" doesn't apply to them.
2833 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2837 sock
= socket(AF_INET
, SOCK_DGRAM
, 0);
2839 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
2840 "Can't create socket to get ethtool information for %s",
2846 * OK, what type of network is this?
2847 * In particular, is it wired or wireless?
2849 if (is_wifi(sock
, name
)) {
2851 * Wi-Fi, hence wireless.
2853 *flags
|= PCAP_IF_WIRELESS
;
2856 * OK, what does /sys/class/net/{if}/type contain?
2857 * (We don't use that for Wi-Fi, as it'll report
2858 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
2863 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
2864 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2865 "%s: Can't generate path name string for /sys/class/net device",
2870 fh
= fopen(pathstr
, "r");
2872 if (fscanf(fh
, "%u", &arptype
) == 1) {
2874 * OK, we got an ARPHRD_ type; what is it?
2878 #ifdef ARPHRD_LOOPBACK
2879 case ARPHRD_LOOPBACK
:
2881 * These are types to which
2882 * "connected" and "disconnected"
2883 * don't apply, so don't bother
2886 * XXX - add other types?
2895 case ARPHRD_IEEE80211
:
2896 case ARPHRD_IEEE80211_PRISM
:
2897 case ARPHRD_IEEE80211_RADIOTAP
:
2898 #ifdef ARPHRD_IEEE802154
2899 case ARPHRD_IEEE802154
:
2901 #ifdef ARPHRD_IEEE802154_MONITOR
2902 case ARPHRD_IEEE802154_MONITOR
:
2904 #ifdef ARPHRD_6LOWPAN
2905 case ARPHRD_6LOWPAN
:
2908 * Various wireless types.
2910 *flags
|= PCAP_IF_WIRELESS
;
2919 #ifdef ETHTOOL_GLINK
2920 memset(&ifr
, 0, sizeof(ifr
));
2921 pcap_strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
2922 info
.cmd
= ETHTOOL_GLINK
;
2923 ifr
.ifr_data
= (caddr_t
)&info
;
2924 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
2925 int save_errno
= errno
;
2927 switch (save_errno
) {
2932 * OK, this OS version or driver doesn't support
2933 * asking for this information.
2934 * XXX - distinguish between "this doesn't
2935 * support ethtool at all because it's not
2936 * that type of device" vs. "this doesn't
2937 * support ethtool even though it's that
2938 * type of device", and return "unknown".
2940 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2946 * OK, no such device.
2947 * The user will find that out when they try to
2948 * activate the device; just say "OK" and
2949 * don't set anything.
2958 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2960 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
2974 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2977 * It's disconnected.
2979 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2988 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
2993 * Get the list of regular interfaces first.
2995 if (pcap_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
2996 get_if_flags
) == -1)
2997 return (-1); /* failure */
3000 * Read "/sys/class/net", and add to the list of interfaces all
3001 * interfaces listed there that we don't already have, because,
3002 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
3003 * and even getifaddrs() won't return information about
3004 * interfaces with no addresses, so you need to read "/sys/class/net"
3005 * to get the names of the rest of the interfaces.
3007 ret
= scan_sys_class_net(devlistp
, errbuf
);
3009 return (-1); /* failed */
3012 * No /sys/class/net; try reading /proc/net/dev instead.
3014 if (scan_proc_net_dev(devlistp
, errbuf
) == -1)
3019 * Add the "any" device.
3020 * As it refers to all network devices, not to any particular
3021 * network device, the notion of "connected" vs. "disconnected"
3024 if (add_dev(devlistp
, "any",
3025 PCAP_IF_UP
|PCAP_IF_RUNNING
|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
3026 any_descr
, errbuf
) == NULL
)
3033 * Attach the given BPF code to the packet capture device.
3036 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
3039 struct pcap_linux
*handlep
;
3040 #ifdef SO_ATTACH_FILTER
3041 struct sock_fprog fcode
;
3042 int can_filter_in_kernel
;
3049 pcap_strlcpy(handle
->errbuf
, "setfilter: No filter specified",
3054 handlep
= handle
->priv
;
3056 /* Make our private copy of the filter */
3058 if (install_bpf_program(handle
, filter
) < 0)
3059 /* install_bpf_program() filled in errbuf */
3063 * Run user level packet filter by default. Will be overriden if
3064 * installing a kernel filter succeeds.
3066 handlep
->filter_in_userland
= 1;
3068 /* Install kernel level filter if possible */
3070 #ifdef SO_ATTACH_FILTER
3072 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
3074 * fcode.len is an unsigned short for current kernel.
3075 * I have yet to see BPF-Code with that much
3076 * instructions but still it is possible. So for the
3077 * sake of correctness I added this check.
3079 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
3081 fcode
.filter
= NULL
;
3082 can_filter_in_kernel
= 0;
3084 #endif /* USHRT_MAX */
3087 * Oh joy, the Linux kernel uses struct sock_fprog instead
3088 * of struct bpf_program and of course the length field is
3089 * of different size. Pointed out by Sebastian
3091 * Oh, and we also need to fix it up so that all "ret"
3092 * instructions with non-zero operands have MAXIMUM_SNAPLEN
3093 * as the operand if we're not capturing in memory-mapped
3094 * mode, and so that, if we're in cooked mode, all memory-
3095 * reference instructions use special magic offsets in
3096 * references to the link-layer header and assume that the
3097 * link-layer payload begins at 0; "fix_program()" will do
3100 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
3105 * Fatal error; just quit.
3106 * (The "default" case shouldn't happen; we
3107 * return -1 for that reason.)
3113 * The program performed checks that we can't make
3114 * work in the kernel.
3116 can_filter_in_kernel
= 0;
3121 * We have a filter that'll work in the kernel.
3123 can_filter_in_kernel
= 1;
3129 * NOTE: at this point, we've set both the "len" and "filter"
3130 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
3131 * those are the only members of the "sock_fprog" structure,
3132 * so we initialize every member of that structure.
3134 * If there is anything in "fcode" that is not initialized,
3135 * it is either a field added in a later kernel, or it's
3138 * If a new field is added, this code needs to be updated
3139 * to set it correctly.
3141 * If there are no other fields, then:
3143 * if the Linux kernel looks at the padding, it's
3146 * if the Linux kernel doesn't look at the padding,
3147 * then if some tool complains that we're passing
3148 * uninitialized data to the kernel, then the tool
3149 * is buggy and needs to understand that it's just
3152 if (can_filter_in_kernel
) {
3153 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
3156 * Installation succeded - using kernel filter,
3157 * so userland filtering not needed.
3159 handlep
->filter_in_userland
= 0;
3161 else if (err
== -1) /* Non-fatal error */
3164 * Print a warning if we weren't able to install
3165 * the filter for a reason other than "this kernel
3166 * isn't configured to support socket filters.
3168 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
3170 "Warning: Kernel filter failed: %s\n",
3171 pcap_strerror(errno
));
3177 * If we're not using the kernel filter, get rid of any kernel
3178 * filter that might've been there before, e.g. because the
3179 * previous filter could work in the kernel, or because some other
3180 * code attached a filter to the socket by some means other than
3181 * calling "pcap_setfilter()". Otherwise, the kernel filter may
3182 * filter out packets that would pass the new userland filter.
3184 if (handlep
->filter_in_userland
) {
3185 if (reset_kernel_filter(handle
) == -1) {
3186 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3187 PCAP_ERRBUF_SIZE
, errno
,
3188 "can't remove kernel filter");
3189 err
= -2; /* fatal error */
3194 * Free up the copy of the filter that was made by "fix_program()".
3196 if (fcode
.filter
!= NULL
)
3202 #endif /* SO_ATTACH_FILTER */
3208 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
3210 return pcap_setfilter_linux_common(handle
, filter
, 0);
3215 * Set direction flag: Which packets do we accept on a forwarding
3216 * single device? IN, OUT or both?
3219 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
3221 #ifdef HAVE_PF_PACKET_SOCKETS
3222 struct pcap_linux
*handlep
= handle
->priv
;
3224 if (!handlep
->sock_packet
) {
3225 handle
->direction
= d
;
3230 * We're not using PF_PACKET sockets, so we can't determine
3231 * the direction of the packet.
3233 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3234 "Setting direction is not supported on SOCK_PACKET sockets");
3240 #ifndef IW_MODE_MONITOR
3243 , const char *device
)
3247 #ifdef IW_MODE_MONITOR
3248 char errbuf
[PCAP_ERRBUF_SIZE
];
3252 * See if there's a sysfs wireless directory for it.
3253 * If so, it's a wireless interface.
3255 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
3257 * Just give up here.
3261 if (stat(pathstr
, &statb
) == 0) {
3267 #ifdef IW_MODE_MONITOR
3269 * OK, maybe it's not wireless, or maybe this kernel doesn't
3270 * support sysfs. Try the wireless extensions.
3272 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
3274 * It supports the wireless extensions, so it's a Wi-Fi
3284 * Linux uses the ARP hardware type to identify the type of an
3285 * interface. pcap uses the DLT_xxx constants for this. This
3286 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
3287 * constant, as arguments, and sets "handle->linktype" to the
3288 * appropriate DLT_XXX constant and sets "handle->offset" to
3289 * the appropriate value (to make "handle->offset" plus link-layer
3290 * header length be a multiple of 4, so that the link-layer payload
3291 * will be aligned on a 4-byte boundary when capturing packets).
3292 * (If the offset isn't set here, it'll be 0; add code as appropriate
3293 * for cases where it shouldn't be 0.)
3295 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
3296 * in cooked mode; otherwise, we can't use cooked mode, so we have
3297 * to pick some type that works in raw mode, or fail.
3299 * Sets the link type to -1 if unable to map the type.
3301 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
3302 const char *device
, int cooked_ok
)
3304 static const char cdma_rmnet
[] = "cdma_rmnet";
3310 * For various annoying reasons having to do with DHCP
3311 * software, some versions of Android give the mobile-
3312 * phone-network interface an ARPHRD_ value of
3313 * ARPHRD_ETHER, even though the packets supplied by
3314 * that interface have no link-layer header, and begin
3315 * with an IP header, so that the ARPHRD_ value should
3318 * Detect those devices by checking the device name, and
3319 * use DLT_RAW for them.
3321 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
3322 handle
->linktype
= DLT_RAW
;
3327 * Is this a real Ethernet device? If so, give it a
3328 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
3329 * that an application can let you choose it, in case you're
3330 * capturing DOCSIS traffic that a Cisco Cable Modem
3331 * Termination System is putting out onto an Ethernet (it
3332 * doesn't put an Ethernet header onto the wire, it puts raw
3333 * DOCSIS frames out on the wire inside the low-level
3334 * Ethernet framing).
3336 * XXX - are there any other sorts of "fake Ethernet" that
3337 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
3338 * a Cisco CMTS won't put traffic onto it or get traffic
3339 * bridged onto it? ISDN is handled in "activate_new()",
3340 * as we fall back on cooked mode there, and we use
3341 * is_wifi() to check for 802.11 devices; are there any
3344 if (!is_wifi(sock_fd
, device
)) {
3348 * This is not a Wi-Fi device but it could be
3349 * a DSA master/management network device.
3351 ret
= iface_dsa_get_proto_info(device
, handle
);
3357 * This is a DSA master/management network
3358 * device linktype is already set by
3359 * iface_dsa_get_proto_info() set an
3360 * appropriate offset here.
3367 * It's not a Wi-Fi device; offer DOCSIS.
3369 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3371 * If that fails, just leave the list empty.
3373 if (handle
->dlt_list
!= NULL
) {
3374 handle
->dlt_list
[0] = DLT_EN10MB
;
3375 handle
->dlt_list
[1] = DLT_DOCSIS
;
3376 handle
->dlt_count
= 2;
3381 case ARPHRD_METRICOM
:
3382 case ARPHRD_LOOPBACK
:
3383 handle
->linktype
= DLT_EN10MB
;
3388 handle
->linktype
= DLT_EN3MB
;
3392 handle
->linktype
= DLT_AX25_KISS
;
3396 handle
->linktype
= DLT_PRONET
;
3400 handle
->linktype
= DLT_CHAOS
;
3403 #define ARPHRD_CAN 280
3407 * Map this to DLT_LINUX_SLL; that way, CAN frames will
3408 * have ETH_P_CAN/LINUX_SLL_P_CAN as the protocol and
3409 * CAN FD frames will have ETH_P_CANFD/LINUX_SLL_P_CANFD
3410 * as the protocol, so they can be distinguished by the
3411 * protocol in the SLL header.
3413 handle
->linktype
= DLT_LINUX_SLL
;
3416 #ifndef ARPHRD_IEEE802_TR
3417 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
3419 case ARPHRD_IEEE802_TR
:
3420 case ARPHRD_IEEE802
:
3421 handle
->linktype
= DLT_IEEE802
;
3426 handle
->linktype
= DLT_ARCNET_LINUX
;
3429 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
3430 #define ARPHRD_FDDI 774
3433 handle
->linktype
= DLT_FDDI
;
3437 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
3438 #define ARPHRD_ATM 19
3442 * The Classical IP implementation in ATM for Linux
3443 * supports both what RFC 1483 calls "LLC Encapsulation",
3444 * in which each packet has an LLC header, possibly
3445 * with a SNAP header as well, prepended to it, and
3446 * what RFC 1483 calls "VC Based Multiplexing", in which
3447 * different virtual circuits carry different network
3448 * layer protocols, and no header is prepended to packets.
3450 * They both have an ARPHRD_ type of ARPHRD_ATM, so
3451 * you can't use the ARPHRD_ type to find out whether
3452 * captured packets will have an LLC header, and,
3453 * while there's a socket ioctl to *set* the encapsulation
3454 * type, there's no ioctl to *get* the encapsulation type.
3458 * programs that dissect Linux Classical IP frames
3459 * would have to check for an LLC header and,
3460 * depending on whether they see one or not, dissect
3461 * the frame as LLC-encapsulated or as raw IP (I
3462 * don't know whether there's any traffic other than
3463 * IP that would show up on the socket, or whether
3464 * there's any support for IPv6 in the Linux
3465 * Classical IP code);
3467 * filter expressions would have to compile into
3468 * code that checks for an LLC header and does
3471 * Both of those are a nuisance - and, at least on systems
3472 * that support PF_PACKET sockets, we don't have to put
3473 * up with those nuisances; instead, we can just capture
3474 * in cooked mode. That's what we'll do, if we can.
3475 * Otherwise, we'll just fail.
3478 handle
->linktype
= DLT_LINUX_SLL
;
3480 handle
->linktype
= -1;
3483 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
3484 #define ARPHRD_IEEE80211 801
3486 case ARPHRD_IEEE80211
:
3487 handle
->linktype
= DLT_IEEE802_11
;
3490 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
3491 #define ARPHRD_IEEE80211_PRISM 802
3493 case ARPHRD_IEEE80211_PRISM
:
3494 handle
->linktype
= DLT_PRISM_HEADER
;
3497 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
3498 #define ARPHRD_IEEE80211_RADIOTAP 803
3500 case ARPHRD_IEEE80211_RADIOTAP
:
3501 handle
->linktype
= DLT_IEEE802_11_RADIO
;
3506 * Some PPP code in the kernel supplies no link-layer
3507 * header whatsoever to PF_PACKET sockets; other PPP
3508 * code supplies PPP link-layer headers ("syncppp.c");
3509 * some PPP code might supply random link-layer
3510 * headers (PPP over ISDN - there's code in Ethereal,
3511 * for example, to cope with PPP-over-ISDN captures
3512 * with which the Ethereal developers have had to cope,
3513 * heuristically trying to determine which of the
3514 * oddball link-layer headers particular packets have).
3516 * As such, we just punt, and run all PPP interfaces
3517 * in cooked mode, if we can; otherwise, we just treat
3518 * it as DLT_RAW, for now - if somebody needs to capture,
3519 * on a 2.0[.x] kernel, on PPP devices that supply a
3520 * link-layer header, they'll have to add code here to
3521 * map to the appropriate DLT_ type (possibly adding a
3522 * new DLT_ type, if necessary).
3525 handle
->linktype
= DLT_LINUX_SLL
;
3528 * XXX - handle ISDN types here? We can't fall
3529 * back on cooked sockets, so we'd have to
3530 * figure out from the device name what type of
3531 * link-layer encapsulation it's using, and map
3532 * that to an appropriate DLT_ value, meaning
3533 * we'd map "isdnN" devices to DLT_RAW (they
3534 * supply raw IP packets with no link-layer
3535 * header) and "isdY" devices to a new DLT_I4L_IP
3536 * type that has only an Ethernet packet type as
3537 * a link-layer header.
3539 * But sometimes we seem to get random crap
3540 * in the link-layer header when capturing on
3543 handle
->linktype
= DLT_RAW
;
3547 #ifndef ARPHRD_CISCO
3548 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3551 handle
->linktype
= DLT_C_HDLC
;
3554 /* Not sure if this is correct for all tunnels, but it
3558 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3566 #ifndef ARPHRD_RAWHDLC
3567 #define ARPHRD_RAWHDLC 518
3569 case ARPHRD_RAWHDLC
:
3571 #define ARPHRD_DLCI 15
3575 * XXX - should some of those be mapped to DLT_LINUX_SLL
3576 * instead? Should we just map all of them to DLT_LINUX_SLL?
3578 handle
->linktype
= DLT_RAW
;
3582 #define ARPHRD_FRAD 770
3585 handle
->linktype
= DLT_FRELAY
;
3588 case ARPHRD_LOCALTLK
:
3589 handle
->linktype
= DLT_LTALK
;
3594 * RFC 4338 defines an encapsulation for IP and ARP
3595 * packets that's compatible with the RFC 2625
3596 * encapsulation, but that uses a different ARP
3597 * hardware type and hardware addresses. That
3598 * ARP hardware type is 18; Linux doesn't define
3599 * any ARPHRD_ value as 18, but if it ever officially
3600 * supports RFC 4338-style IP-over-FC, it should define
3603 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3604 * that this will encourage its use in the future,
3605 * should Linux ever officially support RFC 4338-style
3608 handle
->linktype
= DLT_IP_OVER_FC
;
3612 #define ARPHRD_FCPP 784
3616 #define ARPHRD_FCAL 785
3620 #define ARPHRD_FCPL 786
3623 #ifndef ARPHRD_FCFABRIC
3624 #define ARPHRD_FCFABRIC 787
3626 case ARPHRD_FCFABRIC
:
3628 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3631 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3633 * and one was assigned.
3635 * In a later private discussion (spun off from a message
3636 * on the ethereal-users list) on how to get that DLT_
3637 * value in libpcap on Linux, I ended up deciding that
3638 * the best thing to do would be to have him tweak the
3639 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3640 * type, and map all those types to DLT_IP_OVER_FC:
3642 * I've checked into the libpcap and tcpdump CVS tree
3643 * support for DLT_IP_OVER_FC. In order to use that,
3644 * you'd have to modify your modified driver to return
3645 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3646 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3647 * example (the exact value doesn't matter, it can be
3648 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3651 * 11 years later, Christian Svensson wanted to map
3652 * various ARPHRD_ values to DLT_FC_2 and
3653 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3656 * https://github.com/mcr/libpcap/pull/29
3658 * There doesn't seem to be any network drivers that uses
3659 * any of the ARPHRD_FC* values for IP-over-FC, and
3660 * it's not exactly clear what the "Dummy types for non
3661 * ARP hardware" are supposed to mean (link-layer
3662 * header type? Physical network type?), so it's
3663 * not exactly clear why the ARPHRD_FC* types exist
3664 * in the first place.
3666 * For now, we map them to DLT_FC_2, and provide an
3667 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3668 * DLT_IP_OVER_FC just in case there's some old
3669 * driver out there that uses one of those types for
3670 * IP-over-FC on which somebody wants to capture
3673 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
3675 * If that fails, just leave the list empty.
3677 if (handle
->dlt_list
!= NULL
) {
3678 handle
->dlt_list
[0] = DLT_FC_2
;
3679 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
3680 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
3681 handle
->dlt_count
= 3;
3683 handle
->linktype
= DLT_FC_2
;
3687 #define ARPHRD_IRDA 783
3690 /* Don't expect IP packet out of this interfaces... */
3691 handle
->linktype
= DLT_LINUX_IRDA
;
3692 /* We need to save packet direction for IrDA decoding,
3693 * so let's use "Linux-cooked" mode. Jean II
3695 * XXX - this is handled in activate_new(). */
3696 /* handlep->cooked = 1; */
3699 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3700 * is needed, please report it to <daniele@orlandi.com> */
3702 #define ARPHRD_LAPD 8445
3705 /* Don't expect IP packet out of this interfaces... */
3706 handle
->linktype
= DLT_LINUX_LAPD
;
3710 #define ARPHRD_NONE 0xFFFE
3714 * No link-layer header; packets are just IP
3715 * packets, so use DLT_RAW.
3717 handle
->linktype
= DLT_RAW
;
3720 #ifndef ARPHRD_IEEE802154
3721 #define ARPHRD_IEEE802154 804
3723 case ARPHRD_IEEE802154
:
3724 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
3727 #ifndef ARPHRD_NETLINK
3728 #define ARPHRD_NETLINK 824
3730 case ARPHRD_NETLINK
:
3731 handle
->linktype
= DLT_NETLINK
;
3733 * We need to use cooked mode, so that in sll_protocol we
3734 * pick up the netlink protocol type such as NETLINK_ROUTE,
3735 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3737 * XXX - this is handled in activate_new().
3739 /* handlep->cooked = 1; */
3742 #ifndef ARPHRD_VSOCKMON
3743 #define ARPHRD_VSOCKMON 826
3745 case ARPHRD_VSOCKMON
:
3746 handle
->linktype
= DLT_VSOCK
;
3750 handle
->linktype
= -1;
3755 #ifdef HAVE_PF_PACKET_SOCKETS
3756 /* ===== Functions to interface to the newer kernels ================== */
3758 #ifdef PACKET_RESERVE
3760 set_dlt_list_cooked(pcap_t
*handle
, int sock_fd
)
3763 unsigned int tp_reserve
;
3766 * If we can't do PACKET_RESERVE, we can't reserve extra space
3767 * for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3769 len
= sizeof(tp_reserve
);
3770 if (getsockopt(sock_fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
,
3773 * Yes, we can do DLL_LINUX_SLL2.
3775 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3777 * If that fails, just leave the list empty.
3779 if (handle
->dlt_list
!= NULL
) {
3780 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
3781 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
3782 handle
->dlt_count
= 2;
3786 #else/* PACKET_RESERVE */
3788 * The build environment doesn't define PACKET_RESERVE, so we can't reserve
3789 * extra space for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3792 set_dlt_list_cooked(pcap_t
*handle _U_
, int sock_fd _U_
)
3795 #endif /* PACKET_RESERVE */
3798 * Try to set up a PF_PACKET socket.
3799 * Returns 0 on success and a PCAP_ERROR_ value on failure.
3802 activate_new(pcap_t
*handle
, int is_any_device
)
3804 struct pcap_linux
*handlep
= handle
->priv
;
3805 const char *device
= handle
->opt
.device
;
3807 int sock_fd
, arptype
;
3808 #ifdef HAVE_PACKET_AUXDATA
3812 struct packet_mreq mr
;
3813 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3815 socklen_t len
= sizeof(bpf_extensions
);
3818 sock_fd
= open_pf_packet_socket(handle
, is_any_device
);
3821 * Failed; return its return value.
3826 /* It seems the kernel supports the new interface. */
3827 handlep
->sock_packet
= 0;
3830 * Get the interface index of the loopback device.
3831 * If the attempt fails, don't fail, just set the
3832 * "handlep->lo_ifindex" to -1.
3834 * XXX - can there be more than one device that loops
3835 * packets back, i.e. devices other than "lo"? If so,
3836 * we'd need to find them all, and have an array of
3837 * indices for them, and check all of them in
3838 * "pcap_read_packet()".
3840 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3843 * Default value for offset to align link-layer payload
3844 * on a 4-byte boundary.
3849 * What kind of frames do we have to deal with? Fall back
3850 * to cooked mode if we have an unknown interface type
3851 * or a type we know doesn't work well in raw mode.
3853 if (!is_any_device
) {
3854 /* Assume for now we don't need cooked mode. */
3855 handlep
->cooked
= 0;
3857 if (handle
->opt
.rfmon
) {
3859 * We were asked to turn on monitor mode.
3860 * Do so before we get the link-layer type,
3861 * because entering monitor mode could change
3862 * the link-layer type.
3864 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3872 * Nothing worked for turning monitor mode
3876 return PCAP_ERROR_RFMON_NOTSUP
;
3880 * Either monitor mode has been turned on for
3881 * the device, or we've been given a different
3882 * device to open for monitor mode. If we've
3883 * been given a different device, use it.
3885 if (handlep
->mondevice
!= NULL
)
3886 device
= handlep
->mondevice
;
3888 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3893 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
3894 if (handle
->linktype
== -1 ||
3895 handle
->linktype
== DLT_LINUX_SLL
||
3896 handle
->linktype
== DLT_LINUX_IRDA
||
3897 handle
->linktype
== DLT_LINUX_LAPD
||
3898 handle
->linktype
== DLT_NETLINK
||
3899 (handle
->linktype
== DLT_EN10MB
&&
3900 (strncmp("isdn", device
, 4) == 0 ||
3901 strncmp("isdY", device
, 4) == 0))) {
3903 * Unknown interface type (-1), or a
3904 * device we explicitly chose to run
3905 * in cooked mode (e.g., PPP devices),
3906 * or an ISDN device (whose link-layer
3907 * type we can only determine by using
3908 * APIs that may be different on different
3909 * kernels) - reopen in cooked mode.
3911 * If the type is unknown, return a warning;
3912 * map_arphrd_to_dlt() has already set the
3915 if (close(sock_fd
) == -1) {
3916 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3917 PCAP_ERRBUF_SIZE
, errno
, "close");
3920 sock_fd
= open_pf_packet_socket(handle
, 1);
3922 if (sock_fd
== PCAP_ERROR_NO_PF_PACKET_SOCKETS
) {
3924 * We don't support PF_PACKET/SOCK_whatever
3925 * sockets. This should never happen,
3926 * because we don't support cooked mode
3927 * without those sockets, so we
3928 * shouldn't get called if we're
3929 * running on a kernel old enough
3930 * not to support them.
3932 * The error message has already been
3933 * filled in appropriately.
3935 sock_fd
= PCAP_ERROR
;
3938 * Fatal error; the return value is the
3939 * error code, and handle->errbuf has
3940 * been set to an appropriate error
3945 handlep
->cooked
= 1;
3948 * Get rid of any link-layer type list
3949 * we allocated - this only supports cooked
3952 if (handle
->dlt_list
!= NULL
) {
3953 free(handle
->dlt_list
);
3954 handle
->dlt_list
= NULL
;
3955 handle
->dlt_count
= 0;
3956 set_dlt_list_cooked(handle
, sock_fd
);
3959 if (handle
->linktype
== -1) {
3961 * Warn that we're falling back on
3962 * cooked mode; we may want to
3963 * update "map_arphrd_to_dlt()"
3964 * to handle the new type.
3966 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3968 "supported by libpcap - "
3969 "falling back to cooked "
3975 * IrDA capture is not a real "cooked" capture,
3976 * it's IrLAP frames, not IP packets. The
3977 * same applies to LAPD capture.
3979 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3980 handle
->linktype
!= DLT_LINUX_LAPD
&&
3981 handle
->linktype
!= DLT_NETLINK
)
3982 handle
->linktype
= DLT_LINUX_SLL
;
3983 if (handle
->linktype
== -1) {
3984 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3985 "unknown arptype %d, defaulting to cooked mode",
3987 status
= PCAP_WARNING
;
3991 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3993 if (handlep
->ifindex
== -1) {
3998 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3999 handle
->errbuf
, pcap_protocol(handle
))) != 0) {
4007 if (handle
->opt
.rfmon
) {
4009 * It doesn't support monitor mode.
4012 return PCAP_ERROR_RFMON_NOTSUP
;
4016 * It uses cooked mode.
4018 handlep
->cooked
= 1;
4019 handle
->linktype
= DLT_LINUX_SLL
;
4020 handle
->dlt_list
= NULL
;
4021 handle
->dlt_count
= 0;
4022 set_dlt_list_cooked(handle
, sock_fd
);
4025 * We're not bound to a device.
4026 * For now, we're using this as an indication
4027 * that we can't transmit; stop doing that only
4028 * if we figure out how to transmit in cooked
4031 handlep
->ifindex
= -1;
4035 * Select promiscuous mode on if "promisc" is set.
4037 * Do not turn allmulti mode on if we don't select
4038 * promiscuous mode - on some devices (e.g., Orinoco
4039 * wireless interfaces), allmulti mode isn't supported
4040 * and the driver implements it by turning promiscuous
4041 * mode on, and that screws up the operation of the
4042 * card as a normal networking interface, and on no
4043 * other platform I know of does starting a non-
4044 * promiscuous capture affect which multicast packets
4045 * are received by the interface.
4049 * Hmm, how can we set promiscuous mode on all interfaces?
4050 * I am not sure if that is possible at all. For now, we
4051 * silently ignore attempts to turn promiscuous mode on
4052 * for the "any" device (so you don't have to explicitly
4053 * disable it in programs such as tcpdump).
4056 if (!is_any_device
&& handle
->opt
.promisc
) {
4057 memset(&mr
, 0, sizeof(mr
));
4058 mr
.mr_ifindex
= handlep
->ifindex
;
4059 mr
.mr_type
= PACKET_MR_PROMISC
;
4060 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
4061 &mr
, sizeof(mr
)) == -1) {
4062 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4063 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
4069 /* Enable auxillary data if supported and reserve room for
4070 * reconstructing VLAN headers. */
4071 #ifdef HAVE_PACKET_AUXDATA
4073 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
4074 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
4075 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4076 errno
, "setsockopt (PACKET_AUXDATA)");
4080 handle
->offset
+= VLAN_TAG_LEN
;
4081 #endif /* HAVE_PACKET_AUXDATA */
4084 * This is a 2.2[.x] or later kernel (we know that
4085 * because we're not using a SOCK_PACKET socket -
4086 * PF_PACKET is supported only in 2.2 and later
4089 * We can safely pass "recvfrom()" a byte count
4090 * based on the snapshot length.
4092 * If we're in cooked mode, make the snapshot length
4093 * large enough to hold a "cooked mode" header plus
4094 * 1 byte of packet data (so we don't pass a byte
4095 * count of 0 to "recvfrom()").
4096 * XXX - we don't know whether this will be DLT_LINUX_SLL
4097 * or DLT_LINUX_SLL2, so make sure it's big enough for
4098 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
4099 * that small is silly anyway.
4101 if (handlep
->cooked
) {
4102 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
4103 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
4105 handle
->bufsize
= handle
->snapshot
;
4108 * Set the offset at which to insert VLAN tags.
4109 * That should be the offset of the type field.
4111 switch (handle
->linktype
) {
4115 * The type field is after the destination and source
4118 handlep
->vlan_offset
= 2 * ETH_ALEN
;
4123 * The type field is in the last 2 bytes of the
4124 * DLT_LINUX_SLL header.
4126 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
4130 handlep
->vlan_offset
= -1; /* unknown */
4134 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
4135 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
4136 int nsec_tstamps
= 1;
4138 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
4139 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
4144 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
4147 * We've succeeded. Save the socket FD in the pcap structure.
4149 handle
->fd
= sock_fd
;
4151 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
4153 * Can we generate special code for VLAN checks?
4154 * (XXX - what if we need the special code but it's not supported
4155 * by the OS? Is that possible?)
4157 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
4158 &bpf_extensions
, &len
) == 0) {
4159 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
4161 * Yes, we can. Request that we do so.
4163 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
4166 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
4171 #ifdef HAVE_PACKET_RING
4173 * Attempt to activate with memory-mapped access.
4175 * On success, returns 1, and sets *status to 0 if there are no warnings
4176 * or to a PCAP_WARNING_ code if there is a warning.
4178 * On failure due to lack of support for memory-mapped capture, returns
4181 * On error, returns -1, and sets *status to the appropriate error code;
4182 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4185 activate_mmap(pcap_t
*handle
, int *status
)
4187 struct pcap_linux
*handlep
= handle
->priv
;
4191 * Attempt to allocate a buffer to hold the contents of one
4192 * packet, for use by the oneshot callback.
4194 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
4195 if (handlep
->oneshot_buffer
== NULL
) {
4196 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4197 errno
, "can't allocate oneshot buffer");
4198 *status
= PCAP_ERROR
;
4202 if (handle
->opt
.buffer_size
== 0) {
4203 /* by default request 2M for the ring buffer */
4204 handle
->opt
.buffer_size
= 2*1024*1024;
4206 ret
= prepare_tpacket_socket(handle
);
4208 free(handlep
->oneshot_buffer
);
4209 *status
= PCAP_ERROR
;
4212 ret
= create_ring(handle
, status
);
4215 * We don't support memory-mapped capture; our caller
4216 * will fall back on reading from the socket.
4218 free(handlep
->oneshot_buffer
);
4223 * Error attempting to enable memory-mapped capture;
4224 * fail. create_ring() has set *status.
4226 free(handlep
->oneshot_buffer
);
4231 * Success. *status has been set either to 0 if there are no
4232 * warnings or to a PCAP_WARNING_ value if there is a warning.
4234 * Override some defaults and inherit the other fields from
4236 * handle->offset is used to get the current position into the rx ring.
4237 * handle->cc is used to store the ring size.
4240 switch (handlep
->tp_version
) {
4242 handle
->read_op
= pcap_read_linux_mmap_v1
;
4245 handle
->read_op
= pcap_read_linux_mmap_v1_64
;
4247 #ifdef HAVE_TPACKET2
4249 handle
->read_op
= pcap_read_linux_mmap_v2
;
4252 #ifdef HAVE_TPACKET3
4254 handle
->read_op
= pcap_read_linux_mmap_v3
;
4258 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
4259 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
4260 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
4261 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
4262 handle
->oneshot_callback
= pcap_oneshot_mmap
;
4263 handle
->selectable_fd
= handle
->fd
;
4267 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4269 * Attempt to set the socket to the specified version of the memory-mapped
4272 * Return 0 if we succeed; return 1 if we fail because that version isn't
4273 * supported; return -1 on any other error, and set handle->errbuf.
4276 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
4278 struct pcap_linux
*handlep
= handle
->priv
;
4280 socklen_t len
= sizeof(val
);
4283 * Probe whether kernel supports the specified TPACKET version;
4284 * this also gets the length of the header for that version.
4286 * This socket option was introduced in 2.6.27, which was
4287 * also the first release with TPACKET_V2 support.
4289 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
4290 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
) {
4292 * ENOPROTOOPT means the kernel is too old to
4293 * support PACKET_HDRLEN at all, which means
4294 * it either doesn't support TPACKET at all
4295 * or supports only TPACKET_V1.
4300 /* Failed to even find out; this is a fatal error. */
4301 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4302 errno
, "can't get %s header len on packet socket",
4306 handlep
->tp_hdrlen
= val
;
4309 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
4311 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4312 errno
, "can't activate %s on packet socket", version_str
);
4315 handlep
->tp_version
= version
;
4319 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
4322 * If the instruction set for which we're compiling has both 32-bit
4323 * and 64-bit versions, and Linux support for the 64-bit version
4324 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
4325 * you get from uname() for the 64-bit version. Otherwise, leave
4326 * it undefined. (This includes ARM, which has a 64-bit version,
4327 * but Linux support for it appeared well after TPACKET_V2 support
4328 * did, so there should never be a case where 32-bit ARM code is
4329 * running o a 64-bit kernel that only supports TPACKET_V1.)
4331 * If we've omitted your favorite such architecture, please contribute
4332 * a patch. (No patch is needed for architectures that are 32-bit-only
4333 * or for which Linux has no support for 32-bit userland - or for which,
4334 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
4337 #if defined(__i386__)
4338 #define ISA_64_BIT "x86_64"
4339 #elif defined(__ppc__)
4340 #define ISA_64_BIT "ppc64"
4341 #elif defined(__sparc__)
4342 #define ISA_64_BIT "sparc64"
4343 #elif defined(__s390__)
4344 #define ISA_64_BIT "s390x"
4345 #elif defined(__mips__)
4346 #define ISA_64_BIT "mips64"
4347 #elif defined(__hppa__)
4348 #define ISA_64_BIT "parisc64"
4352 * Attempt to set the socket to version 3 of the memory-mapped header and,
4353 * if that fails because version 3 isn't supported, attempt to fall
4354 * back to version 2. If version 2 isn't supported, just leave it at
4357 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
4358 * supported; return -1 on any other error, and set handle->errbuf.
4361 prepare_tpacket_socket(pcap_t
*handle
)
4363 struct pcap_linux
*handlep
= handle
->priv
;
4364 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4368 #ifdef HAVE_TPACKET3
4370 * Try setting the version to TPACKET_V3.
4372 * The only mode in which buffering is done on PF_PACKET
4373 * sockets, so that packets might not be delivered
4374 * immediately, is TPACKET_V3 mode.
4376 * The buffering cannot be disabled in that mode, so
4377 * if the user has requested immediate mode, we don't
4380 if (!handle
->opt
.immediate
) {
4381 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
4390 * We failed for some reason other than "the
4391 * kernel doesn't support TPACKET_V3".
4396 #endif /* HAVE_TPACKET3 */
4398 #ifdef HAVE_TPACKET2
4400 * Try setting the version to TPACKET_V2.
4402 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
4411 * We failed for some reason other than "the
4412 * kernel doesn't support TPACKET_V2".
4416 #endif /* HAVE_TPACKET2 */
4419 * OK, we're using TPACKET_V1, as either that's all the kernel
4420 * supports or it doesn't support TPACKET at all. In the latter
4421 * case, create_ring() will fail, and we'll fall back on non-
4422 * memory-mapped capture.
4424 handlep
->tp_version
= TPACKET_V1
;
4425 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
4429 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
4430 * each other due to platform-dependent data type size differences.
4432 * If we have a 32-bit userland and a 64-bit kernel, use an
4433 * internally-defined TPACKET_V1_64, with which we use a 64-bit
4434 * version of the data structures.
4436 if (sizeof(long) == 4) {
4438 * This is 32-bit code.
4440 struct utsname utsname
;
4442 if (uname(&utsname
) == -1) {
4446 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4447 PCAP_ERRBUF_SIZE
, errno
, "uname failed");
4450 if (strcmp(utsname
.machine
, ISA_64_BIT
) == 0) {
4452 * uname() tells us the machine is 64-bit,
4453 * so we presumably have a 64-bit kernel.
4455 * XXX - this presumes that uname() won't lie
4456 * in 32-bit code and claim that the machine
4457 * has the 32-bit version of the ISA.
4459 handlep
->tp_version
= TPACKET_V1_64
;
4460 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr_64
);
4468 #define MAX(a,b) ((a)>(b)?(a):(b))
4471 * Attempt to set up memory-mapped access.
4473 * On success, returns 1, and sets *status to 0 if there are no warnings
4474 * or to a PCAP_WARNING_ code if there is a warning.
4476 * On failure due to lack of support for memory-mapped capture, returns
4479 * On error, returns -1, and sets *status to the appropriate error code;
4480 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4483 create_ring(pcap_t
*handle
, int *status
)
4485 struct pcap_linux
*handlep
= handle
->priv
;
4486 unsigned i
, j
, frames_per_block
;
4487 #ifdef HAVE_TPACKET3
4489 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
4490 * stuff at the end of a struct tpacket_req3 will be
4491 * ignored, so this is OK even for those sockets.
4493 struct tpacket_req3 req
;
4495 struct tpacket_req req
;
4498 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
4499 unsigned int frame_size
;
4502 * Start out assuming no warnings or errors.
4506 #ifdef TPACKET_RESERVE
4508 * TPACKET_V2 and PACKET_RESERVE were both introduced in
4509 * 2.6.27. If tp_version is for TPACKET_V1, that means
4510 * the kernel doesn't support TPACKET_V2, so it won't
4511 * support PACKET_RESERVE, either.
4513 if (handle
->tp_version
!= TPACKET_V1
&&
4514 handle
->tp_version
!= TPACKET_V1_64
) {
4516 * Reserve space for VLAN tag reconstruction.
4518 tp_reserve
= VLAN_TAG_LEN
;
4521 * If we're using DLT_LINUX_SLL2, reserve space for a
4522 * DLT_LINUX_SLL2 header.
4524 * XXX - we assume that the kernel is still adding
4525 * 16 bytes of extra space; that happens to
4526 * correspond to SLL_HDR_LEN (whether intentionally
4527 * or not - the kernel code has a raw "16" in
4528 * the expression), so we subtract SLL_HDR_LEN
4529 * from SLL2_HDR_LEN to get the additional space
4530 * needed. That also means we don't bother reserving
4531 * any additional space if we're using DLT_LINUX_SLL.
4533 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
4535 if (handle
->linktype
== DLT_LINUX_SLL2
)
4536 tp_reserve
+= SLL2_HDR_LEN
- SLL_HDR_LEN
;
4539 * Try to request that amount of reserve space.
4540 * This must be done before creating the ring buffer.
4541 * If PACKET_RESERVE is supported, creating the ring
4542 * buffer should be, although if creating the ring
4543 * buffer fails, the PACKET_RESERVE call has no effect,
4544 * so falling back on read-from-the-socket capturing
4545 * won't be affected.
4547 len
= sizeof(tp_reserve
);
4548 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4549 &tp_reserve
, len
) < 0) {
4551 * We treat ENOPROTOOPT as an error, as we
4552 * already determined that we support
4553 * TPACKET_V2 and later; see above.
4555 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4556 PCAP_ERRBUF_SIZE
, errno
,
4557 "setsockopt (PACKET_RESERVE)");
4558 *status
= PCAP_ERROR
;
4563 * Older kernel, so we can't use PACKET_RESERVE;
4564 * this means we can't reserver extra space
4565 * for a DLT_LINUX_SLL2 header.
4567 * Those kernels don't supply the information
4568 * necessary to reconstruct the VLAN tag, so
4569 * that's not an issue here, and we don't allow
4570 * DLT_LINUX_SLL2 if we can't use PACKET_RESERVE,
4571 * so that shouldn't be an issue.
4573 tp_reserve
= 0; /* nothing reserved */
4577 * Build environment for an older kernel, so we can't use
4580 * Those kernels don't supply the information necessary
4581 * to reconstruct the VLAN tag, so that's not an issue
4582 * here, and we don't allow DLT_LINUX_SLL2 if we can't
4583 * use PACKET_RESERVE, so that shouldn't be an issue.
4585 tp_reserve
= 0; /* nothing reserved */
4588 switch (handlep
->tp_version
) {
4592 #ifdef HAVE_TPACKET2
4595 /* Note that with large snapshot length (say 256K, which is
4596 * the default for recent versions of tcpdump, Wireshark,
4597 * TShark, dumpcap or 64K, the value that "-s 0" has given for
4598 * a long time with tcpdump), if we use the snapshot
4599 * length to calculate the frame length, only a few frames
4600 * will be available in the ring even with pretty
4601 * large ring size (and a lot of memory will be unused).
4603 * Ideally, we should choose a frame length based on the
4604 * minimum of the specified snapshot length and the maximum
4605 * packet size. That's not as easy as it sounds; consider,
4606 * for example, an 802.11 interface in monitor mode, where
4607 * the frame would include a radiotap header, where the
4608 * maximum radiotap header length is device-dependent.
4610 * So, for now, we just do this for Ethernet devices, where
4611 * there's no metadata header, and the link-layer header is
4612 * fixed length. We can get the maximum packet size by
4613 * adding 18, the Ethernet header length plus the CRC length
4614 * (just in case we happen to get the CRC in the packet), to
4615 * the MTU of the interface; we fetch the MTU in the hopes
4616 * that it reflects support for jumbo frames. (Even if the
4617 * interface is just being used for passive snooping, the
4618 * driver might set the size of buffers in the receive ring
4619 * based on the MTU, so that the MTU limits the maximum size
4620 * of packets that we can receive.)
4622 * If segmentation/fragmentation or receive offload are
4623 * enabled, we can get reassembled/aggregated packets larger
4624 * than MTU, but bounded to 65535 plus the Ethernet overhead,
4625 * due to kernel and protocol constraints */
4626 frame_size
= handle
->snapshot
;
4627 if (handle
->linktype
== DLT_EN10MB
) {
4628 unsigned int max_frame_len
;
4632 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
4635 *status
= PCAP_ERROR
;
4638 offload
= iface_get_offload(handle
);
4639 if (offload
== -1) {
4640 *status
= PCAP_ERROR
;
4644 max_frame_len
= MAX(mtu
, 65535);
4646 max_frame_len
= mtu
;
4647 max_frame_len
+= 18;
4649 if (frame_size
> max_frame_len
)
4650 frame_size
= max_frame_len
;
4653 /* NOTE: calculus matching those in tpacket_rcv()
4654 * in linux-2.6/net/packet/af_packet.c
4656 len
= sizeof(sk_type
);
4657 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
4659 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4660 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
4661 *status
= PCAP_ERROR
;
4664 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
4665 /* XXX: in the kernel maclen is calculated from
4666 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4667 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4668 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4669 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4670 * but I see no way to get those sizes in userspace,
4671 * like for instance with an ifreq ioctl();
4672 * the best thing I've found so far is MAX_HEADER in
4673 * the kernel part of linux-2.6/include/linux/netdevice.h
4674 * which goes up to 128+48=176; since pcap-linux.c
4675 * defines a MAX_LINKHEADER_SIZE of 256 which is
4676 * greater than that, let's use it.. maybe is it even
4677 * large enough to directly replace macoff..
4679 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
4680 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
4681 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4682 * of netoff, which contradicts
4683 * linux-2.6/Documentation/networking/packet_mmap.txt
4685 * "- Gap, chosen so that packet data (Start+tp_net)
4686 * aligns to TPACKET_ALIGNMENT=16"
4688 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4689 * "CPUs often take a performance hit
4690 * when accessing unaligned memory locations"
4692 macoff
= netoff
- maclen
;
4693 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
4695 * Round the buffer size up to a multiple of the
4696 * frame size (rather than rounding down, which
4697 * would give a buffer smaller than our caller asked
4698 * for, and possibly give zero frames if the requested
4699 * buffer size is too small for one frame).
4701 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
4704 #ifdef HAVE_TPACKET3
4706 /* The "frames" for this are actually buffers that
4707 * contain multiple variable-sized frames.
4709 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
4710 * enough room for at least one reasonably-sized packet
4711 * in the "frame". */
4712 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
4714 * Round the buffer size up to a multiple of the
4715 * "frame" size (rather than rounding down, which
4716 * would give a buffer smaller than our caller asked
4717 * for, and possibly give zero "frames" if the requested
4718 * buffer size is too small for one "frame").
4720 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
4724 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4725 "Internal error: unknown TPACKET_ value %u",
4726 handlep
->tp_version
);
4727 *status
= PCAP_ERROR
;
4731 /* compute the minumum block size that will handle this frame.
4732 * The block has to be page size aligned.
4733 * The max block size allowed by the kernel is arch-dependent and
4734 * it's not explicitly checked here. */
4735 req
.tp_block_size
= getpagesize();
4736 while (req
.tp_block_size
< req
.tp_frame_size
)
4737 req
.tp_block_size
<<= 1;
4739 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
4742 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4743 * so we check for PACKET_TIMESTAMP. We check for
4744 * linux/net_tstamp.h just in case a system somehow has
4745 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4748 * SIOCSHWTSTAMP was introduced in the patch that introduced
4749 * linux/net_tstamp.h, so we don't bother checking whether
4750 * SIOCSHWTSTAMP is defined (if your Linux system has
4751 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4752 * Linux system is badly broken).
4754 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4756 * If we were told to do so, ask the kernel and the driver
4757 * to use hardware timestamps.
4759 * Hardware timestamps are only supported with mmapped
4762 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
4763 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
4764 struct hwtstamp_config hwconfig
;
4769 * Ask for hardware time stamps on all packets,
4770 * including transmitted packets.
4772 memset(&hwconfig
, 0, sizeof(hwconfig
));
4773 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
4774 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
4776 memset(&ifr
, 0, sizeof(ifr
));
4777 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
4778 ifr
.ifr_data
= (void *)&hwconfig
;
4780 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
4785 * Treat this as an error, as the
4786 * user should try to run this
4787 * with the appropriate privileges -
4788 * and, if they can't, shouldn't
4789 * try requesting hardware time stamps.
4791 *status
= PCAP_ERROR_PERM_DENIED
;
4797 * Treat this as a warning, as the
4798 * only way to fix the warning is to
4799 * get an adapter that supports hardware
4800 * time stamps for *all* packets.
4801 * (ERANGE means "we support hardware
4802 * time stamps, but for packets matching
4803 * that particular filter", so it means
4804 * "we don't support hardware time stamps
4805 * for all incoming packets" here.)
4807 * We'll just fall back on the standard
4810 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
4814 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4815 PCAP_ERRBUF_SIZE
, errno
,
4816 "SIOCSHWTSTAMP failed");
4817 *status
= PCAP_ERROR
;
4822 * Well, that worked. Now specify the type of
4823 * hardware time stamp we want for this
4826 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
4828 * Hardware timestamp, synchronized
4829 * with the system clock.
4831 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
4834 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4835 * timestamp, not synchronized with the
4838 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
4840 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
4841 (void *)×ource
, sizeof(timesource
))) {
4842 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4843 PCAP_ERRBUF_SIZE
, errno
,
4844 "can't set PACKET_TIMESTAMP");
4845 *status
= PCAP_ERROR
;
4850 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4852 /* ask the kernel to create the ring */
4854 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
4856 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4857 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
4859 #ifdef HAVE_TPACKET3
4860 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4861 if (handlep
->timeout
> 0) {
4862 /* Use the user specified timeout as the block timeout */
4863 req
.tp_retire_blk_tov
= handlep
->timeout
;
4864 } else if (handlep
->timeout
== 0) {
4866 * In pcap, this means "infinite timeout"; TPACKET_V3
4867 * doesn't support that, so just set it to UINT_MAX
4868 * milliseconds. In the TPACKET_V3 loop, if the
4869 * timeout is 0, and we haven't yet seen any packets,
4870 * and we block and still don't have any packets, we
4871 * keep blocking until we do.
4873 req
.tp_retire_blk_tov
= UINT_MAX
;
4876 * XXX - this is not valid; use 0, meaning "have the
4877 * kernel pick a default", for now.
4879 req
.tp_retire_blk_tov
= 0;
4881 /* private data not used */
4882 req
.tp_sizeof_priv
= 0;
4883 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4884 req
.tp_feature_req_word
= 0;
4887 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4888 (void *) &req
, sizeof(req
))) {
4889 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
4891 * Memory failure; try to reduce the requested ring
4894 * We used to reduce this by half -- do 5% instead.
4895 * That may result in more iterations and a longer
4896 * startup, but the user will be much happier with
4897 * the resulting buffer size.
4899 if (req
.tp_frame_nr
< 20)
4900 req
.tp_frame_nr
-= 1;
4902 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
4905 if (errno
== ENOPROTOOPT
) {
4907 * We don't have ring buffer support in this kernel.
4911 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4912 errno
, "can't create rx ring on packet socket");
4913 *status
= PCAP_ERROR
;
4917 /* memory map the rx ring */
4918 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
4919 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
4920 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
4921 if (handlep
->mmapbuf
== MAP_FAILED
) {
4922 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4923 errno
, "can't mmap rx ring");
4925 /* clear the allocated ring on error*/
4926 destroy_ring(handle
);
4927 *status
= PCAP_ERROR
;
4931 /* allocate a ring for each frame header pointer*/
4932 handle
->cc
= req
.tp_frame_nr
;
4933 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
4934 if (!handle
->buffer
) {
4935 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4936 errno
, "can't allocate ring of frame headers");
4938 destroy_ring(handle
);
4939 *status
= PCAP_ERROR
;
4943 /* fill the header ring with proper frame ptr*/
4945 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
4946 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
4947 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
4948 RING_GET_CURRENT_FRAME(handle
) = base
;
4949 base
+= req
.tp_frame_size
;
4953 handle
->bufsize
= req
.tp_frame_size
;
4958 /* free all ring related resources*/
4960 destroy_ring(pcap_t
*handle
)
4962 struct pcap_linux
*handlep
= handle
->priv
;
4964 /* tell the kernel to destroy the ring*/
4965 struct tpacket_req req
;
4966 memset(&req
, 0, sizeof(req
));
4967 /* do not test for setsockopt failure, as we can't recover from any error */
4968 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4969 (void *) &req
, sizeof(req
));
4971 /* if ring is mapped, unmap it*/
4972 if (handlep
->mmapbuf
) {
4973 /* do not test for mmap failure, as we can't recover from any error */
4974 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
4975 handlep
->mmapbuf
= NULL
;
4980 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4981 * for Linux mmapped capture.
4983 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4984 * data handed to the callback to be valid after the callback returns,
4985 * but pcap_read_linux_mmap() has to release that packet as soon as
4986 * the callback returns (otherwise, the kernel thinks there's still
4987 * at least one unprocessed packet available in the ring, so a select()
4988 * will immediately return indicating that there's data to process), so,
4989 * in the callback, we have to make a copy of the packet.
4991 * Yes, this means that, if the capture is using the ring buffer, using
4992 * pcap_next() or pcap_next_ex() requires more copies than using
4993 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4994 * pcap_next() or pcap_next_ex().
4997 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
4998 const u_char
*bytes
)
5000 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
5001 pcap_t
*handle
= sp
->pd
;
5002 struct pcap_linux
*handlep
= handle
->priv
;
5005 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
5006 *sp
->pkt
= handlep
->oneshot_buffer
;
5010 pcap_cleanup_linux_mmap( pcap_t
*handle
)
5012 struct pcap_linux
*handlep
= handle
->priv
;
5014 destroy_ring(handle
);
5015 if (handlep
->oneshot_buffer
!= NULL
) {
5016 free(handlep
->oneshot_buffer
);
5017 handlep
->oneshot_buffer
= NULL
;
5019 pcap_cleanup_linux(handle
);
5024 pcap_getnonblock_mmap(pcap_t
*handle
)
5026 struct pcap_linux
*handlep
= handle
->priv
;
5028 /* use negative value of timeout to indicate non blocking ops */
5029 return (handlep
->timeout
<0);
5033 pcap_setnonblock_mmap(pcap_t
*handle
, int nonblock
)
5035 struct pcap_linux
*handlep
= handle
->priv
;
5038 * Set the file descriptor to non-blocking mode, as we use
5039 * it for sending packets.
5041 if (pcap_setnonblock_fd(handle
, nonblock
) == -1)
5045 * Map each value to their corresponding negation to
5046 * preserve the timeout value provided with pcap_set_timeout.
5049 if (handlep
->timeout
>= 0) {
5051 * Indicate that we're switching to
5052 * non-blocking mode.
5054 handlep
->timeout
= ~handlep
->timeout
;
5057 if (handlep
->timeout
< 0) {
5058 handlep
->timeout
= ~handlep
->timeout
;
5061 /* Update the timeout to use in poll(). */
5062 set_poll_timeout(handlep
);
5067 * Get the status field of the ring buffer frame at a specified offset.
5070 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
5072 struct pcap_linux
*handlep
= handle
->priv
;
5075 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
5076 switch (handlep
->tp_version
) {
5079 * This is an unsigned long, but only the lower 32
5082 return (u_int
)(h
.h1
->tp_status
);
5086 * This is an unsigned long in the kernel, which is 64-bit,
5087 * but only the lower 32 bits are used.
5089 return (u_int
)(h
.h1_64
->tp_status
);
5091 #ifdef HAVE_TPACKET2
5093 return (h
.h2
->tp_status
);
5096 #ifdef HAVE_TPACKET3
5098 return (h
.h3
->hdr
.bh1
.block_status
);
5102 /* This should not happen. */
5111 * Block waiting for frames to be available.
5113 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
5115 struct pcap_linux
*handlep
= handle
->priv
;
5118 #ifdef HAVE_SYS_EVENTFD_H
5119 struct pollfd pollinfo
[2];
5120 pollinfo
[1].fd
= handlep
->poll_breakloop_fd
;
5121 pollinfo
[1].events
= POLLIN
;
5123 struct pollfd pollinfo
[1];
5125 pollinfo
[0].fd
= handle
->fd
;
5126 pollinfo
[0].events
= POLLIN
;
5130 * Yes, we do this even in non-blocking mode, as it's
5131 * the only way to get error indications from a
5134 * The timeout is 0 in non-blocking mode, so poll()
5135 * returns immediately.
5138 #ifdef HAVE_SYS_EVENTFD_H
5139 ret
= poll(pollinfo
, 2, handlep
->poll_timeout
);
5141 ret
= poll(pollinfo
, 1, handlep
->poll_timeout
);
5143 if (ret
< 0 && errno
!= EINTR
) {
5144 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5145 PCAP_ERRBUF_SIZE
, errno
,
5146 "can't poll on packet socket");
5148 } else if (ret
> 0 && pollinfo
[0].revents
&&
5149 (pollinfo
[0].revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
5151 * There's some indication other than
5152 * "you can read on this descriptor" on
5155 if (pollinfo
[0].revents
& (POLLHUP
| POLLRDHUP
)) {
5156 snprintf(handle
->errbuf
,
5158 "Hangup on packet socket");
5161 if (pollinfo
[0].revents
& POLLERR
) {
5163 * A recv() will give us the actual error code.
5165 * XXX - make the socket non-blocking?
5167 if (recv(handle
->fd
, &c
, sizeof c
,
5169 continue; /* what, no error? */
5170 if (errno
== ENETDOWN
) {
5172 * The device on which we're
5173 * capturing went away.
5175 * XXX - we should really return
5176 * PCAP_ERROR_IFACE_NOT_UP, but
5177 * pcap_dispatch() etc. aren't
5178 * defined to return that.
5180 snprintf(handle
->errbuf
,
5182 "The interface went down");
5184 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5185 PCAP_ERRBUF_SIZE
, errno
,
5186 "Error condition on packet socket");
5190 if (pollinfo
[0].revents
& POLLNVAL
) {
5191 snprintf(handle
->errbuf
,
5193 "Invalid polling request on packet socket");
5198 #ifdef HAVE_SYS_EVENTFD_H
5199 if (pollinfo
[1].revents
& POLLIN
) {
5201 (void)read(handlep
->poll_breakloop_fd
, &value
, sizeof(value
));
5205 /* check for break loop condition on interrupted syscall*/
5206 if (handle
->break_loop
) {
5207 handle
->break_loop
= 0;
5208 return PCAP_ERROR_BREAK
;
5214 /* handle a single memory mapped packet */
5215 static int pcap_handle_packet_mmap(
5217 pcap_handler callback
,
5219 unsigned char *frame
,
5220 unsigned int tp_len
,
5221 unsigned int tp_mac
,
5222 unsigned int tp_snaplen
,
5223 unsigned int tp_sec
,
5224 unsigned int tp_usec
,
5225 int tp_vlan_tci_valid
,
5229 struct pcap_linux
*handlep
= handle
->priv
;
5231 struct sockaddr_ll
*sll
;
5232 struct pcap_pkthdr pcaphdr
;
5233 unsigned int snaplen
= tp_snaplen
;
5234 struct utsname utsname
;
5236 /* perform sanity check on internal offset. */
5237 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
5239 * Report some system information as a debugging aid.
5241 if (uname(&utsname
) != -1) {
5242 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5243 "corrupted frame on kernel ring mac "
5244 "offset %u + caplen %u > frame len %d "
5245 "(kernel %.32s version %s, machine %.16s)",
5246 tp_mac
, tp_snaplen
, handle
->bufsize
,
5247 utsname
.release
, utsname
.version
,
5250 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5251 "corrupted frame on kernel ring mac "
5252 "offset %u + caplen %u > frame len %d",
5253 tp_mac
, tp_snaplen
, handle
->bufsize
);
5258 /* run filter on received packet
5259 * If the kernel filtering is enabled we need to run the
5260 * filter until all the frames present into the ring
5261 * at filter creation time are processed.
5262 * In this case, blocks_to_filter_in_userland is used
5263 * as a counter for the packet we need to filter.
5264 * Note: alternatively it could be possible to stop applying
5265 * the filter when the ring became empty, but it can possibly
5266 * happen a lot later... */
5267 bp
= frame
+ tp_mac
;
5269 /* if required build in place the sll header*/
5270 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
5271 if (handlep
->cooked
) {
5272 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5273 struct sll2_header
*hdrp
;
5276 * The kernel should have left us with enough
5277 * space for an sll header; back up the packet
5278 * data pointer into that space, as that'll be
5279 * the beginning of the packet we pass to the
5285 * Let's make sure that's past the end of
5286 * the tpacket header, i.e. >=
5287 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5288 * don't step on the header when we construct
5291 if (bp
< (u_char
*)frame
+
5292 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
5293 sizeof(struct sockaddr_ll
)) {
5294 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5295 "cooked-mode frame doesn't have room for sll header");
5300 * OK, that worked; construct the sll header.
5302 hdrp
= (struct sll2_header
*)bp
;
5303 hdrp
->sll2_protocol
= sll
->sll_protocol
;
5304 hdrp
->sll2_reserved_mbz
= 0;
5305 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
5306 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
5307 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
5308 hdrp
->sll2_halen
= sll
->sll_halen
;
5309 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
5311 snaplen
+= sizeof(struct sll2_header
);
5313 struct sll_header
*hdrp
;
5316 * The kernel should have left us with enough
5317 * space for an sll header; back up the packet
5318 * data pointer into that space, as that'll be
5319 * the beginning of the packet we pass to the
5325 * Let's make sure that's past the end of
5326 * the tpacket header, i.e. >=
5327 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5328 * don't step on the header when we construct
5331 if (bp
< (u_char
*)frame
+
5332 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
5333 sizeof(struct sockaddr_ll
)) {
5334 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5335 "cooked-mode frame doesn't have room for sll header");
5340 * OK, that worked; construct the sll header.
5342 hdrp
= (struct sll_header
*)bp
;
5343 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
5344 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
5345 hdrp
->sll_halen
= htons(sll
->sll_halen
);
5346 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
5347 hdrp
->sll_protocol
= sll
->sll_protocol
;
5349 snaplen
+= sizeof(struct sll_header
);
5353 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
5354 struct bpf_aux_data aux_data
;
5356 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
5357 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
5359 if (pcap_filter_with_aux_data(handle
->fcode
.bf_insns
,
5367 if (!linux_check_direction(handle
, sll
))
5370 /* get required packet info from ring header */
5371 pcaphdr
.ts
.tv_sec
= tp_sec
;
5372 pcaphdr
.ts
.tv_usec
= tp_usec
;
5373 pcaphdr
.caplen
= tp_snaplen
;
5374 pcaphdr
.len
= tp_len
;
5376 /* if required build in place the sll header*/
5377 if (handlep
->cooked
) {
5378 /* update packet len */
5379 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5380 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
5381 pcaphdr
.len
+= SLL2_HDR_LEN
;
5383 pcaphdr
.caplen
+= SLL_HDR_LEN
;
5384 pcaphdr
.len
+= SLL_HDR_LEN
;
5388 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
5389 if (tp_vlan_tci_valid
&&
5390 handlep
->vlan_offset
!= -1 &&
5391 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
5393 struct vlan_tag
*tag
;
5396 * Move everything in the header, except the type field,
5397 * down VLAN_TAG_LEN bytes, to allow us to insert the
5398 * VLAN tag between that stuff and the type field.
5401 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
5404 * Now insert the tag.
5406 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
5407 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
5408 tag
->vlan_tci
= htons(tp_vlan_tci
);
5411 * Add the tag to the packet lengths.
5413 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
5414 pcaphdr
.len
+= VLAN_TAG_LEN
;
5419 * The only way to tell the kernel to cut off the
5420 * packet at a snapshot length is with a filter program;
5421 * if there's no filter program, the kernel won't cut
5424 * Trim the snapshot length to be no longer than the
5425 * specified snapshot length.
5427 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
5428 pcaphdr
.caplen
= handle
->snapshot
;
5430 /* pass the packet to the user */
5431 callback(user
, &pcaphdr
, bp
);
5437 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5440 struct pcap_linux
*handlep
= handle
->priv
;
5445 /* wait for frames availability.*/
5446 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5447 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
) {
5449 * The current frame is owned by the kernel; wait for
5450 * a frame to be handed to us.
5452 ret
= pcap_wait_for_frames_mmap(handle
);
5458 /* non-positive values of max_packets are used to require all
5459 * packets currently available in the ring */
5460 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5462 * Get the current ring buffer frame, and break if
5463 * it's still owned by the kernel.
5465 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5466 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
)
5469 ret
= pcap_handle_packet_mmap(
5484 handlep
->packets_read
++;
5485 } else if (ret
< 0) {
5490 * Hand this block back to the kernel, and, if we're
5491 * counting blocks that need to be filtered in userland
5492 * after having been filtered by the kernel, count
5493 * the one we've just processed.
5495 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
5496 if (handlep
->blocks_to_filter_in_userland
> 0) {
5497 handlep
->blocks_to_filter_in_userland
--;
5498 if (handlep
->blocks_to_filter_in_userland
== 0) {
5500 * No more blocks need to be filtered
5503 handlep
->filter_in_userland
= 0;
5508 if (++handle
->offset
>= handle
->cc
)
5511 /* check for break loop condition*/
5512 if (handle
->break_loop
) {
5513 handle
->break_loop
= 0;
5514 return PCAP_ERROR_BREAK
;
5521 pcap_read_linux_mmap_v1_64(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5524 struct pcap_linux
*handlep
= handle
->priv
;
5529 /* wait for frames availability.*/
5530 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5531 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
) {
5533 * The current frame is owned by the kernel; wait for
5534 * a frame to be handed to us.
5536 ret
= pcap_wait_for_frames_mmap(handle
);
5542 /* non-positive values of max_packets are used to require all
5543 * packets currently available in the ring */
5544 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5546 * Get the current ring buffer frame, and break if
5547 * it's still owned by the kernel.
5549 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5550 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
)
5553 ret
= pcap_handle_packet_mmap(
5560 h
.h1_64
->tp_snaplen
,
5568 handlep
->packets_read
++;
5569 } else if (ret
< 0) {
5574 * Hand this block back to the kernel, and, if we're
5575 * counting blocks that need to be filtered in userland
5576 * after having been filtered by the kernel, count
5577 * the one we've just processed.
5579 h
.h1_64
->tp_status
= TP_STATUS_KERNEL
;
5580 if (handlep
->blocks_to_filter_in_userland
> 0) {
5581 handlep
->blocks_to_filter_in_userland
--;
5582 if (handlep
->blocks_to_filter_in_userland
== 0) {
5584 * No more blocks need to be filtered
5587 handlep
->filter_in_userland
= 0;
5592 if (++handle
->offset
>= handle
->cc
)
5595 /* check for break loop condition*/
5596 if (handle
->break_loop
) {
5597 handle
->break_loop
= 0;
5598 return PCAP_ERROR_BREAK
;
5604 #ifdef HAVE_TPACKET2
5606 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5609 struct pcap_linux
*handlep
= handle
->priv
;
5614 /* wait for frames availability.*/
5615 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5616 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
) {
5618 * The current frame is owned by the kernel; wait for
5619 * a frame to be handed to us.
5621 ret
= pcap_wait_for_frames_mmap(handle
);
5627 /* non-positive values of max_packets are used to require all
5628 * packets currently available in the ring */
5629 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5631 * Get the current ring buffer frame, and break if
5632 * it's still owned by the kernel.
5634 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5635 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
)
5638 ret
= pcap_handle_packet_mmap(
5647 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
5648 VLAN_VALID(h
.h2
, h
.h2
),
5650 VLAN_TPID(h
.h2
, h
.h2
));
5653 handlep
->packets_read
++;
5654 } else if (ret
< 0) {
5659 * Hand this block back to the kernel, and, if we're
5660 * counting blocks that need to be filtered in userland
5661 * after having been filtered by the kernel, count
5662 * the one we've just processed.
5664 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
5665 if (handlep
->blocks_to_filter_in_userland
> 0) {
5666 handlep
->blocks_to_filter_in_userland
--;
5667 if (handlep
->blocks_to_filter_in_userland
== 0) {
5669 * No more blocks need to be filtered
5672 handlep
->filter_in_userland
= 0;
5677 if (++handle
->offset
>= handle
->cc
)
5680 /* check for break loop condition*/
5681 if (handle
->break_loop
) {
5682 handle
->break_loop
= 0;
5683 return PCAP_ERROR_BREAK
;
5688 #endif /* HAVE_TPACKET2 */
5690 #ifdef HAVE_TPACKET3
5692 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5695 struct pcap_linux
*handlep
= handle
->priv
;
5701 if (handlep
->current_packet
== NULL
) {
5702 /* wait for frames availability.*/
5703 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5704 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
5706 * The current frame is owned by the kernel; wait
5707 * for a frame to be handed to us.
5709 ret
= pcap_wait_for_frames_mmap(handle
);
5715 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5716 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
5717 if (pkts
== 0 && handlep
->timeout
== 0) {
5718 /* Block until we see a packet. */
5724 /* non-positive values of max_packets are used to require all
5725 * packets currently available in the ring */
5726 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5727 int packets_to_read
;
5729 if (handlep
->current_packet
== NULL
) {
5730 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5731 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
)
5734 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
5735 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
5737 packets_to_read
= handlep
->packets_left
;
5739 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) &&
5740 packets_to_read
> (max_packets
- pkts
)) {
5742 * We've been given a maximum number of packets
5743 * to process, and there are more packets in
5744 * this buffer than that. Only process enough
5745 * of them to get us up to that maximum.
5747 packets_to_read
= max_packets
- pkts
;
5750 while (packets_to_read
-- && !handle
->break_loop
) {
5751 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
5752 ret
= pcap_handle_packet_mmap(
5756 handlep
->current_packet
,
5759 tp3_hdr
->tp_snaplen
,
5761 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
5762 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
5763 tp3_hdr
->hv1
.tp_vlan_tci
,
5764 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
5767 handlep
->packets_read
++;
5768 } else if (ret
< 0) {
5769 handlep
->current_packet
= NULL
;
5772 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
5773 handlep
->packets_left
--;
5776 if (handlep
->packets_left
<= 0) {
5778 * Hand this block back to the kernel, and, if
5779 * we're counting blocks that need to be
5780 * filtered in userland after having been
5781 * filtered by the kernel, count the one we've
5784 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
5785 if (handlep
->blocks_to_filter_in_userland
> 0) {
5786 handlep
->blocks_to_filter_in_userland
--;
5787 if (handlep
->blocks_to_filter_in_userland
== 0) {
5789 * No more blocks need to be filtered
5792 handlep
->filter_in_userland
= 0;
5797 if (++handle
->offset
>= handle
->cc
)
5800 handlep
->current_packet
= NULL
;
5803 /* check for break loop condition*/
5804 if (handle
->break_loop
) {
5805 handle
->break_loop
= 0;
5806 return PCAP_ERROR_BREAK
;
5809 if (pkts
== 0 && handlep
->timeout
== 0) {
5810 /* Block until we see a packet. */
5815 #endif /* HAVE_TPACKET3 */
5818 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
5820 struct pcap_linux
*handlep
= handle
->priv
;
5825 * Don't rewrite "ret" instructions; we don't need to, as
5826 * we're not reading packets with recvmsg(), and we don't
5827 * want to, as, by not rewriting them, the kernel can avoid
5828 * copying extra data.
5830 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
5835 * If we're filtering in userland, there's nothing to do;
5836 * the new filter will be used for the next packet.
5838 if (handlep
->filter_in_userland
)
5842 * We're filtering in the kernel; the packets present in
5843 * all blocks currently in the ring were already filtered
5844 * by the old filter, and so will need to be filtered in
5845 * userland by the new filter.
5847 * Get an upper bound for the number of such blocks; first,
5848 * walk the ring backward and count the free blocks.
5850 offset
= handle
->offset
;
5852 offset
= handle
->cc
- 1;
5853 for (n
=0; n
< handle
->cc
; ++n
) {
5855 offset
= handle
->cc
- 1;
5856 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
5861 * If we found free blocks, decrement the count of free
5862 * blocks by 1, just in case we lost a race with another
5863 * thread of control that was adding a packet while
5864 * we were counting and that had run the filter before
5867 * XXX - could there be more than one block added in
5870 * XXX - is there a way to avoid that race, e.g. somehow
5871 * wait for all packets that passed the old filter to
5872 * be added to the ring?
5878 * Set the count of blocks worth of packets to filter
5879 * in userland to the total number of blocks in the
5880 * ring minus the number of free blocks we found, and
5881 * turn on userland filtering. (The count of blocks
5882 * worth of packets to filter in userland is guaranteed
5883 * not to be zero - n, above, couldn't be set to a
5884 * value > handle->cc, and if it were equal to
5885 * handle->cc, it wouldn't be zero, and thus would
5886 * be decremented to handle->cc - 1.)
5888 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
5889 handlep
->filter_in_userland
= 1;
5892 #endif /* HAVE_PACKET_RING */
5895 * Return the index of the given device name. Fill ebuf and return
5899 iface_get_id(int fd
, const char *device
, char *ebuf
)
5903 memset(&ifr
, 0, sizeof(ifr
));
5904 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5906 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
5907 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5908 errno
, "SIOCGIFINDEX");
5912 return ifr
.ifr_ifindex
;
5916 * Bind the socket associated with FD to the given device.
5917 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
5920 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
5922 struct sockaddr_ll sll
;
5924 socklen_t errlen
= sizeof(err
);
5926 memset(&sll
, 0, sizeof(sll
));
5927 sll
.sll_family
= AF_PACKET
;
5928 sll
.sll_ifindex
= ifindex
;
5929 sll
.sll_protocol
= protocol
;
5931 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
5932 if (errno
== ENETDOWN
) {
5934 * Return a "network down" indication, so that
5935 * the application can report that rather than
5936 * saying we had a mysterious failure and
5937 * suggest that they report a problem to the
5938 * libpcap developers.
5940 return PCAP_ERROR_IFACE_NOT_UP
;
5942 if (errno
== ENODEV
)
5943 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
5946 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5951 /* Any pending errors, e.g., network is down? */
5953 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5954 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5955 errno
, "getsockopt (SO_ERROR)");
5959 if (err
== ENETDOWN
) {
5961 * Return a "network down" indication, so that
5962 * the application can report that rather than
5963 * saying we had a mysterious failure and
5964 * suggest that they report a problem to the
5965 * libpcap developers.
5967 return PCAP_ERROR_IFACE_NOT_UP
;
5968 } else if (err
> 0) {
5969 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5977 #ifdef IW_MODE_MONITOR
5979 * Check whether the device supports the Wireless Extensions.
5980 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5981 * if the device doesn't even exist.
5984 has_wext(int sock_fd
, const char *device
, char *ebuf
)
5989 if (is_bonding_device(sock_fd
, device
))
5990 return 0; /* bonding device, so don't even try */
5992 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5993 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5994 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
5996 if (errno
== ENODEV
)
5997 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
6000 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
,
6001 "%s: SIOCGIWNAME", device
);
6006 * Per me si va ne la citta dolente,
6007 * Per me si va ne l'etterno dolore,
6009 * Lasciate ogne speranza, voi ch'intrate.
6011 * XXX - airmon-ng does special stuff with the Orinoco driver and the
6027 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
6028 * on if it's not already on.
6030 * Returns 1 on success, 0 if we don't support the Wireless Extensions
6031 * on this device, or a PCAP_ERROR_ value if we do support them but
6032 * we weren't able to turn monitor mode on.
6035 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
6038 * XXX - at least some adapters require non-Wireless Extensions
6039 * mechanisms to turn monitor mode on.
6041 * Atheros cards might require that a separate "monitor virtual access
6042 * point" be created, with later versions of the madwifi driver.
6043 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
6044 * monitor -bssid", which apparently spits out a line "athN"
6045 * where "athN" is the monitor mode device. To leave monitor
6046 * mode, it destroys the monitor mode device.
6048 * Some Intel Centrino adapters might require private ioctls to get
6049 * radio headers; the ipw2200 and ipw3945 drivers allow you to
6050 * configure a separate "rtapN" interface to capture in monitor
6051 * mode without preventing the adapter from operating normally.
6052 * (airmon-ng doesn't appear to use that, though.)
6054 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
6055 * up, and if all drivers were converted to mac80211 drivers.
6057 * If interface {if} is a mac80211 driver, the file
6058 * /sys/class/net/{if}/phy80211 is a symlink to
6059 * /sys/class/ieee80211/{phydev}, for some {phydev}.
6061 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
6062 * least, has a "wmaster0" device and a "wlan0" device; the
6063 * latter is the one with the IP address. Both show up in
6064 * "tcpdump -D" output. Capturing on the wmaster0 device
6065 * captures with 802.11 headers.
6067 * airmon-ng searches through /sys/class/net for devices named
6068 * monN, starting with mon0; as soon as one *doesn't* exist,
6069 * it chooses that as the monitor device name. If the "iw"
6070 * command exists, it does "iw dev {if} interface add {monif}
6071 * type monitor", where {monif} is the monitor device. It
6072 * then (sigh) sleeps .1 second, and then configures the
6073 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
6074 * is a file, it writes {mondev}, without a newline, to that file,
6075 * and again (sigh) sleeps .1 second, and then iwconfig's that
6076 * device into monitor mode and configures it up. Otherwise,
6077 * you can't do monitor mode.
6079 * All these devices are "glued" together by having the
6080 * /sys/class/net/{device}/phy80211 links pointing to the same
6081 * place, so, given a wmaster, wlan, or mon device, you can
6082 * find the other devices by looking for devices with
6083 * the same phy80211 link.
6085 * To turn monitor mode off, delete the monitor interface,
6086 * either with "iw dev {monif} interface del" or by sending
6087 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
6089 * Note: if you try to create a monitor device named "monN", and
6090 * there's already a "monN" device, it fails, as least with
6091 * the netlink interface (which is what iw uses), with a return
6092 * value of -ENFILE. (Return values are negative errnos.) We
6093 * could probably use that to find an unused device.
6095 struct pcap_linux
*handlep
= handle
->priv
;
6098 struct iw_priv_args
*priv
;
6099 monitor_type montype
;
6108 * Does this device *support* the Wireless Extensions?
6110 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
6112 return err
; /* either it doesn't or the device doesn't even exist */
6114 * Start out assuming we have no private extensions to control
6117 montype
= MONITOR_WEXT
;
6121 * Try to get all the Wireless Extensions private ioctls
6122 * supported by this device.
6124 * First, get the size of the buffer we need, by supplying no
6125 * buffer and a length of 0. If the device supports private
6126 * ioctls, it should return E2BIG, with ireq.u.data.length set
6127 * to the length we need. If it doesn't support them, it should
6128 * return EOPNOTSUPP.
6130 memset(&ireq
, 0, sizeof ireq
);
6131 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6132 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6133 ireq
.u
.data
.pointer
= (void *)args
;
6134 ireq
.u
.data
.length
= 0;
6135 ireq
.u
.data
.flags
= 0;
6136 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
6137 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6138 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
6142 if (errno
!= EOPNOTSUPP
) {
6144 * OK, it's not as if there are no private ioctls.
6146 if (errno
!= E2BIG
) {
6150 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6151 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
6156 * OK, try to get the list of private ioctls.
6158 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
6160 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6161 PCAP_ERRBUF_SIZE
, errno
, "malloc");
6164 ireq
.u
.data
.pointer
= (void *)priv
;
6165 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
6166 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6167 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
6173 * Look for private ioctls to turn monitor mode on or, if
6174 * monitor mode is on, to set the header type.
6176 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
6177 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
6179 * Hostap driver, use this one.
6180 * Set monitor mode first.
6181 * You can set it to 0 to get DLT_IEEE80211,
6182 * 1 to get DLT_PRISM, 2 to get
6183 * DLT_IEEE80211_RADIO_AVS, and, with more
6184 * recent versions of the driver, 3 to get
6185 * DLT_IEEE80211_RADIO.
6187 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6189 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
6191 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
6193 montype
= MONITOR_HOSTAP
;
6197 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
6199 * Prism54 driver, use this one.
6200 * Set monitor mode first.
6201 * You can set it to 2 to get DLT_IEEE80211
6202 * or 3 or get DLT_PRISM.
6204 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6206 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
6208 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
6210 montype
= MONITOR_PRISM54
;
6214 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
6216 * RT2570 driver, use this one.
6217 * Do this after turning monitor mode on.
6218 * You can set it to 1 to get DLT_PRISM or 2
6219 * to get DLT_IEEE80211.
6221 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6223 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
6225 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
6227 montype
= MONITOR_RT2570
;
6231 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
6233 * RT73 driver, use this one.
6234 * Do this after turning monitor mode on.
6235 * Its argument is a *string*; you can
6236 * set it to "1" to get DLT_PRISM or "2"
6237 * to get DLT_IEEE80211.
6239 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
6241 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
6243 montype
= MONITOR_RT73
;
6247 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
6249 * One of the RTL8xxx drivers, use this one.
6250 * It can only be done after monitor mode
6251 * has been turned on. You can set it to 1
6252 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
6254 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6256 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
6258 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
6260 montype
= MONITOR_RTL8XXX
;
6264 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
6266 * RT2500 or RT61 driver, use this one.
6267 * It has one one-byte parameter; set
6268 * u.data.length to 1 and u.data.pointer to
6269 * point to the parameter.
6270 * It doesn't itself turn monitor mode on.
6271 * You can set it to 1 to allow transmitting
6272 * in monitor mode(?) and get DLT_IEEE80211,
6273 * or set it to 0 to disallow transmitting in
6274 * monitor mode(?) and get DLT_PRISM.
6276 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6278 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
6280 montype
= MONITOR_RT2500
;
6284 if (strcmp(priv
[i
].name
, "monitor") == 0) {
6286 * Either ACX100 or hostap, use this one.
6287 * It turns monitor mode on.
6288 * If it takes two arguments, it's ACX100;
6289 * the first argument is 1 for DLT_PRISM
6290 * or 2 for DLT_IEEE80211, and the second
6291 * argument is the channel on which to
6292 * run. If it takes one argument, it's
6293 * HostAP, and the argument is 2 for
6294 * DLT_IEEE80211 and 3 for DLT_PRISM.
6296 * If we see this, we don't quit, as this
6297 * might be a version of the hostap driver
6298 * that also supports "monitor_type".
6300 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6302 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
6304 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
6307 montype
= MONITOR_PRISM
;
6312 montype
= MONITOR_ACX100
;
6325 * XXX - ipw3945? islism?
6331 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6332 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6333 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
6335 * We probably won't be able to set the mode, either.
6337 return PCAP_ERROR_RFMON_NOTSUP
;
6341 * Is it currently in monitor mode?
6343 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
6345 * Yes. Just leave things as they are.
6346 * We don't offer multiple link-layer types, as
6347 * changing the link-layer type out from under
6348 * somebody else capturing in monitor mode would
6349 * be considered rude.
6354 * No. We have to put the adapter into rfmon mode.
6358 * If we haven't already done so, arrange to have
6359 * "pcap_close_all()" called when we exit.
6361 if (!pcap_do_addexit(handle
)) {
6363 * "atexit()" failed; don't put the interface
6364 * in rfmon mode, just give up.
6366 return PCAP_ERROR_RFMON_NOTSUP
;
6370 * Save the old mode.
6372 handlep
->oldmode
= ireq
.u
.mode
;
6375 * Put the adapter in rfmon mode. How we do this depends
6376 * on whether we have a special private ioctl or not.
6378 if (montype
== MONITOR_PRISM
) {
6380 * We have the "monitor" private ioctl, but none of
6381 * the other private ioctls. Use this, and select
6384 * If it fails, just fall back on SIOCSIWMODE.
6386 memset(&ireq
, 0, sizeof ireq
);
6387 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6388 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6389 ireq
.u
.data
.length
= 1; /* 1 argument */
6390 args
[0] = 3; /* request Prism header */
6391 memcpy(ireq
.u
.name
, args
, sizeof (int));
6392 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
6395 * Note that we have to put the old mode back
6396 * when we close the device.
6398 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
6401 * Add this to the list of pcaps to close
6404 pcap_add_to_pcaps_to_close(handle
);
6410 * Failure. Fall back on SIOCSIWMODE.
6415 * First, take the interface down if it's up; otherwise, we
6418 memset(&ifr
, 0, sizeof(ifr
));
6419 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6420 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6421 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6422 errno
, "%s: Can't get flags", device
);
6426 if (ifr
.ifr_flags
& IFF_UP
) {
6427 oldflags
= ifr
.ifr_flags
;
6428 ifr
.ifr_flags
&= ~IFF_UP
;
6429 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6430 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6431 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6438 * Then turn monitor mode on.
6440 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6441 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6442 ireq
.u
.mode
= IW_MODE_MONITOR
;
6443 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
6445 * Scientist, you've failed.
6446 * Bring the interface back up if we shut it down.
6448 ifr
.ifr_flags
= oldflags
;
6449 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6450 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6451 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6455 return PCAP_ERROR_RFMON_NOTSUP
;
6459 * XXX - airmon-ng does "iwconfig {if} key off" after setting
6460 * monitor mode and setting the channel, and then does
6465 * Now select the appropriate radio header.
6471 * We don't have any private ioctl to set the header.
6475 case MONITOR_HOSTAP
:
6477 * Try to select the radiotap header.
6479 memset(&ireq
, 0, sizeof ireq
);
6480 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6481 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6482 args
[0] = 3; /* request radiotap header */
6483 memcpy(ireq
.u
.name
, args
, sizeof (int));
6484 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
6485 break; /* success */
6488 * That failed. Try to select the AVS header.
6490 memset(&ireq
, 0, sizeof ireq
);
6491 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6492 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6493 args
[0] = 2; /* request AVS header */
6494 memcpy(ireq
.u
.name
, args
, sizeof (int));
6495 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
6496 break; /* success */
6499 * That failed. Try to select the Prism header.
6501 memset(&ireq
, 0, sizeof ireq
);
6502 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6503 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6504 args
[0] = 1; /* request Prism header */
6505 memcpy(ireq
.u
.name
, args
, sizeof (int));
6506 ioctl(sock_fd
, cmd
, &ireq
);
6511 * The private ioctl failed.
6515 case MONITOR_PRISM54
:
6517 * Select the Prism header.
6519 memset(&ireq
, 0, sizeof ireq
);
6520 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6521 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6522 args
[0] = 3; /* request Prism header */
6523 memcpy(ireq
.u
.name
, args
, sizeof (int));
6524 ioctl(sock_fd
, cmd
, &ireq
);
6527 case MONITOR_ACX100
:
6529 * Get the current channel.
6531 memset(&ireq
, 0, sizeof ireq
);
6532 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6533 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6534 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
6535 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6536 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWFREQ", device
);
6539 channel
= ireq
.u
.freq
.m
;
6542 * Select the Prism header, and set the channel to the
6545 memset(&ireq
, 0, sizeof ireq
);
6546 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6547 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6548 args
[0] = 1; /* request Prism header */
6549 args
[1] = channel
; /* set channel */
6550 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
6551 ioctl(sock_fd
, cmd
, &ireq
);
6554 case MONITOR_RT2500
:
6556 * Disallow transmission - that turns on the
6559 memset(&ireq
, 0, sizeof ireq
);
6560 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6561 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6562 args
[0] = 0; /* disallow transmitting */
6563 memcpy(ireq
.u
.name
, args
, sizeof (int));
6564 ioctl(sock_fd
, cmd
, &ireq
);
6567 case MONITOR_RT2570
:
6569 * Force the Prism header.
6571 memset(&ireq
, 0, sizeof ireq
);
6572 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6573 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6574 args
[0] = 1; /* request Prism header */
6575 memcpy(ireq
.u
.name
, args
, sizeof (int));
6576 ioctl(sock_fd
, cmd
, &ireq
);
6581 * Force the Prism header.
6583 memset(&ireq
, 0, sizeof ireq
);
6584 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6585 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6586 ireq
.u
.data
.length
= 1; /* 1 argument */
6587 ireq
.u
.data
.pointer
= "1";
6588 ireq
.u
.data
.flags
= 0;
6589 ioctl(sock_fd
, cmd
, &ireq
);
6592 case MONITOR_RTL8XXX
:
6594 * Force the Prism header.
6596 memset(&ireq
, 0, sizeof ireq
);
6597 pcap_strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6598 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6599 args
[0] = 1; /* request Prism header */
6600 memcpy(ireq
.u
.name
, args
, sizeof (int));
6601 ioctl(sock_fd
, cmd
, &ireq
);
6606 * Now bring the interface back up if we brought it down.
6608 if (oldflags
!= 0) {
6609 ifr
.ifr_flags
= oldflags
;
6610 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6611 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6612 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6616 * At least try to restore the old mode on the
6619 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
6621 * Scientist, you've failed.
6624 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
6625 "Please adjust manually.\n",
6633 * Note that we have to put the old mode back when we
6636 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
6639 * Add this to the list of pcaps to close when we exit.
6641 pcap_add_to_pcaps_to_close(handle
);
6645 #endif /* IW_MODE_MONITOR */
6648 * Try various mechanisms to enter monitor mode.
6651 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
6653 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
6658 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
6660 return ret
; /* error attempting to do so */
6662 return 1; /* success */
6663 #endif /* HAVE_LIBNL */
6665 #ifdef IW_MODE_MONITOR
6666 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
6668 return ret
; /* error attempting to do so */
6670 return 1; /* success */
6671 #endif /* IW_MODE_MONITOR */
6674 * Either none of the mechanisms we know about work or none
6675 * of those mechanisms are available, so we can't do monitor
6681 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
6683 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
6685 static const struct {
6686 int soft_timestamping_val
;
6687 int pcap_tstamp_val
;
6688 } sof_ts_type_map
[3] = {
6689 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
6690 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
6691 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
6693 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
6696 * Set the list of time stamping types to include all types.
6699 iface_set_all_ts_types(pcap_t
*handle
)
6703 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
6704 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
6705 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
6706 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6709 #ifdef ETHTOOL_GET_TS_INFO
6711 * Get a list of time stamping capabilities.
6714 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf
)
6718 struct ethtool_ts_info info
;
6723 * This doesn't apply to the "any" device; you can't say "turn on
6724 * hardware time stamping for all devices that exist now and arrange
6725 * that it be turned on for any device that appears in the future",
6726 * and not all devices even necessarily *support* hardware time
6727 * stamping, so don't report any time stamp types.
6729 if (strcmp(device
, "any") == 0) {
6730 handle
->tstamp_type_list
= NULL
;
6735 * Create a socket from which to fetch time stamping capabilities.
6737 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
6739 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6740 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
6744 memset(&ifr
, 0, sizeof(ifr
));
6745 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6746 memset(&info
, 0, sizeof(info
));
6747 info
.cmd
= ETHTOOL_GET_TS_INFO
;
6748 ifr
.ifr_data
= (caddr_t
)&info
;
6749 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
6750 int save_errno
= errno
;
6753 switch (save_errno
) {
6758 * OK, this OS version or driver doesn't support
6759 * asking for the time stamping types, so let's
6760 * just return all the possible types.
6762 iface_set_all_ts_types(handle
);
6767 * OK, no such device.
6768 * The user will find that out when they try to
6769 * activate the device; just return an empty
6770 * list of time stamp types.
6772 handle
->tstamp_type_list
= NULL
;
6779 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6781 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
6789 * Do we support hardware time stamping of *all* packets?
6791 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
6793 * No, so don't report any time stamp types.
6795 * XXX - some devices either don't report
6796 * HWTSTAMP_FILTER_ALL when they do support it, or
6797 * report HWTSTAMP_FILTER_ALL but map it to only
6798 * time stamping a few PTP packets. See
6799 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
6801 handle
->tstamp_type_list
= NULL
;
6806 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6807 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
6810 handle
->tstamp_type_count
= num_ts_types
;
6811 if (num_ts_types
!= 0) {
6812 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
6813 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6814 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
6815 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6820 handle
->tstamp_type_list
= NULL
;
6824 #else /* ETHTOOL_GET_TS_INFO */
6826 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf _U_
)
6829 * This doesn't apply to the "any" device; you can't say "turn on
6830 * hardware time stamping for all devices that exist now and arrange
6831 * that it be turned on for any device that appears in the future",
6832 * and not all devices even necessarily *support* hardware time
6833 * stamping, so don't report any time stamp types.
6835 if (strcmp(device
, "any") == 0) {
6836 handle
->tstamp_type_list
= NULL
;
6841 * We don't have an ioctl to use to ask what's supported,
6842 * so say we support everything.
6844 iface_set_all_ts_types(handle
);
6847 #endif /* ETHTOOL_GET_TS_INFO */
6849 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6851 #ifdef HAVE_PACKET_RING
6853 * Find out if we have any form of fragmentation/reassembly offloading.
6855 * We do so using SIOCETHTOOL checking for various types of offloading;
6856 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6857 * of the types of offloading, there's nothing we can do to check, so
6858 * we just say "no, we don't".
6860 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
6861 * indications that the operation isn't supported. We do EPERM
6862 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
6863 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
6864 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
6865 * and 3) does the "is this permitted" check before doing the "is
6866 * this even supported" check, so it fails with "this is not permitted"
6867 * rather than "this is not even supported". To work around this
6868 * annoyance, we only treat EPERM as an error for the first feature,
6869 * and assume that they all do the same permission checks, so if the
6870 * first one is allowed all the others are allowed if supported.
6872 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6874 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
,
6878 struct ethtool_value eval
;
6880 memset(&ifr
, 0, sizeof(ifr
));
6881 pcap_strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
6884 ifr
.ifr_data
= (caddr_t
)&eval
;
6885 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
6886 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
||
6887 (errno
== EPERM
&& eperm_ok
)) {
6889 * OK, let's just return 0, which, in our
6890 * case, either means "no, what we're asking
6891 * about is not enabled" or "all the flags
6892 * are clear (i.e., nothing is enabled)".
6896 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6897 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
6898 handle
->opt
.device
, cmdname
);
6905 * XXX - it's annoying that we have to check for offloading at all, but,
6906 * given that we have to, it's still annoying that we have to check for
6907 * particular types of offloading, especially that shiny new types of
6908 * offloading may be added - and, worse, may not be checkable with
6909 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
6910 * theory, give those to you, but the actual flags being used are
6911 * opaque (defined in a non-uapi header), and there doesn't seem to
6912 * be any obvious way to ask the kernel what all the offloading flags
6913 * are - at best, you can ask for a set of strings(!) to get *names*
6914 * for various flags. (That whole mechanism appears to have been
6915 * designed for the sole purpose of letting ethtool report flags
6916 * by name and set flags by name, with the names having no semantics
6917 * ethtool understands.)
6920 iface_get_offload(pcap_t
*handle
)
6925 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO", 0);
6929 return 1; /* TCP segmentation offloading on */
6934 * XXX - will this cause large unsegmented packets to be
6935 * handed to PF_PACKET sockets on transmission? If not,
6936 * this need not be checked.
6938 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO", 0);
6942 return 1; /* generic segmentation offloading on */
6945 #ifdef ETHTOOL_GFLAGS
6946 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS", 0);
6949 if (ret
& ETH_FLAG_LRO
)
6950 return 1; /* large receive offloading on */
6955 * XXX - will this cause large reassembled packets to be
6956 * handed to PF_PACKET sockets on receipt? If not,
6957 * this need not be checked.
6959 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO", 0);
6963 return 1; /* generic (large) receive offloading on */
6968 * Do this one last, as support for it was removed in later
6969 * kernels, and it fails with EPERM on those kernels rather
6970 * than with EOPNOTSUPP (see explanation in comment for
6971 * iface_ethtool_flag_ioctl()).
6973 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO", 1);
6977 return 1; /* UDP fragmentation offloading on */
6982 #else /* SIOCETHTOOL */
6984 iface_get_offload(pcap_t
*handle _U_
)
6987 * XXX - do we need to get this information if we don't
6988 * have the ethtool ioctls? If so, how do we do that?
6992 #endif /* SIOCETHTOOL */
6994 #endif /* HAVE_PACKET_RING */
6996 #endif /* HAVE_PF_PACKET_SOCKETS */
6998 static struct dsa_proto
{
7000 bpf_u_int32 linktype
;
7003 * None is special and indicates that the interface does not have
7004 * any tagging protocol configured, and is therefore a standard
7005 * Ethernet interface.
7007 { "none", DLT_EN10MB
},
7008 { "brcm", DLT_DSA_TAG_BRCM
},
7009 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND
},
7010 { "dsa", DLT_DSA_TAG_DSA
},
7011 { "edsa", DLT_DSA_TAG_EDSA
},
7015 iface_dsa_get_proto_info(const char *device
, pcap_t
*handle
)
7020 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
7021 * the tag *shouldn't* have some huge long name, and making
7022 * it smaller keeps newer versions of GCC from whining that
7023 * the error message if we don't support the tag could
7024 * overflow the error message buffer.
7030 fd
= asprintf(&pathstr
, "/sys/class/net/%s/dsa/tagging", device
);
7032 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
7037 fd
= open(pathstr
, O_RDONLY
);
7040 * This is not fatal, kernel >= 4.20 *might* expose this attribute
7045 r
= read(fd
, buf
, sizeof(buf
) - 1);
7047 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
7055 * Buffer should be LF terminated.
7057 if (buf
[r
- 1] == '\n')
7061 for (i
= 0; i
< sizeof(dsa_protos
) / sizeof(dsa_protos
[0]); i
++) {
7062 if (strlen(dsa_protos
[i
].name
) == (size_t)r
&&
7063 strcmp(buf
, dsa_protos
[i
].name
) == 0) {
7064 handle
->linktype
= dsa_protos
[i
].linktype
;
7065 switch (dsa_protos
[i
].linktype
) {
7074 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
7075 "unsupported DSA tag: %s", buf
);
7080 /* ===== Functions to interface to the older kernels ================== */
7083 * Try to open a packet socket using the old kernel interface.
7084 * Returns 0 on success and a PCAP_ERROR_ value on an error.
7087 activate_old(pcap_t
*handle
, int is_any_device
)
7089 struct pcap_linux
*handlep
= handle
->priv
;
7093 const char *device
= handle
->opt
.device
;
7094 struct utsname utsname
;
7098 * PF_INET/SOCK_PACKET sockets must be bound to a device, so we
7099 * can't support the "any" device.
7101 if (is_any_device
) {
7102 pcap_strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
7107 /* Open the socket */
7108 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
7109 if (handle
->fd
== -1) {
7111 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
7113 if (err
== EPERM
|| err
== EACCES
) {
7115 * You don't have permission to open the
7118 return PCAP_ERROR_PERM_DENIED
;
7127 /* It worked - we are using the old interface */
7128 handlep
->sock_packet
= 1;
7130 /* ...which means we get the link-layer header. */
7131 handlep
->cooked
= 0;
7133 /* Bind to the given device */
7134 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1) {
7140 * Try to get the link-layer type.
7142 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
7149 * Try to find the DLT_ type corresponding to that
7152 map_arphrd_to_dlt(handle
, handle
->fd
, arptype
, device
, 0);
7153 if (handle
->linktype
== -1) {
7154 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
7155 "unknown arptype %d", arptype
);
7159 /* Go to promisc mode if requested */
7161 if (handle
->opt
.promisc
) {
7162 memset(&ifr
, 0, sizeof(ifr
));
7163 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
7164 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
7165 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7166 PCAP_ERRBUF_SIZE
, errno
, "SIOCGIFFLAGS");
7170 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
7172 * Promiscuous mode isn't currently on,
7173 * so turn it on, and remember that
7174 * we should turn it off when the
7179 * If we haven't already done so, arrange
7180 * to have "pcap_close_all()" called when
7183 if (!pcap_do_addexit(handle
)) {
7185 * "atexit()" failed; don't put
7186 * the interface in promiscuous
7187 * mode, just give up.
7193 ifr
.ifr_flags
|= IFF_PROMISC
;
7194 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
7195 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7196 PCAP_ERRBUF_SIZE
, errno
, "SIOCSIFFLAGS");
7199 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
7202 * Add this to the list of pcaps
7203 * to close when we exit.
7205 pcap_add_to_pcaps_to_close(handle
);
7210 * Compute the buffer size.
7212 * We're using SOCK_PACKET, so this might be a 2.0[.x]
7213 * kernel, and might require special handling - check.
7215 if (uname(&utsname
) < 0 ||
7216 strncmp(utsname
.release
, "2.0", 3) == 0) {
7218 * Either we couldn't find out what kernel release
7219 * this is, or it's a 2.0[.x] kernel.
7221 * In the 2.0[.x] kernel, a "recvfrom()" on
7222 * a SOCK_PACKET socket, with MSG_TRUNC set, will
7223 * return the number of bytes read, so if we pass
7224 * a length based on the snapshot length, it'll
7225 * return the number of bytes from the packet
7226 * copied to userland, not the actual length
7229 * This means that, for example, the IP dissector
7230 * in tcpdump will get handed a packet length less
7231 * than the length in the IP header, and will
7232 * complain about "truncated-ip".
7234 * So we don't bother trying to copy from the
7235 * kernel only the bytes in which we're interested,
7236 * but instead copy them all, just as the older
7237 * versions of libpcap for Linux did.
7239 * The buffer therefore needs to be big enough to
7240 * hold the largest packet we can get from this
7241 * device. Unfortunately, we can't get the MRU
7242 * of the network; we can only get the MTU. The
7243 * MTU may be too small, in which case a packet larger
7244 * than the buffer size will be truncated *and* we
7245 * won't get the actual packet size.
7247 * However, if the snapshot length is larger than
7248 * the buffer size based on the MTU, we use the
7249 * snapshot length as the buffer size, instead;
7250 * this means that with a sufficiently large snapshot
7251 * length we won't artificially truncate packets
7252 * to the MTU-based size.
7254 * This mess just one of many problems with packet
7255 * capture on 2.0[.x] kernels; you really want a
7256 * 2.2[.x] or later kernel if you want packet capture
7259 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
7264 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
7265 if (handle
->bufsize
< (u_int
)handle
->snapshot
)
7266 handle
->bufsize
= (u_int
)handle
->snapshot
;
7269 * This is a 2.2[.x] or later kernel.
7271 * We can safely pass "recvfrom()" a byte count
7272 * based on the snapshot length.
7274 * XXX - this "should not happen", as 2.2[.x]
7275 * kernels all have PF_PACKET sockets, and there's
7276 * no configuration option to disable them without
7277 * disabling SOCK_PACKET sockets, because
7278 * SOCK_PACKET sockets are implemented in the same
7279 * source file, net/packet/af_packet.c. There *is*
7280 * an option to disable SOCK_PACKET sockets so that
7281 * you only have PF_PACKET sockets, and the kernel
7282 * will log warning messages for code that uses
7283 * "obsolete (PF_INET,SOCK_PACKET)".
7285 handle
->bufsize
= (u_int
)handle
->snapshot
;
7289 * Default value for offset to align link-layer payload
7290 * on a 4-byte boundary.
7295 * SOCK_PACKET sockets don't supply information from
7296 * stripped VLAN tags.
7298 handlep
->vlan_offset
= -1; /* unknown */
7304 * Bind the socket associated with FD to the given device using the
7305 * interface of the old kernels.
7308 iface_bind_old(int fd
, const char *device
, char *ebuf
)
7310 struct sockaddr saddr
;
7312 socklen_t errlen
= sizeof(err
);
7314 memset(&saddr
, 0, sizeof(saddr
));
7315 pcap_strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
7316 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
7317 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
7322 /* Any pending errors, e.g., network is down? */
7324 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
7325 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
7326 errno
, "getsockopt (SO_ERROR)");
7331 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
7340 /* ===== System calls available on all supported kernels ============== */
7343 * Query the kernel for the MTU of the given interface.
7346 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
7351 return BIGGER_THAN_ALL_MTUS
;
7353 memset(&ifr
, 0, sizeof(ifr
));
7354 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
7356 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
7357 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
7358 errno
, "SIOCGIFMTU");
7366 * Get the hardware type of the given interface as ARPHRD_xxx constant.
7369 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
7374 memset(&ifr
, 0, sizeof(ifr
));
7375 pcap_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
7377 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
7378 if (errno
== ENODEV
) {
7382 ret
= PCAP_ERROR_NO_SUCH_DEVICE
;
7385 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
7386 errno
, "SIOCGIFHWADDR");
7390 return ifr
.ifr_hwaddr
.sa_family
;
7393 #ifdef SO_ATTACH_FILTER
7395 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
7397 struct pcap_linux
*handlep
= handle
->priv
;
7400 register struct bpf_insn
*p
;
7405 * Make a copy of the filter, and modify that copy if
7408 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
7409 len
= handle
->fcode
.bf_len
;
7410 f
= (struct bpf_insn
*)malloc(prog_size
);
7412 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
7416 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
7418 fcode
->filter
= (struct sock_filter
*) f
;
7420 for (i
= 0; i
< len
; ++i
) {
7423 * What type of instruction is this?
7425 switch (BPF_CLASS(p
->code
)) {
7429 * It's a return instruction; are we capturing
7430 * in memory-mapped mode?
7434 * No; is the snapshot length a constant,
7435 * rather than the contents of the
7438 if (BPF_MODE(p
->code
) == BPF_K
) {
7440 * Yes - if the value to be returned,
7441 * i.e. the snapshot length, is
7442 * anything other than 0, make it
7443 * MAXIMUM_SNAPLEN, so that the packet
7444 * is truncated by "recvfrom()",
7445 * not by the filter.
7447 * XXX - there's nothing we can
7448 * easily do if it's getting the
7449 * value from the accumulator; we'd
7450 * have to insert code to force
7451 * non-zero values to be
7455 p
->k
= MAXIMUM_SNAPLEN
;
7463 * It's a load instruction; is it loading
7466 switch (BPF_MODE(p
->code
)) {
7472 * Yes; are we in cooked mode?
7474 if (handlep
->cooked
) {
7476 * Yes, so we need to fix this
7479 if (fix_offset(handle
, p
) < 0) {
7481 * We failed to do so.
7482 * Return 0, so our caller
7483 * knows to punt to userland.
7493 return 1; /* we succeeded */
7497 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
7499 if (handle
->linktype
== DLT_LINUX_SLL2
) {
7501 * What's the offset?
7503 if (p
->k
>= SLL2_HDR_LEN
) {
7505 * It's within the link-layer payload; that starts
7506 * at an offset of 0, as far as the kernel packet
7507 * filter is concerned, so subtract the length of
7508 * the link-layer header.
7510 p
->k
-= SLL2_HDR_LEN
;
7511 } else if (p
->k
== 0) {
7513 * It's the protocol field; map it to the
7514 * special magic kernel offset for that field.
7516 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
7517 } else if (p
->k
== 10) {
7519 * It's the packet type field; map it to the
7520 * special magic kernel offset for that field.
7522 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
7523 } else if ((bpf_int32
)(p
->k
) > 0) {
7525 * It's within the header, but it's not one of
7526 * those fields; we can't do that in the kernel,
7527 * so punt to userland.
7533 * What's the offset?
7535 if (p
->k
>= SLL_HDR_LEN
) {
7537 * It's within the link-layer payload; that starts
7538 * at an offset of 0, as far as the kernel packet
7539 * filter is concerned, so subtract the length of
7540 * the link-layer header.
7542 p
->k
-= SLL_HDR_LEN
;
7543 } else if (p
->k
== 0) {
7545 * It's the packet type field; map it to the
7546 * special magic kernel offset for that field.
7548 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
7549 } else if (p
->k
== 14) {
7551 * It's the protocol field; map it to the
7552 * special magic kernel offset for that field.
7554 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
7555 } else if ((bpf_int32
)(p
->k
) > 0) {
7557 * It's within the header, but it's not one of
7558 * those fields; we can't do that in the kernel,
7559 * so punt to userland.
7568 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
7570 int total_filter_on
= 0;
7576 * The socket filter code doesn't discard all packets queued
7577 * up on the socket when the filter is changed; this means
7578 * that packets that don't match the new filter may show up
7579 * after the new filter is put onto the socket, if those
7580 * packets haven't yet been read.
7582 * This means, for example, that if you do a tcpdump capture
7583 * with a filter, the first few packets in the capture might
7584 * be packets that wouldn't have passed the filter.
7586 * We therefore discard all packets queued up on the socket
7587 * when setting a kernel filter. (This isn't an issue for
7588 * userland filters, as the userland filtering is done after
7589 * packets are queued up.)
7591 * To flush those packets, we put the socket in read-only mode,
7592 * and read packets from the socket until there are no more to
7595 * In order to keep that from being an infinite loop - i.e.,
7596 * to keep more packets from arriving while we're draining
7597 * the queue - we put the "total filter", which is a filter
7598 * that rejects all packets, onto the socket before draining
7601 * This code deliberately ignores any errors, so that you may
7602 * get bogus packets if an error occurs, rather than having
7603 * the filtering done in userland even if it could have been
7604 * done in the kernel.
7606 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
7607 &total_fcode
, sizeof(total_fcode
)) == 0) {
7611 * Note that we've put the total filter onto the socket.
7613 total_filter_on
= 1;
7616 * Save the socket's current mode, and put it in
7617 * non-blocking mode; we drain it by reading packets
7618 * until we get an error (which is normally a
7619 * "nothing more to be read" error).
7621 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
7622 if (save_mode
== -1) {
7623 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7624 PCAP_ERRBUF_SIZE
, errno
,
7625 "can't get FD flags when changing filter");
7628 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
7629 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7630 PCAP_ERRBUF_SIZE
, errno
,
7631 "can't set nonblocking mode when changing filter");
7634 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
7637 if (save_errno
!= EAGAIN
) {
7641 * If we can't restore the mode or reset the
7642 * kernel filter, there's nothing we can do.
7644 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
7645 (void)reset_kernel_filter(handle
);
7646 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7647 PCAP_ERRBUF_SIZE
, save_errno
,
7648 "recv failed when changing filter");
7651 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
7652 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7653 PCAP_ERRBUF_SIZE
, errno
,
7654 "can't restore FD flags when changing filter");
7660 * Now attach the new filter.
7662 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
7663 fcode
, sizeof(*fcode
));
7664 if (ret
== -1 && total_filter_on
) {
7666 * Well, we couldn't set that filter on the socket,
7667 * but we could set the total filter on the socket.
7669 * This could, for example, mean that the filter was
7670 * too big to put into the kernel, so we'll have to
7671 * filter in userland; in any case, we'll be doing
7672 * filtering in userland, so we need to remove the
7673 * total filter so we see packets.
7678 * If this fails, we're really screwed; we have the
7679 * total filter on the socket, and it won't come off.
7680 * Report it as a fatal error.
7682 if (reset_kernel_filter(handle
) == -1) {
7683 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7684 PCAP_ERRBUF_SIZE
, errno
,
7685 "can't remove kernel total filter");
7686 return -2; /* fatal error */
7695 reset_kernel_filter(pcap_t
*handle
)
7699 * setsockopt() barfs unless it get a dummy parameter.
7700 * valgrind whines unless the value is initialized,
7701 * as it has no idea that setsockopt() ignores its
7706 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
7707 &dummy
, sizeof(dummy
));
7709 * Ignore ENOENT - it means "we don't have a filter", so there
7710 * was no filter to remove, and there's still no filter.
7712 * Also ignore ENONET, as a lot of kernel versions had a
7713 * typo where ENONET, rather than ENOENT, was returned.
7715 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
7722 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
7724 if (pcap_check_activated(p
))
7725 return (PCAP_ERROR_ACTIVATED
);
7726 p
->opt
.protocol
= protocol
;
7731 * Libpcap version string.
7734 pcap_lib_version(void)
7736 #ifdef HAVE_PACKET_RING
7737 #if defined(HAVE_TPACKET3)
7738 return (PCAP_VERSION_STRING
" (with TPACKET_V3)");
7739 #elif defined(HAVE_TPACKET2)
7740 return (PCAP_VERSION_STRING
" (with TPACKET_V2)");
7742 return (PCAP_VERSION_STRING
" (with TPACKET_V1)");
7745 return (PCAP_VERSION_STRING
" (without TPACKET)");