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
));
757 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
758 "%s: nl_put failed adding %s interface",
765 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
766 const char *device
, const char *mondevice
)
772 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
778 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
779 "%s: failed to allocate netlink msg", device
);
783 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
784 0, NL80211_CMD_DEL_INTERFACE
, 0);
785 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
787 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
789 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
790 "%s: nl_send_auto_complete failed deleting %s interface: %s",
791 device
, mondevice
, get_nl_errmsg(-err
));
795 err
= nl_wait_for_ack(state
->nl_sock
);
797 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
798 "%s: nl_wait_for_ack failed adding %s interface: %s",
799 device
, mondevice
, get_nl_errmsg(-err
));
811 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
812 "%s: nl_put failed deleting %s interface",
819 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
821 struct pcap_linux
*handlep
= handle
->priv
;
823 char phydev_path
[PATH_MAX
+1];
824 struct nl80211_state nlstate
;
829 * Is this a mac80211 device?
831 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
833 return ret
; /* error */
835 return 0; /* no error, but not mac80211 device */
838 * XXX - is this already a monN device?
840 * Is that determined by old Wireless Extensions ioctls?
844 * OK, it's apparently a mac80211 device.
845 * Try to find an unused monN device for it.
847 ret
= nl80211_init(handle
, &nlstate
, device
);
850 for (n
= 0; n
< UINT_MAX
; n
++) {
854 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
856 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
857 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
859 handlep
->mondevice
= strdup(mondevice
);
864 * Hard failure. Just return ret; handle->errbuf
865 * has already been set.
867 nl80211_cleanup(&nlstate
);
872 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
873 "%s: No free monN interfaces", device
);
874 nl80211_cleanup(&nlstate
);
881 * Sleep for .1 seconds.
884 delay
.tv_nsec
= 500000000;
885 nanosleep(&delay
, NULL
);
889 * If we haven't already done so, arrange to have
890 * "pcap_close_all()" called when we exit.
892 if (!pcap_do_addexit(handle
)) {
894 * "atexit()" failed; don't put the interface
895 * in rfmon mode, just give up.
897 return PCAP_ERROR_RFMON_NOTSUP
;
901 * Now configure the monitor interface up.
903 memset(&ifr
, 0, sizeof(ifr
));
904 strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
905 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
906 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
907 "%s: Can't get flags for %s: %s", device
,
908 handlep
->mondevice
, strerror(errno
));
909 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
911 nl80211_cleanup(&nlstate
);
914 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
915 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
916 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
917 "%s: Can't set flags for %s: %s", device
,
918 handlep
->mondevice
, strerror(errno
));
919 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
921 nl80211_cleanup(&nlstate
);
926 * Success. Clean up the libnl state.
928 nl80211_cleanup(&nlstate
);
931 * Note that we have to delete the monitor device when we close
934 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
937 * Add this to the list of pcaps to close when we exit.
939 pcap_add_to_pcaps_to_close(handle
);
943 #endif /* HAVE_LIBNL */
945 #ifdef IW_MODE_MONITOR
947 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
948 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
949 * will fail with ENODEV if we try to do them on a bonding device,
950 * making us return a "no such device" indication rather than just
951 * saying "no Wireless Extensions".
953 * So we check for bonding devices, if we can, before trying those
954 * ioctls, by trying a bonding device information query ioctl to see
955 * whether it succeeds.
958 is_bonding_device(int fd
, const char *device
)
960 #if defined(HAVE_LINUX_IF_BONDING_H) && \
961 (defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY))
965 memset(&ifr
, 0, sizeof ifr
);
966 strlcpy(ifr
.ifr_name
, device
, sizeof ifr
.ifr_name
);
967 memset(&ifb
, 0, sizeof ifb
);
968 ifr
.ifr_data
= (caddr_t
)&ifb
;
969 #ifdef SIOCBONDINFOQUERY
970 if (ioctl(fd
, SIOCBONDINFOQUERY
, &ifr
) == 0)
971 #else /* SIOCBONDINFOQUERY */
972 if (ioctl(fd
, BOND_INFO_QUERY_OLD
, &ifr
) == 0)
973 #endif /* SIOCBONDINFOQUERY */
974 return 1; /* success, so it's a bonding device */
975 #endif /* defined(HAVE_LINUX_IF_BONDING_H) && \
976 (defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY)) */
978 return 0; /* no, it's not a bonding device */
980 #endif /* IW_MODE_MONITOR */
983 pcap_can_set_rfmon_linux(pcap_t
*handle
)
986 char phydev_path
[PATH_MAX
+1];
989 #ifdef IW_MODE_MONITOR
994 if (strcmp(handle
->opt
.source
, "any") == 0) {
996 * Monitor mode makes no sense on the "any" device.
1003 * Bleah. There doesn't seem to be a way to ask a mac80211
1004 * device, through libnl, whether it supports monitor mode;
1005 * we'll just check whether the device appears to be a
1006 * mac80211 device and, if so, assume the device supports
1009 * wmaster devices don't appear to support the Wireless
1010 * Extensions, but we can create a mon device for a
1011 * wmaster device, so we don't bother checking whether
1012 * a mac80211 device supports the Wireless Extensions.
1014 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
1017 return ret
; /* error */
1019 return 1; /* mac80211 device */
1022 #ifdef IW_MODE_MONITOR
1024 * Bleah. There doesn't appear to be an ioctl to use to ask
1025 * whether a device supports monitor mode; we'll just do
1026 * SIOCGIWMODE and, if it succeeds, assume the device supports
1029 * Open a socket on which to attempt to get the mode.
1030 * (We assume that if we have Wireless Extensions support
1031 * we also have PF_PACKET support.)
1033 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
1034 if (sock_fd
== -1) {
1035 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1036 "socket: %s", pcap_strerror(errno
));
1040 if (is_bonding_device(sock_fd
, handle
->opt
.source
)) {
1041 /* It's a bonding device, so don't even try. */
1047 * Attempt to get the current mode.
1049 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
1050 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1051 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1053 * Well, we got the mode; assume we can set it.
1058 if (errno
== ENODEV
) {
1059 /* The device doesn't even exist. */
1060 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1061 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
1063 return PCAP_ERROR_NO_SUCH_DEVICE
;
1071 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1073 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1074 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1076 * Or can we get them in binary form from netlink?
1079 linux_if_drops(const char * if_name
)
1084 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1085 long int dropped_pkts
= 0;
1087 file
= fopen("/proc/net/dev", "r");
1091 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1093 /* search for 'bytes' -- if its in there, then
1094 that means we need to grab the fourth field. otherwise
1095 grab the third field. */
1096 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1098 field_to_convert
= 4;
1102 /* find iface and make sure it actually matches -- space before the name and : after it */
1103 if ((bufptr
= strstr(buffer
, if_name
)) &&
1104 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1105 *(bufptr
+ if_name_sz
) == ':')
1107 bufptr
= bufptr
+ if_name_sz
+ 1;
1109 /* grab the nth field from it */
1110 while( --field_to_convert
&& *bufptr
!= '\0')
1112 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1113 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1116 /* get rid of any final spaces */
1117 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1119 if (*bufptr
!= '\0')
1120 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1127 return dropped_pkts
;
1132 * With older kernels promiscuous mode is kind of interesting because we
1133 * have to reset the interface before exiting. The problem can't really
1134 * be solved without some daemon taking care of managing usage counts.
1135 * If we put the interface into promiscuous mode, we set a flag indicating
1136 * that we must take it out of that mode when the interface is closed,
1137 * and, when closing the interface, if that flag is set we take it out
1138 * of promiscuous mode.
1140 * Even with newer kernels, we have the same issue with rfmon mode.
1143 static void pcap_cleanup_linux( pcap_t
*handle
)
1145 struct pcap_linux
*handlep
= handle
->priv
;
1148 struct nl80211_state nlstate
;
1150 #endif /* HAVE_LIBNL */
1151 #ifdef IW_MODE_MONITOR
1154 #endif /* IW_MODE_MONITOR */
1156 if (handlep
->must_do_on_close
!= 0) {
1158 * There's something we have to do when closing this
1161 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1163 * We put the interface into promiscuous mode;
1164 * take it out of promiscuous mode.
1166 * XXX - if somebody else wants it in promiscuous
1167 * mode, this code cannot know that, so it'll take
1168 * it out of promiscuous mode. That's not fixable
1169 * in 2.0[.x] kernels.
1171 memset(&ifr
, 0, sizeof(ifr
));
1172 strlcpy(ifr
.ifr_name
, handlep
->device
,
1173 sizeof(ifr
.ifr_name
));
1174 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1176 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1177 "Please adjust manually.\n"
1178 "Hint: This can't happen with Linux >= 2.2.0.\n",
1179 handlep
->device
, strerror(errno
));
1181 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1183 * Promiscuous mode is currently on;
1186 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1187 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1190 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1191 "Please adjust manually.\n"
1192 "Hint: This can't happen with Linux >= 2.2.0.\n",
1201 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1202 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1204 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1205 handlep
->device
, handlep
->mondevice
);
1206 nl80211_cleanup(&nlstate
);
1210 "Can't delete monitor interface %s (%s).\n"
1211 "Please delete manually.\n",
1212 handlep
->mondevice
, handle
->errbuf
);
1215 #endif /* HAVE_LIBNL */
1217 #ifdef IW_MODE_MONITOR
1218 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1220 * We put the interface into rfmon mode;
1221 * take it out of rfmon mode.
1223 * XXX - if somebody else wants it in rfmon
1224 * mode, this code cannot know that, so it'll take
1225 * it out of rfmon mode.
1229 * First, take the interface down if it's up;
1230 * otherwise, we might get EBUSY.
1231 * If we get errors, just drive on and print
1232 * a warning if we can't restore the mode.
1235 memset(&ifr
, 0, sizeof(ifr
));
1236 strlcpy(ifr
.ifr_name
, handlep
->device
,
1237 sizeof(ifr
.ifr_name
));
1238 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1239 if (ifr
.ifr_flags
& IFF_UP
) {
1240 oldflags
= ifr
.ifr_flags
;
1241 ifr
.ifr_flags
&= ~IFF_UP
;
1242 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1243 oldflags
= 0; /* didn't set, don't restore */
1248 * Now restore the mode.
1250 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1251 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1252 ireq
.u
.mode
= handlep
->oldmode
;
1253 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1255 * Scientist, you've failed.
1258 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1259 "Please adjust manually.\n",
1260 handlep
->device
, strerror(errno
));
1264 * Now bring the interface back up if we brought
1267 if (oldflags
!= 0) {
1268 ifr
.ifr_flags
= oldflags
;
1269 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1271 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1272 "Please adjust manually.\n",
1273 handlep
->device
, strerror(errno
));
1277 #endif /* IW_MODE_MONITOR */
1280 * Take this pcap out of the list of pcaps for which we
1281 * have to take the interface out of some mode.
1283 pcap_remove_from_pcaps_to_close(handle
);
1286 if (handlep
->mondevice
!= NULL
) {
1287 free(handlep
->mondevice
);
1288 handlep
->mondevice
= NULL
;
1290 if (handlep
->device
!= NULL
) {
1291 free(handlep
->device
);
1292 handlep
->device
= NULL
;
1294 pcap_cleanup_live_common(handle
);
1298 * Set the timeout to be used in poll() with memory-mapped packet capture.
1301 set_poll_timeout(struct pcap_linux
*handlep
)
1303 #ifdef HAVE_TPACKET3
1304 struct utsname utsname
;
1305 char *version_component
, *endp
;
1307 int broken_tpacket_v3
= 1;
1310 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1311 * around which we have to work. Determine if we have those
1314 if (uname(&utsname
) == 0) {
1316 * 3.19 is the first release with a fixed version of
1317 * TPACKET_V3. We treat anything before that as
1318 * not haveing a fixed version; that may really mean
1319 * it has *no* version.
1321 version_component
= utsname
.release
;
1322 major
= strtol(version_component
, &endp
, 10);
1323 if (endp
!= version_component
&& *endp
== '.') {
1325 * OK, that was a valid major version.
1326 * Get the minor version.
1328 version_component
= endp
+ 1;
1329 minor
= strtol(version_component
, &endp
, 10);
1330 if (endp
!= version_component
&&
1331 (*endp
== '.' || *endp
== '\0')) {
1333 * OK, that was a valid minor version.
1334 * Is this 3.19 or newer?
1336 if (major
>= 4 || (major
== 3 && minor
>= 19)) {
1337 /* Yes. TPACKET_V3 works correctly. */
1338 broken_tpacket_v3
= 0;
1344 if (handlep
->timeout
== 0) {
1345 #ifdef HAVE_TPACKET3
1347 * XXX - due to a set of (mis)features in the TPACKET_V3
1348 * kernel code prior to the 3.19 kernel, blocking forever
1349 * with a TPACKET_V3 socket can, if few packets are
1350 * arriving and passing the socket filter, cause most
1351 * packets to be dropped. See libpcap issue #335 for the
1352 * full painful story.
1354 * The workaround is to have poll() time out very quickly,
1355 * so we grab the frames handed to us, and return them to
1358 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1359 handlep
->poll_timeout
= 1; /* don't block for very long */
1362 handlep
->poll_timeout
= -1; /* block forever */
1363 } else if (handlep
->timeout
> 0) {
1365 * For TPACKET_V3, the timeout is handled by the kernel,
1366 * so block forever; that way, we don't get extra timeouts.
1367 * Don't do that if we have a broken TPACKET_V3, though.
1369 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1370 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1372 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1374 handlep
->poll_timeout
= 0; /* non-blocking mode - poll to pick up errors */
1378 * Get a handle for a live capture from the given device. You can
1379 * pass NULL as device to get all packages (without link level
1380 * information of course). If you pass 1 as promisc the interface
1381 * will be set to promiscous mode (XXX: I think this usage should
1382 * be deprecated and functions be added to select that later allow
1383 * modification of that values -- Torsten).
1386 pcap_activate_linux(pcap_t
*handle
)
1388 struct pcap_linux
*handlep
= handle
->priv
;
1394 device
= handle
->opt
.source
;
1397 * Make sure the name we were handed will fit into the ioctls we
1398 * might perform on the device; if not, return a "No such device"
1399 * indication, as the Linux kernel shouldn't support creating
1400 * a device whose name won't fit into those ioctls.
1402 * "Will fit" means "will fit, complete with a null terminator",
1403 * so if the length, which does *not* include the null terminator,
1404 * is greater than *or equal to* the size of the field into which
1405 * we'll be copying it, that won't fit.
1407 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1408 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1412 handle
->inject_op
= pcap_inject_linux
;
1413 handle
->setfilter_op
= pcap_setfilter_linux
;
1414 handle
->setdirection_op
= pcap_setdirection_linux
;
1415 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1416 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1417 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1418 handle
->cleanup_op
= pcap_cleanup_linux
;
1419 handle
->read_op
= pcap_read_linux
;
1420 handle
->stats_op
= pcap_stats_linux
;
1423 * The "any" device is a special device which causes us not
1424 * to bind to a particular device and thus to look at all
1427 if (strcmp(device
, "any") == 0) {
1428 if (handle
->opt
.promisc
) {
1429 handle
->opt
.promisc
= 0;
1430 /* Just a warning. */
1431 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1432 "Promiscuous mode not supported on the \"any\" device");
1433 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1437 handlep
->device
= strdup(device
);
1438 if (handlep
->device
== NULL
) {
1439 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1440 pcap_strerror(errno
) );
1444 /* copy timeout value */
1445 handlep
->timeout
= handle
->opt
.timeout
;
1448 * If we're in promiscuous mode, then we probably want
1449 * to see when the interface drops packets too, so get an
1450 * initial count from /proc/net/dev
1452 if (handle
->opt
.promisc
)
1453 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1456 * Current Linux kernels use the protocol family PF_PACKET to
1457 * allow direct access to all packets on the network while
1458 * older kernels had a special socket type SOCK_PACKET to
1459 * implement this feature.
1460 * While this old implementation is kind of obsolete we need
1461 * to be compatible with older kernels for a while so we are
1462 * trying both methods with the newer method preferred.
1464 ret
= activate_new(handle
);
1467 * Fatal error with the new way; just fail.
1468 * ret has the error return; if it's PCAP_ERROR,
1469 * handle->errbuf has been set appropriately.
1477 * Try to use memory-mapped access.
1479 switch (activate_mmap(handle
, &status
)) {
1483 * We succeeded. status has been
1484 * set to the status to return,
1485 * which might be 0, or might be
1486 * a PCAP_WARNING_ value.
1488 * Set the timeout to use in poll() before
1491 set_poll_timeout(handlep
);
1496 * Kernel doesn't support it - just continue
1497 * with non-memory-mapped access.
1503 * We failed to set up to use it, or the kernel
1504 * supports it, but we failed to enable it.
1505 * ret has been set to the error status to
1506 * return and, if it's PCAP_ERROR, handle->errbuf
1507 * contains the error message.
1513 else if (ret
== 0) {
1514 /* Non-fatal error; try old way */
1515 if ((ret
= activate_old(handle
)) != 1) {
1517 * Both methods to open the packet socket failed.
1518 * Tidy up and report our failure (handle->errbuf
1519 * is expected to be set by the functions above).
1527 * We set up the socket, but not with memory-mapped access.
1529 if (handle
->opt
.buffer_size
!= 0) {
1531 * Set the socket buffer size to the specified value.
1533 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1534 &handle
->opt
.buffer_size
,
1535 sizeof(handle
->opt
.buffer_size
)) == -1) {
1536 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1537 "SO_RCVBUF: %s", pcap_strerror(errno
));
1538 status
= PCAP_ERROR
;
1543 /* Allocate the buffer */
1545 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1546 if (!handle
->buffer
) {
1547 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1548 "malloc: %s", pcap_strerror(errno
));
1549 status
= PCAP_ERROR
;
1554 * "handle->fd" is a socket, so "select()" and "poll()"
1555 * should work on it.
1557 handle
->selectable_fd
= handle
->fd
;
1562 pcap_cleanup_linux(handle
);
1567 * Read at most max_packets from the capture stream and call the callback
1568 * for each of them. Returns the number of packets handled or -1 if an
1572 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1575 * Currently, on Linux only one packet is delivered per read,
1578 return pcap_read_packet(handle
, callback
, user
);
1582 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1584 handle
->linktype
= dlt
;
1589 * linux_check_direction()
1591 * Do checks based on packet direction.
1594 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1596 struct pcap_linux
*handlep
= handle
->priv
;
1598 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1601 * If this is from the loopback device, reject it;
1602 * we'll see the packet as an incoming packet as well,
1603 * and we don't want to see it twice.
1605 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1609 * If the user only wants incoming packets, reject it.
1611 if (handle
->direction
== PCAP_D_IN
)
1616 * If the user only wants outgoing packets, reject it.
1618 if (handle
->direction
== PCAP_D_OUT
)
1625 * Read a packet from the socket calling the handler provided by
1626 * the user. Returns the number of packets received or -1 if an
1630 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1632 struct pcap_linux
*handlep
= handle
->priv
;
1635 #ifdef HAVE_PF_PACKET_SOCKETS
1636 struct sockaddr_ll from
;
1637 struct sll_header
*hdrp
;
1639 struct sockaddr from
;
1641 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1644 struct cmsghdr
*cmsg
;
1646 struct cmsghdr cmsg
;
1647 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1649 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1651 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1652 int packet_len
, caplen
;
1653 struct pcap_pkthdr pcap_header
;
1655 struct bpf_aux_data aux_data
;
1656 #ifdef HAVE_PF_PACKET_SOCKETS
1658 * If this is a cooked device, leave extra room for a
1659 * fake packet header.
1661 if (handlep
->cooked
)
1662 offset
= SLL_HDR_LEN
;
1667 * This system doesn't have PF_PACKET sockets, so it doesn't
1668 * support cooked devices.
1674 * Receive a single packet from the kernel.
1675 * We ignore EINTR, as that might just be due to a signal
1676 * being delivered - if the signal should interrupt the
1677 * loop, the signal handler should call pcap_breakloop()
1678 * to set handle->break_loop (we ignore it on other
1679 * platforms as well).
1680 * We also ignore ENETDOWN, so that we can continue to
1681 * capture traffic if the interface goes down and comes
1682 * back up again; comments in the kernel indicate that
1683 * we'll just block waiting for packets if we try to
1684 * receive from a socket that delivered ENETDOWN, and,
1685 * if we're using a memory-mapped buffer, we won't even
1686 * get notified of "network down" events.
1688 bp
= handle
->buffer
+ handle
->offset
;
1690 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1691 msg
.msg_name
= &from
;
1692 msg
.msg_namelen
= sizeof(from
);
1695 msg
.msg_control
= &cmsg_buf
;
1696 msg
.msg_controllen
= sizeof(cmsg_buf
);
1699 iov
.iov_len
= handle
->bufsize
- offset
;
1700 iov
.iov_base
= bp
+ offset
;
1701 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1705 * Has "pcap_breakloop()" been called?
1707 if (handle
->break_loop
) {
1709 * Yes - clear the flag that indicates that it has,
1710 * and return PCAP_ERROR_BREAK as an indication that
1711 * we were told to break out of the loop.
1713 handle
->break_loop
= 0;
1714 return PCAP_ERROR_BREAK
;
1717 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1718 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1719 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1720 fromlen
= sizeof(from
);
1721 packet_len
= recvfrom(
1722 handle
->fd
, bp
+ offset
,
1723 handle
->bufsize
- offset
, MSG_TRUNC
,
1724 (struct sockaddr
*) &from
, &fromlen
);
1725 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1726 } while (packet_len
== -1 && errno
== EINTR
);
1728 /* Check if an error occured */
1730 if (packet_len
== -1) {
1734 return 0; /* no packet there */
1738 * The device on which we're capturing went away.
1740 * XXX - we should really return
1741 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1742 * etc. aren't defined to return that.
1744 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1745 "The interface went down");
1749 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1750 "recvfrom: %s", pcap_strerror(errno
));
1755 #ifdef HAVE_PF_PACKET_SOCKETS
1756 if (!handlep
->sock_packet
) {
1758 * Unfortunately, there is a window between socket() and
1759 * bind() where the kernel may queue packets from any
1760 * interface. If we're bound to a particular interface,
1761 * discard packets not from that interface.
1763 * (If socket filters are supported, we could do the
1764 * same thing we do when changing the filter; however,
1765 * that won't handle packet sockets without socket
1766 * filter support, and it's a bit more complicated.
1767 * It would save some instructions per packet, however.)
1769 if (handlep
->ifindex
!= -1 &&
1770 from
.sll_ifindex
!= handlep
->ifindex
)
1774 * Do checks based on packet direction.
1775 * We can only do this if we're using PF_PACKET; the
1776 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1777 * which lacks the relevant packet type information.
1779 if (!linux_check_direction(handle
, &from
))
1784 #ifdef HAVE_PF_PACKET_SOCKETS
1786 * If this is a cooked device, fill in the fake packet header.
1788 if (handlep
->cooked
) {
1790 * Add the length of the fake header to the length
1791 * of packet data we read.
1793 packet_len
+= SLL_HDR_LEN
;
1795 hdrp
= (struct sll_header
*)bp
;
1796 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1797 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1798 hdrp
->sll_halen
= htons(from
.sll_halen
);
1799 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1800 (from
.sll_halen
> SLL_ADDRLEN
) ?
1803 hdrp
->sll_protocol
= from
.sll_protocol
;
1806 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1807 if (handlep
->vlan_offset
!= -1) {
1808 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1809 struct tpacket_auxdata
*aux
;
1811 struct vlan_tag
*tag
;
1813 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1814 cmsg
->cmsg_level
!= SOL_PACKET
||
1815 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1818 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1819 #if defined(TP_STATUS_VLAN_VALID)
1820 if ((aux
->tp_vlan_tci
== 0) && !(aux
->tp_status
& TP_STATUS_VLAN_VALID
))
1822 if (aux
->tp_vlan_tci
== 0) /* this is ambigious but without the
1823 TP_STATUS_VLAN_VALID flag, there is
1824 nothing that we can do */
1828 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1829 if (len
< (unsigned int) handlep
->vlan_offset
)
1833 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1835 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1836 tag
->vlan_tpid
= htons(VLAN_TPID(aux
, aux
));
1837 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1839 /* store vlan tci to bpf_aux_data struct for userland bpf filter */
1840 #if defined(TP_STATUS_VLAN_VALID)
1841 aux_data
.vlan_tag
= htons(aux
->tp_vlan_tci
) & 0x0fff;
1842 aux_data
.vlan_tag_present
= (aux
->tp_status
& TP_STATUS_VLAN_VALID
);
1844 packet_len
+= VLAN_TAG_LEN
;
1847 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1848 #endif /* HAVE_PF_PACKET_SOCKETS */
1851 * XXX: According to the kernel source we should get the real
1852 * packet len if calling recvfrom with MSG_TRUNC set. It does
1853 * not seem to work here :(, but it is supported by this code
1855 * To be honest the code RELIES on that feature so this is really
1856 * broken with 2.2.x kernels.
1857 * I spend a day to figure out what's going on and I found out
1858 * that the following is happening:
1860 * The packet comes from a random interface and the packet_rcv
1861 * hook is called with a clone of the packet. That code inserts
1862 * the packet into the receive queue of the packet socket.
1863 * If a filter is attached to that socket that filter is run
1864 * first - and there lies the problem. The default filter always
1865 * cuts the packet at the snaplen:
1870 * So the packet filter cuts down the packet. The recvfrom call
1871 * says "hey, it's only 68 bytes, it fits into the buffer" with
1872 * the result that we don't get the real packet length. This
1873 * is valid at least until kernel 2.2.17pre6.
1875 * We currently handle this by making a copy of the filter
1876 * program, fixing all "ret" instructions with non-zero
1877 * operands to have an operand of MAXIMUM_SNAPLEN so that the
1878 * filter doesn't truncate the packet, and supplying that modified
1879 * filter to the kernel.
1882 caplen
= packet_len
;
1883 if (caplen
> handle
->snapshot
)
1884 caplen
= handle
->snapshot
;
1886 /* Run the packet filter if not using kernel filter */
1887 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
1888 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
1889 packet_len
, caplen
, &aux_data
) == 0) {
1890 /* rejected by filter */
1895 /* Fill in our own header data */
1897 /* get timestamp for this packet */
1898 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1899 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
1900 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
1901 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1902 "SIOCGSTAMPNS: %s", pcap_strerror(errno
));
1908 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1909 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1910 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1915 pcap_header
.caplen
= caplen
;
1916 pcap_header
.len
= packet_len
;
1921 * Arguably, we should count them before we check the filter,
1922 * as on many other platforms "ps_recv" counts packets
1923 * handed to the filter rather than packets that passed
1924 * the filter, but if filtering is done in the kernel, we
1925 * can't get a count of packets that passed the filter,
1926 * and that would mean the meaning of "ps_recv" wouldn't
1927 * be the same on all Linux systems.
1929 * XXX - it's not the same on all systems in any case;
1930 * ideally, we should have a "get the statistics" call
1931 * that supplies more counts and indicates which of them
1932 * it supplies, so that we supply a count of packets
1933 * handed to the filter only on platforms where that
1934 * information is available.
1936 * We count them here even if we can get the packet count
1937 * from the kernel, as we can only determine at run time
1938 * whether we'll be able to get it from the kernel (if
1939 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1940 * the kernel, but if it is defined, the library might
1941 * have been built with a 2.4 or later kernel, but we
1942 * might be running on a 2.2[.x] kernel without Alexey
1943 * Kuznetzov's turbopacket patches, and thus the kernel
1944 * might not be able to supply those statistics). We
1945 * could, I guess, try, when opening the socket, to get
1946 * the statistics, and if we can not increment the count
1947 * here, but it's not clear that always incrementing
1948 * the count is more expensive than always testing a flag
1951 * We keep the count in "handlep->packets_read", and use that
1952 * for "ps_recv" if we can't get the statistics from the kernel.
1953 * We do that because, if we *can* get the statistics from
1954 * the kernel, we use "handlep->stat.ps_recv" and
1955 * "handlep->stat.ps_drop" as running counts, as reading the
1956 * statistics from the kernel resets the kernel statistics,
1957 * and if we directly increment "handlep->stat.ps_recv" here,
1958 * that means it will count packets *twice* on systems where
1959 * we can get kernel statistics - once here, and once in
1960 * pcap_stats_linux().
1962 handlep
->packets_read
++;
1964 /* Call the user supplied callback function */
1965 callback(userdata
, &pcap_header
, bp
);
1971 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1973 struct pcap_linux
*handlep
= handle
->priv
;
1976 #ifdef HAVE_PF_PACKET_SOCKETS
1977 if (!handlep
->sock_packet
) {
1978 /* PF_PACKET socket */
1979 if (handlep
->ifindex
== -1) {
1981 * We don't support sending on the "any" device.
1983 strlcpy(handle
->errbuf
,
1984 "Sending packets isn't supported on the \"any\" device",
1989 if (handlep
->cooked
) {
1991 * We don't support sending on the "any" device.
1993 * XXX - how do you send on a bound cooked-mode
1995 * Is a "sendto()" required there?
1997 strlcpy(handle
->errbuf
,
1998 "Sending packets isn't supported in cooked mode",
2005 ret
= send(handle
->fd
, buf
, size
, 0);
2007 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
2008 pcap_strerror(errno
));
2015 * Get the statistics for the given packet capture handle.
2016 * Reports the number of dropped packets iff the kernel supports
2017 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2018 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2019 * patches); otherwise, that information isn't available, and we lie
2020 * and report 0 as the count of dropped packets.
2023 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
2025 struct pcap_linux
*handlep
= handle
->priv
;
2026 #ifdef HAVE_TPACKET_STATS
2027 #ifdef HAVE_TPACKET3
2029 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2030 * stuff at the end of a struct tpacket_stats_v3 will not
2031 * be filled in, and we don't look at it so this is OK even
2032 * for those sockets. In addition, the PF_PACKET socket
2033 * code in the kernel only uses the length parameter to
2034 * compute how much data to copy out and to indicate how
2035 * much data was copied out, so it's OK to base it on the
2036 * size of a struct tpacket_stats.
2038 * XXX - it's probably OK, in fact, to just use a
2039 * struct tpacket_stats for V3 sockets, as we don't
2040 * care about the tp_freeze_q_cnt stat.
2042 struct tpacket_stats_v3 kstats
;
2043 #else /* HAVE_TPACKET3 */
2044 struct tpacket_stats kstats
;
2045 #endif /* HAVE_TPACKET3 */
2046 socklen_t len
= sizeof (struct tpacket_stats
);
2047 #endif /* HAVE_TPACKET_STATS */
2049 long if_dropped
= 0;
2052 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
2054 if (handle
->opt
.promisc
)
2056 if_dropped
= handlep
->proc_dropped
;
2057 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
2058 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
2061 #ifdef HAVE_TPACKET_STATS
2063 * Try to get the packet counts from the kernel.
2065 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
2066 &kstats
, &len
) > -1) {
2068 * On systems where the PACKET_STATISTICS "getsockopt()"
2069 * argument is supported on PF_PACKET sockets:
2071 * "ps_recv" counts only packets that *passed* the
2072 * filter, not packets that didn't pass the filter.
2073 * This includes packets later dropped because we
2074 * ran out of buffer space.
2076 * "ps_drop" counts packets dropped because we ran
2077 * out of buffer space. It doesn't count packets
2078 * dropped by the interface driver. It counts only
2079 * packets that passed the filter.
2081 * See above for ps_ifdrop.
2083 * Both statistics include packets not yet read from
2084 * the kernel by libpcap, and thus not yet seen by
2087 * In "linux/net/packet/af_packet.c", at least in the
2088 * 2.4.9 kernel, "tp_packets" is incremented for every
2089 * packet that passes the packet filter *and* is
2090 * successfully queued on the socket; "tp_drops" is
2091 * incremented for every packet dropped because there's
2092 * not enough free space in the socket buffer.
2094 * When the statistics are returned for a PACKET_STATISTICS
2095 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2096 * so that "tp_packets" counts all packets handed to
2097 * the PF_PACKET socket, including packets dropped because
2098 * there wasn't room on the socket buffer - but not
2099 * including packets that didn't pass the filter.
2101 * In the BSD BPF, the count of received packets is
2102 * incremented for every packet handed to BPF, regardless
2103 * of whether it passed the filter.
2105 * We can't make "pcap_stats()" work the same on both
2106 * platforms, but the best approximation is to return
2107 * "tp_packets" as the count of packets and "tp_drops"
2108 * as the count of drops.
2110 * Keep a running total because each call to
2111 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2112 * resets the counters to zero.
2114 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
2115 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
2116 *stats
= handlep
->stat
;
2122 * If the error was EOPNOTSUPP, fall through, so that
2123 * if you build the library on a system with
2124 * "struct tpacket_stats" and run it on a system
2125 * that doesn't, it works as it does if the library
2126 * is built on a system without "struct tpacket_stats".
2128 if (errno
!= EOPNOTSUPP
) {
2129 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2130 "pcap_stats: %s", pcap_strerror(errno
));
2136 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2137 * is not supported on PF_PACKET sockets:
2139 * "ps_recv" counts only packets that *passed* the filter,
2140 * not packets that didn't pass the filter. It does not
2141 * count packets dropped because we ran out of buffer
2144 * "ps_drop" is not supported.
2146 * "ps_ifdrop" is supported. It will return the number
2147 * of drops the interface reports in /proc/net/dev,
2148 * if that is available.
2150 * "ps_recv" doesn't include packets not yet read from
2151 * the kernel by libpcap.
2153 * We maintain the count of packets processed by libpcap in
2154 * "handlep->packets_read", for reasons described in the comment
2155 * at the end of pcap_read_packet(). We have no idea how many
2156 * packets were dropped by the kernel buffers -- but we know
2157 * how many the interface dropped, so we can return that.
2160 stats
->ps_recv
= handlep
->packets_read
;
2162 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2167 add_linux_if(pcap_if_t
**devlistp
, const char *ifname
, int fd
, char *errbuf
)
2170 char name
[512]; /* XXX - pick a size */
2172 struct ifreq ifrflags
;
2175 * Get the interface name.
2179 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2182 * This could be the separator between a
2183 * name and an alias number, or it could be
2184 * the separator between a name with no
2185 * alias number and the next field.
2187 * If there's a colon after digits, it
2188 * separates the name and the alias number,
2189 * otherwise it separates the name and the
2193 while (isascii(*p
) && isdigit(*p
))
2197 * That was the next field,
2198 * not the alias number.
2209 * Get the flags for this interface.
2211 strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2212 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2213 if (errno
== ENXIO
|| errno
== ENODEV
)
2214 return (0); /* device doesn't actually exist - ignore it */
2215 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2216 "SIOCGIFFLAGS: %.*s: %s",
2217 (int)sizeof(ifrflags
.ifr_name
),
2219 pcap_strerror(errno
));
2224 * Add an entry for this interface, with no addresses.
2226 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2238 * Get from "/sys/class/net" all interfaces listed there; if they're
2239 * already in the list of interfaces we have, that won't add another
2240 * instance, but if they're not, that'll add them.
2242 * We don't bother getting any addresses for them; it appears you can't
2243 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2244 * although some other types of addresses can be fetched with SIOCGIFADDR,
2245 * we don't bother with them for now.
2247 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2248 * the list of interfaces as is, and return 0, so that we can try
2249 * scanning /proc/net/dev.
2251 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2254 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
2256 DIR *sys_class_net_d
;
2259 char subsystem_path
[PATH_MAX
+1];
2263 sys_class_net_d
= opendir("/sys/class/net");
2264 if (sys_class_net_d
== NULL
) {
2266 * Don't fail if it doesn't exist at all.
2268 if (errno
== ENOENT
)
2272 * Fail if we got some other error.
2274 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2275 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
2280 * Create a socket from which to fetch interface information.
2282 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2284 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2285 "socket: %s", pcap_strerror(errno
));
2286 (void)closedir(sys_class_net_d
);
2292 ent
= readdir(sys_class_net_d
);
2295 * Error or EOF; if errno != 0, it's an error.
2301 * Ignore "." and "..".
2303 if (strcmp(ent
->d_name
, ".") == 0 ||
2304 strcmp(ent
->d_name
, "..") == 0)
2308 * Ignore plain files; they do not have subdirectories
2309 * and thus have no attributes.
2311 if (ent
->d_type
== DT_REG
)
2315 * Is there an "ifindex" file under that name?
2316 * (We don't care whether it's a directory or
2317 * a symlink; older kernels have directories
2318 * for devices, newer kernels have symlinks to
2321 snprintf(subsystem_path
, sizeof subsystem_path
,
2322 "/sys/class/net/%s/ifindex", ent
->d_name
);
2323 if (lstat(subsystem_path
, &statb
) != 0) {
2325 * Stat failed. Either there was an error
2326 * other than ENOENT, and we don't know if
2327 * this is an interface, or it's ENOENT,
2328 * and either some part of "/sys/class/net/{if}"
2329 * disappeared, in which case it probably means
2330 * the interface disappeared, or there's no
2331 * "ifindex" file, which means it's not a
2332 * network interface.
2338 * Attempt to add the interface.
2340 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2348 * Well, we didn't fail for any other reason; did we
2349 * fail due to an error reading the directory?
2352 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2353 "Error reading /sys/class/net: %s",
2354 pcap_strerror(errno
));
2360 (void)closedir(sys_class_net_d
);
2365 * Get from "/proc/net/dev" all interfaces listed there; if they're
2366 * already in the list of interfaces we have, that won't add another
2367 * instance, but if they're not, that'll add them.
2369 * See comments from scan_sys_class_net().
2372 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2381 proc_net_f
= fopen("/proc/net/dev", "r");
2382 if (proc_net_f
== NULL
) {
2384 * Don't fail if it doesn't exist at all.
2386 if (errno
== ENOENT
)
2390 * Fail if we got some other error.
2392 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2393 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2398 * Create a socket from which to fetch interface information.
2400 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2402 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2403 "socket: %s", pcap_strerror(errno
));
2404 (void)fclose(proc_net_f
);
2409 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2411 * Skip the first two lines - they're headers.
2419 * Skip leading white space.
2421 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2423 if (*p
== '\0' || *p
== '\n')
2424 continue; /* blank line */
2427 * Attempt to add the interface.
2429 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2437 * Well, we didn't fail for any other reason; did we
2438 * fail due to an error reading the file?
2440 if (ferror(proc_net_f
)) {
2441 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2442 "Error reading /proc/net/dev: %s",
2443 pcap_strerror(errno
));
2449 (void)fclose(proc_net_f
);
2454 * Description string for the "any" device.
2456 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2459 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2464 * Read "/sys/class/net", and add to the list of interfaces all
2465 * interfaces listed there that we don't already have, because,
2466 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2467 * and even getifaddrs() won't return information about
2468 * interfaces with no addresses, so you need to read "/sys/class/net"
2469 * to get the names of the rest of the interfaces.
2471 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2473 return (-1); /* failed */
2476 * No /sys/class/net; try reading /proc/net/dev instead.
2478 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2483 * Add the "any" device.
2485 if (pcap_add_if(alldevsp
, "any", IFF_UP
|IFF_RUNNING
,
2486 any_descr
, errbuf
) < 0)
2493 * Attach the given BPF code to the packet capture device.
2496 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2499 struct pcap_linux
*handlep
;
2500 #ifdef SO_ATTACH_FILTER
2501 struct sock_fprog fcode
;
2502 int can_filter_in_kernel
;
2509 strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2514 handlep
= handle
->priv
;
2516 /* Make our private copy of the filter */
2518 if (install_bpf_program(handle
, filter
) < 0)
2519 /* install_bpf_program() filled in errbuf */
2523 * Run user level packet filter by default. Will be overriden if
2524 * installing a kernel filter succeeds.
2526 handlep
->filter_in_userland
= 1;
2528 /* Install kernel level filter if possible */
2530 #ifdef SO_ATTACH_FILTER
2532 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2534 * fcode.len is an unsigned short for current kernel.
2535 * I have yet to see BPF-Code with that much
2536 * instructions but still it is possible. So for the
2537 * sake of correctness I added this check.
2539 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2541 fcode
.filter
= NULL
;
2542 can_filter_in_kernel
= 0;
2544 #endif /* USHRT_MAX */
2547 * Oh joy, the Linux kernel uses struct sock_fprog instead
2548 * of struct bpf_program and of course the length field is
2549 * of different size. Pointed out by Sebastian
2551 * Oh, and we also need to fix it up so that all "ret"
2552 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2553 * as the operand if we're not capturing in memory-mapped
2554 * mode, and so that, if we're in cooked mode, all memory-
2555 * reference instructions use special magic offsets in
2556 * references to the link-layer header and assume that the
2557 * link-layer payload begins at 0; "fix_program()" will do
2560 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2565 * Fatal error; just quit.
2566 * (The "default" case shouldn't happen; we
2567 * return -1 for that reason.)
2573 * The program performed checks that we can't make
2574 * work in the kernel.
2576 can_filter_in_kernel
= 0;
2581 * We have a filter that'll work in the kernel.
2583 can_filter_in_kernel
= 1;
2589 * NOTE: at this point, we've set both the "len" and "filter"
2590 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2591 * those are the only members of the "sock_fprog" structure,
2592 * so we initialize every member of that structure.
2594 * If there is anything in "fcode" that is not initialized,
2595 * it is either a field added in a later kernel, or it's
2598 * If a new field is added, this code needs to be updated
2599 * to set it correctly.
2601 * If there are no other fields, then:
2603 * if the Linux kernel looks at the padding, it's
2606 * if the Linux kernel doesn't look at the padding,
2607 * then if some tool complains that we're passing
2608 * uninitialized data to the kernel, then the tool
2609 * is buggy and needs to understand that it's just
2612 if (can_filter_in_kernel
) {
2613 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2616 * Installation succeded - using kernel filter,
2617 * so userland filtering not needed.
2619 handlep
->filter_in_userland
= 0;
2621 else if (err
== -1) /* Non-fatal error */
2624 * Print a warning if we weren't able to install
2625 * the filter for a reason other than "this kernel
2626 * isn't configured to support socket filters.
2628 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2630 "Warning: Kernel filter failed: %s\n",
2631 pcap_strerror(errno
));
2637 * If we're not using the kernel filter, get rid of any kernel
2638 * filter that might've been there before, e.g. because the
2639 * previous filter could work in the kernel, or because some other
2640 * code attached a filter to the socket by some means other than
2641 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2642 * filter out packets that would pass the new userland filter.
2644 if (handlep
->filter_in_userland
) {
2645 if (reset_kernel_filter(handle
) == -1) {
2646 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2647 "can't remove kernel filter: %s",
2648 pcap_strerror(errno
));
2649 err
= -2; /* fatal error */
2654 * Free up the copy of the filter that was made by "fix_program()".
2656 if (fcode
.filter
!= NULL
)
2662 #endif /* SO_ATTACH_FILTER */
2668 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2670 return pcap_setfilter_linux_common(handle
, filter
, 0);
2675 * Set direction flag: Which packets do we accept on a forwarding
2676 * single device? IN, OUT or both?
2679 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2681 #ifdef HAVE_PF_PACKET_SOCKETS
2682 struct pcap_linux
*handlep
= handle
->priv
;
2684 if (!handlep
->sock_packet
) {
2685 handle
->direction
= d
;
2690 * We're not using PF_PACKET sockets, so we can't determine
2691 * the direction of the packet.
2693 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2694 "Setting direction is not supported on SOCK_PACKET sockets");
2698 #ifdef HAVE_PF_PACKET_SOCKETS
2700 * Map the PACKET_ value to a LINUX_SLL_ value; we
2701 * want the same numerical value to be used in
2702 * the link-layer header even if the numerical values
2703 * for the PACKET_ #defines change, so that programs
2704 * that look at the packet type field will always be
2705 * able to handle DLT_LINUX_SLL captures.
2708 map_packet_type_to_sll_type(short int sll_pkttype
)
2710 switch (sll_pkttype
) {
2713 return htons(LINUX_SLL_HOST
);
2715 case PACKET_BROADCAST
:
2716 return htons(LINUX_SLL_BROADCAST
);
2718 case PACKET_MULTICAST
:
2719 return htons(LINUX_SLL_MULTICAST
);
2721 case PACKET_OTHERHOST
:
2722 return htons(LINUX_SLL_OTHERHOST
);
2724 case PACKET_OUTGOING
:
2725 return htons(LINUX_SLL_OUTGOING
);
2735 #ifndef IW_MODE_MONITOR
2738 , const char *device
)
2742 #ifdef IW_MODE_MONITOR
2743 char errbuf
[PCAP_ERRBUF_SIZE
];
2747 * See if there's a sysfs wireless directory for it.
2748 * If so, it's a wireless interface.
2750 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
2752 * Just give up here.
2756 if (stat(pathstr
, &statb
) == 0) {
2762 #ifdef IW_MODE_MONITOR
2764 * OK, maybe it's not wireless, or maybe this kernel doesn't
2765 * support sysfs. Try the wireless extensions.
2767 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
2769 * It supports the wireless extensions, so it's a Wi-Fi
2779 * Linux uses the ARP hardware type to identify the type of an
2780 * interface. pcap uses the DLT_xxx constants for this. This
2781 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2782 * constant, as arguments, and sets "handle->linktype" to the
2783 * appropriate DLT_XXX constant and sets "handle->offset" to
2784 * the appropriate value (to make "handle->offset" plus link-layer
2785 * header length be a multiple of 4, so that the link-layer payload
2786 * will be aligned on a 4-byte boundary when capturing packets).
2787 * (If the offset isn't set here, it'll be 0; add code as appropriate
2788 * for cases where it shouldn't be 0.)
2790 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2791 * in cooked mode; otherwise, we can't use cooked mode, so we have
2792 * to pick some type that works in raw mode, or fail.
2794 * Sets the link type to -1 if unable to map the type.
2796 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
2797 const char *device
, int cooked_ok
)
2799 static const char cdma_rmnet
[] = "cdma_rmnet";
2805 * For various annoying reasons having to do with DHCP
2806 * software, some versions of Android give the mobile-
2807 * phone-network interface an ARPHRD_ value of
2808 * ARPHRD_ETHER, even though the packets supplied by
2809 * that interface have no link-layer header, and begin
2810 * with an IP header, so that the ARPHRD_ value should
2813 * Detect those devices by checking the device name, and
2814 * use DLT_RAW for them.
2816 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2817 handle
->linktype
= DLT_RAW
;
2822 * Is this a real Ethernet device? If so, give it a
2823 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2824 * that an application can let you choose it, in case you're
2825 * capturing DOCSIS traffic that a Cisco Cable Modem
2826 * Termination System is putting out onto an Ethernet (it
2827 * doesn't put an Ethernet header onto the wire, it puts raw
2828 * DOCSIS frames out on the wire inside the low-level
2829 * Ethernet framing).
2831 * XXX - are there any other sorts of "fake Ethernet" that
2832 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2833 * a Cisco CMTS won't put traffic onto it or get traffic
2834 * bridged onto it? ISDN is handled in "activate_new()",
2835 * as we fall back on cooked mode there, and we use
2836 * is_wifi() to check for 802.11 devices; are there any
2839 if (!is_wifi(sock_fd
, device
)) {
2841 * It's not a Wi-Fi device; offer DOCSIS.
2843 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2845 * If that fails, just leave the list empty.
2847 if (handle
->dlt_list
!= NULL
) {
2848 handle
->dlt_list
[0] = DLT_EN10MB
;
2849 handle
->dlt_list
[1] = DLT_DOCSIS
;
2850 handle
->dlt_count
= 2;
2855 case ARPHRD_METRICOM
:
2856 case ARPHRD_LOOPBACK
:
2857 handle
->linktype
= DLT_EN10MB
;
2862 handle
->linktype
= DLT_EN3MB
;
2866 handle
->linktype
= DLT_AX25_KISS
;
2870 handle
->linktype
= DLT_PRONET
;
2874 handle
->linktype
= DLT_CHAOS
;
2877 #define ARPHRD_CAN 280
2880 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2883 #ifndef ARPHRD_IEEE802_TR
2884 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2886 case ARPHRD_IEEE802_TR
:
2887 case ARPHRD_IEEE802
:
2888 handle
->linktype
= DLT_IEEE802
;
2893 handle
->linktype
= DLT_ARCNET_LINUX
;
2896 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2897 #define ARPHRD_FDDI 774
2900 handle
->linktype
= DLT_FDDI
;
2904 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2905 #define ARPHRD_ATM 19
2909 * The Classical IP implementation in ATM for Linux
2910 * supports both what RFC 1483 calls "LLC Encapsulation",
2911 * in which each packet has an LLC header, possibly
2912 * with a SNAP header as well, prepended to it, and
2913 * what RFC 1483 calls "VC Based Multiplexing", in which
2914 * different virtual circuits carry different network
2915 * layer protocols, and no header is prepended to packets.
2917 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2918 * you can't use the ARPHRD_ type to find out whether
2919 * captured packets will have an LLC header, and,
2920 * while there's a socket ioctl to *set* the encapsulation
2921 * type, there's no ioctl to *get* the encapsulation type.
2925 * programs that dissect Linux Classical IP frames
2926 * would have to check for an LLC header and,
2927 * depending on whether they see one or not, dissect
2928 * the frame as LLC-encapsulated or as raw IP (I
2929 * don't know whether there's any traffic other than
2930 * IP that would show up on the socket, or whether
2931 * there's any support for IPv6 in the Linux
2932 * Classical IP code);
2934 * filter expressions would have to compile into
2935 * code that checks for an LLC header and does
2938 * Both of those are a nuisance - and, at least on systems
2939 * that support PF_PACKET sockets, we don't have to put
2940 * up with those nuisances; instead, we can just capture
2941 * in cooked mode. That's what we'll do, if we can.
2942 * Otherwise, we'll just fail.
2945 handle
->linktype
= DLT_LINUX_SLL
;
2947 handle
->linktype
= -1;
2950 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2951 #define ARPHRD_IEEE80211 801
2953 case ARPHRD_IEEE80211
:
2954 handle
->linktype
= DLT_IEEE802_11
;
2957 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2958 #define ARPHRD_IEEE80211_PRISM 802
2960 case ARPHRD_IEEE80211_PRISM
:
2961 handle
->linktype
= DLT_PRISM_HEADER
;
2964 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2965 #define ARPHRD_IEEE80211_RADIOTAP 803
2967 case ARPHRD_IEEE80211_RADIOTAP
:
2968 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2973 * Some PPP code in the kernel supplies no link-layer
2974 * header whatsoever to PF_PACKET sockets; other PPP
2975 * code supplies PPP link-layer headers ("syncppp.c");
2976 * some PPP code might supply random link-layer
2977 * headers (PPP over ISDN - there's code in Ethereal,
2978 * for example, to cope with PPP-over-ISDN captures
2979 * with which the Ethereal developers have had to cope,
2980 * heuristically trying to determine which of the
2981 * oddball link-layer headers particular packets have).
2983 * As such, we just punt, and run all PPP interfaces
2984 * in cooked mode, if we can; otherwise, we just treat
2985 * it as DLT_RAW, for now - if somebody needs to capture,
2986 * on a 2.0[.x] kernel, on PPP devices that supply a
2987 * link-layer header, they'll have to add code here to
2988 * map to the appropriate DLT_ type (possibly adding a
2989 * new DLT_ type, if necessary).
2992 handle
->linktype
= DLT_LINUX_SLL
;
2995 * XXX - handle ISDN types here? We can't fall
2996 * back on cooked sockets, so we'd have to
2997 * figure out from the device name what type of
2998 * link-layer encapsulation it's using, and map
2999 * that to an appropriate DLT_ value, meaning
3000 * we'd map "isdnN" devices to DLT_RAW (they
3001 * supply raw IP packets with no link-layer
3002 * header) and "isdY" devices to a new DLT_I4L_IP
3003 * type that has only an Ethernet packet type as
3004 * a link-layer header.
3006 * But sometimes we seem to get random crap
3007 * in the link-layer header when capturing on
3010 handle
->linktype
= DLT_RAW
;
3014 #ifndef ARPHRD_CISCO
3015 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3018 handle
->linktype
= DLT_C_HDLC
;
3021 /* Not sure if this is correct for all tunnels, but it
3025 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3033 #ifndef ARPHRD_RAWHDLC
3034 #define ARPHRD_RAWHDLC 518
3036 case ARPHRD_RAWHDLC
:
3038 #define ARPHRD_DLCI 15
3042 * XXX - should some of those be mapped to DLT_LINUX_SLL
3043 * instead? Should we just map all of them to DLT_LINUX_SLL?
3045 handle
->linktype
= DLT_RAW
;
3049 #define ARPHRD_FRAD 770
3052 handle
->linktype
= DLT_FRELAY
;
3055 case ARPHRD_LOCALTLK
:
3056 handle
->linktype
= DLT_LTALK
;
3061 * RFC 4338 defines an encapsulation for IP and ARP
3062 * packets that's compatible with the RFC 2625
3063 * encapsulation, but that uses a different ARP
3064 * hardware type and hardware addresses. That
3065 * ARP hardware type is 18; Linux doesn't define
3066 * any ARPHRD_ value as 18, but if it ever officially
3067 * supports RFC 4338-style IP-over-FC, it should define
3070 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3071 * that this will encourage its use in the future,
3072 * should Linux ever officially support RFC 4338-style
3075 handle
->linktype
= DLT_IP_OVER_FC
;
3079 #define ARPHRD_FCPP 784
3083 #define ARPHRD_FCAL 785
3087 #define ARPHRD_FCPL 786
3090 #ifndef ARPHRD_FCFABRIC
3091 #define ARPHRD_FCFABRIC 787
3093 case ARPHRD_FCFABRIC
:
3095 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3098 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3100 * and one was assigned.
3102 * In a later private discussion (spun off from a message
3103 * on the ethereal-users list) on how to get that DLT_
3104 * value in libpcap on Linux, I ended up deciding that
3105 * the best thing to do would be to have him tweak the
3106 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3107 * type, and map all those types to DLT_IP_OVER_FC:
3109 * I've checked into the libpcap and tcpdump CVS tree
3110 * support for DLT_IP_OVER_FC. In order to use that,
3111 * you'd have to modify your modified driver to return
3112 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3113 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3114 * example (the exact value doesn't matter, it can be
3115 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3118 * 11 years later, Christian Svensson wanted to map
3119 * various ARPHRD_ values to DLT_FC_2 and
3120 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3123 * https://github.com/mcr/libpcap/pull/29
3125 * There doesn't seem to be any network drivers that uses
3126 * any of the ARPHRD_FC* values for IP-over-FC, and
3127 * it's not exactly clear what the "Dummy types for non
3128 * ARP hardware" are supposed to mean (link-layer
3129 * header type? Physical network type?), so it's
3130 * not exactly clear why the ARPHRD_FC* types exist
3131 * in the first place.
3133 * For now, we map them to DLT_FC_2, and provide an
3134 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3135 * DLT_IP_OVER_FC just in case there's some old
3136 * driver out there that uses one of those types for
3137 * IP-over-FC on which somebody wants to capture
3140 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3142 * If that fails, just leave the list empty.
3144 if (handle
->dlt_list
!= NULL
) {
3145 handle
->dlt_list
[0] = DLT_FC_2
;
3146 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
3147 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
3148 handle
->dlt_count
= 3;
3150 handle
->linktype
= DLT_FC_2
;
3154 #define ARPHRD_IRDA 783
3157 /* Don't expect IP packet out of this interfaces... */
3158 handle
->linktype
= DLT_LINUX_IRDA
;
3159 /* We need to save packet direction for IrDA decoding,
3160 * so let's use "Linux-cooked" mode. Jean II
3162 * XXX - this is handled in activate_new(). */
3163 //handlep->cooked = 1;
3166 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3167 * is needed, please report it to <daniele@orlandi.com> */
3169 #define ARPHRD_LAPD 8445
3172 /* Don't expect IP packet out of this interfaces... */
3173 handle
->linktype
= DLT_LINUX_LAPD
;
3177 #define ARPHRD_NONE 0xFFFE
3181 * No link-layer header; packets are just IP
3182 * packets, so use DLT_RAW.
3184 handle
->linktype
= DLT_RAW
;
3187 #ifndef ARPHRD_IEEE802154
3188 #define ARPHRD_IEEE802154 804
3190 case ARPHRD_IEEE802154
:
3191 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
3194 #ifndef ARPHRD_NETLINK
3195 #define ARPHRD_NETLINK 824
3197 case ARPHRD_NETLINK
:
3198 handle
->linktype
= DLT_NETLINK
;
3200 * We need to use cooked mode, so that in sll_protocol we
3201 * pick up the netlink protocol type such as NETLINK_ROUTE,
3202 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3204 * XXX - this is handled in activate_new().
3206 //handlep->cooked = 1;
3210 handle
->linktype
= -1;
3215 /* ===== Functions to interface to the newer kernels ================== */
3218 * Try to open a packet socket using the new kernel PF_PACKET interface.
3219 * Returns 1 on success, 0 on an error that means the new interface isn't
3220 * present (so the old SOCK_PACKET interface should be tried), and a
3221 * PCAP_ERROR_ value on an error that means that the old mechanism won't
3222 * work either (so it shouldn't be tried).
3225 activate_new(pcap_t
*handle
)
3227 #ifdef HAVE_PF_PACKET_SOCKETS
3228 struct pcap_linux
*handlep
= handle
->priv
;
3229 const char *device
= handle
->opt
.source
;
3230 int is_any_device
= (strcmp(device
, "any") == 0);
3231 int sock_fd
= -1, arptype
;
3232 #ifdef HAVE_PACKET_AUXDATA
3236 struct packet_mreq mr
;
3237 #ifdef SO_BPF_EXTENSIONS
3239 socklen_t len
= sizeof(bpf_extensions
);
3243 * Open a socket with protocol family packet. If the
3244 * "any" device was specified, we open a SOCK_DGRAM
3245 * socket for the cooked interface, otherwise we first
3246 * try a SOCK_RAW socket for the raw interface.
3248 sock_fd
= is_any_device
?
3249 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
3250 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
3252 if (sock_fd
== -1) {
3253 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
3255 * We don't support PF_PACKET/SOCK_whatever
3256 * sockets; try the old mechanism.
3261 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
3262 pcap_strerror(errno
) );
3263 if (errno
== EPERM
|| errno
== EACCES
) {
3265 * You don't have permission to open the
3268 return PCAP_ERROR_PERM_DENIED
;
3277 /* It seems the kernel supports the new interface. */
3278 handlep
->sock_packet
= 0;
3281 * Get the interface index of the loopback device.
3282 * If the attempt fails, don't fail, just set the
3283 * "handlep->lo_ifindex" to -1.
3285 * XXX - can there be more than one device that loops
3286 * packets back, i.e. devices other than "lo"? If so,
3287 * we'd need to find them all, and have an array of
3288 * indices for them, and check all of them in
3289 * "pcap_read_packet()".
3291 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3294 * Default value for offset to align link-layer payload
3295 * on a 4-byte boundary.
3300 * What kind of frames do we have to deal with? Fall back
3301 * to cooked mode if we have an unknown interface type
3302 * or a type we know doesn't work well in raw mode.
3304 if (!is_any_device
) {
3305 /* Assume for now we don't need cooked mode. */
3306 handlep
->cooked
= 0;
3308 if (handle
->opt
.rfmon
) {
3310 * We were asked to turn on monitor mode.
3311 * Do so before we get the link-layer type,
3312 * because entering monitor mode could change
3313 * the link-layer type.
3315 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3323 * Nothing worked for turning monitor mode
3327 return PCAP_ERROR_RFMON_NOTSUP
;
3331 * Either monitor mode has been turned on for
3332 * the device, or we've been given a different
3333 * device to open for monitor mode. If we've
3334 * been given a different device, use it.
3336 if (handlep
->mondevice
!= NULL
)
3337 device
= handlep
->mondevice
;
3339 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3344 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
3345 if (handle
->linktype
== -1 ||
3346 handle
->linktype
== DLT_LINUX_SLL
||
3347 handle
->linktype
== DLT_LINUX_IRDA
||
3348 handle
->linktype
== DLT_LINUX_LAPD
||
3349 handle
->linktype
== DLT_NETLINK
||
3350 (handle
->linktype
== DLT_EN10MB
&&
3351 (strncmp("isdn", device
, 4) == 0 ||
3352 strncmp("isdY", device
, 4) == 0))) {
3354 * Unknown interface type (-1), or a
3355 * device we explicitly chose to run
3356 * in cooked mode (e.g., PPP devices),
3357 * or an ISDN device (whose link-layer
3358 * type we can only determine by using
3359 * APIs that may be different on different
3360 * kernels) - reopen in cooked mode.
3362 if (close(sock_fd
) == -1) {
3363 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3364 "close: %s", pcap_strerror(errno
));
3367 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3369 if (sock_fd
== -1) {
3370 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3371 "socket: %s", pcap_strerror(errno
));
3372 if (errno
== EPERM
|| errno
== EACCES
) {
3374 * You don't have permission to
3377 return PCAP_ERROR_PERM_DENIED
;
3385 handlep
->cooked
= 1;
3388 * Get rid of any link-layer type list
3389 * we allocated - this only supports cooked
3392 if (handle
->dlt_list
!= NULL
) {
3393 free(handle
->dlt_list
);
3394 handle
->dlt_list
= NULL
;
3395 handle
->dlt_count
= 0;
3398 if (handle
->linktype
== -1) {
3400 * Warn that we're falling back on
3401 * cooked mode; we may want to
3402 * update "map_arphrd_to_dlt()"
3403 * to handle the new type.
3405 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3407 "supported by libpcap - "
3408 "falling back to cooked "
3414 * IrDA capture is not a real "cooked" capture,
3415 * it's IrLAP frames, not IP packets. The
3416 * same applies to LAPD capture.
3418 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3419 handle
->linktype
!= DLT_LINUX_LAPD
&&
3420 handle
->linktype
!= DLT_NETLINK
)
3421 handle
->linktype
= DLT_LINUX_SLL
;
3424 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3426 if (handlep
->ifindex
== -1) {
3431 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3432 handle
->errbuf
)) != 1) {
3437 return 0; /* try old mechanism */
3443 if (handle
->opt
.rfmon
) {
3445 * It doesn't support monitor mode.
3448 return PCAP_ERROR_RFMON_NOTSUP
;
3452 * It uses cooked mode.
3454 handlep
->cooked
= 1;
3455 handle
->linktype
= DLT_LINUX_SLL
;
3458 * We're not bound to a device.
3459 * For now, we're using this as an indication
3460 * that we can't transmit; stop doing that only
3461 * if we figure out how to transmit in cooked
3464 handlep
->ifindex
= -1;
3468 * Select promiscuous mode on if "promisc" is set.
3470 * Do not turn allmulti mode on if we don't select
3471 * promiscuous mode - on some devices (e.g., Orinoco
3472 * wireless interfaces), allmulti mode isn't supported
3473 * and the driver implements it by turning promiscuous
3474 * mode on, and that screws up the operation of the
3475 * card as a normal networking interface, and on no
3476 * other platform I know of does starting a non-
3477 * promiscuous capture affect which multicast packets
3478 * are received by the interface.
3482 * Hmm, how can we set promiscuous mode on all interfaces?
3483 * I am not sure if that is possible at all. For now, we
3484 * silently ignore attempts to turn promiscuous mode on
3485 * for the "any" device (so you don't have to explicitly
3486 * disable it in programs such as tcpdump).
3489 if (!is_any_device
&& handle
->opt
.promisc
) {
3490 memset(&mr
, 0, sizeof(mr
));
3491 mr
.mr_ifindex
= handlep
->ifindex
;
3492 mr
.mr_type
= PACKET_MR_PROMISC
;
3493 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3494 &mr
, sizeof(mr
)) == -1) {
3495 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3496 "setsockopt: %s", pcap_strerror(errno
));
3502 /* Enable auxillary data if supported and reserve room for
3503 * reconstructing VLAN headers. */
3504 #ifdef HAVE_PACKET_AUXDATA
3506 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3507 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3508 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3509 "setsockopt: %s", pcap_strerror(errno
));
3513 handle
->offset
+= VLAN_TAG_LEN
;
3514 #endif /* HAVE_PACKET_AUXDATA */
3517 * This is a 2.2[.x] or later kernel (we know that
3518 * because we're not using a SOCK_PACKET socket -
3519 * PF_PACKET is supported only in 2.2 and later
3522 * We can safely pass "recvfrom()" a byte count
3523 * based on the snapshot length.
3525 * If we're in cooked mode, make the snapshot length
3526 * large enough to hold a "cooked mode" header plus
3527 * 1 byte of packet data (so we don't pass a byte
3528 * count of 0 to "recvfrom()").
3530 if (handlep
->cooked
) {
3531 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3532 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3534 handle
->bufsize
= handle
->snapshot
;
3537 * Set the offset at which to insert VLAN tags.
3539 switch (handle
->linktype
) {
3542 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3546 handlep
->vlan_offset
= 14;
3550 handlep
->vlan_offset
= -1; /* unknown */
3554 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3555 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3556 int nsec_tstamps
= 1;
3558 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3559 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3564 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3567 * We've succeeded. Save the socket FD in the pcap structure.
3569 handle
->fd
= sock_fd
;
3571 #ifdef SO_BPF_EXTENSIONS
3573 * Can we generate special code for VLAN checks?
3574 * (XXX - what if we need the special code but it's not supported
3575 * by the OS? Is that possible?)
3577 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
3578 &bpf_extensions
, &len
) == 0) {
3579 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
3581 * Yes, we can. Request that we do so.
3583 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
3586 #endif /* SO_BPF_EXTENSIONS */
3589 #else /* HAVE_PF_PACKET_SOCKETS */
3591 "New packet capturing interface not supported by build "
3592 "environment", PCAP_ERRBUF_SIZE
);
3594 #endif /* HAVE_PF_PACKET_SOCKETS */
3597 #ifdef HAVE_PACKET_RING
3599 * Attempt to activate with memory-mapped access.
3601 * On success, returns 1, and sets *status to 0 if there are no warnings
3602 * or to a PCAP_WARNING_ code if there is a warning.
3604 * On failure due to lack of support for memory-mapped capture, returns
3607 * On error, returns -1, and sets *status to the appropriate error code;
3608 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3611 activate_mmap(pcap_t
*handle
, int *status
)
3613 struct pcap_linux
*handlep
= handle
->priv
;
3617 * Attempt to allocate a buffer to hold the contents of one
3618 * packet, for use by the oneshot callback.
3620 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3621 if (handlep
->oneshot_buffer
== NULL
) {
3622 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3623 "can't allocate oneshot buffer: %s",
3624 pcap_strerror(errno
));
3625 *status
= PCAP_ERROR
;
3629 if (handle
->opt
.buffer_size
== 0) {
3630 /* by default request 2M for the ring buffer */
3631 handle
->opt
.buffer_size
= 2*1024*1024;
3633 ret
= prepare_tpacket_socket(handle
);
3635 free(handlep
->oneshot_buffer
);
3636 *status
= PCAP_ERROR
;
3639 ret
= create_ring(handle
, status
);
3642 * We don't support memory-mapped capture; our caller
3643 * will fall back on reading from the socket.
3645 free(handlep
->oneshot_buffer
);
3650 * Error attempting to enable memory-mapped capture;
3651 * fail. create_ring() has set *status.
3653 free(handlep
->oneshot_buffer
);
3658 * Success. *status has been set either to 0 if there are no
3659 * warnings or to a PCAP_WARNING_ value if there is a warning.
3661 * Override some defaults and inherit the other fields from
3663 * handle->offset is used to get the current position into the rx ring.
3664 * handle->cc is used to store the ring size.
3667 switch (handlep
->tp_version
) {
3669 handle
->read_op
= pcap_read_linux_mmap_v1
;
3672 handle
->read_op
= pcap_read_linux_mmap_v1_64
;
3674 #ifdef HAVE_TPACKET2
3676 handle
->read_op
= pcap_read_linux_mmap_v2
;
3679 #ifdef HAVE_TPACKET3
3681 handle
->read_op
= pcap_read_linux_mmap_v3
;
3685 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3686 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3687 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3688 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3689 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3690 handle
->selectable_fd
= handle
->fd
;
3693 #else /* HAVE_PACKET_RING */
3695 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3699 #endif /* HAVE_PACKET_RING */
3701 #ifdef HAVE_PACKET_RING
3703 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3705 * Attempt to set the socket to the specified version of the memory-mapped
3708 * Return 0 if we succeed; return 1 if we fail because that version isn't
3709 * supported; return -1 on any other error, and set handle->errbuf.
3712 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
3714 struct pcap_linux
*handlep
= handle
->priv
;
3716 socklen_t len
= sizeof(val
);
3719 * Probe whether kernel supports the specified TPACKET version;
3720 * this also gets the length of the header for that version.
3722 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3723 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
)
3726 /* Failed to even find out; this is a fatal error. */
3727 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3728 "can't get %s header len on packet socket: %s",
3730 pcap_strerror(errno
));
3733 handlep
->tp_hdrlen
= val
;
3736 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3738 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3739 "can't activate %s on packet socket: %s",
3741 pcap_strerror(errno
));
3744 handlep
->tp_version
= version
;
3746 /* Reserve space for VLAN tag reconstruction */
3748 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3750 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3751 "can't set up reserve on packet socket: %s",
3752 pcap_strerror(errno
));
3758 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3761 * If the instruction set for which we're compiling has both 32-bit
3762 * and 64-bit versions, and Linux support for the 64-bit version
3763 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
3764 * you get from uname() for the 64-bit version. Otherwise, leave
3765 * it undefined. (This includes ARM, which has a 64-bit version,
3766 * but Linux support for it appeared well after TPACKET_V2 support
3767 * did, so there should never be a case where 32-bit ARM code is
3768 * running o a 64-bit kernel that only supports TPACKET_V1.)
3770 * If we've omitted your favorite such architecture, please contribute
3771 * a patch. (No patch is needed for architectures that are 32-bit-only
3772 * or for which Linux has no support for 32-bit userland - or for which,
3773 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
3776 #if defined(__i386__)
3777 #define ISA_64_BIT "x86_64"
3778 #elif defined(__ppc__)
3779 #define ISA_64_BIT "ppc64"
3780 #elif defined(__sparc__)
3781 #define ISA_64_BIT "sparc64"
3782 #elif defined(__s390__)
3783 #define ISA_64_BIT "s390x"
3784 #elif defined(__mips__)
3785 #define ISA_64_BIT "mips64"
3786 #elif defined(__hppa__)
3787 #define ISA_64_BIT "parisc64"
3791 * Attempt to set the socket to version 3 of the memory-mapped header and,
3792 * if that fails because version 3 isn't supported, attempt to fall
3793 * back to version 2. If version 2 isn't supported, just leave it at
3796 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
3797 * supported; return -1 on any other error, and set handle->errbuf.
3800 prepare_tpacket_socket(pcap_t
*handle
)
3802 struct pcap_linux
*handlep
= handle
->priv
;
3803 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3807 #ifdef HAVE_TPACKET3
3809 * Try setting the version to TPACKET_V3.
3811 * The only mode in which buffering is done on PF_PACKET
3812 * sockets, so that packets might not be delivered
3813 * immediately, is TPACKET_V3 mode.
3815 * The buffering cannot be disabled in that mode, so
3816 * if the user has requested immediate mode, we don't
3819 if (!handle
->opt
.immediate
) {
3820 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
3829 * We failed for some reason other than "the
3830 * kernel doesn't support TPACKET_V3".
3835 #endif /* HAVE_TPACKET3 */
3837 #ifdef HAVE_TPACKET2
3839 * Try setting the version to TPACKET_V2.
3841 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
3850 * We failed for some reason other than "the
3851 * kernel doesn't support TPACKET_V2".
3855 #endif /* HAVE_TPACKET2 */
3858 * OK, we're using TPACKET_V1, as that's all the kernel supports.
3860 handlep
->tp_version
= TPACKET_V1
;
3861 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
3865 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
3866 * each other due to platform-dependent data type size differences.
3868 * If we have a 32-bit userland and a 64-bit kernel, use an
3869 * internally-defined TPACKET_V1_64, with which we use a 64-bit
3870 * version of the data structures.
3872 if (sizeof(long) == 4) {
3874 * This is 32-bit code.
3876 struct utsname utsname
;
3878 if (uname(&utsname
) == -1) {
3882 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3883 "uname failed: %s", pcap_strerror(errno
));
3886 if (strcmp(utsname
.machine
, ISA_64_BIT
) == 0) {
3888 * uname() tells us the machine is 64-bit,
3889 * so we presumably have a 64-bit kernel.
3891 * XXX - this presumes that uname() won't lie
3892 * in 32-bit code and claim that the machine
3893 * has the 32-bit version of the ISA.
3895 handlep
->tp_version
= TPACKET_V1_64
;
3896 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr_64
);
3905 * Attempt to set up memory-mapped access.
3907 * On success, returns 1, and sets *status to 0 if there are no warnings
3908 * or to a PCAP_WARNING_ code if there is a warning.
3910 * On failure due to lack of support for memory-mapped capture, returns
3913 * On error, returns -1, and sets *status to the appropriate error code;
3914 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3917 create_ring(pcap_t
*handle
, int *status
)
3919 struct pcap_linux
*handlep
= handle
->priv
;
3920 unsigned i
, j
, frames_per_block
;
3921 #ifdef HAVE_TPACKET3
3923 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
3924 * stuff at the end of a struct tpacket_req3 will be
3925 * ignored, so this is OK even for those sockets.
3927 struct tpacket_req3 req
;
3929 struct tpacket_req req
;
3932 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3933 unsigned int frame_size
;
3936 * Start out assuming no warnings or errors.
3940 switch (handlep
->tp_version
) {
3944 #ifdef HAVE_TPACKET2
3947 /* Note that with large snapshot length (say 64K, which is
3948 * the default for recent versions of tcpdump, the value that
3949 * "-s 0" has given for a long time with tcpdump, and the
3950 * default in Wireshark/TShark/dumpcap), if we use the snapshot
3951 * length to calculate the frame length, only a few frames
3952 * will be available in the ring even with pretty
3953 * large ring size (and a lot of memory will be unused).
3955 * Ideally, we should choose a frame length based on the
3956 * minimum of the specified snapshot length and the maximum
3957 * packet size. That's not as easy as it sounds; consider,
3958 * for example, an 802.11 interface in monitor mode, where
3959 * the frame would include a radiotap header, where the
3960 * maximum radiotap header length is device-dependent.
3962 * So, for now, we just do this for Ethernet devices, where
3963 * there's no metadata header, and the link-layer header is
3964 * fixed length. We can get the maximum packet size by
3965 * adding 18, the Ethernet header length plus the CRC length
3966 * (just in case we happen to get the CRC in the packet), to
3967 * the MTU of the interface; we fetch the MTU in the hopes
3968 * that it reflects support for jumbo frames. (Even if the
3969 * interface is just being used for passive snooping, the
3970 * driver might set the size of buffers in the receive ring
3971 * based on the MTU, so that the MTU limits the maximum size
3972 * of packets that we can receive.)
3974 * We don't do that if segmentation/fragmentation or receive
3975 * offload are enabled, so we don't get rudely surprised by
3976 * "packets" bigger than the MTU. */
3977 frame_size
= handle
->snapshot
;
3978 if (handle
->linktype
== DLT_EN10MB
) {
3982 offload
= iface_get_offload(handle
);
3983 if (offload
== -1) {
3984 *status
= PCAP_ERROR
;
3988 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
3991 *status
= PCAP_ERROR
;
3994 if (frame_size
> mtu
+ 18)
3995 frame_size
= mtu
+ 18;
3999 /* NOTE: calculus matching those in tpacket_rcv()
4000 * in linux-2.6/net/packet/af_packet.c
4002 len
= sizeof(sk_type
);
4003 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
4005 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4006 "getsockopt: %s", pcap_strerror(errno
));
4007 *status
= PCAP_ERROR
;
4010 #ifdef PACKET_RESERVE
4011 len
= sizeof(tp_reserve
);
4012 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4013 &tp_reserve
, &len
) < 0) {
4014 if (errno
!= ENOPROTOOPT
) {
4016 * ENOPROTOOPT means "kernel doesn't support
4017 * PACKET_RESERVE", in which case we fall back
4020 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4021 "getsockopt: %s", pcap_strerror(errno
));
4022 *status
= PCAP_ERROR
;
4025 tp_reserve
= 0; /* older kernel, reserve not supported */
4028 tp_reserve
= 0; /* older kernel, reserve not supported */
4030 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
4031 /* XXX: in the kernel maclen is calculated from
4032 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4033 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4034 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4035 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4036 * but I see no way to get those sizes in userspace,
4037 * like for instance with an ifreq ioctl();
4038 * the best thing I've found so far is MAX_HEADER in
4039 * the kernel part of linux-2.6/include/linux/netdevice.h
4040 * which goes up to 128+48=176; since pcap-linux.c
4041 * defines a MAX_LINKHEADER_SIZE of 256 which is
4042 * greater than that, let's use it.. maybe is it even
4043 * large enough to directly replace macoff..
4045 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
4046 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
4047 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4048 * of netoff, which contradicts
4049 * linux-2.6/Documentation/networking/packet_mmap.txt
4051 * "- Gap, chosen so that packet data (Start+tp_net)
4052 * aligns to TPACKET_ALIGNMENT=16"
4054 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4055 * "CPUs often take a performance hit
4056 * when accessing unaligned memory locations"
4058 macoff
= netoff
- maclen
;
4059 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
4060 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
4063 #ifdef HAVE_TPACKET3
4065 /* The "frames" for this are actually buffers that
4066 * contain multiple variable-sized frames.
4068 * We pick a "frame" size of 128K to leave enough
4069 * room for at least one reasonably-sized packet
4070 * in the "frame". */
4071 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
4072 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
4076 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4077 "Internal error: unknown TPACKET_ value %u",
4078 handlep
->tp_version
);
4079 *status
= PCAP_ERROR
;
4083 /* compute the minumum block size that will handle this frame.
4084 * The block has to be page size aligned.
4085 * The max block size allowed by the kernel is arch-dependent and
4086 * it's not explicitly checked here. */
4087 req
.tp_block_size
= getpagesize();
4088 while (req
.tp_block_size
< req
.tp_frame_size
)
4089 req
.tp_block_size
<<= 1;
4091 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
4094 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4095 * so we check for PACKET_TIMESTAMP. We check for
4096 * linux/net_tstamp.h just in case a system somehow has
4097 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4100 * SIOCSHWTSTAMP was introduced in the patch that introduced
4101 * linux/net_tstamp.h, so we don't bother checking whether
4102 * SIOCSHWTSTAMP is defined (if your Linux system has
4103 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4104 * Linux system is badly broken).
4106 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4108 * If we were told to do so, ask the kernel and the driver
4109 * to use hardware timestamps.
4111 * Hardware timestamps are only supported with mmapped
4114 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
4115 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
4116 struct hwtstamp_config hwconfig
;
4121 * Ask for hardware time stamps on all packets,
4122 * including transmitted packets.
4124 memset(&hwconfig
, 0, sizeof(hwconfig
));
4125 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
4126 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
4128 memset(&ifr
, 0, sizeof(ifr
));
4129 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
4130 ifr
.ifr_data
= (void *)&hwconfig
;
4132 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
4137 * Treat this as an error, as the
4138 * user should try to run this
4139 * with the appropriate privileges -
4140 * and, if they can't, shouldn't
4141 * try requesting hardware time stamps.
4143 *status
= PCAP_ERROR_PERM_DENIED
;
4148 * Treat this as a warning, as the
4149 * only way to fix the warning is to
4150 * get an adapter that supports hardware
4151 * time stamps. We'll just fall back
4152 * on the standard host time stamps.
4154 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
4158 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4159 "SIOCSHWTSTAMP failed: %s",
4160 pcap_strerror(errno
));
4161 *status
= PCAP_ERROR
;
4166 * Well, that worked. Now specify the type of
4167 * hardware time stamp we want for this
4170 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
4172 * Hardware timestamp, synchronized
4173 * with the system clock.
4175 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
4178 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4179 * timestamp, not synchronized with the
4182 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
4184 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
4185 (void *)×ource
, sizeof(timesource
))) {
4186 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4187 "can't set PACKET_TIMESTAMP: %s",
4188 pcap_strerror(errno
));
4189 *status
= PCAP_ERROR
;
4194 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4196 /* ask the kernel to create the ring */
4198 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
4200 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4201 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
4203 #ifdef HAVE_TPACKET3
4204 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4205 req
.tp_retire_blk_tov
= (handlep
->timeout
>=0)?handlep
->timeout
:0;
4206 /* private data not used */
4207 req
.tp_sizeof_priv
= 0;
4208 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4209 req
.tp_feature_req_word
= 0;
4212 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4213 (void *) &req
, sizeof(req
))) {
4214 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
4216 * Memory failure; try to reduce the requested ring
4219 * We used to reduce this by half -- do 5% instead.
4220 * That may result in more iterations and a longer
4221 * startup, but the user will be much happier with
4222 * the resulting buffer size.
4224 if (req
.tp_frame_nr
< 20)
4225 req
.tp_frame_nr
-= 1;
4227 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
4230 if (errno
== ENOPROTOOPT
) {
4232 * We don't have ring buffer support in this kernel.
4236 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4237 "can't create rx ring on packet socket: %s",
4238 pcap_strerror(errno
));
4239 *status
= PCAP_ERROR
;
4243 /* memory map the rx ring */
4244 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
4245 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
4246 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
4247 if (handlep
->mmapbuf
== MAP_FAILED
) {
4248 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4249 "can't mmap rx ring: %s", pcap_strerror(errno
));
4251 /* clear the allocated ring on error*/
4252 destroy_ring(handle
);
4253 *status
= PCAP_ERROR
;
4257 /* allocate a ring for each frame header pointer*/
4258 handle
->cc
= req
.tp_frame_nr
;
4259 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
4260 if (!handle
->buffer
) {
4261 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4262 "can't allocate ring of frame headers: %s",
4263 pcap_strerror(errno
));
4265 destroy_ring(handle
);
4266 *status
= PCAP_ERROR
;
4270 /* fill the header ring with proper frame ptr*/
4272 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
4273 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
4274 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
4275 RING_GET_CURRENT_FRAME(handle
) = base
;
4276 base
+= req
.tp_frame_size
;
4280 handle
->bufsize
= req
.tp_frame_size
;
4285 /* free all ring related resources*/
4287 destroy_ring(pcap_t
*handle
)
4289 struct pcap_linux
*handlep
= handle
->priv
;
4291 /* tell the kernel to destroy the ring*/
4292 struct tpacket_req req
;
4293 memset(&req
, 0, sizeof(req
));
4294 /* do not test for setsockopt failure, as we can't recover from any error */
4295 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4296 (void *) &req
, sizeof(req
));
4298 /* if ring is mapped, unmap it*/
4299 if (handlep
->mmapbuf
) {
4300 /* do not test for mmap failure, as we can't recover from any error */
4301 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
4302 handlep
->mmapbuf
= NULL
;
4307 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4308 * for Linux mmapped capture.
4310 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4311 * data handed to the callback to be valid after the callback returns,
4312 * but pcap_read_linux_mmap() has to release that packet as soon as
4313 * the callback returns (otherwise, the kernel thinks there's still
4314 * at least one unprocessed packet available in the ring, so a select()
4315 * will immediately return indicating that there's data to process), so,
4316 * in the callback, we have to make a copy of the packet.
4318 * Yes, this means that, if the capture is using the ring buffer, using
4319 * pcap_next() or pcap_next_ex() requires more copies than using
4320 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4321 * pcap_next() or pcap_next_ex().
4324 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
4325 const u_char
*bytes
)
4327 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
4328 pcap_t
*handle
= sp
->pd
;
4329 struct pcap_linux
*handlep
= handle
->priv
;
4332 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
4333 *sp
->pkt
= handlep
->oneshot_buffer
;
4337 pcap_cleanup_linux_mmap( pcap_t
*handle
)
4339 struct pcap_linux
*handlep
= handle
->priv
;
4341 destroy_ring(handle
);
4342 if (handlep
->oneshot_buffer
!= NULL
) {
4343 free(handlep
->oneshot_buffer
);
4344 handlep
->oneshot_buffer
= NULL
;
4346 pcap_cleanup_linux(handle
);
4351 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
4353 struct pcap_linux
*handlep
= p
->priv
;
4355 /* use negative value of timeout to indicate non blocking ops */
4356 return (handlep
->timeout
<0);
4360 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
4362 struct pcap_linux
*handlep
= p
->priv
;
4365 * Set the file descriptor to non-blocking mode, as we use
4366 * it for sending packets.
4368 if (pcap_setnonblock_fd(p
, nonblock
, errbuf
) == -1)
4372 * Map each value to their corresponding negation to
4373 * preserve the timeout value provided with pcap_set_timeout.
4376 if (handlep
->timeout
>= 0) {
4378 * Indicate that we're switching to
4379 * non-blocking mode.
4381 handlep
->timeout
= ~handlep
->timeout
;
4384 if (handlep
->timeout
< 0) {
4385 handlep
->timeout
= ~handlep
->timeout
;
4388 /* Update the timeout to use in poll(). */
4389 set_poll_timeout(handlep
);
4394 * Get the status field of the ring buffer frame at a specified offset.
4397 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
4399 struct pcap_linux
*handlep
= handle
->priv
;
4402 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
4403 switch (handlep
->tp_version
) {
4405 return (h
.h1
->tp_status
);
4408 return (h
.h1_64
->tp_status
);
4410 #ifdef HAVE_TPACKET2
4412 return (h
.h2
->tp_status
);
4415 #ifdef HAVE_TPACKET3
4417 return (h
.h3
->hdr
.bh1
.block_status
);
4421 /* This should not happen. */
4430 * Block waiting for frames to be available.
4432 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4434 struct pcap_linux
*handlep
= handle
->priv
;
4436 struct pollfd pollinfo
;
4439 pollinfo
.fd
= handle
->fd
;
4440 pollinfo
.events
= POLLIN
;
4443 ret
= poll(&pollinfo
, 1, handlep
->poll_timeout
);
4444 if (ret
< 0 && errno
!= EINTR
) {
4445 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4446 "can't poll on packet socket: %s",
4447 pcap_strerror(errno
));
4449 } else if (ret
> 0 &&
4450 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4452 * There's some indication other than
4453 * "you can read on this descriptor" on
4456 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
4457 snprintf(handle
->errbuf
,
4459 "Hangup on packet socket");
4462 if (pollinfo
.revents
& POLLERR
) {
4464 * A recv() will give us the actual error code.
4466 * XXX - make the socket non-blocking?
4468 if (recv(handle
->fd
, &c
, sizeof c
,
4470 continue; /* what, no error? */
4471 if (errno
== ENETDOWN
) {
4473 * The device on which we're
4474 * capturing went away.
4476 * XXX - we should really return
4477 * PCAP_ERROR_IFACE_NOT_UP, but
4478 * pcap_dispatch() etc. aren't
4479 * defined to return that.
4481 snprintf(handle
->errbuf
,
4483 "The interface went down");
4485 snprintf(handle
->errbuf
,
4487 "Error condition on packet socket: %s",
4492 if (pollinfo
.revents
& POLLNVAL
) {
4493 snprintf(handle
->errbuf
,
4495 "Invalid polling request on packet socket");
4499 /* check for break loop condition on interrupted syscall*/
4500 if (handle
->break_loop
) {
4501 handle
->break_loop
= 0;
4502 return PCAP_ERROR_BREAK
;
4508 /* handle a single memory mapped packet */
4509 static int pcap_handle_packet_mmap(
4511 pcap_handler callback
,
4513 unsigned char *frame
,
4514 unsigned int tp_len
,
4515 unsigned int tp_mac
,
4516 unsigned int tp_snaplen
,
4517 unsigned int tp_sec
,
4518 unsigned int tp_usec
,
4519 int tp_vlan_tci_valid
,
4523 struct pcap_linux
*handlep
= handle
->priv
;
4525 struct sockaddr_ll
*sll
;
4526 struct pcap_pkthdr pcaphdr
;
4528 /* perform sanity check on internal offset. */
4529 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
4530 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4531 "corrupted frame on kernel ring mac "
4532 "offset %u + caplen %u > frame len %d",
4533 tp_mac
, tp_snaplen
, handle
->bufsize
);
4537 /* run filter on received packet
4538 * If the kernel filtering is enabled we need to run the
4539 * filter until all the frames present into the ring
4540 * at filter creation time are processed.
4541 * In this case, blocks_to_filter_in_userland is used
4542 * as a counter for the packet we need to filter.
4543 * Note: alternatively it could be possible to stop applying
4544 * the filter when the ring became empty, but it can possibly
4545 * happen a lot later... */
4546 bp
= frame
+ tp_mac
;
4548 /* if required build in place the sll header*/
4549 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
4550 if (handlep
->cooked
) {
4551 struct sll_header
*hdrp
;
4554 * The kernel should have left us with enough
4555 * space for an sll header; back up the packet
4556 * data pointer into that space, as that'll be
4557 * the beginning of the packet we pass to the
4563 * Let's make sure that's past the end of
4564 * the tpacket header, i.e. >=
4565 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4566 * don't step on the header when we construct
4569 if (bp
< (u_char
*)frame
+
4570 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4571 sizeof(struct sockaddr_ll
)) {
4572 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4573 "cooked-mode frame doesn't have room for sll header");
4578 * OK, that worked; construct the sll header.
4580 hdrp
= (struct sll_header
*)bp
;
4581 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4583 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4584 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4585 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4586 hdrp
->sll_protocol
= sll
->sll_protocol
;
4589 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
4590 struct bpf_aux_data aux_data
;
4592 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4593 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
4595 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
4596 tp_len
, tp_snaplen
, &aux_data
) == 0)
4600 if (!linux_check_direction(handle
, sll
))
4603 /* get required packet info from ring header */
4604 pcaphdr
.ts
.tv_sec
= tp_sec
;
4605 pcaphdr
.ts
.tv_usec
= tp_usec
;
4606 pcaphdr
.caplen
= tp_snaplen
;
4607 pcaphdr
.len
= tp_len
;
4609 /* if required build in place the sll header*/
4610 if (handlep
->cooked
) {
4611 /* update packet len */
4612 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4613 pcaphdr
.len
+= SLL_HDR_LEN
;
4616 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4617 if (tp_vlan_tci_valid
&&
4618 handlep
->vlan_offset
!= -1 &&
4619 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4621 struct vlan_tag
*tag
;
4624 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4626 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4627 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4628 tag
->vlan_tci
= htons(tp_vlan_tci
);
4630 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4631 pcaphdr
.len
+= VLAN_TAG_LEN
;
4636 * The only way to tell the kernel to cut off the
4637 * packet at a snapshot length is with a filter program;
4638 * if there's no filter program, the kernel won't cut
4641 * Trim the snapshot length to be no longer than the
4642 * specified snapshot length.
4644 if (pcaphdr
.caplen
> handle
->snapshot
)
4645 pcaphdr
.caplen
= handle
->snapshot
;
4647 /* pass the packet to the user */
4648 callback(user
, &pcaphdr
, bp
);
4654 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4657 struct pcap_linux
*handlep
= handle
->priv
;
4662 /* wait for frames availability.*/
4663 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4664 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
) {
4666 * The current frame is owned by the kernel; wait for
4667 * a frame to be handed to us.
4669 ret
= pcap_wait_for_frames_mmap(handle
);
4675 /* non-positive values of max_packets are used to require all
4676 * packets currently available in the ring */
4677 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4679 * Get the current ring buffer frame, and break if
4680 * it's still owned by the kernel.
4682 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4683 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
)
4686 ret
= pcap_handle_packet_mmap(
4701 handlep
->packets_read
++;
4702 } else if (ret
< 0) {
4707 * Hand this block back to the kernel, and, if we're
4708 * counting blocks that need to be filtered in userland
4709 * after having been filtered by the kernel, count
4710 * the one we've just processed.
4712 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4713 if (handlep
->blocks_to_filter_in_userland
> 0) {
4714 handlep
->blocks_to_filter_in_userland
--;
4715 if (handlep
->blocks_to_filter_in_userland
== 0) {
4717 * No more blocks need to be filtered
4720 handlep
->filter_in_userland
= 0;
4725 if (++handle
->offset
>= handle
->cc
)
4728 /* check for break loop condition*/
4729 if (handle
->break_loop
) {
4730 handle
->break_loop
= 0;
4731 return PCAP_ERROR_BREAK
;
4738 pcap_read_linux_mmap_v1_64(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4741 struct pcap_linux
*handlep
= handle
->priv
;
4746 /* wait for frames availability.*/
4747 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4748 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
) {
4750 * The current frame is owned by the kernel; wait for
4751 * a frame to be handed to us.
4753 ret
= pcap_wait_for_frames_mmap(handle
);
4759 /* non-positive values of max_packets are used to require all
4760 * packets currently available in the ring */
4761 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4763 * Get the current ring buffer frame, and break if
4764 * it's still owned by the kernel.
4766 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4767 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
)
4770 ret
= pcap_handle_packet_mmap(
4777 h
.h1_64
->tp_snaplen
,
4785 handlep
->packets_read
++;
4786 } else if (ret
< 0) {
4791 * Hand this block back to the kernel, and, if we're
4792 * counting blocks that need to be filtered in userland
4793 * after having been filtered by the kernel, count
4794 * the one we've just processed.
4796 h
.h1_64
->tp_status
= TP_STATUS_KERNEL
;
4797 if (handlep
->blocks_to_filter_in_userland
> 0) {
4798 handlep
->blocks_to_filter_in_userland
--;
4799 if (handlep
->blocks_to_filter_in_userland
== 0) {
4801 * No more blocks need to be filtered
4804 handlep
->filter_in_userland
= 0;
4809 if (++handle
->offset
>= handle
->cc
)
4812 /* check for break loop condition*/
4813 if (handle
->break_loop
) {
4814 handle
->break_loop
= 0;
4815 return PCAP_ERROR_BREAK
;
4821 #ifdef HAVE_TPACKET2
4823 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4826 struct pcap_linux
*handlep
= handle
->priv
;
4831 /* wait for frames availability.*/
4832 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4833 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
) {
4835 * The current frame is owned by the kernel; wait for
4836 * a frame to be handed to us.
4838 ret
= pcap_wait_for_frames_mmap(handle
);
4844 /* non-positive values of max_packets are used to require all
4845 * packets currently available in the ring */
4846 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4848 * Get the current ring buffer frame, and break if
4849 * it's still owned by the kernel.
4851 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4852 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
)
4855 ret
= pcap_handle_packet_mmap(
4864 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4865 #if defined(TP_STATUS_VLAN_VALID)
4866 (h
.h2
->tp_vlan_tci
|| (h
.h2
->tp_status
& TP_STATUS_VLAN_VALID
)),
4868 h
.h2
->tp_vlan_tci
!= 0,
4871 VLAN_TPID(h
.h2
, h
.h2
));
4874 handlep
->packets_read
++;
4875 } else if (ret
< 0) {
4880 * Hand this block back to the kernel, and, if we're
4881 * counting blocks that need to be filtered in userland
4882 * after having been filtered by the kernel, count
4883 * the one we've just processed.
4885 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4886 if (handlep
->blocks_to_filter_in_userland
> 0) {
4887 handlep
->blocks_to_filter_in_userland
--;
4888 if (handlep
->blocks_to_filter_in_userland
== 0) {
4890 * No more blocks need to be filtered
4893 handlep
->filter_in_userland
= 0;
4898 if (++handle
->offset
>= handle
->cc
)
4901 /* check for break loop condition*/
4902 if (handle
->break_loop
) {
4903 handle
->break_loop
= 0;
4904 return PCAP_ERROR_BREAK
;
4909 #endif /* HAVE_TPACKET2 */
4911 #ifdef HAVE_TPACKET3
4913 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4916 struct pcap_linux
*handlep
= handle
->priv
;
4922 if (handlep
->current_packet
== NULL
) {
4923 /* wait for frames availability.*/
4924 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4925 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4927 * The current frame is owned by the kernel; wait
4928 * for a frame to be handed to us.
4930 ret
= pcap_wait_for_frames_mmap(handle
);
4936 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4937 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4938 if (pkts
== 0 && handlep
->timeout
== 0) {
4939 /* Block until we see a packet. */
4945 /* non-positive values of max_packets are used to require all
4946 * packets currently available in the ring */
4947 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4948 if (handlep
->current_packet
== NULL
) {
4949 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4950 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
)
4953 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4954 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4956 int packets_to_read
= handlep
->packets_left
;
4958 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) && packets_to_read
> max_packets
) {
4959 packets_to_read
= max_packets
;
4962 while(packets_to_read
--) {
4963 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4964 ret
= pcap_handle_packet_mmap(
4968 handlep
->current_packet
,
4971 tp3_hdr
->tp_snaplen
,
4973 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4974 #if defined(TP_STATUS_VLAN_VALID)
4975 (tp3_hdr
->hv1
.tp_vlan_tci
|| (tp3_hdr
->tp_status
& TP_STATUS_VLAN_VALID
)),
4977 tp3_hdr
->hv1
.tp_vlan_tci
!= 0,
4979 tp3_hdr
->hv1
.tp_vlan_tci
,
4980 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
4983 handlep
->packets_read
++;
4984 } else if (ret
< 0) {
4985 handlep
->current_packet
= NULL
;
4988 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4989 handlep
->packets_left
--;
4992 if (handlep
->packets_left
<= 0) {
4994 * Hand this block back to the kernel, and, if
4995 * we're counting blocks that need to be
4996 * filtered in userland after having been
4997 * filtered by the kernel, count the one we've
5000 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
5001 if (handlep
->blocks_to_filter_in_userland
> 0) {
5002 handlep
->blocks_to_filter_in_userland
--;
5003 if (handlep
->blocks_to_filter_in_userland
== 0) {
5005 * No more blocks need to be filtered
5008 handlep
->filter_in_userland
= 0;
5013 if (++handle
->offset
>= handle
->cc
)
5016 handlep
->current_packet
= NULL
;
5019 /* check for break loop condition*/
5020 if (handle
->break_loop
) {
5021 handle
->break_loop
= 0;
5022 return PCAP_ERROR_BREAK
;
5025 if (pkts
== 0 && handlep
->timeout
== 0) {
5026 /* Block until we see a packet. */
5031 #endif /* HAVE_TPACKET3 */
5034 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
5036 struct pcap_linux
*handlep
= handle
->priv
;
5041 * Don't rewrite "ret" instructions; we don't need to, as
5042 * we're not reading packets with recvmsg(), and we don't
5043 * want to, as, by not rewriting them, the kernel can avoid
5044 * copying extra data.
5046 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
5051 * If we're filtering in userland, there's nothing to do;
5052 * the new filter will be used for the next packet.
5054 if (handlep
->filter_in_userland
)
5058 * We're filtering in the kernel; the packets present in
5059 * all blocks currently in the ring were already filtered
5060 * by the old filter, and so will need to be filtered in
5061 * userland by the new filter.
5063 * Get an upper bound for the number of such blocks; first,
5064 * walk the ring backward and count the free blocks.
5066 offset
= handle
->offset
;
5068 offset
= handle
->cc
- 1;
5069 for (n
=0; n
< handle
->cc
; ++n
) {
5071 offset
= handle
->cc
- 1;
5072 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
5077 * If we found free blocks, decrement the count of free
5078 * blocks by 1, just in case we lost a race with another
5079 * thread of control that was adding a packet while
5080 * we were counting and that had run the filter before
5083 * XXX - could there be more than one block added in
5086 * XXX - is there a way to avoid that race, e.g. somehow
5087 * wait for all packets that passed the old filter to
5088 * be added to the ring?
5094 * Set the count of blocks worth of packets to filter
5095 * in userland to the total number of blocks in the
5096 * ring minus the number of free blocks we found, and
5097 * turn on userland filtering. (The count of blocks
5098 * worth of packets to filter in userland is guaranteed
5099 * not to be zero - n, above, couldn't be set to a
5100 * value > handle->cc, and if it were equal to
5101 * handle->cc, it wouldn't be zero, and thus would
5102 * be decremented to handle->cc - 1.)
5104 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
5105 handlep
->filter_in_userland
= 1;
5109 #endif /* HAVE_PACKET_RING */
5112 #ifdef HAVE_PF_PACKET_SOCKETS
5114 * Return the index of the given device name. Fill ebuf and return
5118 iface_get_id(int fd
, const char *device
, char *ebuf
)
5122 memset(&ifr
, 0, sizeof(ifr
));
5123 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5125 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
5126 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5127 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
5131 return ifr
.ifr_ifindex
;
5135 * Bind the socket associated with FD to the given device.
5136 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
5137 * or a PCAP_ERROR_ value on a hard error.
5140 iface_bind(int fd
, int ifindex
, char *ebuf
)
5142 struct sockaddr_ll sll
;
5144 socklen_t errlen
= sizeof(err
);
5146 memset(&sll
, 0, sizeof(sll
));
5147 sll
.sll_family
= AF_PACKET
;
5148 sll
.sll_ifindex
= ifindex
;
5149 sll
.sll_protocol
= htons(ETH_P_ALL
);
5151 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
5152 if (errno
== ENETDOWN
) {
5154 * Return a "network down" indication, so that
5155 * the application can report that rather than
5156 * saying we had a mysterious failure and
5157 * suggest that they report a problem to the
5158 * libpcap developers.
5160 return PCAP_ERROR_IFACE_NOT_UP
;
5162 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5163 "bind: %s", pcap_strerror(errno
));
5168 /* Any pending errors, e.g., network is down? */
5170 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5171 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5172 "getsockopt: %s", pcap_strerror(errno
));
5176 if (err
== ENETDOWN
) {
5178 * Return a "network down" indication, so that
5179 * the application can report that rather than
5180 * saying we had a mysterious failure and
5181 * suggest that they report a problem to the
5182 * libpcap developers.
5184 return PCAP_ERROR_IFACE_NOT_UP
;
5185 } else if (err
> 0) {
5186 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5187 "bind: %s", pcap_strerror(err
));
5194 #ifdef IW_MODE_MONITOR
5196 * Check whether the device supports the Wireless Extensions.
5197 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5198 * if the device doesn't even exist.
5201 has_wext(int sock_fd
, const char *device
, char *ebuf
)
5205 if (is_bonding_device(sock_fd
, device
))
5206 return 0; /* bonding device, so don't even try */
5208 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5209 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5210 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
5212 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5213 "%s: SIOCGIWNAME: %s", device
, pcap_strerror(errno
));
5214 if (errno
== ENODEV
)
5215 return PCAP_ERROR_NO_SUCH_DEVICE
;
5220 * Per me si va ne la citta dolente,
5221 * Per me si va ne l'etterno dolore,
5223 * Lasciate ogne speranza, voi ch'intrate.
5225 * XXX - airmon-ng does special stuff with the Orinoco driver and the
5241 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5242 * on if it's not already on.
5244 * Returns 1 on success, 0 if we don't support the Wireless Extensions
5245 * on this device, or a PCAP_ERROR_ value if we do support them but
5246 * we weren't able to turn monitor mode on.
5249 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
5252 * XXX - at least some adapters require non-Wireless Extensions
5253 * mechanisms to turn monitor mode on.
5255 * Atheros cards might require that a separate "monitor virtual access
5256 * point" be created, with later versions of the madwifi driver.
5257 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
5258 * monitor -bssid", which apparently spits out a line "athN"
5259 * where "athN" is the monitor mode device. To leave monitor
5260 * mode, it destroys the monitor mode device.
5262 * Some Intel Centrino adapters might require private ioctls to get
5263 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5264 * configure a separate "rtapN" interface to capture in monitor
5265 * mode without preventing the adapter from operating normally.
5266 * (airmon-ng doesn't appear to use that, though.)
5268 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5269 * up, and if all drivers were converted to mac80211 drivers.
5271 * If interface {if} is a mac80211 driver, the file
5272 * /sys/class/net/{if}/phy80211 is a symlink to
5273 * /sys/class/ieee80211/{phydev}, for some {phydev}.
5275 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5276 * least, has a "wmaster0" device and a "wlan0" device; the
5277 * latter is the one with the IP address. Both show up in
5278 * "tcpdump -D" output. Capturing on the wmaster0 device
5279 * captures with 802.11 headers.
5281 * airmon-ng searches through /sys/class/net for devices named
5282 * monN, starting with mon0; as soon as one *doesn't* exist,
5283 * it chooses that as the monitor device name. If the "iw"
5284 * command exists, it does "iw dev {if} interface add {monif}
5285 * type monitor", where {monif} is the monitor device. It
5286 * then (sigh) sleeps .1 second, and then configures the
5287 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
5288 * is a file, it writes {mondev}, without a newline, to that file,
5289 * and again (sigh) sleeps .1 second, and then iwconfig's that
5290 * device into monitor mode and configures it up. Otherwise,
5291 * you can't do monitor mode.
5293 * All these devices are "glued" together by having the
5294 * /sys/class/net/{device}/phy80211 links pointing to the same
5295 * place, so, given a wmaster, wlan, or mon device, you can
5296 * find the other devices by looking for devices with
5297 * the same phy80211 link.
5299 * To turn monitor mode off, delete the monitor interface,
5300 * either with "iw dev {monif} interface del" or by sending
5301 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
5303 * Note: if you try to create a monitor device named "monN", and
5304 * there's already a "monN" device, it fails, as least with
5305 * the netlink interface (which is what iw uses), with a return
5306 * value of -ENFILE. (Return values are negative errnos.) We
5307 * could probably use that to find an unused device.
5309 struct pcap_linux
*handlep
= handle
->priv
;
5312 struct iw_priv_args
*priv
;
5313 monitor_type montype
;
5322 * Does this device *support* the Wireless Extensions?
5324 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
5326 return err
; /* either it doesn't or the device doesn't even exist */
5328 * Start out assuming we have no private extensions to control
5331 montype
= MONITOR_WEXT
;
5335 * Try to get all the Wireless Extensions private ioctls
5336 * supported by this device.
5338 * First, get the size of the buffer we need, by supplying no
5339 * buffer and a length of 0. If the device supports private
5340 * ioctls, it should return E2BIG, with ireq.u.data.length set
5341 * to the length we need. If it doesn't support them, it should
5342 * return EOPNOTSUPP.
5344 memset(&ireq
, 0, sizeof ireq
);
5345 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5346 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5347 ireq
.u
.data
.pointer
= (void *)args
;
5348 ireq
.u
.data
.length
= 0;
5349 ireq
.u
.data
.flags
= 0;
5350 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
5351 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5352 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
5356 if (errno
!= EOPNOTSUPP
) {
5358 * OK, it's not as if there are no private ioctls.
5360 if (errno
!= E2BIG
) {
5364 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5365 "%s: SIOCGIWPRIV: %s", device
,
5366 pcap_strerror(errno
));
5371 * OK, try to get the list of private ioctls.
5373 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
5375 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5376 "malloc: %s", pcap_strerror(errno
));
5379 ireq
.u
.data
.pointer
= (void *)priv
;
5380 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
5381 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5382 "%s: SIOCGIWPRIV: %s", device
,
5383 pcap_strerror(errno
));
5389 * Look for private ioctls to turn monitor mode on or, if
5390 * monitor mode is on, to set the header type.
5392 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
5393 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
5395 * Hostap driver, use this one.
5396 * Set monitor mode first.
5397 * You can set it to 0 to get DLT_IEEE80211,
5398 * 1 to get DLT_PRISM, 2 to get
5399 * DLT_IEEE80211_RADIO_AVS, and, with more
5400 * recent versions of the driver, 3 to get
5401 * DLT_IEEE80211_RADIO.
5403 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5405 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5407 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5409 montype
= MONITOR_HOSTAP
;
5413 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
5415 * Prism54 driver, use this one.
5416 * Set monitor mode first.
5417 * You can set it to 2 to get DLT_IEEE80211
5418 * or 3 or get DLT_PRISM.
5420 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5422 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5424 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5426 montype
= MONITOR_PRISM54
;
5430 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
5432 * RT2570 driver, use this one.
5433 * Do this after turning monitor mode on.
5434 * You can set it to 1 to get DLT_PRISM or 2
5435 * to get DLT_IEEE80211.
5437 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5439 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5441 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5443 montype
= MONITOR_RT2570
;
5447 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
5449 * RT73 driver, use this one.
5450 * Do this after turning monitor mode on.
5451 * Its argument is a *string*; you can
5452 * set it to "1" to get DLT_PRISM or "2"
5453 * to get DLT_IEEE80211.
5455 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
5457 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
5459 montype
= MONITOR_RT73
;
5463 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
5465 * One of the RTL8xxx drivers, use this one.
5466 * It can only be done after monitor mode
5467 * has been turned on. You can set it to 1
5468 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5470 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5472 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5474 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5476 montype
= MONITOR_RTL8XXX
;
5480 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
5482 * RT2500 or RT61 driver, use this one.
5483 * It has one one-byte parameter; set
5484 * u.data.length to 1 and u.data.pointer to
5485 * point to the parameter.
5486 * It doesn't itself turn monitor mode on.
5487 * You can set it to 1 to allow transmitting
5488 * in monitor mode(?) and get DLT_IEEE80211,
5489 * or set it to 0 to disallow transmitting in
5490 * monitor mode(?) and get DLT_PRISM.
5492 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5494 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
5496 montype
= MONITOR_RT2500
;
5500 if (strcmp(priv
[i
].name
, "monitor") == 0) {
5502 * Either ACX100 or hostap, use this one.
5503 * It turns monitor mode on.
5504 * If it takes two arguments, it's ACX100;
5505 * the first argument is 1 for DLT_PRISM
5506 * or 2 for DLT_IEEE80211, and the second
5507 * argument is the channel on which to
5508 * run. If it takes one argument, it's
5509 * HostAP, and the argument is 2 for
5510 * DLT_IEEE80211 and 3 for DLT_PRISM.
5512 * If we see this, we don't quit, as this
5513 * might be a version of the hostap driver
5514 * that also supports "monitor_type".
5516 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5518 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5520 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5523 montype
= MONITOR_PRISM
;
5528 montype
= MONITOR_ACX100
;
5541 * XXX - ipw3945? islism?
5547 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5548 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5549 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
5551 * We probably won't be able to set the mode, either.
5553 return PCAP_ERROR_RFMON_NOTSUP
;
5557 * Is it currently in monitor mode?
5559 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
5561 * Yes. Just leave things as they are.
5562 * We don't offer multiple link-layer types, as
5563 * changing the link-layer type out from under
5564 * somebody else capturing in monitor mode would
5565 * be considered rude.
5570 * No. We have to put the adapter into rfmon mode.
5574 * If we haven't already done so, arrange to have
5575 * "pcap_close_all()" called when we exit.
5577 if (!pcap_do_addexit(handle
)) {
5579 * "atexit()" failed; don't put the interface
5580 * in rfmon mode, just give up.
5582 return PCAP_ERROR_RFMON_NOTSUP
;
5586 * Save the old mode.
5588 handlep
->oldmode
= ireq
.u
.mode
;
5591 * Put the adapter in rfmon mode. How we do this depends
5592 * on whether we have a special private ioctl or not.
5594 if (montype
== MONITOR_PRISM
) {
5596 * We have the "monitor" private ioctl, but none of
5597 * the other private ioctls. Use this, and select
5600 * If it fails, just fall back on SIOCSIWMODE.
5602 memset(&ireq
, 0, sizeof ireq
);
5603 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5604 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5605 ireq
.u
.data
.length
= 1; /* 1 argument */
5606 args
[0] = 3; /* request Prism header */
5607 memcpy(ireq
.u
.name
, args
, sizeof (int));
5608 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
5611 * Note that we have to put the old mode back
5612 * when we close the device.
5614 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5617 * Add this to the list of pcaps to close
5620 pcap_add_to_pcaps_to_close(handle
);
5626 * Failure. Fall back on SIOCSIWMODE.
5631 * First, take the interface down if it's up; otherwise, we
5634 memset(&ifr
, 0, sizeof(ifr
));
5635 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5636 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5637 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5638 "%s: Can't get flags: %s", device
, strerror(errno
));
5642 if (ifr
.ifr_flags
& IFF_UP
) {
5643 oldflags
= ifr
.ifr_flags
;
5644 ifr
.ifr_flags
&= ~IFF_UP
;
5645 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5646 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5647 "%s: Can't set flags: %s", device
, strerror(errno
));
5653 * Then turn monitor mode on.
5655 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5656 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5657 ireq
.u
.mode
= IW_MODE_MONITOR
;
5658 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
5660 * Scientist, you've failed.
5661 * Bring the interface back up if we shut it down.
5663 ifr
.ifr_flags
= oldflags
;
5664 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5665 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5666 "%s: Can't set flags: %s", device
, strerror(errno
));
5669 return PCAP_ERROR_RFMON_NOTSUP
;
5673 * XXX - airmon-ng does "iwconfig {if} key off" after setting
5674 * monitor mode and setting the channel, and then does
5679 * Now select the appropriate radio header.
5685 * We don't have any private ioctl to set the header.
5689 case MONITOR_HOSTAP
:
5691 * Try to select the radiotap header.
5693 memset(&ireq
, 0, sizeof ireq
);
5694 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5695 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5696 args
[0] = 3; /* request radiotap header */
5697 memcpy(ireq
.u
.name
, args
, sizeof (int));
5698 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5699 break; /* success */
5702 * That failed. Try to select the AVS header.
5704 memset(&ireq
, 0, sizeof ireq
);
5705 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5706 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5707 args
[0] = 2; /* request AVS header */
5708 memcpy(ireq
.u
.name
, args
, sizeof (int));
5709 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5710 break; /* success */
5713 * That failed. Try to select the Prism header.
5715 memset(&ireq
, 0, sizeof ireq
);
5716 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5717 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5718 args
[0] = 1; /* request Prism header */
5719 memcpy(ireq
.u
.name
, args
, sizeof (int));
5720 ioctl(sock_fd
, cmd
, &ireq
);
5725 * The private ioctl failed.
5729 case MONITOR_PRISM54
:
5731 * Select the Prism header.
5733 memset(&ireq
, 0, sizeof ireq
);
5734 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5735 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5736 args
[0] = 3; /* request Prism header */
5737 memcpy(ireq
.u
.name
, args
, sizeof (int));
5738 ioctl(sock_fd
, cmd
, &ireq
);
5741 case MONITOR_ACX100
:
5743 * Get the current channel.
5745 memset(&ireq
, 0, sizeof ireq
);
5746 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5747 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5748 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
5749 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5750 "%s: SIOCGIWFREQ: %s", device
,
5751 pcap_strerror(errno
));
5754 channel
= ireq
.u
.freq
.m
;
5757 * Select the Prism header, and set the channel to the
5760 memset(&ireq
, 0, sizeof ireq
);
5761 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5762 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5763 args
[0] = 1; /* request Prism header */
5764 args
[1] = channel
; /* set channel */
5765 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
5766 ioctl(sock_fd
, cmd
, &ireq
);
5769 case MONITOR_RT2500
:
5771 * Disallow transmission - that turns on the
5774 memset(&ireq
, 0, sizeof ireq
);
5775 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5776 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5777 args
[0] = 0; /* disallow transmitting */
5778 memcpy(ireq
.u
.name
, args
, sizeof (int));
5779 ioctl(sock_fd
, cmd
, &ireq
);
5782 case MONITOR_RT2570
:
5784 * Force the Prism header.
5786 memset(&ireq
, 0, sizeof ireq
);
5787 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5788 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5789 args
[0] = 1; /* request Prism header */
5790 memcpy(ireq
.u
.name
, args
, sizeof (int));
5791 ioctl(sock_fd
, cmd
, &ireq
);
5796 * Force the Prism header.
5798 memset(&ireq
, 0, sizeof ireq
);
5799 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5800 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5801 ireq
.u
.data
.length
= 1; /* 1 argument */
5802 ireq
.u
.data
.pointer
= "1";
5803 ireq
.u
.data
.flags
= 0;
5804 ioctl(sock_fd
, cmd
, &ireq
);
5807 case MONITOR_RTL8XXX
:
5809 * Force the Prism header.
5811 memset(&ireq
, 0, sizeof ireq
);
5812 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5813 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5814 args
[0] = 1; /* request Prism header */
5815 memcpy(ireq
.u
.name
, args
, sizeof (int));
5816 ioctl(sock_fd
, cmd
, &ireq
);
5821 * Now bring the interface back up if we brought it down.
5823 if (oldflags
!= 0) {
5824 ifr
.ifr_flags
= oldflags
;
5825 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5826 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5827 "%s: Can't set flags: %s", device
, strerror(errno
));
5830 * At least try to restore the old mode on the
5833 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
5835 * Scientist, you've failed.
5838 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5839 "Please adjust manually.\n",
5847 * Note that we have to put the old mode back when we
5850 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5853 * Add this to the list of pcaps to close when we exit.
5855 pcap_add_to_pcaps_to_close(handle
);
5859 #endif /* IW_MODE_MONITOR */
5862 * Try various mechanisms to enter monitor mode.
5865 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
5867 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5872 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
5874 return ret
; /* error attempting to do so */
5876 return 1; /* success */
5877 #endif /* HAVE_LIBNL */
5879 #ifdef IW_MODE_MONITOR
5880 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
5882 return ret
; /* error attempting to do so */
5884 return 1; /* success */
5885 #endif /* IW_MODE_MONITOR */
5888 * Either none of the mechanisms we know about work or none
5889 * of those mechanisms are available, so we can't do monitor
5895 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5897 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5899 static const struct {
5900 int soft_timestamping_val
;
5901 int pcap_tstamp_val
;
5902 } sof_ts_type_map
[3] = {
5903 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5904 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5905 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5907 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5910 iface_set_default_ts_types(pcap_t
*handle
)
5914 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5915 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5916 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5917 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5920 #ifdef ETHTOOL_GET_TS_INFO
5922 * Get a list of time stamping capabilities.
5925 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
)
5929 struct ethtool_ts_info info
;
5934 * This doesn't apply to the "any" device; you have to ask
5935 * specific devices for their capabilities, so just default
5936 * to saying we support all of them.
5938 if (strcmp(handle
->opt
.source
, "any") == 0) {
5939 iface_set_default_ts_types(handle
);
5944 * Create a socket from which to fetch time stamping capabilities.
5946 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
5948 (void)snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5949 "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO): %s", pcap_strerror(errno
));
5953 memset(&ifr
, 0, sizeof(ifr
));
5954 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5955 memset(&info
, 0, sizeof(info
));
5956 info
.cmd
= ETHTOOL_GET_TS_INFO
;
5957 ifr
.ifr_data
= (caddr_t
)&info
;
5958 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
5960 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
5962 * OK, let's just return all the possible time
5965 iface_set_default_ts_types(handle
);
5968 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5969 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: %s", handle
->opt
.source
,
5976 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5977 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
5980 handle
->tstamp_type_count
= num_ts_types
;
5981 if (num_ts_types
!= 0) {
5982 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
5983 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5984 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
5985 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5990 handle
->tstamp_type_list
= NULL
;
5994 #else /* ETHTOOL_GET_TS_INFO */
5996 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf _U_
)
5999 * We don't have an ioctl to use to ask what's supported,
6000 * so say we support everything.
6002 iface_set_default_ts_types(handle
);
6005 #endif /* ETHTOOL_GET_TS_INFO */
6007 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6009 #ifdef HAVE_PACKET_RING
6011 * Find out if we have any form of fragmentation/reassembly offloading.
6013 * We do so using SIOCETHTOOL checking for various types of offloading;
6014 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6015 * of the types of offloading, there's nothing we can do to check, so
6016 * we just say "no, we don't".
6018 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6020 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
6023 struct ethtool_value eval
;
6025 memset(&ifr
, 0, sizeof(ifr
));
6026 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
6029 ifr
.ifr_data
= (caddr_t
)&eval
;
6030 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
6031 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
6033 * OK, let's just return 0, which, in our
6034 * case, either means "no, what we're asking
6035 * about is not enabled" or "all the flags
6036 * are clear (i.e., nothing is enabled)".
6040 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6041 "%s: SIOCETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
6042 cmdname
, strerror(errno
));
6049 iface_get_offload(pcap_t
*handle
)
6054 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
6058 return 1; /* TCP segmentation offloading on */
6062 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
6066 return 1; /* UDP fragmentation offloading on */
6071 * XXX - will this cause large unsegmented packets to be
6072 * handed to PF_PACKET sockets on transmission? If not,
6073 * this need not be checked.
6075 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
6079 return 1; /* generic segmentation offloading on */
6082 #ifdef ETHTOOL_GFLAGS
6083 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
6086 if (ret
& ETH_FLAG_LRO
)
6087 return 1; /* large receive offloading on */
6092 * XXX - will this cause large reassembled packets to be
6093 * handed to PF_PACKET sockets on receipt? If not,
6094 * this need not be checked.
6096 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
6100 return 1; /* generic (large) receive offloading on */
6105 #else /* SIOCETHTOOL */
6107 iface_get_offload(pcap_t
*handle _U_
)
6110 * XXX - do we need to get this information if we don't
6111 * have the ethtool ioctls? If so, how do we do that?
6115 #endif /* SIOCETHTOOL */
6117 #endif /* HAVE_PACKET_RING */
6119 #endif /* HAVE_PF_PACKET_SOCKETS */
6121 /* ===== Functions to interface to the older kernels ================== */
6124 * Try to open a packet socket using the old kernel interface.
6125 * Returns 1 on success and a PCAP_ERROR_ value on an error.
6128 activate_old(pcap_t
*handle
)
6130 struct pcap_linux
*handlep
= handle
->priv
;
6133 const char *device
= handle
->opt
.source
;
6134 struct utsname utsname
;
6137 /* Open the socket */
6139 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
6140 if (handle
->fd
== -1) {
6141 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6142 "socket: %s", pcap_strerror(errno
));
6143 if (errno
== EPERM
|| errno
== EACCES
) {
6145 * You don't have permission to open the
6148 return PCAP_ERROR_PERM_DENIED
;
6157 /* It worked - we are using the old interface */
6158 handlep
->sock_packet
= 1;
6160 /* ...which means we get the link-layer header. */
6161 handlep
->cooked
= 0;
6163 /* Bind to the given device */
6165 if (strcmp(device
, "any") == 0) {
6166 strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
6170 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
6174 * Try to get the link-layer type.
6176 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
6181 * Try to find the DLT_ type corresponding to that
6184 map_arphrd_to_dlt(handle
, handle
->fd
, arptype
, device
, 0);
6185 if (handle
->linktype
== -1) {
6186 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6187 "unknown arptype %d", arptype
);
6191 /* Go to promisc mode if requested */
6193 if (handle
->opt
.promisc
) {
6194 memset(&ifr
, 0, sizeof(ifr
));
6195 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6196 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6197 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6198 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
6201 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
6203 * Promiscuous mode isn't currently on,
6204 * so turn it on, and remember that
6205 * we should turn it off when the
6210 * If we haven't already done so, arrange
6211 * to have "pcap_close_all()" called when
6214 if (!pcap_do_addexit(handle
)) {
6216 * "atexit()" failed; don't put
6217 * the interface in promiscuous
6218 * mode, just give up.
6223 ifr
.ifr_flags
|= IFF_PROMISC
;
6224 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6225 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6227 pcap_strerror(errno
));
6230 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
6233 * Add this to the list of pcaps
6234 * to close when we exit.
6236 pcap_add_to_pcaps_to_close(handle
);
6241 * Compute the buffer size.
6243 * We're using SOCK_PACKET, so this might be a 2.0[.x]
6244 * kernel, and might require special handling - check.
6246 if (uname(&utsname
) < 0 ||
6247 strncmp(utsname
.release
, "2.0", 3) == 0) {
6249 * Either we couldn't find out what kernel release
6250 * this is, or it's a 2.0[.x] kernel.
6252 * In the 2.0[.x] kernel, a "recvfrom()" on
6253 * a SOCK_PACKET socket, with MSG_TRUNC set, will
6254 * return the number of bytes read, so if we pass
6255 * a length based on the snapshot length, it'll
6256 * return the number of bytes from the packet
6257 * copied to userland, not the actual length
6260 * This means that, for example, the IP dissector
6261 * in tcpdump will get handed a packet length less
6262 * than the length in the IP header, and will
6263 * complain about "truncated-ip".
6265 * So we don't bother trying to copy from the
6266 * kernel only the bytes in which we're interested,
6267 * but instead copy them all, just as the older
6268 * versions of libpcap for Linux did.
6270 * The buffer therefore needs to be big enough to
6271 * hold the largest packet we can get from this
6272 * device. Unfortunately, we can't get the MRU
6273 * of the network; we can only get the MTU. The
6274 * MTU may be too small, in which case a packet larger
6275 * than the buffer size will be truncated *and* we
6276 * won't get the actual packet size.
6278 * However, if the snapshot length is larger than
6279 * the buffer size based on the MTU, we use the
6280 * snapshot length as the buffer size, instead;
6281 * this means that with a sufficiently large snapshot
6282 * length we won't artificially truncate packets
6283 * to the MTU-based size.
6285 * This mess just one of many problems with packet
6286 * capture on 2.0[.x] kernels; you really want a
6287 * 2.2[.x] or later kernel if you want packet capture
6290 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
6293 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
6294 if (handle
->bufsize
< handle
->snapshot
)
6295 handle
->bufsize
= handle
->snapshot
;
6298 * This is a 2.2[.x] or later kernel.
6300 * We can safely pass "recvfrom()" a byte count
6301 * based on the snapshot length.
6303 handle
->bufsize
= handle
->snapshot
;
6307 * Default value for offset to align link-layer payload
6308 * on a 4-byte boundary.
6313 * SOCK_PACKET sockets don't supply information from
6314 * stripped VLAN tags.
6316 handlep
->vlan_offset
= -1; /* unknown */
6322 * Bind the socket associated with FD to the given device using the
6323 * interface of the old kernels.
6326 iface_bind_old(int fd
, const char *device
, char *ebuf
)
6328 struct sockaddr saddr
;
6330 socklen_t errlen
= sizeof(err
);
6332 memset(&saddr
, 0, sizeof(saddr
));
6333 strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
6334 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
6335 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6336 "bind: %s", pcap_strerror(errno
));
6340 /* Any pending errors, e.g., network is down? */
6342 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
6343 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6344 "getsockopt: %s", pcap_strerror(errno
));
6349 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6350 "bind: %s", pcap_strerror(err
));
6358 /* ===== System calls available on all supported kernels ============== */
6361 * Query the kernel for the MTU of the given interface.
6364 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
6369 return BIGGER_THAN_ALL_MTUS
;
6371 memset(&ifr
, 0, sizeof(ifr
));
6372 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6374 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
6375 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6376 "SIOCGIFMTU: %s", pcap_strerror(errno
));
6384 * Get the hardware type of the given interface as ARPHRD_xxx constant.
6387 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
6391 memset(&ifr
, 0, sizeof(ifr
));
6392 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6394 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
6395 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6396 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
6397 if (errno
== ENODEV
) {
6401 return PCAP_ERROR_NO_SUCH_DEVICE
;
6406 return ifr
.ifr_hwaddr
.sa_family
;
6409 #ifdef SO_ATTACH_FILTER
6411 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
6413 struct pcap_linux
*handlep
= handle
->priv
;
6416 register struct bpf_insn
*p
;
6421 * Make a copy of the filter, and modify that copy if
6424 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
6425 len
= handle
->fcode
.bf_len
;
6426 f
= (struct bpf_insn
*)malloc(prog_size
);
6428 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6429 "malloc: %s", pcap_strerror(errno
));
6432 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
6434 fcode
->filter
= (struct sock_filter
*) f
;
6436 for (i
= 0; i
< len
; ++i
) {
6439 * What type of instruction is this?
6441 switch (BPF_CLASS(p
->code
)) {
6445 * It's a return instruction; are we capturing
6446 * in memory-mapped mode?
6450 * No; is the snapshot length a constant,
6451 * rather than the contents of the
6454 if (BPF_MODE(p
->code
) == BPF_K
) {
6456 * Yes - if the value to be returned,
6457 * i.e. the snapshot length, is
6458 * anything other than 0, make it
6459 * MAXIMUM_SNAPLEN, so that the packet
6460 * is truncated by "recvfrom()",
6461 * not by the filter.
6463 * XXX - there's nothing we can
6464 * easily do if it's getting the
6465 * value from the accumulator; we'd
6466 * have to insert code to force
6467 * non-zero values to be
6471 p
->k
= MAXIMUM_SNAPLEN
;
6479 * It's a load instruction; is it loading
6482 switch (BPF_MODE(p
->code
)) {
6488 * Yes; are we in cooked mode?
6490 if (handlep
->cooked
) {
6492 * Yes, so we need to fix this
6495 if (fix_offset(p
) < 0) {
6497 * We failed to do so.
6498 * Return 0, so our caller
6499 * knows to punt to userland.
6509 return 1; /* we succeeded */
6513 fix_offset(struct bpf_insn
*p
)
6516 * What's the offset?
6518 if (p
->k
>= SLL_HDR_LEN
) {
6520 * It's within the link-layer payload; that starts at an
6521 * offset of 0, as far as the kernel packet filter is
6522 * concerned, so subtract the length of the link-layer
6525 p
->k
-= SLL_HDR_LEN
;
6526 } else if (p
->k
== 0) {
6528 * It's the packet type field; map it to the special magic
6529 * kernel offset for that field.
6531 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6532 } else if (p
->k
== 14) {
6534 * It's the protocol field; map it to the special magic
6535 * kernel offset for that field.
6537 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6538 } else if ((bpf_int32
)(p
->k
) > 0) {
6540 * It's within the header, but it's not one of those
6541 * fields; we can't do that in the kernel, so punt
6550 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
6552 int total_filter_on
= 0;
6558 * The socket filter code doesn't discard all packets queued
6559 * up on the socket when the filter is changed; this means
6560 * that packets that don't match the new filter may show up
6561 * after the new filter is put onto the socket, if those
6562 * packets haven't yet been read.
6564 * This means, for example, that if you do a tcpdump capture
6565 * with a filter, the first few packets in the capture might
6566 * be packets that wouldn't have passed the filter.
6568 * We therefore discard all packets queued up on the socket
6569 * when setting a kernel filter. (This isn't an issue for
6570 * userland filters, as the userland filtering is done after
6571 * packets are queued up.)
6573 * To flush those packets, we put the socket in read-only mode,
6574 * and read packets from the socket until there are no more to
6577 * In order to keep that from being an infinite loop - i.e.,
6578 * to keep more packets from arriving while we're draining
6579 * the queue - we put the "total filter", which is a filter
6580 * that rejects all packets, onto the socket before draining
6583 * This code deliberately ignores any errors, so that you may
6584 * get bogus packets if an error occurs, rather than having
6585 * the filtering done in userland even if it could have been
6586 * done in the kernel.
6588 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6589 &total_fcode
, sizeof(total_fcode
)) == 0) {
6593 * Note that we've put the total filter onto the socket.
6595 total_filter_on
= 1;
6598 * Save the socket's current mode, and put it in
6599 * non-blocking mode; we drain it by reading packets
6600 * until we get an error (which is normally a
6601 * "nothing more to be read" error).
6603 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6604 if (save_mode
== -1) {
6605 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6606 "can't get FD flags when changing filter: %s",
6607 pcap_strerror(errno
));
6610 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
6611 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6612 "can't set nonblocking mode when changing filter: %s",
6613 pcap_strerror(errno
));
6616 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
6619 if (save_errno
!= EAGAIN
) {
6623 * If we can't restore the mode or reset the
6624 * kernel filter, there's nothing we can do.
6626 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
6627 (void)reset_kernel_filter(handle
);
6628 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6629 "recv failed when changing filter: %s",
6630 pcap_strerror(save_errno
));
6633 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
6634 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6635 "can't restore FD flags when changing filter: %s",
6636 pcap_strerror(save_errno
));
6642 * Now attach the new filter.
6644 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6645 fcode
, sizeof(*fcode
));
6646 if (ret
== -1 && total_filter_on
) {
6648 * Well, we couldn't set that filter on the socket,
6649 * but we could set the total filter on the socket.
6651 * This could, for example, mean that the filter was
6652 * too big to put into the kernel, so we'll have to
6653 * filter in userland; in any case, we'll be doing
6654 * filtering in userland, so we need to remove the
6655 * total filter so we see packets.
6660 * If this fails, we're really screwed; we have the
6661 * total filter on the socket, and it won't come off.
6662 * Report it as a fatal error.
6664 if (reset_kernel_filter(handle
) == -1) {
6665 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6666 "can't remove kernel total filter: %s",
6667 pcap_strerror(errno
));
6668 return -2; /* fatal error */
6677 reset_kernel_filter(pcap_t
*handle
)
6680 * setsockopt() barfs unless it get a dummy parameter.
6681 * valgrind whines unless the value is initialized,
6682 * as it has no idea that setsockopt() ignores its
6687 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6688 &dummy
, sizeof(dummy
));