1 /* $NetBSD: pcap-linux.c,v 1.3 2015/03/31 21:39:42 christos Exp $ */
4 * pcap-linux.c: Packet capture interface to the Linux kernel
6 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
7 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the
21 * 3. The names of the authors may not be used to endorse or promote
22 * products derived from this software without specific prior
25 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
27 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
29 * Modifications: Added PACKET_MMAP support
30 * Paolo Abeni <paolo.abeni@email.it>
31 * Added TPACKET_V3 support
32 * Gabor Tatarka <gabor.tatarka@ericsson.com>
34 * based on previous works of:
35 * Simon Patarin <patarin@cs.unibo.it>
36 * Phil Wood <cpw@lanl.gov>
38 * Monitor-mode support for mac80211 includes code taken from the iw
39 * command; the copyright notice for that code is
41 * Copyright (c) 2007, 2008 Johannes Berg
42 * Copyright (c) 2007 Andy Lutomirski
43 * Copyright (c) 2007 Mike Kershaw
44 * Copyright (c) 2008 Gábor Stefanik
46 * All rights reserved.
48 * Redistribution and use in source and binary forms, with or without
49 * modification, are permitted provided that the following conditions
51 * 1. Redistributions of source code must retain the above copyright
52 * notice, this list of conditions and the following disclaimer.
53 * 2. Redistributions in binary form must reproduce the above copyright
54 * notice, this list of conditions and the following disclaimer in the
55 * documentation and/or other materials provided with the distribution.
56 * 3. The name of the author may not be used to endorse or promote products
57 * derived from this software without specific prior written permission.
59 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
60 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
61 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
62 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
63 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
64 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
65 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
66 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
67 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * Known problems with 2.0[.x] kernels:
75 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
76 * if we use PF_PACKET, we can filter out the transmitted version
77 * of the packet by using data in the "sockaddr_ll" returned by
78 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
79 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
80 * "sockaddr_pkt" which doesn't give us enough information to let
83 * - We have to set the interface's IFF_PROMISC flag ourselves, if
84 * we're to run in promiscuous mode, which means we have to turn
85 * it off ourselves when we're done; the kernel doesn't keep track
86 * of how many sockets are listening promiscuously, which means
87 * it won't get turned off automatically when no sockets are
88 * listening promiscuously. We catch "pcap_close()" and, for
89 * interfaces we put into promiscuous mode, take them out of
90 * promiscuous mode - which isn't necessarily the right thing to
91 * do, if another socket also requested promiscuous mode between
92 * the time when we opened the socket and the time when we close
95 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
96 * return the amount of data that you could have read, rather than
97 * the amount that was returned, so we can't just allocate a buffer
98 * whose size is the snapshot length and pass the snapshot length
99 * as the byte count, and also pass MSG_TRUNC, so that the return
100 * value tells us how long the packet was on the wire.
102 * This means that, if we want to get the actual size of the packet,
103 * so we can return it in the "len" field of the packet header,
104 * we have to read the entire packet, not just the part that fits
105 * within the snapshot length, and thus waste CPU time copying data
106 * from the kernel that our caller won't see.
108 * We have to get the actual size, and supply it in "len", because
109 * otherwise, the IP dissector in tcpdump, for example, will complain
110 * about "truncated-ip", as the packet will appear to have been
111 * shorter, on the wire, than the IP header said it should have been.
117 #include <sys/cdefs.h>
118 __RCSID("$NetBSD: pcap-linux.c,v 1.3 2015/03/31 21:39:42 christos Exp $");
132 #include <sys/stat.h>
133 #include <sys/socket.h>
134 #include <sys/ioctl.h>
135 #include <sys/utsname.h>
136 #include <sys/mman.h>
137 #include <linux/if.h>
138 #include <linux/if_packet.h>
139 #include <linux/sockios.h>
140 #include <netinet/in.h>
141 #include <linux/if_ether.h>
142 #include <net/if_arp.h>
146 #include "pcap-int.h"
147 #include "pcap/sll.h"
148 #include "pcap/vlan.h"
151 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
152 * sockets rather than SOCK_PACKET sockets.
154 * To use them, we include <linux/if_packet.h> rather than
155 * <netpacket/packet.h>; we do so because
157 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
158 * later kernels and libc5, and don't provide a <netpacket/packet.h>
161 * not all versions of glibc2 have a <netpacket/packet.h> file
162 * that defines stuff needed for some of the 2.4-or-later-kernel
163 * features, so if the system has a 2.4 or later kernel, we
164 * still can't use those features.
166 * We're already including a number of other <linux/XXX.h> headers, and
167 * this code is Linux-specific (no other OS has PF_PACKET sockets as
168 * a raw packet capture mechanism), so it's not as if you gain any
169 * useful portability by using <netpacket/packet.h>
171 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
172 * isn't defined? It only defines one data structure in 2.0.x, so
173 * it shouldn't cause any problems.
176 # include <linux/if_packet.h>
179 * On at least some Linux distributions (for example, Red Hat 5.2),
180 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
181 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
182 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
183 * the PACKET_xxx stuff.
185 * So we check whether PACKET_HOST is defined, and assume that we have
186 * PF_PACKET sockets only if it is defined.
189 # define HAVE_PF_PACKET_SOCKETS
190 # ifdef PACKET_AUXDATA
191 # define HAVE_PACKET_AUXDATA
192 # endif /* PACKET_AUXDATA */
193 # endif /* PACKET_HOST */
196 /* check for memory mapped access avaibility. We assume every needed
197 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
198 * uses many ring related structs and macros */
199 # ifdef PCAP_SUPPORT_PACKET_RING
200 # ifdef TPACKET_HDRLEN
201 # define HAVE_PACKET_RING
202 # ifdef TPACKET3_HDRLEN
203 # define HAVE_TPACKET3
204 # endif /* TPACKET3_HDRLEN */
205 # ifdef TPACKET2_HDRLEN
206 # define HAVE_TPACKET2
207 # else /* TPACKET2_HDRLEN */
208 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
209 # endif /* TPACKET2_HDRLEN */
210 # endif /* TPACKET_HDRLEN */
211 # endif /* PCAP_SUPPORT_PACKET_RING */
212 #endif /* PF_PACKET */
214 #ifdef SO_ATTACH_FILTER
215 #include <linux/types.h>
216 #include <linux/filter.h>
219 #ifdef HAVE_LINUX_NET_TSTAMP_H
220 #include <linux/net_tstamp.h>
224 * Got Wireless Extensions?
226 #ifdef HAVE_LINUX_WIRELESS_H
227 #include <linux/wireless.h>
228 #endif /* HAVE_LINUX_WIRELESS_H */
234 #include <linux/nl80211.h>
236 #include <netlink/genl/genl.h>
237 #include <netlink/genl/family.h>
238 #include <netlink/genl/ctrl.h>
239 #include <netlink/msg.h>
240 #include <netlink/attr.h>
241 #endif /* HAVE_LIBNL */
244 * Got ethtool support?
246 #ifdef HAVE_LINUX_ETHTOOL_H
247 #include <linux/ethtool.h>
250 #ifndef HAVE_SOCKLEN_T
251 typedef int socklen_t
;
256 * This is being compiled on a system that lacks MSG_TRUNC; define it
257 * with the value it has in the 2.2 and later kernels, so that, on
258 * those kernels, when we pass it in the flags argument to "recvfrom()"
259 * we're passing the right value and thus get the MSG_TRUNC behavior
260 * we want. (We don't get that behavior on 2.0[.x] kernels, because
261 * they didn't support MSG_TRUNC.)
263 #define MSG_TRUNC 0x20
268 * This is being compiled on a system that lacks SOL_PACKET; define it
269 * with the value it has in the 2.2 and later kernels, so that we can
270 * set promiscuous mode in the good modern way rather than the old
271 * 2.0-kernel crappy way.
273 #define SOL_PACKET 263
276 #define MAX_LINKHEADER_SIZE 256
279 * When capturing on all interfaces we use this as the buffer size.
280 * Should be bigger then all MTUs that occur in real life.
281 * 64kB should be enough for now.
283 #define BIGGER_THAN_ALL_MTUS (64*1024)
286 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
289 u_int packets_read
; /* count of packets read with recvfrom() */
290 long proc_dropped
; /* packets reported dropped by /proc/net/dev */
291 struct pcap_stat stat
;
293 char *device
; /* device name */
294 int filter_in_userland
; /* must filter in userland */
295 int blocks_to_filter_in_userland
;
296 int must_do_on_close
; /* stuff we must do when we close */
297 int timeout
; /* timeout for buffering */
298 int sock_packet
; /* using Linux 2.0 compatible interface */
299 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
300 int ifindex
; /* interface index of device we're bound to */
301 int lo_ifindex
; /* interface index of the loopback device */
302 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
303 char *mondevice
; /* mac80211 monitor device we created */
304 u_char
*mmapbuf
; /* memory-mapped region pointer */
305 size_t mmapbuflen
; /* size of region */
306 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
307 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
308 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
309 u_char
*oneshot_buffer
; /* buffer for copy of packet */
311 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
312 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
317 * Stuff to do when we close.
319 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
320 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
321 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
324 * Prototypes for internal functions and methods.
326 static void map_arphrd_to_dlt(pcap_t
*, int, int, const char *, int);
327 #ifdef HAVE_PF_PACKET_SOCKETS
328 static short int map_packet_type_to_sll_type(short int);
330 static int pcap_activate_linux(pcap_t
*);
331 static int activate_old(pcap_t
*);
332 static int activate_new(pcap_t
*);
333 static int activate_mmap(pcap_t
*, int *);
334 static int pcap_can_set_rfmon_linux(pcap_t
*);
335 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
336 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
337 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
338 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
339 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
340 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
341 static int pcap_set_datalink_linux(pcap_t
*, int);
342 static void pcap_cleanup_linux(pcap_t
*);
345 * This is what the header structure looks like in a 64-bit kernel;
346 * we use this, rather than struct tpacket_hdr, if we're using
347 * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
349 struct tpacket_hdr_64
{
352 unsigned int tp_snaplen
;
353 unsigned short tp_mac
;
354 unsigned short tp_net
;
356 unsigned int tp_usec
;
360 * We use this internally as the tpacket version for TPACKET_V1 in
361 * 32-bit code on a 64-bit kernel.
363 #define TPACKET_V1_64 99
366 struct tpacket_hdr
*h1
;
367 struct tpacket_hdr_64
*h1_64
;
369 struct tpacket2_hdr
*h2
;
372 struct tpacket_block_desc
*h3
;
377 #ifdef HAVE_PACKET_RING
378 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
380 static void destroy_ring(pcap_t
*handle
);
381 static int create_ring(pcap_t
*handle
, int *status
);
382 static int prepare_tpacket_socket(pcap_t
*handle
);
383 static void pcap_cleanup_linux_mmap(pcap_t
*);
384 static int pcap_read_linux_mmap_v1(pcap_t
*, int, pcap_handler
, u_char
*);
385 static int pcap_read_linux_mmap_v1_64(pcap_t
*, int, pcap_handler
, u_char
*);
387 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
390 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
392 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
393 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
394 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
395 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
396 const u_char
*bytes
);
399 #ifdef TP_STATUS_VLAN_TPID_VALID
400 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
402 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
406 * Wrap some ioctl calls
408 #ifdef HAVE_PF_PACKET_SOCKETS
409 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
410 #endif /* HAVE_PF_PACKET_SOCKETS */
411 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
412 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
413 #ifdef HAVE_PF_PACKET_SOCKETS
414 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
415 #ifdef IW_MODE_MONITOR
416 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
417 #endif /* IW_MODE_MONITOR */
418 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
420 #endif /* HAVE_PF_PACKET_SOCKETS */
421 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
422 static int iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
);
424 #ifdef HAVE_PACKET_RING
425 static int iface_get_offload(pcap_t
*handle
);
427 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
429 #ifdef SO_ATTACH_FILTER
430 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
432 static int fix_offset(struct bpf_insn
*p
);
433 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
434 static int reset_kernel_filter(pcap_t
*handle
);
436 static struct sock_filter total_insn
437 = BPF_STMT(BPF_RET
| BPF_K
, 0);
438 static struct sock_fprog total_fcode
439 = { 1, &total_insn
};
440 #endif /* SO_ATTACH_FILTER */
443 pcap_create_interface(const char *device
, char *ebuf
)
447 handle
= pcap_create_common(device
, ebuf
, sizeof (struct pcap_linux
));
451 handle
->activate_op
= pcap_activate_linux
;
452 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
454 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
456 * See what time stamp types we support.
458 if (iface_ethtool_get_ts_info(handle
, ebuf
) == -1) {
464 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
466 * We claim that we support microsecond and nanosecond time
469 * XXX - with adapter-supplied time stamps, can we choose
470 * microsecond or nanosecond time stamps on arbitrary
473 handle
->tstamp_precision_count
= 2;
474 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
475 if (handle
->tstamp_precision_list
== NULL
) {
476 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
477 pcap_strerror(errno
));
478 if (handle
->tstamp_type_list
!= NULL
)
479 free(handle
->tstamp_type_list
);
483 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
484 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
485 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
492 * If interface {if} is a mac80211 driver, the file
493 * /sys/class/net/{if}/phy80211 is a symlink to
494 * /sys/class/ieee80211/{phydev}, for some {phydev}.
496 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
497 * least, has a "wmaster0" device and a "wlan0" device; the
498 * latter is the one with the IP address. Both show up in
499 * "tcpdump -D" output. Capturing on the wmaster0 device
500 * captures with 802.11 headers.
502 * airmon-ng searches through /sys/class/net for devices named
503 * monN, starting with mon0; as soon as one *doesn't* exist,
504 * it chooses that as the monitor device name. If the "iw"
505 * command exists, it does "iw dev {if} interface add {monif}
506 * type monitor", where {monif} is the monitor device. It
507 * then (sigh) sleeps .1 second, and then configures the
508 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
509 * is a file, it writes {mondev}, without a newline, to that file,
510 * and again (sigh) sleeps .1 second, and then iwconfig's that
511 * device into monitor mode and configures it up. Otherwise,
512 * you can't do monitor mode.
514 * All these devices are "glued" together by having the
515 * /sys/class/net/{device}/phy80211 links pointing to the same
516 * place, so, given a wmaster, wlan, or mon device, you can
517 * find the other devices by looking for devices with
518 * the same phy80211 link.
520 * To turn monitor mode off, delete the monitor interface,
521 * either with "iw dev {monif} interface del" or by sending
522 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
524 * Note: if you try to create a monitor device named "monN", and
525 * there's already a "monN" device, it fails, as least with
526 * the netlink interface (which is what iw uses), with a return
527 * value of -ENFILE. (Return values are negative errnos.) We
528 * could probably use that to find an unused device.
530 * Yes, you can have multiple monitor devices for a given
535 * Is this a mac80211 device? If so, fill in the physical device path and
536 * return 1; if not, return 0. On an error, fill in handle->errbuf and
540 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
541 size_t phydev_max_pathlen
)
547 * Generate the path string for the symlink to the physical device.
549 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
550 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
551 "%s: Can't generate path name string for /sys/class/net device",
555 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
556 if (bytes_read
== -1) {
557 if (errno
== ENOENT
|| errno
== EINVAL
) {
559 * Doesn't exist, or not a symlink; assume that
560 * means it's not a mac80211 device.
565 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
566 "%s: Can't readlink %s: %s", device
, pathstr
,
572 phydev_path
[bytes_read
] = '\0';
576 #ifdef HAVE_LIBNL_SOCKETS
577 #define get_nl_errmsg nl_geterror
579 /* libnl 2.x compatibility code */
581 #define nl_sock nl_handle
583 static inline struct nl_handle
*
584 nl_socket_alloc(void)
586 return nl_handle_alloc();
590 nl_socket_free(struct nl_handle
*h
)
592 nl_handle_destroy(h
);
595 #define get_nl_errmsg strerror
598 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
600 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
606 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
607 #endif /* !HAVE_LIBNL_SOCKETS */
609 struct nl80211_state
{
610 struct nl_sock
*nl_sock
;
611 struct nl_cache
*nl_cache
;
612 struct genl_family
*nl80211
;
616 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
620 state
->nl_sock
= nl_socket_alloc();
621 if (!state
->nl_sock
) {
622 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
623 "%s: failed to allocate netlink handle", device
);
627 if (genl_connect(state
->nl_sock
)) {
628 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
629 "%s: failed to connect to generic netlink", device
);
630 goto out_handle_destroy
;
633 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
635 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
636 "%s: failed to allocate generic netlink cache: %s",
637 device
, get_nl_errmsg(-err
));
638 goto out_handle_destroy
;
641 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
642 if (!state
->nl80211
) {
643 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
644 "%s: nl80211 not found", device
);
651 nl_cache_free(state
->nl_cache
);
653 nl_socket_free(state
->nl_sock
);
658 nl80211_cleanup(struct nl80211_state
*state
)
660 genl_family_put(state
->nl80211
);
661 nl_cache_free(state
->nl_cache
);
662 nl_socket_free(state
->nl_sock
);
666 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
667 const char *device
, const char *mondevice
)
673 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
679 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
680 "%s: failed to allocate netlink msg", device
);
684 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
685 0, NL80211_CMD_NEW_INTERFACE
, 0);
686 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
687 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
688 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
690 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
692 #if defined HAVE_LIBNL_NLE
693 if (err
== -NLE_FAILURE
) {
695 if (err
== -ENFILE
) {
698 * Device not available; our caller should just
699 * keep trying. (libnl 2.x maps ENFILE to
700 * NLE_FAILURE; it can also map other errors
701 * to that, but there's not much we can do
708 * Real failure, not just "that device is not
711 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
712 "%s: nl_send_auto_complete failed adding %s interface: %s",
713 device
, mondevice
, get_nl_errmsg(-err
));
718 err
= nl_wait_for_ack(state
->nl_sock
);
720 #if defined HAVE_LIBNL_NLE
721 if (err
== -NLE_FAILURE
) {
723 if (err
== -ENFILE
) {
726 * Device not available; our caller should just
727 * keep trying. (libnl 2.x maps ENFILE to
728 * NLE_FAILURE; it can also map other errors
729 * to that, but there's not much we can do
736 * Real failure, not just "that device is not
739 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
740 "%s: nl_wait_for_ack failed adding %s interface: %s",
741 device
, mondevice
, get_nl_errmsg(-err
));
754 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
755 "%s: nl_put failed adding %s interface",
762 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
763 const char *device
, const char *mondevice
)
769 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
775 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
776 "%s: failed to allocate netlink msg", device
);
780 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
781 0, NL80211_CMD_DEL_INTERFACE
, 0);
782 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
784 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
786 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
787 "%s: nl_send_auto_complete failed deleting %s interface: %s",
788 device
, mondevice
, get_nl_errmsg(-err
));
792 err
= nl_wait_for_ack(state
->nl_sock
);
794 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
795 "%s: nl_wait_for_ack failed adding %s interface: %s",
796 device
, mondevice
, get_nl_errmsg(-err
));
808 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
809 "%s: nl_put failed deleting %s interface",
816 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
818 struct pcap_linux
*handlep
= handle
->priv
;
820 char phydev_path
[PATH_MAX
+1];
821 struct nl80211_state nlstate
;
826 * Is this a mac80211 device?
828 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
830 return ret
; /* error */
832 return 0; /* no error, but not mac80211 device */
835 * XXX - is this already a monN device?
837 * Is that determined by old Wireless Extensions ioctls?
841 * OK, it's apparently a mac80211 device.
842 * Try to find an unused monN device for it.
844 ret
= nl80211_init(handle
, &nlstate
, device
);
847 for (n
= 0; n
< UINT_MAX
; n
++) {
851 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
853 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
854 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
856 handlep
->mondevice
= strdup(mondevice
);
861 * Hard failure. Just return ret; handle->errbuf
862 * has already been set.
864 nl80211_cleanup(&nlstate
);
869 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
870 "%s: No free monN interfaces", device
);
871 nl80211_cleanup(&nlstate
);
878 * Sleep for .1 seconds.
881 delay
.tv_nsec
= 500000000;
882 nanosleep(&delay
, NULL
);
886 * If we haven't already done so, arrange to have
887 * "pcap_close_all()" called when we exit.
889 if (!pcap_do_addexit(handle
)) {
891 * "atexit()" failed; don't put the interface
892 * in rfmon mode, just give up.
894 return PCAP_ERROR_RFMON_NOTSUP
;
898 * Now configure the monitor interface up.
900 memset(&ifr
, 0, sizeof(ifr
));
901 strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
902 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
903 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
904 "%s: Can't get flags for %s: %s", device
,
905 handlep
->mondevice
, strerror(errno
));
906 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
908 nl80211_cleanup(&nlstate
);
911 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
912 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
913 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
914 "%s: Can't set flags for %s: %s", device
,
915 handlep
->mondevice
, strerror(errno
));
916 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
918 nl80211_cleanup(&nlstate
);
923 * Success. Clean up the libnl state.
925 nl80211_cleanup(&nlstate
);
928 * Note that we have to delete the monitor device when we close
931 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
934 * Add this to the list of pcaps to close when we exit.
936 pcap_add_to_pcaps_to_close(handle
);
940 #endif /* HAVE_LIBNL */
943 pcap_can_set_rfmon_linux(pcap_t
*handle
)
946 char phydev_path
[PATH_MAX
+1];
949 #ifdef IW_MODE_MONITOR
954 if (strcmp(handle
->opt
.source
, "any") == 0) {
956 * Monitor mode makes no sense on the "any" device.
963 * Bleah. There doesn't seem to be a way to ask a mac80211
964 * device, through libnl, whether it supports monitor mode;
965 * we'll just check whether the device appears to be a
966 * mac80211 device and, if so, assume the device supports
969 * wmaster devices don't appear to support the Wireless
970 * Extensions, but we can create a mon device for a
971 * wmaster device, so we don't bother checking whether
972 * a mac80211 device supports the Wireless Extensions.
974 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
977 return ret
; /* error */
979 return 1; /* mac80211 device */
982 #ifdef IW_MODE_MONITOR
984 * Bleah. There doesn't appear to be an ioctl to use to ask
985 * whether a device supports monitor mode; we'll just do
986 * SIOCGIWMODE and, if it succeeds, assume the device supports
989 * Open a socket on which to attempt to get the mode.
990 * (We assume that if we have Wireless Extensions support
991 * we also have PF_PACKET support.)
993 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
995 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
996 "socket: %s", pcap_strerror(errno
));
1001 * Attempt to get the current mode.
1003 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
1004 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1005 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1007 * Well, we got the mode; assume we can set it.
1012 if (errno
== ENODEV
) {
1013 /* The device doesn't even exist. */
1014 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1015 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
1017 return PCAP_ERROR_NO_SUCH_DEVICE
;
1025 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1027 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1028 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1030 * Or can we get them in binary form from netlink?
1033 linux_if_drops(const char * if_name
)
1038 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1039 long int dropped_pkts
= 0;
1041 file
= fopen("/proc/net/dev", "r");
1045 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1047 /* search for 'bytes' -- if its in there, then
1048 that means we need to grab the fourth field. otherwise
1049 grab the third field. */
1050 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1052 field_to_convert
= 4;
1056 /* find iface and make sure it actually matches -- space before the name and : after it */
1057 if ((bufptr
= strstr(buffer
, if_name
)) &&
1058 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1059 *(bufptr
+ if_name_sz
) == ':')
1061 bufptr
= bufptr
+ if_name_sz
+ 1;
1063 /* grab the nth field from it */
1064 while( --field_to_convert
&& *bufptr
!= '\0')
1066 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1067 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1070 /* get rid of any final spaces */
1071 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1073 if (*bufptr
!= '\0')
1074 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1081 return dropped_pkts
;
1086 * With older kernels promiscuous mode is kind of interesting because we
1087 * have to reset the interface before exiting. The problem can't really
1088 * be solved without some daemon taking care of managing usage counts.
1089 * If we put the interface into promiscuous mode, we set a flag indicating
1090 * that we must take it out of that mode when the interface is closed,
1091 * and, when closing the interface, if that flag is set we take it out
1092 * of promiscuous mode.
1094 * Even with newer kernels, we have the same issue with rfmon mode.
1097 static void pcap_cleanup_linux( pcap_t
*handle
)
1099 struct pcap_linux
*handlep
= handle
->priv
;
1102 struct nl80211_state nlstate
;
1104 #endif /* HAVE_LIBNL */
1105 #ifdef IW_MODE_MONITOR
1108 #endif /* IW_MODE_MONITOR */
1110 if (handlep
->must_do_on_close
!= 0) {
1112 * There's something we have to do when closing this
1115 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1117 * We put the interface into promiscuous mode;
1118 * take it out of promiscuous mode.
1120 * XXX - if somebody else wants it in promiscuous
1121 * mode, this code cannot know that, so it'll take
1122 * it out of promiscuous mode. That's not fixable
1123 * in 2.0[.x] kernels.
1125 memset(&ifr
, 0, sizeof(ifr
));
1126 strlcpy(ifr
.ifr_name
, handlep
->device
,
1127 sizeof(ifr
.ifr_name
));
1128 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1130 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1131 "Please adjust manually.\n"
1132 "Hint: This can't happen with Linux >= 2.2.0.\n",
1133 handlep
->device
, strerror(errno
));
1135 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1137 * Promiscuous mode is currently on;
1140 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1141 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1144 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1145 "Please adjust manually.\n"
1146 "Hint: This can't happen with Linux >= 2.2.0.\n",
1155 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1156 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1158 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1159 handlep
->device
, handlep
->mondevice
);
1160 nl80211_cleanup(&nlstate
);
1164 "Can't delete monitor interface %s (%s).\n"
1165 "Please delete manually.\n",
1166 handlep
->mondevice
, handle
->errbuf
);
1169 #endif /* HAVE_LIBNL */
1171 #ifdef IW_MODE_MONITOR
1172 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1174 * We put the interface into rfmon mode;
1175 * take it out of rfmon mode.
1177 * XXX - if somebody else wants it in rfmon
1178 * mode, this code cannot know that, so it'll take
1179 * it out of rfmon mode.
1183 * First, take the interface down if it's up;
1184 * otherwise, we might get EBUSY.
1185 * If we get errors, just drive on and print
1186 * a warning if we can't restore the mode.
1189 memset(&ifr
, 0, sizeof(ifr
));
1190 strlcpy(ifr
.ifr_name
, handlep
->device
,
1191 sizeof(ifr
.ifr_name
));
1192 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1193 if (ifr
.ifr_flags
& IFF_UP
) {
1194 oldflags
= ifr
.ifr_flags
;
1195 ifr
.ifr_flags
&= ~IFF_UP
;
1196 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1197 oldflags
= 0; /* didn't set, don't restore */
1202 * Now restore the mode.
1204 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1205 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1206 ireq
.u
.mode
= handlep
->oldmode
;
1207 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1209 * Scientist, you've failed.
1212 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1213 "Please adjust manually.\n",
1214 handlep
->device
, strerror(errno
));
1218 * Now bring the interface back up if we brought
1221 if (oldflags
!= 0) {
1222 ifr
.ifr_flags
= oldflags
;
1223 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1225 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1226 "Please adjust manually.\n",
1227 handlep
->device
, strerror(errno
));
1231 #endif /* IW_MODE_MONITOR */
1234 * Take this pcap out of the list of pcaps for which we
1235 * have to take the interface out of some mode.
1237 pcap_remove_from_pcaps_to_close(handle
);
1240 if (handlep
->mondevice
!= NULL
) {
1241 free(handlep
->mondevice
);
1242 handlep
->mondevice
= NULL
;
1244 if (handlep
->device
!= NULL
) {
1245 free(handlep
->device
);
1246 handlep
->device
= NULL
;
1248 pcap_cleanup_live_common(handle
);
1252 * Get a handle for a live capture from the given device. You can
1253 * pass NULL as device to get all packages (without link level
1254 * information of course). If you pass 1 as promisc the interface
1255 * will be set to promiscous mode (XXX: I think this usage should
1256 * be deprecated and functions be added to select that later allow
1257 * modification of that values -- Torsten).
1260 pcap_activate_linux(pcap_t
*handle
)
1262 struct pcap_linux
*handlep
= handle
->priv
;
1268 device
= handle
->opt
.source
;
1271 * Make sure the name we were handed will fit into the ioctls we
1272 * might perform on the device; if not, return a "No such device"
1273 * indication, as the Linux kernel shouldn't support creating
1274 * a device whose name won't fit into those ioctls.
1276 * "Will fit" means "will fit, complete with a null terminator",
1277 * so if the length, which does *not* include the null terminator,
1278 * is greater than *or equal to* the size of the field into which
1279 * we'll be copying it, that won't fit.
1281 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1282 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1286 handle
->inject_op
= pcap_inject_linux
;
1287 handle
->setfilter_op
= pcap_setfilter_linux
;
1288 handle
->setdirection_op
= pcap_setdirection_linux
;
1289 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1290 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1291 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1292 handle
->cleanup_op
= pcap_cleanup_linux
;
1293 handle
->read_op
= pcap_read_linux
;
1294 handle
->stats_op
= pcap_stats_linux
;
1297 * The "any" device is a special device which causes us not
1298 * to bind to a particular device and thus to look at all
1301 if (strcmp(device
, "any") == 0) {
1302 if (handle
->opt
.promisc
) {
1303 handle
->opt
.promisc
= 0;
1304 /* Just a warning. */
1305 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1306 "Promiscuous mode not supported on the \"any\" device");
1307 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1311 handlep
->device
= strdup(device
);
1312 if (handlep
->device
== NULL
) {
1313 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1314 pcap_strerror(errno
) );
1318 /* copy timeout value */
1319 handlep
->timeout
= handle
->opt
.timeout
;
1322 * If we're in promiscuous mode, then we probably want
1323 * to see when the interface drops packets too, so get an
1324 * initial count from /proc/net/dev
1326 if (handle
->opt
.promisc
)
1327 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1330 * Current Linux kernels use the protocol family PF_PACKET to
1331 * allow direct access to all packets on the network while
1332 * older kernels had a special socket type SOCK_PACKET to
1333 * implement this feature.
1334 * While this old implementation is kind of obsolete we need
1335 * to be compatible with older kernels for a while so we are
1336 * trying both methods with the newer method preferred.
1338 ret
= activate_new(handle
);
1341 * Fatal error with the new way; just fail.
1342 * ret has the error return; if it's PCAP_ERROR,
1343 * handle->errbuf has been set appropriately.
1351 * Try to use memory-mapped access.
1353 switch (activate_mmap(handle
, &status
)) {
1357 * We succeeded. status has been
1358 * set to the status to return,
1359 * which might be 0, or might be
1360 * a PCAP_WARNING_ value.
1366 * Kernel doesn't support it - just continue
1367 * with non-memory-mapped access.
1373 * We failed to set up to use it, or the kernel
1374 * supports it, but we failed to enable it.
1375 * ret has been set to the error status to
1376 * return and, if it's PCAP_ERROR, handle->errbuf
1377 * contains the error message.
1383 else if (ret
== 0) {
1384 /* Non-fatal error; try old way */
1385 if ((ret
= activate_old(handle
)) != 1) {
1387 * Both methods to open the packet socket failed.
1388 * Tidy up and report our failure (handle->errbuf
1389 * is expected to be set by the functions above).
1397 * We set up the socket, but not with memory-mapped access.
1399 if (handle
->opt
.buffer_size
!= 0) {
1401 * Set the socket buffer size to the specified value.
1403 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1404 &handle
->opt
.buffer_size
,
1405 sizeof(handle
->opt
.buffer_size
)) == -1) {
1406 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1407 "SO_RCVBUF: %s", pcap_strerror(errno
));
1408 status
= PCAP_ERROR
;
1413 /* Allocate the buffer */
1415 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1416 if (!handle
->buffer
) {
1417 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1418 "malloc: %s", pcap_strerror(errno
));
1419 status
= PCAP_ERROR
;
1424 * "handle->fd" is a socket, so "select()" and "poll()"
1425 * should work on it.
1427 handle
->selectable_fd
= handle
->fd
;
1432 pcap_cleanup_linux(handle
);
1437 * Read at most max_packets from the capture stream and call the callback
1438 * for each of them. Returns the number of packets handled or -1 if an
1442 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1445 * Currently, on Linux only one packet is delivered per read,
1448 return pcap_read_packet(handle
, callback
, user
);
1452 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1454 handle
->linktype
= dlt
;
1459 * linux_check_direction()
1461 * Do checks based on packet direction.
1464 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1466 struct pcap_linux
*handlep
= handle
->priv
;
1468 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1471 * If this is from the loopback device, reject it;
1472 * we'll see the packet as an incoming packet as well,
1473 * and we don't want to see it twice.
1475 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1479 * If the user only wants incoming packets, reject it.
1481 if (handle
->direction
== PCAP_D_IN
)
1486 * If the user only wants outgoing packets, reject it.
1488 if (handle
->direction
== PCAP_D_OUT
)
1495 * Read a packet from the socket calling the handler provided by
1496 * the user. Returns the number of packets received or -1 if an
1500 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1502 struct pcap_linux
*handlep
= handle
->priv
;
1505 #ifdef HAVE_PF_PACKET_SOCKETS
1506 struct sockaddr_ll from
;
1507 struct sll_header
*hdrp
;
1509 struct sockaddr from
;
1511 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1514 struct cmsghdr
*cmsg
;
1516 struct cmsghdr cmsg
;
1517 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1519 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1521 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1522 int packet_len
, caplen
;
1523 struct pcap_pkthdr pcap_header
;
1525 struct bpf_aux_data aux_data
;
1526 #ifdef HAVE_PF_PACKET_SOCKETS
1528 * If this is a cooked device, leave extra room for a
1529 * fake packet header.
1531 if (handlep
->cooked
)
1532 offset
= SLL_HDR_LEN
;
1537 * This system doesn't have PF_PACKET sockets, so it doesn't
1538 * support cooked devices.
1544 * Receive a single packet from the kernel.
1545 * We ignore EINTR, as that might just be due to a signal
1546 * being delivered - if the signal should interrupt the
1547 * loop, the signal handler should call pcap_breakloop()
1548 * to set handle->break_loop (we ignore it on other
1549 * platforms as well).
1550 * We also ignore ENETDOWN, so that we can continue to
1551 * capture traffic if the interface goes down and comes
1552 * back up again; comments in the kernel indicate that
1553 * we'll just block waiting for packets if we try to
1554 * receive from a socket that delivered ENETDOWN, and,
1555 * if we're using a memory-mapped buffer, we won't even
1556 * get notified of "network down" events.
1558 bp
= handle
->buffer
+ handle
->offset
;
1560 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1561 msg
.msg_name
= &from
;
1562 msg
.msg_namelen
= sizeof(from
);
1565 msg
.msg_control
= &cmsg_buf
;
1566 msg
.msg_controllen
= sizeof(cmsg_buf
);
1569 iov
.iov_len
= handle
->bufsize
- offset
;
1570 iov
.iov_base
= bp
+ offset
;
1571 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1575 * Has "pcap_breakloop()" been called?
1577 if (handle
->break_loop
) {
1579 * Yes - clear the flag that indicates that it has,
1580 * and return PCAP_ERROR_BREAK as an indication that
1581 * we were told to break out of the loop.
1583 handle
->break_loop
= 0;
1584 return PCAP_ERROR_BREAK
;
1587 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1588 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1589 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1590 fromlen
= sizeof(from
);
1591 packet_len
= recvfrom(
1592 handle
->fd
, bp
+ offset
,
1593 handle
->bufsize
- offset
, MSG_TRUNC
,
1594 (struct sockaddr
*) &from
, &fromlen
);
1595 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1596 } while (packet_len
== -1 && errno
== EINTR
);
1598 /* Check if an error occured */
1600 if (packet_len
== -1) {
1604 return 0; /* no packet there */
1608 * The device on which we're capturing went away.
1610 * XXX - we should really return
1611 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1612 * etc. aren't defined to return that.
1614 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1615 "The interface went down");
1619 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1620 "recvfrom: %s", pcap_strerror(errno
));
1625 #ifdef HAVE_PF_PACKET_SOCKETS
1626 if (!handlep
->sock_packet
) {
1628 * Unfortunately, there is a window between socket() and
1629 * bind() where the kernel may queue packets from any
1630 * interface. If we're bound to a particular interface,
1631 * discard packets not from that interface.
1633 * (If socket filters are supported, we could do the
1634 * same thing we do when changing the filter; however,
1635 * that won't handle packet sockets without socket
1636 * filter support, and it's a bit more complicated.
1637 * It would save some instructions per packet, however.)
1639 if (handlep
->ifindex
!= -1 &&
1640 from
.sll_ifindex
!= handlep
->ifindex
)
1644 * Do checks based on packet direction.
1645 * We can only do this if we're using PF_PACKET; the
1646 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1647 * which lacks the relevant packet type information.
1649 if (!linux_check_direction(handle
, &from
))
1654 #ifdef HAVE_PF_PACKET_SOCKETS
1656 * If this is a cooked device, fill in the fake packet header.
1658 if (handlep
->cooked
) {
1660 * Add the length of the fake header to the length
1661 * of packet data we read.
1663 packet_len
+= SLL_HDR_LEN
;
1665 hdrp
= (struct sll_header
*)bp
;
1666 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1667 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1668 hdrp
->sll_halen
= htons(from
.sll_halen
);
1669 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1670 (from
.sll_halen
> SLL_ADDRLEN
) ?
1673 hdrp
->sll_protocol
= from
.sll_protocol
;
1676 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1677 if (handlep
->vlan_offset
!= -1) {
1678 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1679 struct tpacket_auxdata
*aux
;
1681 struct vlan_tag
*tag
;
1683 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1684 cmsg
->cmsg_level
!= SOL_PACKET
||
1685 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1688 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1689 #if defined(TP_STATUS_VLAN_VALID)
1690 if ((aux
->tp_vlan_tci
== 0) && !(aux
->tp_status
& TP_STATUS_VLAN_VALID
))
1692 if (aux
->tp_vlan_tci
== 0) /* this is ambigious but without the
1693 TP_STATUS_VLAN_VALID flag, there is
1694 nothing that we can do */
1698 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1699 if (len
< (unsigned int) handlep
->vlan_offset
)
1703 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1705 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1706 tag
->vlan_tpid
= htons(VLAN_TPID(aux
, aux
));
1707 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1709 /* store vlan tci to bpf_aux_data struct for userland bpf filter */
1710 #if defined(TP_STATUS_VLAN_VALID)
1711 aux_data
.vlan_tag
= htons(aux
->tp_vlan_tci
) & 0x0fff;
1712 aux_data
.vlan_tag_present
= (aux
->tp_status
& TP_STATUS_VLAN_VALID
);
1714 packet_len
+= VLAN_TAG_LEN
;
1717 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1718 #endif /* HAVE_PF_PACKET_SOCKETS */
1721 * XXX: According to the kernel source we should get the real
1722 * packet len if calling recvfrom with MSG_TRUNC set. It does
1723 * not seem to work here :(, but it is supported by this code
1725 * To be honest the code RELIES on that feature so this is really
1726 * broken with 2.2.x kernels.
1727 * I spend a day to figure out what's going on and I found out
1728 * that the following is happening:
1730 * The packet comes from a random interface and the packet_rcv
1731 * hook is called with a clone of the packet. That code inserts
1732 * the packet into the receive queue of the packet socket.
1733 * If a filter is attached to that socket that filter is run
1734 * first - and there lies the problem. The default filter always
1735 * cuts the packet at the snaplen:
1740 * So the packet filter cuts down the packet. The recvfrom call
1741 * says "hey, it's only 68 bytes, it fits into the buffer" with
1742 * the result that we don't get the real packet length. This
1743 * is valid at least until kernel 2.2.17pre6.
1745 * We currently handle this by making a copy of the filter
1746 * program, fixing all "ret" instructions with non-zero
1747 * operands to have an operand of MAXIMUM_SNAPLEN so that the
1748 * filter doesn't truncate the packet, and supplying that modified
1749 * filter to the kernel.
1752 caplen
= packet_len
;
1753 if (caplen
> handle
->snapshot
)
1754 caplen
= handle
->snapshot
;
1756 /* Run the packet filter if not using kernel filter */
1757 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
1758 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
1759 packet_len
, caplen
, &aux_data
) == 0) {
1760 /* rejected by filter */
1765 /* Fill in our own header data */
1767 /* get timestamp for this packet */
1768 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1769 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
1770 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
1771 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1772 "SIOCGSTAMPNS: %s", pcap_strerror(errno
));
1778 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1779 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1780 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1785 pcap_header
.caplen
= caplen
;
1786 pcap_header
.len
= packet_len
;
1791 * Arguably, we should count them before we check the filter,
1792 * as on many other platforms "ps_recv" counts packets
1793 * handed to the filter rather than packets that passed
1794 * the filter, but if filtering is done in the kernel, we
1795 * can't get a count of packets that passed the filter,
1796 * and that would mean the meaning of "ps_recv" wouldn't
1797 * be the same on all Linux systems.
1799 * XXX - it's not the same on all systems in any case;
1800 * ideally, we should have a "get the statistics" call
1801 * that supplies more counts and indicates which of them
1802 * it supplies, so that we supply a count of packets
1803 * handed to the filter only on platforms where that
1804 * information is available.
1806 * We count them here even if we can get the packet count
1807 * from the kernel, as we can only determine at run time
1808 * whether we'll be able to get it from the kernel (if
1809 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1810 * the kernel, but if it is defined, the library might
1811 * have been built with a 2.4 or later kernel, but we
1812 * might be running on a 2.2[.x] kernel without Alexey
1813 * Kuznetzov's turbopacket patches, and thus the kernel
1814 * might not be able to supply those statistics). We
1815 * could, I guess, try, when opening the socket, to get
1816 * the statistics, and if we can not increment the count
1817 * here, but it's not clear that always incrementing
1818 * the count is more expensive than always testing a flag
1821 * We keep the count in "handlep->packets_read", and use that
1822 * for "ps_recv" if we can't get the statistics from the kernel.
1823 * We do that because, if we *can* get the statistics from
1824 * the kernel, we use "handlep->stat.ps_recv" and
1825 * "handlep->stat.ps_drop" as running counts, as reading the
1826 * statistics from the kernel resets the kernel statistics,
1827 * and if we directly increment "handlep->stat.ps_recv" here,
1828 * that means it will count packets *twice* on systems where
1829 * we can get kernel statistics - once here, and once in
1830 * pcap_stats_linux().
1832 handlep
->packets_read
++;
1834 /* Call the user supplied callback function */
1835 callback(userdata
, &pcap_header
, bp
);
1841 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1843 struct pcap_linux
*handlep
= handle
->priv
;
1846 #ifdef HAVE_PF_PACKET_SOCKETS
1847 if (!handlep
->sock_packet
) {
1848 /* PF_PACKET socket */
1849 if (handlep
->ifindex
== -1) {
1851 * We don't support sending on the "any" device.
1853 strlcpy(handle
->errbuf
,
1854 "Sending packets isn't supported on the \"any\" device",
1859 if (handlep
->cooked
) {
1861 * We don't support sending on the "any" device.
1863 * XXX - how do you send on a bound cooked-mode
1865 * Is a "sendto()" required there?
1867 strlcpy(handle
->errbuf
,
1868 "Sending packets isn't supported in cooked mode",
1875 ret
= send(handle
->fd
, buf
, size
, 0);
1877 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1878 pcap_strerror(errno
));
1885 * Get the statistics for the given packet capture handle.
1886 * Reports the number of dropped packets iff the kernel supports
1887 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1888 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1889 * patches); otherwise, that information isn't available, and we lie
1890 * and report 0 as the count of dropped packets.
1893 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1895 struct pcap_linux
*handlep
= handle
->priv
;
1896 #ifdef HAVE_TPACKET_STATS
1897 #ifdef HAVE_TPACKET3
1899 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
1900 * stuff at the end of a struct tpacket_stats_v3 will not
1901 * be filled in, and we don't look at it so this is OK even
1902 * for those sockets. In addition, the PF_PACKET socket
1903 * code in the kernel only uses the length parameter to
1904 * compute how much data to copy out and to indicate how
1905 * much data was copied out, so it's OK to base it on the
1906 * size of a struct tpacket_stats.
1908 * XXX - it's probably OK, in fact, to just use a
1909 * struct tpacket_stats for V3 sockets, as we don't
1910 * care about the tp_freeze_q_cnt stat.
1912 struct tpacket_stats_v3 kstats
;
1913 #else /* HAVE_TPACKET3 */
1914 struct tpacket_stats kstats
;
1915 #endif /* HAVE_TPACKET3 */
1916 socklen_t len
= sizeof (struct tpacket_stats
);
1917 #endif /* HAVE_TPACKET_STATS */
1919 long if_dropped
= 0;
1922 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1924 if (handle
->opt
.promisc
)
1926 if_dropped
= handlep
->proc_dropped
;
1927 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1928 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
1931 #ifdef HAVE_TPACKET_STATS
1933 * Try to get the packet counts from the kernel.
1935 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1936 &kstats
, &len
) > -1) {
1938 * On systems where the PACKET_STATISTICS "getsockopt()"
1939 * argument is supported on PF_PACKET sockets:
1941 * "ps_recv" counts only packets that *passed* the
1942 * filter, not packets that didn't pass the filter.
1943 * This includes packets later dropped because we
1944 * ran out of buffer space.
1946 * "ps_drop" counts packets dropped because we ran
1947 * out of buffer space. It doesn't count packets
1948 * dropped by the interface driver. It counts only
1949 * packets that passed the filter.
1951 * See above for ps_ifdrop.
1953 * Both statistics include packets not yet read from
1954 * the kernel by libpcap, and thus not yet seen by
1957 * In "linux/net/packet/af_packet.c", at least in the
1958 * 2.4.9 kernel, "tp_packets" is incremented for every
1959 * packet that passes the packet filter *and* is
1960 * successfully queued on the socket; "tp_drops" is
1961 * incremented for every packet dropped because there's
1962 * not enough free space in the socket buffer.
1964 * When the statistics are returned for a PACKET_STATISTICS
1965 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1966 * so that "tp_packets" counts all packets handed to
1967 * the PF_PACKET socket, including packets dropped because
1968 * there wasn't room on the socket buffer - but not
1969 * including packets that didn't pass the filter.
1971 * In the BSD BPF, the count of received packets is
1972 * incremented for every packet handed to BPF, regardless
1973 * of whether it passed the filter.
1975 * We can't make "pcap_stats()" work the same on both
1976 * platforms, but the best approximation is to return
1977 * "tp_packets" as the count of packets and "tp_drops"
1978 * as the count of drops.
1980 * Keep a running total because each call to
1981 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1982 * resets the counters to zero.
1984 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1985 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1986 *stats
= handlep
->stat
;
1992 * If the error was EOPNOTSUPP, fall through, so that
1993 * if you build the library on a system with
1994 * "struct tpacket_stats" and run it on a system
1995 * that doesn't, it works as it does if the library
1996 * is built on a system without "struct tpacket_stats".
1998 if (errno
!= EOPNOTSUPP
) {
1999 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2000 "pcap_stats: %s", pcap_strerror(errno
));
2006 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2007 * is not supported on PF_PACKET sockets:
2009 * "ps_recv" counts only packets that *passed* the filter,
2010 * not packets that didn't pass the filter. It does not
2011 * count packets dropped because we ran out of buffer
2014 * "ps_drop" is not supported.
2016 * "ps_ifdrop" is supported. It will return the number
2017 * of drops the interface reports in /proc/net/dev,
2018 * if that is available.
2020 * "ps_recv" doesn't include packets not yet read from
2021 * the kernel by libpcap.
2023 * We maintain the count of packets processed by libpcap in
2024 * "handlep->packets_read", for reasons described in the comment
2025 * at the end of pcap_read_packet(). We have no idea how many
2026 * packets were dropped by the kernel buffers -- but we know
2027 * how many the interface dropped, so we can return that.
2030 stats
->ps_recv
= handlep
->packets_read
;
2032 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2037 add_linux_if(pcap_if_t
**devlistp
, const char *ifname
, int fd
, char *errbuf
)
2040 char name
[512]; /* XXX - pick a size */
2042 struct ifreq ifrflags
;
2045 * Get the interface name.
2049 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2052 * This could be the separator between a
2053 * name and an alias number, or it could be
2054 * the separator between a name with no
2055 * alias number and the next field.
2057 * If there's a colon after digits, it
2058 * separates the name and the alias number,
2059 * otherwise it separates the name and the
2063 while (isascii(*p
) && isdigit(*p
))
2067 * That was the next field,
2068 * not the alias number.
2079 * Get the flags for this interface.
2081 strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2082 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2083 if (errno
== ENXIO
|| errno
== ENODEV
)
2084 return (0); /* device doesn't actually exist - ignore it */
2085 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2086 "SIOCGIFFLAGS: %.*s: %s",
2087 (int)sizeof(ifrflags
.ifr_name
),
2089 pcap_strerror(errno
));
2094 * Add an entry for this interface, with no addresses.
2096 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2108 * Get from "/sys/class/net" all interfaces listed there; if they're
2109 * already in the list of interfaces we have, that won't add another
2110 * instance, but if they're not, that'll add them.
2112 * We don't bother getting any addresses for them; it appears you can't
2113 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2114 * although some other types of addresses can be fetched with SIOCGIFADDR,
2115 * we don't bother with them for now.
2117 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2118 * the list of interfaces as is, and return 0, so that we can try
2119 * scanning /proc/net/dev.
2121 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2124 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
2126 DIR *sys_class_net_d
;
2129 char subsystem_path
[PATH_MAX
+1];
2133 sys_class_net_d
= opendir("/sys/class/net");
2134 if (sys_class_net_d
== NULL
) {
2136 * Don't fail if it doesn't exist at all.
2138 if (errno
== ENOENT
)
2142 * Fail if we got some other error.
2144 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2145 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
2150 * Create a socket from which to fetch interface information.
2152 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2154 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2155 "socket: %s", pcap_strerror(errno
));
2156 (void)closedir(sys_class_net_d
);
2162 ent
= readdir(sys_class_net_d
);
2165 * Error or EOF; if errno != 0, it's an error.
2171 * Ignore "." and "..".
2173 if (strcmp(ent
->d_name
, ".") == 0 ||
2174 strcmp(ent
->d_name
, "..") == 0)
2178 * Ignore plain files; they do not have subdirectories
2179 * and thus have no attributes.
2181 if (ent
->d_type
== DT_REG
)
2185 * Is there an "ifindex" file under that name?
2186 * (We don't care whether it's a directory or
2187 * a symlink; older kernels have directories
2188 * for devices, newer kernels have symlinks to
2191 snprintf(subsystem_path
, sizeof subsystem_path
,
2192 "/sys/class/net/%s/ifindex", ent
->d_name
);
2193 if (lstat(subsystem_path
, &statb
) != 0) {
2195 * Stat failed. Either there was an error
2196 * other than ENOENT, and we don't know if
2197 * this is an interface, or it's ENOENT,
2198 * and either some part of "/sys/class/net/{if}"
2199 * disappeared, in which case it probably means
2200 * the interface disappeared, or there's no
2201 * "ifindex" file, which means it's not a
2202 * network interface.
2208 * Attempt to add the interface.
2210 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2218 * Well, we didn't fail for any other reason; did we
2219 * fail due to an error reading the directory?
2222 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2223 "Error reading /sys/class/net: %s",
2224 pcap_strerror(errno
));
2230 (void)closedir(sys_class_net_d
);
2235 * Get from "/proc/net/dev" all interfaces listed there; if they're
2236 * already in the list of interfaces we have, that won't add another
2237 * instance, but if they're not, that'll add them.
2239 * See comments from scan_sys_class_net().
2242 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2251 proc_net_f
= fopen("/proc/net/dev", "r");
2252 if (proc_net_f
== NULL
) {
2254 * Don't fail if it doesn't exist at all.
2256 if (errno
== ENOENT
)
2260 * Fail if we got some other error.
2262 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2263 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2268 * Create a socket from which to fetch interface information.
2270 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2272 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2273 "socket: %s", pcap_strerror(errno
));
2274 (void)fclose(proc_net_f
);
2279 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2281 * Skip the first two lines - they're headers.
2289 * Skip leading white space.
2291 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2293 if (*p
== '\0' || *p
== '\n')
2294 continue; /* blank line */
2297 * Attempt to add the interface.
2299 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2307 * Well, we didn't fail for any other reason; did we
2308 * fail due to an error reading the file?
2310 if (ferror(proc_net_f
)) {
2311 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2312 "Error reading /proc/net/dev: %s",
2313 pcap_strerror(errno
));
2319 (void)fclose(proc_net_f
);
2324 * Description string for the "any" device.
2326 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2329 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2334 * Read "/sys/class/net", and add to the list of interfaces all
2335 * interfaces listed there that we don't already have, because,
2336 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2337 * and even getifaddrs() won't return information about
2338 * interfaces with no addresses, so you need to read "/sys/class/net"
2339 * to get the names of the rest of the interfaces.
2341 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2343 return (-1); /* failed */
2346 * No /sys/class/net; try reading /proc/net/dev instead.
2348 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2353 * Add the "any" device.
2355 if (pcap_add_if(alldevsp
, "any", IFF_UP
|IFF_RUNNING
,
2356 any_descr
, errbuf
) < 0)
2363 * Attach the given BPF code to the packet capture device.
2366 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2369 struct pcap_linux
*handlep
;
2370 #ifdef SO_ATTACH_FILTER
2371 struct sock_fprog fcode
;
2372 int can_filter_in_kernel
;
2379 strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2384 handlep
= handle
->priv
;
2386 /* Make our private copy of the filter */
2388 if (install_bpf_program(handle
, filter
) < 0)
2389 /* install_bpf_program() filled in errbuf */
2393 * Run user level packet filter by default. Will be overriden if
2394 * installing a kernel filter succeeds.
2396 handlep
->filter_in_userland
= 1;
2398 /* Install kernel level filter if possible */
2400 #ifdef SO_ATTACH_FILTER
2402 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2404 * fcode.len is an unsigned short for current kernel.
2405 * I have yet to see BPF-Code with that much
2406 * instructions but still it is possible. So for the
2407 * sake of correctness I added this check.
2409 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2411 fcode
.filter
= NULL
;
2412 can_filter_in_kernel
= 0;
2414 #endif /* USHRT_MAX */
2417 * Oh joy, the Linux kernel uses struct sock_fprog instead
2418 * of struct bpf_program and of course the length field is
2419 * of different size. Pointed out by Sebastian
2421 * Oh, and we also need to fix it up so that all "ret"
2422 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2423 * as the operand if we're not capturing in memory-mapped
2424 * mode, and so that, if we're in cooked mode, all memory-
2425 * reference instructions use special magic offsets in
2426 * references to the link-layer header and assume that the
2427 * link-layer payload begins at 0; "fix_program()" will do
2430 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2435 * Fatal error; just quit.
2436 * (The "default" case shouldn't happen; we
2437 * return -1 for that reason.)
2443 * The program performed checks that we can't make
2444 * work in the kernel.
2446 can_filter_in_kernel
= 0;
2451 * We have a filter that'll work in the kernel.
2453 can_filter_in_kernel
= 1;
2459 * NOTE: at this point, we've set both the "len" and "filter"
2460 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2461 * those are the only members of the "sock_fprog" structure,
2462 * so we initialize every member of that structure.
2464 * If there is anything in "fcode" that is not initialized,
2465 * it is either a field added in a later kernel, or it's
2468 * If a new field is added, this code needs to be updated
2469 * to set it correctly.
2471 * If there are no other fields, then:
2473 * if the Linux kernel looks at the padding, it's
2476 * if the Linux kernel doesn't look at the padding,
2477 * then if some tool complains that we're passing
2478 * uninitialized data to the kernel, then the tool
2479 * is buggy and needs to understand that it's just
2482 if (can_filter_in_kernel
) {
2483 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2486 * Installation succeded - using kernel filter,
2487 * so userland filtering not needed.
2489 handlep
->filter_in_userland
= 0;
2491 else if (err
== -1) /* Non-fatal error */
2494 * Print a warning if we weren't able to install
2495 * the filter for a reason other than "this kernel
2496 * isn't configured to support socket filters.
2498 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2500 "Warning: Kernel filter failed: %s\n",
2501 pcap_strerror(errno
));
2507 * If we're not using the kernel filter, get rid of any kernel
2508 * filter that might've been there before, e.g. because the
2509 * previous filter could work in the kernel, or because some other
2510 * code attached a filter to the socket by some means other than
2511 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2512 * filter out packets that would pass the new userland filter.
2514 if (handlep
->filter_in_userland
) {
2515 if (reset_kernel_filter(handle
) == -1) {
2516 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2517 "can't remove kernel filter: %s",
2518 pcap_strerror(errno
));
2519 err
= -2; /* fatal error */
2524 * Free up the copy of the filter that was made by "fix_program()".
2526 if (fcode
.filter
!= NULL
)
2532 #endif /* SO_ATTACH_FILTER */
2538 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2540 return pcap_setfilter_linux_common(handle
, filter
, 0);
2545 * Set direction flag: Which packets do we accept on a forwarding
2546 * single device? IN, OUT or both?
2549 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2551 #ifdef HAVE_PF_PACKET_SOCKETS
2552 struct pcap_linux
*handlep
= handle
->priv
;
2554 if (!handlep
->sock_packet
) {
2555 handle
->direction
= d
;
2560 * We're not using PF_PACKET sockets, so we can't determine
2561 * the direction of the packet.
2563 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2564 "Setting direction is not supported on SOCK_PACKET sockets");
2568 #ifdef HAVE_PF_PACKET_SOCKETS
2570 * Map the PACKET_ value to a LINUX_SLL_ value; we
2571 * want the same numerical value to be used in
2572 * the link-layer header even if the numerical values
2573 * for the PACKET_ #defines change, so that programs
2574 * that look at the packet type field will always be
2575 * able to handle DLT_LINUX_SLL captures.
2578 map_packet_type_to_sll_type(short int sll_pkttype
)
2580 switch (sll_pkttype
) {
2583 return htons(LINUX_SLL_HOST
);
2585 case PACKET_BROADCAST
:
2586 return htons(LINUX_SLL_BROADCAST
);
2588 case PACKET_MULTICAST
:
2589 return htons(LINUX_SLL_MULTICAST
);
2591 case PACKET_OTHERHOST
:
2592 return htons(LINUX_SLL_OTHERHOST
);
2594 case PACKET_OUTGOING
:
2595 return htons(LINUX_SLL_OUTGOING
);
2605 #ifndef IW_MODE_MONITOR
2608 , const char *device
)
2612 #ifdef IW_MODE_MONITOR
2613 char errbuf
[PCAP_ERRBUF_SIZE
];
2617 * See if there's a sysfs wireless directory for it.
2618 * If so, it's a wireless interface.
2620 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
2622 * Just give up here.
2626 if (stat(pathstr
, &statb
) == 0) {
2632 #ifdef IW_MODE_MONITOR
2634 * OK, maybe it's not wireless, or maybe this kernel doesn't
2635 * support sysfs. Try the wireless extensions.
2637 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
2639 * It supports the wireless extensions, so it's a Wi-Fi
2649 * Linux uses the ARP hardware type to identify the type of an
2650 * interface. pcap uses the DLT_xxx constants for this. This
2651 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2652 * constant, as arguments, and sets "handle->linktype" to the
2653 * appropriate DLT_XXX constant and sets "handle->offset" to
2654 * the appropriate value (to make "handle->offset" plus link-layer
2655 * header length be a multiple of 4, so that the link-layer payload
2656 * will be aligned on a 4-byte boundary when capturing packets).
2657 * (If the offset isn't set here, it'll be 0; add code as appropriate
2658 * for cases where it shouldn't be 0.)
2660 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2661 * in cooked mode; otherwise, we can't use cooked mode, so we have
2662 * to pick some type that works in raw mode, or fail.
2664 * Sets the link type to -1 if unable to map the type.
2666 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
2667 const char *device
, int cooked_ok
)
2669 static const char cdma_rmnet
[] = "cdma_rmnet";
2675 * For various annoying reasons having to do with DHCP
2676 * software, some versions of Android give the mobile-
2677 * phone-network interface an ARPHRD_ value of
2678 * ARPHRD_ETHER, even though the packets supplied by
2679 * that interface have no link-layer header, and begin
2680 * with an IP header, so that the ARPHRD_ value should
2683 * Detect those devices by checking the device name, and
2684 * use DLT_RAW for them.
2686 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2687 handle
->linktype
= DLT_RAW
;
2692 * Is this a real Ethernet device? If so, give it a
2693 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2694 * that an application can let you choose it, in case you're
2695 * capturing DOCSIS traffic that a Cisco Cable Modem
2696 * Termination System is putting out onto an Ethernet (it
2697 * doesn't put an Ethernet header onto the wire, it puts raw
2698 * DOCSIS frames out on the wire inside the low-level
2699 * Ethernet framing).
2701 * XXX - are there any other sorts of "fake Ethernet" that
2702 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2703 * a Cisco CMTS won't put traffic onto it or get traffic
2704 * bridged onto it? ISDN is handled in "activate_new()",
2705 * as we fall back on cooked mode there, and we use
2706 * is_wifi() to check for 802.11 devices; are there any
2709 if (!is_wifi(sock_fd
, device
)) {
2711 * It's not a Wi-Fi device; offer DOCSIS.
2713 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2715 * If that fails, just leave the list empty.
2717 if (handle
->dlt_list
!= NULL
) {
2718 handle
->dlt_list
[0] = DLT_EN10MB
;
2719 handle
->dlt_list
[1] = DLT_DOCSIS
;
2720 handle
->dlt_count
= 2;
2725 case ARPHRD_METRICOM
:
2726 case ARPHRD_LOOPBACK
:
2727 handle
->linktype
= DLT_EN10MB
;
2732 handle
->linktype
= DLT_EN3MB
;
2736 handle
->linktype
= DLT_AX25_KISS
;
2740 handle
->linktype
= DLT_PRONET
;
2744 handle
->linktype
= DLT_CHAOS
;
2747 #define ARPHRD_CAN 280
2750 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2753 #ifndef ARPHRD_IEEE802_TR
2754 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2756 case ARPHRD_IEEE802_TR
:
2757 case ARPHRD_IEEE802
:
2758 handle
->linktype
= DLT_IEEE802
;
2763 handle
->linktype
= DLT_ARCNET_LINUX
;
2766 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2767 #define ARPHRD_FDDI 774
2770 handle
->linktype
= DLT_FDDI
;
2774 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2775 #define ARPHRD_ATM 19
2779 * The Classical IP implementation in ATM for Linux
2780 * supports both what RFC 1483 calls "LLC Encapsulation",
2781 * in which each packet has an LLC header, possibly
2782 * with a SNAP header as well, prepended to it, and
2783 * what RFC 1483 calls "VC Based Multiplexing", in which
2784 * different virtual circuits carry different network
2785 * layer protocols, and no header is prepended to packets.
2787 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2788 * you can't use the ARPHRD_ type to find out whether
2789 * captured packets will have an LLC header, and,
2790 * while there's a socket ioctl to *set* the encapsulation
2791 * type, there's no ioctl to *get* the encapsulation type.
2795 * programs that dissect Linux Classical IP frames
2796 * would have to check for an LLC header and,
2797 * depending on whether they see one or not, dissect
2798 * the frame as LLC-encapsulated or as raw IP (I
2799 * don't know whether there's any traffic other than
2800 * IP that would show up on the socket, or whether
2801 * there's any support for IPv6 in the Linux
2802 * Classical IP code);
2804 * filter expressions would have to compile into
2805 * code that checks for an LLC header and does
2808 * Both of those are a nuisance - and, at least on systems
2809 * that support PF_PACKET sockets, we don't have to put
2810 * up with those nuisances; instead, we can just capture
2811 * in cooked mode. That's what we'll do, if we can.
2812 * Otherwise, we'll just fail.
2815 handle
->linktype
= DLT_LINUX_SLL
;
2817 handle
->linktype
= -1;
2820 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2821 #define ARPHRD_IEEE80211 801
2823 case ARPHRD_IEEE80211
:
2824 handle
->linktype
= DLT_IEEE802_11
;
2827 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2828 #define ARPHRD_IEEE80211_PRISM 802
2830 case ARPHRD_IEEE80211_PRISM
:
2831 handle
->linktype
= DLT_PRISM_HEADER
;
2834 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2835 #define ARPHRD_IEEE80211_RADIOTAP 803
2837 case ARPHRD_IEEE80211_RADIOTAP
:
2838 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2843 * Some PPP code in the kernel supplies no link-layer
2844 * header whatsoever to PF_PACKET sockets; other PPP
2845 * code supplies PPP link-layer headers ("syncppp.c");
2846 * some PPP code might supply random link-layer
2847 * headers (PPP over ISDN - there's code in Ethereal,
2848 * for example, to cope with PPP-over-ISDN captures
2849 * with which the Ethereal developers have had to cope,
2850 * heuristically trying to determine which of the
2851 * oddball link-layer headers particular packets have).
2853 * As such, we just punt, and run all PPP interfaces
2854 * in cooked mode, if we can; otherwise, we just treat
2855 * it as DLT_RAW, for now - if somebody needs to capture,
2856 * on a 2.0[.x] kernel, on PPP devices that supply a
2857 * link-layer header, they'll have to add code here to
2858 * map to the appropriate DLT_ type (possibly adding a
2859 * new DLT_ type, if necessary).
2862 handle
->linktype
= DLT_LINUX_SLL
;
2865 * XXX - handle ISDN types here? We can't fall
2866 * back on cooked sockets, so we'd have to
2867 * figure out from the device name what type of
2868 * link-layer encapsulation it's using, and map
2869 * that to an appropriate DLT_ value, meaning
2870 * we'd map "isdnN" devices to DLT_RAW (they
2871 * supply raw IP packets with no link-layer
2872 * header) and "isdY" devices to a new DLT_I4L_IP
2873 * type that has only an Ethernet packet type as
2874 * a link-layer header.
2876 * But sometimes we seem to get random crap
2877 * in the link-layer header when capturing on
2880 handle
->linktype
= DLT_RAW
;
2884 #ifndef ARPHRD_CISCO
2885 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2888 handle
->linktype
= DLT_C_HDLC
;
2891 /* Not sure if this is correct for all tunnels, but it
2895 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2903 #ifndef ARPHRD_RAWHDLC
2904 #define ARPHRD_RAWHDLC 518
2906 case ARPHRD_RAWHDLC
:
2908 #define ARPHRD_DLCI 15
2912 * XXX - should some of those be mapped to DLT_LINUX_SLL
2913 * instead? Should we just map all of them to DLT_LINUX_SLL?
2915 handle
->linktype
= DLT_RAW
;
2919 #define ARPHRD_FRAD 770
2922 handle
->linktype
= DLT_FRELAY
;
2925 case ARPHRD_LOCALTLK
:
2926 handle
->linktype
= DLT_LTALK
;
2931 * RFC 4338 defines an encapsulation for IP and ARP
2932 * packets that's compatible with the RFC 2625
2933 * encapsulation, but that uses a different ARP
2934 * hardware type and hardware addresses. That
2935 * ARP hardware type is 18; Linux doesn't define
2936 * any ARPHRD_ value as 18, but if it ever officially
2937 * supports RFC 4338-style IP-over-FC, it should define
2940 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2941 * that this will encourage its use in the future,
2942 * should Linux ever officially support RFC 4338-style
2945 handle
->linktype
= DLT_IP_OVER_FC
;
2949 #define ARPHRD_FCPP 784
2953 #define ARPHRD_FCAL 785
2957 #define ARPHRD_FCPL 786
2960 #ifndef ARPHRD_FCFABRIC
2961 #define ARPHRD_FCFABRIC 787
2963 case ARPHRD_FCFABRIC
:
2965 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2968 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2970 * and one was assigned.
2972 * In a later private discussion (spun off from a message
2973 * on the ethereal-users list) on how to get that DLT_
2974 * value in libpcap on Linux, I ended up deciding that
2975 * the best thing to do would be to have him tweak the
2976 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2977 * type, and map all those types to DLT_IP_OVER_FC:
2979 * I've checked into the libpcap and tcpdump CVS tree
2980 * support for DLT_IP_OVER_FC. In order to use that,
2981 * you'd have to modify your modified driver to return
2982 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2983 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2984 * example (the exact value doesn't matter, it can be
2985 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2988 * 11 years later, Christian Svensson wanted to map
2989 * various ARPHRD_ values to DLT_FC_2 and
2990 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2993 * https://github.com/mcr/libpcap/pull/29
2995 * There doesn't seem to be any network drivers that uses
2996 * any of the ARPHRD_FC* values for IP-over-FC, and
2997 * it's not exactly clear what the "Dummy types for non
2998 * ARP hardware" are supposed to mean (link-layer
2999 * header type? Physical network type?), so it's
3000 * not exactly clear why the ARPHRD_FC* types exist
3001 * in the first place.
3003 * For now, we map them to DLT_FC_2, and provide an
3004 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3005 * DLT_IP_OVER_FC just in case there's some old
3006 * driver out there that uses one of those types for
3007 * IP-over-FC on which somebody wants to capture
3010 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3012 * If that fails, just leave the list empty.
3014 if (handle
->dlt_list
!= NULL
) {
3015 handle
->dlt_list
[0] = DLT_FC_2
;
3016 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
3017 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
3018 handle
->dlt_count
= 3;
3020 handle
->linktype
= DLT_FC_2
;
3024 #define ARPHRD_IRDA 783
3027 /* Don't expect IP packet out of this interfaces... */
3028 handle
->linktype
= DLT_LINUX_IRDA
;
3029 /* We need to save packet direction for IrDA decoding,
3030 * so let's use "Linux-cooked" mode. Jean II
3032 * XXX - this is handled in activate_new(). */
3033 //handlep->cooked = 1;
3036 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3037 * is needed, please report it to <daniele@orlandi.com> */
3039 #define ARPHRD_LAPD 8445
3042 /* Don't expect IP packet out of this interfaces... */
3043 handle
->linktype
= DLT_LINUX_LAPD
;
3047 #define ARPHRD_NONE 0xFFFE
3051 * No link-layer header; packets are just IP
3052 * packets, so use DLT_RAW.
3054 handle
->linktype
= DLT_RAW
;
3057 #ifndef ARPHRD_IEEE802154
3058 #define ARPHRD_IEEE802154 804
3060 case ARPHRD_IEEE802154
:
3061 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
3064 #ifndef ARPHRD_NETLINK
3065 #define ARPHRD_NETLINK 824
3067 case ARPHRD_NETLINK
:
3068 handle
->linktype
= DLT_NETLINK
;
3070 * We need to use cooked mode, so that in sll_protocol we
3071 * pick up the netlink protocol type such as NETLINK_ROUTE,
3072 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3074 * XXX - this is handled in activate_new().
3076 //handlep->cooked = 1;
3080 handle
->linktype
= -1;
3085 /* ===== Functions to interface to the newer kernels ================== */
3088 * Try to open a packet socket using the new kernel PF_PACKET interface.
3089 * Returns 1 on success, 0 on an error that means the new interface isn't
3090 * present (so the old SOCK_PACKET interface should be tried), and a
3091 * PCAP_ERROR_ value on an error that means that the old mechanism won't
3092 * work either (so it shouldn't be tried).
3095 activate_new(pcap_t
*handle
)
3097 #ifdef HAVE_PF_PACKET_SOCKETS
3098 struct pcap_linux
*handlep
= handle
->priv
;
3099 const char *device
= handle
->opt
.source
;
3100 int is_any_device
= (strcmp(device
, "any") == 0);
3101 int sock_fd
= -1, arptype
;
3102 #ifdef HAVE_PACKET_AUXDATA
3106 struct packet_mreq mr
;
3107 #ifdef SO_BPF_EXTENSIONS
3109 socklen_t len
= sizeof(bpf_extensions
);
3113 * Open a socket with protocol family packet. If the
3114 * "any" device was specified, we open a SOCK_DGRAM
3115 * socket for the cooked interface, otherwise we first
3116 * try a SOCK_RAW socket for the raw interface.
3118 sock_fd
= is_any_device
?
3119 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
3120 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
3122 if (sock_fd
== -1) {
3123 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
3125 * We don't support PF_PACKET/SOCK_whatever
3126 * sockets; try the old mechanism.
3131 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
3132 pcap_strerror(errno
) );
3133 if (errno
== EPERM
|| errno
== EACCES
) {
3135 * You don't have permission to open the
3138 return PCAP_ERROR_PERM_DENIED
;
3147 /* It seems the kernel supports the new interface. */
3148 handlep
->sock_packet
= 0;
3151 * Get the interface index of the loopback device.
3152 * If the attempt fails, don't fail, just set the
3153 * "handlep->lo_ifindex" to -1.
3155 * XXX - can there be more than one device that loops
3156 * packets back, i.e. devices other than "lo"? If so,
3157 * we'd need to find them all, and have an array of
3158 * indices for them, and check all of them in
3159 * "pcap_read_packet()".
3161 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3164 * Default value for offset to align link-layer payload
3165 * on a 4-byte boundary.
3170 * What kind of frames do we have to deal with? Fall back
3171 * to cooked mode if we have an unknown interface type
3172 * or a type we know doesn't work well in raw mode.
3174 if (!is_any_device
) {
3175 /* Assume for now we don't need cooked mode. */
3176 handlep
->cooked
= 0;
3178 if (handle
->opt
.rfmon
) {
3180 * We were asked to turn on monitor mode.
3181 * Do so before we get the link-layer type,
3182 * because entering monitor mode could change
3183 * the link-layer type.
3185 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3193 * Nothing worked for turning monitor mode
3197 return PCAP_ERROR_RFMON_NOTSUP
;
3201 * Either monitor mode has been turned on for
3202 * the device, or we've been given a different
3203 * device to open for monitor mode. If we've
3204 * been given a different device, use it.
3206 if (handlep
->mondevice
!= NULL
)
3207 device
= handlep
->mondevice
;
3209 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3214 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
3215 if (handle
->linktype
== -1 ||
3216 handle
->linktype
== DLT_LINUX_SLL
||
3217 handle
->linktype
== DLT_LINUX_IRDA
||
3218 handle
->linktype
== DLT_LINUX_LAPD
||
3219 handle
->linktype
== DLT_NETLINK
||
3220 (handle
->linktype
== DLT_EN10MB
&&
3221 (strncmp("isdn", device
, 4) == 0 ||
3222 strncmp("isdY", device
, 4) == 0))) {
3224 * Unknown interface type (-1), or a
3225 * device we explicitly chose to run
3226 * in cooked mode (e.g., PPP devices),
3227 * or an ISDN device (whose link-layer
3228 * type we can only determine by using
3229 * APIs that may be different on different
3230 * kernels) - reopen in cooked mode.
3232 if (close(sock_fd
) == -1) {
3233 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3234 "close: %s", pcap_strerror(errno
));
3237 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3239 if (sock_fd
== -1) {
3240 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3241 "socket: %s", pcap_strerror(errno
));
3242 if (errno
== EPERM
|| errno
== EACCES
) {
3244 * You don't have permission to
3247 return PCAP_ERROR_PERM_DENIED
;
3255 handlep
->cooked
= 1;
3258 * Get rid of any link-layer type list
3259 * we allocated - this only supports cooked
3262 if (handle
->dlt_list
!= NULL
) {
3263 free(handle
->dlt_list
);
3264 handle
->dlt_list
= NULL
;
3265 handle
->dlt_count
= 0;
3268 if (handle
->linktype
== -1) {
3270 * Warn that we're falling back on
3271 * cooked mode; we may want to
3272 * update "map_arphrd_to_dlt()"
3273 * to handle the new type.
3275 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3277 "supported by libpcap - "
3278 "falling back to cooked "
3284 * IrDA capture is not a real "cooked" capture,
3285 * it's IrLAP frames, not IP packets. The
3286 * same applies to LAPD capture.
3288 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3289 handle
->linktype
!= DLT_LINUX_LAPD
&&
3290 handle
->linktype
!= DLT_NETLINK
)
3291 handle
->linktype
= DLT_LINUX_SLL
;
3294 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3296 if (handlep
->ifindex
== -1) {
3301 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3302 handle
->errbuf
)) != 1) {
3307 return 0; /* try old mechanism */
3313 if (handle
->opt
.rfmon
) {
3315 * It doesn't support monitor mode.
3318 return PCAP_ERROR_RFMON_NOTSUP
;
3322 * It uses cooked mode.
3324 handlep
->cooked
= 1;
3325 handle
->linktype
= DLT_LINUX_SLL
;
3328 * We're not bound to a device.
3329 * For now, we're using this as an indication
3330 * that we can't transmit; stop doing that only
3331 * if we figure out how to transmit in cooked
3334 handlep
->ifindex
= -1;
3338 * Select promiscuous mode on if "promisc" is set.
3340 * Do not turn allmulti mode on if we don't select
3341 * promiscuous mode - on some devices (e.g., Orinoco
3342 * wireless interfaces), allmulti mode isn't supported
3343 * and the driver implements it by turning promiscuous
3344 * mode on, and that screws up the operation of the
3345 * card as a normal networking interface, and on no
3346 * other platform I know of does starting a non-
3347 * promiscuous capture affect which multicast packets
3348 * are received by the interface.
3352 * Hmm, how can we set promiscuous mode on all interfaces?
3353 * I am not sure if that is possible at all. For now, we
3354 * silently ignore attempts to turn promiscuous mode on
3355 * for the "any" device (so you don't have to explicitly
3356 * disable it in programs such as tcpdump).
3359 if (!is_any_device
&& handle
->opt
.promisc
) {
3360 memset(&mr
, 0, sizeof(mr
));
3361 mr
.mr_ifindex
= handlep
->ifindex
;
3362 mr
.mr_type
= PACKET_MR_PROMISC
;
3363 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3364 &mr
, sizeof(mr
)) == -1) {
3365 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3366 "setsockopt: %s", pcap_strerror(errno
));
3372 /* Enable auxillary data if supported and reserve room for
3373 * reconstructing VLAN headers. */
3374 #ifdef HAVE_PACKET_AUXDATA
3376 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3377 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3378 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3379 "setsockopt: %s", pcap_strerror(errno
));
3383 handle
->offset
+= VLAN_TAG_LEN
;
3384 #endif /* HAVE_PACKET_AUXDATA */
3387 * This is a 2.2[.x] or later kernel (we know that
3388 * because we're not using a SOCK_PACKET socket -
3389 * PF_PACKET is supported only in 2.2 and later
3392 * We can safely pass "recvfrom()" a byte count
3393 * based on the snapshot length.
3395 * If we're in cooked mode, make the snapshot length
3396 * large enough to hold a "cooked mode" header plus
3397 * 1 byte of packet data (so we don't pass a byte
3398 * count of 0 to "recvfrom()").
3400 if (handlep
->cooked
) {
3401 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3402 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3404 handle
->bufsize
= handle
->snapshot
;
3407 * Set the offset at which to insert VLAN tags.
3409 switch (handle
->linktype
) {
3412 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3416 handlep
->vlan_offset
= 14;
3420 handlep
->vlan_offset
= -1; /* unknown */
3424 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3425 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3426 int nsec_tstamps
= 1;
3428 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3429 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3434 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3437 * We've succeeded. Save the socket FD in the pcap structure.
3439 handle
->fd
= sock_fd
;
3441 #ifdef SO_BPF_EXTENSIONS
3443 * Can we generate special code for VLAN checks?
3444 * (XXX - what if we need the special code but it's not supported
3445 * by the OS? Is that possible?)
3447 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
3448 &bpf_extensions
, &len
) == 0) {
3449 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
3451 * Yes, we can. Request that we do so.
3453 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
3456 #endif /* SO_BPF_EXTENSIONS */
3459 #else /* HAVE_PF_PACKET_SOCKETS */
3461 "New packet capturing interface not supported by build "
3462 "environment", PCAP_ERRBUF_SIZE
);
3464 #endif /* HAVE_PF_PACKET_SOCKETS */
3467 #ifdef HAVE_PACKET_RING
3469 * Attempt to activate with memory-mapped access.
3471 * On success, returns 1, and sets *status to 0 if there are no warnings
3472 * or to a PCAP_WARNING_ code if there is a warning.
3474 * On failure due to lack of support for memory-mapped capture, returns
3477 * On error, returns -1, and sets *status to the appropriate error code;
3478 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3481 activate_mmap(pcap_t
*handle
, int *status
)
3483 struct pcap_linux
*handlep
= handle
->priv
;
3487 * Attempt to allocate a buffer to hold the contents of one
3488 * packet, for use by the oneshot callback.
3490 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3491 if (handlep
->oneshot_buffer
== NULL
) {
3492 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3493 "can't allocate oneshot buffer: %s",
3494 pcap_strerror(errno
));
3495 *status
= PCAP_ERROR
;
3499 if (handle
->opt
.buffer_size
== 0) {
3500 /* by default request 2M for the ring buffer */
3501 handle
->opt
.buffer_size
= 2*1024*1024;
3503 ret
= prepare_tpacket_socket(handle
);
3505 free(handlep
->oneshot_buffer
);
3506 *status
= PCAP_ERROR
;
3509 ret
= create_ring(handle
, status
);
3512 * We don't support memory-mapped capture; our caller
3513 * will fall back on reading from the socket.
3515 free(handlep
->oneshot_buffer
);
3520 * Error attempting to enable memory-mapped capture;
3521 * fail. create_ring() has set *status.
3523 free(handlep
->oneshot_buffer
);
3528 * Success. *status has been set either to 0 if there are no
3529 * warnings or to a PCAP_WARNING_ value if there is a warning.
3531 * Override some defaults and inherit the other fields from
3533 * handle->offset is used to get the current position into the rx ring.
3534 * handle->cc is used to store the ring size.
3537 switch (handlep
->tp_version
) {
3539 handle
->read_op
= pcap_read_linux_mmap_v1
;
3542 handle
->read_op
= pcap_read_linux_mmap_v1_64
;
3544 #ifdef HAVE_TPACKET2
3546 handle
->read_op
= pcap_read_linux_mmap_v2
;
3549 #ifdef HAVE_TPACKET3
3551 handle
->read_op
= pcap_read_linux_mmap_v3
;
3555 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3556 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3557 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3558 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3559 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3560 handle
->selectable_fd
= handle
->fd
;
3563 #else /* HAVE_PACKET_RING */
3565 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3569 #endif /* HAVE_PACKET_RING */
3571 #ifdef HAVE_PACKET_RING
3573 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3575 * Attempt to set the socket to the specified version of the memory-mapped
3578 * Return 0 if we succeed; return 1 if we fail because that version isn't
3579 * supported; return -1 on any other error, and set handle->errbuf.
3582 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
3584 struct pcap_linux
*handlep
= handle
->priv
;
3586 socklen_t len
= sizeof(val
);
3589 * Probe whether kernel supports the specified TPACKET version;
3590 * this also gets the length of the header for that version.
3592 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3593 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
)
3596 /* Failed to even find out; this is a fatal error. */
3597 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3598 "can't get %s header len on packet socket: %s",
3600 pcap_strerror(errno
));
3603 handlep
->tp_hdrlen
= val
;
3606 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3608 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3609 "can't activate %s on packet socket: %s",
3611 pcap_strerror(errno
));
3614 handlep
->tp_version
= version
;
3616 /* Reserve space for VLAN tag reconstruction */
3618 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3620 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3621 "can't set up reserve on packet socket: %s",
3622 pcap_strerror(errno
));
3628 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3631 * If the instruction set for which we're compiling has both 32-bit
3632 * and 64-bit versions, and Linux support for the 64-bit version
3633 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
3634 * you get from uname() for the 64-bit version. Otherwise, leave
3635 * it undefined. (This includes ARM, which has a 64-bit version,
3636 * but Linux support for it appeared well after TPACKET_V2 support
3637 * did, so there should never be a case where 32-bit ARM code is
3638 * running o a 64-bit kernel that only supports TPACKET_V1.)
3640 * If we've omitted your favorite such architecture, please contribute
3641 * a patch. (No patch is needed for architectures that are 32-bit-only
3642 * or for which Linux has no support for 32-bit userland - or for which,
3643 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
3646 #if defined(__i386__)
3647 #define ISA_64_BIT "x86_64"
3648 #elif defined(__ppc__)
3649 #define ISA_64_BIT "ppc64"
3650 #elif defined(__sparc__)
3651 #define ISA_64_BIT "sparc64"
3652 #elif defined(__s390__)
3653 #define ISA_64_BIT "s390x"
3654 #elif defined(__mips__)
3655 #define ISA_64_BIT "mips64"
3656 #elif defined(__hppa__)
3657 #define ISA_64_BIT "parisc64"
3661 * Attempt to set the socket to version 3 of the memory-mapped header and,
3662 * if that fails because version 3 isn't supported, attempt to fall
3663 * back to version 2. If version 2 isn't supported, just leave it at
3666 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
3667 * supported; return -1 on any other error, and set handle->errbuf.
3670 prepare_tpacket_socket(pcap_t
*handle
)
3672 struct pcap_linux
*handlep
= handle
->priv
;
3673 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3677 #ifdef HAVE_TPACKET3
3679 * Try setting the version to TPACKET_V3.
3681 * The only mode in which buffering is done on PF_PACKET
3682 * sockets, so that packets might not be delivered
3683 * immediately, is TPACKET_V3 mode.
3685 * The buffering cannot be disabled in that mode, so
3686 * if the user has requested immediate mode, we don't
3689 if (!handle
->opt
.immediate
) {
3690 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
3699 * We failed for some reason other than "the
3700 * kernel doesn't support TPACKET_V3".
3705 #endif /* HAVE_TPACKET3 */
3707 #ifdef HAVE_TPACKET2
3709 * Try setting the version to TPACKET_V2.
3711 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
3720 * We failed for some reason other than "the
3721 * kernel doesn't support TPACKET_V2".
3725 #endif /* HAVE_TPACKET2 */
3728 * OK, we're using TPACKET_V1, as that's all the kernel supports.
3730 handlep
->tp_version
= TPACKET_V1
;
3731 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
3735 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
3736 * each other due to platform-dependent data type size differences.
3738 * If we have a 32-bit userland and a 64-bit kernel, use an
3739 * internally-defined TPACKET_V1_64, with which we use a 64-bit
3740 * version of the data structures.
3742 if (sizeof(long) == 4) {
3744 * This is 32-bit code.
3746 struct utsname utsname
;
3748 if (uname(&utsname
) == -1) {
3752 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3753 "uname failed: %s", pcap_strerror(errno
));
3756 if (strcmp(utsname
.machine
, ISA_64_BIT
) == 0) {
3758 * uname() tells us the machine is 64-bit,
3759 * so we presumably have a 64-bit kernel.
3761 * XXX - this presumes that uname() won't lie
3762 * in 32-bit code and claim that the machine
3763 * has the 32-bit version of the ISA.
3765 handlep
->tp_version
= TPACKET_V1_64
;
3766 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr_64
);
3775 * Attempt to set up memory-mapped access.
3777 * On success, returns 1, and sets *status to 0 if there are no warnings
3778 * or to a PCAP_WARNING_ code if there is a warning.
3780 * On failure due to lack of support for memory-mapped capture, returns
3783 * On error, returns -1, and sets *status to the appropriate error code;
3784 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3787 create_ring(pcap_t
*handle
, int *status
)
3789 struct pcap_linux
*handlep
= handle
->priv
;
3790 unsigned i
, j
, frames_per_block
;
3791 #ifdef HAVE_TPACKET3
3793 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
3794 * stuff at the end of a struct tpacket_req3 will be
3795 * ignored, so this is OK even for those sockets.
3797 struct tpacket_req3 req
;
3799 struct tpacket_req req
;
3802 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3803 unsigned int frame_size
;
3806 * Start out assuming no warnings or errors.
3810 switch (handlep
->tp_version
) {
3814 #ifdef HAVE_TPACKET2
3817 /* Note that with large snapshot length (say 64K, which is
3818 * the default for recent versions of tcpdump, the value that
3819 * "-s 0" has given for a long time with tcpdump, and the
3820 * default in Wireshark/TShark/dumpcap), if we use the snapshot
3821 * length to calculate the frame length, only a few frames
3822 * will be available in the ring even with pretty
3823 * large ring size (and a lot of memory will be unused).
3825 * Ideally, we should choose a frame length based on the
3826 * minimum of the specified snapshot length and the maximum
3827 * packet size. That's not as easy as it sounds; consider,
3828 * for example, an 802.11 interface in monitor mode, where
3829 * the frame would include a radiotap header, where the
3830 * maximum radiotap header length is device-dependent.
3832 * So, for now, we just do this for Ethernet devices, where
3833 * there's no metadata header, and the link-layer header is
3834 * fixed length. We can get the maximum packet size by
3835 * adding 18, the Ethernet header length plus the CRC length
3836 * (just in case we happen to get the CRC in the packet), to
3837 * the MTU of the interface; we fetch the MTU in the hopes
3838 * that it reflects support for jumbo frames. (Even if the
3839 * interface is just being used for passive snooping, the
3840 * driver might set the size of buffers in the receive ring
3841 * based on the MTU, so that the MTU limits the maximum size
3842 * of packets that we can receive.)
3844 * We don't do that if segmentation/fragmentation or receive
3845 * offload are enabled, so we don't get rudely surprised by
3846 * "packets" bigger than the MTU. */
3847 frame_size
= handle
->snapshot
;
3848 if (handle
->linktype
== DLT_EN10MB
) {
3852 offload
= iface_get_offload(handle
);
3853 if (offload
== -1) {
3854 *status
= PCAP_ERROR
;
3858 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
3861 *status
= PCAP_ERROR
;
3864 if (frame_size
> mtu
+ 18)
3865 frame_size
= mtu
+ 18;
3869 /* NOTE: calculus matching those in tpacket_rcv()
3870 * in linux-2.6/net/packet/af_packet.c
3872 len
= sizeof(sk_type
);
3873 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
3875 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3876 "getsockopt: %s", pcap_strerror(errno
));
3877 *status
= PCAP_ERROR
;
3880 #ifdef PACKET_RESERVE
3881 len
= sizeof(tp_reserve
);
3882 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
3883 &tp_reserve
, &len
) < 0) {
3884 if (errno
!= ENOPROTOOPT
) {
3886 * ENOPROTOOPT means "kernel doesn't support
3887 * PACKET_RESERVE", in which case we fall back
3890 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3891 "getsockopt: %s", pcap_strerror(errno
));
3892 *status
= PCAP_ERROR
;
3895 tp_reserve
= 0; /* older kernel, reserve not supported */
3898 tp_reserve
= 0; /* older kernel, reserve not supported */
3900 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3901 /* XXX: in the kernel maclen is calculated from
3902 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3903 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3904 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3905 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3906 * but I see no way to get those sizes in userspace,
3907 * like for instance with an ifreq ioctl();
3908 * the best thing I've found so far is MAX_HEADER in
3909 * the kernel part of linux-2.6/include/linux/netdevice.h
3910 * which goes up to 128+48=176; since pcap-linux.c
3911 * defines a MAX_LINKHEADER_SIZE of 256 which is
3912 * greater than that, let's use it.. maybe is it even
3913 * large enough to directly replace macoff..
3915 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3916 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3917 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3918 * of netoff, which contradicts
3919 * linux-2.6/Documentation/networking/packet_mmap.txt
3921 * "- Gap, chosen so that packet data (Start+tp_net)
3922 * aligns to TPACKET_ALIGNMENT=16"
3924 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3925 * "CPUs often take a performance hit
3926 * when accessing unaligned memory locations"
3928 macoff
= netoff
- maclen
;
3929 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3930 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3933 #ifdef HAVE_TPACKET3
3935 /* The "frames" for this are actually buffers that
3936 * contain multiple variable-sized frames.
3938 * We pick a "frame" size of 128K to leave enough
3939 * room for at least one reasonably-sized packet
3940 * in the "frame". */
3941 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
3942 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3946 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3947 "Internal error: unknown TPACKET_ value %u",
3948 handlep
->tp_version
);
3949 *status
= PCAP_ERROR
;
3953 /* compute the minumum block size that will handle this frame.
3954 * The block has to be page size aligned.
3955 * The max block size allowed by the kernel is arch-dependent and
3956 * it's not explicitly checked here. */
3957 req
.tp_block_size
= getpagesize();
3958 while (req
.tp_block_size
< req
.tp_frame_size
)
3959 req
.tp_block_size
<<= 1;
3961 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3964 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3965 * so we check for PACKET_TIMESTAMP. We check for
3966 * linux/net_tstamp.h just in case a system somehow has
3967 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3970 * SIOCSHWTSTAMP was introduced in the patch that introduced
3971 * linux/net_tstamp.h, so we don't bother checking whether
3972 * SIOCSHWTSTAMP is defined (if your Linux system has
3973 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3974 * Linux system is badly broken).
3976 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3978 * If we were told to do so, ask the kernel and the driver
3979 * to use hardware timestamps.
3981 * Hardware timestamps are only supported with mmapped
3984 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3985 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3986 struct hwtstamp_config hwconfig
;
3991 * Ask for hardware time stamps on all packets,
3992 * including transmitted packets.
3994 memset(&hwconfig
, 0, sizeof(hwconfig
));
3995 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3996 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3998 memset(&ifr
, 0, sizeof(ifr
));
3999 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
4000 ifr
.ifr_data
= (void *)&hwconfig
;
4002 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
4007 * Treat this as an error, as the
4008 * user should try to run this
4009 * with the appropriate privileges -
4010 * and, if they can't, shouldn't
4011 * try requesting hardware time stamps.
4013 *status
= PCAP_ERROR_PERM_DENIED
;
4018 * Treat this as a warning, as the
4019 * only way to fix the warning is to
4020 * get an adapter that supports hardware
4021 * time stamps. We'll just fall back
4022 * on the standard host time stamps.
4024 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
4028 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4029 "SIOCSHWTSTAMP failed: %s",
4030 pcap_strerror(errno
));
4031 *status
= PCAP_ERROR
;
4036 * Well, that worked. Now specify the type of
4037 * hardware time stamp we want for this
4040 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
4042 * Hardware timestamp, synchronized
4043 * with the system clock.
4045 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
4048 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4049 * timestamp, not synchronized with the
4052 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
4054 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
4055 (void *)×ource
, sizeof(timesource
))) {
4056 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4057 "can't set PACKET_TIMESTAMP: %s",
4058 pcap_strerror(errno
));
4059 *status
= PCAP_ERROR
;
4064 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4066 /* ask the kernel to create the ring */
4068 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
4070 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4071 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
4073 #ifdef HAVE_TPACKET3
4074 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4075 req
.tp_retire_blk_tov
= (handlep
->timeout
>=0)?handlep
->timeout
:0;
4076 /* private data not used */
4077 req
.tp_sizeof_priv
= 0;
4078 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4079 req
.tp_feature_req_word
= 0;
4082 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4083 (void *) &req
, sizeof(req
))) {
4084 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
4086 * Memory failure; try to reduce the requested ring
4089 * We used to reduce this by half -- do 5% instead.
4090 * That may result in more iterations and a longer
4091 * startup, but the user will be much happier with
4092 * the resulting buffer size.
4094 if (req
.tp_frame_nr
< 20)
4095 req
.tp_frame_nr
-= 1;
4097 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
4100 if (errno
== ENOPROTOOPT
) {
4102 * We don't have ring buffer support in this kernel.
4106 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4107 "can't create rx ring on packet socket: %s",
4108 pcap_strerror(errno
));
4109 *status
= PCAP_ERROR
;
4113 /* memory map the rx ring */
4114 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
4115 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
4116 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
4117 if (handlep
->mmapbuf
== MAP_FAILED
) {
4118 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4119 "can't mmap rx ring: %s", pcap_strerror(errno
));
4121 /* clear the allocated ring on error*/
4122 destroy_ring(handle
);
4123 *status
= PCAP_ERROR
;
4127 /* allocate a ring for each frame header pointer*/
4128 handle
->cc
= req
.tp_frame_nr
;
4129 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
4130 if (!handle
->buffer
) {
4131 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4132 "can't allocate ring of frame headers: %s",
4133 pcap_strerror(errno
));
4135 destroy_ring(handle
);
4136 *status
= PCAP_ERROR
;
4140 /* fill the header ring with proper frame ptr*/
4142 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
4143 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
4144 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
4145 RING_GET_FRAME(handle
) = base
;
4146 base
+= req
.tp_frame_size
;
4150 handle
->bufsize
= req
.tp_frame_size
;
4155 /* free all ring related resources*/
4157 destroy_ring(pcap_t
*handle
)
4159 struct pcap_linux
*handlep
= handle
->priv
;
4161 /* tell the kernel to destroy the ring*/
4162 struct tpacket_req req
;
4163 memset(&req
, 0, sizeof(req
));
4164 /* do not test for setsockopt failure, as we can't recover from any error */
4165 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4166 (void *) &req
, sizeof(req
));
4168 /* if ring is mapped, unmap it*/
4169 if (handlep
->mmapbuf
) {
4170 /* do not test for mmap failure, as we can't recover from any error */
4171 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
4172 handlep
->mmapbuf
= NULL
;
4177 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4178 * for Linux mmapped capture.
4180 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4181 * data handed to the callback to be valid after the callback returns,
4182 * but pcap_read_linux_mmap() has to release that packet as soon as
4183 * the callback returns (otherwise, the kernel thinks there's still
4184 * at least one unprocessed packet available in the ring, so a select()
4185 * will immediately return indicating that there's data to process), so,
4186 * in the callback, we have to make a copy of the packet.
4188 * Yes, this means that, if the capture is using the ring buffer, using
4189 * pcap_next() or pcap_next_ex() requires more copies than using
4190 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4191 * pcap_next() or pcap_next_ex().
4194 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
4195 const u_char
*bytes
)
4197 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
4198 pcap_t
*handle
= sp
->pd
;
4199 struct pcap_linux
*handlep
= handle
->priv
;
4202 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
4203 *sp
->pkt
= handlep
->oneshot_buffer
;
4207 pcap_cleanup_linux_mmap( pcap_t
*handle
)
4209 struct pcap_linux
*handlep
= handle
->priv
;
4211 destroy_ring(handle
);
4212 if (handlep
->oneshot_buffer
!= NULL
) {
4213 free(handlep
->oneshot_buffer
);
4214 handlep
->oneshot_buffer
= NULL
;
4216 pcap_cleanup_linux(handle
);
4221 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
4223 struct pcap_linux
*handlep
= p
->priv
;
4225 /* use negative value of timeout to indicate non blocking ops */
4226 return (handlep
->timeout
<0);
4230 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
4232 struct pcap_linux
*handlep
= p
->priv
;
4235 * Set the file descriptor to non-blocking mode, as we use
4236 * it for sending packets.
4238 if (pcap_setnonblock_fd(p
, nonblock
, errbuf
) == -1)
4242 * Map each value to their corresponding negation to
4243 * preserve the timeout value provided with pcap_set_timeout.
4246 if (handlep
->timeout
>= 0) {
4248 * Indicate that we're switching to
4249 * non-blocking mode.
4251 handlep
->timeout
= ~handlep
->timeout
;
4254 if (handlep
->timeout
< 0) {
4255 handlep
->timeout
= ~handlep
->timeout
;
4261 static inline union thdr
*
4262 pcap_get_ring_frame(pcap_t
*handle
, int status
)
4264 struct pcap_linux
*handlep
= handle
->priv
;
4267 h
.raw
= RING_GET_FRAME(handle
);
4268 switch (handlep
->tp_version
) {
4270 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
4275 if (status
!= (h
.h1_64
->tp_status
? TP_STATUS_USER
:
4279 #ifdef HAVE_TPACKET2
4281 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
4286 #ifdef HAVE_TPACKET3
4288 if (status
!= (h
.h3
->hdr
.bh1
.block_status
? TP_STATUS_USER
:
4301 /* wait for frames availability.*/
4302 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4304 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
4305 struct pcap_linux
*handlep
= handle
->priv
;
4308 struct pollfd pollinfo
;
4311 pollinfo
.fd
= handle
->fd
;
4312 pollinfo
.events
= POLLIN
;
4314 if (handlep
->timeout
== 0) {
4315 #ifdef HAVE_TPACKET3
4317 * XXX - due to a set of (mis)features in the
4318 * TPACKET_V3 kernel code, blocking forever with
4319 * a TPACKET_V3 socket can, if few packets
4320 * are arriving and passing the socket filter,
4321 * cause most packets to be dropped. See
4322 * libpcap issue #335 for the full painful
4323 * story. The workaround is to have poll()
4324 * time out very quickly, so we grab the
4325 * frames handed to us, and return them to
4328 * If those issues are ever fixed, we might
4329 * want to check the kernel version and block
4330 * forever with TPACKET_V3 if we're running
4331 * with a kernel that has the fix.
4333 if (handlep
->tp_version
== TPACKET_V3
)
4334 timeout
= 1; /* don't block for very long */
4337 timeout
= -1; /* block forever */
4338 } else if (handlep
->timeout
> 0)
4339 timeout
= handlep
->timeout
; /* block for that amount of time */
4341 timeout
= 0; /* non-blocking mode - poll to pick up errors */
4343 ret
= poll(&pollinfo
, 1, timeout
);
4344 if (ret
< 0 && errno
!= EINTR
) {
4345 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4346 "can't poll on packet socket: %s",
4347 pcap_strerror(errno
));
4349 } else if (ret
> 0 &&
4350 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4352 * There's some indication other than
4353 * "you can read on this descriptor" on
4356 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
4357 snprintf(handle
->errbuf
,
4359 "Hangup on packet socket");
4362 if (pollinfo
.revents
& POLLERR
) {
4364 * A recv() will give us the
4365 * actual error code.
4367 * XXX - make the socket non-blocking?
4369 if (recv(handle
->fd
, &c
, sizeof c
,
4371 continue; /* what, no error? */
4372 if (errno
== ENETDOWN
) {
4374 * The device on which we're
4375 * capturing went away.
4377 * XXX - we should really return
4378 * PCAP_ERROR_IFACE_NOT_UP,
4379 * but pcap_dispatch() etc.
4380 * aren't defined to return
4383 snprintf(handle
->errbuf
,
4385 "The interface went down");
4387 snprintf(handle
->errbuf
,
4389 "Error condition on packet socket: %s",
4394 if (pollinfo
.revents
& POLLNVAL
) {
4395 snprintf(handle
->errbuf
,
4397 "Invalid polling request on packet socket");
4401 /* check for break loop condition on interrupted syscall*/
4402 if (handle
->break_loop
) {
4403 handle
->break_loop
= 0;
4404 return PCAP_ERROR_BREAK
;
4411 /* handle a single memory mapped packet */
4412 static int pcap_handle_packet_mmap(
4414 pcap_handler callback
,
4416 unsigned char *frame
,
4417 unsigned int tp_len
,
4418 unsigned int tp_mac
,
4419 unsigned int tp_snaplen
,
4420 unsigned int tp_sec
,
4421 unsigned int tp_usec
,
4422 int tp_vlan_tci_valid
,
4426 struct pcap_linux
*handlep
= handle
->priv
;
4428 struct sockaddr_ll
*sll
;
4429 struct pcap_pkthdr pcaphdr
;
4431 /* perform sanity check on internal offset. */
4432 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
4433 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4434 "corrupted frame on kernel ring mac "
4435 "offset %u + caplen %u > frame len %d",
4436 tp_mac
, tp_snaplen
, handle
->bufsize
);
4440 /* run filter on received packet
4441 * If the kernel filtering is enabled we need to run the
4442 * filter until all the frames present into the ring
4443 * at filter creation time are processed.
4444 * In this case, blocks_to_filter_in_userland is used
4445 * as a counter for the packet we need to filter.
4446 * Note: alternatively it could be possible to stop applying
4447 * the filter when the ring became empty, but it can possibly
4448 * happen a lot later... */
4449 bp
= frame
+ tp_mac
;
4451 /* if required build in place the sll header*/
4452 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
4453 if (handlep
->cooked
) {
4454 struct sll_header
*hdrp
;
4457 * The kernel should have left us with enough
4458 * space for an sll header; back up the packet
4459 * data pointer into that space, as that'll be
4460 * the beginning of the packet we pass to the
4466 * Let's make sure that's past the end of
4467 * the tpacket header, i.e. >=
4468 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4469 * don't step on the header when we construct
4472 if (bp
< (u_char
*)frame
+
4473 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4474 sizeof(struct sockaddr_ll
)) {
4475 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4476 "cooked-mode frame doesn't have room for sll header");
4481 * OK, that worked; construct the sll header.
4483 hdrp
= (struct sll_header
*)bp
;
4484 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4486 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4487 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4488 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4489 hdrp
->sll_protocol
= sll
->sll_protocol
;
4492 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
4493 struct bpf_aux_data aux_data
;
4495 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4496 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
4498 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
4499 tp_len
, tp_snaplen
, &aux_data
) == 0)
4503 if (!linux_check_direction(handle
, sll
))
4506 /* get required packet info from ring header */
4507 pcaphdr
.ts
.tv_sec
= tp_sec
;
4508 pcaphdr
.ts
.tv_usec
= tp_usec
;
4509 pcaphdr
.caplen
= tp_snaplen
;
4510 pcaphdr
.len
= tp_len
;
4512 /* if required build in place the sll header*/
4513 if (handlep
->cooked
) {
4514 /* update packet len */
4515 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4516 pcaphdr
.len
+= SLL_HDR_LEN
;
4519 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4520 if (tp_vlan_tci_valid
&&
4521 handlep
->vlan_offset
!= -1 &&
4522 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4524 struct vlan_tag
*tag
;
4527 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4529 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4530 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4531 tag
->vlan_tci
= htons(tp_vlan_tci
);
4533 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4534 pcaphdr
.len
+= VLAN_TAG_LEN
;
4539 * The only way to tell the kernel to cut off the
4540 * packet at a snapshot length is with a filter program;
4541 * if there's no filter program, the kernel won't cut
4544 * Trim the snapshot length to be no longer than the
4545 * specified snapshot length.
4547 if (pcaphdr
.caplen
> handle
->snapshot
)
4548 pcaphdr
.caplen
= handle
->snapshot
;
4550 /* pass the packet to the user */
4551 callback(user
, &pcaphdr
, bp
);
4557 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4560 struct pcap_linux
*handlep
= handle
->priv
;
4564 /* wait for frames availability.*/
4565 ret
= pcap_wait_for_frames_mmap(handle
);
4570 /* non-positive values of max_packets are used to require all
4571 * packets currently available in the ring */
4572 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4575 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4579 ret
= pcap_handle_packet_mmap(
4594 handlep
->packets_read
++;
4595 } else if (ret
< 0) {
4600 * Hand this block back to the kernel, and, if we're
4601 * counting blocks that need to be filtered in userland
4602 * after having been filtered by the kernel, count
4603 * the one we've just processed.
4605 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4606 if (handlep
->blocks_to_filter_in_userland
> 0) {
4607 handlep
->blocks_to_filter_in_userland
--;
4608 if (handlep
->blocks_to_filter_in_userland
== 0) {
4610 * No more blocks need to be filtered
4613 handlep
->filter_in_userland
= 0;
4618 if (++handle
->offset
>= handle
->cc
)
4621 /* check for break loop condition*/
4622 if (handle
->break_loop
) {
4623 handle
->break_loop
= 0;
4624 return PCAP_ERROR_BREAK
;
4631 pcap_read_linux_mmap_v1_64(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4634 struct pcap_linux
*handlep
= handle
->priv
;
4638 /* wait for frames availability.*/
4639 ret
= pcap_wait_for_frames_mmap(handle
);
4644 /* non-positive values of max_packets are used to require all
4645 * packets currently available in the ring */
4646 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4649 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4653 ret
= pcap_handle_packet_mmap(
4660 h
.h1_64
->tp_snaplen
,
4668 handlep
->packets_read
++;
4669 } else if (ret
< 0) {
4674 * Hand this block back to the kernel, and, if we're
4675 * counting blocks that need to be filtered in userland
4676 * after having been filtered by the kernel, count
4677 * the one we've just processed.
4679 h
.h1_64
->tp_status
= TP_STATUS_KERNEL
;
4680 if (handlep
->blocks_to_filter_in_userland
> 0) {
4681 handlep
->blocks_to_filter_in_userland
--;
4682 if (handlep
->blocks_to_filter_in_userland
== 0) {
4684 * No more blocks need to be filtered
4687 handlep
->filter_in_userland
= 0;
4692 if (++handle
->offset
>= handle
->cc
)
4695 /* check for break loop condition*/
4696 if (handle
->break_loop
) {
4697 handle
->break_loop
= 0;
4698 return PCAP_ERROR_BREAK
;
4704 #ifdef HAVE_TPACKET2
4706 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4709 struct pcap_linux
*handlep
= handle
->priv
;
4713 /* wait for frames availability.*/
4714 ret
= pcap_wait_for_frames_mmap(handle
);
4719 /* non-positive values of max_packets are used to require all
4720 * packets currently available in the ring */
4721 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4724 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4728 ret
= pcap_handle_packet_mmap(
4737 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4738 #if defined(TP_STATUS_VLAN_VALID)
4739 (h
.h2
->tp_vlan_tci
|| (h
.h2
->tp_status
& TP_STATUS_VLAN_VALID
)),
4741 h
.h2
->tp_vlan_tci
!= 0,
4744 VLAN_TPID(h
.h2
, h
.h2
));
4747 handlep
->packets_read
++;
4748 } else if (ret
< 0) {
4753 * Hand this block back to the kernel, and, if we're
4754 * counting blocks that need to be filtered in userland
4755 * after having been filtered by the kernel, count
4756 * the one we've just processed.
4758 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4759 if (handlep
->blocks_to_filter_in_userland
> 0) {
4760 handlep
->blocks_to_filter_in_userland
--;
4761 if (handlep
->blocks_to_filter_in_userland
== 0) {
4763 * No more blocks need to be filtered
4766 handlep
->filter_in_userland
= 0;
4771 if (++handle
->offset
>= handle
->cc
)
4774 /* check for break loop condition*/
4775 if (handle
->break_loop
) {
4776 handle
->break_loop
= 0;
4777 return PCAP_ERROR_BREAK
;
4782 #endif /* HAVE_TPACKET2 */
4784 #ifdef HAVE_TPACKET3
4786 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4789 struct pcap_linux
*handlep
= handle
->priv
;
4795 if (handlep
->current_packet
== NULL
) {
4796 /* wait for frames availability.*/
4797 ret
= pcap_wait_for_frames_mmap(handle
);
4802 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4804 if (pkts
== 0 && handlep
->timeout
== 0) {
4805 /* Block until we see a packet. */
4811 /* non-positive values of max_packets are used to require all
4812 * packets currently available in the ring */
4813 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4814 if (handlep
->current_packet
== NULL
) {
4815 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4819 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4820 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4822 int packets_to_read
= handlep
->packets_left
;
4824 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) && packets_to_read
> max_packets
) {
4825 packets_to_read
= max_packets
;
4828 while(packets_to_read
--) {
4829 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4830 ret
= pcap_handle_packet_mmap(
4834 handlep
->current_packet
,
4837 tp3_hdr
->tp_snaplen
,
4839 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4840 #if defined(TP_STATUS_VLAN_VALID)
4841 (tp3_hdr
->hv1
.tp_vlan_tci
|| (tp3_hdr
->tp_status
& TP_STATUS_VLAN_VALID
)),
4843 tp3_hdr
->hv1
.tp_vlan_tci
!= 0,
4845 tp3_hdr
->hv1
.tp_vlan_tci
,
4846 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
4849 handlep
->packets_read
++;
4850 } else if (ret
< 0) {
4851 handlep
->current_packet
= NULL
;
4854 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4855 handlep
->packets_left
--;
4858 if (handlep
->packets_left
<= 0) {
4860 * Hand this block back to the kernel, and, if
4861 * we're counting blocks that need to be
4862 * filtered in userland after having been
4863 * filtered by the kernel, count the one we've
4866 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
4867 if (handlep
->blocks_to_filter_in_userland
> 0) {
4868 handlep
->blocks_to_filter_in_userland
--;
4869 if (handlep
->blocks_to_filter_in_userland
== 0) {
4871 * No more blocks need to be filtered
4874 handlep
->filter_in_userland
= 0;
4879 if (++handle
->offset
>= handle
->cc
)
4882 handlep
->current_packet
= NULL
;
4885 /* check for break loop condition*/
4886 if (handle
->break_loop
) {
4887 handle
->break_loop
= 0;
4888 return PCAP_ERROR_BREAK
;
4891 if (pkts
== 0 && handlep
->timeout
== 0) {
4892 /* Block until we see a packet. */
4897 #endif /* HAVE_TPACKET3 */
4900 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
4902 struct pcap_linux
*handlep
= handle
->priv
;
4907 * Don't rewrite "ret" instructions; we don't need to, as
4908 * we're not reading packets with recvmsg(), and we don't
4909 * want to, as, by not rewriting them, the kernel can avoid
4910 * copying extra data.
4912 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
4917 * If we're filtering in userland, there's nothing to do;
4918 * the new filter will be used for the next packet.
4920 if (handlep
->filter_in_userland
)
4924 * We're filtering in the kernel; the packets present in
4925 * all blocks currently in the ring were already filtered
4926 * by the old filter, and so will need to be filtered in
4927 * userland by the new filter.
4929 * Get an upper bound for the number of such blocks; first,
4930 * walk the ring backward and count the free blocks.
4932 offset
= handle
->offset
;
4933 if (--handle
->offset
< 0)
4934 handle
->offset
= handle
->cc
- 1;
4935 for (n
=0; n
< handle
->cc
; ++n
) {
4936 if (--handle
->offset
< 0)
4937 handle
->offset
= handle
->cc
- 1;
4938 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
4943 * If we found free blocks, decrement the count of free
4944 * blocks by 1, just in case we lost a race with another
4945 * thread of control that was adding a packet while
4946 * we were counting and that had run the filter before
4949 * XXX - could there be more than one block added in
4952 * XXX - is there a way to avoid that race, e.g. somehow
4953 * wait for all packets that passed the old filter to
4954 * be added to the ring?
4959 /* be careful to not change current ring position */
4960 handle
->offset
= offset
;
4963 * Set the count of blocks worth of packets to filter
4964 * in userland to the total number of blocks in the
4965 * ring minus the number of free blocks we found, and
4966 * turn on userland filtering. (The count of blocks
4967 * worth of packets to filter in userland is guaranteed
4968 * not to be zero - n, above, couldn't be set to a
4969 * value > handle->cc, and if it were equal to
4970 * handle->cc, it wouldn't be zero, and thus would
4971 * be decremented to handle->cc - 1.)
4973 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4974 handlep
->filter_in_userland
= 1;
4978 #endif /* HAVE_PACKET_RING */
4981 #ifdef HAVE_PF_PACKET_SOCKETS
4983 * Return the index of the given device name. Fill ebuf and return
4987 iface_get_id(int fd
, const char *device
, char *ebuf
)
4991 memset(&ifr
, 0, sizeof(ifr
));
4992 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4994 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4995 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4996 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
5000 return ifr
.ifr_ifindex
;
5004 * Bind the socket associated with FD to the given device.
5005 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
5006 * or a PCAP_ERROR_ value on a hard error.
5009 iface_bind(int fd
, int ifindex
, char *ebuf
)
5011 struct sockaddr_ll sll
;
5013 socklen_t errlen
= sizeof(err
);
5015 memset(&sll
, 0, sizeof(sll
));
5016 sll
.sll_family
= AF_PACKET
;
5017 sll
.sll_ifindex
= ifindex
;
5018 sll
.sll_protocol
= htons(ETH_P_ALL
);
5020 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
5021 if (errno
== ENETDOWN
) {
5023 * Return a "network down" indication, so that
5024 * the application can report that rather than
5025 * saying we had a mysterious failure and
5026 * suggest that they report a problem to the
5027 * libpcap developers.
5029 return PCAP_ERROR_IFACE_NOT_UP
;
5031 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5032 "bind: %s", pcap_strerror(errno
));
5037 /* Any pending errors, e.g., network is down? */
5039 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5040 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5041 "getsockopt: %s", pcap_strerror(errno
));
5045 if (err
== ENETDOWN
) {
5047 * Return a "network down" indication, so that
5048 * the application can report that rather than
5049 * saying we had a mysterious failure and
5050 * suggest that they report a problem to the
5051 * libpcap developers.
5053 return PCAP_ERROR_IFACE_NOT_UP
;
5054 } else if (err
> 0) {
5055 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5056 "bind: %s", pcap_strerror(err
));
5063 #ifdef IW_MODE_MONITOR
5065 * Check whether the device supports the Wireless Extensions.
5066 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5067 * if the device doesn't even exist.
5070 has_wext(int sock_fd
, const char *device
, char *ebuf
)
5074 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5075 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5076 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
5078 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5079 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
5080 if (errno
== ENODEV
)
5081 return PCAP_ERROR_NO_SUCH_DEVICE
;
5086 * Per me si va ne la citta dolente,
5087 * Per me si va ne l'etterno dolore,
5089 * Lasciate ogne speranza, voi ch'intrate.
5091 * XXX - airmon-ng does special stuff with the Orinoco driver and the
5107 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5108 * on if it's not already on.
5110 * Returns 1 on success, 0 if we don't support the Wireless Extensions
5111 * on this device, or a PCAP_ERROR_ value if we do support them but
5112 * we weren't able to turn monitor mode on.
5115 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
5118 * XXX - at least some adapters require non-Wireless Extensions
5119 * mechanisms to turn monitor mode on.
5121 * Atheros cards might require that a separate "monitor virtual access
5122 * point" be created, with later versions of the madwifi driver.
5123 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
5124 * monitor -bssid", which apparently spits out a line "athN"
5125 * where "athN" is the monitor mode device. To leave monitor
5126 * mode, it destroys the monitor mode device.
5128 * Some Intel Centrino adapters might require private ioctls to get
5129 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5130 * configure a separate "rtapN" interface to capture in monitor
5131 * mode without preventing the adapter from operating normally.
5132 * (airmon-ng doesn't appear to use that, though.)
5134 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5135 * up, and if all drivers were converted to mac80211 drivers.
5137 * If interface {if} is a mac80211 driver, the file
5138 * /sys/class/net/{if}/phy80211 is a symlink to
5139 * /sys/class/ieee80211/{phydev}, for some {phydev}.
5141 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5142 * least, has a "wmaster0" device and a "wlan0" device; the
5143 * latter is the one with the IP address. Both show up in
5144 * "tcpdump -D" output. Capturing on the wmaster0 device
5145 * captures with 802.11 headers.
5147 * airmon-ng searches through /sys/class/net for devices named
5148 * monN, starting with mon0; as soon as one *doesn't* exist,
5149 * it chooses that as the monitor device name. If the "iw"
5150 * command exists, it does "iw dev {if} interface add {monif}
5151 * type monitor", where {monif} is the monitor device. It
5152 * then (sigh) sleeps .1 second, and then configures the
5153 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
5154 * is a file, it writes {mondev}, without a newline, to that file,
5155 * and again (sigh) sleeps .1 second, and then iwconfig's that
5156 * device into monitor mode and configures it up. Otherwise,
5157 * you can't do monitor mode.
5159 * All these devices are "glued" together by having the
5160 * /sys/class/net/{device}/phy80211 links pointing to the same
5161 * place, so, given a wmaster, wlan, or mon device, you can
5162 * find the other devices by looking for devices with
5163 * the same phy80211 link.
5165 * To turn monitor mode off, delete the monitor interface,
5166 * either with "iw dev {monif} interface del" or by sending
5167 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
5169 * Note: if you try to create a monitor device named "monN", and
5170 * there's already a "monN" device, it fails, as least with
5171 * the netlink interface (which is what iw uses), with a return
5172 * value of -ENFILE. (Return values are negative errnos.) We
5173 * could probably use that to find an unused device.
5175 struct pcap_linux
*handlep
= handle
->priv
;
5178 struct iw_priv_args
*priv
;
5179 monitor_type montype
;
5188 * Does this device *support* the Wireless Extensions?
5190 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
5192 return err
; /* either it doesn't or the device doesn't even exist */
5194 * Start out assuming we have no private extensions to control
5197 montype
= MONITOR_WEXT
;
5201 * Try to get all the Wireless Extensions private ioctls
5202 * supported by this device.
5204 * First, get the size of the buffer we need, by supplying no
5205 * buffer and a length of 0. If the device supports private
5206 * ioctls, it should return E2BIG, with ireq.u.data.length set
5207 * to the length we need. If it doesn't support them, it should
5208 * return EOPNOTSUPP.
5210 memset(&ireq
, 0, sizeof ireq
);
5211 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5212 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5213 ireq
.u
.data
.pointer
= (void *)args
;
5214 ireq
.u
.data
.length
= 0;
5215 ireq
.u
.data
.flags
= 0;
5216 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
5217 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5218 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
5222 if (errno
!= EOPNOTSUPP
) {
5224 * OK, it's not as if there are no private ioctls.
5226 if (errno
!= E2BIG
) {
5230 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5231 "%s: SIOCGIWPRIV: %s", device
,
5232 pcap_strerror(errno
));
5237 * OK, try to get the list of private ioctls.
5239 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
5241 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5242 "malloc: %s", pcap_strerror(errno
));
5245 ireq
.u
.data
.pointer
= (void *)priv
;
5246 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
5247 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5248 "%s: SIOCGIWPRIV: %s", device
,
5249 pcap_strerror(errno
));
5255 * Look for private ioctls to turn monitor mode on or, if
5256 * monitor mode is on, to set the header type.
5258 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
5259 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
5261 * Hostap driver, use this one.
5262 * Set monitor mode first.
5263 * You can set it to 0 to get DLT_IEEE80211,
5264 * 1 to get DLT_PRISM, 2 to get
5265 * DLT_IEEE80211_RADIO_AVS, and, with more
5266 * recent versions of the driver, 3 to get
5267 * DLT_IEEE80211_RADIO.
5269 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5271 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5273 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5275 montype
= MONITOR_HOSTAP
;
5279 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
5281 * Prism54 driver, use this one.
5282 * Set monitor mode first.
5283 * You can set it to 2 to get DLT_IEEE80211
5284 * or 3 or get DLT_PRISM.
5286 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5288 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5290 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5292 montype
= MONITOR_PRISM54
;
5296 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
5298 * RT2570 driver, use this one.
5299 * Do this after turning monitor mode on.
5300 * You can set it to 1 to get DLT_PRISM or 2
5301 * to get DLT_IEEE80211.
5303 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5305 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5307 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5309 montype
= MONITOR_RT2570
;
5313 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
5315 * RT73 driver, use this one.
5316 * Do this after turning monitor mode on.
5317 * Its argument is a *string*; you can
5318 * set it to "1" to get DLT_PRISM or "2"
5319 * to get DLT_IEEE80211.
5321 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
5323 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
5325 montype
= MONITOR_RT73
;
5329 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
5331 * One of the RTL8xxx drivers, use this one.
5332 * It can only be done after monitor mode
5333 * has been turned on. You can set it to 1
5334 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5336 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5338 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5340 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5342 montype
= MONITOR_RTL8XXX
;
5346 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
5348 * RT2500 or RT61 driver, use this one.
5349 * It has one one-byte parameter; set
5350 * u.data.length to 1 and u.data.pointer to
5351 * point to the parameter.
5352 * It doesn't itself turn monitor mode on.
5353 * You can set it to 1 to allow transmitting
5354 * in monitor mode(?) and get DLT_IEEE80211,
5355 * or set it to 0 to disallow transmitting in
5356 * monitor mode(?) and get DLT_PRISM.
5358 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5360 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
5362 montype
= MONITOR_RT2500
;
5366 if (strcmp(priv
[i
].name
, "monitor") == 0) {
5368 * Either ACX100 or hostap, use this one.
5369 * It turns monitor mode on.
5370 * If it takes two arguments, it's ACX100;
5371 * the first argument is 1 for DLT_PRISM
5372 * or 2 for DLT_IEEE80211, and the second
5373 * argument is the channel on which to
5374 * run. If it takes one argument, it's
5375 * HostAP, and the argument is 2 for
5376 * DLT_IEEE80211 and 3 for DLT_PRISM.
5378 * If we see this, we don't quit, as this
5379 * might be a version of the hostap driver
5380 * that also supports "monitor_type".
5382 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5384 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5386 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5389 montype
= MONITOR_PRISM
;
5394 montype
= MONITOR_ACX100
;
5407 * XXX - ipw3945? islism?
5413 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5414 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5415 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
5417 * We probably won't be able to set the mode, either.
5419 return PCAP_ERROR_RFMON_NOTSUP
;
5423 * Is it currently in monitor mode?
5425 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
5427 * Yes. Just leave things as they are.
5428 * We don't offer multiple link-layer types, as
5429 * changing the link-layer type out from under
5430 * somebody else capturing in monitor mode would
5431 * be considered rude.
5436 * No. We have to put the adapter into rfmon mode.
5440 * If we haven't already done so, arrange to have
5441 * "pcap_close_all()" called when we exit.
5443 if (!pcap_do_addexit(handle
)) {
5445 * "atexit()" failed; don't put the interface
5446 * in rfmon mode, just give up.
5448 return PCAP_ERROR_RFMON_NOTSUP
;
5452 * Save the old mode.
5454 handlep
->oldmode
= ireq
.u
.mode
;
5457 * Put the adapter in rfmon mode. How we do this depends
5458 * on whether we have a special private ioctl or not.
5460 if (montype
== MONITOR_PRISM
) {
5462 * We have the "monitor" private ioctl, but none of
5463 * the other private ioctls. Use this, and select
5466 * If it fails, just fall back on SIOCSIWMODE.
5468 memset(&ireq
, 0, sizeof ireq
);
5469 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5470 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5471 ireq
.u
.data
.length
= 1; /* 1 argument */
5472 args
[0] = 3; /* request Prism header */
5473 memcpy(ireq
.u
.name
, args
, sizeof (int));
5474 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
5477 * Note that we have to put the old mode back
5478 * when we close the device.
5480 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5483 * Add this to the list of pcaps to close
5486 pcap_add_to_pcaps_to_close(handle
);
5492 * Failure. Fall back on SIOCSIWMODE.
5497 * First, take the interface down if it's up; otherwise, we
5500 memset(&ifr
, 0, sizeof(ifr
));
5501 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5502 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5503 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5504 "%s: Can't get flags: %s", device
, strerror(errno
));
5508 if (ifr
.ifr_flags
& IFF_UP
) {
5509 oldflags
= ifr
.ifr_flags
;
5510 ifr
.ifr_flags
&= ~IFF_UP
;
5511 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5512 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5513 "%s: Can't set flags: %s", device
, strerror(errno
));
5519 * Then turn monitor mode on.
5521 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5522 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5523 ireq
.u
.mode
= IW_MODE_MONITOR
;
5524 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
5526 * Scientist, you've failed.
5527 * Bring the interface back up if we shut it down.
5529 ifr
.ifr_flags
= oldflags
;
5530 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5531 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5532 "%s: Can't set flags: %s", device
, strerror(errno
));
5535 return PCAP_ERROR_RFMON_NOTSUP
;
5539 * XXX - airmon-ng does "iwconfig {if} key off" after setting
5540 * monitor mode and setting the channel, and then does
5545 * Now select the appropriate radio header.
5551 * We don't have any private ioctl to set the header.
5555 case MONITOR_HOSTAP
:
5557 * Try to select the radiotap header.
5559 memset(&ireq
, 0, sizeof ireq
);
5560 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5561 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5562 args
[0] = 3; /* request radiotap header */
5563 memcpy(ireq
.u
.name
, args
, sizeof (int));
5564 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5565 break; /* success */
5568 * That failed. Try to select the AVS header.
5570 memset(&ireq
, 0, sizeof ireq
);
5571 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5572 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5573 args
[0] = 2; /* request AVS header */
5574 memcpy(ireq
.u
.name
, args
, sizeof (int));
5575 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5576 break; /* success */
5579 * That failed. Try to select the Prism header.
5581 memset(&ireq
, 0, sizeof ireq
);
5582 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5583 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5584 args
[0] = 1; /* request Prism header */
5585 memcpy(ireq
.u
.name
, args
, sizeof (int));
5586 ioctl(sock_fd
, cmd
, &ireq
);
5591 * The private ioctl failed.
5595 case MONITOR_PRISM54
:
5597 * Select the Prism header.
5599 memset(&ireq
, 0, sizeof ireq
);
5600 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5601 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5602 args
[0] = 3; /* request Prism header */
5603 memcpy(ireq
.u
.name
, args
, sizeof (int));
5604 ioctl(sock_fd
, cmd
, &ireq
);
5607 case MONITOR_ACX100
:
5609 * Get the current channel.
5611 memset(&ireq
, 0, sizeof ireq
);
5612 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5613 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5614 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
5615 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5616 "%s: SIOCGIWFREQ: %s", device
,
5617 pcap_strerror(errno
));
5620 channel
= ireq
.u
.freq
.m
;
5623 * Select the Prism header, and set the channel to the
5626 memset(&ireq
, 0, sizeof ireq
);
5627 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5628 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5629 args
[0] = 1; /* request Prism header */
5630 args
[1] = channel
; /* set channel */
5631 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
5632 ioctl(sock_fd
, cmd
, &ireq
);
5635 case MONITOR_RT2500
:
5637 * Disallow transmission - that turns on the
5640 memset(&ireq
, 0, sizeof ireq
);
5641 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5642 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5643 args
[0] = 0; /* disallow transmitting */
5644 memcpy(ireq
.u
.name
, args
, sizeof (int));
5645 ioctl(sock_fd
, cmd
, &ireq
);
5648 case MONITOR_RT2570
:
5650 * Force the Prism header.
5652 memset(&ireq
, 0, sizeof ireq
);
5653 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5654 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5655 args
[0] = 1; /* request Prism header */
5656 memcpy(ireq
.u
.name
, args
, sizeof (int));
5657 ioctl(sock_fd
, cmd
, &ireq
);
5662 * Force the Prism header.
5664 memset(&ireq
, 0, sizeof ireq
);
5665 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5666 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5667 ireq
.u
.data
.length
= 1; /* 1 argument */
5668 ireq
.u
.data
.pointer
= "1";
5669 ireq
.u
.data
.flags
= 0;
5670 ioctl(sock_fd
, cmd
, &ireq
);
5673 case MONITOR_RTL8XXX
:
5675 * Force the Prism header.
5677 memset(&ireq
, 0, sizeof ireq
);
5678 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5679 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5680 args
[0] = 1; /* request Prism header */
5681 memcpy(ireq
.u
.name
, args
, sizeof (int));
5682 ioctl(sock_fd
, cmd
, &ireq
);
5687 * Now bring the interface back up if we brought it down.
5689 if (oldflags
!= 0) {
5690 ifr
.ifr_flags
= oldflags
;
5691 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5692 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5693 "%s: Can't set flags: %s", device
, strerror(errno
));
5696 * At least try to restore the old mode on the
5699 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
5701 * Scientist, you've failed.
5704 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5705 "Please adjust manually.\n",
5713 * Note that we have to put the old mode back when we
5716 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5719 * Add this to the list of pcaps to close when we exit.
5721 pcap_add_to_pcaps_to_close(handle
);
5725 #endif /* IW_MODE_MONITOR */
5728 * Try various mechanisms to enter monitor mode.
5731 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
5733 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5738 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
5740 return ret
; /* error attempting to do so */
5742 return 1; /* success */
5743 #endif /* HAVE_LIBNL */
5745 #ifdef IW_MODE_MONITOR
5746 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
5748 return ret
; /* error attempting to do so */
5750 return 1; /* success */
5751 #endif /* IW_MODE_MONITOR */
5754 * Either none of the mechanisms we know about work or none
5755 * of those mechanisms are available, so we can't do monitor
5761 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5763 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5765 static const struct {
5766 int soft_timestamping_val
;
5767 int pcap_tstamp_val
;
5768 } sof_ts_type_map
[3] = {
5769 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5770 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5771 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5773 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5776 iface_set_default_ts_types(pcap_t
*handle
)
5780 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5781 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5782 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5783 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5786 #ifdef ETHTOOL_GET_TS_INFO
5788 * Get a list of time stamping capabilities.
5791 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
)
5795 struct ethtool_ts_info info
;
5800 * This doesn't apply to the "any" device; you have to ask
5801 * specific devices for their capabilities, so just default
5802 * to saying we support all of them.
5804 if (strcmp(handle
->opt
.source
, "any") == 0) {
5805 iface_set_default_ts_types(handle
);
5810 * Create a socket from which to fetch time stamping capabilities.
5812 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
5814 (void)snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5815 "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO): %s", pcap_strerror(errno
));
5819 memset(&ifr
, 0, sizeof(ifr
));
5820 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5821 memset(&info
, 0, sizeof(info
));
5822 info
.cmd
= ETHTOOL_GET_TS_INFO
;
5823 ifr
.ifr_data
= (caddr_t
)&info
;
5824 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
5826 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
5828 * OK, let's just return all the possible time
5831 iface_set_default_ts_types(handle
);
5834 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5835 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: %s", handle
->opt
.source
,
5842 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5843 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
5846 handle
->tstamp_type_count
= num_ts_types
;
5847 if (num_ts_types
!= 0) {
5848 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
5849 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5850 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
5851 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5856 handle
->tstamp_type_list
= NULL
;
5860 #else /* ETHTOOL_GET_TS_INFO */
5862 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf _U_
)
5865 * We don't have an ioctl to use to ask what's supported,
5866 * so say we support everything.
5868 iface_set_default_ts_types(handle
);
5871 #endif /* ETHTOOL_GET_TS_INFO */
5873 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5875 #ifdef HAVE_PACKET_RING
5877 * Find out if we have any form of fragmentation/reassembly offloading.
5879 * We do so using SIOCETHTOOL checking for various types of offloading;
5880 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5881 * of the types of offloading, there's nothing we can do to check, so
5882 * we just say "no, we don't".
5884 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5886 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
5889 struct ethtool_value eval
;
5891 memset(&ifr
, 0, sizeof(ifr
));
5892 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5895 ifr
.ifr_data
= (caddr_t
)&eval
;
5896 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5897 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
5899 * OK, let's just return 0, which, in our
5900 * case, either means "no, what we're asking
5901 * about is not enabled" or "all the flags
5902 * are clear (i.e., nothing is enabled)".
5906 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5907 "%s: SIOCETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
5908 cmdname
, strerror(errno
));
5915 iface_get_offload(pcap_t
*handle
)
5920 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
5924 return 1; /* TCP segmentation offloading on */
5928 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
5932 return 1; /* UDP fragmentation offloading on */
5937 * XXX - will this cause large unsegmented packets to be
5938 * handed to PF_PACKET sockets on transmission? If not,
5939 * this need not be checked.
5941 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
5945 return 1; /* generic segmentation offloading on */
5948 #ifdef ETHTOOL_GFLAGS
5949 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
5952 if (ret
& ETH_FLAG_LRO
)
5953 return 1; /* large receive offloading on */
5958 * XXX - will this cause large reassembled packets to be
5959 * handed to PF_PACKET sockets on receipt? If not,
5960 * this need not be checked.
5962 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
5966 return 1; /* generic (large) receive offloading on */
5971 #else /* SIOCETHTOOL */
5973 iface_get_offload(pcap_t
*handle _U_
)
5976 * XXX - do we need to get this information if we don't
5977 * have the ethtool ioctls? If so, how do we do that?
5981 #endif /* SIOCETHTOOL */
5983 #endif /* HAVE_PACKET_RING */
5985 #endif /* HAVE_PF_PACKET_SOCKETS */
5987 /* ===== Functions to interface to the older kernels ================== */
5990 * Try to open a packet socket using the old kernel interface.
5991 * Returns 1 on success and a PCAP_ERROR_ value on an error.
5994 activate_old(pcap_t
*handle
)
5996 struct pcap_linux
*handlep
= handle
->priv
;
5999 const char *device
= handle
->opt
.source
;
6000 struct utsname utsname
;
6003 /* Open the socket */
6005 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
6006 if (handle
->fd
== -1) {
6007 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6008 "socket: %s", pcap_strerror(errno
));
6009 if (errno
== EPERM
|| errno
== EACCES
) {
6011 * You don't have permission to open the
6014 return PCAP_ERROR_PERM_DENIED
;
6023 /* It worked - we are using the old interface */
6024 handlep
->sock_packet
= 1;
6026 /* ...which means we get the link-layer header. */
6027 handlep
->cooked
= 0;
6029 /* Bind to the given device */
6031 if (strcmp(device
, "any") == 0) {
6032 strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
6036 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
6040 * Try to get the link-layer type.
6042 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
6047 * Try to find the DLT_ type corresponding to that
6050 map_arphrd_to_dlt(handle
, handle
->fd
, arptype
, device
, 0);
6051 if (handle
->linktype
== -1) {
6052 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6053 "unknown arptype %d", arptype
);
6057 /* Go to promisc mode if requested */
6059 if (handle
->opt
.promisc
) {
6060 memset(&ifr
, 0, sizeof(ifr
));
6061 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6062 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6063 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6064 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
6067 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
6069 * Promiscuous mode isn't currently on,
6070 * so turn it on, and remember that
6071 * we should turn it off when the
6076 * If we haven't already done so, arrange
6077 * to have "pcap_close_all()" called when
6080 if (!pcap_do_addexit(handle
)) {
6082 * "atexit()" failed; don't put
6083 * the interface in promiscuous
6084 * mode, just give up.
6089 ifr
.ifr_flags
|= IFF_PROMISC
;
6090 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6091 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6093 pcap_strerror(errno
));
6096 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
6099 * Add this to the list of pcaps
6100 * to close when we exit.
6102 pcap_add_to_pcaps_to_close(handle
);
6107 * Compute the buffer size.
6109 * We're using SOCK_PACKET, so this might be a 2.0[.x]
6110 * kernel, and might require special handling - check.
6112 if (uname(&utsname
) < 0 ||
6113 strncmp(utsname
.release
, "2.0", 3) == 0) {
6115 * Either we couldn't find out what kernel release
6116 * this is, or it's a 2.0[.x] kernel.
6118 * In the 2.0[.x] kernel, a "recvfrom()" on
6119 * a SOCK_PACKET socket, with MSG_TRUNC set, will
6120 * return the number of bytes read, so if we pass
6121 * a length based on the snapshot length, it'll
6122 * return the number of bytes from the packet
6123 * copied to userland, not the actual length
6126 * This means that, for example, the IP dissector
6127 * in tcpdump will get handed a packet length less
6128 * than the length in the IP header, and will
6129 * complain about "truncated-ip".
6131 * So we don't bother trying to copy from the
6132 * kernel only the bytes in which we're interested,
6133 * but instead copy them all, just as the older
6134 * versions of libpcap for Linux did.
6136 * The buffer therefore needs to be big enough to
6137 * hold the largest packet we can get from this
6138 * device. Unfortunately, we can't get the MRU
6139 * of the network; we can only get the MTU. The
6140 * MTU may be too small, in which case a packet larger
6141 * than the buffer size will be truncated *and* we
6142 * won't get the actual packet size.
6144 * However, if the snapshot length is larger than
6145 * the buffer size based on the MTU, we use the
6146 * snapshot length as the buffer size, instead;
6147 * this means that with a sufficiently large snapshot
6148 * length we won't artificially truncate packets
6149 * to the MTU-based size.
6151 * This mess just one of many problems with packet
6152 * capture on 2.0[.x] kernels; you really want a
6153 * 2.2[.x] or later kernel if you want packet capture
6156 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
6159 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
6160 if (handle
->bufsize
< handle
->snapshot
)
6161 handle
->bufsize
= handle
->snapshot
;
6164 * This is a 2.2[.x] or later kernel.
6166 * We can safely pass "recvfrom()" a byte count
6167 * based on the snapshot length.
6169 handle
->bufsize
= handle
->snapshot
;
6173 * Default value for offset to align link-layer payload
6174 * on a 4-byte boundary.
6179 * SOCK_PACKET sockets don't supply information from
6180 * stripped VLAN tags.
6182 handlep
->vlan_offset
= -1; /* unknown */
6188 * Bind the socket associated with FD to the given device using the
6189 * interface of the old kernels.
6192 iface_bind_old(int fd
, const char *device
, char *ebuf
)
6194 struct sockaddr saddr
;
6196 socklen_t errlen
= sizeof(err
);
6198 memset(&saddr
, 0, sizeof(saddr
));
6199 strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
6200 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
6201 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6202 "bind: %s", pcap_strerror(errno
));
6206 /* Any pending errors, e.g., network is down? */
6208 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
6209 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6210 "getsockopt: %s", pcap_strerror(errno
));
6215 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6216 "bind: %s", pcap_strerror(err
));
6224 /* ===== System calls available on all supported kernels ============== */
6227 * Query the kernel for the MTU of the given interface.
6230 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
6235 return BIGGER_THAN_ALL_MTUS
;
6237 memset(&ifr
, 0, sizeof(ifr
));
6238 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6240 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
6241 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6242 "SIOCGIFMTU: %s", pcap_strerror(errno
));
6250 * Get the hardware type of the given interface as ARPHRD_xxx constant.
6253 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
6257 memset(&ifr
, 0, sizeof(ifr
));
6258 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6260 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
6261 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6262 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
6263 if (errno
== ENODEV
) {
6267 return PCAP_ERROR_NO_SUCH_DEVICE
;
6272 return ifr
.ifr_hwaddr
.sa_family
;
6275 #ifdef SO_ATTACH_FILTER
6277 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
6279 struct pcap_linux
*handlep
= handle
->priv
;
6282 register struct bpf_insn
*p
;
6287 * Make a copy of the filter, and modify that copy if
6290 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
6291 len
= handle
->fcode
.bf_len
;
6292 f
= (struct bpf_insn
*)malloc(prog_size
);
6294 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6295 "malloc: %s", pcap_strerror(errno
));
6298 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
6300 fcode
->filter
= (struct sock_filter
*) f
;
6302 for (i
= 0; i
< len
; ++i
) {
6305 * What type of instruction is this?
6307 switch (BPF_CLASS(p
->code
)) {
6311 * It's a return instruction; are we capturing
6312 * in memory-mapped mode?
6316 * No; is the snapshot length a constant,
6317 * rather than the contents of the
6320 if (BPF_MODE(p
->code
) == BPF_K
) {
6322 * Yes - if the value to be returned,
6323 * i.e. the snapshot length, is
6324 * anything other than 0, make it
6325 * MAXIMUM_SNAPLEN, so that the packet
6326 * is truncated by "recvfrom()",
6327 * not by the filter.
6329 * XXX - there's nothing we can
6330 * easily do if it's getting the
6331 * value from the accumulator; we'd
6332 * have to insert code to force
6333 * non-zero values to be
6337 p
->k
= MAXIMUM_SNAPLEN
;
6345 * It's a load instruction; is it loading
6348 switch (BPF_MODE(p
->code
)) {
6354 * Yes; are we in cooked mode?
6356 if (handlep
->cooked
) {
6358 * Yes, so we need to fix this
6361 if (fix_offset(p
) < 0) {
6363 * We failed to do so.
6364 * Return 0, so our caller
6365 * knows to punt to userland.
6375 return 1; /* we succeeded */
6379 fix_offset(struct bpf_insn
*p
)
6382 * What's the offset?
6384 if (p
->k
>= SLL_HDR_LEN
) {
6386 * It's within the link-layer payload; that starts at an
6387 * offset of 0, as far as the kernel packet filter is
6388 * concerned, so subtract the length of the link-layer
6391 p
->k
-= SLL_HDR_LEN
;
6392 } else if (p
->k
== 0) {
6394 * It's the packet type field; map it to the special magic
6395 * kernel offset for that field.
6397 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6398 } else if (p
->k
== 14) {
6400 * It's the protocol field; map it to the special magic
6401 * kernel offset for that field.
6403 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6404 } else if ((bpf_int32
)(p
->k
) > 0) {
6406 * It's within the header, but it's not one of those
6407 * fields; we can't do that in the kernel, so punt
6416 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
6418 int total_filter_on
= 0;
6424 * The socket filter code doesn't discard all packets queued
6425 * up on the socket when the filter is changed; this means
6426 * that packets that don't match the new filter may show up
6427 * after the new filter is put onto the socket, if those
6428 * packets haven't yet been read.
6430 * This means, for example, that if you do a tcpdump capture
6431 * with a filter, the first few packets in the capture might
6432 * be packets that wouldn't have passed the filter.
6434 * We therefore discard all packets queued up on the socket
6435 * when setting a kernel filter. (This isn't an issue for
6436 * userland filters, as the userland filtering is done after
6437 * packets are queued up.)
6439 * To flush those packets, we put the socket in read-only mode,
6440 * and read packets from the socket until there are no more to
6443 * In order to keep that from being an infinite loop - i.e.,
6444 * to keep more packets from arriving while we're draining
6445 * the queue - we put the "total filter", which is a filter
6446 * that rejects all packets, onto the socket before draining
6449 * This code deliberately ignores any errors, so that you may
6450 * get bogus packets if an error occurs, rather than having
6451 * the filtering done in userland even if it could have been
6452 * done in the kernel.
6454 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6455 &total_fcode
, sizeof(total_fcode
)) == 0) {
6459 * Note that we've put the total filter onto the socket.
6461 total_filter_on
= 1;
6464 * Save the socket's current mode, and put it in
6465 * non-blocking mode; we drain it by reading packets
6466 * until we get an error (which is normally a
6467 * "nothing more to be read" error).
6469 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6470 if (save_mode
== -1) {
6471 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6472 "can't get FD flags when changing filter: %s",
6473 pcap_strerror(errno
));
6476 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
6477 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6478 "can't set nonblocking mode when changing filter: %s",
6479 pcap_strerror(errno
));
6482 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
6485 if (save_errno
!= EAGAIN
) {
6489 * If we can't restore the mode or reset the
6490 * kernel filter, there's nothing we can do.
6492 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
6493 (void)reset_kernel_filter(handle
);
6494 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6495 "recv failed when changing filter: %s",
6496 pcap_strerror(save_errno
));
6499 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
6500 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6501 "can't restore FD flags when changing filter: %s",
6502 pcap_strerror(save_errno
));
6508 * Now attach the new filter.
6510 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6511 fcode
, sizeof(*fcode
));
6512 if (ret
== -1 && total_filter_on
) {
6514 * Well, we couldn't set that filter on the socket,
6515 * but we could set the total filter on the socket.
6517 * This could, for example, mean that the filter was
6518 * too big to put into the kernel, so we'll have to
6519 * filter in userland; in any case, we'll be doing
6520 * filtering in userland, so we need to remove the
6521 * total filter so we see packets.
6526 * If this fails, we're really screwed; we have the
6527 * total filter on the socket, and it won't come off.
6528 * Report it as a fatal error.
6530 if (reset_kernel_filter(handle
) == -1) {
6531 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6532 "can't remove kernel total filter: %s",
6533 pcap_strerror(errno
));
6534 return -2; /* fatal error */
6543 reset_kernel_filter(pcap_t
*handle
)
6546 * setsockopt() barfs unless it get a dummy parameter.
6547 * valgrind whines unless the value is initialized,
6548 * as it has no idea that setsockopt() ignores its
6553 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6554 &dummy
, sizeof(dummy
));