2 * pcap-linux.c: Packet capture interface to the Linux kernel
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
23 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
29 * Added TPACKET_V3 support
30 * Gabor Tatarka <gabor.tatarka@ericsson.com>
32 * based on previous works of:
33 * Simon Patarin <patarin@cs.unibo.it>
34 * Phil Wood <cpw@lanl.gov>
36 * Monitor-mode support for mac80211 includes code taken from the iw
37 * command; the copyright notice for that code is
39 * Copyright (c) 2007, 2008 Johannes Berg
40 * Copyright (c) 2007 Andy Lutomirski
41 * Copyright (c) 2007 Mike Kershaw
42 * Copyright (c) 2008 Gábor Stefanik
44 * All rights reserved.
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
49 * 1. Redistributions of source code must retain the above copyright
50 * notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 * notice, this list of conditions and the following disclaimer in the
53 * documentation and/or other materials provided with the distribution.
54 * 3. The name of the author may not be used to endorse or promote products
55 * derived from this software without specific prior written permission.
57 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
58 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
60 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
61 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
62 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
63 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
64 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
65 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
71 * Known problems with 2.0[.x] kernels:
73 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
74 * if we use PF_PACKET, we can filter out the transmitted version
75 * of the packet by using data in the "sockaddr_ll" returned by
76 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
77 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
78 * "sockaddr_pkt" which doesn't give us enough information to let
81 * - We have to set the interface's IFF_PROMISC flag ourselves, if
82 * we're to run in promiscuous mode, which means we have to turn
83 * it off ourselves when we're done; the kernel doesn't keep track
84 * of how many sockets are listening promiscuously, which means
85 * it won't get turned off automatically when no sockets are
86 * listening promiscuously. We catch "pcap_close()" and, for
87 * interfaces we put into promiscuous mode, take them out of
88 * promiscuous mode - which isn't necessarily the right thing to
89 * do, if another socket also requested promiscuous mode between
90 * the time when we opened the socket and the time when we close
93 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
94 * return the amount of data that you could have read, rather than
95 * the amount that was returned, so we can't just allocate a buffer
96 * whose size is the snapshot length and pass the snapshot length
97 * as the byte count, and also pass MSG_TRUNC, so that the return
98 * value tells us how long the packet was on the wire.
100 * This means that, if we want to get the actual size of the packet,
101 * so we can return it in the "len" field of the packet header,
102 * we have to read the entire packet, not just the part that fits
103 * within the snapshot length, and thus waste CPU time copying data
104 * from the kernel that our caller won't see.
106 * We have to get the actual size, and supply it in "len", because
107 * otherwise, the IP dissector in tcpdump, for example, will complain
108 * about "truncated-ip", as the packet will appear to have been
109 * shorter, on the wire, than the IP header said it should have been.
127 #include <sys/stat.h>
128 #include <sys/socket.h>
129 #include <sys/ioctl.h>
130 #include <sys/utsname.h>
131 #include <sys/mman.h>
132 #include <linux/if.h>
133 #include <linux/if_packet.h>
134 #include <linux/sockios.h>
135 #include <netinet/in.h>
136 #include <linux/if_ether.h>
137 #include <net/if_arp.h>
141 #include "pcap-int.h"
142 #include "pcap/sll.h"
143 #include "pcap/vlan.h"
146 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
147 * sockets rather than SOCK_PACKET sockets.
149 * To use them, we include <linux/if_packet.h> rather than
150 * <netpacket/packet.h>; we do so because
152 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
153 * later kernels and libc5, and don't provide a <netpacket/packet.h>
156 * not all versions of glibc2 have a <netpacket/packet.h> file
157 * that defines stuff needed for some of the 2.4-or-later-kernel
158 * features, so if the system has a 2.4 or later kernel, we
159 * still can't use those features.
161 * We're already including a number of other <linux/XXX.h> headers, and
162 * this code is Linux-specific (no other OS has PF_PACKET sockets as
163 * a raw packet capture mechanism), so it's not as if you gain any
164 * useful portability by using <netpacket/packet.h>
166 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
167 * isn't defined? It only defines one data structure in 2.0.x, so
168 * it shouldn't cause any problems.
171 # include <linux/if_packet.h>
174 * On at least some Linux distributions (for example, Red Hat 5.2),
175 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
176 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
177 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
178 * the PACKET_xxx stuff.
180 * So we check whether PACKET_HOST is defined, and assume that we have
181 * PF_PACKET sockets only if it is defined.
184 # define HAVE_PF_PACKET_SOCKETS
185 # ifdef PACKET_AUXDATA
186 # define HAVE_PACKET_AUXDATA
187 # endif /* PACKET_AUXDATA */
188 # endif /* PACKET_HOST */
191 /* check for memory mapped access avaibility. We assume every needed
192 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
193 * uses many ring related structs and macros */
194 # ifdef PCAP_SUPPORT_PACKET_RING
195 # ifdef TPACKET_HDRLEN
196 # define HAVE_PACKET_RING
197 # ifdef TPACKET3_HDRLEN
198 # define HAVE_TPACKET3
199 # endif /* TPACKET3_HDRLEN */
200 # ifdef TPACKET2_HDRLEN
201 # define HAVE_TPACKET2
202 # else /* TPACKET2_HDRLEN */
203 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
204 # endif /* TPACKET2_HDRLEN */
205 # endif /* TPACKET_HDRLEN */
206 # endif /* PCAP_SUPPORT_PACKET_RING */
207 #endif /* PF_PACKET */
209 #ifdef SO_ATTACH_FILTER
210 #include <linux/types.h>
211 #include <linux/filter.h>
214 #ifdef HAVE_LINUX_NET_TSTAMP_H
215 #include <linux/net_tstamp.h>
218 #ifdef HAVE_LINUX_SOCKIOS_H
219 #include <linux/sockios.h>
222 #ifdef HAVE_LINUX_IF_BONDING_H
223 #include <linux/if_bonding.h>
227 * Got Wireless Extensions?
229 #ifdef HAVE_LINUX_WIRELESS_H
230 #include <linux/wireless.h>
231 #endif /* HAVE_LINUX_WIRELESS_H */
237 #include <linux/nl80211.h>
239 #include <netlink/genl/genl.h>
240 #include <netlink/genl/family.h>
241 #include <netlink/genl/ctrl.h>
242 #include <netlink/msg.h>
243 #include <netlink/attr.h>
244 #endif /* HAVE_LIBNL */
247 * Got ethtool support?
249 #ifdef HAVE_LINUX_ETHTOOL_H
250 #include <linux/ethtool.h>
253 #ifndef HAVE_SOCKLEN_T
254 typedef int socklen_t
;
259 * This is being compiled on a system that lacks MSG_TRUNC; define it
260 * with the value it has in the 2.2 and later kernels, so that, on
261 * those kernels, when we pass it in the flags argument to "recvfrom()"
262 * we're passing the right value and thus get the MSG_TRUNC behavior
263 * we want. (We don't get that behavior on 2.0[.x] kernels, because
264 * they didn't support MSG_TRUNC.)
266 #define MSG_TRUNC 0x20
271 * This is being compiled on a system that lacks SOL_PACKET; define it
272 * with the value it has in the 2.2 and later kernels, so that we can
273 * set promiscuous mode in the good modern way rather than the old
274 * 2.0-kernel crappy way.
276 #define SOL_PACKET 263
279 #define MAX_LINKHEADER_SIZE 256
282 * When capturing on all interfaces we use this as the buffer size.
283 * Should be bigger then all MTUs that occur in real life.
284 * 64kB should be enough for now.
286 #define BIGGER_THAN_ALL_MTUS (64*1024)
289 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
292 u_int packets_read
; /* count of packets read with recvfrom() */
293 long proc_dropped
; /* packets reported dropped by /proc/net/dev */
294 struct pcap_stat stat
;
296 char *device
; /* device name */
297 int filter_in_userland
; /* must filter in userland */
298 int blocks_to_filter_in_userland
;
299 int must_do_on_close
; /* stuff we must do when we close */
300 int timeout
; /* timeout for buffering */
301 int sock_packet
; /* using Linux 2.0 compatible interface */
302 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
303 int ifindex
; /* interface index of device we're bound to */
304 int lo_ifindex
; /* interface index of the loopback device */
305 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
306 char *mondevice
; /* mac80211 monitor device we created */
307 u_char
*mmapbuf
; /* memory-mapped region pointer */
308 size_t mmapbuflen
; /* size of region */
309 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
310 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
311 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
312 u_char
*oneshot_buffer
; /* buffer for copy of packet */
313 int poll_timeout
; /* timeout to use in poll() */
315 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
316 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
321 * Stuff to do when we close.
323 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
324 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
325 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
328 * Prototypes for internal functions and methods.
330 static void map_arphrd_to_dlt(pcap_t
*, int, int, const char *, int);
331 #ifdef HAVE_PF_PACKET_SOCKETS
332 static short int map_packet_type_to_sll_type(short int);
334 static int pcap_activate_linux(pcap_t
*);
335 static int activate_old(pcap_t
*);
336 static int activate_new(pcap_t
*);
337 static int activate_mmap(pcap_t
*, int *);
338 static int pcap_can_set_rfmon_linux(pcap_t
*);
339 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
340 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
341 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
342 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
343 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
344 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
345 static int pcap_set_datalink_linux(pcap_t
*, int);
346 static void pcap_cleanup_linux(pcap_t
*);
349 * This is what the header structure looks like in a 64-bit kernel;
350 * we use this, rather than struct tpacket_hdr, if we're using
351 * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
353 struct tpacket_hdr_64
{
356 unsigned int tp_snaplen
;
357 unsigned short tp_mac
;
358 unsigned short tp_net
;
360 unsigned int tp_usec
;
364 * We use this internally as the tpacket version for TPACKET_V1 in
365 * 32-bit code on a 64-bit kernel.
367 #define TPACKET_V1_64 99
370 struct tpacket_hdr
*h1
;
371 struct tpacket_hdr_64
*h1_64
;
373 struct tpacket2_hdr
*h2
;
376 struct tpacket_block_desc
*h3
;
381 #ifdef HAVE_PACKET_RING
382 #define RING_GET_FRAME_AT(h, offset) (((union thdr **)h->buffer)[(offset)])
383 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
385 static void destroy_ring(pcap_t
*handle
);
386 static int create_ring(pcap_t
*handle
, int *status
);
387 static int prepare_tpacket_socket(pcap_t
*handle
);
388 static void pcap_cleanup_linux_mmap(pcap_t
*);
389 static int pcap_read_linux_mmap_v1(pcap_t
*, int, pcap_handler
, u_char
*);
390 static int pcap_read_linux_mmap_v1_64(pcap_t
*, int, pcap_handler
, u_char
*);
392 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
395 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
397 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
398 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
399 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
400 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
401 const u_char
*bytes
);
404 #ifdef TP_STATUS_VLAN_TPID_VALID
405 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
407 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
411 * Wrap some ioctl calls
413 #ifdef HAVE_PF_PACKET_SOCKETS
414 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
415 #endif /* HAVE_PF_PACKET_SOCKETS */
416 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
417 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
418 #ifdef HAVE_PF_PACKET_SOCKETS
419 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
420 #ifdef IW_MODE_MONITOR
421 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
422 #endif /* IW_MODE_MONITOR */
423 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
425 #endif /* HAVE_PF_PACKET_SOCKETS */
426 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
427 static int iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
);
429 #ifdef HAVE_PACKET_RING
430 static int iface_get_offload(pcap_t
*handle
);
432 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
434 #ifdef SO_ATTACH_FILTER
435 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
437 static int fix_offset(struct bpf_insn
*p
);
438 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
439 static int reset_kernel_filter(pcap_t
*handle
);
441 static struct sock_filter total_insn
442 = BPF_STMT(BPF_RET
| BPF_K
, 0);
443 static struct sock_fprog total_fcode
444 = { 1, &total_insn
};
445 #endif /* SO_ATTACH_FILTER */
448 pcap_create_interface(const char *device
, char *ebuf
)
452 handle
= pcap_create_common(device
, ebuf
, sizeof (struct pcap_linux
));
456 handle
->activate_op
= pcap_activate_linux
;
457 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
459 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
461 * See what time stamp types we support.
463 if (iface_ethtool_get_ts_info(handle
, ebuf
) == -1) {
469 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
471 * We claim that we support microsecond and nanosecond time
474 * XXX - with adapter-supplied time stamps, can we choose
475 * microsecond or nanosecond time stamps on arbitrary
478 handle
->tstamp_precision_count
= 2;
479 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
480 if (handle
->tstamp_precision_list
== NULL
) {
481 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
482 pcap_strerror(errno
));
486 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
487 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
488 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
495 * If interface {if} is a mac80211 driver, the file
496 * /sys/class/net/{if}/phy80211 is a symlink to
497 * /sys/class/ieee80211/{phydev}, for some {phydev}.
499 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
500 * least, has a "wmaster0" device and a "wlan0" device; the
501 * latter is the one with the IP address. Both show up in
502 * "tcpdump -D" output. Capturing on the wmaster0 device
503 * captures with 802.11 headers.
505 * airmon-ng searches through /sys/class/net for devices named
506 * monN, starting with mon0; as soon as one *doesn't* exist,
507 * it chooses that as the monitor device name. If the "iw"
508 * command exists, it does "iw dev {if} interface add {monif}
509 * type monitor", where {monif} is the monitor device. It
510 * then (sigh) sleeps .1 second, and then configures the
511 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
512 * is a file, it writes {mondev}, without a newline, to that file,
513 * and again (sigh) sleeps .1 second, and then iwconfig's that
514 * device into monitor mode and configures it up. Otherwise,
515 * you can't do monitor mode.
517 * All these devices are "glued" together by having the
518 * /sys/class/net/{device}/phy80211 links pointing to the same
519 * place, so, given a wmaster, wlan, or mon device, you can
520 * find the other devices by looking for devices with
521 * the same phy80211 link.
523 * To turn monitor mode off, delete the monitor interface,
524 * either with "iw dev {monif} interface del" or by sending
525 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
527 * Note: if you try to create a monitor device named "monN", and
528 * there's already a "monN" device, it fails, as least with
529 * the netlink interface (which is what iw uses), with a return
530 * value of -ENFILE. (Return values are negative errnos.) We
531 * could probably use that to find an unused device.
533 * Yes, you can have multiple monitor devices for a given
538 * Is this a mac80211 device? If so, fill in the physical device path and
539 * return 1; if not, return 0. On an error, fill in handle->errbuf and
543 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
544 size_t phydev_max_pathlen
)
550 * Generate the path string for the symlink to the physical device.
552 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
553 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
554 "%s: Can't generate path name string for /sys/class/net device",
558 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
559 if (bytes_read
== -1) {
560 if (errno
== ENOENT
|| errno
== EINVAL
) {
562 * Doesn't exist, or not a symlink; assume that
563 * means it's not a mac80211 device.
568 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
569 "%s: Can't readlink %s: %s", device
, pathstr
,
575 phydev_path
[bytes_read
] = '\0';
579 #ifdef HAVE_LIBNL_SOCKETS
580 #define get_nl_errmsg nl_geterror
582 /* libnl 2.x compatibility code */
584 #define nl_sock nl_handle
586 static inline struct nl_handle
*
587 nl_socket_alloc(void)
589 return nl_handle_alloc();
593 nl_socket_free(struct nl_handle
*h
)
595 nl_handle_destroy(h
);
598 #define get_nl_errmsg strerror
601 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
603 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
609 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
610 #endif /* !HAVE_LIBNL_SOCKETS */
612 struct nl80211_state
{
613 struct nl_sock
*nl_sock
;
614 struct nl_cache
*nl_cache
;
615 struct genl_family
*nl80211
;
619 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
623 state
->nl_sock
= nl_socket_alloc();
624 if (!state
->nl_sock
) {
625 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
626 "%s: failed to allocate netlink handle", device
);
630 if (genl_connect(state
->nl_sock
)) {
631 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
632 "%s: failed to connect to generic netlink", device
);
633 goto out_handle_destroy
;
636 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
638 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
639 "%s: failed to allocate generic netlink cache: %s",
640 device
, get_nl_errmsg(-err
));
641 goto out_handle_destroy
;
644 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
645 if (!state
->nl80211
) {
646 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
647 "%s: nl80211 not found", device
);
654 nl_cache_free(state
->nl_cache
);
656 nl_socket_free(state
->nl_sock
);
661 nl80211_cleanup(struct nl80211_state
*state
)
663 genl_family_put(state
->nl80211
);
664 nl_cache_free(state
->nl_cache
);
665 nl_socket_free(state
->nl_sock
);
669 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
670 const char *device
, const char *mondevice
)
676 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
682 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
683 "%s: failed to allocate netlink msg", device
);
687 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
688 0, NL80211_CMD_NEW_INTERFACE
, 0);
689 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
690 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
691 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
693 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
695 #if defined HAVE_LIBNL_NLE
696 if (err
== -NLE_FAILURE
) {
698 if (err
== -ENFILE
) {
701 * Device not available; our caller should just
702 * keep trying. (libnl 2.x maps ENFILE to
703 * NLE_FAILURE; it can also map other errors
704 * to that, but there's not much we can do
711 * Real failure, not just "that device is not
714 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
715 "%s: nl_send_auto_complete failed adding %s interface: %s",
716 device
, mondevice
, get_nl_errmsg(-err
));
721 err
= nl_wait_for_ack(state
->nl_sock
);
723 #if defined HAVE_LIBNL_NLE
724 if (err
== -NLE_FAILURE
) {
726 if (err
== -ENFILE
) {
729 * Device not available; our caller should just
730 * keep trying. (libnl 2.x maps ENFILE to
731 * NLE_FAILURE; it can also map other errors
732 * to that, but there's not much we can do
739 * Real failure, not just "that device is not
742 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
743 "%s: nl_wait_for_ack failed adding %s interface: %s",
744 device
, mondevice
, get_nl_errmsg(-err
));
756 * Try to remember the monitor device.
758 handlep
->mondevice
= strdup(mondevice
);
759 if (handlep
->mondevice
== NULL
) {
760 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
761 pcap_strerror(errno
));
763 * Get rid of the monitor device.
765 del_mon_if(handle
, sock_fd
, state
, device
, >mondevice
);
771 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
772 "%s: nl_put failed adding %s interface",
779 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
780 const char *device
, const char *mondevice
)
786 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
792 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
793 "%s: failed to allocate netlink msg", device
);
797 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
798 0, NL80211_CMD_DEL_INTERFACE
, 0);
799 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
801 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
803 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
804 "%s: nl_send_auto_complete failed deleting %s interface: %s",
805 device
, mondevice
, get_nl_errmsg(-err
));
809 err
= nl_wait_for_ack(state
->nl_sock
);
811 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
812 "%s: nl_wait_for_ack failed adding %s interface: %s",
813 device
, mondevice
, get_nl_errmsg(-err
));
825 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
826 "%s: nl_put failed deleting %s interface",
833 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
835 struct pcap_linux
*handlep
= handle
->priv
;
837 char phydev_path
[PATH_MAX
+1];
838 struct nl80211_state nlstate
;
843 * Is this a mac80211 device?
845 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
847 return ret
; /* error */
849 return 0; /* no error, but not mac80211 device */
852 * XXX - is this already a monN device?
854 * Is that determined by old Wireless Extensions ioctls?
858 * OK, it's apparently a mac80211 device.
859 * Try to find an unused monN device for it.
861 ret
= nl80211_init(handle
, &nlstate
, device
);
864 for (n
= 0; n
< UINT_MAX
; n
++) {
868 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
870 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
871 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
874 * Success. We don't clean up the libnl state
875 * yet, as we'll be using it later.
881 * Hard failure. Just return ret; handle->errbuf
882 * has already been set.
884 nl80211_cleanup(&nlstate
);
889 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
890 "%s: No free monN interfaces", device
);
891 nl80211_cleanup(&nlstate
);
898 * Sleep for .1 seconds.
901 delay
.tv_nsec
= 500000000;
902 nanosleep(&delay
, NULL
);
906 * If we haven't already done so, arrange to have
907 * "pcap_close_all()" called when we exit.
909 if (!pcap_do_addexit(handle
)) {
911 * "atexit()" failed; don't put the interface
912 * in rfmon mode, just give up.
914 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
915 "%s: atexit failed", device
);
916 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
918 nl80211_cleanup(&nlstate
);
923 * Now configure the monitor interface up.
925 memset(&ifr
, 0, sizeof(ifr
));
926 strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
927 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
928 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
929 "%s: Can't get flags for %s: %s", device
,
930 handlep
->mondevice
, strerror(errno
));
931 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
933 nl80211_cleanup(&nlstate
);
936 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
937 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
938 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
939 "%s: Can't set flags for %s: %s", device
,
940 handlep
->mondevice
, strerror(errno
));
941 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
943 nl80211_cleanup(&nlstate
);
948 * Success. Clean up the libnl state.
950 nl80211_cleanup(&nlstate
);
953 * Note that we have to delete the monitor device when we close
956 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
959 * Add this to the list of pcaps to close when we exit.
961 pcap_add_to_pcaps_to_close(handle
);
965 #endif /* HAVE_LIBNL */
967 #ifdef IW_MODE_MONITOR
969 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
970 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
971 * will fail with ENODEV if we try to do them on a bonding device,
972 * making us return a "no such device" indication rather than just
973 * saying "no Wireless Extensions".
975 * So we check for bonding devices, if we can, before trying those
976 * ioctls, by trying a bonding device information query ioctl to see
977 * whether it succeeds.
980 is_bonding_device(int fd
, const char *device
)
982 #if defined(HAVE_LINUX_IF_BONDING_H) && \
983 (defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY))
987 memset(&ifr
, 0, sizeof ifr
);
988 strlcpy(ifr
.ifr_name
, device
, sizeof ifr
.ifr_name
);
989 memset(&ifb
, 0, sizeof ifb
);
990 ifr
.ifr_data
= (caddr_t
)&ifb
;
991 #ifdef SIOCBONDINFOQUERY
992 if (ioctl(fd
, SIOCBONDINFOQUERY
, &ifr
) == 0)
993 #else /* SIOCBONDINFOQUERY */
994 if (ioctl(fd
, BOND_INFO_QUERY_OLD
, &ifr
) == 0)
995 #endif /* SIOCBONDINFOQUERY */
996 return 1; /* success, so it's a bonding device */
997 #endif /* defined(HAVE_LINUX_IF_BONDING_H) && \
998 (defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY)) */
1000 return 0; /* no, it's not a bonding device */
1002 #endif /* IW_MODE_MONITOR */
1005 pcap_can_set_rfmon_linux(pcap_t
*handle
)
1008 char phydev_path
[PATH_MAX
+1];
1011 #ifdef IW_MODE_MONITOR
1016 if (strcmp(handle
->opt
.source
, "any") == 0) {
1018 * Monitor mode makes no sense on the "any" device.
1025 * Bleah. There doesn't seem to be a way to ask a mac80211
1026 * device, through libnl, whether it supports monitor mode;
1027 * we'll just check whether the device appears to be a
1028 * mac80211 device and, if so, assume the device supports
1031 * wmaster devices don't appear to support the Wireless
1032 * Extensions, but we can create a mon device for a
1033 * wmaster device, so we don't bother checking whether
1034 * a mac80211 device supports the Wireless Extensions.
1036 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
1039 return ret
; /* error */
1041 return 1; /* mac80211 device */
1044 #ifdef IW_MODE_MONITOR
1046 * Bleah. There doesn't appear to be an ioctl to use to ask
1047 * whether a device supports monitor mode; we'll just do
1048 * SIOCGIWMODE and, if it succeeds, assume the device supports
1051 * Open a socket on which to attempt to get the mode.
1052 * (We assume that if we have Wireless Extensions support
1053 * we also have PF_PACKET support.)
1055 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
1056 if (sock_fd
== -1) {
1057 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1058 "socket: %s", pcap_strerror(errno
));
1062 if (is_bonding_device(sock_fd
, handle
->opt
.source
)) {
1063 /* It's a bonding device, so don't even try. */
1069 * Attempt to get the current mode.
1071 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
1072 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1073 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1075 * Well, we got the mode; assume we can set it.
1080 if (errno
== ENODEV
) {
1081 /* The device doesn't even exist. */
1082 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1083 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
1085 return PCAP_ERROR_NO_SUCH_DEVICE
;
1093 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1095 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1096 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1098 * Or can we get them in binary form from netlink?
1101 linux_if_drops(const char * if_name
)
1106 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1107 long int dropped_pkts
= 0;
1109 file
= fopen("/proc/net/dev", "r");
1113 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1115 /* search for 'bytes' -- if its in there, then
1116 that means we need to grab the fourth field. otherwise
1117 grab the third field. */
1118 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1120 field_to_convert
= 4;
1124 /* find iface and make sure it actually matches -- space before the name and : after it */
1125 if ((bufptr
= strstr(buffer
, if_name
)) &&
1126 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1127 *(bufptr
+ if_name_sz
) == ':')
1129 bufptr
= bufptr
+ if_name_sz
+ 1;
1131 /* grab the nth field from it */
1132 while( --field_to_convert
&& *bufptr
!= '\0')
1134 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1135 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1138 /* get rid of any final spaces */
1139 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1141 if (*bufptr
!= '\0')
1142 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1149 return dropped_pkts
;
1154 * With older kernels promiscuous mode is kind of interesting because we
1155 * have to reset the interface before exiting. The problem can't really
1156 * be solved without some daemon taking care of managing usage counts.
1157 * If we put the interface into promiscuous mode, we set a flag indicating
1158 * that we must take it out of that mode when the interface is closed,
1159 * and, when closing the interface, if that flag is set we take it out
1160 * of promiscuous mode.
1162 * Even with newer kernels, we have the same issue with rfmon mode.
1165 static void pcap_cleanup_linux( pcap_t
*handle
)
1167 struct pcap_linux
*handlep
= handle
->priv
;
1170 struct nl80211_state nlstate
;
1172 #endif /* HAVE_LIBNL */
1173 #ifdef IW_MODE_MONITOR
1176 #endif /* IW_MODE_MONITOR */
1178 if (handlep
->must_do_on_close
!= 0) {
1180 * There's something we have to do when closing this
1183 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1185 * We put the interface into promiscuous mode;
1186 * take it out of promiscuous mode.
1188 * XXX - if somebody else wants it in promiscuous
1189 * mode, this code cannot know that, so it'll take
1190 * it out of promiscuous mode. That's not fixable
1191 * in 2.0[.x] kernels.
1193 memset(&ifr
, 0, sizeof(ifr
));
1194 strlcpy(ifr
.ifr_name
, handlep
->device
,
1195 sizeof(ifr
.ifr_name
));
1196 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1198 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1199 "Please adjust manually.\n"
1200 "Hint: This can't happen with Linux >= 2.2.0.\n",
1201 handlep
->device
, strerror(errno
));
1203 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1205 * Promiscuous mode is currently on;
1208 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1209 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1212 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1213 "Please adjust manually.\n"
1214 "Hint: This can't happen with Linux >= 2.2.0.\n",
1223 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1224 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1226 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1227 handlep
->device
, handlep
->mondevice
);
1228 nl80211_cleanup(&nlstate
);
1232 "Can't delete monitor interface %s (%s).\n"
1233 "Please delete manually.\n",
1234 handlep
->mondevice
, handle
->errbuf
);
1237 #endif /* HAVE_LIBNL */
1239 #ifdef IW_MODE_MONITOR
1240 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1242 * We put the interface into rfmon mode;
1243 * take it out of rfmon mode.
1245 * XXX - if somebody else wants it in rfmon
1246 * mode, this code cannot know that, so it'll take
1247 * it out of rfmon mode.
1251 * First, take the interface down if it's up;
1252 * otherwise, we might get EBUSY.
1253 * If we get errors, just drive on and print
1254 * a warning if we can't restore the mode.
1257 memset(&ifr
, 0, sizeof(ifr
));
1258 strlcpy(ifr
.ifr_name
, handlep
->device
,
1259 sizeof(ifr
.ifr_name
));
1260 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1261 if (ifr
.ifr_flags
& IFF_UP
) {
1262 oldflags
= ifr
.ifr_flags
;
1263 ifr
.ifr_flags
&= ~IFF_UP
;
1264 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1265 oldflags
= 0; /* didn't set, don't restore */
1270 * Now restore the mode.
1272 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1273 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1274 ireq
.u
.mode
= handlep
->oldmode
;
1275 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1277 * Scientist, you've failed.
1280 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1281 "Please adjust manually.\n",
1282 handlep
->device
, strerror(errno
));
1286 * Now bring the interface back up if we brought
1289 if (oldflags
!= 0) {
1290 ifr
.ifr_flags
= oldflags
;
1291 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1293 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1294 "Please adjust manually.\n",
1295 handlep
->device
, strerror(errno
));
1299 #endif /* IW_MODE_MONITOR */
1302 * Take this pcap out of the list of pcaps for which we
1303 * have to take the interface out of some mode.
1305 pcap_remove_from_pcaps_to_close(handle
);
1308 if (handlep
->mondevice
!= NULL
) {
1309 free(handlep
->mondevice
);
1310 handlep
->mondevice
= NULL
;
1312 if (handlep
->device
!= NULL
) {
1313 free(handlep
->device
);
1314 handlep
->device
= NULL
;
1316 pcap_cleanup_live_common(handle
);
1320 * Set the timeout to be used in poll() with memory-mapped packet capture.
1323 set_poll_timeout(struct pcap_linux
*handlep
)
1325 #ifdef HAVE_TPACKET3
1326 struct utsname utsname
;
1327 char *version_component
, *endp
;
1329 int broken_tpacket_v3
= 1;
1332 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1333 * around which we have to work. Determine if we have those
1336 if (uname(&utsname
) == 0) {
1338 * 3.19 is the first release with a fixed version of
1339 * TPACKET_V3. We treat anything before that as
1340 * not haveing a fixed version; that may really mean
1341 * it has *no* version.
1343 version_component
= utsname
.release
;
1344 major
= strtol(version_component
, &endp
, 10);
1345 if (endp
!= version_component
&& *endp
== '.') {
1347 * OK, that was a valid major version.
1348 * Get the minor version.
1350 version_component
= endp
+ 1;
1351 minor
= strtol(version_component
, &endp
, 10);
1352 if (endp
!= version_component
&&
1353 (*endp
== '.' || *endp
== '\0')) {
1355 * OK, that was a valid minor version.
1356 * Is this 3.19 or newer?
1358 if (major
>= 4 || (major
== 3 && minor
>= 19)) {
1359 /* Yes. TPACKET_V3 works correctly. */
1360 broken_tpacket_v3
= 0;
1366 if (handlep
->timeout
== 0) {
1367 #ifdef HAVE_TPACKET3
1369 * XXX - due to a set of (mis)features in the TPACKET_V3
1370 * kernel code prior to the 3.19 kernel, blocking forever
1371 * with a TPACKET_V3 socket can, if few packets are
1372 * arriving and passing the socket filter, cause most
1373 * packets to be dropped. See libpcap issue #335 for the
1374 * full painful story.
1376 * The workaround is to have poll() time out very quickly,
1377 * so we grab the frames handed to us, and return them to
1380 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1381 handlep
->poll_timeout
= 1; /* don't block for very long */
1384 handlep
->poll_timeout
= -1; /* block forever */
1385 } else if (handlep
->timeout
> 0) {
1386 #ifdef HAVE_TPACKET3
1388 * For TPACKET_V3, the timeout is handled by the kernel,
1389 * so block forever; that way, we don't get extra timeouts.
1390 * Don't do that if we have a broken TPACKET_V3, though.
1392 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1393 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1396 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1399 * Non-blocking mode; we call poll() to pick up error
1400 * indications, but we don't want it to wait for
1403 handlep
->poll_timeout
= 0;
1408 * Get a handle for a live capture from the given device. You can
1409 * pass NULL as device to get all packages (without link level
1410 * information of course). If you pass 1 as promisc the interface
1411 * will be set to promiscous mode (XXX: I think this usage should
1412 * be deprecated and functions be added to select that later allow
1413 * modification of that values -- Torsten).
1416 pcap_activate_linux(pcap_t
*handle
)
1418 struct pcap_linux
*handlep
= handle
->priv
;
1424 device
= handle
->opt
.source
;
1427 * Make sure the name we were handed will fit into the ioctls we
1428 * might perform on the device; if not, return a "No such device"
1429 * indication, as the Linux kernel shouldn't support creating
1430 * a device whose name won't fit into those ioctls.
1432 * "Will fit" means "will fit, complete with a null terminator",
1433 * so if the length, which does *not* include the null terminator,
1434 * is greater than *or equal to* the size of the field into which
1435 * we'll be copying it, that won't fit.
1437 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1438 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1442 handle
->inject_op
= pcap_inject_linux
;
1443 handle
->setfilter_op
= pcap_setfilter_linux
;
1444 handle
->setdirection_op
= pcap_setdirection_linux
;
1445 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1446 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1447 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1448 handle
->cleanup_op
= pcap_cleanup_linux
;
1449 handle
->read_op
= pcap_read_linux
;
1450 handle
->stats_op
= pcap_stats_linux
;
1453 * The "any" device is a special device which causes us not
1454 * to bind to a particular device and thus to look at all
1457 if (strcmp(device
, "any") == 0) {
1458 if (handle
->opt
.promisc
) {
1459 handle
->opt
.promisc
= 0;
1460 /* Just a warning. */
1461 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1462 "Promiscuous mode not supported on the \"any\" device");
1463 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1467 handlep
->device
= strdup(device
);
1468 if (handlep
->device
== NULL
) {
1469 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1470 pcap_strerror(errno
) );
1474 /* copy timeout value */
1475 handlep
->timeout
= handle
->opt
.timeout
;
1478 * If we're in promiscuous mode, then we probably want
1479 * to see when the interface drops packets too, so get an
1480 * initial count from /proc/net/dev
1482 if (handle
->opt
.promisc
)
1483 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1486 * Current Linux kernels use the protocol family PF_PACKET to
1487 * allow direct access to all packets on the network while
1488 * older kernels had a special socket type SOCK_PACKET to
1489 * implement this feature.
1490 * While this old implementation is kind of obsolete we need
1491 * to be compatible with older kernels for a while so we are
1492 * trying both methods with the newer method preferred.
1494 ret
= activate_new(handle
);
1497 * Fatal error with the new way; just fail.
1498 * ret has the error return; if it's PCAP_ERROR,
1499 * handle->errbuf has been set appropriately.
1507 * Try to use memory-mapped access.
1509 switch (activate_mmap(handle
, &status
)) {
1513 * We succeeded. status has been
1514 * set to the status to return,
1515 * which might be 0, or might be
1516 * a PCAP_WARNING_ value.
1518 * Set the timeout to use in poll() before
1521 set_poll_timeout(handlep
);
1526 * Kernel doesn't support it - just continue
1527 * with non-memory-mapped access.
1533 * We failed to set up to use it, or the kernel
1534 * supports it, but we failed to enable it.
1535 * ret has been set to the error status to
1536 * return and, if it's PCAP_ERROR, handle->errbuf
1537 * contains the error message.
1543 else if (ret
== 0) {
1544 /* Non-fatal error; try old way */
1545 if ((ret
= activate_old(handle
)) != 1) {
1547 * Both methods to open the packet socket failed.
1548 * Tidy up and report our failure (handle->errbuf
1549 * is expected to be set by the functions above).
1557 * We set up the socket, but not with memory-mapped access.
1559 if (handle
->opt
.buffer_size
!= 0) {
1561 * Set the socket buffer size to the specified value.
1563 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1564 &handle
->opt
.buffer_size
,
1565 sizeof(handle
->opt
.buffer_size
)) == -1) {
1566 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1567 "SO_RCVBUF: %s", pcap_strerror(errno
));
1568 status
= PCAP_ERROR
;
1573 /* Allocate the buffer */
1575 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1576 if (!handle
->buffer
) {
1577 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1578 "malloc: %s", pcap_strerror(errno
));
1579 status
= PCAP_ERROR
;
1584 * "handle->fd" is a socket, so "select()" and "poll()"
1585 * should work on it.
1587 handle
->selectable_fd
= handle
->fd
;
1592 pcap_cleanup_linux(handle
);
1597 * Read at most max_packets from the capture stream and call the callback
1598 * for each of them. Returns the number of packets handled or -1 if an
1602 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1605 * Currently, on Linux only one packet is delivered per read,
1608 return pcap_read_packet(handle
, callback
, user
);
1612 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1614 handle
->linktype
= dlt
;
1619 * linux_check_direction()
1621 * Do checks based on packet direction.
1624 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1626 struct pcap_linux
*handlep
= handle
->priv
;
1628 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1631 * If this is from the loopback device, reject it;
1632 * we'll see the packet as an incoming packet as well,
1633 * and we don't want to see it twice.
1635 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1639 * If the user only wants incoming packets, reject it.
1641 if (handle
->direction
== PCAP_D_IN
)
1646 * If the user only wants outgoing packets, reject it.
1648 if (handle
->direction
== PCAP_D_OUT
)
1655 * Read a packet from the socket calling the handler provided by
1656 * the user. Returns the number of packets received or -1 if an
1660 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1662 struct pcap_linux
*handlep
= handle
->priv
;
1665 #ifdef HAVE_PF_PACKET_SOCKETS
1666 struct sockaddr_ll from
;
1667 struct sll_header
*hdrp
;
1669 struct sockaddr from
;
1671 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1674 struct cmsghdr
*cmsg
;
1676 struct cmsghdr cmsg
;
1677 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1679 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1681 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1682 int packet_len
, caplen
;
1683 struct pcap_pkthdr pcap_header
;
1685 struct bpf_aux_data aux_data
;
1686 #ifdef HAVE_PF_PACKET_SOCKETS
1688 * If this is a cooked device, leave extra room for a
1689 * fake packet header.
1691 if (handlep
->cooked
)
1692 offset
= SLL_HDR_LEN
;
1697 * This system doesn't have PF_PACKET sockets, so it doesn't
1698 * support cooked devices.
1704 * Receive a single packet from the kernel.
1705 * We ignore EINTR, as that might just be due to a signal
1706 * being delivered - if the signal should interrupt the
1707 * loop, the signal handler should call pcap_breakloop()
1708 * to set handle->break_loop (we ignore it on other
1709 * platforms as well).
1710 * We also ignore ENETDOWN, so that we can continue to
1711 * capture traffic if the interface goes down and comes
1712 * back up again; comments in the kernel indicate that
1713 * we'll just block waiting for packets if we try to
1714 * receive from a socket that delivered ENETDOWN, and,
1715 * if we're using a memory-mapped buffer, we won't even
1716 * get notified of "network down" events.
1718 bp
= (u_char
*)handle
->buffer
+ handle
->offset
;
1720 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1721 msg
.msg_name
= &from
;
1722 msg
.msg_namelen
= sizeof(from
);
1725 msg
.msg_control
= &cmsg_buf
;
1726 msg
.msg_controllen
= sizeof(cmsg_buf
);
1729 iov
.iov_len
= handle
->bufsize
- offset
;
1730 iov
.iov_base
= bp
+ offset
;
1731 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1735 * Has "pcap_breakloop()" been called?
1737 if (handle
->break_loop
) {
1739 * Yes - clear the flag that indicates that it has,
1740 * and return PCAP_ERROR_BREAK as an indication that
1741 * we were told to break out of the loop.
1743 handle
->break_loop
= 0;
1744 return PCAP_ERROR_BREAK
;
1747 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1748 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1749 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1750 fromlen
= sizeof(from
);
1751 packet_len
= recvfrom(
1752 handle
->fd
, bp
+ offset
,
1753 handle
->bufsize
- offset
, MSG_TRUNC
,
1754 (struct sockaddr
*) &from
, &fromlen
);
1755 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1756 } while (packet_len
== -1 && errno
== EINTR
);
1758 /* Check if an error occured */
1760 if (packet_len
== -1) {
1764 return 0; /* no packet there */
1768 * The device on which we're capturing went away.
1770 * XXX - we should really return
1771 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1772 * etc. aren't defined to return that.
1774 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1775 "The interface went down");
1779 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1780 "recvfrom: %s", pcap_strerror(errno
));
1785 #ifdef HAVE_PF_PACKET_SOCKETS
1786 if (!handlep
->sock_packet
) {
1788 * Unfortunately, there is a window between socket() and
1789 * bind() where the kernel may queue packets from any
1790 * interface. If we're bound to a particular interface,
1791 * discard packets not from that interface.
1793 * (If socket filters are supported, we could do the
1794 * same thing we do when changing the filter; however,
1795 * that won't handle packet sockets without socket
1796 * filter support, and it's a bit more complicated.
1797 * It would save some instructions per packet, however.)
1799 if (handlep
->ifindex
!= -1 &&
1800 from
.sll_ifindex
!= handlep
->ifindex
)
1804 * Do checks based on packet direction.
1805 * We can only do this if we're using PF_PACKET; the
1806 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1807 * which lacks the relevant packet type information.
1809 if (!linux_check_direction(handle
, &from
))
1814 #ifdef HAVE_PF_PACKET_SOCKETS
1816 * If this is a cooked device, fill in the fake packet header.
1818 if (handlep
->cooked
) {
1820 * Add the length of the fake header to the length
1821 * of packet data we read.
1823 packet_len
+= SLL_HDR_LEN
;
1825 hdrp
= (struct sll_header
*)bp
;
1826 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1827 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1828 hdrp
->sll_halen
= htons(from
.sll_halen
);
1829 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1830 (from
.sll_halen
> SLL_ADDRLEN
) ?
1833 hdrp
->sll_protocol
= from
.sll_protocol
;
1836 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1837 if (handlep
->vlan_offset
!= -1) {
1838 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1839 struct tpacket_auxdata
*aux
;
1841 struct vlan_tag
*tag
;
1843 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1844 cmsg
->cmsg_level
!= SOL_PACKET
||
1845 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1848 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1849 #if defined(TP_STATUS_VLAN_VALID)
1850 if ((aux
->tp_vlan_tci
== 0) && !(aux
->tp_status
& TP_STATUS_VLAN_VALID
))
1852 if (aux
->tp_vlan_tci
== 0) /* this is ambigious but without the
1853 TP_STATUS_VLAN_VALID flag, there is
1854 nothing that we can do */
1858 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1859 if (len
< (unsigned int) handlep
->vlan_offset
)
1863 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1865 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1866 tag
->vlan_tpid
= htons(VLAN_TPID(aux
, aux
));
1867 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1869 /* store vlan tci to bpf_aux_data struct for userland bpf filter */
1870 #if defined(TP_STATUS_VLAN_VALID)
1871 aux_data
.vlan_tag
= htons(aux
->tp_vlan_tci
) & 0x0fff;
1872 aux_data
.vlan_tag_present
= (aux
->tp_status
& TP_STATUS_VLAN_VALID
);
1874 packet_len
+= VLAN_TAG_LEN
;
1877 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1878 #endif /* HAVE_PF_PACKET_SOCKETS */
1881 * XXX: According to the kernel source we should get the real
1882 * packet len if calling recvfrom with MSG_TRUNC set. It does
1883 * not seem to work here :(, but it is supported by this code
1885 * To be honest the code RELIES on that feature so this is really
1886 * broken with 2.2.x kernels.
1887 * I spend a day to figure out what's going on and I found out
1888 * that the following is happening:
1890 * The packet comes from a random interface and the packet_rcv
1891 * hook is called with a clone of the packet. That code inserts
1892 * the packet into the receive queue of the packet socket.
1893 * If a filter is attached to that socket that filter is run
1894 * first - and there lies the problem. The default filter always
1895 * cuts the packet at the snaplen:
1900 * So the packet filter cuts down the packet. The recvfrom call
1901 * says "hey, it's only 68 bytes, it fits into the buffer" with
1902 * the result that we don't get the real packet length. This
1903 * is valid at least until kernel 2.2.17pre6.
1905 * We currently handle this by making a copy of the filter
1906 * program, fixing all "ret" instructions with non-zero
1907 * operands to have an operand of MAXIMUM_SNAPLEN so that the
1908 * filter doesn't truncate the packet, and supplying that modified
1909 * filter to the kernel.
1912 caplen
= packet_len
;
1913 if (caplen
> handle
->snapshot
)
1914 caplen
= handle
->snapshot
;
1916 /* Run the packet filter if not using kernel filter */
1917 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
1918 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
1919 packet_len
, caplen
, &aux_data
) == 0) {
1920 /* rejected by filter */
1925 /* Fill in our own header data */
1927 /* get timestamp for this packet */
1928 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1929 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
1930 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
1931 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1932 "SIOCGSTAMPNS: %s", pcap_strerror(errno
));
1938 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1939 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1940 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1945 pcap_header
.caplen
= caplen
;
1946 pcap_header
.len
= packet_len
;
1951 * Arguably, we should count them before we check the filter,
1952 * as on many other platforms "ps_recv" counts packets
1953 * handed to the filter rather than packets that passed
1954 * the filter, but if filtering is done in the kernel, we
1955 * can't get a count of packets that passed the filter,
1956 * and that would mean the meaning of "ps_recv" wouldn't
1957 * be the same on all Linux systems.
1959 * XXX - it's not the same on all systems in any case;
1960 * ideally, we should have a "get the statistics" call
1961 * that supplies more counts and indicates which of them
1962 * it supplies, so that we supply a count of packets
1963 * handed to the filter only on platforms where that
1964 * information is available.
1966 * We count them here even if we can get the packet count
1967 * from the kernel, as we can only determine at run time
1968 * whether we'll be able to get it from the kernel (if
1969 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1970 * the kernel, but if it is defined, the library might
1971 * have been built with a 2.4 or later kernel, but we
1972 * might be running on a 2.2[.x] kernel without Alexey
1973 * Kuznetzov's turbopacket patches, and thus the kernel
1974 * might not be able to supply those statistics). We
1975 * could, I guess, try, when opening the socket, to get
1976 * the statistics, and if we can not increment the count
1977 * here, but it's not clear that always incrementing
1978 * the count is more expensive than always testing a flag
1981 * We keep the count in "handlep->packets_read", and use that
1982 * for "ps_recv" if we can't get the statistics from the kernel.
1983 * We do that because, if we *can* get the statistics from
1984 * the kernel, we use "handlep->stat.ps_recv" and
1985 * "handlep->stat.ps_drop" as running counts, as reading the
1986 * statistics from the kernel resets the kernel statistics,
1987 * and if we directly increment "handlep->stat.ps_recv" here,
1988 * that means it will count packets *twice* on systems where
1989 * we can get kernel statistics - once here, and once in
1990 * pcap_stats_linux().
1992 handlep
->packets_read
++;
1994 /* Call the user supplied callback function */
1995 callback(userdata
, &pcap_header
, bp
);
2001 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
2003 struct pcap_linux
*handlep
= handle
->priv
;
2006 #ifdef HAVE_PF_PACKET_SOCKETS
2007 if (!handlep
->sock_packet
) {
2008 /* PF_PACKET socket */
2009 if (handlep
->ifindex
== -1) {
2011 * We don't support sending on the "any" device.
2013 strlcpy(handle
->errbuf
,
2014 "Sending packets isn't supported on the \"any\" device",
2019 if (handlep
->cooked
) {
2021 * We don't support sending on the "any" device.
2023 * XXX - how do you send on a bound cooked-mode
2025 * Is a "sendto()" required there?
2027 strlcpy(handle
->errbuf
,
2028 "Sending packets isn't supported in cooked mode",
2035 ret
= send(handle
->fd
, buf
, size
, 0);
2037 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
2038 pcap_strerror(errno
));
2045 * Get the statistics for the given packet capture handle.
2046 * Reports the number of dropped packets iff the kernel supports
2047 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2048 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2049 * patches); otherwise, that information isn't available, and we lie
2050 * and report 0 as the count of dropped packets.
2053 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
2055 struct pcap_linux
*handlep
= handle
->priv
;
2056 #ifdef HAVE_TPACKET_STATS
2057 #ifdef HAVE_TPACKET3
2059 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2060 * stuff at the end of a struct tpacket_stats_v3 will not
2061 * be filled in, and we don't look at it so this is OK even
2062 * for those sockets. In addition, the PF_PACKET socket
2063 * code in the kernel only uses the length parameter to
2064 * compute how much data to copy out and to indicate how
2065 * much data was copied out, so it's OK to base it on the
2066 * size of a struct tpacket_stats.
2068 * XXX - it's probably OK, in fact, to just use a
2069 * struct tpacket_stats for V3 sockets, as we don't
2070 * care about the tp_freeze_q_cnt stat.
2072 struct tpacket_stats_v3 kstats
;
2073 #else /* HAVE_TPACKET3 */
2074 struct tpacket_stats kstats
;
2075 #endif /* HAVE_TPACKET3 */
2076 socklen_t len
= sizeof (struct tpacket_stats
);
2077 #endif /* HAVE_TPACKET_STATS */
2079 long if_dropped
= 0;
2082 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
2084 if (handle
->opt
.promisc
)
2086 if_dropped
= handlep
->proc_dropped
;
2087 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
2088 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
2091 #ifdef HAVE_TPACKET_STATS
2093 * Try to get the packet counts from the kernel.
2095 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
2096 &kstats
, &len
) > -1) {
2098 * On systems where the PACKET_STATISTICS "getsockopt()"
2099 * argument is supported on PF_PACKET sockets:
2101 * "ps_recv" counts only packets that *passed* the
2102 * filter, not packets that didn't pass the filter.
2103 * This includes packets later dropped because we
2104 * ran out of buffer space.
2106 * "ps_drop" counts packets dropped because we ran
2107 * out of buffer space. It doesn't count packets
2108 * dropped by the interface driver. It counts only
2109 * packets that passed the filter.
2111 * See above for ps_ifdrop.
2113 * Both statistics include packets not yet read from
2114 * the kernel by libpcap, and thus not yet seen by
2117 * In "linux/net/packet/af_packet.c", at least in the
2118 * 2.4.9 kernel, "tp_packets" is incremented for every
2119 * packet that passes the packet filter *and* is
2120 * successfully queued on the socket; "tp_drops" is
2121 * incremented for every packet dropped because there's
2122 * not enough free space in the socket buffer.
2124 * When the statistics are returned for a PACKET_STATISTICS
2125 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2126 * so that "tp_packets" counts all packets handed to
2127 * the PF_PACKET socket, including packets dropped because
2128 * there wasn't room on the socket buffer - but not
2129 * including packets that didn't pass the filter.
2131 * In the BSD BPF, the count of received packets is
2132 * incremented for every packet handed to BPF, regardless
2133 * of whether it passed the filter.
2135 * We can't make "pcap_stats()" work the same on both
2136 * platforms, but the best approximation is to return
2137 * "tp_packets" as the count of packets and "tp_drops"
2138 * as the count of drops.
2140 * Keep a running total because each call to
2141 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2142 * resets the counters to zero.
2144 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
2145 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
2146 *stats
= handlep
->stat
;
2152 * If the error was EOPNOTSUPP, fall through, so that
2153 * if you build the library on a system with
2154 * "struct tpacket_stats" and run it on a system
2155 * that doesn't, it works as it does if the library
2156 * is built on a system without "struct tpacket_stats".
2158 if (errno
!= EOPNOTSUPP
) {
2159 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2160 "pcap_stats: %s", pcap_strerror(errno
));
2166 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2167 * is not supported on PF_PACKET sockets:
2169 * "ps_recv" counts only packets that *passed* the filter,
2170 * not packets that didn't pass the filter. It does not
2171 * count packets dropped because we ran out of buffer
2174 * "ps_drop" is not supported.
2176 * "ps_ifdrop" is supported. It will return the number
2177 * of drops the interface reports in /proc/net/dev,
2178 * if that is available.
2180 * "ps_recv" doesn't include packets not yet read from
2181 * the kernel by libpcap.
2183 * We maintain the count of packets processed by libpcap in
2184 * "handlep->packets_read", for reasons described in the comment
2185 * at the end of pcap_read_packet(). We have no idea how many
2186 * packets were dropped by the kernel buffers -- but we know
2187 * how many the interface dropped, so we can return that.
2190 stats
->ps_recv
= handlep
->packets_read
;
2192 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2197 add_linux_if(pcap_if_t
**devlistp
, const char *ifname
, int fd
, char *errbuf
)
2200 char name
[512]; /* XXX - pick a size */
2202 struct ifreq ifrflags
;
2205 * Get the interface name.
2209 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2212 * This could be the separator between a
2213 * name and an alias number, or it could be
2214 * the separator between a name with no
2215 * alias number and the next field.
2217 * If there's a colon after digits, it
2218 * separates the name and the alias number,
2219 * otherwise it separates the name and the
2223 while (isascii(*p
) && isdigit(*p
))
2227 * That was the next field,
2228 * not the alias number.
2239 * Get the flags for this interface.
2241 strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2242 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2243 if (errno
== ENXIO
|| errno
== ENODEV
)
2244 return (0); /* device doesn't actually exist - ignore it */
2245 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2246 "SIOCGIFFLAGS: %.*s: %s",
2247 (int)sizeof(ifrflags
.ifr_name
),
2249 pcap_strerror(errno
));
2254 * Add an entry for this interface, with no addresses.
2256 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2268 * Get from "/sys/class/net" all interfaces listed there; if they're
2269 * already in the list of interfaces we have, that won't add another
2270 * instance, but if they're not, that'll add them.
2272 * We don't bother getting any addresses for them; it appears you can't
2273 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2274 * although some other types of addresses can be fetched with SIOCGIFADDR,
2275 * we don't bother with them for now.
2277 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2278 * the list of interfaces as is, and return 0, so that we can try
2279 * scanning /proc/net/dev.
2281 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2284 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
2286 DIR *sys_class_net_d
;
2289 char subsystem_path
[PATH_MAX
+1];
2293 sys_class_net_d
= opendir("/sys/class/net");
2294 if (sys_class_net_d
== NULL
) {
2296 * Don't fail if it doesn't exist at all.
2298 if (errno
== ENOENT
)
2302 * Fail if we got some other error.
2304 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2305 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
2310 * Create a socket from which to fetch interface information.
2312 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2314 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2315 "socket: %s", pcap_strerror(errno
));
2316 (void)closedir(sys_class_net_d
);
2322 ent
= readdir(sys_class_net_d
);
2325 * Error or EOF; if errno != 0, it's an error.
2331 * Ignore "." and "..".
2333 if (strcmp(ent
->d_name
, ".") == 0 ||
2334 strcmp(ent
->d_name
, "..") == 0)
2338 * Ignore plain files; they do not have subdirectories
2339 * and thus have no attributes.
2341 if (ent
->d_type
== DT_REG
)
2345 * Is there an "ifindex" file under that name?
2346 * (We don't care whether it's a directory or
2347 * a symlink; older kernels have directories
2348 * for devices, newer kernels have symlinks to
2351 snprintf(subsystem_path
, sizeof subsystem_path
,
2352 "/sys/class/net/%s/ifindex", ent
->d_name
);
2353 if (lstat(subsystem_path
, &statb
) != 0) {
2355 * Stat failed. Either there was an error
2356 * other than ENOENT, and we don't know if
2357 * this is an interface, or it's ENOENT,
2358 * and either some part of "/sys/class/net/{if}"
2359 * disappeared, in which case it probably means
2360 * the interface disappeared, or there's no
2361 * "ifindex" file, which means it's not a
2362 * network interface.
2368 * Attempt to add the interface.
2370 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2378 * Well, we didn't fail for any other reason; did we
2379 * fail due to an error reading the directory?
2382 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2383 "Error reading /sys/class/net: %s",
2384 pcap_strerror(errno
));
2390 (void)closedir(sys_class_net_d
);
2395 * Get from "/proc/net/dev" all interfaces listed there; if they're
2396 * already in the list of interfaces we have, that won't add another
2397 * instance, but if they're not, that'll add them.
2399 * See comments from scan_sys_class_net().
2402 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2411 proc_net_f
= fopen("/proc/net/dev", "r");
2412 if (proc_net_f
== NULL
) {
2414 * Don't fail if it doesn't exist at all.
2416 if (errno
== ENOENT
)
2420 * Fail if we got some other error.
2422 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2423 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2428 * Create a socket from which to fetch interface information.
2430 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2432 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2433 "socket: %s", pcap_strerror(errno
));
2434 (void)fclose(proc_net_f
);
2439 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2441 * Skip the first two lines - they're headers.
2449 * Skip leading white space.
2451 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2453 if (*p
== '\0' || *p
== '\n')
2454 continue; /* blank line */
2457 * Attempt to add the interface.
2459 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2467 * Well, we didn't fail for any other reason; did we
2468 * fail due to an error reading the file?
2470 if (ferror(proc_net_f
)) {
2471 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2472 "Error reading /proc/net/dev: %s",
2473 pcap_strerror(errno
));
2479 (void)fclose(proc_net_f
);
2484 * Description string for the "any" device.
2486 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2489 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2494 * Read "/sys/class/net", and add to the list of interfaces all
2495 * interfaces listed there that we don't already have, because,
2496 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2497 * and even getifaddrs() won't return information about
2498 * interfaces with no addresses, so you need to read "/sys/class/net"
2499 * to get the names of the rest of the interfaces.
2501 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2503 return (-1); /* failed */
2506 * No /sys/class/net; try reading /proc/net/dev instead.
2508 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2513 * Add the "any" device.
2515 if (pcap_add_if(alldevsp
, "any", IFF_UP
|IFF_RUNNING
,
2516 any_descr
, errbuf
) < 0)
2523 * Attach the given BPF code to the packet capture device.
2526 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2529 struct pcap_linux
*handlep
;
2530 #ifdef SO_ATTACH_FILTER
2531 struct sock_fprog fcode
;
2532 int can_filter_in_kernel
;
2539 strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2544 handlep
= handle
->priv
;
2546 /* Make our private copy of the filter */
2548 if (install_bpf_program(handle
, filter
) < 0)
2549 /* install_bpf_program() filled in errbuf */
2553 * Run user level packet filter by default. Will be overriden if
2554 * installing a kernel filter succeeds.
2556 handlep
->filter_in_userland
= 1;
2558 /* Install kernel level filter if possible */
2560 #ifdef SO_ATTACH_FILTER
2562 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2564 * fcode.len is an unsigned short for current kernel.
2565 * I have yet to see BPF-Code with that much
2566 * instructions but still it is possible. So for the
2567 * sake of correctness I added this check.
2569 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2571 fcode
.filter
= NULL
;
2572 can_filter_in_kernel
= 0;
2574 #endif /* USHRT_MAX */
2577 * Oh joy, the Linux kernel uses struct sock_fprog instead
2578 * of struct bpf_program and of course the length field is
2579 * of different size. Pointed out by Sebastian
2581 * Oh, and we also need to fix it up so that all "ret"
2582 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2583 * as the operand if we're not capturing in memory-mapped
2584 * mode, and so that, if we're in cooked mode, all memory-
2585 * reference instructions use special magic offsets in
2586 * references to the link-layer header and assume that the
2587 * link-layer payload begins at 0; "fix_program()" will do
2590 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2595 * Fatal error; just quit.
2596 * (The "default" case shouldn't happen; we
2597 * return -1 for that reason.)
2603 * The program performed checks that we can't make
2604 * work in the kernel.
2606 can_filter_in_kernel
= 0;
2611 * We have a filter that'll work in the kernel.
2613 can_filter_in_kernel
= 1;
2619 * NOTE: at this point, we've set both the "len" and "filter"
2620 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2621 * those are the only members of the "sock_fprog" structure,
2622 * so we initialize every member of that structure.
2624 * If there is anything in "fcode" that is not initialized,
2625 * it is either a field added in a later kernel, or it's
2628 * If a new field is added, this code needs to be updated
2629 * to set it correctly.
2631 * If there are no other fields, then:
2633 * if the Linux kernel looks at the padding, it's
2636 * if the Linux kernel doesn't look at the padding,
2637 * then if some tool complains that we're passing
2638 * uninitialized data to the kernel, then the tool
2639 * is buggy and needs to understand that it's just
2642 if (can_filter_in_kernel
) {
2643 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2646 * Installation succeded - using kernel filter,
2647 * so userland filtering not needed.
2649 handlep
->filter_in_userland
= 0;
2651 else if (err
== -1) /* Non-fatal error */
2654 * Print a warning if we weren't able to install
2655 * the filter for a reason other than "this kernel
2656 * isn't configured to support socket filters.
2658 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2660 "Warning: Kernel filter failed: %s\n",
2661 pcap_strerror(errno
));
2667 * If we're not using the kernel filter, get rid of any kernel
2668 * filter that might've been there before, e.g. because the
2669 * previous filter could work in the kernel, or because some other
2670 * code attached a filter to the socket by some means other than
2671 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2672 * filter out packets that would pass the new userland filter.
2674 if (handlep
->filter_in_userland
) {
2675 if (reset_kernel_filter(handle
) == -1) {
2676 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2677 "can't remove kernel filter: %s",
2678 pcap_strerror(errno
));
2679 err
= -2; /* fatal error */
2684 * Free up the copy of the filter that was made by "fix_program()".
2686 if (fcode
.filter
!= NULL
)
2692 #endif /* SO_ATTACH_FILTER */
2698 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2700 return pcap_setfilter_linux_common(handle
, filter
, 0);
2705 * Set direction flag: Which packets do we accept on a forwarding
2706 * single device? IN, OUT or both?
2709 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2711 #ifdef HAVE_PF_PACKET_SOCKETS
2712 struct pcap_linux
*handlep
= handle
->priv
;
2714 if (!handlep
->sock_packet
) {
2715 handle
->direction
= d
;
2720 * We're not using PF_PACKET sockets, so we can't determine
2721 * the direction of the packet.
2723 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2724 "Setting direction is not supported on SOCK_PACKET sockets");
2728 #ifdef HAVE_PF_PACKET_SOCKETS
2730 * Map the PACKET_ value to a LINUX_SLL_ value; we
2731 * want the same numerical value to be used in
2732 * the link-layer header even if the numerical values
2733 * for the PACKET_ #defines change, so that programs
2734 * that look at the packet type field will always be
2735 * able to handle DLT_LINUX_SLL captures.
2738 map_packet_type_to_sll_type(short int sll_pkttype
)
2740 switch (sll_pkttype
) {
2743 return htons(LINUX_SLL_HOST
);
2745 case PACKET_BROADCAST
:
2746 return htons(LINUX_SLL_BROADCAST
);
2748 case PACKET_MULTICAST
:
2749 return htons(LINUX_SLL_MULTICAST
);
2751 case PACKET_OTHERHOST
:
2752 return htons(LINUX_SLL_OTHERHOST
);
2754 case PACKET_OUTGOING
:
2755 return htons(LINUX_SLL_OUTGOING
);
2765 #ifndef IW_MODE_MONITOR
2768 , const char *device
)
2772 #ifdef IW_MODE_MONITOR
2773 char errbuf
[PCAP_ERRBUF_SIZE
];
2777 * See if there's a sysfs wireless directory for it.
2778 * If so, it's a wireless interface.
2780 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
2782 * Just give up here.
2786 if (stat(pathstr
, &statb
) == 0) {
2792 #ifdef IW_MODE_MONITOR
2794 * OK, maybe it's not wireless, or maybe this kernel doesn't
2795 * support sysfs. Try the wireless extensions.
2797 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
2799 * It supports the wireless extensions, so it's a Wi-Fi
2809 * Linux uses the ARP hardware type to identify the type of an
2810 * interface. pcap uses the DLT_xxx constants for this. This
2811 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2812 * constant, as arguments, and sets "handle->linktype" to the
2813 * appropriate DLT_XXX constant and sets "handle->offset" to
2814 * the appropriate value (to make "handle->offset" plus link-layer
2815 * header length be a multiple of 4, so that the link-layer payload
2816 * will be aligned on a 4-byte boundary when capturing packets).
2817 * (If the offset isn't set here, it'll be 0; add code as appropriate
2818 * for cases where it shouldn't be 0.)
2820 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2821 * in cooked mode; otherwise, we can't use cooked mode, so we have
2822 * to pick some type that works in raw mode, or fail.
2824 * Sets the link type to -1 if unable to map the type.
2826 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
2827 const char *device
, int cooked_ok
)
2829 static const char cdma_rmnet
[] = "cdma_rmnet";
2835 * For various annoying reasons having to do with DHCP
2836 * software, some versions of Android give the mobile-
2837 * phone-network interface an ARPHRD_ value of
2838 * ARPHRD_ETHER, even though the packets supplied by
2839 * that interface have no link-layer header, and begin
2840 * with an IP header, so that the ARPHRD_ value should
2843 * Detect those devices by checking the device name, and
2844 * use DLT_RAW for them.
2846 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2847 handle
->linktype
= DLT_RAW
;
2852 * Is this a real Ethernet device? If so, give it a
2853 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2854 * that an application can let you choose it, in case you're
2855 * capturing DOCSIS traffic that a Cisco Cable Modem
2856 * Termination System is putting out onto an Ethernet (it
2857 * doesn't put an Ethernet header onto the wire, it puts raw
2858 * DOCSIS frames out on the wire inside the low-level
2859 * Ethernet framing).
2861 * XXX - are there any other sorts of "fake Ethernet" that
2862 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2863 * a Cisco CMTS won't put traffic onto it or get traffic
2864 * bridged onto it? ISDN is handled in "activate_new()",
2865 * as we fall back on cooked mode there, and we use
2866 * is_wifi() to check for 802.11 devices; are there any
2869 if (!is_wifi(sock_fd
, device
)) {
2871 * It's not a Wi-Fi device; offer DOCSIS.
2873 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2875 * If that fails, just leave the list empty.
2877 if (handle
->dlt_list
!= NULL
) {
2878 handle
->dlt_list
[0] = DLT_EN10MB
;
2879 handle
->dlt_list
[1] = DLT_DOCSIS
;
2880 handle
->dlt_count
= 2;
2885 case ARPHRD_METRICOM
:
2886 case ARPHRD_LOOPBACK
:
2887 handle
->linktype
= DLT_EN10MB
;
2892 handle
->linktype
= DLT_EN3MB
;
2896 handle
->linktype
= DLT_AX25_KISS
;
2900 handle
->linktype
= DLT_PRONET
;
2904 handle
->linktype
= DLT_CHAOS
;
2907 #define ARPHRD_CAN 280
2910 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2913 #ifndef ARPHRD_IEEE802_TR
2914 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2916 case ARPHRD_IEEE802_TR
:
2917 case ARPHRD_IEEE802
:
2918 handle
->linktype
= DLT_IEEE802
;
2923 handle
->linktype
= DLT_ARCNET_LINUX
;
2926 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2927 #define ARPHRD_FDDI 774
2930 handle
->linktype
= DLT_FDDI
;
2934 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2935 #define ARPHRD_ATM 19
2939 * The Classical IP implementation in ATM for Linux
2940 * supports both what RFC 1483 calls "LLC Encapsulation",
2941 * in which each packet has an LLC header, possibly
2942 * with a SNAP header as well, prepended to it, and
2943 * what RFC 1483 calls "VC Based Multiplexing", in which
2944 * different virtual circuits carry different network
2945 * layer protocols, and no header is prepended to packets.
2947 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2948 * you can't use the ARPHRD_ type to find out whether
2949 * captured packets will have an LLC header, and,
2950 * while there's a socket ioctl to *set* the encapsulation
2951 * type, there's no ioctl to *get* the encapsulation type.
2955 * programs that dissect Linux Classical IP frames
2956 * would have to check for an LLC header and,
2957 * depending on whether they see one or not, dissect
2958 * the frame as LLC-encapsulated or as raw IP (I
2959 * don't know whether there's any traffic other than
2960 * IP that would show up on the socket, or whether
2961 * there's any support for IPv6 in the Linux
2962 * Classical IP code);
2964 * filter expressions would have to compile into
2965 * code that checks for an LLC header and does
2968 * Both of those are a nuisance - and, at least on systems
2969 * that support PF_PACKET sockets, we don't have to put
2970 * up with those nuisances; instead, we can just capture
2971 * in cooked mode. That's what we'll do, if we can.
2972 * Otherwise, we'll just fail.
2975 handle
->linktype
= DLT_LINUX_SLL
;
2977 handle
->linktype
= -1;
2980 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2981 #define ARPHRD_IEEE80211 801
2983 case ARPHRD_IEEE80211
:
2984 handle
->linktype
= DLT_IEEE802_11
;
2987 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2988 #define ARPHRD_IEEE80211_PRISM 802
2990 case ARPHRD_IEEE80211_PRISM
:
2991 handle
->linktype
= DLT_PRISM_HEADER
;
2994 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2995 #define ARPHRD_IEEE80211_RADIOTAP 803
2997 case ARPHRD_IEEE80211_RADIOTAP
:
2998 handle
->linktype
= DLT_IEEE802_11_RADIO
;
3003 * Some PPP code in the kernel supplies no link-layer
3004 * header whatsoever to PF_PACKET sockets; other PPP
3005 * code supplies PPP link-layer headers ("syncppp.c");
3006 * some PPP code might supply random link-layer
3007 * headers (PPP over ISDN - there's code in Ethereal,
3008 * for example, to cope with PPP-over-ISDN captures
3009 * with which the Ethereal developers have had to cope,
3010 * heuristically trying to determine which of the
3011 * oddball link-layer headers particular packets have).
3013 * As such, we just punt, and run all PPP interfaces
3014 * in cooked mode, if we can; otherwise, we just treat
3015 * it as DLT_RAW, for now - if somebody needs to capture,
3016 * on a 2.0[.x] kernel, on PPP devices that supply a
3017 * link-layer header, they'll have to add code here to
3018 * map to the appropriate DLT_ type (possibly adding a
3019 * new DLT_ type, if necessary).
3022 handle
->linktype
= DLT_LINUX_SLL
;
3025 * XXX - handle ISDN types here? We can't fall
3026 * back on cooked sockets, so we'd have to
3027 * figure out from the device name what type of
3028 * link-layer encapsulation it's using, and map
3029 * that to an appropriate DLT_ value, meaning
3030 * we'd map "isdnN" devices to DLT_RAW (they
3031 * supply raw IP packets with no link-layer
3032 * header) and "isdY" devices to a new DLT_I4L_IP
3033 * type that has only an Ethernet packet type as
3034 * a link-layer header.
3036 * But sometimes we seem to get random crap
3037 * in the link-layer header when capturing on
3040 handle
->linktype
= DLT_RAW
;
3044 #ifndef ARPHRD_CISCO
3045 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3048 handle
->linktype
= DLT_C_HDLC
;
3051 /* Not sure if this is correct for all tunnels, but it
3055 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3063 #ifndef ARPHRD_RAWHDLC
3064 #define ARPHRD_RAWHDLC 518
3066 case ARPHRD_RAWHDLC
:
3068 #define ARPHRD_DLCI 15
3072 * XXX - should some of those be mapped to DLT_LINUX_SLL
3073 * instead? Should we just map all of them to DLT_LINUX_SLL?
3075 handle
->linktype
= DLT_RAW
;
3079 #define ARPHRD_FRAD 770
3082 handle
->linktype
= DLT_FRELAY
;
3085 case ARPHRD_LOCALTLK
:
3086 handle
->linktype
= DLT_LTALK
;
3091 * RFC 4338 defines an encapsulation for IP and ARP
3092 * packets that's compatible with the RFC 2625
3093 * encapsulation, but that uses a different ARP
3094 * hardware type and hardware addresses. That
3095 * ARP hardware type is 18; Linux doesn't define
3096 * any ARPHRD_ value as 18, but if it ever officially
3097 * supports RFC 4338-style IP-over-FC, it should define
3100 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3101 * that this will encourage its use in the future,
3102 * should Linux ever officially support RFC 4338-style
3105 handle
->linktype
= DLT_IP_OVER_FC
;
3109 #define ARPHRD_FCPP 784
3113 #define ARPHRD_FCAL 785
3117 #define ARPHRD_FCPL 786
3120 #ifndef ARPHRD_FCFABRIC
3121 #define ARPHRD_FCFABRIC 787
3123 case ARPHRD_FCFABRIC
:
3125 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3128 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3130 * and one was assigned.
3132 * In a later private discussion (spun off from a message
3133 * on the ethereal-users list) on how to get that DLT_
3134 * value in libpcap on Linux, I ended up deciding that
3135 * the best thing to do would be to have him tweak the
3136 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3137 * type, and map all those types to DLT_IP_OVER_FC:
3139 * I've checked into the libpcap and tcpdump CVS tree
3140 * support for DLT_IP_OVER_FC. In order to use that,
3141 * you'd have to modify your modified driver to return
3142 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3143 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3144 * example (the exact value doesn't matter, it can be
3145 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3148 * 11 years later, Christian Svensson wanted to map
3149 * various ARPHRD_ values to DLT_FC_2 and
3150 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3153 * https://github.com/mcr/libpcap/pull/29
3155 * There doesn't seem to be any network drivers that uses
3156 * any of the ARPHRD_FC* values for IP-over-FC, and
3157 * it's not exactly clear what the "Dummy types for non
3158 * ARP hardware" are supposed to mean (link-layer
3159 * header type? Physical network type?), so it's
3160 * not exactly clear why the ARPHRD_FC* types exist
3161 * in the first place.
3163 * For now, we map them to DLT_FC_2, and provide an
3164 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3165 * DLT_IP_OVER_FC just in case there's some old
3166 * driver out there that uses one of those types for
3167 * IP-over-FC on which somebody wants to capture
3170 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3172 * If that fails, just leave the list empty.
3174 if (handle
->dlt_list
!= NULL
) {
3175 handle
->dlt_list
[0] = DLT_FC_2
;
3176 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
3177 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
3178 handle
->dlt_count
= 3;
3180 handle
->linktype
= DLT_FC_2
;
3184 #define ARPHRD_IRDA 783
3187 /* Don't expect IP packet out of this interfaces... */
3188 handle
->linktype
= DLT_LINUX_IRDA
;
3189 /* We need to save packet direction for IrDA decoding,
3190 * so let's use "Linux-cooked" mode. Jean II
3192 * XXX - this is handled in activate_new(). */
3193 //handlep->cooked = 1;
3196 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3197 * is needed, please report it to <daniele@orlandi.com> */
3199 #define ARPHRD_LAPD 8445
3202 /* Don't expect IP packet out of this interfaces... */
3203 handle
->linktype
= DLT_LINUX_LAPD
;
3207 #define ARPHRD_NONE 0xFFFE
3211 * No link-layer header; packets are just IP
3212 * packets, so use DLT_RAW.
3214 handle
->linktype
= DLT_RAW
;
3217 #ifndef ARPHRD_IEEE802154
3218 #define ARPHRD_IEEE802154 804
3220 case ARPHRD_IEEE802154
:
3221 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
3224 #ifndef ARPHRD_NETLINK
3225 #define ARPHRD_NETLINK 824
3227 case ARPHRD_NETLINK
:
3228 handle
->linktype
= DLT_NETLINK
;
3230 * We need to use cooked mode, so that in sll_protocol we
3231 * pick up the netlink protocol type such as NETLINK_ROUTE,
3232 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3234 * XXX - this is handled in activate_new().
3236 //handlep->cooked = 1;
3240 handle
->linktype
= -1;
3245 /* ===== Functions to interface to the newer kernels ================== */
3248 * Try to open a packet socket using the new kernel PF_PACKET interface.
3249 * Returns 1 on success, 0 on an error that means the new interface isn't
3250 * present (so the old SOCK_PACKET interface should be tried), and a
3251 * PCAP_ERROR_ value on an error that means that the old mechanism won't
3252 * work either (so it shouldn't be tried).
3255 activate_new(pcap_t
*handle
)
3257 #ifdef HAVE_PF_PACKET_SOCKETS
3258 struct pcap_linux
*handlep
= handle
->priv
;
3259 const char *device
= handle
->opt
.source
;
3260 int is_any_device
= (strcmp(device
, "any") == 0);
3261 int sock_fd
= -1, arptype
;
3262 #ifdef HAVE_PACKET_AUXDATA
3266 struct packet_mreq mr
;
3267 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3269 socklen_t len
= sizeof(bpf_extensions
);
3273 * Open a socket with protocol family packet. If the
3274 * "any" device was specified, we open a SOCK_DGRAM
3275 * socket for the cooked interface, otherwise we first
3276 * try a SOCK_RAW socket for the raw interface.
3278 sock_fd
= is_any_device
?
3279 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
3280 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
3282 if (sock_fd
== -1) {
3283 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
3285 * We don't support PF_PACKET/SOCK_whatever
3286 * sockets; try the old mechanism.
3291 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
3292 pcap_strerror(errno
) );
3293 if (errno
== EPERM
|| errno
== EACCES
) {
3295 * You don't have permission to open the
3298 return PCAP_ERROR_PERM_DENIED
;
3307 /* It seems the kernel supports the new interface. */
3308 handlep
->sock_packet
= 0;
3311 * Get the interface index of the loopback device.
3312 * If the attempt fails, don't fail, just set the
3313 * "handlep->lo_ifindex" to -1.
3315 * XXX - can there be more than one device that loops
3316 * packets back, i.e. devices other than "lo"? If so,
3317 * we'd need to find them all, and have an array of
3318 * indices for them, and check all of them in
3319 * "pcap_read_packet()".
3321 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3324 * Default value for offset to align link-layer payload
3325 * on a 4-byte boundary.
3330 * What kind of frames do we have to deal with? Fall back
3331 * to cooked mode if we have an unknown interface type
3332 * or a type we know doesn't work well in raw mode.
3334 if (!is_any_device
) {
3335 /* Assume for now we don't need cooked mode. */
3336 handlep
->cooked
= 0;
3338 if (handle
->opt
.rfmon
) {
3340 * We were asked to turn on monitor mode.
3341 * Do so before we get the link-layer type,
3342 * because entering monitor mode could change
3343 * the link-layer type.
3345 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3353 * Nothing worked for turning monitor mode
3357 return PCAP_ERROR_RFMON_NOTSUP
;
3361 * Either monitor mode has been turned on for
3362 * the device, or we've been given a different
3363 * device to open for monitor mode. If we've
3364 * been given a different device, use it.
3366 if (handlep
->mondevice
!= NULL
)
3367 device
= handlep
->mondevice
;
3369 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3374 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
3375 if (handle
->linktype
== -1 ||
3376 handle
->linktype
== DLT_LINUX_SLL
||
3377 handle
->linktype
== DLT_LINUX_IRDA
||
3378 handle
->linktype
== DLT_LINUX_LAPD
||
3379 handle
->linktype
== DLT_NETLINK
||
3380 (handle
->linktype
== DLT_EN10MB
&&
3381 (strncmp("isdn", device
, 4) == 0 ||
3382 strncmp("isdY", device
, 4) == 0))) {
3384 * Unknown interface type (-1), or a
3385 * device we explicitly chose to run
3386 * in cooked mode (e.g., PPP devices),
3387 * or an ISDN device (whose link-layer
3388 * type we can only determine by using
3389 * APIs that may be different on different
3390 * kernels) - reopen in cooked mode.
3392 if (close(sock_fd
) == -1) {
3393 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3394 "close: %s", pcap_strerror(errno
));
3397 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3399 if (sock_fd
== -1) {
3400 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3401 "socket: %s", pcap_strerror(errno
));
3402 if (errno
== EPERM
|| errno
== EACCES
) {
3404 * You don't have permission to
3407 return PCAP_ERROR_PERM_DENIED
;
3415 handlep
->cooked
= 1;
3418 * Get rid of any link-layer type list
3419 * we allocated - this only supports cooked
3422 if (handle
->dlt_list
!= NULL
) {
3423 free(handle
->dlt_list
);
3424 handle
->dlt_list
= NULL
;
3425 handle
->dlt_count
= 0;
3428 if (handle
->linktype
== -1) {
3430 * Warn that we're falling back on
3431 * cooked mode; we may want to
3432 * update "map_arphrd_to_dlt()"
3433 * to handle the new type.
3435 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3437 "supported by libpcap - "
3438 "falling back to cooked "
3444 * IrDA capture is not a real "cooked" capture,
3445 * it's IrLAP frames, not IP packets. The
3446 * same applies to LAPD capture.
3448 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3449 handle
->linktype
!= DLT_LINUX_LAPD
&&
3450 handle
->linktype
!= DLT_NETLINK
)
3451 handle
->linktype
= DLT_LINUX_SLL
;
3454 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3456 if (handlep
->ifindex
== -1) {
3461 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3462 handle
->errbuf
)) != 1) {
3467 return 0; /* try old mechanism */
3473 if (handle
->opt
.rfmon
) {
3475 * It doesn't support monitor mode.
3478 return PCAP_ERROR_RFMON_NOTSUP
;
3482 * It uses cooked mode.
3484 handlep
->cooked
= 1;
3485 handle
->linktype
= DLT_LINUX_SLL
;
3488 * We're not bound to a device.
3489 * For now, we're using this as an indication
3490 * that we can't transmit; stop doing that only
3491 * if we figure out how to transmit in cooked
3494 handlep
->ifindex
= -1;
3498 * Select promiscuous mode on if "promisc" is set.
3500 * Do not turn allmulti mode on if we don't select
3501 * promiscuous mode - on some devices (e.g., Orinoco
3502 * wireless interfaces), allmulti mode isn't supported
3503 * and the driver implements it by turning promiscuous
3504 * mode on, and that screws up the operation of the
3505 * card as a normal networking interface, and on no
3506 * other platform I know of does starting a non-
3507 * promiscuous capture affect which multicast packets
3508 * are received by the interface.
3512 * Hmm, how can we set promiscuous mode on all interfaces?
3513 * I am not sure if that is possible at all. For now, we
3514 * silently ignore attempts to turn promiscuous mode on
3515 * for the "any" device (so you don't have to explicitly
3516 * disable it in programs such as tcpdump).
3519 if (!is_any_device
&& handle
->opt
.promisc
) {
3520 memset(&mr
, 0, sizeof(mr
));
3521 mr
.mr_ifindex
= handlep
->ifindex
;
3522 mr
.mr_type
= PACKET_MR_PROMISC
;
3523 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3524 &mr
, sizeof(mr
)) == -1) {
3525 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3526 "setsockopt: %s", pcap_strerror(errno
));
3532 /* Enable auxillary data if supported and reserve room for
3533 * reconstructing VLAN headers. */
3534 #ifdef HAVE_PACKET_AUXDATA
3536 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3537 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3538 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3539 "setsockopt: %s", pcap_strerror(errno
));
3543 handle
->offset
+= VLAN_TAG_LEN
;
3544 #endif /* HAVE_PACKET_AUXDATA */
3547 * This is a 2.2[.x] or later kernel (we know that
3548 * because we're not using a SOCK_PACKET socket -
3549 * PF_PACKET is supported only in 2.2 and later
3552 * We can safely pass "recvfrom()" a byte count
3553 * based on the snapshot length.
3555 * If we're in cooked mode, make the snapshot length
3556 * large enough to hold a "cooked mode" header plus
3557 * 1 byte of packet data (so we don't pass a byte
3558 * count of 0 to "recvfrom()").
3560 if (handlep
->cooked
) {
3561 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3562 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3564 handle
->bufsize
= handle
->snapshot
;
3567 * Set the offset at which to insert VLAN tags.
3569 switch (handle
->linktype
) {
3572 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3576 handlep
->vlan_offset
= 14;
3580 handlep
->vlan_offset
= -1; /* unknown */
3584 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3585 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3586 int nsec_tstamps
= 1;
3588 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3589 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3594 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3597 * We've succeeded. Save the socket FD in the pcap structure.
3599 handle
->fd
= sock_fd
;
3601 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3603 * Can we generate special code for VLAN checks?
3604 * (XXX - what if we need the special code but it's not supported
3605 * by the OS? Is that possible?)
3607 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
3608 &bpf_extensions
, &len
) == 0) {
3609 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
3611 * Yes, we can. Request that we do so.
3613 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
3616 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
3619 #else /* HAVE_PF_PACKET_SOCKETS */
3621 "New packet capturing interface not supported by build "
3622 "environment", PCAP_ERRBUF_SIZE
);
3624 #endif /* HAVE_PF_PACKET_SOCKETS */
3627 #ifdef HAVE_PACKET_RING
3629 * Attempt to activate with memory-mapped access.
3631 * On success, returns 1, and sets *status to 0 if there are no warnings
3632 * or to a PCAP_WARNING_ code if there is a warning.
3634 * On failure due to lack of support for memory-mapped capture, returns
3637 * On error, returns -1, and sets *status to the appropriate error code;
3638 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3641 activate_mmap(pcap_t
*handle
, int *status
)
3643 struct pcap_linux
*handlep
= handle
->priv
;
3647 * Attempt to allocate a buffer to hold the contents of one
3648 * packet, for use by the oneshot callback.
3650 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3651 if (handlep
->oneshot_buffer
== NULL
) {
3652 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3653 "can't allocate oneshot buffer: %s",
3654 pcap_strerror(errno
));
3655 *status
= PCAP_ERROR
;
3659 if (handle
->opt
.buffer_size
== 0) {
3660 /* by default request 2M for the ring buffer */
3661 handle
->opt
.buffer_size
= 2*1024*1024;
3663 ret
= prepare_tpacket_socket(handle
);
3665 free(handlep
->oneshot_buffer
);
3666 *status
= PCAP_ERROR
;
3669 ret
= create_ring(handle
, status
);
3672 * We don't support memory-mapped capture; our caller
3673 * will fall back on reading from the socket.
3675 free(handlep
->oneshot_buffer
);
3680 * Error attempting to enable memory-mapped capture;
3681 * fail. create_ring() has set *status.
3683 free(handlep
->oneshot_buffer
);
3688 * Success. *status has been set either to 0 if there are no
3689 * warnings or to a PCAP_WARNING_ value if there is a warning.
3691 * Override some defaults and inherit the other fields from
3693 * handle->offset is used to get the current position into the rx ring.
3694 * handle->cc is used to store the ring size.
3697 switch (handlep
->tp_version
) {
3699 handle
->read_op
= pcap_read_linux_mmap_v1
;
3702 handle
->read_op
= pcap_read_linux_mmap_v1_64
;
3704 #ifdef HAVE_TPACKET2
3706 handle
->read_op
= pcap_read_linux_mmap_v2
;
3709 #ifdef HAVE_TPACKET3
3711 handle
->read_op
= pcap_read_linux_mmap_v3
;
3715 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3716 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3717 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3718 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3719 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3720 handle
->selectable_fd
= handle
->fd
;
3723 #else /* HAVE_PACKET_RING */
3725 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3729 #endif /* HAVE_PACKET_RING */
3731 #ifdef HAVE_PACKET_RING
3733 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3735 * Attempt to set the socket to the specified version of the memory-mapped
3738 * Return 0 if we succeed; return 1 if we fail because that version isn't
3739 * supported; return -1 on any other error, and set handle->errbuf.
3742 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
3744 struct pcap_linux
*handlep
= handle
->priv
;
3746 socklen_t len
= sizeof(val
);
3749 * Probe whether kernel supports the specified TPACKET version;
3750 * this also gets the length of the header for that version.
3752 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3753 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
)
3756 /* Failed to even find out; this is a fatal error. */
3757 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3758 "can't get %s header len on packet socket: %s",
3760 pcap_strerror(errno
));
3763 handlep
->tp_hdrlen
= val
;
3766 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3768 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3769 "can't activate %s on packet socket: %s",
3771 pcap_strerror(errno
));
3774 handlep
->tp_version
= version
;
3776 /* Reserve space for VLAN tag reconstruction */
3778 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3780 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3781 "can't set up reserve on packet socket: %s",
3782 pcap_strerror(errno
));
3788 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3791 * If the instruction set for which we're compiling has both 32-bit
3792 * and 64-bit versions, and Linux support for the 64-bit version
3793 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
3794 * you get from uname() for the 64-bit version. Otherwise, leave
3795 * it undefined. (This includes ARM, which has a 64-bit version,
3796 * but Linux support for it appeared well after TPACKET_V2 support
3797 * did, so there should never be a case where 32-bit ARM code is
3798 * running o a 64-bit kernel that only supports TPACKET_V1.)
3800 * If we've omitted your favorite such architecture, please contribute
3801 * a patch. (No patch is needed for architectures that are 32-bit-only
3802 * or for which Linux has no support for 32-bit userland - or for which,
3803 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
3806 #if defined(__i386__)
3807 #define ISA_64_BIT "x86_64"
3808 #elif defined(__ppc__)
3809 #define ISA_64_BIT "ppc64"
3810 #elif defined(__sparc__)
3811 #define ISA_64_BIT "sparc64"
3812 #elif defined(__s390__)
3813 #define ISA_64_BIT "s390x"
3814 #elif defined(__mips__)
3815 #define ISA_64_BIT "mips64"
3816 #elif defined(__hppa__)
3817 #define ISA_64_BIT "parisc64"
3821 * Attempt to set the socket to version 3 of the memory-mapped header and,
3822 * if that fails because version 3 isn't supported, attempt to fall
3823 * back to version 2. If version 2 isn't supported, just leave it at
3826 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
3827 * supported; return -1 on any other error, and set handle->errbuf.
3830 prepare_tpacket_socket(pcap_t
*handle
)
3832 struct pcap_linux
*handlep
= handle
->priv
;
3833 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3837 #ifdef HAVE_TPACKET3
3839 * Try setting the version to TPACKET_V3.
3841 * The only mode in which buffering is done on PF_PACKET
3842 * sockets, so that packets might not be delivered
3843 * immediately, is TPACKET_V3 mode.
3845 * The buffering cannot be disabled in that mode, so
3846 * if the user has requested immediate mode, we don't
3849 if (!handle
->opt
.immediate
) {
3850 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
3859 * We failed for some reason other than "the
3860 * kernel doesn't support TPACKET_V3".
3865 #endif /* HAVE_TPACKET3 */
3867 #ifdef HAVE_TPACKET2
3869 * Try setting the version to TPACKET_V2.
3871 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
3880 * We failed for some reason other than "the
3881 * kernel doesn't support TPACKET_V2".
3885 #endif /* HAVE_TPACKET2 */
3888 * OK, we're using TPACKET_V1, as that's all the kernel supports.
3890 handlep
->tp_version
= TPACKET_V1
;
3891 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
3895 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
3896 * each other due to platform-dependent data type size differences.
3898 * If we have a 32-bit userland and a 64-bit kernel, use an
3899 * internally-defined TPACKET_V1_64, with which we use a 64-bit
3900 * version of the data structures.
3902 if (sizeof(long) == 4) {
3904 * This is 32-bit code.
3906 struct utsname utsname
;
3908 if (uname(&utsname
) == -1) {
3912 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3913 "uname failed: %s", pcap_strerror(errno
));
3916 if (strcmp(utsname
.machine
, ISA_64_BIT
) == 0) {
3918 * uname() tells us the machine is 64-bit,
3919 * so we presumably have a 64-bit kernel.
3921 * XXX - this presumes that uname() won't lie
3922 * in 32-bit code and claim that the machine
3923 * has the 32-bit version of the ISA.
3925 handlep
->tp_version
= TPACKET_V1_64
;
3926 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr_64
);
3935 * Attempt to set up memory-mapped access.
3937 * On success, returns 1, and sets *status to 0 if there are no warnings
3938 * or to a PCAP_WARNING_ code if there is a warning.
3940 * On failure due to lack of support for memory-mapped capture, returns
3943 * On error, returns -1, and sets *status to the appropriate error code;
3944 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3947 create_ring(pcap_t
*handle
, int *status
)
3949 struct pcap_linux
*handlep
= handle
->priv
;
3950 unsigned i
, j
, frames_per_block
;
3951 #ifdef HAVE_TPACKET3
3953 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
3954 * stuff at the end of a struct tpacket_req3 will be
3955 * ignored, so this is OK even for those sockets.
3957 struct tpacket_req3 req
;
3959 struct tpacket_req req
;
3962 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3963 unsigned int frame_size
;
3966 * Start out assuming no warnings or errors.
3970 switch (handlep
->tp_version
) {
3974 #ifdef HAVE_TPACKET2
3977 /* Note that with large snapshot length (say 64K, which is
3978 * the default for recent versions of tcpdump, the value that
3979 * "-s 0" has given for a long time with tcpdump, and the
3980 * default in Wireshark/TShark/dumpcap), if we use the snapshot
3981 * length to calculate the frame length, only a few frames
3982 * will be available in the ring even with pretty
3983 * large ring size (and a lot of memory will be unused).
3985 * Ideally, we should choose a frame length based on the
3986 * minimum of the specified snapshot length and the maximum
3987 * packet size. That's not as easy as it sounds; consider,
3988 * for example, an 802.11 interface in monitor mode, where
3989 * the frame would include a radiotap header, where the
3990 * maximum radiotap header length is device-dependent.
3992 * So, for now, we just do this for Ethernet devices, where
3993 * there's no metadata header, and the link-layer header is
3994 * fixed length. We can get the maximum packet size by
3995 * adding 18, the Ethernet header length plus the CRC length
3996 * (just in case we happen to get the CRC in the packet), to
3997 * the MTU of the interface; we fetch the MTU in the hopes
3998 * that it reflects support for jumbo frames. (Even if the
3999 * interface is just being used for passive snooping, the
4000 * driver might set the size of buffers in the receive ring
4001 * based on the MTU, so that the MTU limits the maximum size
4002 * of packets that we can receive.)
4004 * We don't do that if segmentation/fragmentation or receive
4005 * offload are enabled, so we don't get rudely surprised by
4006 * "packets" bigger than the MTU. */
4007 frame_size
= handle
->snapshot
;
4008 if (handle
->linktype
== DLT_EN10MB
) {
4012 offload
= iface_get_offload(handle
);
4013 if (offload
== -1) {
4014 *status
= PCAP_ERROR
;
4018 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
4021 *status
= PCAP_ERROR
;
4024 if (frame_size
> mtu
+ 18)
4025 frame_size
= mtu
+ 18;
4029 /* NOTE: calculus matching those in tpacket_rcv()
4030 * in linux-2.6/net/packet/af_packet.c
4032 len
= sizeof(sk_type
);
4033 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
4035 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4036 "getsockopt: %s", pcap_strerror(errno
));
4037 *status
= PCAP_ERROR
;
4040 #ifdef PACKET_RESERVE
4041 len
= sizeof(tp_reserve
);
4042 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4043 &tp_reserve
, &len
) < 0) {
4044 if (errno
!= ENOPROTOOPT
) {
4046 * ENOPROTOOPT means "kernel doesn't support
4047 * PACKET_RESERVE", in which case we fall back
4050 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4051 "getsockopt: %s", pcap_strerror(errno
));
4052 *status
= PCAP_ERROR
;
4055 tp_reserve
= 0; /* older kernel, reserve not supported */
4058 tp_reserve
= 0; /* older kernel, reserve not supported */
4060 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
4061 /* XXX: in the kernel maclen is calculated from
4062 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4063 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4064 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4065 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4066 * but I see no way to get those sizes in userspace,
4067 * like for instance with an ifreq ioctl();
4068 * the best thing I've found so far is MAX_HEADER in
4069 * the kernel part of linux-2.6/include/linux/netdevice.h
4070 * which goes up to 128+48=176; since pcap-linux.c
4071 * defines a MAX_LINKHEADER_SIZE of 256 which is
4072 * greater than that, let's use it.. maybe is it even
4073 * large enough to directly replace macoff..
4075 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
4076 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
4077 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4078 * of netoff, which contradicts
4079 * linux-2.6/Documentation/networking/packet_mmap.txt
4081 * "- Gap, chosen so that packet data (Start+tp_net)
4082 * aligns to TPACKET_ALIGNMENT=16"
4084 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4085 * "CPUs often take a performance hit
4086 * when accessing unaligned memory locations"
4088 macoff
= netoff
- maclen
;
4089 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
4090 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
4093 #ifdef HAVE_TPACKET3
4095 /* The "frames" for this are actually buffers that
4096 * contain multiple variable-sized frames.
4098 * We pick a "frame" size of 128K to leave enough
4099 * room for at least one reasonably-sized packet
4100 * in the "frame". */
4101 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
4102 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
4106 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4107 "Internal error: unknown TPACKET_ value %u",
4108 handlep
->tp_version
);
4109 *status
= PCAP_ERROR
;
4113 /* compute the minumum block size that will handle this frame.
4114 * The block has to be page size aligned.
4115 * The max block size allowed by the kernel is arch-dependent and
4116 * it's not explicitly checked here. */
4117 req
.tp_block_size
= getpagesize();
4118 while (req
.tp_block_size
< req
.tp_frame_size
)
4119 req
.tp_block_size
<<= 1;
4121 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
4124 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4125 * so we check for PACKET_TIMESTAMP. We check for
4126 * linux/net_tstamp.h just in case a system somehow has
4127 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4130 * SIOCSHWTSTAMP was introduced in the patch that introduced
4131 * linux/net_tstamp.h, so we don't bother checking whether
4132 * SIOCSHWTSTAMP is defined (if your Linux system has
4133 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4134 * Linux system is badly broken).
4136 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4138 * If we were told to do so, ask the kernel and the driver
4139 * to use hardware timestamps.
4141 * Hardware timestamps are only supported with mmapped
4144 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
4145 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
4146 struct hwtstamp_config hwconfig
;
4151 * Ask for hardware time stamps on all packets,
4152 * including transmitted packets.
4154 memset(&hwconfig
, 0, sizeof(hwconfig
));
4155 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
4156 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
4158 memset(&ifr
, 0, sizeof(ifr
));
4159 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
4160 ifr
.ifr_data
= (void *)&hwconfig
;
4162 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
4167 * Treat this as an error, as the
4168 * user should try to run this
4169 * with the appropriate privileges -
4170 * and, if they can't, shouldn't
4171 * try requesting hardware time stamps.
4173 *status
= PCAP_ERROR_PERM_DENIED
;
4178 * Treat this as a warning, as the
4179 * only way to fix the warning is to
4180 * get an adapter that supports hardware
4181 * time stamps. We'll just fall back
4182 * on the standard host time stamps.
4184 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
4188 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4189 "SIOCSHWTSTAMP failed: %s",
4190 pcap_strerror(errno
));
4191 *status
= PCAP_ERROR
;
4196 * Well, that worked. Now specify the type of
4197 * hardware time stamp we want for this
4200 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
4202 * Hardware timestamp, synchronized
4203 * with the system clock.
4205 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
4208 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4209 * timestamp, not synchronized with the
4212 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
4214 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
4215 (void *)×ource
, sizeof(timesource
))) {
4216 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4217 "can't set PACKET_TIMESTAMP: %s",
4218 pcap_strerror(errno
));
4219 *status
= PCAP_ERROR
;
4224 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4226 /* ask the kernel to create the ring */
4228 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
4230 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4231 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
4233 #ifdef HAVE_TPACKET3
4234 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4235 req
.tp_retire_blk_tov
= (handlep
->timeout
>=0)?handlep
->timeout
:0;
4236 /* private data not used */
4237 req
.tp_sizeof_priv
= 0;
4238 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4239 req
.tp_feature_req_word
= 0;
4242 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4243 (void *) &req
, sizeof(req
))) {
4244 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
4246 * Memory failure; try to reduce the requested ring
4249 * We used to reduce this by half -- do 5% instead.
4250 * That may result in more iterations and a longer
4251 * startup, but the user will be much happier with
4252 * the resulting buffer size.
4254 if (req
.tp_frame_nr
< 20)
4255 req
.tp_frame_nr
-= 1;
4257 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
4260 if (errno
== ENOPROTOOPT
) {
4262 * We don't have ring buffer support in this kernel.
4266 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4267 "can't create rx ring on packet socket: %s",
4268 pcap_strerror(errno
));
4269 *status
= PCAP_ERROR
;
4273 /* memory map the rx ring */
4274 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
4275 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
4276 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
4277 if (handlep
->mmapbuf
== MAP_FAILED
) {
4278 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4279 "can't mmap rx ring: %s", pcap_strerror(errno
));
4281 /* clear the allocated ring on error*/
4282 destroy_ring(handle
);
4283 *status
= PCAP_ERROR
;
4287 /* allocate a ring for each frame header pointer*/
4288 handle
->cc
= req
.tp_frame_nr
;
4289 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
4290 if (!handle
->buffer
) {
4291 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4292 "can't allocate ring of frame headers: %s",
4293 pcap_strerror(errno
));
4295 destroy_ring(handle
);
4296 *status
= PCAP_ERROR
;
4300 /* fill the header ring with proper frame ptr*/
4302 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
4303 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
4304 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
4305 RING_GET_CURRENT_FRAME(handle
) = base
;
4306 base
+= req
.tp_frame_size
;
4310 handle
->bufsize
= req
.tp_frame_size
;
4315 /* free all ring related resources*/
4317 destroy_ring(pcap_t
*handle
)
4319 struct pcap_linux
*handlep
= handle
->priv
;
4321 /* tell the kernel to destroy the ring*/
4322 struct tpacket_req req
;
4323 memset(&req
, 0, sizeof(req
));
4324 /* do not test for setsockopt failure, as we can't recover from any error */
4325 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4326 (void *) &req
, sizeof(req
));
4328 /* if ring is mapped, unmap it*/
4329 if (handlep
->mmapbuf
) {
4330 /* do not test for mmap failure, as we can't recover from any error */
4331 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
4332 handlep
->mmapbuf
= NULL
;
4337 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4338 * for Linux mmapped capture.
4340 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4341 * data handed to the callback to be valid after the callback returns,
4342 * but pcap_read_linux_mmap() has to release that packet as soon as
4343 * the callback returns (otherwise, the kernel thinks there's still
4344 * at least one unprocessed packet available in the ring, so a select()
4345 * will immediately return indicating that there's data to process), so,
4346 * in the callback, we have to make a copy of the packet.
4348 * Yes, this means that, if the capture is using the ring buffer, using
4349 * pcap_next() or pcap_next_ex() requires more copies than using
4350 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4351 * pcap_next() or pcap_next_ex().
4354 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
4355 const u_char
*bytes
)
4357 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
4358 pcap_t
*handle
= sp
->pd
;
4359 struct pcap_linux
*handlep
= handle
->priv
;
4362 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
4363 *sp
->pkt
= handlep
->oneshot_buffer
;
4367 pcap_cleanup_linux_mmap( pcap_t
*handle
)
4369 struct pcap_linux
*handlep
= handle
->priv
;
4371 destroy_ring(handle
);
4372 if (handlep
->oneshot_buffer
!= NULL
) {
4373 free(handlep
->oneshot_buffer
);
4374 handlep
->oneshot_buffer
= NULL
;
4376 pcap_cleanup_linux(handle
);
4381 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
4383 struct pcap_linux
*handlep
= p
->priv
;
4385 /* use negative value of timeout to indicate non blocking ops */
4386 return (handlep
->timeout
<0);
4390 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
4392 struct pcap_linux
*handlep
= p
->priv
;
4395 * Set the file descriptor to non-blocking mode, as we use
4396 * it for sending packets.
4398 if (pcap_setnonblock_fd(p
, nonblock
, errbuf
) == -1)
4402 * Map each value to their corresponding negation to
4403 * preserve the timeout value provided with pcap_set_timeout.
4406 if (handlep
->timeout
>= 0) {
4408 * Indicate that we're switching to
4409 * non-blocking mode.
4411 handlep
->timeout
= ~handlep
->timeout
;
4414 if (handlep
->timeout
< 0) {
4415 handlep
->timeout
= ~handlep
->timeout
;
4418 /* Update the timeout to use in poll(). */
4419 set_poll_timeout(handlep
);
4424 * Get the status field of the ring buffer frame at a specified offset.
4427 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
4429 struct pcap_linux
*handlep
= handle
->priv
;
4432 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
4433 switch (handlep
->tp_version
) {
4435 return (h
.h1
->tp_status
);
4438 return (h
.h1_64
->tp_status
);
4440 #ifdef HAVE_TPACKET2
4442 return (h
.h2
->tp_status
);
4445 #ifdef HAVE_TPACKET3
4447 return (h
.h3
->hdr
.bh1
.block_status
);
4451 /* This should not happen. */
4460 * Block waiting for frames to be available.
4462 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4464 struct pcap_linux
*handlep
= handle
->priv
;
4466 struct pollfd pollinfo
;
4469 pollinfo
.fd
= handle
->fd
;
4470 pollinfo
.events
= POLLIN
;
4474 * Yes, we do this even in non-blocking mode, as it's
4475 * the only way to get error indications from a
4478 * The timeout is 0 in non-blocking mode, so poll()
4479 * returns immediately.
4481 ret
= poll(&pollinfo
, 1, handlep
->poll_timeout
);
4482 if (ret
< 0 && errno
!= EINTR
) {
4483 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4484 "can't poll on packet socket: %s",
4485 pcap_strerror(errno
));
4487 } else if (ret
> 0 &&
4488 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4490 * There's some indication other than
4491 * "you can read on this descriptor" on
4494 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
4495 snprintf(handle
->errbuf
,
4497 "Hangup on packet socket");
4500 if (pollinfo
.revents
& POLLERR
) {
4502 * A recv() will give us the actual error code.
4504 * XXX - make the socket non-blocking?
4506 if (recv(handle
->fd
, &c
, sizeof c
,
4508 continue; /* what, no error? */
4509 if (errno
== ENETDOWN
) {
4511 * The device on which we're
4512 * capturing went away.
4514 * XXX - we should really return
4515 * PCAP_ERROR_IFACE_NOT_UP, but
4516 * pcap_dispatch() etc. aren't
4517 * defined to return that.
4519 snprintf(handle
->errbuf
,
4521 "The interface went down");
4523 snprintf(handle
->errbuf
,
4525 "Error condition on packet socket: %s",
4530 if (pollinfo
.revents
& POLLNVAL
) {
4531 snprintf(handle
->errbuf
,
4533 "Invalid polling request on packet socket");
4537 /* check for break loop condition on interrupted syscall*/
4538 if (handle
->break_loop
) {
4539 handle
->break_loop
= 0;
4540 return PCAP_ERROR_BREAK
;
4546 /* handle a single memory mapped packet */
4547 static int pcap_handle_packet_mmap(
4549 pcap_handler callback
,
4551 unsigned char *frame
,
4552 unsigned int tp_len
,
4553 unsigned int tp_mac
,
4554 unsigned int tp_snaplen
,
4555 unsigned int tp_sec
,
4556 unsigned int tp_usec
,
4557 int tp_vlan_tci_valid
,
4561 struct pcap_linux
*handlep
= handle
->priv
;
4563 struct sockaddr_ll
*sll
;
4564 struct pcap_pkthdr pcaphdr
;
4566 /* perform sanity check on internal offset. */
4567 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
4568 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4569 "corrupted frame on kernel ring mac "
4570 "offset %u + caplen %u > frame len %d",
4571 tp_mac
, tp_snaplen
, handle
->bufsize
);
4575 /* run filter on received packet
4576 * If the kernel filtering is enabled we need to run the
4577 * filter until all the frames present into the ring
4578 * at filter creation time are processed.
4579 * In this case, blocks_to_filter_in_userland is used
4580 * as a counter for the packet we need to filter.
4581 * Note: alternatively it could be possible to stop applying
4582 * the filter when the ring became empty, but it can possibly
4583 * happen a lot later... */
4584 bp
= frame
+ tp_mac
;
4586 /* if required build in place the sll header*/
4587 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
4588 if (handlep
->cooked
) {
4589 struct sll_header
*hdrp
;
4592 * The kernel should have left us with enough
4593 * space for an sll header; back up the packet
4594 * data pointer into that space, as that'll be
4595 * the beginning of the packet we pass to the
4601 * Let's make sure that's past the end of
4602 * the tpacket header, i.e. >=
4603 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4604 * don't step on the header when we construct
4607 if (bp
< (u_char
*)frame
+
4608 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4609 sizeof(struct sockaddr_ll
)) {
4610 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4611 "cooked-mode frame doesn't have room for sll header");
4616 * OK, that worked; construct the sll header.
4618 hdrp
= (struct sll_header
*)bp
;
4619 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4621 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4622 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4623 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4624 hdrp
->sll_protocol
= sll
->sll_protocol
;
4627 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
4628 struct bpf_aux_data aux_data
;
4630 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4631 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
4633 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
4634 tp_len
, tp_snaplen
, &aux_data
) == 0)
4638 if (!linux_check_direction(handle
, sll
))
4641 /* get required packet info from ring header */
4642 pcaphdr
.ts
.tv_sec
= tp_sec
;
4643 pcaphdr
.ts
.tv_usec
= tp_usec
;
4644 pcaphdr
.caplen
= tp_snaplen
;
4645 pcaphdr
.len
= tp_len
;
4647 /* if required build in place the sll header*/
4648 if (handlep
->cooked
) {
4649 /* update packet len */
4650 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4651 pcaphdr
.len
+= SLL_HDR_LEN
;
4654 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4655 if (tp_vlan_tci_valid
&&
4656 handlep
->vlan_offset
!= -1 &&
4657 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4659 struct vlan_tag
*tag
;
4662 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4664 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4665 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4666 tag
->vlan_tci
= htons(tp_vlan_tci
);
4668 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4669 pcaphdr
.len
+= VLAN_TAG_LEN
;
4674 * The only way to tell the kernel to cut off the
4675 * packet at a snapshot length is with a filter program;
4676 * if there's no filter program, the kernel won't cut
4679 * Trim the snapshot length to be no longer than the
4680 * specified snapshot length.
4682 if (pcaphdr
.caplen
> handle
->snapshot
)
4683 pcaphdr
.caplen
= handle
->snapshot
;
4685 /* pass the packet to the user */
4686 callback(user
, &pcaphdr
, bp
);
4692 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4695 struct pcap_linux
*handlep
= handle
->priv
;
4700 /* wait for frames availability.*/
4701 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4702 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
) {
4704 * The current frame is owned by the kernel; wait for
4705 * a frame to be handed to us.
4707 ret
= pcap_wait_for_frames_mmap(handle
);
4713 /* non-positive values of max_packets are used to require all
4714 * packets currently available in the ring */
4715 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4717 * Get the current ring buffer frame, and break if
4718 * it's still owned by the kernel.
4720 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4721 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
)
4724 ret
= pcap_handle_packet_mmap(
4739 handlep
->packets_read
++;
4740 } else if (ret
< 0) {
4745 * Hand this block back to the kernel, and, if we're
4746 * counting blocks that need to be filtered in userland
4747 * after having been filtered by the kernel, count
4748 * the one we've just processed.
4750 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4751 if (handlep
->blocks_to_filter_in_userland
> 0) {
4752 handlep
->blocks_to_filter_in_userland
--;
4753 if (handlep
->blocks_to_filter_in_userland
== 0) {
4755 * No more blocks need to be filtered
4758 handlep
->filter_in_userland
= 0;
4763 if (++handle
->offset
>= handle
->cc
)
4766 /* check for break loop condition*/
4767 if (handle
->break_loop
) {
4768 handle
->break_loop
= 0;
4769 return PCAP_ERROR_BREAK
;
4776 pcap_read_linux_mmap_v1_64(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4779 struct pcap_linux
*handlep
= handle
->priv
;
4784 /* wait for frames availability.*/
4785 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4786 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
) {
4788 * The current frame is owned by the kernel; wait for
4789 * a frame to be handed to us.
4791 ret
= pcap_wait_for_frames_mmap(handle
);
4797 /* non-positive values of max_packets are used to require all
4798 * packets currently available in the ring */
4799 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4801 * Get the current ring buffer frame, and break if
4802 * it's still owned by the kernel.
4804 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4805 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
)
4808 ret
= pcap_handle_packet_mmap(
4815 h
.h1_64
->tp_snaplen
,
4823 handlep
->packets_read
++;
4824 } else if (ret
< 0) {
4829 * Hand this block back to the kernel, and, if we're
4830 * counting blocks that need to be filtered in userland
4831 * after having been filtered by the kernel, count
4832 * the one we've just processed.
4834 h
.h1_64
->tp_status
= TP_STATUS_KERNEL
;
4835 if (handlep
->blocks_to_filter_in_userland
> 0) {
4836 handlep
->blocks_to_filter_in_userland
--;
4837 if (handlep
->blocks_to_filter_in_userland
== 0) {
4839 * No more blocks need to be filtered
4842 handlep
->filter_in_userland
= 0;
4847 if (++handle
->offset
>= handle
->cc
)
4850 /* check for break loop condition*/
4851 if (handle
->break_loop
) {
4852 handle
->break_loop
= 0;
4853 return PCAP_ERROR_BREAK
;
4859 #ifdef HAVE_TPACKET2
4861 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4864 struct pcap_linux
*handlep
= handle
->priv
;
4869 /* wait for frames availability.*/
4870 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4871 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
) {
4873 * The current frame is owned by the kernel; wait for
4874 * a frame to be handed to us.
4876 ret
= pcap_wait_for_frames_mmap(handle
);
4882 /* non-positive values of max_packets are used to require all
4883 * packets currently available in the ring */
4884 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4886 * Get the current ring buffer frame, and break if
4887 * it's still owned by the kernel.
4889 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4890 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
)
4893 ret
= pcap_handle_packet_mmap(
4902 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4903 #if defined(TP_STATUS_VLAN_VALID)
4904 (h
.h2
->tp_vlan_tci
|| (h
.h2
->tp_status
& TP_STATUS_VLAN_VALID
)),
4906 h
.h2
->tp_vlan_tci
!= 0,
4909 VLAN_TPID(h
.h2
, h
.h2
));
4912 handlep
->packets_read
++;
4913 } else if (ret
< 0) {
4918 * Hand this block back to the kernel, and, if we're
4919 * counting blocks that need to be filtered in userland
4920 * after having been filtered by the kernel, count
4921 * the one we've just processed.
4923 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4924 if (handlep
->blocks_to_filter_in_userland
> 0) {
4925 handlep
->blocks_to_filter_in_userland
--;
4926 if (handlep
->blocks_to_filter_in_userland
== 0) {
4928 * No more blocks need to be filtered
4931 handlep
->filter_in_userland
= 0;
4936 if (++handle
->offset
>= handle
->cc
)
4939 /* check for break loop condition*/
4940 if (handle
->break_loop
) {
4941 handle
->break_loop
= 0;
4942 return PCAP_ERROR_BREAK
;
4947 #endif /* HAVE_TPACKET2 */
4949 #ifdef HAVE_TPACKET3
4951 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4954 struct pcap_linux
*handlep
= handle
->priv
;
4960 if (handlep
->current_packet
== NULL
) {
4961 /* wait for frames availability.*/
4962 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4963 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4965 * The current frame is owned by the kernel; wait
4966 * for a frame to be handed to us.
4968 ret
= pcap_wait_for_frames_mmap(handle
);
4974 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4975 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4976 if (pkts
== 0 && handlep
->timeout
== 0) {
4977 /* Block until we see a packet. */
4983 /* non-positive values of max_packets are used to require all
4984 * packets currently available in the ring */
4985 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4986 if (handlep
->current_packet
== NULL
) {
4987 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4988 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
)
4991 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4992 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4994 int packets_to_read
= handlep
->packets_left
;
4996 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) && packets_to_read
> max_packets
) {
4997 packets_to_read
= max_packets
;
5000 while(packets_to_read
--) {
5001 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
5002 ret
= pcap_handle_packet_mmap(
5006 handlep
->current_packet
,
5009 tp3_hdr
->tp_snaplen
,
5011 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
5012 #if defined(TP_STATUS_VLAN_VALID)
5013 (tp3_hdr
->hv1
.tp_vlan_tci
|| (tp3_hdr
->tp_status
& TP_STATUS_VLAN_VALID
)),
5015 tp3_hdr
->hv1
.tp_vlan_tci
!= 0,
5017 tp3_hdr
->hv1
.tp_vlan_tci
,
5018 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
5021 handlep
->packets_read
++;
5022 } else if (ret
< 0) {
5023 handlep
->current_packet
= NULL
;
5026 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
5027 handlep
->packets_left
--;
5030 if (handlep
->packets_left
<= 0) {
5032 * Hand this block back to the kernel, and, if
5033 * we're counting blocks that need to be
5034 * filtered in userland after having been
5035 * filtered by the kernel, count the one we've
5038 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
5039 if (handlep
->blocks_to_filter_in_userland
> 0) {
5040 handlep
->blocks_to_filter_in_userland
--;
5041 if (handlep
->blocks_to_filter_in_userland
== 0) {
5043 * No more blocks need to be filtered
5046 handlep
->filter_in_userland
= 0;
5051 if (++handle
->offset
>= handle
->cc
)
5054 handlep
->current_packet
= NULL
;
5057 /* check for break loop condition*/
5058 if (handle
->break_loop
) {
5059 handle
->break_loop
= 0;
5060 return PCAP_ERROR_BREAK
;
5063 if (pkts
== 0 && handlep
->timeout
== 0) {
5064 /* Block until we see a packet. */
5069 #endif /* HAVE_TPACKET3 */
5072 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
5074 struct pcap_linux
*handlep
= handle
->priv
;
5079 * Don't rewrite "ret" instructions; we don't need to, as
5080 * we're not reading packets with recvmsg(), and we don't
5081 * want to, as, by not rewriting them, the kernel can avoid
5082 * copying extra data.
5084 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
5089 * If we're filtering in userland, there's nothing to do;
5090 * the new filter will be used for the next packet.
5092 if (handlep
->filter_in_userland
)
5096 * We're filtering in the kernel; the packets present in
5097 * all blocks currently in the ring were already filtered
5098 * by the old filter, and so will need to be filtered in
5099 * userland by the new filter.
5101 * Get an upper bound for the number of such blocks; first,
5102 * walk the ring backward and count the free blocks.
5104 offset
= handle
->offset
;
5106 offset
= handle
->cc
- 1;
5107 for (n
=0; n
< handle
->cc
; ++n
) {
5109 offset
= handle
->cc
- 1;
5110 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
5115 * If we found free blocks, decrement the count of free
5116 * blocks by 1, just in case we lost a race with another
5117 * thread of control that was adding a packet while
5118 * we were counting and that had run the filter before
5121 * XXX - could there be more than one block added in
5124 * XXX - is there a way to avoid that race, e.g. somehow
5125 * wait for all packets that passed the old filter to
5126 * be added to the ring?
5132 * Set the count of blocks worth of packets to filter
5133 * in userland to the total number of blocks in the
5134 * ring minus the number of free blocks we found, and
5135 * turn on userland filtering. (The count of blocks
5136 * worth of packets to filter in userland is guaranteed
5137 * not to be zero - n, above, couldn't be set to a
5138 * value > handle->cc, and if it were equal to
5139 * handle->cc, it wouldn't be zero, and thus would
5140 * be decremented to handle->cc - 1.)
5142 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
5143 handlep
->filter_in_userland
= 1;
5147 #endif /* HAVE_PACKET_RING */
5150 #ifdef HAVE_PF_PACKET_SOCKETS
5152 * Return the index of the given device name. Fill ebuf and return
5156 iface_get_id(int fd
, const char *device
, char *ebuf
)
5160 memset(&ifr
, 0, sizeof(ifr
));
5161 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5163 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
5164 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5165 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
5169 return ifr
.ifr_ifindex
;
5173 * Bind the socket associated with FD to the given device.
5174 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
5175 * or a PCAP_ERROR_ value on a hard error.
5178 iface_bind(int fd
, int ifindex
, char *ebuf
)
5180 struct sockaddr_ll sll
;
5182 socklen_t errlen
= sizeof(err
);
5184 memset(&sll
, 0, sizeof(sll
));
5185 sll
.sll_family
= AF_PACKET
;
5186 sll
.sll_ifindex
= ifindex
;
5187 sll
.sll_protocol
= htons(ETH_P_ALL
);
5189 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
5190 if (errno
== ENETDOWN
) {
5192 * Return a "network down" indication, so that
5193 * the application can report that rather than
5194 * saying we had a mysterious failure and
5195 * suggest that they report a problem to the
5196 * libpcap developers.
5198 return PCAP_ERROR_IFACE_NOT_UP
;
5200 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5201 "bind: %s", pcap_strerror(errno
));
5206 /* Any pending errors, e.g., network is down? */
5208 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5209 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5210 "getsockopt: %s", pcap_strerror(errno
));
5214 if (err
== ENETDOWN
) {
5216 * Return a "network down" indication, so that
5217 * the application can report that rather than
5218 * saying we had a mysterious failure and
5219 * suggest that they report a problem to the
5220 * libpcap developers.
5222 return PCAP_ERROR_IFACE_NOT_UP
;
5223 } else if (err
> 0) {
5224 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5225 "bind: %s", pcap_strerror(err
));
5232 #ifdef IW_MODE_MONITOR
5234 * Check whether the device supports the Wireless Extensions.
5235 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5236 * if the device doesn't even exist.
5239 has_wext(int sock_fd
, const char *device
, char *ebuf
)
5243 if (is_bonding_device(sock_fd
, device
))
5244 return 0; /* bonding device, so don't even try */
5246 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5247 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5248 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
5250 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5251 "%s: SIOCGIWNAME: %s", device
, pcap_strerror(errno
));
5252 if (errno
== ENODEV
)
5253 return PCAP_ERROR_NO_SUCH_DEVICE
;
5258 * Per me si va ne la citta dolente,
5259 * Per me si va ne l'etterno dolore,
5261 * Lasciate ogne speranza, voi ch'intrate.
5263 * XXX - airmon-ng does special stuff with the Orinoco driver and the
5279 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5280 * on if it's not already on.
5282 * Returns 1 on success, 0 if we don't support the Wireless Extensions
5283 * on this device, or a PCAP_ERROR_ value if we do support them but
5284 * we weren't able to turn monitor mode on.
5287 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
5290 * XXX - at least some adapters require non-Wireless Extensions
5291 * mechanisms to turn monitor mode on.
5293 * Atheros cards might require that a separate "monitor virtual access
5294 * point" be created, with later versions of the madwifi driver.
5295 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
5296 * monitor -bssid", which apparently spits out a line "athN"
5297 * where "athN" is the monitor mode device. To leave monitor
5298 * mode, it destroys the monitor mode device.
5300 * Some Intel Centrino adapters might require private ioctls to get
5301 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5302 * configure a separate "rtapN" interface to capture in monitor
5303 * mode without preventing the adapter from operating normally.
5304 * (airmon-ng doesn't appear to use that, though.)
5306 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5307 * up, and if all drivers were converted to mac80211 drivers.
5309 * If interface {if} is a mac80211 driver, the file
5310 * /sys/class/net/{if}/phy80211 is a symlink to
5311 * /sys/class/ieee80211/{phydev}, for some {phydev}.
5313 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5314 * least, has a "wmaster0" device and a "wlan0" device; the
5315 * latter is the one with the IP address. Both show up in
5316 * "tcpdump -D" output. Capturing on the wmaster0 device
5317 * captures with 802.11 headers.
5319 * airmon-ng searches through /sys/class/net for devices named
5320 * monN, starting with mon0; as soon as one *doesn't* exist,
5321 * it chooses that as the monitor device name. If the "iw"
5322 * command exists, it does "iw dev {if} interface add {monif}
5323 * type monitor", where {monif} is the monitor device. It
5324 * then (sigh) sleeps .1 second, and then configures the
5325 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
5326 * is a file, it writes {mondev}, without a newline, to that file,
5327 * and again (sigh) sleeps .1 second, and then iwconfig's that
5328 * device into monitor mode and configures it up. Otherwise,
5329 * you can't do monitor mode.
5331 * All these devices are "glued" together by having the
5332 * /sys/class/net/{device}/phy80211 links pointing to the same
5333 * place, so, given a wmaster, wlan, or mon device, you can
5334 * find the other devices by looking for devices with
5335 * the same phy80211 link.
5337 * To turn monitor mode off, delete the monitor interface,
5338 * either with "iw dev {monif} interface del" or by sending
5339 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
5341 * Note: if you try to create a monitor device named "monN", and
5342 * there's already a "monN" device, it fails, as least with
5343 * the netlink interface (which is what iw uses), with a return
5344 * value of -ENFILE. (Return values are negative errnos.) We
5345 * could probably use that to find an unused device.
5347 struct pcap_linux
*handlep
= handle
->priv
;
5350 struct iw_priv_args
*priv
;
5351 monitor_type montype
;
5360 * Does this device *support* the Wireless Extensions?
5362 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
5364 return err
; /* either it doesn't or the device doesn't even exist */
5366 * Start out assuming we have no private extensions to control
5369 montype
= MONITOR_WEXT
;
5373 * Try to get all the Wireless Extensions private ioctls
5374 * supported by this device.
5376 * First, get the size of the buffer we need, by supplying no
5377 * buffer and a length of 0. If the device supports private
5378 * ioctls, it should return E2BIG, with ireq.u.data.length set
5379 * to the length we need. If it doesn't support them, it should
5380 * return EOPNOTSUPP.
5382 memset(&ireq
, 0, sizeof ireq
);
5383 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5384 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5385 ireq
.u
.data
.pointer
= (void *)args
;
5386 ireq
.u
.data
.length
= 0;
5387 ireq
.u
.data
.flags
= 0;
5388 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
5389 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5390 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
5394 if (errno
!= EOPNOTSUPP
) {
5396 * OK, it's not as if there are no private ioctls.
5398 if (errno
!= E2BIG
) {
5402 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5403 "%s: SIOCGIWPRIV: %s", device
,
5404 pcap_strerror(errno
));
5409 * OK, try to get the list of private ioctls.
5411 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
5413 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5414 "malloc: %s", pcap_strerror(errno
));
5417 ireq
.u
.data
.pointer
= (void *)priv
;
5418 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
5419 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5420 "%s: SIOCGIWPRIV: %s", device
,
5421 pcap_strerror(errno
));
5427 * Look for private ioctls to turn monitor mode on or, if
5428 * monitor mode is on, to set the header type.
5430 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
5431 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
5433 * Hostap driver, use this one.
5434 * Set monitor mode first.
5435 * You can set it to 0 to get DLT_IEEE80211,
5436 * 1 to get DLT_PRISM, 2 to get
5437 * DLT_IEEE80211_RADIO_AVS, and, with more
5438 * recent versions of the driver, 3 to get
5439 * DLT_IEEE80211_RADIO.
5441 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5443 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5445 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5447 montype
= MONITOR_HOSTAP
;
5451 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
5453 * Prism54 driver, use this one.
5454 * Set monitor mode first.
5455 * You can set it to 2 to get DLT_IEEE80211
5456 * or 3 or get DLT_PRISM.
5458 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5460 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5462 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5464 montype
= MONITOR_PRISM54
;
5468 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
5470 * RT2570 driver, use this one.
5471 * Do this after turning monitor mode on.
5472 * You can set it to 1 to get DLT_PRISM or 2
5473 * to get DLT_IEEE80211.
5475 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5477 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5479 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5481 montype
= MONITOR_RT2570
;
5485 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
5487 * RT73 driver, use this one.
5488 * Do this after turning monitor mode on.
5489 * Its argument is a *string*; you can
5490 * set it to "1" to get DLT_PRISM or "2"
5491 * to get DLT_IEEE80211.
5493 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
5495 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
5497 montype
= MONITOR_RT73
;
5501 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
5503 * One of the RTL8xxx drivers, use this one.
5504 * It can only be done after monitor mode
5505 * has been turned on. You can set it to 1
5506 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5508 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5510 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5512 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5514 montype
= MONITOR_RTL8XXX
;
5518 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
5520 * RT2500 or RT61 driver, use this one.
5521 * It has one one-byte parameter; set
5522 * u.data.length to 1 and u.data.pointer to
5523 * point to the parameter.
5524 * It doesn't itself turn monitor mode on.
5525 * You can set it to 1 to allow transmitting
5526 * in monitor mode(?) and get DLT_IEEE80211,
5527 * or set it to 0 to disallow transmitting in
5528 * monitor mode(?) and get DLT_PRISM.
5530 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5532 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
5534 montype
= MONITOR_RT2500
;
5538 if (strcmp(priv
[i
].name
, "monitor") == 0) {
5540 * Either ACX100 or hostap, use this one.
5541 * It turns monitor mode on.
5542 * If it takes two arguments, it's ACX100;
5543 * the first argument is 1 for DLT_PRISM
5544 * or 2 for DLT_IEEE80211, and the second
5545 * argument is the channel on which to
5546 * run. If it takes one argument, it's
5547 * HostAP, and the argument is 2 for
5548 * DLT_IEEE80211 and 3 for DLT_PRISM.
5550 * If we see this, we don't quit, as this
5551 * might be a version of the hostap driver
5552 * that also supports "monitor_type".
5554 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5556 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5558 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5561 montype
= MONITOR_PRISM
;
5566 montype
= MONITOR_ACX100
;
5579 * XXX - ipw3945? islism?
5585 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5586 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5587 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
5589 * We probably won't be able to set the mode, either.
5591 return PCAP_ERROR_RFMON_NOTSUP
;
5595 * Is it currently in monitor mode?
5597 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
5599 * Yes. Just leave things as they are.
5600 * We don't offer multiple link-layer types, as
5601 * changing the link-layer type out from under
5602 * somebody else capturing in monitor mode would
5603 * be considered rude.
5608 * No. We have to put the adapter into rfmon mode.
5612 * If we haven't already done so, arrange to have
5613 * "pcap_close_all()" called when we exit.
5615 if (!pcap_do_addexit(handle
)) {
5617 * "atexit()" failed; don't put the interface
5618 * in rfmon mode, just give up.
5620 return PCAP_ERROR_RFMON_NOTSUP
;
5624 * Save the old mode.
5626 handlep
->oldmode
= ireq
.u
.mode
;
5629 * Put the adapter in rfmon mode. How we do this depends
5630 * on whether we have a special private ioctl or not.
5632 if (montype
== MONITOR_PRISM
) {
5634 * We have the "monitor" private ioctl, but none of
5635 * the other private ioctls. Use this, and select
5638 * If it fails, just fall back on SIOCSIWMODE.
5640 memset(&ireq
, 0, sizeof ireq
);
5641 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5642 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5643 ireq
.u
.data
.length
= 1; /* 1 argument */
5644 args
[0] = 3; /* request Prism header */
5645 memcpy(ireq
.u
.name
, args
, sizeof (int));
5646 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
5649 * Note that we have to put the old mode back
5650 * when we close the device.
5652 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5655 * Add this to the list of pcaps to close
5658 pcap_add_to_pcaps_to_close(handle
);
5664 * Failure. Fall back on SIOCSIWMODE.
5669 * First, take the interface down if it's up; otherwise, we
5672 memset(&ifr
, 0, sizeof(ifr
));
5673 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5674 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5675 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5676 "%s: Can't get flags: %s", device
, strerror(errno
));
5680 if (ifr
.ifr_flags
& IFF_UP
) {
5681 oldflags
= ifr
.ifr_flags
;
5682 ifr
.ifr_flags
&= ~IFF_UP
;
5683 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5684 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5685 "%s: Can't set flags: %s", device
, strerror(errno
));
5691 * Then turn monitor mode on.
5693 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5694 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5695 ireq
.u
.mode
= IW_MODE_MONITOR
;
5696 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
5698 * Scientist, you've failed.
5699 * Bring the interface back up if we shut it down.
5701 ifr
.ifr_flags
= oldflags
;
5702 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5703 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5704 "%s: Can't set flags: %s", device
, strerror(errno
));
5707 return PCAP_ERROR_RFMON_NOTSUP
;
5711 * XXX - airmon-ng does "iwconfig {if} key off" after setting
5712 * monitor mode and setting the channel, and then does
5717 * Now select the appropriate radio header.
5723 * We don't have any private ioctl to set the header.
5727 case MONITOR_HOSTAP
:
5729 * Try to select the radiotap header.
5731 memset(&ireq
, 0, sizeof ireq
);
5732 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5733 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5734 args
[0] = 3; /* request radiotap header */
5735 memcpy(ireq
.u
.name
, args
, sizeof (int));
5736 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5737 break; /* success */
5740 * That failed. Try to select the AVS header.
5742 memset(&ireq
, 0, sizeof ireq
);
5743 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5744 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5745 args
[0] = 2; /* request AVS header */
5746 memcpy(ireq
.u
.name
, args
, sizeof (int));
5747 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5748 break; /* success */
5751 * That failed. Try to select the Prism header.
5753 memset(&ireq
, 0, sizeof ireq
);
5754 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5755 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5756 args
[0] = 1; /* request Prism header */
5757 memcpy(ireq
.u
.name
, args
, sizeof (int));
5758 ioctl(sock_fd
, cmd
, &ireq
);
5763 * The private ioctl failed.
5767 case MONITOR_PRISM54
:
5769 * Select the Prism header.
5771 memset(&ireq
, 0, sizeof ireq
);
5772 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5773 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5774 args
[0] = 3; /* request Prism header */
5775 memcpy(ireq
.u
.name
, args
, sizeof (int));
5776 ioctl(sock_fd
, cmd
, &ireq
);
5779 case MONITOR_ACX100
:
5781 * Get the current channel.
5783 memset(&ireq
, 0, sizeof ireq
);
5784 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5785 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5786 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
5787 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5788 "%s: SIOCGIWFREQ: %s", device
,
5789 pcap_strerror(errno
));
5792 channel
= ireq
.u
.freq
.m
;
5795 * Select the Prism header, and set the channel to the
5798 memset(&ireq
, 0, sizeof ireq
);
5799 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5800 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5801 args
[0] = 1; /* request Prism header */
5802 args
[1] = channel
; /* set channel */
5803 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
5804 ioctl(sock_fd
, cmd
, &ireq
);
5807 case MONITOR_RT2500
:
5809 * Disallow transmission - that turns on the
5812 memset(&ireq
, 0, sizeof ireq
);
5813 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5814 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5815 args
[0] = 0; /* disallow transmitting */
5816 memcpy(ireq
.u
.name
, args
, sizeof (int));
5817 ioctl(sock_fd
, cmd
, &ireq
);
5820 case MONITOR_RT2570
:
5822 * Force the Prism header.
5824 memset(&ireq
, 0, sizeof ireq
);
5825 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5826 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5827 args
[0] = 1; /* request Prism header */
5828 memcpy(ireq
.u
.name
, args
, sizeof (int));
5829 ioctl(sock_fd
, cmd
, &ireq
);
5834 * Force the Prism header.
5836 memset(&ireq
, 0, sizeof ireq
);
5837 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5838 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5839 ireq
.u
.data
.length
= 1; /* 1 argument */
5840 ireq
.u
.data
.pointer
= "1";
5841 ireq
.u
.data
.flags
= 0;
5842 ioctl(sock_fd
, cmd
, &ireq
);
5845 case MONITOR_RTL8XXX
:
5847 * Force the Prism header.
5849 memset(&ireq
, 0, sizeof ireq
);
5850 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5851 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5852 args
[0] = 1; /* request Prism header */
5853 memcpy(ireq
.u
.name
, args
, sizeof (int));
5854 ioctl(sock_fd
, cmd
, &ireq
);
5859 * Now bring the interface back up if we brought it down.
5861 if (oldflags
!= 0) {
5862 ifr
.ifr_flags
= oldflags
;
5863 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5864 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5865 "%s: Can't set flags: %s", device
, strerror(errno
));
5868 * At least try to restore the old mode on the
5871 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
5873 * Scientist, you've failed.
5876 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5877 "Please adjust manually.\n",
5885 * Note that we have to put the old mode back when we
5888 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5891 * Add this to the list of pcaps to close when we exit.
5893 pcap_add_to_pcaps_to_close(handle
);
5897 #endif /* IW_MODE_MONITOR */
5900 * Try various mechanisms to enter monitor mode.
5903 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
5905 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5910 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
5912 return ret
; /* error attempting to do so */
5914 return 1; /* success */
5915 #endif /* HAVE_LIBNL */
5917 #ifdef IW_MODE_MONITOR
5918 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
5920 return ret
; /* error attempting to do so */
5922 return 1; /* success */
5923 #endif /* IW_MODE_MONITOR */
5926 * Either none of the mechanisms we know about work or none
5927 * of those mechanisms are available, so we can't do monitor
5933 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5935 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5937 static const struct {
5938 int soft_timestamping_val
;
5939 int pcap_tstamp_val
;
5940 } sof_ts_type_map
[3] = {
5941 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5942 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5943 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5945 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5948 iface_set_default_ts_types(pcap_t
*handle
)
5952 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5953 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5954 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5955 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5958 #ifdef ETHTOOL_GET_TS_INFO
5960 * Get a list of time stamping capabilities.
5963 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
)
5967 struct ethtool_ts_info info
;
5972 * This doesn't apply to the "any" device; you have to ask
5973 * specific devices for their capabilities, so just default
5974 * to saying we support all of them.
5976 if (strcmp(handle
->opt
.source
, "any") == 0) {
5977 iface_set_default_ts_types(handle
);
5982 * Create a socket from which to fetch time stamping capabilities.
5984 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
5986 (void)snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5987 "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO): %s", pcap_strerror(errno
));
5991 memset(&ifr
, 0, sizeof(ifr
));
5992 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5993 memset(&info
, 0, sizeof(info
));
5994 info
.cmd
= ETHTOOL_GET_TS_INFO
;
5995 ifr
.ifr_data
= (caddr_t
)&info
;
5996 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
5998 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
6000 * OK, let's just return all the possible time
6003 iface_set_default_ts_types(handle
);
6006 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6007 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: %s", handle
->opt
.source
,
6014 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6015 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
6018 handle
->tstamp_type_count
= num_ts_types
;
6019 if (num_ts_types
!= 0) {
6020 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
6021 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6022 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
6023 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6028 handle
->tstamp_type_list
= NULL
;
6032 #else /* ETHTOOL_GET_TS_INFO */
6034 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf _U_
)
6037 * We don't have an ioctl to use to ask what's supported,
6038 * so say we support everything.
6040 iface_set_default_ts_types(handle
);
6043 #endif /* ETHTOOL_GET_TS_INFO */
6045 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6047 #ifdef HAVE_PACKET_RING
6049 * Find out if we have any form of fragmentation/reassembly offloading.
6051 * We do so using SIOCETHTOOL checking for various types of offloading;
6052 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6053 * of the types of offloading, there's nothing we can do to check, so
6054 * we just say "no, we don't".
6056 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6058 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
6061 struct ethtool_value eval
;
6063 memset(&ifr
, 0, sizeof(ifr
));
6064 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
6067 ifr
.ifr_data
= (caddr_t
)&eval
;
6068 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
6069 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
6071 * OK, let's just return 0, which, in our
6072 * case, either means "no, what we're asking
6073 * about is not enabled" or "all the flags
6074 * are clear (i.e., nothing is enabled)".
6078 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6079 "%s: SIOCETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
6080 cmdname
, strerror(errno
));
6087 iface_get_offload(pcap_t
*handle
)
6092 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
6096 return 1; /* TCP segmentation offloading on */
6100 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
6104 return 1; /* UDP fragmentation offloading on */
6109 * XXX - will this cause large unsegmented packets to be
6110 * handed to PF_PACKET sockets on transmission? If not,
6111 * this need not be checked.
6113 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
6117 return 1; /* generic segmentation offloading on */
6120 #ifdef ETHTOOL_GFLAGS
6121 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
6124 if (ret
& ETH_FLAG_LRO
)
6125 return 1; /* large receive offloading on */
6130 * XXX - will this cause large reassembled packets to be
6131 * handed to PF_PACKET sockets on receipt? If not,
6132 * this need not be checked.
6134 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
6138 return 1; /* generic (large) receive offloading on */
6143 #else /* SIOCETHTOOL */
6145 iface_get_offload(pcap_t
*handle _U_
)
6148 * XXX - do we need to get this information if we don't
6149 * have the ethtool ioctls? If so, how do we do that?
6153 #endif /* SIOCETHTOOL */
6155 #endif /* HAVE_PACKET_RING */
6157 #endif /* HAVE_PF_PACKET_SOCKETS */
6159 /* ===== Functions to interface to the older kernels ================== */
6162 * Try to open a packet socket using the old kernel interface.
6163 * Returns 1 on success and a PCAP_ERROR_ value on an error.
6166 activate_old(pcap_t
*handle
)
6168 struct pcap_linux
*handlep
= handle
->priv
;
6171 const char *device
= handle
->opt
.source
;
6172 struct utsname utsname
;
6175 /* Open the socket */
6177 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
6178 if (handle
->fd
== -1) {
6179 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6180 "socket: %s", pcap_strerror(errno
));
6181 if (errno
== EPERM
|| errno
== EACCES
) {
6183 * You don't have permission to open the
6186 return PCAP_ERROR_PERM_DENIED
;
6195 /* It worked - we are using the old interface */
6196 handlep
->sock_packet
= 1;
6198 /* ...which means we get the link-layer header. */
6199 handlep
->cooked
= 0;
6201 /* Bind to the given device */
6203 if (strcmp(device
, "any") == 0) {
6204 strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
6208 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
6212 * Try to get the link-layer type.
6214 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
6219 * Try to find the DLT_ type corresponding to that
6222 map_arphrd_to_dlt(handle
, handle
->fd
, arptype
, device
, 0);
6223 if (handle
->linktype
== -1) {
6224 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6225 "unknown arptype %d", arptype
);
6229 /* Go to promisc mode if requested */
6231 if (handle
->opt
.promisc
) {
6232 memset(&ifr
, 0, sizeof(ifr
));
6233 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6234 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6235 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6236 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
6239 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
6241 * Promiscuous mode isn't currently on,
6242 * so turn it on, and remember that
6243 * we should turn it off when the
6248 * If we haven't already done so, arrange
6249 * to have "pcap_close_all()" called when
6252 if (!pcap_do_addexit(handle
)) {
6254 * "atexit()" failed; don't put
6255 * the interface in promiscuous
6256 * mode, just give up.
6261 ifr
.ifr_flags
|= IFF_PROMISC
;
6262 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6263 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6265 pcap_strerror(errno
));
6268 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
6271 * Add this to the list of pcaps
6272 * to close when we exit.
6274 pcap_add_to_pcaps_to_close(handle
);
6279 * Compute the buffer size.
6281 * We're using SOCK_PACKET, so this might be a 2.0[.x]
6282 * kernel, and might require special handling - check.
6284 if (uname(&utsname
) < 0 ||
6285 strncmp(utsname
.release
, "2.0", 3) == 0) {
6287 * Either we couldn't find out what kernel release
6288 * this is, or it's a 2.0[.x] kernel.
6290 * In the 2.0[.x] kernel, a "recvfrom()" on
6291 * a SOCK_PACKET socket, with MSG_TRUNC set, will
6292 * return the number of bytes read, so if we pass
6293 * a length based on the snapshot length, it'll
6294 * return the number of bytes from the packet
6295 * copied to userland, not the actual length
6298 * This means that, for example, the IP dissector
6299 * in tcpdump will get handed a packet length less
6300 * than the length in the IP header, and will
6301 * complain about "truncated-ip".
6303 * So we don't bother trying to copy from the
6304 * kernel only the bytes in which we're interested,
6305 * but instead copy them all, just as the older
6306 * versions of libpcap for Linux did.
6308 * The buffer therefore needs to be big enough to
6309 * hold the largest packet we can get from this
6310 * device. Unfortunately, we can't get the MRU
6311 * of the network; we can only get the MTU. The
6312 * MTU may be too small, in which case a packet larger
6313 * than the buffer size will be truncated *and* we
6314 * won't get the actual packet size.
6316 * However, if the snapshot length is larger than
6317 * the buffer size based on the MTU, we use the
6318 * snapshot length as the buffer size, instead;
6319 * this means that with a sufficiently large snapshot
6320 * length we won't artificially truncate packets
6321 * to the MTU-based size.
6323 * This mess just one of many problems with packet
6324 * capture on 2.0[.x] kernels; you really want a
6325 * 2.2[.x] or later kernel if you want packet capture
6328 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
6331 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
6332 if (handle
->bufsize
< handle
->snapshot
)
6333 handle
->bufsize
= handle
->snapshot
;
6336 * This is a 2.2[.x] or later kernel.
6338 * We can safely pass "recvfrom()" a byte count
6339 * based on the snapshot length.
6341 handle
->bufsize
= handle
->snapshot
;
6345 * Default value for offset to align link-layer payload
6346 * on a 4-byte boundary.
6351 * SOCK_PACKET sockets don't supply information from
6352 * stripped VLAN tags.
6354 handlep
->vlan_offset
= -1; /* unknown */
6360 * Bind the socket associated with FD to the given device using the
6361 * interface of the old kernels.
6364 iface_bind_old(int fd
, const char *device
, char *ebuf
)
6366 struct sockaddr saddr
;
6368 socklen_t errlen
= sizeof(err
);
6370 memset(&saddr
, 0, sizeof(saddr
));
6371 strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
6372 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
6373 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6374 "bind: %s", pcap_strerror(errno
));
6378 /* Any pending errors, e.g., network is down? */
6380 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
6381 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6382 "getsockopt: %s", pcap_strerror(errno
));
6387 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6388 "bind: %s", pcap_strerror(err
));
6396 /* ===== System calls available on all supported kernels ============== */
6399 * Query the kernel for the MTU of the given interface.
6402 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
6407 return BIGGER_THAN_ALL_MTUS
;
6409 memset(&ifr
, 0, sizeof(ifr
));
6410 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6412 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
6413 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6414 "SIOCGIFMTU: %s", pcap_strerror(errno
));
6422 * Get the hardware type of the given interface as ARPHRD_xxx constant.
6425 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
6429 memset(&ifr
, 0, sizeof(ifr
));
6430 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6432 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
6433 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6434 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
6435 if (errno
== ENODEV
) {
6439 return PCAP_ERROR_NO_SUCH_DEVICE
;
6444 return ifr
.ifr_hwaddr
.sa_family
;
6447 #ifdef SO_ATTACH_FILTER
6449 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
6451 struct pcap_linux
*handlep
= handle
->priv
;
6454 register struct bpf_insn
*p
;
6459 * Make a copy of the filter, and modify that copy if
6462 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
6463 len
= handle
->fcode
.bf_len
;
6464 f
= (struct bpf_insn
*)malloc(prog_size
);
6466 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6467 "malloc: %s", pcap_strerror(errno
));
6470 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
6472 fcode
->filter
= (struct sock_filter
*) f
;
6474 for (i
= 0; i
< len
; ++i
) {
6477 * What type of instruction is this?
6479 switch (BPF_CLASS(p
->code
)) {
6483 * It's a return instruction; are we capturing
6484 * in memory-mapped mode?
6488 * No; is the snapshot length a constant,
6489 * rather than the contents of the
6492 if (BPF_MODE(p
->code
) == BPF_K
) {
6494 * Yes - if the value to be returned,
6495 * i.e. the snapshot length, is
6496 * anything other than 0, make it
6497 * MAXIMUM_SNAPLEN, so that the packet
6498 * is truncated by "recvfrom()",
6499 * not by the filter.
6501 * XXX - there's nothing we can
6502 * easily do if it's getting the
6503 * value from the accumulator; we'd
6504 * have to insert code to force
6505 * non-zero values to be
6509 p
->k
= MAXIMUM_SNAPLEN
;
6517 * It's a load instruction; is it loading
6520 switch (BPF_MODE(p
->code
)) {
6526 * Yes; are we in cooked mode?
6528 if (handlep
->cooked
) {
6530 * Yes, so we need to fix this
6533 if (fix_offset(p
) < 0) {
6535 * We failed to do so.
6536 * Return 0, so our caller
6537 * knows to punt to userland.
6547 return 1; /* we succeeded */
6551 fix_offset(struct bpf_insn
*p
)
6554 * What's the offset?
6556 if (p
->k
>= SLL_HDR_LEN
) {
6558 * It's within the link-layer payload; that starts at an
6559 * offset of 0, as far as the kernel packet filter is
6560 * concerned, so subtract the length of the link-layer
6563 p
->k
-= SLL_HDR_LEN
;
6564 } else if (p
->k
== 0) {
6566 * It's the packet type field; map it to the special magic
6567 * kernel offset for that field.
6569 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6570 } else if (p
->k
== 14) {
6572 * It's the protocol field; map it to the special magic
6573 * kernel offset for that field.
6575 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6576 } else if ((bpf_int32
)(p
->k
) > 0) {
6578 * It's within the header, but it's not one of those
6579 * fields; we can't do that in the kernel, so punt
6588 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
6590 int total_filter_on
= 0;
6596 * The socket filter code doesn't discard all packets queued
6597 * up on the socket when the filter is changed; this means
6598 * that packets that don't match the new filter may show up
6599 * after the new filter is put onto the socket, if those
6600 * packets haven't yet been read.
6602 * This means, for example, that if you do a tcpdump capture
6603 * with a filter, the first few packets in the capture might
6604 * be packets that wouldn't have passed the filter.
6606 * We therefore discard all packets queued up on the socket
6607 * when setting a kernel filter. (This isn't an issue for
6608 * userland filters, as the userland filtering is done after
6609 * packets are queued up.)
6611 * To flush those packets, we put the socket in read-only mode,
6612 * and read packets from the socket until there are no more to
6615 * In order to keep that from being an infinite loop - i.e.,
6616 * to keep more packets from arriving while we're draining
6617 * the queue - we put the "total filter", which is a filter
6618 * that rejects all packets, onto the socket before draining
6621 * This code deliberately ignores any errors, so that you may
6622 * get bogus packets if an error occurs, rather than having
6623 * the filtering done in userland even if it could have been
6624 * done in the kernel.
6626 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6627 &total_fcode
, sizeof(total_fcode
)) == 0) {
6631 * Note that we've put the total filter onto the socket.
6633 total_filter_on
= 1;
6636 * Save the socket's current mode, and put it in
6637 * non-blocking mode; we drain it by reading packets
6638 * until we get an error (which is normally a
6639 * "nothing more to be read" error).
6641 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6642 if (save_mode
== -1) {
6643 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6644 "can't get FD flags when changing filter: %s",
6645 pcap_strerror(errno
));
6648 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
6649 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6650 "can't set nonblocking mode when changing filter: %s",
6651 pcap_strerror(errno
));
6654 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
6657 if (save_errno
!= EAGAIN
) {
6661 * If we can't restore the mode or reset the
6662 * kernel filter, there's nothing we can do.
6664 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
6665 (void)reset_kernel_filter(handle
);
6666 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6667 "recv failed when changing filter: %s",
6668 pcap_strerror(save_errno
));
6671 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
6672 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6673 "can't restore FD flags when changing filter: %s",
6674 pcap_strerror(save_errno
));
6680 * Now attach the new filter.
6682 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6683 fcode
, sizeof(*fcode
));
6684 if (ret
== -1 && total_filter_on
) {
6686 * Well, we couldn't set that filter on the socket,
6687 * but we could set the total filter on the socket.
6689 * This could, for example, mean that the filter was
6690 * too big to put into the kernel, so we'll have to
6691 * filter in userland; in any case, we'll be doing
6692 * filtering in userland, so we need to remove the
6693 * total filter so we see packets.
6698 * If this fails, we're really screwed; we have the
6699 * total filter on the socket, and it won't come off.
6700 * Report it as a fatal error.
6702 if (reset_kernel_filter(handle
) == -1) {
6703 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6704 "can't remove kernel total filter: %s",
6705 pcap_strerror(errno
));
6706 return -2; /* fatal error */
6715 reset_kernel_filter(pcap_t
*handle
)
6718 * setsockopt() barfs unless it get a dummy parameter.
6719 * valgrind whines unless the value is initialized,
6720 * as it has no idea that setsockopt() ignores its
6725 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6726 &dummy
, sizeof(dummy
));