2 * pcap-linux.c: Packet capture interface to the Linux kernel
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
23 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
29 * Added TPACKET_V3 support
30 * Gabor Tatarka <gabor.tatarka@ericsson.com>
32 * based on previous works of:
33 * Simon Patarin <patarin@cs.unibo.it>
34 * Phil Wood <cpw@lanl.gov>
36 * Monitor-mode support for mac80211 includes code taken from the iw
37 * command; the copyright notice for that code is
39 * Copyright (c) 2007, 2008 Johannes Berg
40 * Copyright (c) 2007 Andy Lutomirski
41 * Copyright (c) 2007 Mike Kershaw
42 * Copyright (c) 2008 Gábor Stefanik
44 * All rights reserved.
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
49 * 1. Redistributions of source code must retain the above copyright
50 * notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 * notice, this list of conditions and the following disclaimer in the
53 * documentation and/or other materials provided with the distribution.
54 * 3. The name of the author may not be used to endorse or promote products
55 * derived from this software without specific prior written permission.
57 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
58 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
60 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
61 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
62 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
63 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
64 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
65 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
71 * Known problems with 2.0[.x] kernels:
73 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
74 * if we use PF_PACKET, we can filter out the transmitted version
75 * of the packet by using data in the "sockaddr_ll" returned by
76 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
77 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
78 * "sockaddr_pkt" which doesn't give us enough information to let
81 * - We have to set the interface's IFF_PROMISC flag ourselves, if
82 * we're to run in promiscuous mode, which means we have to turn
83 * it off ourselves when we're done; the kernel doesn't keep track
84 * of how many sockets are listening promiscuously, which means
85 * it won't get turned off automatically when no sockets are
86 * listening promiscuously. We catch "pcap_close()" and, for
87 * interfaces we put into promiscuous mode, take them out of
88 * promiscuous mode - which isn't necessarily the right thing to
89 * do, if another socket also requested promiscuous mode between
90 * the time when we opened the socket and the time when we close
93 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
94 * return the amount of data that you could have read, rather than
95 * the amount that was returned, so we can't just allocate a buffer
96 * whose size is the snapshot length and pass the snapshot length
97 * as the byte count, and also pass MSG_TRUNC, so that the return
98 * value tells us how long the packet was on the wire.
100 * This means that, if we want to get the actual size of the packet,
101 * so we can return it in the "len" field of the packet header,
102 * we have to read the entire packet, not just the part that fits
103 * within the snapshot length, and thus waste CPU time copying data
104 * from the kernel that our caller won't see.
106 * We have to get the actual size, and supply it in "len", because
107 * otherwise, the IP dissector in tcpdump, for example, will complain
108 * about "truncated-ip", as the packet will appear to have been
109 * shorter, on the wire, than the IP header said it should have been.
127 #include <sys/stat.h>
128 #include <sys/socket.h>
129 #include <sys/ioctl.h>
130 #include <sys/utsname.h>
131 #include <sys/mman.h>
132 #include <linux/if.h>
133 #include <linux/if_packet.h>
134 #include <linux/sockios.h>
135 #include <netinet/in.h>
136 #include <linux/if_ether.h>
137 #include <net/if_arp.h>
141 #include "pcap-int.h"
142 #include "pcap/sll.h"
143 #include "pcap/vlan.h"
146 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
147 * sockets rather than SOCK_PACKET sockets.
149 * To use them, we include <linux/if_packet.h> rather than
150 * <netpacket/packet.h>; we do so because
152 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
153 * later kernels and libc5, and don't provide a <netpacket/packet.h>
156 * not all versions of glibc2 have a <netpacket/packet.h> file
157 * that defines stuff needed for some of the 2.4-or-later-kernel
158 * features, so if the system has a 2.4 or later kernel, we
159 * still can't use those features.
161 * We're already including a number of other <linux/XXX.h> headers, and
162 * this code is Linux-specific (no other OS has PF_PACKET sockets as
163 * a raw packet capture mechanism), so it's not as if you gain any
164 * useful portability by using <netpacket/packet.h>
166 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
167 * isn't defined? It only defines one data structure in 2.0.x, so
168 * it shouldn't cause any problems.
171 # include <linux/if_packet.h>
174 * On at least some Linux distributions (for example, Red Hat 5.2),
175 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
176 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
177 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
178 * the PACKET_xxx stuff.
180 * So we check whether PACKET_HOST is defined, and assume that we have
181 * PF_PACKET sockets only if it is defined.
184 # define HAVE_PF_PACKET_SOCKETS
185 # ifdef PACKET_AUXDATA
186 # define HAVE_PACKET_AUXDATA
187 # endif /* PACKET_AUXDATA */
188 # endif /* PACKET_HOST */
191 /* check for memory mapped access avaibility. We assume every needed
192 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
193 * uses many ring related structs and macros */
194 # ifdef PCAP_SUPPORT_PACKET_RING
195 # ifdef TPACKET_HDRLEN
196 # define HAVE_PACKET_RING
197 # ifdef TPACKET3_HDRLEN
198 # define HAVE_TPACKET3
199 # endif /* TPACKET3_HDRLEN */
200 # ifdef TPACKET2_HDRLEN
201 # define HAVE_TPACKET2
202 # else /* TPACKET2_HDRLEN */
203 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
204 # endif /* TPACKET2_HDRLEN */
205 # endif /* TPACKET_HDRLEN */
206 # endif /* PCAP_SUPPORT_PACKET_RING */
207 #endif /* PF_PACKET */
209 #ifdef SO_ATTACH_FILTER
210 #include <linux/types.h>
211 #include <linux/filter.h>
214 #ifdef HAVE_LINUX_NET_TSTAMP_H
215 #include <linux/net_tstamp.h>
218 #ifdef HAVE_LINUX_SOCKIOS_H
219 #include <linux/sockios.h>
222 #ifdef HAVE_LINUX_IF_BONDING_H
223 #include <linux/if_bonding.h>
226 * The ioctl code to use to check whether a device is a bonding device.
228 #if defined(SIOCBONDINFOQUERY)
229 #define BOND_INFO_QUERY_IOCTL SIOCBONDINFOQUERY
230 #elif defined(BOND_INFO_QUERY_OLD)
231 #define BOND_INFO_QUERY_IOCTL BOND_INFO_QUERY_OLD
233 #endif /* HAVE_LINUX_IF_BONDING_H */
236 * Got Wireless Extensions?
238 #ifdef HAVE_LINUX_WIRELESS_H
239 #include <linux/wireless.h>
240 #endif /* HAVE_LINUX_WIRELESS_H */
246 #include <linux/nl80211.h>
248 #include <netlink/genl/genl.h>
249 #include <netlink/genl/family.h>
250 #include <netlink/genl/ctrl.h>
251 #include <netlink/msg.h>
252 #include <netlink/attr.h>
253 #endif /* HAVE_LIBNL */
256 * Got ethtool support?
258 #ifdef HAVE_LINUX_ETHTOOL_H
259 #include <linux/ethtool.h>
262 #ifndef HAVE_SOCKLEN_T
263 typedef int socklen_t
;
268 * This is being compiled on a system that lacks MSG_TRUNC; define it
269 * with the value it has in the 2.2 and later kernels, so that, on
270 * those kernels, when we pass it in the flags argument to "recvfrom()"
271 * we're passing the right value and thus get the MSG_TRUNC behavior
272 * we want. (We don't get that behavior on 2.0[.x] kernels, because
273 * they didn't support MSG_TRUNC.)
275 #define MSG_TRUNC 0x20
280 * This is being compiled on a system that lacks SOL_PACKET; define it
281 * with the value it has in the 2.2 and later kernels, so that we can
282 * set promiscuous mode in the good modern way rather than the old
283 * 2.0-kernel crappy way.
285 #define SOL_PACKET 263
288 #define MAX_LINKHEADER_SIZE 256
291 * When capturing on all interfaces we use this as the buffer size.
292 * Should be bigger then all MTUs that occur in real life.
293 * 64kB should be enough for now.
295 #define BIGGER_THAN_ALL_MTUS (64*1024)
298 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
301 u_int packets_read
; /* count of packets read with recvfrom() */
302 long proc_dropped
; /* packets reported dropped by /proc/net/dev */
303 struct pcap_stat stat
;
305 char *device
; /* device name */
306 int filter_in_userland
; /* must filter in userland */
307 int blocks_to_filter_in_userland
;
308 int must_do_on_close
; /* stuff we must do when we close */
309 int timeout
; /* timeout for buffering */
310 int sock_packet
; /* using Linux 2.0 compatible interface */
311 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
312 int ifindex
; /* interface index of device we're bound to */
313 int lo_ifindex
; /* interface index of the loopback device */
314 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
315 char *mondevice
; /* mac80211 monitor device we created */
316 u_char
*mmapbuf
; /* memory-mapped region pointer */
317 size_t mmapbuflen
; /* size of region */
318 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
319 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
320 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
321 u_char
*oneshot_buffer
; /* buffer for copy of packet */
322 int poll_timeout
; /* timeout to use in poll() */
324 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
325 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
330 * Stuff to do when we close.
332 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
333 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
334 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
337 * Prototypes for internal functions and methods.
339 static int get_if_flags(const char *, bpf_u_int32
*, char *);
340 static int is_wifi(int, const char *);
341 static void map_arphrd_to_dlt(pcap_t
*, int, int, const char *, int);
342 static int pcap_activate_linux(pcap_t
*);
343 static int activate_old(pcap_t
*);
344 static int activate_new(pcap_t
*);
345 static int activate_mmap(pcap_t
*, int *);
346 static int pcap_can_set_rfmon_linux(pcap_t
*);
347 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
348 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
349 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
350 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
351 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
352 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
353 static int pcap_set_datalink_linux(pcap_t
*, int);
354 static void pcap_cleanup_linux(pcap_t
*);
357 * This is what the header structure looks like in a 64-bit kernel;
358 * we use this, rather than struct tpacket_hdr, if we're using
359 * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
361 struct tpacket_hdr_64
{
364 unsigned int tp_snaplen
;
365 unsigned short tp_mac
;
366 unsigned short tp_net
;
368 unsigned int tp_usec
;
372 * We use this internally as the tpacket version for TPACKET_V1 in
373 * 32-bit code on a 64-bit kernel.
375 #define TPACKET_V1_64 99
378 struct tpacket_hdr
*h1
;
379 struct tpacket_hdr_64
*h1_64
;
381 struct tpacket2_hdr
*h2
;
384 struct tpacket_block_desc
*h3
;
389 #ifdef HAVE_PACKET_RING
390 #define RING_GET_FRAME_AT(h, offset) (((union thdr **)h->buffer)[(offset)])
391 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
393 static void destroy_ring(pcap_t
*handle
);
394 static int create_ring(pcap_t
*handle
, int *status
);
395 static int prepare_tpacket_socket(pcap_t
*handle
);
396 static void pcap_cleanup_linux_mmap(pcap_t
*);
397 static int pcap_read_linux_mmap_v1(pcap_t
*, int, pcap_handler
, u_char
*);
398 static int pcap_read_linux_mmap_v1_64(pcap_t
*, int, pcap_handler
, u_char
*);
400 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
403 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
405 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
406 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
);
407 static int pcap_getnonblock_mmap(pcap_t
*p
);
408 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
409 const u_char
*bytes
);
413 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
414 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
415 * or "on VLAN 0". There is no flag set in the tp_status field to
416 * distinguish between them.
418 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
419 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
420 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
421 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
423 * With a pre-3.0 kernel, we cannot distinguish between packets with no
424 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
425 * there's nothing we can do about that.
427 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
428 * continue the behavior of earlier libpcaps, wherein we treated packets
429 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
430 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
431 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
432 * VLAN tags. This does the right thing on 3.0 and later kernels, and
433 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
435 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
436 * has that value in 3.0 and later kernels.
438 #ifdef TP_STATUS_VLAN_VALID
439 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
442 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
443 * so we testwith the value it has in the 3.0 and later kernels, so
444 * we can test it if we're running on a system that has it. (If we're
445 * running on a system that doesn't have it, it won't be set in the
446 * tp_status field, so the tests of it will always fail; that means
447 * we behave the way we did before we introduced this macro.)
449 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
452 #ifdef TP_STATUS_VLAN_TPID_VALID
453 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
455 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
459 * Wrap some ioctl calls
461 #ifdef HAVE_PF_PACKET_SOCKETS
462 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
463 #endif /* HAVE_PF_PACKET_SOCKETS */
464 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
465 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
466 #ifdef HAVE_PF_PACKET_SOCKETS
467 static int iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
);
468 #ifdef IW_MODE_MONITOR
469 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
470 #endif /* IW_MODE_MONITOR */
471 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
473 #endif /* HAVE_PF_PACKET_SOCKETS */
474 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
475 static int iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
,
478 #ifdef HAVE_PACKET_RING
479 static int iface_get_offload(pcap_t
*handle
);
481 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
483 #ifdef SO_ATTACH_FILTER
484 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
486 static int fix_offset(pcap_t
*handle
, struct bpf_insn
*p
);
487 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
488 static int reset_kernel_filter(pcap_t
*handle
);
490 static struct sock_filter total_insn
491 = BPF_STMT(BPF_RET
| BPF_K
, 0);
492 static struct sock_fprog total_fcode
493 = { 1, &total_insn
};
494 #endif /* SO_ATTACH_FILTER */
497 pcap_create_interface(const char *device
, char *ebuf
)
501 handle
= pcap_create_common(ebuf
, sizeof (struct pcap_linux
));
505 handle
->activate_op
= pcap_activate_linux
;
506 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
508 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
510 * See what time stamp types we support.
512 if (iface_ethtool_get_ts_info(device
, handle
, ebuf
) == -1) {
518 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
520 * We claim that we support microsecond and nanosecond time
523 * XXX - with adapter-supplied time stamps, can we choose
524 * microsecond or nanosecond time stamps on arbitrary
527 handle
->tstamp_precision_count
= 2;
528 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
529 if (handle
->tstamp_precision_list
== NULL
) {
530 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
535 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
536 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
537 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
544 * If interface {if} is a mac80211 driver, the file
545 * /sys/class/net/{if}/phy80211 is a symlink to
546 * /sys/class/ieee80211/{phydev}, for some {phydev}.
548 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
549 * least, has a "wmaster0" device and a "wlan0" device; the
550 * latter is the one with the IP address. Both show up in
551 * "tcpdump -D" output. Capturing on the wmaster0 device
552 * captures with 802.11 headers.
554 * airmon-ng searches through /sys/class/net for devices named
555 * monN, starting with mon0; as soon as one *doesn't* exist,
556 * it chooses that as the monitor device name. If the "iw"
557 * command exists, it does "iw dev {if} interface add {monif}
558 * type monitor", where {monif} is the monitor device. It
559 * then (sigh) sleeps .1 second, and then configures the
560 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
561 * is a file, it writes {mondev}, without a newline, to that file,
562 * and again (sigh) sleeps .1 second, and then iwconfig's that
563 * device into monitor mode and configures it up. Otherwise,
564 * you can't do monitor mode.
566 * All these devices are "glued" together by having the
567 * /sys/class/net/{device}/phy80211 links pointing to the same
568 * place, so, given a wmaster, wlan, or mon device, you can
569 * find the other devices by looking for devices with
570 * the same phy80211 link.
572 * To turn monitor mode off, delete the monitor interface,
573 * either with "iw dev {monif} interface del" or by sending
574 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
576 * Note: if you try to create a monitor device named "monN", and
577 * there's already a "monN" device, it fails, as least with
578 * the netlink interface (which is what iw uses), with a return
579 * value of -ENFILE. (Return values are negative errnos.) We
580 * could probably use that to find an unused device.
582 * Yes, you can have multiple monitor devices for a given
587 * Is this a mac80211 device? If so, fill in the physical device path and
588 * return 1; if not, return 0. On an error, fill in handle->errbuf and
592 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
593 size_t phydev_max_pathlen
)
599 * Generate the path string for the symlink to the physical device.
601 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
602 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
603 "%s: Can't generate path name string for /sys/class/net device",
607 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
608 if (bytes_read
== -1) {
609 if (errno
== ENOENT
|| errno
== EINVAL
) {
611 * Doesn't exist, or not a symlink; assume that
612 * means it's not a mac80211 device.
617 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
618 errno
, "%s: Can't readlink %s", device
, pathstr
);
623 phydev_path
[bytes_read
] = '\0';
627 #ifdef HAVE_LIBNL_SOCKETS
628 #define get_nl_errmsg nl_geterror
630 /* libnl 2.x compatibility code */
632 #define nl_sock nl_handle
634 static inline struct nl_handle
*
635 nl_socket_alloc(void)
637 return nl_handle_alloc();
641 nl_socket_free(struct nl_handle
*h
)
643 nl_handle_destroy(h
);
646 #define get_nl_errmsg strerror
649 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
651 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
657 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
658 #endif /* !HAVE_LIBNL_SOCKETS */
660 struct nl80211_state
{
661 struct nl_sock
*nl_sock
;
662 struct nl_cache
*nl_cache
;
663 struct genl_family
*nl80211
;
667 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
671 state
->nl_sock
= nl_socket_alloc();
672 if (!state
->nl_sock
) {
673 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
674 "%s: failed to allocate netlink handle", device
);
678 if (genl_connect(state
->nl_sock
)) {
679 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
680 "%s: failed to connect to generic netlink", device
);
681 goto out_handle_destroy
;
684 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
686 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
687 "%s: failed to allocate generic netlink cache: %s",
688 device
, get_nl_errmsg(-err
));
689 goto out_handle_destroy
;
692 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
693 if (!state
->nl80211
) {
694 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
695 "%s: nl80211 not found", device
);
702 nl_cache_free(state
->nl_cache
);
704 nl_socket_free(state
->nl_sock
);
709 nl80211_cleanup(struct nl80211_state
*state
)
711 genl_family_put(state
->nl80211
);
712 nl_cache_free(state
->nl_cache
);
713 nl_socket_free(state
->nl_sock
);
717 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
718 const char *device
, const char *mondevice
);
721 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
722 const char *device
, const char *mondevice
)
724 struct pcap_linux
*handlep
= handle
->priv
;
729 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
735 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
736 "%s: failed to allocate netlink msg", device
);
740 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
741 0, NL80211_CMD_NEW_INTERFACE
, 0);
742 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
743 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
744 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
746 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
748 #if defined HAVE_LIBNL_NLE
749 if (err
== -NLE_FAILURE
) {
751 if (err
== -ENFILE
) {
754 * Device not available; our caller should just
755 * keep trying. (libnl 2.x maps ENFILE to
756 * NLE_FAILURE; it can also map other errors
757 * to that, but there's not much we can do
764 * Real failure, not just "that device is not
767 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
768 "%s: nl_send_auto_complete failed adding %s interface: %s",
769 device
, mondevice
, get_nl_errmsg(-err
));
774 err
= nl_wait_for_ack(state
->nl_sock
);
776 #if defined HAVE_LIBNL_NLE
777 if (err
== -NLE_FAILURE
) {
779 if (err
== -ENFILE
) {
782 * Device not available; our caller should just
783 * keep trying. (libnl 2.x maps ENFILE to
784 * NLE_FAILURE; it can also map other errors
785 * to that, but there's not much we can do
792 * Real failure, not just "that device is not
795 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
796 "%s: nl_wait_for_ack failed adding %s interface: %s",
797 device
, mondevice
, get_nl_errmsg(-err
));
809 * Try to remember the monitor device.
811 handlep
->mondevice
= strdup(mondevice
);
812 if (handlep
->mondevice
== NULL
) {
813 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
816 * Get rid of the monitor device.
818 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
824 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
825 "%s: nl_put failed adding %s interface",
832 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
833 const char *device
, const char *mondevice
)
839 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
845 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
846 "%s: failed to allocate netlink msg", device
);
850 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
851 0, NL80211_CMD_DEL_INTERFACE
, 0);
852 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
854 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
856 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
857 "%s: nl_send_auto_complete failed deleting %s interface: %s",
858 device
, mondevice
, get_nl_errmsg(-err
));
862 err
= nl_wait_for_ack(state
->nl_sock
);
864 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
865 "%s: nl_wait_for_ack failed adding %s interface: %s",
866 device
, mondevice
, get_nl_errmsg(-err
));
878 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
879 "%s: nl_put failed deleting %s interface",
886 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
888 struct pcap_linux
*handlep
= handle
->priv
;
890 char phydev_path
[PATH_MAX
+1];
891 struct nl80211_state nlstate
;
896 * Is this a mac80211 device?
898 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
900 return ret
; /* error */
902 return 0; /* no error, but not mac80211 device */
905 * XXX - is this already a monN device?
907 * Is that determined by old Wireless Extensions ioctls?
911 * OK, it's apparently a mac80211 device.
912 * Try to find an unused monN device for it.
914 ret
= nl80211_init(handle
, &nlstate
, device
);
917 for (n
= 0; n
< UINT_MAX
; n
++) {
921 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
923 pcap_snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
924 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
927 * Success. We don't clean up the libnl state
928 * yet, as we'll be using it later.
934 * Hard failure. Just return ret; handle->errbuf
935 * has already been set.
937 nl80211_cleanup(&nlstate
);
942 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
943 "%s: No free monN interfaces", device
);
944 nl80211_cleanup(&nlstate
);
951 * Sleep for .1 seconds.
954 delay
.tv_nsec
= 500000000;
955 nanosleep(&delay
, NULL
);
959 * If we haven't already done so, arrange to have
960 * "pcap_close_all()" called when we exit.
962 if (!pcap_do_addexit(handle
)) {
964 * "atexit()" failed; don't put the interface
965 * in rfmon mode, just give up.
967 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
969 nl80211_cleanup(&nlstate
);
974 * Now configure the monitor interface up.
976 memset(&ifr
, 0, sizeof(ifr
));
977 strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
978 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
979 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
980 errno
, "%s: Can't get flags for %s", device
,
982 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
984 nl80211_cleanup(&nlstate
);
987 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
988 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
989 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
990 errno
, "%s: Can't set flags for %s", device
,
992 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
994 nl80211_cleanup(&nlstate
);
999 * Success. Clean up the libnl state.
1001 nl80211_cleanup(&nlstate
);
1004 * Note that we have to delete the monitor device when we close
1007 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
1010 * Add this to the list of pcaps to close when we exit.
1012 pcap_add_to_pcaps_to_close(handle
);
1016 #endif /* HAVE_LIBNL */
1018 #ifdef IW_MODE_MONITOR
1020 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
1021 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
1022 * will fail with ENODEV if we try to do them on a bonding device,
1023 * making us return a "no such device" indication rather than just
1024 * saying "no Wireless Extensions".
1026 * So we check for bonding devices, if we can, before trying those
1027 * ioctls, by trying a bonding device information query ioctl to see
1028 * whether it succeeds.
1031 is_bonding_device(int fd
, const char *device
)
1033 #ifdef BOND_INFO_QUERY_IOCTL
1037 memset(&ifr
, 0, sizeof ifr
);
1038 strlcpy(ifr
.ifr_name
, device
, sizeof ifr
.ifr_name
);
1039 memset(&ifb
, 0, sizeof ifb
);
1040 ifr
.ifr_data
= (caddr_t
)&ifb
;
1041 if (ioctl(fd
, BOND_INFO_QUERY_IOCTL
, &ifr
) == 0)
1042 return 1; /* success, so it's a bonding device */
1043 #endif /* BOND_INFO_QUERY_IOCTL */
1045 return 0; /* no, it's not a bonding device */
1047 #endif /* IW_MODE_MONITOR */
1049 static int pcap_protocol(pcap_t
*handle
)
1053 protocol
= handle
->opt
.protocol
;
1055 protocol
= ETH_P_ALL
;
1057 return htons(protocol
);
1061 pcap_can_set_rfmon_linux(pcap_t
*handle
)
1064 char phydev_path
[PATH_MAX
+1];
1067 #ifdef IW_MODE_MONITOR
1072 if (strcmp(handle
->opt
.device
, "any") == 0) {
1074 * Monitor mode makes no sense on the "any" device.
1081 * Bleah. There doesn't seem to be a way to ask a mac80211
1082 * device, through libnl, whether it supports monitor mode;
1083 * we'll just check whether the device appears to be a
1084 * mac80211 device and, if so, assume the device supports
1087 * wmaster devices don't appear to support the Wireless
1088 * Extensions, but we can create a mon device for a
1089 * wmaster device, so we don't bother checking whether
1090 * a mac80211 device supports the Wireless Extensions.
1092 ret
= get_mac80211_phydev(handle
, handle
->opt
.device
, phydev_path
,
1095 return ret
; /* error */
1097 return 1; /* mac80211 device */
1100 #ifdef IW_MODE_MONITOR
1102 * Bleah. There doesn't appear to be an ioctl to use to ask
1103 * whether a device supports monitor mode; we'll just do
1104 * SIOCGIWMODE and, if it succeeds, assume the device supports
1107 * Open a socket on which to attempt to get the mode.
1108 * (We assume that if we have Wireless Extensions support
1109 * we also have PF_PACKET support.)
1111 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, pcap_protocol(handle
));
1112 if (sock_fd
== -1) {
1113 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1118 if (is_bonding_device(sock_fd
, handle
->opt
.device
)) {
1119 /* It's a bonding device, so don't even try. */
1125 * Attempt to get the current mode.
1127 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.device
,
1128 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1129 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1131 * Well, we got the mode; assume we can set it.
1136 if (errno
== ENODEV
) {
1137 /* The device doesn't even exist. */
1138 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1139 errno
, "SIOCGIWMODE failed");
1141 return PCAP_ERROR_NO_SUCH_DEVICE
;
1149 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1151 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1152 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1154 * Or can we get them in binary form from netlink?
1157 linux_if_drops(const char * if_name
)
1162 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1163 long int dropped_pkts
= 0;
1165 file
= fopen("/proc/net/dev", "r");
1169 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1171 /* search for 'bytes' -- if its in there, then
1172 that means we need to grab the fourth field. otherwise
1173 grab the third field. */
1174 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1176 field_to_convert
= 4;
1180 /* find iface and make sure it actually matches -- space before the name and : after it */
1181 if ((bufptr
= strstr(buffer
, if_name
)) &&
1182 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1183 *(bufptr
+ if_name_sz
) == ':')
1185 bufptr
= bufptr
+ if_name_sz
+ 1;
1187 /* grab the nth field from it */
1188 while( --field_to_convert
&& *bufptr
!= '\0')
1190 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1191 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1194 /* get rid of any final spaces */
1195 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1197 if (*bufptr
!= '\0')
1198 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1205 return dropped_pkts
;
1210 * With older kernels promiscuous mode is kind of interesting because we
1211 * have to reset the interface before exiting. The problem can't really
1212 * be solved without some daemon taking care of managing usage counts.
1213 * If we put the interface into promiscuous mode, we set a flag indicating
1214 * that we must take it out of that mode when the interface is closed,
1215 * and, when closing the interface, if that flag is set we take it out
1216 * of promiscuous mode.
1218 * Even with newer kernels, we have the same issue with rfmon mode.
1221 static void pcap_cleanup_linux( pcap_t
*handle
)
1223 struct pcap_linux
*handlep
= handle
->priv
;
1226 struct nl80211_state nlstate
;
1228 #endif /* HAVE_LIBNL */
1229 #ifdef IW_MODE_MONITOR
1232 #endif /* IW_MODE_MONITOR */
1234 if (handlep
->must_do_on_close
!= 0) {
1236 * There's something we have to do when closing this
1239 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1241 * We put the interface into promiscuous mode;
1242 * take it out of promiscuous mode.
1244 * XXX - if somebody else wants it in promiscuous
1245 * mode, this code cannot know that, so it'll take
1246 * it out of promiscuous mode. That's not fixable
1247 * in 2.0[.x] kernels.
1249 memset(&ifr
, 0, sizeof(ifr
));
1250 strlcpy(ifr
.ifr_name
, handlep
->device
,
1251 sizeof(ifr
.ifr_name
));
1252 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1254 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1255 "Please adjust manually.\n"
1256 "Hint: This can't happen with Linux >= 2.2.0.\n",
1257 handlep
->device
, strerror(errno
));
1259 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1261 * Promiscuous mode is currently on;
1264 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1265 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1268 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1269 "Please adjust manually.\n"
1270 "Hint: This can't happen with Linux >= 2.2.0.\n",
1279 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1280 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1282 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1283 handlep
->device
, handlep
->mondevice
);
1284 nl80211_cleanup(&nlstate
);
1288 "Can't delete monitor interface %s (%s).\n"
1289 "Please delete manually.\n",
1290 handlep
->mondevice
, handle
->errbuf
);
1293 #endif /* HAVE_LIBNL */
1295 #ifdef IW_MODE_MONITOR
1296 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1298 * We put the interface into rfmon mode;
1299 * take it out of rfmon mode.
1301 * XXX - if somebody else wants it in rfmon
1302 * mode, this code cannot know that, so it'll take
1303 * it out of rfmon mode.
1307 * First, take the interface down if it's up;
1308 * otherwise, we might get EBUSY.
1309 * If we get errors, just drive on and print
1310 * a warning if we can't restore the mode.
1313 memset(&ifr
, 0, sizeof(ifr
));
1314 strlcpy(ifr
.ifr_name
, handlep
->device
,
1315 sizeof(ifr
.ifr_name
));
1316 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1317 if (ifr
.ifr_flags
& IFF_UP
) {
1318 oldflags
= ifr
.ifr_flags
;
1319 ifr
.ifr_flags
&= ~IFF_UP
;
1320 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1321 oldflags
= 0; /* didn't set, don't restore */
1326 * Now restore the mode.
1328 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1329 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1330 ireq
.u
.mode
= handlep
->oldmode
;
1331 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1333 * Scientist, you've failed.
1336 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1337 "Please adjust manually.\n",
1338 handlep
->device
, strerror(errno
));
1342 * Now bring the interface back up if we brought
1345 if (oldflags
!= 0) {
1346 ifr
.ifr_flags
= oldflags
;
1347 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1349 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1350 "Please adjust manually.\n",
1351 handlep
->device
, strerror(errno
));
1355 #endif /* IW_MODE_MONITOR */
1358 * Take this pcap out of the list of pcaps for which we
1359 * have to take the interface out of some mode.
1361 pcap_remove_from_pcaps_to_close(handle
);
1364 if (handlep
->mondevice
!= NULL
) {
1365 free(handlep
->mondevice
);
1366 handlep
->mondevice
= NULL
;
1368 if (handlep
->device
!= NULL
) {
1369 free(handlep
->device
);
1370 handlep
->device
= NULL
;
1372 pcap_cleanup_live_common(handle
);
1376 * Set the timeout to be used in poll() with memory-mapped packet capture.
1379 set_poll_timeout(struct pcap_linux
*handlep
)
1381 #ifdef HAVE_TPACKET3
1382 struct utsname utsname
;
1383 char *version_component
, *endp
;
1385 int broken_tpacket_v3
= 1;
1388 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1389 * around which we have to work. Determine if we have those
1392 if (uname(&utsname
) == 0) {
1394 * 3.19 is the first release with a fixed version of
1395 * TPACKET_V3. We treat anything before that as
1396 * not haveing a fixed version; that may really mean
1397 * it has *no* version.
1399 version_component
= utsname
.release
;
1400 major
= strtol(version_component
, &endp
, 10);
1401 if (endp
!= version_component
&& *endp
== '.') {
1403 * OK, that was a valid major version.
1404 * Get the minor version.
1406 version_component
= endp
+ 1;
1407 minor
= strtol(version_component
, &endp
, 10);
1408 if (endp
!= version_component
&&
1409 (*endp
== '.' || *endp
== '\0')) {
1411 * OK, that was a valid minor version.
1412 * Is this 3.19 or newer?
1414 if (major
>= 4 || (major
== 3 && minor
>= 19)) {
1415 /* Yes. TPACKET_V3 works correctly. */
1416 broken_tpacket_v3
= 0;
1422 if (handlep
->timeout
== 0) {
1423 #ifdef HAVE_TPACKET3
1425 * XXX - due to a set of (mis)features in the TPACKET_V3
1426 * kernel code prior to the 3.19 kernel, blocking forever
1427 * with a TPACKET_V3 socket can, if few packets are
1428 * arriving and passing the socket filter, cause most
1429 * packets to be dropped. See libpcap issue #335 for the
1430 * full painful story.
1432 * The workaround is to have poll() time out very quickly,
1433 * so we grab the frames handed to us, and return them to
1436 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1437 handlep
->poll_timeout
= 1; /* don't block for very long */
1440 handlep
->poll_timeout
= -1; /* block forever */
1441 } else if (handlep
->timeout
> 0) {
1442 #ifdef HAVE_TPACKET3
1444 * For TPACKET_V3, the timeout is handled by the kernel,
1445 * so block forever; that way, we don't get extra timeouts.
1446 * Don't do that if we have a broken TPACKET_V3, though.
1448 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1449 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1452 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1455 * Non-blocking mode; we call poll() to pick up error
1456 * indications, but we don't want it to wait for
1459 handlep
->poll_timeout
= 0;
1464 * Get a handle for a live capture from the given device. You can
1465 * pass NULL as device to get all packages (without link level
1466 * information of course). If you pass 1 as promisc the interface
1467 * will be set to promiscous mode (XXX: I think this usage should
1468 * be deprecated and functions be added to select that later allow
1469 * modification of that values -- Torsten).
1472 pcap_activate_linux(pcap_t
*handle
)
1474 struct pcap_linux
*handlep
= handle
->priv
;
1480 device
= handle
->opt
.device
;
1483 * Make sure the name we were handed will fit into the ioctls we
1484 * might perform on the device; if not, return a "No such device"
1485 * indication, as the Linux kernel shouldn't support creating
1486 * a device whose name won't fit into those ioctls.
1488 * "Will fit" means "will fit, complete with a null terminator",
1489 * so if the length, which does *not* include the null terminator,
1490 * is greater than *or equal to* the size of the field into which
1491 * we'll be copying it, that won't fit.
1493 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1494 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1499 * Turn a negative snapshot value (invalid), a snapshot value of
1500 * 0 (unspecified), or a value bigger than the normal maximum
1501 * value, into the maximum allowed value.
1503 * If some application really *needs* a bigger snapshot
1504 * length, we should just increase MAXIMUM_SNAPLEN.
1506 if (handle
->snapshot
<= 0 || handle
->snapshot
> MAXIMUM_SNAPLEN
)
1507 handle
->snapshot
= MAXIMUM_SNAPLEN
;
1509 handle
->inject_op
= pcap_inject_linux
;
1510 handle
->setfilter_op
= pcap_setfilter_linux
;
1511 handle
->setdirection_op
= pcap_setdirection_linux
;
1512 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1513 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1514 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1515 handle
->cleanup_op
= pcap_cleanup_linux
;
1516 handle
->read_op
= pcap_read_linux
;
1517 handle
->stats_op
= pcap_stats_linux
;
1520 * The "any" device is a special device which causes us not
1521 * to bind to a particular device and thus to look at all
1524 if (strcmp(device
, "any") == 0) {
1525 if (handle
->opt
.promisc
) {
1526 handle
->opt
.promisc
= 0;
1527 /* Just a warning. */
1528 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1529 "Promiscuous mode not supported on the \"any\" device");
1530 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1534 handlep
->device
= strdup(device
);
1535 if (handlep
->device
== NULL
) {
1536 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1541 /* copy timeout value */
1542 handlep
->timeout
= handle
->opt
.timeout
;
1545 * If we're in promiscuous mode, then we probably want
1546 * to see when the interface drops packets too, so get an
1547 * initial count from /proc/net/dev
1549 if (handle
->opt
.promisc
)
1550 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1553 * Current Linux kernels use the protocol family PF_PACKET to
1554 * allow direct access to all packets on the network while
1555 * older kernels had a special socket type SOCK_PACKET to
1556 * implement this feature.
1557 * While this old implementation is kind of obsolete we need
1558 * to be compatible with older kernels for a while so we are
1559 * trying both methods with the newer method preferred.
1561 ret
= activate_new(handle
);
1564 * Fatal error with the new way; just fail.
1565 * ret has the error return; if it's PCAP_ERROR,
1566 * handle->errbuf has been set appropriately.
1574 * Try to use memory-mapped access.
1576 switch (activate_mmap(handle
, &status
)) {
1580 * We succeeded. status has been
1581 * set to the status to return,
1582 * which might be 0, or might be
1583 * a PCAP_WARNING_ value.
1585 * Set the timeout to use in poll() before
1588 set_poll_timeout(handlep
);
1593 * Kernel doesn't support it - just continue
1594 * with non-memory-mapped access.
1600 * We failed to set up to use it, or the kernel
1601 * supports it, but we failed to enable it.
1602 * ret has been set to the error status to
1603 * return and, if it's PCAP_ERROR, handle->errbuf
1604 * contains the error message.
1610 else if (ret
== 0) {
1611 /* Non-fatal error; try old way */
1612 if ((ret
= activate_old(handle
)) != 1) {
1614 * Both methods to open the packet socket failed.
1615 * Tidy up and report our failure (handle->errbuf
1616 * is expected to be set by the functions above).
1624 * We set up the socket, but not with memory-mapped access.
1626 if (handle
->opt
.buffer_size
!= 0) {
1628 * Set the socket buffer size to the specified value.
1630 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1631 &handle
->opt
.buffer_size
,
1632 sizeof(handle
->opt
.buffer_size
)) == -1) {
1633 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1634 PCAP_ERRBUF_SIZE
, errno
, "SO_RCVBUF");
1635 status
= PCAP_ERROR
;
1640 /* Allocate the buffer */
1642 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1643 if (!handle
->buffer
) {
1644 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1646 status
= PCAP_ERROR
;
1651 * "handle->fd" is a socket, so "select()" and "poll()"
1652 * should work on it.
1654 handle
->selectable_fd
= handle
->fd
;
1659 pcap_cleanup_linux(handle
);
1664 * Read at most max_packets from the capture stream and call the callback
1665 * for each of them. Returns the number of packets handled or -1 if an
1669 pcap_read_linux(pcap_t
*handle
, int max_packets _U_
, pcap_handler callback
, u_char
*user
)
1672 * Currently, on Linux only one packet is delivered per read,
1675 return pcap_read_packet(handle
, callback
, user
);
1679 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1681 handle
->linktype
= dlt
;
1686 * linux_check_direction()
1688 * Do checks based on packet direction.
1691 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1693 struct pcap_linux
*handlep
= handle
->priv
;
1695 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1698 * If this is from the loopback device, reject it;
1699 * we'll see the packet as an incoming packet as well,
1700 * and we don't want to see it twice.
1702 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1706 * If this is an outgoing CAN or CAN FD frame, and
1707 * the user doesn't only want outgoing packets,
1708 * reject it; CAN devices and drivers, and the CAN
1709 * stack, always arrange to loop back transmitted
1710 * packets, so they also appear as incoming packets.
1711 * We don't want duplicate packets, and we can't
1712 * easily distinguish packets looped back by the CAN
1713 * layer than those received by the CAN layer, so we
1714 * eliminate this packet instead.
1716 if ((sll
->sll_protocol
== LINUX_SLL_P_CAN
||
1717 sll
->sll_protocol
== LINUX_SLL_P_CANFD
) &&
1718 handle
->direction
!= PCAP_D_OUT
)
1722 * If the user only wants incoming packets, reject it.
1724 if (handle
->direction
== PCAP_D_IN
)
1729 * If the user only wants outgoing packets, reject it.
1731 if (handle
->direction
== PCAP_D_OUT
)
1738 * Read a packet from the socket calling the handler provided by
1739 * the user. Returns the number of packets received or -1 if an
1743 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1745 struct pcap_linux
*handlep
= handle
->priv
;
1748 #ifdef HAVE_PF_PACKET_SOCKETS
1749 struct sockaddr_ll from
;
1751 struct sockaddr from
;
1753 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1756 struct cmsghdr
*cmsg
;
1758 struct cmsghdr cmsg
;
1759 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1761 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1763 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1764 int packet_len
, caplen
;
1765 struct pcap_pkthdr pcap_header
;
1767 struct bpf_aux_data aux_data
;
1768 #ifdef HAVE_PF_PACKET_SOCKETS
1770 * If this is a cooked device, leave extra room for a
1771 * fake packet header.
1773 if (handlep
->cooked
) {
1774 if (handle
->linktype
== DLT_LINUX_SLL2
)
1775 offset
= SLL2_HDR_LEN
;
1777 offset
= SLL_HDR_LEN
;
1782 * This system doesn't have PF_PACKET sockets, so it doesn't
1783 * support cooked devices.
1789 * Receive a single packet from the kernel.
1790 * We ignore EINTR, as that might just be due to a signal
1791 * being delivered - if the signal should interrupt the
1792 * loop, the signal handler should call pcap_breakloop()
1793 * to set handle->break_loop (we ignore it on other
1794 * platforms as well).
1795 * We also ignore ENETDOWN, so that we can continue to
1796 * capture traffic if the interface goes down and comes
1797 * back up again; comments in the kernel indicate that
1798 * we'll just block waiting for packets if we try to
1799 * receive from a socket that delivered ENETDOWN, and,
1800 * if we're using a memory-mapped buffer, we won't even
1801 * get notified of "network down" events.
1803 bp
= (u_char
*)handle
->buffer
+ handle
->offset
;
1805 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1806 msg
.msg_name
= &from
;
1807 msg
.msg_namelen
= sizeof(from
);
1810 msg
.msg_control
= &cmsg_buf
;
1811 msg
.msg_controllen
= sizeof(cmsg_buf
);
1814 iov
.iov_len
= handle
->bufsize
- offset
;
1815 iov
.iov_base
= bp
+ offset
;
1816 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1820 * Has "pcap_breakloop()" been called?
1822 if (handle
->break_loop
) {
1824 * Yes - clear the flag that indicates that it has,
1825 * and return PCAP_ERROR_BREAK as an indication that
1826 * we were told to break out of the loop.
1828 handle
->break_loop
= 0;
1829 return PCAP_ERROR_BREAK
;
1832 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1833 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1834 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1835 fromlen
= sizeof(from
);
1836 packet_len
= recvfrom(
1837 handle
->fd
, bp
+ offset
,
1838 handle
->bufsize
- offset
, MSG_TRUNC
,
1839 (struct sockaddr
*) &from
, &fromlen
);
1840 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1841 } while (packet_len
== -1 && errno
== EINTR
);
1843 /* Check if an error occured */
1845 if (packet_len
== -1) {
1849 return 0; /* no packet there */
1853 * The device on which we're capturing went away.
1855 * XXX - we should really return
1856 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1857 * etc. aren't defined to return that.
1859 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1860 "The interface went down");
1864 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
1865 PCAP_ERRBUF_SIZE
, errno
, "recvfrom");
1870 #ifdef HAVE_PF_PACKET_SOCKETS
1871 if (!handlep
->sock_packet
) {
1873 * Unfortunately, there is a window between socket() and
1874 * bind() where the kernel may queue packets from any
1875 * interface. If we're bound to a particular interface,
1876 * discard packets not from that interface.
1878 * (If socket filters are supported, we could do the
1879 * same thing we do when changing the filter; however,
1880 * that won't handle packet sockets without socket
1881 * filter support, and it's a bit more complicated.
1882 * It would save some instructions per packet, however.)
1884 if (handlep
->ifindex
!= -1 &&
1885 from
.sll_ifindex
!= handlep
->ifindex
)
1889 * Do checks based on packet direction.
1890 * We can only do this if we're using PF_PACKET; the
1891 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1892 * which lacks the relevant packet type information.
1894 if (!linux_check_direction(handle
, &from
))
1899 #ifdef HAVE_PF_PACKET_SOCKETS
1901 * If this is a cooked device, fill in the fake packet header.
1903 if (handlep
->cooked
) {
1905 * Add the length of the fake header to the length
1906 * of packet data we read.
1908 if (handle
->linktype
== DLT_LINUX_SLL2
) {
1909 struct sll2_header
*hdrp
;
1911 packet_len
+= SLL2_HDR_LEN
;
1913 hdrp
= (struct sll2_header
*)bp
;
1914 hdrp
->sll2_protocol
= from
.sll_protocol
;
1915 hdrp
->sll2_reserved_mbz
= 0;
1916 hdrp
->sll2_if_index
= htonl(from
.sll_ifindex
);
1917 hdrp
->sll2_hatype
= htons(from
.sll_hatype
);
1918 hdrp
->sll2_pkttype
= from
.sll_pkttype
;
1919 hdrp
->sll2_halen
= from
.sll_halen
;
1920 memcpy(hdrp
->sll2_addr
, from
.sll_addr
,
1921 (from
.sll_halen
> SLL_ADDRLEN
) ?
1925 struct sll_header
*hdrp
;
1927 packet_len
+= SLL_HDR_LEN
;
1929 hdrp
= (struct sll_header
*)bp
;
1930 hdrp
->sll_pkttype
= htons(from
.sll_pkttype
);
1931 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1932 hdrp
->sll_halen
= htons(from
.sll_halen
);
1933 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1934 (from
.sll_halen
> SLL_ADDRLEN
) ?
1937 hdrp
->sll_protocol
= from
.sll_protocol
;
1942 * Start out with no VLAN information.
1944 aux_data
.vlan_tag_present
= 0;
1945 aux_data
.vlan_tag
= 0;
1946 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1947 if (handlep
->vlan_offset
!= -1) {
1948 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1949 struct tpacket_auxdata
*aux
;
1951 struct vlan_tag
*tag
;
1953 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1954 cmsg
->cmsg_level
!= SOL_PACKET
||
1955 cmsg
->cmsg_type
!= PACKET_AUXDATA
) {
1957 * This isn't a PACKET_AUXDATA auxiliary
1963 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1964 if (!VLAN_VALID(aux
, aux
)) {
1966 * There is no VLAN information in the
1972 len
= (u_int
)packet_len
> iov
.iov_len
? iov
.iov_len
: (u_int
)packet_len
;
1973 if (len
< (u_int
)handlep
->vlan_offset
)
1977 * Move everything in the header, except the
1978 * type field, down VLAN_TAG_LEN bytes, to
1979 * allow us to insert the VLAN tag between
1980 * that stuff and the type field.
1983 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1986 * Now insert the tag.
1988 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1989 tag
->vlan_tpid
= htons(VLAN_TPID(aux
, aux
));
1990 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1993 * Save a flag indicating that we have a VLAN tag,
1994 * and the VLAN TCI, to bpf_aux_data struct for
1995 * use by the BPF filter if we're doing the
1996 * filtering in userland.
1998 aux_data
.vlan_tag_present
= 1;
1999 aux_data
.vlan_tag
= htons(aux
->tp_vlan_tci
) & 0x0fff;
2002 * Add the tag to the packet lengths.
2004 packet_len
+= VLAN_TAG_LEN
;
2007 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2008 #endif /* HAVE_PF_PACKET_SOCKETS */
2011 * XXX: According to the kernel source we should get the real
2012 * packet len if calling recvfrom with MSG_TRUNC set. It does
2013 * not seem to work here :(, but it is supported by this code
2015 * To be honest the code RELIES on that feature so this is really
2016 * broken with 2.2.x kernels.
2017 * I spend a day to figure out what's going on and I found out
2018 * that the following is happening:
2020 * The packet comes from a random interface and the packet_rcv
2021 * hook is called with a clone of the packet. That code inserts
2022 * the packet into the receive queue of the packet socket.
2023 * If a filter is attached to that socket that filter is run
2024 * first - and there lies the problem. The default filter always
2025 * cuts the packet at the snaplen:
2030 * So the packet filter cuts down the packet. The recvfrom call
2031 * says "hey, it's only 68 bytes, it fits into the buffer" with
2032 * the result that we don't get the real packet length. This
2033 * is valid at least until kernel 2.2.17pre6.
2035 * We currently handle this by making a copy of the filter
2036 * program, fixing all "ret" instructions with non-zero
2037 * operands to have an operand of MAXIMUM_SNAPLEN so that the
2038 * filter doesn't truncate the packet, and supplying that modified
2039 * filter to the kernel.
2042 caplen
= packet_len
;
2043 if (caplen
> handle
->snapshot
)
2044 caplen
= handle
->snapshot
;
2046 /* Run the packet filter if not using kernel filter */
2047 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
2048 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
2049 packet_len
, caplen
, &aux_data
) == 0) {
2050 /* rejected by filter */
2055 /* Fill in our own header data */
2057 /* get timestamp for this packet */
2058 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
2059 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
2060 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
2061 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2062 PCAP_ERRBUF_SIZE
, errno
, "SIOCGSTAMPNS");
2068 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
2069 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2070 PCAP_ERRBUF_SIZE
, errno
, "SIOCGSTAMP");
2075 pcap_header
.caplen
= caplen
;
2076 pcap_header
.len
= packet_len
;
2081 * Arguably, we should count them before we check the filter,
2082 * as on many other platforms "ps_recv" counts packets
2083 * handed to the filter rather than packets that passed
2084 * the filter, but if filtering is done in the kernel, we
2085 * can't get a count of packets that passed the filter,
2086 * and that would mean the meaning of "ps_recv" wouldn't
2087 * be the same on all Linux systems.
2089 * XXX - it's not the same on all systems in any case;
2090 * ideally, we should have a "get the statistics" call
2091 * that supplies more counts and indicates which of them
2092 * it supplies, so that we supply a count of packets
2093 * handed to the filter only on platforms where that
2094 * information is available.
2096 * We count them here even if we can get the packet count
2097 * from the kernel, as we can only determine at run time
2098 * whether we'll be able to get it from the kernel (if
2099 * HAVE_STRUCT_TPACKET_STATS isn't defined, we can't get it from
2100 * the kernel, but if it is defined, the library might
2101 * have been built with a 2.4 or later kernel, but we
2102 * might be running on a 2.2[.x] kernel without Alexey
2103 * Kuznetzov's turbopacket patches, and thus the kernel
2104 * might not be able to supply those statistics). We
2105 * could, I guess, try, when opening the socket, to get
2106 * the statistics, and if we can not increment the count
2107 * here, but it's not clear that always incrementing
2108 * the count is more expensive than always testing a flag
2111 * We keep the count in "handlep->packets_read", and use that
2112 * for "ps_recv" if we can't get the statistics from the kernel.
2113 * We do that because, if we *can* get the statistics from
2114 * the kernel, we use "handlep->stat.ps_recv" and
2115 * "handlep->stat.ps_drop" as running counts, as reading the
2116 * statistics from the kernel resets the kernel statistics,
2117 * and if we directly increment "handlep->stat.ps_recv" here,
2118 * that means it will count packets *twice* on systems where
2119 * we can get kernel statistics - once here, and once in
2120 * pcap_stats_linux().
2122 handlep
->packets_read
++;
2124 /* Call the user supplied callback function */
2125 callback(userdata
, &pcap_header
, bp
);
2131 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
2133 struct pcap_linux
*handlep
= handle
->priv
;
2136 #ifdef HAVE_PF_PACKET_SOCKETS
2137 if (!handlep
->sock_packet
) {
2138 /* PF_PACKET socket */
2139 if (handlep
->ifindex
== -1) {
2141 * We don't support sending on the "any" device.
2143 strlcpy(handle
->errbuf
,
2144 "Sending packets isn't supported on the \"any\" device",
2149 if (handlep
->cooked
) {
2151 * We don't support sending on cooked-mode sockets.
2153 * XXX - how do you send on a bound cooked-mode
2155 * Is a "sendto()" required there?
2157 strlcpy(handle
->errbuf
,
2158 "Sending packets isn't supported in cooked mode",
2165 ret
= send(handle
->fd
, buf
, size
, 0);
2167 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2175 * Get the statistics for the given packet capture handle.
2176 * Reports the number of dropped packets iff the kernel supports
2177 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2178 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2179 * patches); otherwise, that information isn't available, and we lie
2180 * and report 0 as the count of dropped packets.
2183 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
2185 struct pcap_linux
*handlep
= handle
->priv
;
2186 #ifdef HAVE_STRUCT_TPACKET_STATS
2187 #ifdef HAVE_TPACKET3
2189 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2190 * stuff at the end of a struct tpacket_stats_v3 will not
2191 * be filled in, and we don't look at it so this is OK even
2192 * for those sockets. In addition, the PF_PACKET socket
2193 * code in the kernel only uses the length parameter to
2194 * compute how much data to copy out and to indicate how
2195 * much data was copied out, so it's OK to base it on the
2196 * size of a struct tpacket_stats.
2198 * XXX - it's probably OK, in fact, to just use a
2199 * struct tpacket_stats for V3 sockets, as we don't
2200 * care about the tp_freeze_q_cnt stat.
2202 struct tpacket_stats_v3 kstats
;
2203 #else /* HAVE_TPACKET3 */
2204 struct tpacket_stats kstats
;
2205 #endif /* HAVE_TPACKET3 */
2206 socklen_t len
= sizeof (struct tpacket_stats
);
2207 #endif /* HAVE_STRUCT_TPACKET_STATS */
2209 long if_dropped
= 0;
2212 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
2214 if (handle
->opt
.promisc
)
2216 if_dropped
= handlep
->proc_dropped
;
2217 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
2218 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
2221 #ifdef HAVE_STRUCT_TPACKET_STATS
2223 * Try to get the packet counts from the kernel.
2225 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
2226 &kstats
, &len
) > -1) {
2228 * On systems where the PACKET_STATISTICS "getsockopt()"
2229 * argument is supported on PF_PACKET sockets:
2231 * "ps_recv" counts only packets that *passed* the
2232 * filter, not packets that didn't pass the filter.
2233 * This includes packets later dropped because we
2234 * ran out of buffer space.
2236 * "ps_drop" counts packets dropped because we ran
2237 * out of buffer space. It doesn't count packets
2238 * dropped by the interface driver. It counts only
2239 * packets that passed the filter.
2241 * See above for ps_ifdrop.
2243 * Both statistics include packets not yet read from
2244 * the kernel by libpcap, and thus not yet seen by
2247 * In "linux/net/packet/af_packet.c", at least in the
2248 * 2.4.9 kernel, "tp_packets" is incremented for every
2249 * packet that passes the packet filter *and* is
2250 * successfully queued on the socket; "tp_drops" is
2251 * incremented for every packet dropped because there's
2252 * not enough free space in the socket buffer.
2254 * When the statistics are returned for a PACKET_STATISTICS
2255 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2256 * so that "tp_packets" counts all packets handed to
2257 * the PF_PACKET socket, including packets dropped because
2258 * there wasn't room on the socket buffer - but not
2259 * including packets that didn't pass the filter.
2261 * In the BSD BPF, the count of received packets is
2262 * incremented for every packet handed to BPF, regardless
2263 * of whether it passed the filter.
2265 * We can't make "pcap_stats()" work the same on both
2266 * platforms, but the best approximation is to return
2267 * "tp_packets" as the count of packets and "tp_drops"
2268 * as the count of drops.
2270 * Keep a running total because each call to
2271 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2272 * resets the counters to zero.
2274 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
2275 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
2276 *stats
= handlep
->stat
;
2282 * If the error was EOPNOTSUPP, fall through, so that
2283 * if you build the library on a system with
2284 * "struct tpacket_stats" and run it on a system
2285 * that doesn't, it works as it does if the library
2286 * is built on a system without "struct tpacket_stats".
2288 if (errno
!= EOPNOTSUPP
) {
2289 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2290 PCAP_ERRBUF_SIZE
, errno
, "pcap_stats");
2296 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2297 * is not supported on PF_PACKET sockets:
2299 * "ps_recv" counts only packets that *passed* the filter,
2300 * not packets that didn't pass the filter. It does not
2301 * count packets dropped because we ran out of buffer
2304 * "ps_drop" is not supported.
2306 * "ps_ifdrop" is supported. It will return the number
2307 * of drops the interface reports in /proc/net/dev,
2308 * if that is available.
2310 * "ps_recv" doesn't include packets not yet read from
2311 * the kernel by libpcap.
2313 * We maintain the count of packets processed by libpcap in
2314 * "handlep->packets_read", for reasons described in the comment
2315 * at the end of pcap_read_packet(). We have no idea how many
2316 * packets were dropped by the kernel buffers -- but we know
2317 * how many the interface dropped, so we can return that.
2320 stats
->ps_recv
= handlep
->packets_read
;
2322 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2327 add_linux_if(pcap_if_list_t
*devlistp
, const char *ifname
, int fd
, char *errbuf
)
2330 char name
[512]; /* XXX - pick a size */
2332 struct ifreq ifrflags
;
2335 * Get the interface name.
2339 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2342 * This could be the separator between a
2343 * name and an alias number, or it could be
2344 * the separator between a name with no
2345 * alias number and the next field.
2347 * If there's a colon after digits, it
2348 * separates the name and the alias number,
2349 * otherwise it separates the name and the
2353 while (isascii(*p
) && isdigit(*p
))
2357 * That was the next field,
2358 * not the alias number.
2369 * Get the flags for this interface.
2371 strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2372 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2373 if (errno
== ENXIO
|| errno
== ENODEV
)
2374 return (0); /* device doesn't actually exist - ignore it */
2375 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2376 errno
, "SIOCGIFFLAGS: %.*s",
2377 (int)sizeof(ifrflags
.ifr_name
),
2383 * Add an entry for this interface, with no addresses, if it's
2384 * not already in the list.
2386 if (find_or_add_if(devlistp
, name
, ifrflags
.ifr_flags
,
2387 get_if_flags
, errbuf
) == NULL
) {
2398 * Get from "/sys/class/net" all interfaces listed there; if they're
2399 * already in the list of interfaces we have, that won't add another
2400 * instance, but if they're not, that'll add them.
2402 * We don't bother getting any addresses for them; it appears you can't
2403 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2404 * although some other types of addresses can be fetched with SIOCGIFADDR,
2405 * we don't bother with them for now.
2407 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2408 * the list of interfaces as is, and return 0, so that we can try
2409 * scanning /proc/net/dev.
2411 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2414 scan_sys_class_net(pcap_if_list_t
*devlistp
, char *errbuf
)
2416 DIR *sys_class_net_d
;
2419 char subsystem_path
[PATH_MAX
+1];
2423 sys_class_net_d
= opendir("/sys/class/net");
2424 if (sys_class_net_d
== NULL
) {
2426 * Don't fail if it doesn't exist at all.
2428 if (errno
== ENOENT
)
2432 * Fail if we got some other error.
2434 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2435 errno
, "Can't open /sys/class/net");
2440 * Create a socket from which to fetch interface information.
2442 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
2444 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2446 (void)closedir(sys_class_net_d
);
2452 ent
= readdir(sys_class_net_d
);
2455 * Error or EOF; if errno != 0, it's an error.
2461 * Ignore "." and "..".
2463 if (strcmp(ent
->d_name
, ".") == 0 ||
2464 strcmp(ent
->d_name
, "..") == 0)
2468 * Ignore plain files; they do not have subdirectories
2469 * and thus have no attributes.
2471 if (ent
->d_type
== DT_REG
)
2475 * Is there an "ifindex" file under that name?
2476 * (We don't care whether it's a directory or
2477 * a symlink; older kernels have directories
2478 * for devices, newer kernels have symlinks to
2481 pcap_snprintf(subsystem_path
, sizeof subsystem_path
,
2482 "/sys/class/net/%s/ifindex", ent
->d_name
);
2483 if (lstat(subsystem_path
, &statb
) != 0) {
2485 * Stat failed. Either there was an error
2486 * other than ENOENT, and we don't know if
2487 * this is an interface, or it's ENOENT,
2488 * and either some part of "/sys/class/net/{if}"
2489 * disappeared, in which case it probably means
2490 * the interface disappeared, or there's no
2491 * "ifindex" file, which means it's not a
2492 * network interface.
2498 * Attempt to add the interface.
2500 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2508 * Well, we didn't fail for any other reason; did we
2509 * fail due to an error reading the directory?
2512 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2513 errno
, "Error reading /sys/class/net");
2519 (void)closedir(sys_class_net_d
);
2524 * Get from "/proc/net/dev" all interfaces listed there; if they're
2525 * already in the list of interfaces we have, that won't add another
2526 * instance, but if they're not, that'll add them.
2528 * See comments from scan_sys_class_net().
2531 scan_proc_net_dev(pcap_if_list_t
*devlistp
, char *errbuf
)
2540 proc_net_f
= fopen("/proc/net/dev", "r");
2541 if (proc_net_f
== NULL
) {
2543 * Don't fail if it doesn't exist at all.
2545 if (errno
== ENOENT
)
2549 * Fail if we got some other error.
2551 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2552 errno
, "Can't open /proc/net/dev");
2557 * Create a socket from which to fetch interface information.
2559 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
2561 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2563 (void)fclose(proc_net_f
);
2568 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2570 * Skip the first two lines - they're headers.
2578 * Skip leading white space.
2580 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2582 if (*p
== '\0' || *p
== '\n')
2583 continue; /* blank line */
2586 * Attempt to add the interface.
2588 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2596 * Well, we didn't fail for any other reason; did we
2597 * fail due to an error reading the file?
2599 if (ferror(proc_net_f
)) {
2600 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2601 errno
, "Error reading /proc/net/dev");
2607 (void)fclose(proc_net_f
);
2612 * Description string for the "any" device.
2614 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2617 * A SOCK_PACKET or PF_PACKET socket can be bound to any network interface.
2620 can_be_bound(const char *name _U_
)
2626 * Get additional flags for a device, using SIOCGIFMEDIA.
2629 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
2633 unsigned int arptype
;
2635 struct ethtool_value info
;
2637 if (*flags
& PCAP_IF_LOOPBACK
) {
2639 * Loopback devices aren't wireless, and "connected"/
2640 * "disconnected" doesn't apply to them.
2642 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2646 sock
= socket(AF_INET
, SOCK_DGRAM
, 0);
2648 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
, errno
,
2649 "Can't create socket to get ethtool information for %s",
2655 * OK, what type of network is this?
2656 * In particular, is it wired or wireless?
2658 if (is_wifi(sock
, name
)) {
2660 * Wi-Fi, hence wireless.
2662 *flags
|= PCAP_IF_WIRELESS
;
2665 * OK, what does /sys/class/net/{if}/type contain?
2666 * (We don't use that for Wi-Fi, as it'll report
2667 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
2672 if (asprintf(&pathstr
, "/sys/class/net/%s/type", name
) == -1) {
2673 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2674 "%s: Can't generate path name string for /sys/class/net device",
2679 fh
= fopen(pathstr
, "r");
2681 if (fscanf(fh
, "%u", &arptype
) == 1) {
2683 * OK, we got an ARPHRD_ type; what is it?
2687 #ifdef ARPHRD_LOOPBACK
2688 case ARPHRD_LOOPBACK
:
2690 * These are types to which
2691 * "connected" and "disconnected"
2692 * don't apply, so don't bother
2695 * XXX - add other types?
2704 case ARPHRD_IEEE80211
:
2705 case ARPHRD_IEEE80211_PRISM
:
2706 case ARPHRD_IEEE80211_RADIOTAP
:
2707 #ifdef ARPHRD_IEEE802154
2708 case ARPHRD_IEEE802154
:
2710 #ifdef ARPHRD_IEEE802154_MONITOR
2711 case ARPHRD_IEEE802154_MONITOR
:
2713 #ifdef ARPHRD_6LOWPAN
2714 case ARPHRD_6LOWPAN
:
2717 * Various wireless types.
2719 *flags
|= PCAP_IF_WIRELESS
;
2728 #ifdef ETHTOOL_GLINK
2729 memset(&ifr
, 0, sizeof(ifr
));
2730 strlcpy(ifr
.ifr_name
, name
, sizeof(ifr
.ifr_name
));
2731 info
.cmd
= ETHTOOL_GLINK
;
2732 ifr
.ifr_data
= (caddr_t
)&info
;
2733 if (ioctl(sock
, SIOCETHTOOL
, &ifr
) == -1) {
2734 int save_errno
= errno
;
2736 switch (save_errno
) {
2741 * OK, this OS version or driver doesn't support
2742 * asking for this information.
2743 * XXX - distinguish between "this doesn't
2744 * support ethtool at all because it's not
2745 * that type of device" vs. "this doesn't
2746 * support ethtool even though it's that
2747 * type of device", and return "unknown".
2749 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2755 * OK, no such device.
2756 * The user will find that out when they try to
2757 * activate the device; just say "OK" and
2758 * don't set anything.
2767 pcap_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2769 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
2783 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2786 * It's disconnected.
2788 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2797 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
2802 * Get the list of regular interfaces first.
2804 if (pcap_findalldevs_interfaces(devlistp
, errbuf
, can_be_bound
,
2805 get_if_flags
) == -1)
2806 return (-1); /* failure */
2809 * Read "/sys/class/net", and add to the list of interfaces all
2810 * interfaces listed there that we don't already have, because,
2811 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2812 * and even getifaddrs() won't return information about
2813 * interfaces with no addresses, so you need to read "/sys/class/net"
2814 * to get the names of the rest of the interfaces.
2816 ret
= scan_sys_class_net(devlistp
, errbuf
);
2818 return (-1); /* failed */
2821 * No /sys/class/net; try reading /proc/net/dev instead.
2823 if (scan_proc_net_dev(devlistp
, errbuf
) == -1)
2828 * Add the "any" device.
2829 * As it refers to all network devices, not to any particular
2830 * network device, the notion of "connected" vs. "disconnected"
2833 if (add_dev(devlistp
, "any",
2834 PCAP_IF_UP
|PCAP_IF_RUNNING
|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
2835 any_descr
, errbuf
) == NULL
)
2842 * Attach the given BPF code to the packet capture device.
2845 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2848 struct pcap_linux
*handlep
;
2849 #ifdef SO_ATTACH_FILTER
2850 struct sock_fprog fcode
;
2851 int can_filter_in_kernel
;
2858 strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2863 handlep
= handle
->priv
;
2865 /* Make our private copy of the filter */
2867 if (install_bpf_program(handle
, filter
) < 0)
2868 /* install_bpf_program() filled in errbuf */
2872 * Run user level packet filter by default. Will be overriden if
2873 * installing a kernel filter succeeds.
2875 handlep
->filter_in_userland
= 1;
2877 /* Install kernel level filter if possible */
2879 #ifdef SO_ATTACH_FILTER
2881 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2883 * fcode.len is an unsigned short for current kernel.
2884 * I have yet to see BPF-Code with that much
2885 * instructions but still it is possible. So for the
2886 * sake of correctness I added this check.
2888 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2890 fcode
.filter
= NULL
;
2891 can_filter_in_kernel
= 0;
2893 #endif /* USHRT_MAX */
2896 * Oh joy, the Linux kernel uses struct sock_fprog instead
2897 * of struct bpf_program and of course the length field is
2898 * of different size. Pointed out by Sebastian
2900 * Oh, and we also need to fix it up so that all "ret"
2901 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2902 * as the operand if we're not capturing in memory-mapped
2903 * mode, and so that, if we're in cooked mode, all memory-
2904 * reference instructions use special magic offsets in
2905 * references to the link-layer header and assume that the
2906 * link-layer payload begins at 0; "fix_program()" will do
2909 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2914 * Fatal error; just quit.
2915 * (The "default" case shouldn't happen; we
2916 * return -1 for that reason.)
2922 * The program performed checks that we can't make
2923 * work in the kernel.
2925 can_filter_in_kernel
= 0;
2930 * We have a filter that'll work in the kernel.
2932 can_filter_in_kernel
= 1;
2938 * NOTE: at this point, we've set both the "len" and "filter"
2939 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2940 * those are the only members of the "sock_fprog" structure,
2941 * so we initialize every member of that structure.
2943 * If there is anything in "fcode" that is not initialized,
2944 * it is either a field added in a later kernel, or it's
2947 * If a new field is added, this code needs to be updated
2948 * to set it correctly.
2950 * If there are no other fields, then:
2952 * if the Linux kernel looks at the padding, it's
2955 * if the Linux kernel doesn't look at the padding,
2956 * then if some tool complains that we're passing
2957 * uninitialized data to the kernel, then the tool
2958 * is buggy and needs to understand that it's just
2961 if (can_filter_in_kernel
) {
2962 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2965 * Installation succeded - using kernel filter,
2966 * so userland filtering not needed.
2968 handlep
->filter_in_userland
= 0;
2970 else if (err
== -1) /* Non-fatal error */
2973 * Print a warning if we weren't able to install
2974 * the filter for a reason other than "this kernel
2975 * isn't configured to support socket filters.
2977 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2979 "Warning: Kernel filter failed: %s\n",
2980 pcap_strerror(errno
));
2986 * If we're not using the kernel filter, get rid of any kernel
2987 * filter that might've been there before, e.g. because the
2988 * previous filter could work in the kernel, or because some other
2989 * code attached a filter to the socket by some means other than
2990 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2991 * filter out packets that would pass the new userland filter.
2993 if (handlep
->filter_in_userland
) {
2994 if (reset_kernel_filter(handle
) == -1) {
2995 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
2996 PCAP_ERRBUF_SIZE
, errno
,
2997 "can't remove kernel filter");
2998 err
= -2; /* fatal error */
3003 * Free up the copy of the filter that was made by "fix_program()".
3005 if (fcode
.filter
!= NULL
)
3011 #endif /* SO_ATTACH_FILTER */
3017 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
3019 return pcap_setfilter_linux_common(handle
, filter
, 0);
3024 * Set direction flag: Which packets do we accept on a forwarding
3025 * single device? IN, OUT or both?
3028 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
3030 #ifdef HAVE_PF_PACKET_SOCKETS
3031 struct pcap_linux
*handlep
= handle
->priv
;
3033 if (!handlep
->sock_packet
) {
3034 handle
->direction
= d
;
3039 * We're not using PF_PACKET sockets, so we can't determine
3040 * the direction of the packet.
3042 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3043 "Setting direction is not supported on SOCK_PACKET sockets");
3049 #ifndef IW_MODE_MONITOR
3052 , const char *device
)
3056 #ifdef IW_MODE_MONITOR
3057 char errbuf
[PCAP_ERRBUF_SIZE
];
3061 * See if there's a sysfs wireless directory for it.
3062 * If so, it's a wireless interface.
3064 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
3066 * Just give up here.
3070 if (stat(pathstr
, &statb
) == 0) {
3076 #ifdef IW_MODE_MONITOR
3078 * OK, maybe it's not wireless, or maybe this kernel doesn't
3079 * support sysfs. Try the wireless extensions.
3081 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
3083 * It supports the wireless extensions, so it's a Wi-Fi
3093 * Linux uses the ARP hardware type to identify the type of an
3094 * interface. pcap uses the DLT_xxx constants for this. This
3095 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
3096 * constant, as arguments, and sets "handle->linktype" to the
3097 * appropriate DLT_XXX constant and sets "handle->offset" to
3098 * the appropriate value (to make "handle->offset" plus link-layer
3099 * header length be a multiple of 4, so that the link-layer payload
3100 * will be aligned on a 4-byte boundary when capturing packets).
3101 * (If the offset isn't set here, it'll be 0; add code as appropriate
3102 * for cases where it shouldn't be 0.)
3104 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
3105 * in cooked mode; otherwise, we can't use cooked mode, so we have
3106 * to pick some type that works in raw mode, or fail.
3108 * Sets the link type to -1 if unable to map the type.
3110 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
3111 const char *device
, int cooked_ok
)
3113 static const char cdma_rmnet
[] = "cdma_rmnet";
3119 * For various annoying reasons having to do with DHCP
3120 * software, some versions of Android give the mobile-
3121 * phone-network interface an ARPHRD_ value of
3122 * ARPHRD_ETHER, even though the packets supplied by
3123 * that interface have no link-layer header, and begin
3124 * with an IP header, so that the ARPHRD_ value should
3127 * Detect those devices by checking the device name, and
3128 * use DLT_RAW for them.
3130 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
3131 handle
->linktype
= DLT_RAW
;
3136 * Is this a real Ethernet device? If so, give it a
3137 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
3138 * that an application can let you choose it, in case you're
3139 * capturing DOCSIS traffic that a Cisco Cable Modem
3140 * Termination System is putting out onto an Ethernet (it
3141 * doesn't put an Ethernet header onto the wire, it puts raw
3142 * DOCSIS frames out on the wire inside the low-level
3143 * Ethernet framing).
3145 * XXX - are there any other sorts of "fake Ethernet" that
3146 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
3147 * a Cisco CMTS won't put traffic onto it or get traffic
3148 * bridged onto it? ISDN is handled in "activate_new()",
3149 * as we fall back on cooked mode there, and we use
3150 * is_wifi() to check for 802.11 devices; are there any
3153 if (!is_wifi(sock_fd
, device
)) {
3155 * It's not a Wi-Fi device; offer DOCSIS.
3157 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3159 * If that fails, just leave the list empty.
3161 if (handle
->dlt_list
!= NULL
) {
3162 handle
->dlt_list
[0] = DLT_EN10MB
;
3163 handle
->dlt_list
[1] = DLT_DOCSIS
;
3164 handle
->dlt_count
= 2;
3169 case ARPHRD_METRICOM
:
3170 case ARPHRD_LOOPBACK
:
3171 handle
->linktype
= DLT_EN10MB
;
3176 handle
->linktype
= DLT_EN3MB
;
3180 handle
->linktype
= DLT_AX25_KISS
;
3184 handle
->linktype
= DLT_PRONET
;
3188 handle
->linktype
= DLT_CHAOS
;
3191 #define ARPHRD_CAN 280
3195 * Map this to DLT_LINUX_SLL; that way, CAN frames will
3196 * have ETH_P_CAN/LINUX_SLL_P_CAN as the protocol and
3197 * CAN FD frames will have ETH_P_CANFD/LINUX_SLL_P_CANFD
3198 * as the protocol, so they can be distinguished by the
3199 * protocol in the SLL header.
3201 handle
->linktype
= DLT_LINUX_SLL
;
3204 #ifndef ARPHRD_IEEE802_TR
3205 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
3207 case ARPHRD_IEEE802_TR
:
3208 case ARPHRD_IEEE802
:
3209 handle
->linktype
= DLT_IEEE802
;
3214 handle
->linktype
= DLT_ARCNET_LINUX
;
3217 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
3218 #define ARPHRD_FDDI 774
3221 handle
->linktype
= DLT_FDDI
;
3225 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
3226 #define ARPHRD_ATM 19
3230 * The Classical IP implementation in ATM for Linux
3231 * supports both what RFC 1483 calls "LLC Encapsulation",
3232 * in which each packet has an LLC header, possibly
3233 * with a SNAP header as well, prepended to it, and
3234 * what RFC 1483 calls "VC Based Multiplexing", in which
3235 * different virtual circuits carry different network
3236 * layer protocols, and no header is prepended to packets.
3238 * They both have an ARPHRD_ type of ARPHRD_ATM, so
3239 * you can't use the ARPHRD_ type to find out whether
3240 * captured packets will have an LLC header, and,
3241 * while there's a socket ioctl to *set* the encapsulation
3242 * type, there's no ioctl to *get* the encapsulation type.
3246 * programs that dissect Linux Classical IP frames
3247 * would have to check for an LLC header and,
3248 * depending on whether they see one or not, dissect
3249 * the frame as LLC-encapsulated or as raw IP (I
3250 * don't know whether there's any traffic other than
3251 * IP that would show up on the socket, or whether
3252 * there's any support for IPv6 in the Linux
3253 * Classical IP code);
3255 * filter expressions would have to compile into
3256 * code that checks for an LLC header and does
3259 * Both of those are a nuisance - and, at least on systems
3260 * that support PF_PACKET sockets, we don't have to put
3261 * up with those nuisances; instead, we can just capture
3262 * in cooked mode. That's what we'll do, if we can.
3263 * Otherwise, we'll just fail.
3266 handle
->linktype
= DLT_LINUX_SLL
;
3268 handle
->linktype
= -1;
3271 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
3272 #define ARPHRD_IEEE80211 801
3274 case ARPHRD_IEEE80211
:
3275 handle
->linktype
= DLT_IEEE802_11
;
3278 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
3279 #define ARPHRD_IEEE80211_PRISM 802
3281 case ARPHRD_IEEE80211_PRISM
:
3282 handle
->linktype
= DLT_PRISM_HEADER
;
3285 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
3286 #define ARPHRD_IEEE80211_RADIOTAP 803
3288 case ARPHRD_IEEE80211_RADIOTAP
:
3289 handle
->linktype
= DLT_IEEE802_11_RADIO
;
3294 * Some PPP code in the kernel supplies no link-layer
3295 * header whatsoever to PF_PACKET sockets; other PPP
3296 * code supplies PPP link-layer headers ("syncppp.c");
3297 * some PPP code might supply random link-layer
3298 * headers (PPP over ISDN - there's code in Ethereal,
3299 * for example, to cope with PPP-over-ISDN captures
3300 * with which the Ethereal developers have had to cope,
3301 * heuristically trying to determine which of the
3302 * oddball link-layer headers particular packets have).
3304 * As such, we just punt, and run all PPP interfaces
3305 * in cooked mode, if we can; otherwise, we just treat
3306 * it as DLT_RAW, for now - if somebody needs to capture,
3307 * on a 2.0[.x] kernel, on PPP devices that supply a
3308 * link-layer header, they'll have to add code here to
3309 * map to the appropriate DLT_ type (possibly adding a
3310 * new DLT_ type, if necessary).
3313 handle
->linktype
= DLT_LINUX_SLL
;
3316 * XXX - handle ISDN types here? We can't fall
3317 * back on cooked sockets, so we'd have to
3318 * figure out from the device name what type of
3319 * link-layer encapsulation it's using, and map
3320 * that to an appropriate DLT_ value, meaning
3321 * we'd map "isdnN" devices to DLT_RAW (they
3322 * supply raw IP packets with no link-layer
3323 * header) and "isdY" devices to a new DLT_I4L_IP
3324 * type that has only an Ethernet packet type as
3325 * a link-layer header.
3327 * But sometimes we seem to get random crap
3328 * in the link-layer header when capturing on
3331 handle
->linktype
= DLT_RAW
;
3335 #ifndef ARPHRD_CISCO
3336 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3339 handle
->linktype
= DLT_C_HDLC
;
3342 /* Not sure if this is correct for all tunnels, but it
3346 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3354 #ifndef ARPHRD_RAWHDLC
3355 #define ARPHRD_RAWHDLC 518
3357 case ARPHRD_RAWHDLC
:
3359 #define ARPHRD_DLCI 15
3363 * XXX - should some of those be mapped to DLT_LINUX_SLL
3364 * instead? Should we just map all of them to DLT_LINUX_SLL?
3366 handle
->linktype
= DLT_RAW
;
3370 #define ARPHRD_FRAD 770
3373 handle
->linktype
= DLT_FRELAY
;
3376 case ARPHRD_LOCALTLK
:
3377 handle
->linktype
= DLT_LTALK
;
3382 * RFC 4338 defines an encapsulation for IP and ARP
3383 * packets that's compatible with the RFC 2625
3384 * encapsulation, but that uses a different ARP
3385 * hardware type and hardware addresses. That
3386 * ARP hardware type is 18; Linux doesn't define
3387 * any ARPHRD_ value as 18, but if it ever officially
3388 * supports RFC 4338-style IP-over-FC, it should define
3391 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3392 * that this will encourage its use in the future,
3393 * should Linux ever officially support RFC 4338-style
3396 handle
->linktype
= DLT_IP_OVER_FC
;
3400 #define ARPHRD_FCPP 784
3404 #define ARPHRD_FCAL 785
3408 #define ARPHRD_FCPL 786
3411 #ifndef ARPHRD_FCFABRIC
3412 #define ARPHRD_FCFABRIC 787
3414 case ARPHRD_FCFABRIC
:
3416 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3419 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3421 * and one was assigned.
3423 * In a later private discussion (spun off from a message
3424 * on the ethereal-users list) on how to get that DLT_
3425 * value in libpcap on Linux, I ended up deciding that
3426 * the best thing to do would be to have him tweak the
3427 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3428 * type, and map all those types to DLT_IP_OVER_FC:
3430 * I've checked into the libpcap and tcpdump CVS tree
3431 * support for DLT_IP_OVER_FC. In order to use that,
3432 * you'd have to modify your modified driver to return
3433 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3434 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3435 * example (the exact value doesn't matter, it can be
3436 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3439 * 11 years later, Christian Svensson wanted to map
3440 * various ARPHRD_ values to DLT_FC_2 and
3441 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3444 * https://github.com/mcr/libpcap/pull/29
3446 * There doesn't seem to be any network drivers that uses
3447 * any of the ARPHRD_FC* values for IP-over-FC, and
3448 * it's not exactly clear what the "Dummy types for non
3449 * ARP hardware" are supposed to mean (link-layer
3450 * header type? Physical network type?), so it's
3451 * not exactly clear why the ARPHRD_FC* types exist
3452 * in the first place.
3454 * For now, we map them to DLT_FC_2, and provide an
3455 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3456 * DLT_IP_OVER_FC just in case there's some old
3457 * driver out there that uses one of those types for
3458 * IP-over-FC on which somebody wants to capture
3461 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 3);
3463 * If that fails, just leave the list empty.
3465 if (handle
->dlt_list
!= NULL
) {
3466 handle
->dlt_list
[0] = DLT_FC_2
;
3467 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
3468 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
3469 handle
->dlt_count
= 3;
3471 handle
->linktype
= DLT_FC_2
;
3475 #define ARPHRD_IRDA 783
3478 /* Don't expect IP packet out of this interfaces... */
3479 handle
->linktype
= DLT_LINUX_IRDA
;
3480 /* We need to save packet direction for IrDA decoding,
3481 * so let's use "Linux-cooked" mode. Jean II
3483 * XXX - this is handled in activate_new(). */
3484 /* handlep->cooked = 1; */
3487 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3488 * is needed, please report it to <daniele@orlandi.com> */
3490 #define ARPHRD_LAPD 8445
3493 /* Don't expect IP packet out of this interfaces... */
3494 handle
->linktype
= DLT_LINUX_LAPD
;
3498 #define ARPHRD_NONE 0xFFFE
3502 * No link-layer header; packets are just IP
3503 * packets, so use DLT_RAW.
3505 handle
->linktype
= DLT_RAW
;
3508 #ifndef ARPHRD_IEEE802154
3509 #define ARPHRD_IEEE802154 804
3511 case ARPHRD_IEEE802154
:
3512 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
3515 #ifndef ARPHRD_NETLINK
3516 #define ARPHRD_NETLINK 824
3518 case ARPHRD_NETLINK
:
3519 handle
->linktype
= DLT_NETLINK
;
3521 * We need to use cooked mode, so that in sll_protocol we
3522 * pick up the netlink protocol type such as NETLINK_ROUTE,
3523 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3525 * XXX - this is handled in activate_new().
3527 /* handlep->cooked = 1; */
3530 #ifndef ARPHRD_VSOCKMON
3531 #define ARPHRD_VSOCKMON 826
3533 case ARPHRD_VSOCKMON
:
3534 handle
->linktype
= DLT_VSOCK
;
3538 handle
->linktype
= -1;
3543 /* ===== Functions to interface to the newer kernels ================== */
3545 #ifdef PACKET_RESERVE
3547 set_dlt_list_cooked(pcap_t
*handle
, int sock_fd
)
3550 unsigned int tp_reserve
;
3553 * If we can't do PACKET_RESERVE, we can't reserve extra space
3554 * for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3556 len
= sizeof(tp_reserve
);
3557 if (getsockopt(sock_fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
,
3560 * Yes, we can do DLL_LINUX_SLL2.
3562 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3564 * If that fails, just leave the list empty.
3566 if (handle
->dlt_list
!= NULL
) {
3567 handle
->dlt_list
[0] = DLT_LINUX_SLL
;
3568 handle
->dlt_list
[1] = DLT_LINUX_SLL2
;
3569 handle
->dlt_count
= 2;
3575 * The build environment doesn't define PACKET_RESERVE, so we can't reserve
3576 * extra space for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3579 set_dlt_list_cooked(pcap_t
*handle _U_
, int sock_fd _U_
)
3585 * Try to open a packet socket using the new kernel PF_PACKET interface.
3586 * Returns 1 on success, 0 on an error that means the new interface isn't
3587 * present (so the old SOCK_PACKET interface should be tried), and a
3588 * PCAP_ERROR_ value on an error that means that the old mechanism won't
3589 * work either (so it shouldn't be tried).
3592 activate_new(pcap_t
*handle
)
3594 #ifdef HAVE_PF_PACKET_SOCKETS
3595 struct pcap_linux
*handlep
= handle
->priv
;
3596 const char *device
= handle
->opt
.device
;
3597 int is_any_device
= (strcmp(device
, "any") == 0);
3598 int protocol
= pcap_protocol(handle
);
3599 int sock_fd
= -1, arptype
;
3600 #ifdef HAVE_PACKET_AUXDATA
3604 struct packet_mreq mr
;
3605 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3607 socklen_t len
= sizeof(bpf_extensions
);
3611 * Open a socket with protocol family packet. If the
3612 * "any" device was specified, we open a SOCK_DGRAM
3613 * socket for the cooked interface, otherwise we first
3614 * try a SOCK_RAW socket for the raw interface.
3616 sock_fd
= is_any_device
?
3617 socket(PF_PACKET
, SOCK_DGRAM
, protocol
) :
3618 socket(PF_PACKET
, SOCK_RAW
, protocol
);
3620 if (sock_fd
== -1) {
3621 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
3623 * We don't support PF_PACKET/SOCK_whatever
3624 * sockets; try the old mechanism.
3629 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3631 if (errno
== EPERM
|| errno
== EACCES
) {
3633 * You don't have permission to open the
3636 return PCAP_ERROR_PERM_DENIED
;
3645 /* It seems the kernel supports the new interface. */
3646 handlep
->sock_packet
= 0;
3649 * Get the interface index of the loopback device.
3650 * If the attempt fails, don't fail, just set the
3651 * "handlep->lo_ifindex" to -1.
3653 * XXX - can there be more than one device that loops
3654 * packets back, i.e. devices other than "lo"? If so,
3655 * we'd need to find them all, and have an array of
3656 * indices for them, and check all of them in
3657 * "pcap_read_packet()".
3659 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3662 * Default value for offset to align link-layer payload
3663 * on a 4-byte boundary.
3668 * What kind of frames do we have to deal with? Fall back
3669 * to cooked mode if we have an unknown interface type
3670 * or a type we know doesn't work well in raw mode.
3672 if (!is_any_device
) {
3673 /* Assume for now we don't need cooked mode. */
3674 handlep
->cooked
= 0;
3676 if (handle
->opt
.rfmon
) {
3678 * We were asked to turn on monitor mode.
3679 * Do so before we get the link-layer type,
3680 * because entering monitor mode could change
3681 * the link-layer type.
3683 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3691 * Nothing worked for turning monitor mode
3695 return PCAP_ERROR_RFMON_NOTSUP
;
3699 * Either monitor mode has been turned on for
3700 * the device, or we've been given a different
3701 * device to open for monitor mode. If we've
3702 * been given a different device, use it.
3704 if (handlep
->mondevice
!= NULL
)
3705 device
= handlep
->mondevice
;
3707 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3712 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
3713 if (handle
->linktype
== -1 ||
3714 handle
->linktype
== DLT_LINUX_SLL
||
3715 handle
->linktype
== DLT_LINUX_IRDA
||
3716 handle
->linktype
== DLT_LINUX_LAPD
||
3717 handle
->linktype
== DLT_NETLINK
||
3718 (handle
->linktype
== DLT_EN10MB
&&
3719 (strncmp("isdn", device
, 4) == 0 ||
3720 strncmp("isdY", device
, 4) == 0))) {
3722 * Unknown interface type (-1), or a
3723 * device we explicitly chose to run
3724 * in cooked mode (e.g., PPP devices),
3725 * or an ISDN device (whose link-layer
3726 * type we can only determine by using
3727 * APIs that may be different on different
3728 * kernels) - reopen in cooked mode.
3730 if (close(sock_fd
) == -1) {
3731 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3732 PCAP_ERRBUF_SIZE
, errno
, "close");
3735 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
, protocol
);
3736 if (sock_fd
== -1) {
3737 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3738 PCAP_ERRBUF_SIZE
, errno
, "socket");
3739 if (errno
== EPERM
|| errno
== EACCES
) {
3741 * You don't have permission to
3744 return PCAP_ERROR_PERM_DENIED
;
3752 handlep
->cooked
= 1;
3755 * Get rid of any link-layer type list
3756 * we allocated - this only supports cooked
3759 if (handle
->dlt_list
!= NULL
) {
3760 free(handle
->dlt_list
);
3761 handle
->dlt_list
= NULL
;
3762 handle
->dlt_count
= 0;
3763 set_dlt_list_cooked(handle
, sock_fd
);
3766 if (handle
->linktype
== -1) {
3768 * Warn that we're falling back on
3769 * cooked mode; we may want to
3770 * update "map_arphrd_to_dlt()"
3771 * to handle the new type.
3773 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3775 "supported by libpcap - "
3776 "falling back to cooked "
3782 * IrDA capture is not a real "cooked" capture,
3783 * it's IrLAP frames, not IP packets. The
3784 * same applies to LAPD capture.
3786 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3787 handle
->linktype
!= DLT_LINUX_LAPD
&&
3788 handle
->linktype
!= DLT_NETLINK
)
3789 handle
->linktype
= DLT_LINUX_SLL
;
3792 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3794 if (handlep
->ifindex
== -1) {
3799 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3800 handle
->errbuf
, protocol
)) != 1) {
3805 return 0; /* try old mechanism */
3811 if (handle
->opt
.rfmon
) {
3813 * It doesn't support monitor mode.
3816 return PCAP_ERROR_RFMON_NOTSUP
;
3820 * It uses cooked mode.
3822 handlep
->cooked
= 1;
3823 handle
->linktype
= DLT_LINUX_SLL
;
3824 handle
->dlt_list
= NULL
;
3825 handle
->dlt_count
= 0;
3826 set_dlt_list_cooked(handle
, sock_fd
);
3829 * We're not bound to a device.
3830 * For now, we're using this as an indication
3831 * that we can't transmit; stop doing that only
3832 * if we figure out how to transmit in cooked
3835 handlep
->ifindex
= -1;
3839 * Select promiscuous mode on if "promisc" is set.
3841 * Do not turn allmulti mode on if we don't select
3842 * promiscuous mode - on some devices (e.g., Orinoco
3843 * wireless interfaces), allmulti mode isn't supported
3844 * and the driver implements it by turning promiscuous
3845 * mode on, and that screws up the operation of the
3846 * card as a normal networking interface, and on no
3847 * other platform I know of does starting a non-
3848 * promiscuous capture affect which multicast packets
3849 * are received by the interface.
3853 * Hmm, how can we set promiscuous mode on all interfaces?
3854 * I am not sure if that is possible at all. For now, we
3855 * silently ignore attempts to turn promiscuous mode on
3856 * for the "any" device (so you don't have to explicitly
3857 * disable it in programs such as tcpdump).
3860 if (!is_any_device
&& handle
->opt
.promisc
) {
3861 memset(&mr
, 0, sizeof(mr
));
3862 mr
.mr_ifindex
= handlep
->ifindex
;
3863 mr
.mr_type
= PACKET_MR_PROMISC
;
3864 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3865 &mr
, sizeof(mr
)) == -1) {
3866 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
3867 PCAP_ERRBUF_SIZE
, errno
, "setsockopt (PACKET_ADD_MEMBERSHIP)");
3873 /* Enable auxillary data if supported and reserve room for
3874 * reconstructing VLAN headers. */
3875 #ifdef HAVE_PACKET_AUXDATA
3877 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3878 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3879 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3880 errno
, "setsockopt (PACKET_AUXDATA)");
3884 handle
->offset
+= VLAN_TAG_LEN
;
3885 #endif /* HAVE_PACKET_AUXDATA */
3888 * This is a 2.2[.x] or later kernel (we know that
3889 * because we're not using a SOCK_PACKET socket -
3890 * PF_PACKET is supported only in 2.2 and later
3893 * We can safely pass "recvfrom()" a byte count
3894 * based on the snapshot length.
3896 * If we're in cooked mode, make the snapshot length
3897 * large enough to hold a "cooked mode" header plus
3898 * 1 byte of packet data (so we don't pass a byte
3899 * count of 0 to "recvfrom()").
3900 * XXX - we don't know whether this will be DLT_LINUX_SLL
3901 * or DLT_LINUX_SLL2, so make sure it's big enough for
3902 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
3903 * that small is silly anyway.
3905 if (handlep
->cooked
) {
3906 if (handle
->snapshot
< SLL2_HDR_LEN
+ 1)
3907 handle
->snapshot
= SLL2_HDR_LEN
+ 1;
3909 handle
->bufsize
= handle
->snapshot
;
3912 * Set the offset at which to insert VLAN tags.
3913 * That should be the offset of the type field.
3915 switch (handle
->linktype
) {
3919 * The type field is after the destination and source
3922 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3927 * The type field is in the last 2 bytes of the
3928 * DLT_LINUX_SLL header.
3930 handlep
->vlan_offset
= SLL_HDR_LEN
- 2;
3934 handlep
->vlan_offset
= -1; /* unknown */
3938 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3939 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3940 int nsec_tstamps
= 1;
3942 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3943 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3948 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3951 * We've succeeded. Save the socket FD in the pcap structure.
3953 handle
->fd
= sock_fd
;
3955 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3957 * Can we generate special code for VLAN checks?
3958 * (XXX - what if we need the special code but it's not supported
3959 * by the OS? Is that possible?)
3961 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
3962 &bpf_extensions
, &len
) == 0) {
3963 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
3965 * Yes, we can. Request that we do so.
3967 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
3970 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
3973 #else /* HAVE_PF_PACKET_SOCKETS */
3975 "New packet capturing interface not supported by build "
3976 "environment", PCAP_ERRBUF_SIZE
);
3978 #endif /* HAVE_PF_PACKET_SOCKETS */
3981 #ifdef HAVE_PACKET_RING
3983 * Attempt to activate with memory-mapped access.
3985 * On success, returns 1, and sets *status to 0 if there are no warnings
3986 * or to a PCAP_WARNING_ code if there is a warning.
3988 * On failure due to lack of support for memory-mapped capture, returns
3991 * On error, returns -1, and sets *status to the appropriate error code;
3992 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3995 activate_mmap(pcap_t
*handle
, int *status
)
3997 struct pcap_linux
*handlep
= handle
->priv
;
4001 * Attempt to allocate a buffer to hold the contents of one
4002 * packet, for use by the oneshot callback.
4004 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
4005 if (handlep
->oneshot_buffer
== NULL
) {
4006 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4007 errno
, "can't allocate oneshot buffer");
4008 *status
= PCAP_ERROR
;
4012 if (handle
->opt
.buffer_size
== 0) {
4013 /* by default request 2M for the ring buffer */
4014 handle
->opt
.buffer_size
= 2*1024*1024;
4016 ret
= prepare_tpacket_socket(handle
);
4018 free(handlep
->oneshot_buffer
);
4019 *status
= PCAP_ERROR
;
4022 ret
= create_ring(handle
, status
);
4025 * We don't support memory-mapped capture; our caller
4026 * will fall back on reading from the socket.
4028 free(handlep
->oneshot_buffer
);
4033 * Error attempting to enable memory-mapped capture;
4034 * fail. create_ring() has set *status.
4036 free(handlep
->oneshot_buffer
);
4041 * Success. *status has been set either to 0 if there are no
4042 * warnings or to a PCAP_WARNING_ value if there is a warning.
4044 * Override some defaults and inherit the other fields from
4046 * handle->offset is used to get the current position into the rx ring.
4047 * handle->cc is used to store the ring size.
4050 switch (handlep
->tp_version
) {
4052 handle
->read_op
= pcap_read_linux_mmap_v1
;
4055 handle
->read_op
= pcap_read_linux_mmap_v1_64
;
4057 #ifdef HAVE_TPACKET2
4059 handle
->read_op
= pcap_read_linux_mmap_v2
;
4062 #ifdef HAVE_TPACKET3
4064 handle
->read_op
= pcap_read_linux_mmap_v3
;
4068 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
4069 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
4070 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
4071 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
4072 handle
->oneshot_callback
= pcap_oneshot_mmap
;
4073 handle
->selectable_fd
= handle
->fd
;
4076 #else /* HAVE_PACKET_RING */
4078 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
4082 #endif /* HAVE_PACKET_RING */
4084 #ifdef HAVE_PACKET_RING
4086 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4088 * Attempt to set the socket to the specified version of the memory-mapped
4091 * Return 0 if we succeed; return 1 if we fail because that version isn't
4092 * supported; return -1 on any other error, and set handle->errbuf.
4095 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
4097 struct pcap_linux
*handlep
= handle
->priv
;
4099 socklen_t len
= sizeof(val
);
4102 * Probe whether kernel supports the specified TPACKET version;
4103 * this also gets the length of the header for that version.
4105 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
4106 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
)
4109 /* Failed to even find out; this is a fatal error. */
4110 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4111 errno
, "can't get %s header len on packet socket",
4115 handlep
->tp_hdrlen
= val
;
4118 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
4120 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4121 errno
, "can't activate %s on packet socket", version_str
);
4124 handlep
->tp_version
= version
;
4126 /* Reserve space for VLAN tag reconstruction */
4128 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
4130 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4131 errno
, "can't set up reserve on packet socket");
4137 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
4140 * If the instruction set for which we're compiling has both 32-bit
4141 * and 64-bit versions, and Linux support for the 64-bit version
4142 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
4143 * you get from uname() for the 64-bit version. Otherwise, leave
4144 * it undefined. (This includes ARM, which has a 64-bit version,
4145 * but Linux support for it appeared well after TPACKET_V2 support
4146 * did, so there should never be a case where 32-bit ARM code is
4147 * running o a 64-bit kernel that only supports TPACKET_V1.)
4149 * If we've omitted your favorite such architecture, please contribute
4150 * a patch. (No patch is needed for architectures that are 32-bit-only
4151 * or for which Linux has no support for 32-bit userland - or for which,
4152 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
4155 #if defined(__i386__)
4156 #define ISA_64_BIT "x86_64"
4157 #elif defined(__ppc__)
4158 #define ISA_64_BIT "ppc64"
4159 #elif defined(__sparc__)
4160 #define ISA_64_BIT "sparc64"
4161 #elif defined(__s390__)
4162 #define ISA_64_BIT "s390x"
4163 #elif defined(__mips__)
4164 #define ISA_64_BIT "mips64"
4165 #elif defined(__hppa__)
4166 #define ISA_64_BIT "parisc64"
4170 * Attempt to set the socket to version 3 of the memory-mapped header and,
4171 * if that fails because version 3 isn't supported, attempt to fall
4172 * back to version 2. If version 2 isn't supported, just leave it at
4175 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
4176 * supported; return -1 on any other error, and set handle->errbuf.
4179 prepare_tpacket_socket(pcap_t
*handle
)
4181 struct pcap_linux
*handlep
= handle
->priv
;
4182 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4186 #ifdef HAVE_TPACKET3
4188 * Try setting the version to TPACKET_V3.
4190 * The only mode in which buffering is done on PF_PACKET
4191 * sockets, so that packets might not be delivered
4192 * immediately, is TPACKET_V3 mode.
4194 * The buffering cannot be disabled in that mode, so
4195 * if the user has requested immediate mode, we don't
4198 if (!handle
->opt
.immediate
) {
4199 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
4208 * We failed for some reason other than "the
4209 * kernel doesn't support TPACKET_V3".
4214 #endif /* HAVE_TPACKET3 */
4216 #ifdef HAVE_TPACKET2
4218 * Try setting the version to TPACKET_V2.
4220 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
4229 * We failed for some reason other than "the
4230 * kernel doesn't support TPACKET_V2".
4234 #endif /* HAVE_TPACKET2 */
4237 * OK, we're using TPACKET_V1, as that's all the kernel supports.
4239 handlep
->tp_version
= TPACKET_V1
;
4240 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
4244 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
4245 * each other due to platform-dependent data type size differences.
4247 * If we have a 32-bit userland and a 64-bit kernel, use an
4248 * internally-defined TPACKET_V1_64, with which we use a 64-bit
4249 * version of the data structures.
4251 if (sizeof(long) == 4) {
4253 * This is 32-bit code.
4255 struct utsname utsname
;
4257 if (uname(&utsname
) == -1) {
4261 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4262 PCAP_ERRBUF_SIZE
, errno
, "uname failed");
4265 if (strcmp(utsname
.machine
, ISA_64_BIT
) == 0) {
4267 * uname() tells us the machine is 64-bit,
4268 * so we presumably have a 64-bit kernel.
4270 * XXX - this presumes that uname() won't lie
4271 * in 32-bit code and claim that the machine
4272 * has the 32-bit version of the ISA.
4274 handlep
->tp_version
= TPACKET_V1_64
;
4275 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr_64
);
4283 #define MAX(a,b) ((a)>(b)?(a):(b))
4286 * Attempt to set up memory-mapped access.
4288 * On success, returns 1, and sets *status to 0 if there are no warnings
4289 * or to a PCAP_WARNING_ code if there is a warning.
4291 * On failure due to lack of support for memory-mapped capture, returns
4294 * On error, returns -1, and sets *status to the appropriate error code;
4295 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4298 create_ring(pcap_t
*handle
, int *status
)
4300 struct pcap_linux
*handlep
= handle
->priv
;
4301 unsigned i
, j
, frames_per_block
;
4302 #ifdef HAVE_TPACKET3
4304 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
4305 * stuff at the end of a struct tpacket_req3 will be
4306 * ignored, so this is OK even for those sockets.
4308 struct tpacket_req3 req
;
4310 struct tpacket_req req
;
4313 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
4314 unsigned int frame_size
;
4317 * Start out assuming no warnings or errors.
4321 switch (handlep
->tp_version
) {
4325 #ifdef HAVE_TPACKET2
4328 /* Note that with large snapshot length (say 256K, which is
4329 * the default for recent versions of tcpdump, Wireshark,
4330 * TShark, dumpcap or 64K, the value that "-s 0" has given for
4331 * a long time with tcpdump), if we use the snapshot
4332 * length to calculate the frame length, only a few frames
4333 * will be available in the ring even with pretty
4334 * large ring size (and a lot of memory will be unused).
4336 * Ideally, we should choose a frame length based on the
4337 * minimum of the specified snapshot length and the maximum
4338 * packet size. That's not as easy as it sounds; consider,
4339 * for example, an 802.11 interface in monitor mode, where
4340 * the frame would include a radiotap header, where the
4341 * maximum radiotap header length is device-dependent.
4343 * So, for now, we just do this for Ethernet devices, where
4344 * there's no metadata header, and the link-layer header is
4345 * fixed length. We can get the maximum packet size by
4346 * adding 18, the Ethernet header length plus the CRC length
4347 * (just in case we happen to get the CRC in the packet), to
4348 * the MTU of the interface; we fetch the MTU in the hopes
4349 * that it reflects support for jumbo frames. (Even if the
4350 * interface is just being used for passive snooping, the
4351 * driver might set the size of buffers in the receive ring
4352 * based on the MTU, so that the MTU limits the maximum size
4353 * of packets that we can receive.)
4355 * If segmentation/fragmentation or receive offload are
4356 * enabled, we can get reassembled/aggregated packets larger
4357 * than MTU, but bounded to 65535 plus the Ethernet overhead,
4358 * due to kernel and protocol constraints */
4359 frame_size
= handle
->snapshot
;
4360 if (handle
->linktype
== DLT_EN10MB
) {
4361 unsigned int max_frame_len
;
4365 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.device
,
4368 *status
= PCAP_ERROR
;
4371 offload
= iface_get_offload(handle
);
4372 if (offload
== -1) {
4373 *status
= PCAP_ERROR
;
4377 max_frame_len
= MAX(mtu
, 65535);
4379 max_frame_len
= mtu
;
4380 max_frame_len
+= 18;
4382 if (frame_size
> max_frame_len
)
4383 frame_size
= max_frame_len
;
4386 /* NOTE: calculus matching those in tpacket_rcv()
4387 * in linux-2.6/net/packet/af_packet.c
4389 len
= sizeof(sk_type
);
4390 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
4392 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4393 PCAP_ERRBUF_SIZE
, errno
, "getsockopt (SO_TYPE)");
4394 *status
= PCAP_ERROR
;
4397 #ifdef PACKET_RESERVE
4398 len
= sizeof(tp_reserve
);
4399 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4400 &tp_reserve
, &len
) < 0) {
4401 if (errno
!= ENOPROTOOPT
) {
4403 * ENOPROTOOPT means "kernel doesn't support
4404 * PACKET_RESERVE", in which case we fall back
4407 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4408 PCAP_ERRBUF_SIZE
, errno
,
4409 "getsockopt (PACKET_RESERVE)");
4410 *status
= PCAP_ERROR
;
4414 * Older kernel, so we can't use PACKET_RESERVE;
4415 * this means we can't reserver extra space
4416 * for a DLT_LINUX_SLL2 header.
4421 * We can reserve extra space for a DLT_LINUX_SLL2
4424 * XXX - we assume that the kernel is still adding
4425 * 16 bytes of extra space; that happens to
4426 * correspond to SLL_HDR_LEN (whether intentionally
4427 * or not - the kernel code has a raw "16" in
4428 * the expression), so we subtract SLL_HDR_LEN
4429 * from SLL2_HDR_LEN to get the additional space
4432 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
4434 tp_reserve
+= SLL2_HDR_LEN
- SLL_HDR_LEN
;
4435 len
= sizeof(tp_reserve
);
4436 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4437 &tp_reserve
, len
) < 0) {
4438 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4439 PCAP_ERRBUF_SIZE
, errno
,
4440 "setsockopt (PACKET_RESERVE)");
4441 *status
= PCAP_ERROR
;
4447 * Build environment for an older kernel, so we can't
4448 * use PACKET_RESERVE; this means we can't reserve
4449 * extra space for a DLT_LINUX_SLL2 header.
4453 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
4454 /* XXX: in the kernel maclen is calculated from
4455 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4456 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4457 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4458 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4459 * but I see no way to get those sizes in userspace,
4460 * like for instance with an ifreq ioctl();
4461 * the best thing I've found so far is MAX_HEADER in
4462 * the kernel part of linux-2.6/include/linux/netdevice.h
4463 * which goes up to 128+48=176; since pcap-linux.c
4464 * defines a MAX_LINKHEADER_SIZE of 256 which is
4465 * greater than that, let's use it.. maybe is it even
4466 * large enough to directly replace macoff..
4468 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
4469 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
4470 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4471 * of netoff, which contradicts
4472 * linux-2.6/Documentation/networking/packet_mmap.txt
4474 * "- Gap, chosen so that packet data (Start+tp_net)
4475 * aligns to TPACKET_ALIGNMENT=16"
4477 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4478 * "CPUs often take a performance hit
4479 * when accessing unaligned memory locations"
4481 macoff
= netoff
- maclen
;
4482 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
4484 * Round the buffer size up to a multiple of the
4485 * frame size (rather than rounding down, which
4486 * would give a buffer smaller than our caller asked
4487 * for, and possibly give zero frames if the requested
4488 * buffer size is too small for one frame).
4490 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
4493 #ifdef HAVE_TPACKET3
4496 * If we have TPACKET_V3, we have PACKET_RESERVE.
4498 len
= sizeof(tp_reserve
);
4499 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4500 &tp_reserve
, &len
) < 0) {
4502 * Even ENOPROTOOPT is an error - we wouldn't
4503 * be here if the kernel didn't support
4504 * TPACKET_V3, which means it supports
4507 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4508 PCAP_ERRBUF_SIZE
, errno
,
4509 "getsockopt (PACKET_RESERVE)");
4510 *status
= PCAP_ERROR
;
4514 * We can reserve extra space for a DLT_LINUX_SLL2
4517 * XXX - we assume that the kernel is still adding
4518 * 16 bytes of extra space; that happens to
4519 * correspond to SLL_HDR_LEN (whether intentionally
4520 * or not - the kernel code has a raw "16" in
4521 * the expression), so we subtract SLL_HDR_LEN
4522 * from SLL2_HDR_LEN to get the additional space
4525 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
4527 tp_reserve
+= SLL2_HDR_LEN
- SLL_HDR_LEN
;
4528 len
= sizeof(tp_reserve
);
4529 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4530 &tp_reserve
, len
) < 0) {
4531 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4532 PCAP_ERRBUF_SIZE
, errno
,
4533 "setsockopt (PACKET_RESERVE)");
4534 *status
= PCAP_ERROR
;
4538 /* The "frames" for this are actually buffers that
4539 * contain multiple variable-sized frames.
4541 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
4542 * enough room for at least one reasonably-sized packet
4543 * in the "frame". */
4544 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
4546 * Round the buffer size up to a multiple of the
4547 * "frame" size (rather than rounding down, which
4548 * would give a buffer smaller than our caller asked
4549 * for, and possibly give zero "frames" if the requested
4550 * buffer size is too small for one "frame").
4552 req
.tp_frame_nr
= (handle
->opt
.buffer_size
+ req
.tp_frame_size
- 1)/req
.tp_frame_size
;
4556 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4557 "Internal error: unknown TPACKET_ value %u",
4558 handlep
->tp_version
);
4559 *status
= PCAP_ERROR
;
4563 /* compute the minumum block size that will handle this frame.
4564 * The block has to be page size aligned.
4565 * The max block size allowed by the kernel is arch-dependent and
4566 * it's not explicitly checked here. */
4567 req
.tp_block_size
= getpagesize();
4568 while (req
.tp_block_size
< req
.tp_frame_size
)
4569 req
.tp_block_size
<<= 1;
4571 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
4574 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4575 * so we check for PACKET_TIMESTAMP. We check for
4576 * linux/net_tstamp.h just in case a system somehow has
4577 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4580 * SIOCSHWTSTAMP was introduced in the patch that introduced
4581 * linux/net_tstamp.h, so we don't bother checking whether
4582 * SIOCSHWTSTAMP is defined (if your Linux system has
4583 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4584 * Linux system is badly broken).
4586 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4588 * If we were told to do so, ask the kernel and the driver
4589 * to use hardware timestamps.
4591 * Hardware timestamps are only supported with mmapped
4594 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
4595 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
4596 struct hwtstamp_config hwconfig
;
4601 * Ask for hardware time stamps on all packets,
4602 * including transmitted packets.
4604 memset(&hwconfig
, 0, sizeof(hwconfig
));
4605 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
4606 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
4608 memset(&ifr
, 0, sizeof(ifr
));
4609 strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
4610 ifr
.ifr_data
= (void *)&hwconfig
;
4612 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
4617 * Treat this as an error, as the
4618 * user should try to run this
4619 * with the appropriate privileges -
4620 * and, if they can't, shouldn't
4621 * try requesting hardware time stamps.
4623 *status
= PCAP_ERROR_PERM_DENIED
;
4629 * Treat this as a warning, as the
4630 * only way to fix the warning is to
4631 * get an adapter that supports hardware
4632 * time stamps for *all* packets.
4633 * (ERANGE means "we support hardware
4634 * time stamps, but for packets matching
4635 * that particular filter", so it means
4636 * "we don't support hardware time stamps
4637 * for all incoming packets" here.)
4639 * We'll just fall back on the standard
4642 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
4646 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4647 PCAP_ERRBUF_SIZE
, errno
,
4648 "SIOCSHWTSTAMP failed");
4649 *status
= PCAP_ERROR
;
4654 * Well, that worked. Now specify the type of
4655 * hardware time stamp we want for this
4658 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
4660 * Hardware timestamp, synchronized
4661 * with the system clock.
4663 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
4666 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4667 * timestamp, not synchronized with the
4670 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
4672 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
4673 (void *)×ource
, sizeof(timesource
))) {
4674 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4675 PCAP_ERRBUF_SIZE
, errno
,
4676 "can't set PACKET_TIMESTAMP");
4677 *status
= PCAP_ERROR
;
4682 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4684 /* ask the kernel to create the ring */
4686 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
4688 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4689 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
4691 #ifdef HAVE_TPACKET3
4692 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4693 req
.tp_retire_blk_tov
= (handlep
->timeout
>=0)?handlep
->timeout
:0;
4694 /* private data not used */
4695 req
.tp_sizeof_priv
= 0;
4696 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4697 req
.tp_feature_req_word
= 0;
4700 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4701 (void *) &req
, sizeof(req
))) {
4702 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
4704 * Memory failure; try to reduce the requested ring
4707 * We used to reduce this by half -- do 5% instead.
4708 * That may result in more iterations and a longer
4709 * startup, but the user will be much happier with
4710 * the resulting buffer size.
4712 if (req
.tp_frame_nr
< 20)
4713 req
.tp_frame_nr
-= 1;
4715 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
4718 if (errno
== ENOPROTOOPT
) {
4720 * We don't have ring buffer support in this kernel.
4724 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4725 errno
, "can't create rx ring on packet socket");
4726 *status
= PCAP_ERROR
;
4730 /* memory map the rx ring */
4731 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
4732 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
4733 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
4734 if (handlep
->mmapbuf
== MAP_FAILED
) {
4735 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4736 errno
, "can't mmap rx ring");
4738 /* clear the allocated ring on error*/
4739 destroy_ring(handle
);
4740 *status
= PCAP_ERROR
;
4744 /* allocate a ring for each frame header pointer*/
4745 handle
->cc
= req
.tp_frame_nr
;
4746 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
4747 if (!handle
->buffer
) {
4748 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4749 errno
, "can't allocate ring of frame headers");
4751 destroy_ring(handle
);
4752 *status
= PCAP_ERROR
;
4756 /* fill the header ring with proper frame ptr*/
4758 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
4759 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
4760 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
4761 RING_GET_CURRENT_FRAME(handle
) = base
;
4762 base
+= req
.tp_frame_size
;
4766 handle
->bufsize
= req
.tp_frame_size
;
4771 /* free all ring related resources*/
4773 destroy_ring(pcap_t
*handle
)
4775 struct pcap_linux
*handlep
= handle
->priv
;
4777 /* tell the kernel to destroy the ring*/
4778 struct tpacket_req req
;
4779 memset(&req
, 0, sizeof(req
));
4780 /* do not test for setsockopt failure, as we can't recover from any error */
4781 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4782 (void *) &req
, sizeof(req
));
4784 /* if ring is mapped, unmap it*/
4785 if (handlep
->mmapbuf
) {
4786 /* do not test for mmap failure, as we can't recover from any error */
4787 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
4788 handlep
->mmapbuf
= NULL
;
4793 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4794 * for Linux mmapped capture.
4796 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4797 * data handed to the callback to be valid after the callback returns,
4798 * but pcap_read_linux_mmap() has to release that packet as soon as
4799 * the callback returns (otherwise, the kernel thinks there's still
4800 * at least one unprocessed packet available in the ring, so a select()
4801 * will immediately return indicating that there's data to process), so,
4802 * in the callback, we have to make a copy of the packet.
4804 * Yes, this means that, if the capture is using the ring buffer, using
4805 * pcap_next() or pcap_next_ex() requires more copies than using
4806 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4807 * pcap_next() or pcap_next_ex().
4810 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
4811 const u_char
*bytes
)
4813 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
4814 pcap_t
*handle
= sp
->pd
;
4815 struct pcap_linux
*handlep
= handle
->priv
;
4818 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
4819 *sp
->pkt
= handlep
->oneshot_buffer
;
4823 pcap_cleanup_linux_mmap( pcap_t
*handle
)
4825 struct pcap_linux
*handlep
= handle
->priv
;
4827 destroy_ring(handle
);
4828 if (handlep
->oneshot_buffer
!= NULL
) {
4829 free(handlep
->oneshot_buffer
);
4830 handlep
->oneshot_buffer
= NULL
;
4832 pcap_cleanup_linux(handle
);
4837 pcap_getnonblock_mmap(pcap_t
*handle
)
4839 struct pcap_linux
*handlep
= handle
->priv
;
4841 /* use negative value of timeout to indicate non blocking ops */
4842 return (handlep
->timeout
<0);
4846 pcap_setnonblock_mmap(pcap_t
*handle
, int nonblock
)
4848 struct pcap_linux
*handlep
= handle
->priv
;
4851 * Set the file descriptor to non-blocking mode, as we use
4852 * it for sending packets.
4854 if (pcap_setnonblock_fd(handle
, nonblock
) == -1)
4858 * Map each value to their corresponding negation to
4859 * preserve the timeout value provided with pcap_set_timeout.
4862 if (handlep
->timeout
>= 0) {
4864 * Indicate that we're switching to
4865 * non-blocking mode.
4867 handlep
->timeout
= ~handlep
->timeout
;
4870 if (handlep
->timeout
< 0) {
4871 handlep
->timeout
= ~handlep
->timeout
;
4874 /* Update the timeout to use in poll(). */
4875 set_poll_timeout(handlep
);
4880 * Get the status field of the ring buffer frame at a specified offset.
4883 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
4885 struct pcap_linux
*handlep
= handle
->priv
;
4888 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
4889 switch (handlep
->tp_version
) {
4891 return (h
.h1
->tp_status
);
4894 return (h
.h1_64
->tp_status
);
4896 #ifdef HAVE_TPACKET2
4898 return (h
.h2
->tp_status
);
4901 #ifdef HAVE_TPACKET3
4903 return (h
.h3
->hdr
.bh1
.block_status
);
4907 /* This should not happen. */
4916 * Block waiting for frames to be available.
4918 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4920 struct pcap_linux
*handlep
= handle
->priv
;
4922 struct pollfd pollinfo
;
4925 pollinfo
.fd
= handle
->fd
;
4926 pollinfo
.events
= POLLIN
;
4930 * Yes, we do this even in non-blocking mode, as it's
4931 * the only way to get error indications from a
4934 * The timeout is 0 in non-blocking mode, so poll()
4935 * returns immediately.
4937 ret
= poll(&pollinfo
, 1, handlep
->poll_timeout
);
4938 if (ret
< 0 && errno
!= EINTR
) {
4939 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4940 PCAP_ERRBUF_SIZE
, errno
,
4941 "can't poll on packet socket");
4943 } else if (ret
> 0 &&
4944 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4946 * There's some indication other than
4947 * "you can read on this descriptor" on
4950 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
4951 pcap_snprintf(handle
->errbuf
,
4953 "Hangup on packet socket");
4956 if (pollinfo
.revents
& POLLERR
) {
4958 * A recv() will give us the actual error code.
4960 * XXX - make the socket non-blocking?
4962 if (recv(handle
->fd
, &c
, sizeof c
,
4964 continue; /* what, no error? */
4965 if (errno
== ENETDOWN
) {
4967 * The device on which we're
4968 * capturing went away.
4970 * XXX - we should really return
4971 * PCAP_ERROR_IFACE_NOT_UP, but
4972 * pcap_dispatch() etc. aren't
4973 * defined to return that.
4975 pcap_snprintf(handle
->errbuf
,
4977 "The interface went down");
4979 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
4980 PCAP_ERRBUF_SIZE
, errno
,
4981 "Error condition on packet socket");
4985 if (pollinfo
.revents
& POLLNVAL
) {
4986 pcap_snprintf(handle
->errbuf
,
4988 "Invalid polling request on packet socket");
4992 /* check for break loop condition on interrupted syscall*/
4993 if (handle
->break_loop
) {
4994 handle
->break_loop
= 0;
4995 return PCAP_ERROR_BREAK
;
5001 /* handle a single memory mapped packet */
5002 static int pcap_handle_packet_mmap(
5004 pcap_handler callback
,
5006 unsigned char *frame
,
5007 unsigned int tp_len
,
5008 unsigned int tp_mac
,
5009 unsigned int tp_snaplen
,
5010 unsigned int tp_sec
,
5011 unsigned int tp_usec
,
5012 int tp_vlan_tci_valid
,
5016 struct pcap_linux
*handlep
= handle
->priv
;
5018 struct sockaddr_ll
*sll
;
5019 struct pcap_pkthdr pcaphdr
;
5020 unsigned int snaplen
= tp_snaplen
;
5022 /* perform sanity check on internal offset. */
5023 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
5024 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5025 "corrupted frame on kernel ring mac "
5026 "offset %u + caplen %u > frame len %d",
5027 tp_mac
, tp_snaplen
, handle
->bufsize
);
5031 /* run filter on received packet
5032 * If the kernel filtering is enabled we need to run the
5033 * filter until all the frames present into the ring
5034 * at filter creation time are processed.
5035 * In this case, blocks_to_filter_in_userland is used
5036 * as a counter for the packet we need to filter.
5037 * Note: alternatively it could be possible to stop applying
5038 * the filter when the ring became empty, but it can possibly
5039 * happen a lot later... */
5040 bp
= frame
+ tp_mac
;
5042 /* if required build in place the sll header*/
5043 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
5044 if (handlep
->cooked
) {
5045 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5046 struct sll2_header
*hdrp
;
5049 * The kernel should have left us with enough
5050 * space for an sll header; back up the packet
5051 * data pointer into that space, as that'll be
5052 * the beginning of the packet we pass to the
5058 * Let's make sure that's past the end of
5059 * the tpacket header, i.e. >=
5060 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5061 * don't step on the header when we construct
5064 if (bp
< (u_char
*)frame
+
5065 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
5066 sizeof(struct sockaddr_ll
)) {
5067 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5068 "cooked-mode frame doesn't have room for sll header");
5073 * OK, that worked; construct the sll header.
5075 hdrp
= (struct sll2_header
*)bp
;
5076 hdrp
->sll2_protocol
= sll
->sll_protocol
;
5077 hdrp
->sll2_reserved_mbz
= 0;
5078 hdrp
->sll2_if_index
= htonl(sll
->sll_ifindex
);
5079 hdrp
->sll2_hatype
= htons(sll
->sll_hatype
);
5080 hdrp
->sll2_pkttype
= sll
->sll_pkttype
;
5081 hdrp
->sll2_halen
= sll
->sll_halen
;
5082 memcpy(hdrp
->sll2_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
5084 snaplen
+= sizeof(struct sll2_header
);
5086 struct sll_header
*hdrp
;
5089 * The kernel should have left us with enough
5090 * space for an sll header; back up the packet
5091 * data pointer into that space, as that'll be
5092 * the beginning of the packet we pass to the
5098 * Let's make sure that's past the end of
5099 * the tpacket header, i.e. >=
5100 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5101 * don't step on the header when we construct
5104 if (bp
< (u_char
*)frame
+
5105 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
5106 sizeof(struct sockaddr_ll
)) {
5107 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5108 "cooked-mode frame doesn't have room for sll header");
5113 * OK, that worked; construct the sll header.
5115 hdrp
= (struct sll_header
*)bp
;
5116 hdrp
->sll_pkttype
= htons(sll
->sll_pkttype
);
5117 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
5118 hdrp
->sll_halen
= htons(sll
->sll_halen
);
5119 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
5120 hdrp
->sll_protocol
= sll
->sll_protocol
;
5122 snaplen
+= sizeof(struct sll_header
);
5126 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
5127 struct bpf_aux_data aux_data
;
5129 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
5130 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
5132 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
,
5140 if (!linux_check_direction(handle
, sll
))
5143 /* get required packet info from ring header */
5144 pcaphdr
.ts
.tv_sec
= tp_sec
;
5145 pcaphdr
.ts
.tv_usec
= tp_usec
;
5146 pcaphdr
.caplen
= tp_snaplen
;
5147 pcaphdr
.len
= tp_len
;
5149 /* if required build in place the sll header*/
5150 if (handlep
->cooked
) {
5151 /* update packet len */
5152 if (handle
->linktype
== DLT_LINUX_SLL2
) {
5153 pcaphdr
.caplen
+= SLL2_HDR_LEN
;
5154 pcaphdr
.len
+= SLL2_HDR_LEN
;
5156 pcaphdr
.caplen
+= SLL_HDR_LEN
;
5157 pcaphdr
.len
+= SLL_HDR_LEN
;
5161 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
5162 if (tp_vlan_tci_valid
&&
5163 handlep
->vlan_offset
!= -1 &&
5164 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
5166 struct vlan_tag
*tag
;
5169 * Move everything in the header, except the type field,
5170 * down VLAN_TAG_LEN bytes, to allow us to insert the
5171 * VLAN tag between that stuff and the type field.
5174 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
5177 * Now insert the tag.
5179 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
5180 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
5181 tag
->vlan_tci
= htons(tp_vlan_tci
);
5184 * Add the tag to the packet lengths.
5186 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
5187 pcaphdr
.len
+= VLAN_TAG_LEN
;
5192 * The only way to tell the kernel to cut off the
5193 * packet at a snapshot length is with a filter program;
5194 * if there's no filter program, the kernel won't cut
5197 * Trim the snapshot length to be no longer than the
5198 * specified snapshot length.
5200 if (pcaphdr
.caplen
> (bpf_u_int32
)handle
->snapshot
)
5201 pcaphdr
.caplen
= handle
->snapshot
;
5203 /* pass the packet to the user */
5204 callback(user
, &pcaphdr
, bp
);
5210 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5213 struct pcap_linux
*handlep
= handle
->priv
;
5218 /* wait for frames availability.*/
5219 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5220 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
) {
5222 * The current frame is owned by the kernel; wait for
5223 * a frame to be handed to us.
5225 ret
= pcap_wait_for_frames_mmap(handle
);
5231 /* non-positive values of max_packets are used to require all
5232 * packets currently available in the ring */
5233 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5235 * Get the current ring buffer frame, and break if
5236 * it's still owned by the kernel.
5238 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5239 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
)
5242 ret
= pcap_handle_packet_mmap(
5257 handlep
->packets_read
++;
5258 } else if (ret
< 0) {
5263 * Hand this block back to the kernel, and, if we're
5264 * counting blocks that need to be filtered in userland
5265 * after having been filtered by the kernel, count
5266 * the one we've just processed.
5268 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
5269 if (handlep
->blocks_to_filter_in_userland
> 0) {
5270 handlep
->blocks_to_filter_in_userland
--;
5271 if (handlep
->blocks_to_filter_in_userland
== 0) {
5273 * No more blocks need to be filtered
5276 handlep
->filter_in_userland
= 0;
5281 if (++handle
->offset
>= handle
->cc
)
5284 /* check for break loop condition*/
5285 if (handle
->break_loop
) {
5286 handle
->break_loop
= 0;
5287 return PCAP_ERROR_BREAK
;
5294 pcap_read_linux_mmap_v1_64(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5297 struct pcap_linux
*handlep
= handle
->priv
;
5302 /* wait for frames availability.*/
5303 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5304 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
) {
5306 * The current frame is owned by the kernel; wait for
5307 * a frame to be handed to us.
5309 ret
= pcap_wait_for_frames_mmap(handle
);
5315 /* non-positive values of max_packets are used to require all
5316 * packets currently available in the ring */
5317 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5319 * Get the current ring buffer frame, and break if
5320 * it's still owned by the kernel.
5322 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5323 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
)
5326 ret
= pcap_handle_packet_mmap(
5333 h
.h1_64
->tp_snaplen
,
5341 handlep
->packets_read
++;
5342 } else if (ret
< 0) {
5347 * Hand this block back to the kernel, and, if we're
5348 * counting blocks that need to be filtered in userland
5349 * after having been filtered by the kernel, count
5350 * the one we've just processed.
5352 h
.h1_64
->tp_status
= TP_STATUS_KERNEL
;
5353 if (handlep
->blocks_to_filter_in_userland
> 0) {
5354 handlep
->blocks_to_filter_in_userland
--;
5355 if (handlep
->blocks_to_filter_in_userland
== 0) {
5357 * No more blocks need to be filtered
5360 handlep
->filter_in_userland
= 0;
5365 if (++handle
->offset
>= handle
->cc
)
5368 /* check for break loop condition*/
5369 if (handle
->break_loop
) {
5370 handle
->break_loop
= 0;
5371 return PCAP_ERROR_BREAK
;
5377 #ifdef HAVE_TPACKET2
5379 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5382 struct pcap_linux
*handlep
= handle
->priv
;
5387 /* wait for frames availability.*/
5388 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5389 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
) {
5391 * The current frame is owned by the kernel; wait for
5392 * a frame to be handed to us.
5394 ret
= pcap_wait_for_frames_mmap(handle
);
5400 /* non-positive values of max_packets are used to require all
5401 * packets currently available in the ring */
5402 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5404 * Get the current ring buffer frame, and break if
5405 * it's still owned by the kernel.
5407 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5408 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
)
5411 ret
= pcap_handle_packet_mmap(
5420 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
5421 VLAN_VALID(h
.h2
, h
.h2
),
5423 VLAN_TPID(h
.h2
, h
.h2
));
5426 handlep
->packets_read
++;
5427 } else if (ret
< 0) {
5432 * Hand this block back to the kernel, and, if we're
5433 * counting blocks that need to be filtered in userland
5434 * after having been filtered by the kernel, count
5435 * the one we've just processed.
5437 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
5438 if (handlep
->blocks_to_filter_in_userland
> 0) {
5439 handlep
->blocks_to_filter_in_userland
--;
5440 if (handlep
->blocks_to_filter_in_userland
== 0) {
5442 * No more blocks need to be filtered
5445 handlep
->filter_in_userland
= 0;
5450 if (++handle
->offset
>= handle
->cc
)
5453 /* check for break loop condition*/
5454 if (handle
->break_loop
) {
5455 handle
->break_loop
= 0;
5456 return PCAP_ERROR_BREAK
;
5461 #endif /* HAVE_TPACKET2 */
5463 #ifdef HAVE_TPACKET3
5465 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
5468 struct pcap_linux
*handlep
= handle
->priv
;
5474 if (handlep
->current_packet
== NULL
) {
5475 /* wait for frames availability.*/
5476 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5477 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
5479 * The current frame is owned by the kernel; wait
5480 * for a frame to be handed to us.
5482 ret
= pcap_wait_for_frames_mmap(handle
);
5488 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5489 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
5490 if (pkts
== 0 && handlep
->timeout
== 0) {
5491 /* Block until we see a packet. */
5497 /* non-positive values of max_packets are used to require all
5498 * packets currently available in the ring */
5499 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
5500 int packets_to_read
;
5502 if (handlep
->current_packet
== NULL
) {
5503 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
5504 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
)
5507 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
5508 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
5510 packets_to_read
= handlep
->packets_left
;
5512 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) &&
5513 packets_to_read
> (max_packets
- pkts
)) {
5515 * We've been given a maximum number of packets
5516 * to process, and there are more packets in
5517 * this buffer than that. Only process enough
5518 * of them to get us up to that maximum.
5520 packets_to_read
= max_packets
- pkts
;
5523 while (packets_to_read
-- && !handle
->break_loop
) {
5524 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
5525 ret
= pcap_handle_packet_mmap(
5529 handlep
->current_packet
,
5532 tp3_hdr
->tp_snaplen
,
5534 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
5535 VLAN_VALID(tp3_hdr
, &tp3_hdr
->hv1
),
5536 tp3_hdr
->hv1
.tp_vlan_tci
,
5537 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
5540 handlep
->packets_read
++;
5541 } else if (ret
< 0) {
5542 handlep
->current_packet
= NULL
;
5545 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
5546 handlep
->packets_left
--;
5549 if (handlep
->packets_left
<= 0) {
5551 * Hand this block back to the kernel, and, if
5552 * we're counting blocks that need to be
5553 * filtered in userland after having been
5554 * filtered by the kernel, count the one we've
5557 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
5558 if (handlep
->blocks_to_filter_in_userland
> 0) {
5559 handlep
->blocks_to_filter_in_userland
--;
5560 if (handlep
->blocks_to_filter_in_userland
== 0) {
5562 * No more blocks need to be filtered
5565 handlep
->filter_in_userland
= 0;
5570 if (++handle
->offset
>= handle
->cc
)
5573 handlep
->current_packet
= NULL
;
5576 /* check for break loop condition*/
5577 if (handle
->break_loop
) {
5578 handle
->break_loop
= 0;
5579 return PCAP_ERROR_BREAK
;
5582 if (pkts
== 0 && handlep
->timeout
== 0) {
5583 /* Block until we see a packet. */
5588 #endif /* HAVE_TPACKET3 */
5591 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
5593 struct pcap_linux
*handlep
= handle
->priv
;
5598 * Don't rewrite "ret" instructions; we don't need to, as
5599 * we're not reading packets with recvmsg(), and we don't
5600 * want to, as, by not rewriting them, the kernel can avoid
5601 * copying extra data.
5603 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
5608 * If we're filtering in userland, there's nothing to do;
5609 * the new filter will be used for the next packet.
5611 if (handlep
->filter_in_userland
)
5615 * We're filtering in the kernel; the packets present in
5616 * all blocks currently in the ring were already filtered
5617 * by the old filter, and so will need to be filtered in
5618 * userland by the new filter.
5620 * Get an upper bound for the number of such blocks; first,
5621 * walk the ring backward and count the free blocks.
5623 offset
= handle
->offset
;
5625 offset
= handle
->cc
- 1;
5626 for (n
=0; n
< handle
->cc
; ++n
) {
5628 offset
= handle
->cc
- 1;
5629 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
5634 * If we found free blocks, decrement the count of free
5635 * blocks by 1, just in case we lost a race with another
5636 * thread of control that was adding a packet while
5637 * we were counting and that had run the filter before
5640 * XXX - could there be more than one block added in
5643 * XXX - is there a way to avoid that race, e.g. somehow
5644 * wait for all packets that passed the old filter to
5645 * be added to the ring?
5651 * Set the count of blocks worth of packets to filter
5652 * in userland to the total number of blocks in the
5653 * ring minus the number of free blocks we found, and
5654 * turn on userland filtering. (The count of blocks
5655 * worth of packets to filter in userland is guaranteed
5656 * not to be zero - n, above, couldn't be set to a
5657 * value > handle->cc, and if it were equal to
5658 * handle->cc, it wouldn't be zero, and thus would
5659 * be decremented to handle->cc - 1.)
5661 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
5662 handlep
->filter_in_userland
= 1;
5666 #endif /* HAVE_PACKET_RING */
5669 #ifdef HAVE_PF_PACKET_SOCKETS
5671 * Return the index of the given device name. Fill ebuf and return
5675 iface_get_id(int fd
, const char *device
, char *ebuf
)
5679 memset(&ifr
, 0, sizeof(ifr
));
5680 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5682 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
5683 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5684 errno
, "SIOCGIFINDEX");
5688 return ifr
.ifr_ifindex
;
5692 * Bind the socket associated with FD to the given device.
5693 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
5694 * or a PCAP_ERROR_ value on a hard error.
5697 iface_bind(int fd
, int ifindex
, char *ebuf
, int protocol
)
5699 struct sockaddr_ll sll
;
5701 socklen_t errlen
= sizeof(err
);
5703 memset(&sll
, 0, sizeof(sll
));
5704 sll
.sll_family
= AF_PACKET
;
5705 sll
.sll_ifindex
= ifindex
;
5706 sll
.sll_protocol
= protocol
;
5708 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
5709 if (errno
== ENETDOWN
) {
5711 * Return a "network down" indication, so that
5712 * the application can report that rather than
5713 * saying we had a mysterious failure and
5714 * suggest that they report a problem to the
5715 * libpcap developers.
5717 return PCAP_ERROR_IFACE_NOT_UP
;
5719 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5725 /* Any pending errors, e.g., network is down? */
5727 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5728 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5729 errno
, "getsockopt (SO_ERROR)");
5733 if (err
== ENETDOWN
) {
5735 * Return a "network down" indication, so that
5736 * the application can report that rather than
5737 * saying we had a mysterious failure and
5738 * suggest that they report a problem to the
5739 * libpcap developers.
5741 return PCAP_ERROR_IFACE_NOT_UP
;
5742 } else if (err
> 0) {
5743 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
5751 #ifdef IW_MODE_MONITOR
5753 * Check whether the device supports the Wireless Extensions.
5754 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5755 * if the device doesn't even exist.
5758 has_wext(int sock_fd
, const char *device
, char *ebuf
)
5762 if (is_bonding_device(sock_fd
, device
))
5763 return 0; /* bonding device, so don't even try */
5765 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5766 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5767 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
5769 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
,
5770 "%s: SIOCGIWNAME", device
);
5771 if (errno
== ENODEV
)
5772 return PCAP_ERROR_NO_SUCH_DEVICE
;
5777 * Per me si va ne la citta dolente,
5778 * Per me si va ne l'etterno dolore,
5780 * Lasciate ogne speranza, voi ch'intrate.
5782 * XXX - airmon-ng does special stuff with the Orinoco driver and the
5798 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5799 * on if it's not already on.
5801 * Returns 1 on success, 0 if we don't support the Wireless Extensions
5802 * on this device, or a PCAP_ERROR_ value if we do support them but
5803 * we weren't able to turn monitor mode on.
5806 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
5809 * XXX - at least some adapters require non-Wireless Extensions
5810 * mechanisms to turn monitor mode on.
5812 * Atheros cards might require that a separate "monitor virtual access
5813 * point" be created, with later versions of the madwifi driver.
5814 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
5815 * monitor -bssid", which apparently spits out a line "athN"
5816 * where "athN" is the monitor mode device. To leave monitor
5817 * mode, it destroys the monitor mode device.
5819 * Some Intel Centrino adapters might require private ioctls to get
5820 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5821 * configure a separate "rtapN" interface to capture in monitor
5822 * mode without preventing the adapter from operating normally.
5823 * (airmon-ng doesn't appear to use that, though.)
5825 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5826 * up, and if all drivers were converted to mac80211 drivers.
5828 * If interface {if} is a mac80211 driver, the file
5829 * /sys/class/net/{if}/phy80211 is a symlink to
5830 * /sys/class/ieee80211/{phydev}, for some {phydev}.
5832 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5833 * least, has a "wmaster0" device and a "wlan0" device; the
5834 * latter is the one with the IP address. Both show up in
5835 * "tcpdump -D" output. Capturing on the wmaster0 device
5836 * captures with 802.11 headers.
5838 * airmon-ng searches through /sys/class/net for devices named
5839 * monN, starting with mon0; as soon as one *doesn't* exist,
5840 * it chooses that as the monitor device name. If the "iw"
5841 * command exists, it does "iw dev {if} interface add {monif}
5842 * type monitor", where {monif} is the monitor device. It
5843 * then (sigh) sleeps .1 second, and then configures the
5844 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
5845 * is a file, it writes {mondev}, without a newline, to that file,
5846 * and again (sigh) sleeps .1 second, and then iwconfig's that
5847 * device into monitor mode and configures it up. Otherwise,
5848 * you can't do monitor mode.
5850 * All these devices are "glued" together by having the
5851 * /sys/class/net/{device}/phy80211 links pointing to the same
5852 * place, so, given a wmaster, wlan, or mon device, you can
5853 * find the other devices by looking for devices with
5854 * the same phy80211 link.
5856 * To turn monitor mode off, delete the monitor interface,
5857 * either with "iw dev {monif} interface del" or by sending
5858 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
5860 * Note: if you try to create a monitor device named "monN", and
5861 * there's already a "monN" device, it fails, as least with
5862 * the netlink interface (which is what iw uses), with a return
5863 * value of -ENFILE. (Return values are negative errnos.) We
5864 * could probably use that to find an unused device.
5866 struct pcap_linux
*handlep
= handle
->priv
;
5869 struct iw_priv_args
*priv
;
5870 monitor_type montype
;
5879 * Does this device *support* the Wireless Extensions?
5881 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
5883 return err
; /* either it doesn't or the device doesn't even exist */
5885 * Start out assuming we have no private extensions to control
5888 montype
= MONITOR_WEXT
;
5892 * Try to get all the Wireless Extensions private ioctls
5893 * supported by this device.
5895 * First, get the size of the buffer we need, by supplying no
5896 * buffer and a length of 0. If the device supports private
5897 * ioctls, it should return E2BIG, with ireq.u.data.length set
5898 * to the length we need. If it doesn't support them, it should
5899 * return EOPNOTSUPP.
5901 memset(&ireq
, 0, sizeof ireq
);
5902 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5903 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5904 ireq
.u
.data
.pointer
= (void *)args
;
5905 ireq
.u
.data
.length
= 0;
5906 ireq
.u
.data
.flags
= 0;
5907 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
5908 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5909 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
5913 if (errno
!= EOPNOTSUPP
) {
5915 * OK, it's not as if there are no private ioctls.
5917 if (errno
!= E2BIG
) {
5921 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5922 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
5927 * OK, try to get the list of private ioctls.
5929 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
5931 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5932 PCAP_ERRBUF_SIZE
, errno
, "malloc");
5935 ireq
.u
.data
.pointer
= (void *)priv
;
5936 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
5937 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
5938 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWPRIV", device
);
5944 * Look for private ioctls to turn monitor mode on or, if
5945 * monitor mode is on, to set the header type.
5947 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
5948 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
5950 * Hostap driver, use this one.
5951 * Set monitor mode first.
5952 * You can set it to 0 to get DLT_IEEE80211,
5953 * 1 to get DLT_PRISM, 2 to get
5954 * DLT_IEEE80211_RADIO_AVS, and, with more
5955 * recent versions of the driver, 3 to get
5956 * DLT_IEEE80211_RADIO.
5958 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5960 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5962 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5964 montype
= MONITOR_HOSTAP
;
5968 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
5970 * Prism54 driver, use this one.
5971 * Set monitor mode first.
5972 * You can set it to 2 to get DLT_IEEE80211
5973 * or 3 or get DLT_PRISM.
5975 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5977 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5979 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5981 montype
= MONITOR_PRISM54
;
5985 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
5987 * RT2570 driver, use this one.
5988 * Do this after turning monitor mode on.
5989 * You can set it to 1 to get DLT_PRISM or 2
5990 * to get DLT_IEEE80211.
5992 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5994 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5996 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5998 montype
= MONITOR_RT2570
;
6002 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
6004 * RT73 driver, use this one.
6005 * Do this after turning monitor mode on.
6006 * Its argument is a *string*; you can
6007 * set it to "1" to get DLT_PRISM or "2"
6008 * to get DLT_IEEE80211.
6010 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
6012 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
6014 montype
= MONITOR_RT73
;
6018 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
6020 * One of the RTL8xxx drivers, use this one.
6021 * It can only be done after monitor mode
6022 * has been turned on. You can set it to 1
6023 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
6025 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6027 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
6029 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
6031 montype
= MONITOR_RTL8XXX
;
6035 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
6037 * RT2500 or RT61 driver, use this one.
6038 * It has one one-byte parameter; set
6039 * u.data.length to 1 and u.data.pointer to
6040 * point to the parameter.
6041 * It doesn't itself turn monitor mode on.
6042 * You can set it to 1 to allow transmitting
6043 * in monitor mode(?) and get DLT_IEEE80211,
6044 * or set it to 0 to disallow transmitting in
6045 * monitor mode(?) and get DLT_PRISM.
6047 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6049 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
6051 montype
= MONITOR_RT2500
;
6055 if (strcmp(priv
[i
].name
, "monitor") == 0) {
6057 * Either ACX100 or hostap, use this one.
6058 * It turns monitor mode on.
6059 * If it takes two arguments, it's ACX100;
6060 * the first argument is 1 for DLT_PRISM
6061 * or 2 for DLT_IEEE80211, and the second
6062 * argument is the channel on which to
6063 * run. If it takes one argument, it's
6064 * HostAP, and the argument is 2 for
6065 * DLT_IEEE80211 and 3 for DLT_PRISM.
6067 * If we see this, we don't quit, as this
6068 * might be a version of the hostap driver
6069 * that also supports "monitor_type".
6071 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
6073 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
6075 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
6078 montype
= MONITOR_PRISM
;
6083 montype
= MONITOR_ACX100
;
6096 * XXX - ipw3945? islism?
6102 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6103 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6104 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
6106 * We probably won't be able to set the mode, either.
6108 return PCAP_ERROR_RFMON_NOTSUP
;
6112 * Is it currently in monitor mode?
6114 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
6116 * Yes. Just leave things as they are.
6117 * We don't offer multiple link-layer types, as
6118 * changing the link-layer type out from under
6119 * somebody else capturing in monitor mode would
6120 * be considered rude.
6125 * No. We have to put the adapter into rfmon mode.
6129 * If we haven't already done so, arrange to have
6130 * "pcap_close_all()" called when we exit.
6132 if (!pcap_do_addexit(handle
)) {
6134 * "atexit()" failed; don't put the interface
6135 * in rfmon mode, just give up.
6137 return PCAP_ERROR_RFMON_NOTSUP
;
6141 * Save the old mode.
6143 handlep
->oldmode
= ireq
.u
.mode
;
6146 * Put the adapter in rfmon mode. How we do this depends
6147 * on whether we have a special private ioctl or not.
6149 if (montype
== MONITOR_PRISM
) {
6151 * We have the "monitor" private ioctl, but none of
6152 * the other private ioctls. Use this, and select
6155 * If it fails, just fall back on SIOCSIWMODE.
6157 memset(&ireq
, 0, sizeof ireq
);
6158 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6159 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6160 ireq
.u
.data
.length
= 1; /* 1 argument */
6161 args
[0] = 3; /* request Prism header */
6162 memcpy(ireq
.u
.name
, args
, sizeof (int));
6163 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
6166 * Note that we have to put the old mode back
6167 * when we close the device.
6169 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
6172 * Add this to the list of pcaps to close
6175 pcap_add_to_pcaps_to_close(handle
);
6181 * Failure. Fall back on SIOCSIWMODE.
6186 * First, take the interface down if it's up; otherwise, we
6189 memset(&ifr
, 0, sizeof(ifr
));
6190 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6191 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6192 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6193 errno
, "%s: Can't get flags", device
);
6197 if (ifr
.ifr_flags
& IFF_UP
) {
6198 oldflags
= ifr
.ifr_flags
;
6199 ifr
.ifr_flags
&= ~IFF_UP
;
6200 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6201 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6202 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6209 * Then turn monitor mode on.
6211 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6212 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6213 ireq
.u
.mode
= IW_MODE_MONITOR
;
6214 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
6216 * Scientist, you've failed.
6217 * Bring the interface back up if we shut it down.
6219 ifr
.ifr_flags
= oldflags
;
6220 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6221 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6222 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6226 return PCAP_ERROR_RFMON_NOTSUP
;
6230 * XXX - airmon-ng does "iwconfig {if} key off" after setting
6231 * monitor mode and setting the channel, and then does
6236 * Now select the appropriate radio header.
6242 * We don't have any private ioctl to set the header.
6246 case MONITOR_HOSTAP
:
6248 * Try to select the radiotap header.
6250 memset(&ireq
, 0, sizeof ireq
);
6251 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6252 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6253 args
[0] = 3; /* request radiotap header */
6254 memcpy(ireq
.u
.name
, args
, sizeof (int));
6255 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
6256 break; /* success */
6259 * That failed. Try to select the AVS header.
6261 memset(&ireq
, 0, sizeof ireq
);
6262 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6263 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6264 args
[0] = 2; /* request AVS header */
6265 memcpy(ireq
.u
.name
, args
, sizeof (int));
6266 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
6267 break; /* success */
6270 * That failed. Try to select the Prism header.
6272 memset(&ireq
, 0, sizeof ireq
);
6273 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6274 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6275 args
[0] = 1; /* request Prism header */
6276 memcpy(ireq
.u
.name
, args
, sizeof (int));
6277 ioctl(sock_fd
, cmd
, &ireq
);
6282 * The private ioctl failed.
6286 case MONITOR_PRISM54
:
6288 * Select the Prism header.
6290 memset(&ireq
, 0, sizeof ireq
);
6291 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6292 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6293 args
[0] = 3; /* request Prism header */
6294 memcpy(ireq
.u
.name
, args
, sizeof (int));
6295 ioctl(sock_fd
, cmd
, &ireq
);
6298 case MONITOR_ACX100
:
6300 * Get the current channel.
6302 memset(&ireq
, 0, sizeof ireq
);
6303 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6304 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6305 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
6306 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6307 PCAP_ERRBUF_SIZE
, errno
, "%s: SIOCGIWFREQ", device
);
6310 channel
= ireq
.u
.freq
.m
;
6313 * Select the Prism header, and set the channel to the
6316 memset(&ireq
, 0, sizeof ireq
);
6317 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6318 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6319 args
[0] = 1; /* request Prism header */
6320 args
[1] = channel
; /* set channel */
6321 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
6322 ioctl(sock_fd
, cmd
, &ireq
);
6325 case MONITOR_RT2500
:
6327 * Disallow transmission - that turns on the
6330 memset(&ireq
, 0, sizeof ireq
);
6331 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6332 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6333 args
[0] = 0; /* disallow transmitting */
6334 memcpy(ireq
.u
.name
, args
, sizeof (int));
6335 ioctl(sock_fd
, cmd
, &ireq
);
6338 case MONITOR_RT2570
:
6340 * Force the Prism header.
6342 memset(&ireq
, 0, sizeof ireq
);
6343 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6344 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6345 args
[0] = 1; /* request Prism header */
6346 memcpy(ireq
.u
.name
, args
, sizeof (int));
6347 ioctl(sock_fd
, cmd
, &ireq
);
6352 * Force the Prism header.
6354 memset(&ireq
, 0, sizeof ireq
);
6355 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6356 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6357 ireq
.u
.data
.length
= 1; /* 1 argument */
6358 ireq
.u
.data
.pointer
= "1";
6359 ireq
.u
.data
.flags
= 0;
6360 ioctl(sock_fd
, cmd
, &ireq
);
6363 case MONITOR_RTL8XXX
:
6365 * Force the Prism header.
6367 memset(&ireq
, 0, sizeof ireq
);
6368 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
6369 sizeof ireq
.ifr_ifrn
.ifrn_name
);
6370 args
[0] = 1; /* request Prism header */
6371 memcpy(ireq
.u
.name
, args
, sizeof (int));
6372 ioctl(sock_fd
, cmd
, &ireq
);
6377 * Now bring the interface back up if we brought it down.
6379 if (oldflags
!= 0) {
6380 ifr
.ifr_flags
= oldflags
;
6381 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6382 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6383 PCAP_ERRBUF_SIZE
, errno
, "%s: Can't set flags",
6387 * At least try to restore the old mode on the
6390 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
6392 * Scientist, you've failed.
6395 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
6396 "Please adjust manually.\n",
6404 * Note that we have to put the old mode back when we
6407 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
6410 * Add this to the list of pcaps to close when we exit.
6412 pcap_add_to_pcaps_to_close(handle
);
6416 #endif /* IW_MODE_MONITOR */
6419 * Try various mechanisms to enter monitor mode.
6422 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
6424 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
6429 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
6431 return ret
; /* error attempting to do so */
6433 return 1; /* success */
6434 #endif /* HAVE_LIBNL */
6436 #ifdef IW_MODE_MONITOR
6437 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
6439 return ret
; /* error attempting to do so */
6441 return 1; /* success */
6442 #endif /* IW_MODE_MONITOR */
6445 * Either none of the mechanisms we know about work or none
6446 * of those mechanisms are available, so we can't do monitor
6452 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
6454 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
6456 static const struct {
6457 int soft_timestamping_val
;
6458 int pcap_tstamp_val
;
6459 } sof_ts_type_map
[3] = {
6460 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
6461 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
6462 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
6464 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
6467 * Set the list of time stamping types to include all types.
6470 iface_set_all_ts_types(pcap_t
*handle
)
6474 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
6475 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
6476 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
6477 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6480 #ifdef ETHTOOL_GET_TS_INFO
6482 * Get a list of time stamping capabilities.
6485 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf
)
6489 struct ethtool_ts_info info
;
6494 * This doesn't apply to the "any" device; you can't say "turn on
6495 * hardware time stamping for all devices that exist now and arrange
6496 * that it be turned on for any device that appears in the future",
6497 * and not all devices even necessarily *support* hardware time
6498 * stamping, so don't report any time stamp types.
6500 if (strcmp(device
, "any") == 0) {
6501 handle
->tstamp_type_list
= NULL
;
6506 * Create a socket from which to fetch time stamping capabilities.
6508 fd
= socket(PF_UNIX
, SOCK_RAW
, 0);
6510 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6511 errno
, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
6515 memset(&ifr
, 0, sizeof(ifr
));
6516 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6517 memset(&info
, 0, sizeof(info
));
6518 info
.cmd
= ETHTOOL_GET_TS_INFO
;
6519 ifr
.ifr_data
= (caddr_t
)&info
;
6520 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
6521 int save_errno
= errno
;
6524 switch (save_errno
) {
6529 * OK, this OS version or driver doesn't support
6530 * asking for the time stamping types, so let's
6531 * just return all the possible types.
6533 iface_set_all_ts_types(handle
);
6538 * OK, no such device.
6539 * The user will find that out when they try to
6540 * activate the device; just return an empty
6541 * list of time stamp types.
6543 handle
->tstamp_type_list
= NULL
;
6550 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6552 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
6560 * Do we support hardware time stamping of *all* packets?
6562 if (!(info
.rx_filters
& (1 << HWTSTAMP_FILTER_ALL
))) {
6564 * No, so don't report any time stamp types.
6566 * XXX - some devices either don't report
6567 * HWTSTAMP_FILTER_ALL when they do support it, or
6568 * report HWTSTAMP_FILTER_ALL but map it to only
6569 * time stamping a few PTP packets. See
6570 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
6572 handle
->tstamp_type_list
= NULL
;
6577 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6578 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
6581 handle
->tstamp_type_count
= num_ts_types
;
6582 if (num_ts_types
!= 0) {
6583 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
6584 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6585 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
6586 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6591 handle
->tstamp_type_list
= NULL
;
6595 #else /* ETHTOOL_GET_TS_INFO */
6597 iface_ethtool_get_ts_info(const char *device
, pcap_t
*handle
, char *ebuf _U_
)
6600 * This doesn't apply to the "any" device; you can't say "turn on
6601 * hardware time stamping for all devices that exist now and arrange
6602 * that it be turned on for any device that appears in the future",
6603 * and not all devices even necessarily *support* hardware time
6604 * stamping, so don't report any time stamp types.
6606 if (strcmp(device
, "any") == 0) {
6607 handle
->tstamp_type_list
= NULL
;
6612 * We don't have an ioctl to use to ask what's supported,
6613 * so say we support everything.
6615 iface_set_all_ts_types(handle
);
6618 #endif /* ETHTOOL_GET_TS_INFO */
6620 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6622 #ifdef HAVE_PACKET_RING
6624 * Find out if we have any form of fragmentation/reassembly offloading.
6626 * We do so using SIOCETHTOOL checking for various types of offloading;
6627 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6628 * of the types of offloading, there's nothing we can do to check, so
6629 * we just say "no, we don't".
6631 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6633 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
6636 struct ethtool_value eval
;
6638 memset(&ifr
, 0, sizeof(ifr
));
6639 strlcpy(ifr
.ifr_name
, handle
->opt
.device
, sizeof(ifr
.ifr_name
));
6642 ifr
.ifr_data
= (caddr_t
)&eval
;
6643 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
6644 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
6646 * OK, let's just return 0, which, in our
6647 * case, either means "no, what we're asking
6648 * about is not enabled" or "all the flags
6649 * are clear (i.e., nothing is enabled)".
6653 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6654 errno
, "%s: SIOCETHTOOL(%s) ioctl failed",
6655 handle
->opt
.device
, cmdname
);
6662 iface_get_offload(pcap_t
*handle
)
6667 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
6671 return 1; /* TCP segmentation offloading on */
6675 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
6679 return 1; /* UDP fragmentation offloading on */
6684 * XXX - will this cause large unsegmented packets to be
6685 * handed to PF_PACKET sockets on transmission? If not,
6686 * this need not be checked.
6688 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
6692 return 1; /* generic segmentation offloading on */
6695 #ifdef ETHTOOL_GFLAGS
6696 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
6699 if (ret
& ETH_FLAG_LRO
)
6700 return 1; /* large receive offloading on */
6705 * XXX - will this cause large reassembled packets to be
6706 * handed to PF_PACKET sockets on receipt? If not,
6707 * this need not be checked.
6709 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
6713 return 1; /* generic (large) receive offloading on */
6718 #else /* SIOCETHTOOL */
6720 iface_get_offload(pcap_t
*handle _U_
)
6723 * XXX - do we need to get this information if we don't
6724 * have the ethtool ioctls? If so, how do we do that?
6728 #endif /* SIOCETHTOOL */
6730 #endif /* HAVE_PACKET_RING */
6732 #endif /* HAVE_PF_PACKET_SOCKETS */
6734 /* ===== Functions to interface to the older kernels ================== */
6737 * Try to open a packet socket using the old kernel interface.
6738 * Returns 1 on success and a PCAP_ERROR_ value on an error.
6741 activate_old(pcap_t
*handle
)
6743 struct pcap_linux
*handlep
= handle
->priv
;
6747 const char *device
= handle
->opt
.device
;
6748 struct utsname utsname
;
6751 /* Open the socket */
6753 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
6754 if (handle
->fd
== -1) {
6756 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6758 if (err
== EPERM
|| err
== EACCES
) {
6760 * You don't have permission to open the
6763 return PCAP_ERROR_PERM_DENIED
;
6772 /* It worked - we are using the old interface */
6773 handlep
->sock_packet
= 1;
6775 /* ...which means we get the link-layer header. */
6776 handlep
->cooked
= 0;
6778 /* Bind to the given device */
6780 if (strcmp(device
, "any") == 0) {
6781 strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
6785 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
6789 * Try to get the link-layer type.
6791 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
6796 * Try to find the DLT_ type corresponding to that
6799 map_arphrd_to_dlt(handle
, handle
->fd
, arptype
, device
, 0);
6800 if (handle
->linktype
== -1) {
6801 pcap_snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6802 "unknown arptype %d", arptype
);
6806 /* Go to promisc mode if requested */
6808 if (handle
->opt
.promisc
) {
6809 memset(&ifr
, 0, sizeof(ifr
));
6810 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6811 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6812 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6813 PCAP_ERRBUF_SIZE
, errno
, "SIOCGIFFLAGS");
6816 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
6818 * Promiscuous mode isn't currently on,
6819 * so turn it on, and remember that
6820 * we should turn it off when the
6825 * If we haven't already done so, arrange
6826 * to have "pcap_close_all()" called when
6829 if (!pcap_do_addexit(handle
)) {
6831 * "atexit()" failed; don't put
6832 * the interface in promiscuous
6833 * mode, just give up.
6838 ifr
.ifr_flags
|= IFF_PROMISC
;
6839 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6840 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
6841 PCAP_ERRBUF_SIZE
, errno
, "SIOCSIFFLAGS");
6844 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
6847 * Add this to the list of pcaps
6848 * to close when we exit.
6850 pcap_add_to_pcaps_to_close(handle
);
6855 * Compute the buffer size.
6857 * We're using SOCK_PACKET, so this might be a 2.0[.x]
6858 * kernel, and might require special handling - check.
6860 if (uname(&utsname
) < 0 ||
6861 strncmp(utsname
.release
, "2.0", 3) == 0) {
6863 * Either we couldn't find out what kernel release
6864 * this is, or it's a 2.0[.x] kernel.
6866 * In the 2.0[.x] kernel, a "recvfrom()" on
6867 * a SOCK_PACKET socket, with MSG_TRUNC set, will
6868 * return the number of bytes read, so if we pass
6869 * a length based on the snapshot length, it'll
6870 * return the number of bytes from the packet
6871 * copied to userland, not the actual length
6874 * This means that, for example, the IP dissector
6875 * in tcpdump will get handed a packet length less
6876 * than the length in the IP header, and will
6877 * complain about "truncated-ip".
6879 * So we don't bother trying to copy from the
6880 * kernel only the bytes in which we're interested,
6881 * but instead copy them all, just as the older
6882 * versions of libpcap for Linux did.
6884 * The buffer therefore needs to be big enough to
6885 * hold the largest packet we can get from this
6886 * device. Unfortunately, we can't get the MRU
6887 * of the network; we can only get the MTU. The
6888 * MTU may be too small, in which case a packet larger
6889 * than the buffer size will be truncated *and* we
6890 * won't get the actual packet size.
6892 * However, if the snapshot length is larger than
6893 * the buffer size based on the MTU, we use the
6894 * snapshot length as the buffer size, instead;
6895 * this means that with a sufficiently large snapshot
6896 * length we won't artificially truncate packets
6897 * to the MTU-based size.
6899 * This mess just one of many problems with packet
6900 * capture on 2.0[.x] kernels; you really want a
6901 * 2.2[.x] or later kernel if you want packet capture
6904 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
6907 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
6908 if (handle
->bufsize
< (u_int
)handle
->snapshot
)
6909 handle
->bufsize
= (u_int
)handle
->snapshot
;
6912 * This is a 2.2[.x] or later kernel.
6914 * We can safely pass "recvfrom()" a byte count
6915 * based on the snapshot length.
6917 handle
->bufsize
= (u_int
)handle
->snapshot
;
6921 * Default value for offset to align link-layer payload
6922 * on a 4-byte boundary.
6927 * SOCK_PACKET sockets don't supply information from
6928 * stripped VLAN tags.
6930 handlep
->vlan_offset
= -1; /* unknown */
6936 * Bind the socket associated with FD to the given device using the
6937 * interface of the old kernels.
6940 iface_bind_old(int fd
, const char *device
, char *ebuf
)
6942 struct sockaddr saddr
;
6944 socklen_t errlen
= sizeof(err
);
6946 memset(&saddr
, 0, sizeof(saddr
));
6947 strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
6948 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
6949 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6954 /* Any pending errors, e.g., network is down? */
6956 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
6957 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6958 errno
, "getsockopt (SO_ERROR)");
6963 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6972 /* ===== System calls available on all supported kernels ============== */
6975 * Query the kernel for the MTU of the given interface.
6978 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
6983 return BIGGER_THAN_ALL_MTUS
;
6985 memset(&ifr
, 0, sizeof(ifr
));
6986 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6988 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
6989 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
6990 errno
, "SIOCGIFMTU");
6998 * Get the hardware type of the given interface as ARPHRD_xxx constant.
7001 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
7005 memset(&ifr
, 0, sizeof(ifr
));
7006 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
7008 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
7009 pcap_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
7010 errno
, "SIOCGIFHWADDR");
7011 if (errno
== ENODEV
) {
7015 return PCAP_ERROR_NO_SUCH_DEVICE
;
7020 return ifr
.ifr_hwaddr
.sa_family
;
7023 #ifdef SO_ATTACH_FILTER
7025 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
7027 struct pcap_linux
*handlep
= handle
->priv
;
7030 register struct bpf_insn
*p
;
7035 * Make a copy of the filter, and modify that copy if
7038 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
7039 len
= handle
->fcode
.bf_len
;
7040 f
= (struct bpf_insn
*)malloc(prog_size
);
7042 pcap_fmt_errmsg_for_errno(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
7046 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
7048 fcode
->filter
= (struct sock_filter
*) f
;
7050 for (i
= 0; i
< len
; ++i
) {
7053 * What type of instruction is this?
7055 switch (BPF_CLASS(p
->code
)) {
7059 * It's a return instruction; are we capturing
7060 * in memory-mapped mode?
7064 * No; is the snapshot length a constant,
7065 * rather than the contents of the
7068 if (BPF_MODE(p
->code
) == BPF_K
) {
7070 * Yes - if the value to be returned,
7071 * i.e. the snapshot length, is
7072 * anything other than 0, make it
7073 * MAXIMUM_SNAPLEN, so that the packet
7074 * is truncated by "recvfrom()",
7075 * not by the filter.
7077 * XXX - there's nothing we can
7078 * easily do if it's getting the
7079 * value from the accumulator; we'd
7080 * have to insert code to force
7081 * non-zero values to be
7085 p
->k
= MAXIMUM_SNAPLEN
;
7093 * It's a load instruction; is it loading
7096 switch (BPF_MODE(p
->code
)) {
7102 * Yes; are we in cooked mode?
7104 if (handlep
->cooked
) {
7106 * Yes, so we need to fix this
7109 if (fix_offset(handle
, p
) < 0) {
7111 * We failed to do so.
7112 * Return 0, so our caller
7113 * knows to punt to userland.
7123 return 1; /* we succeeded */
7127 fix_offset(pcap_t
*handle
, struct bpf_insn
*p
)
7129 if (handle
->linktype
== DLT_LINUX_SLL2
) {
7131 * What's the offset?
7133 if (p
->k
>= SLL2_HDR_LEN
) {
7135 * It's within the link-layer payload; that starts
7136 * at an offset of 0, as far as the kernel packet
7137 * filter is concerned, so subtract the length of
7138 * the link-layer header.
7140 p
->k
-= SLL2_HDR_LEN
;
7141 } else if (p
->k
== 0) {
7143 * It's the protocol field; map it to the
7144 * special magic kernel offset for that field.
7146 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
7147 } else if (p
->k
== 10) {
7149 * It's the packet type field; map it to the
7150 * special magic kernel offset for that field.
7152 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
7153 } else if ((bpf_int32
)(p
->k
) > 0) {
7155 * It's within the header, but it's not one of
7156 * those fields; we can't do that in the kernel,
7157 * so punt to userland.
7163 * What's the offset?
7165 if (p
->k
>= SLL_HDR_LEN
) {
7167 * It's within the link-layer payload; that starts
7168 * at an offset of 0, as far as the kernel packet
7169 * filter is concerned, so subtract the length of
7170 * the link-layer header.
7172 p
->k
-= SLL_HDR_LEN
;
7173 } else if (p
->k
== 0) {
7175 * It's the packet type field; map it to the
7176 * special magic kernel offset for that field.
7178 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
7179 } else if (p
->k
== 14) {
7181 * It's the protocol field; map it to the
7182 * special magic kernel offset for that field.
7184 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
7185 } else if ((bpf_int32
)(p
->k
) > 0) {
7187 * It's within the header, but it's not one of
7188 * those fields; we can't do that in the kernel,
7189 * so punt to userland.
7198 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
7200 int total_filter_on
= 0;
7206 * The socket filter code doesn't discard all packets queued
7207 * up on the socket when the filter is changed; this means
7208 * that packets that don't match the new filter may show up
7209 * after the new filter is put onto the socket, if those
7210 * packets haven't yet been read.
7212 * This means, for example, that if you do a tcpdump capture
7213 * with a filter, the first few packets in the capture might
7214 * be packets that wouldn't have passed the filter.
7216 * We therefore discard all packets queued up on the socket
7217 * when setting a kernel filter. (This isn't an issue for
7218 * userland filters, as the userland filtering is done after
7219 * packets are queued up.)
7221 * To flush those packets, we put the socket in read-only mode,
7222 * and read packets from the socket until there are no more to
7225 * In order to keep that from being an infinite loop - i.e.,
7226 * to keep more packets from arriving while we're draining
7227 * the queue - we put the "total filter", which is a filter
7228 * that rejects all packets, onto the socket before draining
7231 * This code deliberately ignores any errors, so that you may
7232 * get bogus packets if an error occurs, rather than having
7233 * the filtering done in userland even if it could have been
7234 * done in the kernel.
7236 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
7237 &total_fcode
, sizeof(total_fcode
)) == 0) {
7241 * Note that we've put the total filter onto the socket.
7243 total_filter_on
= 1;
7246 * Save the socket's current mode, and put it in
7247 * non-blocking mode; we drain it by reading packets
7248 * until we get an error (which is normally a
7249 * "nothing more to be read" error).
7251 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
7252 if (save_mode
== -1) {
7253 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7254 PCAP_ERRBUF_SIZE
, errno
,
7255 "can't get FD flags when changing filter");
7258 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
7259 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7260 PCAP_ERRBUF_SIZE
, errno
,
7261 "can't set nonblocking mode when changing filter");
7264 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
7267 if (save_errno
!= EAGAIN
) {
7271 * If we can't restore the mode or reset the
7272 * kernel filter, there's nothing we can do.
7274 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
7275 (void)reset_kernel_filter(handle
);
7276 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7277 PCAP_ERRBUF_SIZE
, save_errno
,
7278 "recv failed when changing filter");
7281 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
7282 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7283 PCAP_ERRBUF_SIZE
, errno
,
7284 "can't restore FD flags when changing filter");
7290 * Now attach the new filter.
7292 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
7293 fcode
, sizeof(*fcode
));
7294 if (ret
== -1 && total_filter_on
) {
7296 * Well, we couldn't set that filter on the socket,
7297 * but we could set the total filter on the socket.
7299 * This could, for example, mean that the filter was
7300 * too big to put into the kernel, so we'll have to
7301 * filter in userland; in any case, we'll be doing
7302 * filtering in userland, so we need to remove the
7303 * total filter so we see packets.
7308 * If this fails, we're really screwed; we have the
7309 * total filter on the socket, and it won't come off.
7310 * Report it as a fatal error.
7312 if (reset_kernel_filter(handle
) == -1) {
7313 pcap_fmt_errmsg_for_errno(handle
->errbuf
,
7314 PCAP_ERRBUF_SIZE
, errno
,
7315 "can't remove kernel total filter");
7316 return -2; /* fatal error */
7325 reset_kernel_filter(pcap_t
*handle
)
7329 * setsockopt() barfs unless it get a dummy parameter.
7330 * valgrind whines unless the value is initialized,
7331 * as it has no idea that setsockopt() ignores its
7336 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
7337 &dummy
, sizeof(dummy
));
7339 * Ignore ENOENT - it means "we don't have a filter", so there
7340 * was no filter to remove, and there's still no filter.
7342 * Also ignore ENONET, as a lot of kernel versions had a
7343 * typo where ENONET, rather than ENOENT, was returned.
7345 if (ret
== -1 && errno
!= ENOENT
&& errno
!= ENONET
)
7352 pcap_set_protocol_linux(pcap_t
*p
, int protocol
)
7354 if (pcap_check_activated(p
))
7355 return (PCAP_ERROR_ACTIVATED
);
7356 p
->opt
.protocol
= protocol
;
7361 * Libpcap version string.
7364 pcap_lib_version(void)
7366 #ifdef HAVE_PACKET_RING
7367 #if defined(HAVE_TPACKET3)
7368 return (PCAP_VERSION_STRING
" (with TPACKET_V3)");
7369 #elif defined(HAVE_TPACKET2)
7370 return (PCAP_VERSION_STRING
" (with TPACKET_V2)");
7372 return (PCAP_VERSION_STRING
" (with TPACKET_V1)");
7375 return (PCAP_VERSION_STRING
" (without TPACKET)");