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 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
670 const char *device
, const char *mondevice
);
673 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
674 const char *device
, const char *mondevice
)
676 struct pcap_linux
*handlep
= handle
->priv
;
681 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
687 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
688 "%s: failed to allocate netlink msg", device
);
692 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
693 0, NL80211_CMD_NEW_INTERFACE
, 0);
694 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
695 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
696 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
698 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
700 #if defined HAVE_LIBNL_NLE
701 if (err
== -NLE_FAILURE
) {
703 if (err
== -ENFILE
) {
706 * Device not available; our caller should just
707 * keep trying. (libnl 2.x maps ENFILE to
708 * NLE_FAILURE; it can also map other errors
709 * to that, but there's not much we can do
716 * Real failure, not just "that device is not
719 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
720 "%s: nl_send_auto_complete failed adding %s interface: %s",
721 device
, mondevice
, get_nl_errmsg(-err
));
726 err
= nl_wait_for_ack(state
->nl_sock
);
728 #if defined HAVE_LIBNL_NLE
729 if (err
== -NLE_FAILURE
) {
731 if (err
== -ENFILE
) {
734 * Device not available; our caller should just
735 * keep trying. (libnl 2.x maps ENFILE to
736 * NLE_FAILURE; it can also map other errors
737 * to that, but there's not much we can do
744 * Real failure, not just "that device is not
747 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
748 "%s: nl_wait_for_ack failed adding %s interface: %s",
749 device
, mondevice
, get_nl_errmsg(-err
));
761 * Try to remember the monitor device.
763 handlep
->mondevice
= strdup(mondevice
);
764 if (handlep
->mondevice
== NULL
) {
765 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
766 pcap_strerror(errno
));
768 * Get rid of the monitor device.
770 del_mon_if(handle
, sock_fd
, state
, device
, mondevice
);
776 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
777 "%s: nl_put failed adding %s interface",
784 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
785 const char *device
, const char *mondevice
)
791 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
797 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
798 "%s: failed to allocate netlink msg", device
);
802 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
803 0, NL80211_CMD_DEL_INTERFACE
, 0);
804 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
806 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
808 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
809 "%s: nl_send_auto_complete failed deleting %s interface: %s",
810 device
, mondevice
, get_nl_errmsg(-err
));
814 err
= nl_wait_for_ack(state
->nl_sock
);
816 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
817 "%s: nl_wait_for_ack failed adding %s interface: %s",
818 device
, mondevice
, get_nl_errmsg(-err
));
830 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
831 "%s: nl_put failed deleting %s interface",
838 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
840 struct pcap_linux
*handlep
= handle
->priv
;
842 char phydev_path
[PATH_MAX
+1];
843 struct nl80211_state nlstate
;
848 * Is this a mac80211 device?
850 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
852 return ret
; /* error */
854 return 0; /* no error, but not mac80211 device */
857 * XXX - is this already a monN device?
859 * Is that determined by old Wireless Extensions ioctls?
863 * OK, it's apparently a mac80211 device.
864 * Try to find an unused monN device for it.
866 ret
= nl80211_init(handle
, &nlstate
, device
);
869 for (n
= 0; n
< UINT_MAX
; n
++) {
873 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
875 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
876 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
879 * Success. We don't clean up the libnl state
880 * yet, as we'll be using it later.
886 * Hard failure. Just return ret; handle->errbuf
887 * has already been set.
889 nl80211_cleanup(&nlstate
);
894 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
895 "%s: No free monN interfaces", device
);
896 nl80211_cleanup(&nlstate
);
903 * Sleep for .1 seconds.
906 delay
.tv_nsec
= 500000000;
907 nanosleep(&delay
, NULL
);
911 * If we haven't already done so, arrange to have
912 * "pcap_close_all()" called when we exit.
914 if (!pcap_do_addexit(handle
)) {
916 * "atexit()" failed; don't put the interface
917 * in rfmon mode, just give up.
919 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
920 "%s: atexit failed", device
);
921 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
923 nl80211_cleanup(&nlstate
);
928 * Now configure the monitor interface up.
930 memset(&ifr
, 0, sizeof(ifr
));
931 strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
932 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
933 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
934 "%s: Can't get flags for %s: %s", device
,
935 handlep
->mondevice
, strerror(errno
));
936 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
938 nl80211_cleanup(&nlstate
);
941 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
942 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
943 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
944 "%s: Can't set flags for %s: %s", device
,
945 handlep
->mondevice
, strerror(errno
));
946 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
948 nl80211_cleanup(&nlstate
);
953 * Success. Clean up the libnl state.
955 nl80211_cleanup(&nlstate
);
958 * Note that we have to delete the monitor device when we close
961 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
964 * Add this to the list of pcaps to close when we exit.
966 pcap_add_to_pcaps_to_close(handle
);
970 #endif /* HAVE_LIBNL */
972 #ifdef IW_MODE_MONITOR
974 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
975 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
976 * will fail with ENODEV if we try to do them on a bonding device,
977 * making us return a "no such device" indication rather than just
978 * saying "no Wireless Extensions".
980 * So we check for bonding devices, if we can, before trying those
981 * ioctls, by trying a bonding device information query ioctl to see
982 * whether it succeeds.
985 is_bonding_device(int fd
, const char *device
)
987 #if defined(HAVE_LINUX_IF_BONDING_H) && \
988 (defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY))
992 memset(&ifr
, 0, sizeof ifr
);
993 strlcpy(ifr
.ifr_name
, device
, sizeof ifr
.ifr_name
);
994 memset(&ifb
, 0, sizeof ifb
);
995 ifr
.ifr_data
= (caddr_t
)&ifb
;
996 #ifdef SIOCBONDINFOQUERY
997 if (ioctl(fd
, SIOCBONDINFOQUERY
, &ifr
) == 0)
998 #else /* SIOCBONDINFOQUERY */
999 if (ioctl(fd
, BOND_INFO_QUERY_OLD
, &ifr
) == 0)
1000 #endif /* SIOCBONDINFOQUERY */
1001 return 1; /* success, so it's a bonding device */
1002 #endif /* defined(HAVE_LINUX_IF_BONDING_H) && \
1003 (defined(BOND_INFO_QUERY_OLD) || defined(SIOCBONDINFOQUERY)) */
1005 return 0; /* no, it's not a bonding device */
1007 #endif /* IW_MODE_MONITOR */
1010 pcap_can_set_rfmon_linux(pcap_t
*handle
)
1013 char phydev_path
[PATH_MAX
+1];
1016 #ifdef IW_MODE_MONITOR
1021 if (strcmp(handle
->opt
.source
, "any") == 0) {
1023 * Monitor mode makes no sense on the "any" device.
1030 * Bleah. There doesn't seem to be a way to ask a mac80211
1031 * device, through libnl, whether it supports monitor mode;
1032 * we'll just check whether the device appears to be a
1033 * mac80211 device and, if so, assume the device supports
1036 * wmaster devices don't appear to support the Wireless
1037 * Extensions, but we can create a mon device for a
1038 * wmaster device, so we don't bother checking whether
1039 * a mac80211 device supports the Wireless Extensions.
1041 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
1044 return ret
; /* error */
1046 return 1; /* mac80211 device */
1049 #ifdef IW_MODE_MONITOR
1051 * Bleah. There doesn't appear to be an ioctl to use to ask
1052 * whether a device supports monitor mode; we'll just do
1053 * SIOCGIWMODE and, if it succeeds, assume the device supports
1056 * Open a socket on which to attempt to get the mode.
1057 * (We assume that if we have Wireless Extensions support
1058 * we also have PF_PACKET support.)
1060 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
1061 if (sock_fd
== -1) {
1062 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1063 "socket: %s", pcap_strerror(errno
));
1067 if (is_bonding_device(sock_fd
, handle
->opt
.source
)) {
1068 /* It's a bonding device, so don't even try. */
1074 * Attempt to get the current mode.
1076 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
1077 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1078 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
1080 * Well, we got the mode; assume we can set it.
1085 if (errno
== ENODEV
) {
1086 /* The device doesn't even exist. */
1087 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1088 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
1090 return PCAP_ERROR_NO_SUCH_DEVICE
;
1098 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1100 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1101 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1103 * Or can we get them in binary form from netlink?
1106 linux_if_drops(const char * if_name
)
1111 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1112 long int dropped_pkts
= 0;
1114 file
= fopen("/proc/net/dev", "r");
1118 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1120 /* search for 'bytes' -- if its in there, then
1121 that means we need to grab the fourth field. otherwise
1122 grab the third field. */
1123 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1125 field_to_convert
= 4;
1129 /* find iface and make sure it actually matches -- space before the name and : after it */
1130 if ((bufptr
= strstr(buffer
, if_name
)) &&
1131 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1132 *(bufptr
+ if_name_sz
) == ':')
1134 bufptr
= bufptr
+ if_name_sz
+ 1;
1136 /* grab the nth field from it */
1137 while( --field_to_convert
&& *bufptr
!= '\0')
1139 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1140 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1143 /* get rid of any final spaces */
1144 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1146 if (*bufptr
!= '\0')
1147 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1154 return dropped_pkts
;
1159 * With older kernels promiscuous mode is kind of interesting because we
1160 * have to reset the interface before exiting. The problem can't really
1161 * be solved without some daemon taking care of managing usage counts.
1162 * If we put the interface into promiscuous mode, we set a flag indicating
1163 * that we must take it out of that mode when the interface is closed,
1164 * and, when closing the interface, if that flag is set we take it out
1165 * of promiscuous mode.
1167 * Even with newer kernels, we have the same issue with rfmon mode.
1170 static void pcap_cleanup_linux( pcap_t
*handle
)
1172 struct pcap_linux
*handlep
= handle
->priv
;
1175 struct nl80211_state nlstate
;
1177 #endif /* HAVE_LIBNL */
1178 #ifdef IW_MODE_MONITOR
1181 #endif /* IW_MODE_MONITOR */
1183 if (handlep
->must_do_on_close
!= 0) {
1185 * There's something we have to do when closing this
1188 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1190 * We put the interface into promiscuous mode;
1191 * take it out of promiscuous mode.
1193 * XXX - if somebody else wants it in promiscuous
1194 * mode, this code cannot know that, so it'll take
1195 * it out of promiscuous mode. That's not fixable
1196 * in 2.0[.x] kernels.
1198 memset(&ifr
, 0, sizeof(ifr
));
1199 strlcpy(ifr
.ifr_name
, handlep
->device
,
1200 sizeof(ifr
.ifr_name
));
1201 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1203 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1204 "Please adjust manually.\n"
1205 "Hint: This can't happen with Linux >= 2.2.0.\n",
1206 handlep
->device
, strerror(errno
));
1208 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1210 * Promiscuous mode is currently on;
1213 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1214 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1217 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1218 "Please adjust manually.\n"
1219 "Hint: This can't happen with Linux >= 2.2.0.\n",
1228 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1229 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1231 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1232 handlep
->device
, handlep
->mondevice
);
1233 nl80211_cleanup(&nlstate
);
1237 "Can't delete monitor interface %s (%s).\n"
1238 "Please delete manually.\n",
1239 handlep
->mondevice
, handle
->errbuf
);
1242 #endif /* HAVE_LIBNL */
1244 #ifdef IW_MODE_MONITOR
1245 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1247 * We put the interface into rfmon mode;
1248 * take it out of rfmon mode.
1250 * XXX - if somebody else wants it in rfmon
1251 * mode, this code cannot know that, so it'll take
1252 * it out of rfmon mode.
1256 * First, take the interface down if it's up;
1257 * otherwise, we might get EBUSY.
1258 * If we get errors, just drive on and print
1259 * a warning if we can't restore the mode.
1262 memset(&ifr
, 0, sizeof(ifr
));
1263 strlcpy(ifr
.ifr_name
, handlep
->device
,
1264 sizeof(ifr
.ifr_name
));
1265 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1266 if (ifr
.ifr_flags
& IFF_UP
) {
1267 oldflags
= ifr
.ifr_flags
;
1268 ifr
.ifr_flags
&= ~IFF_UP
;
1269 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1270 oldflags
= 0; /* didn't set, don't restore */
1275 * Now restore the mode.
1277 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1278 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1279 ireq
.u
.mode
= handlep
->oldmode
;
1280 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1282 * Scientist, you've failed.
1285 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1286 "Please adjust manually.\n",
1287 handlep
->device
, strerror(errno
));
1291 * Now bring the interface back up if we brought
1294 if (oldflags
!= 0) {
1295 ifr
.ifr_flags
= oldflags
;
1296 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1298 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1299 "Please adjust manually.\n",
1300 handlep
->device
, strerror(errno
));
1304 #endif /* IW_MODE_MONITOR */
1307 * Take this pcap out of the list of pcaps for which we
1308 * have to take the interface out of some mode.
1310 pcap_remove_from_pcaps_to_close(handle
);
1313 if (handlep
->mondevice
!= NULL
) {
1314 free(handlep
->mondevice
);
1315 handlep
->mondevice
= NULL
;
1317 if (handlep
->device
!= NULL
) {
1318 free(handlep
->device
);
1319 handlep
->device
= NULL
;
1321 pcap_cleanup_live_common(handle
);
1325 * Set the timeout to be used in poll() with memory-mapped packet capture.
1328 set_poll_timeout(struct pcap_linux
*handlep
)
1330 #ifdef HAVE_TPACKET3
1331 struct utsname utsname
;
1332 char *version_component
, *endp
;
1334 int broken_tpacket_v3
= 1;
1337 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1338 * around which we have to work. Determine if we have those
1341 if (uname(&utsname
) == 0) {
1343 * 3.19 is the first release with a fixed version of
1344 * TPACKET_V3. We treat anything before that as
1345 * not haveing a fixed version; that may really mean
1346 * it has *no* version.
1348 version_component
= utsname
.release
;
1349 major
= strtol(version_component
, &endp
, 10);
1350 if (endp
!= version_component
&& *endp
== '.') {
1352 * OK, that was a valid major version.
1353 * Get the minor version.
1355 version_component
= endp
+ 1;
1356 minor
= strtol(version_component
, &endp
, 10);
1357 if (endp
!= version_component
&&
1358 (*endp
== '.' || *endp
== '\0')) {
1360 * OK, that was a valid minor version.
1361 * Is this 3.19 or newer?
1363 if (major
>= 4 || (major
== 3 && minor
>= 19)) {
1364 /* Yes. TPACKET_V3 works correctly. */
1365 broken_tpacket_v3
= 0;
1371 if (handlep
->timeout
== 0) {
1372 #ifdef HAVE_TPACKET3
1374 * XXX - due to a set of (mis)features in the TPACKET_V3
1375 * kernel code prior to the 3.19 kernel, blocking forever
1376 * with a TPACKET_V3 socket can, if few packets are
1377 * arriving and passing the socket filter, cause most
1378 * packets to be dropped. See libpcap issue #335 for the
1379 * full painful story.
1381 * The workaround is to have poll() time out very quickly,
1382 * so we grab the frames handed to us, and return them to
1385 if (handlep
->tp_version
== TPACKET_V3
&& broken_tpacket_v3
)
1386 handlep
->poll_timeout
= 1; /* don't block for very long */
1389 handlep
->poll_timeout
= -1; /* block forever */
1390 } else if (handlep
->timeout
> 0) {
1391 #ifdef HAVE_TPACKET3
1393 * For TPACKET_V3, the timeout is handled by the kernel,
1394 * so block forever; that way, we don't get extra timeouts.
1395 * Don't do that if we have a broken TPACKET_V3, though.
1397 if (handlep
->tp_version
== TPACKET_V3
&& !broken_tpacket_v3
)
1398 handlep
->poll_timeout
= -1; /* block forever, let TPACKET_V3 wake us up */
1401 handlep
->poll_timeout
= handlep
->timeout
; /* block for that amount of time */
1404 * Non-blocking mode; we call poll() to pick up error
1405 * indications, but we don't want it to wait for
1408 handlep
->poll_timeout
= 0;
1413 * Get a handle for a live capture from the given device. You can
1414 * pass NULL as device to get all packages (without link level
1415 * information of course). If you pass 1 as promisc the interface
1416 * will be set to promiscous mode (XXX: I think this usage should
1417 * be deprecated and functions be added to select that later allow
1418 * modification of that values -- Torsten).
1421 pcap_activate_linux(pcap_t
*handle
)
1423 struct pcap_linux
*handlep
= handle
->priv
;
1429 device
= handle
->opt
.source
;
1432 * Make sure the name we were handed will fit into the ioctls we
1433 * might perform on the device; if not, return a "No such device"
1434 * indication, as the Linux kernel shouldn't support creating
1435 * a device whose name won't fit into those ioctls.
1437 * "Will fit" means "will fit, complete with a null terminator",
1438 * so if the length, which does *not* include the null terminator,
1439 * is greater than *or equal to* the size of the field into which
1440 * we'll be copying it, that won't fit.
1442 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1443 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1447 handle
->inject_op
= pcap_inject_linux
;
1448 handle
->setfilter_op
= pcap_setfilter_linux
;
1449 handle
->setdirection_op
= pcap_setdirection_linux
;
1450 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1451 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1452 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1453 handle
->cleanup_op
= pcap_cleanup_linux
;
1454 handle
->read_op
= pcap_read_linux
;
1455 handle
->stats_op
= pcap_stats_linux
;
1458 * The "any" device is a special device which causes us not
1459 * to bind to a particular device and thus to look at all
1462 if (strcmp(device
, "any") == 0) {
1463 if (handle
->opt
.promisc
) {
1464 handle
->opt
.promisc
= 0;
1465 /* Just a warning. */
1466 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1467 "Promiscuous mode not supported on the \"any\" device");
1468 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1472 handlep
->device
= strdup(device
);
1473 if (handlep
->device
== NULL
) {
1474 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1475 pcap_strerror(errno
) );
1479 /* copy timeout value */
1480 handlep
->timeout
= handle
->opt
.timeout
;
1483 * If we're in promiscuous mode, then we probably want
1484 * to see when the interface drops packets too, so get an
1485 * initial count from /proc/net/dev
1487 if (handle
->opt
.promisc
)
1488 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1491 * Current Linux kernels use the protocol family PF_PACKET to
1492 * allow direct access to all packets on the network while
1493 * older kernels had a special socket type SOCK_PACKET to
1494 * implement this feature.
1495 * While this old implementation is kind of obsolete we need
1496 * to be compatible with older kernels for a while so we are
1497 * trying both methods with the newer method preferred.
1499 ret
= activate_new(handle
);
1502 * Fatal error with the new way; just fail.
1503 * ret has the error return; if it's PCAP_ERROR,
1504 * handle->errbuf has been set appropriately.
1512 * Try to use memory-mapped access.
1514 switch (activate_mmap(handle
, &status
)) {
1518 * We succeeded. status has been
1519 * set to the status to return,
1520 * which might be 0, or might be
1521 * a PCAP_WARNING_ value.
1523 * Set the timeout to use in poll() before
1526 set_poll_timeout(handlep
);
1531 * Kernel doesn't support it - just continue
1532 * with non-memory-mapped access.
1538 * We failed to set up to use it, or the kernel
1539 * supports it, but we failed to enable it.
1540 * ret has been set to the error status to
1541 * return and, if it's PCAP_ERROR, handle->errbuf
1542 * contains the error message.
1548 else if (ret
== 0) {
1549 /* Non-fatal error; try old way */
1550 if ((ret
= activate_old(handle
)) != 1) {
1552 * Both methods to open the packet socket failed.
1553 * Tidy up and report our failure (handle->errbuf
1554 * is expected to be set by the functions above).
1562 * We set up the socket, but not with memory-mapped access.
1564 if (handle
->opt
.buffer_size
!= 0) {
1566 * Set the socket buffer size to the specified value.
1568 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1569 &handle
->opt
.buffer_size
,
1570 sizeof(handle
->opt
.buffer_size
)) == -1) {
1571 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1572 "SO_RCVBUF: %s", pcap_strerror(errno
));
1573 status
= PCAP_ERROR
;
1578 /* Allocate the buffer */
1580 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1581 if (!handle
->buffer
) {
1582 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1583 "malloc: %s", pcap_strerror(errno
));
1584 status
= PCAP_ERROR
;
1589 * "handle->fd" is a socket, so "select()" and "poll()"
1590 * should work on it.
1592 handle
->selectable_fd
= handle
->fd
;
1597 pcap_cleanup_linux(handle
);
1602 * Read at most max_packets from the capture stream and call the callback
1603 * for each of them. Returns the number of packets handled or -1 if an
1607 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1610 * Currently, on Linux only one packet is delivered per read,
1613 return pcap_read_packet(handle
, callback
, user
);
1617 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1619 handle
->linktype
= dlt
;
1624 * linux_check_direction()
1626 * Do checks based on packet direction.
1629 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1631 struct pcap_linux
*handlep
= handle
->priv
;
1633 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1636 * If this is from the loopback device, reject it;
1637 * we'll see the packet as an incoming packet as well,
1638 * and we don't want to see it twice.
1640 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1644 * If the user only wants incoming packets, reject it.
1646 if (handle
->direction
== PCAP_D_IN
)
1651 * If the user only wants outgoing packets, reject it.
1653 if (handle
->direction
== PCAP_D_OUT
)
1660 * Read a packet from the socket calling the handler provided by
1661 * the user. Returns the number of packets received or -1 if an
1665 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1667 struct pcap_linux
*handlep
= handle
->priv
;
1670 #ifdef HAVE_PF_PACKET_SOCKETS
1671 struct sockaddr_ll from
;
1672 struct sll_header
*hdrp
;
1674 struct sockaddr from
;
1676 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1679 struct cmsghdr
*cmsg
;
1681 struct cmsghdr cmsg
;
1682 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1684 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1686 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1687 int packet_len
, caplen
;
1688 struct pcap_pkthdr pcap_header
;
1690 struct bpf_aux_data aux_data
;
1691 #ifdef HAVE_PF_PACKET_SOCKETS
1693 * If this is a cooked device, leave extra room for a
1694 * fake packet header.
1696 if (handlep
->cooked
)
1697 offset
= SLL_HDR_LEN
;
1702 * This system doesn't have PF_PACKET sockets, so it doesn't
1703 * support cooked devices.
1709 * Receive a single packet from the kernel.
1710 * We ignore EINTR, as that might just be due to a signal
1711 * being delivered - if the signal should interrupt the
1712 * loop, the signal handler should call pcap_breakloop()
1713 * to set handle->break_loop (we ignore it on other
1714 * platforms as well).
1715 * We also ignore ENETDOWN, so that we can continue to
1716 * capture traffic if the interface goes down and comes
1717 * back up again; comments in the kernel indicate that
1718 * we'll just block waiting for packets if we try to
1719 * receive from a socket that delivered ENETDOWN, and,
1720 * if we're using a memory-mapped buffer, we won't even
1721 * get notified of "network down" events.
1723 bp
= (u_char
*)handle
->buffer
+ handle
->offset
;
1725 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1726 msg
.msg_name
= &from
;
1727 msg
.msg_namelen
= sizeof(from
);
1730 msg
.msg_control
= &cmsg_buf
;
1731 msg
.msg_controllen
= sizeof(cmsg_buf
);
1734 iov
.iov_len
= handle
->bufsize
- offset
;
1735 iov
.iov_base
= bp
+ offset
;
1736 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1740 * Has "pcap_breakloop()" been called?
1742 if (handle
->break_loop
) {
1744 * Yes - clear the flag that indicates that it has,
1745 * and return PCAP_ERROR_BREAK as an indication that
1746 * we were told to break out of the loop.
1748 handle
->break_loop
= 0;
1749 return PCAP_ERROR_BREAK
;
1752 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1753 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1754 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1755 fromlen
= sizeof(from
);
1756 packet_len
= recvfrom(
1757 handle
->fd
, bp
+ offset
,
1758 handle
->bufsize
- offset
, MSG_TRUNC
,
1759 (struct sockaddr
*) &from
, &fromlen
);
1760 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1761 } while (packet_len
== -1 && errno
== EINTR
);
1763 /* Check if an error occured */
1765 if (packet_len
== -1) {
1769 return 0; /* no packet there */
1773 * The device on which we're capturing went away.
1775 * XXX - we should really return
1776 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1777 * etc. aren't defined to return that.
1779 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1780 "The interface went down");
1784 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1785 "recvfrom: %s", pcap_strerror(errno
));
1790 #ifdef HAVE_PF_PACKET_SOCKETS
1791 if (!handlep
->sock_packet
) {
1793 * Unfortunately, there is a window between socket() and
1794 * bind() where the kernel may queue packets from any
1795 * interface. If we're bound to a particular interface,
1796 * discard packets not from that interface.
1798 * (If socket filters are supported, we could do the
1799 * same thing we do when changing the filter; however,
1800 * that won't handle packet sockets without socket
1801 * filter support, and it's a bit more complicated.
1802 * It would save some instructions per packet, however.)
1804 if (handlep
->ifindex
!= -1 &&
1805 from
.sll_ifindex
!= handlep
->ifindex
)
1809 * Do checks based on packet direction.
1810 * We can only do this if we're using PF_PACKET; the
1811 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1812 * which lacks the relevant packet type information.
1814 if (!linux_check_direction(handle
, &from
))
1819 #ifdef HAVE_PF_PACKET_SOCKETS
1821 * If this is a cooked device, fill in the fake packet header.
1823 if (handlep
->cooked
) {
1825 * Add the length of the fake header to the length
1826 * of packet data we read.
1828 packet_len
+= SLL_HDR_LEN
;
1830 hdrp
= (struct sll_header
*)bp
;
1831 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1832 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1833 hdrp
->sll_halen
= htons(from
.sll_halen
);
1834 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1835 (from
.sll_halen
> SLL_ADDRLEN
) ?
1838 hdrp
->sll_protocol
= from
.sll_protocol
;
1841 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1842 if (handlep
->vlan_offset
!= -1) {
1843 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1844 struct tpacket_auxdata
*aux
;
1846 struct vlan_tag
*tag
;
1848 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1849 cmsg
->cmsg_level
!= SOL_PACKET
||
1850 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1853 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1854 #if defined(TP_STATUS_VLAN_VALID)
1855 if ((aux
->tp_vlan_tci
== 0) && !(aux
->tp_status
& TP_STATUS_VLAN_VALID
))
1857 if (aux
->tp_vlan_tci
== 0) /* this is ambigious but without the
1858 TP_STATUS_VLAN_VALID flag, there is
1859 nothing that we can do */
1863 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1864 if (len
< (unsigned int) handlep
->vlan_offset
)
1868 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1870 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1871 tag
->vlan_tpid
= htons(VLAN_TPID(aux
, aux
));
1872 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1874 /* store vlan tci to bpf_aux_data struct for userland bpf filter */
1875 #if defined(TP_STATUS_VLAN_VALID)
1876 aux_data
.vlan_tag
= htons(aux
->tp_vlan_tci
) & 0x0fff;
1877 aux_data
.vlan_tag_present
= (aux
->tp_status
& TP_STATUS_VLAN_VALID
);
1879 packet_len
+= VLAN_TAG_LEN
;
1882 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1883 #endif /* HAVE_PF_PACKET_SOCKETS */
1886 * XXX: According to the kernel source we should get the real
1887 * packet len if calling recvfrom with MSG_TRUNC set. It does
1888 * not seem to work here :(, but it is supported by this code
1890 * To be honest the code RELIES on that feature so this is really
1891 * broken with 2.2.x kernels.
1892 * I spend a day to figure out what's going on and I found out
1893 * that the following is happening:
1895 * The packet comes from a random interface and the packet_rcv
1896 * hook is called with a clone of the packet. That code inserts
1897 * the packet into the receive queue of the packet socket.
1898 * If a filter is attached to that socket that filter is run
1899 * first - and there lies the problem. The default filter always
1900 * cuts the packet at the snaplen:
1905 * So the packet filter cuts down the packet. The recvfrom call
1906 * says "hey, it's only 68 bytes, it fits into the buffer" with
1907 * the result that we don't get the real packet length. This
1908 * is valid at least until kernel 2.2.17pre6.
1910 * We currently handle this by making a copy of the filter
1911 * program, fixing all "ret" instructions with non-zero
1912 * operands to have an operand of MAXIMUM_SNAPLEN so that the
1913 * filter doesn't truncate the packet, and supplying that modified
1914 * filter to the kernel.
1917 caplen
= packet_len
;
1918 if (caplen
> handle
->snapshot
)
1919 caplen
= handle
->snapshot
;
1921 /* Run the packet filter if not using kernel filter */
1922 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
1923 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
1924 packet_len
, caplen
, &aux_data
) == 0) {
1925 /* rejected by filter */
1930 /* Fill in our own header data */
1932 /* get timestamp for this packet */
1933 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1934 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
1935 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
1936 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1937 "SIOCGSTAMPNS: %s", pcap_strerror(errno
));
1943 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1944 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1945 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1950 pcap_header
.caplen
= caplen
;
1951 pcap_header
.len
= packet_len
;
1956 * Arguably, we should count them before we check the filter,
1957 * as on many other platforms "ps_recv" counts packets
1958 * handed to the filter rather than packets that passed
1959 * the filter, but if filtering is done in the kernel, we
1960 * can't get a count of packets that passed the filter,
1961 * and that would mean the meaning of "ps_recv" wouldn't
1962 * be the same on all Linux systems.
1964 * XXX - it's not the same on all systems in any case;
1965 * ideally, we should have a "get the statistics" call
1966 * that supplies more counts and indicates which of them
1967 * it supplies, so that we supply a count of packets
1968 * handed to the filter only on platforms where that
1969 * information is available.
1971 * We count them here even if we can get the packet count
1972 * from the kernel, as we can only determine at run time
1973 * whether we'll be able to get it from the kernel (if
1974 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1975 * the kernel, but if it is defined, the library might
1976 * have been built with a 2.4 or later kernel, but we
1977 * might be running on a 2.2[.x] kernel without Alexey
1978 * Kuznetzov's turbopacket patches, and thus the kernel
1979 * might not be able to supply those statistics). We
1980 * could, I guess, try, when opening the socket, to get
1981 * the statistics, and if we can not increment the count
1982 * here, but it's not clear that always incrementing
1983 * the count is more expensive than always testing a flag
1986 * We keep the count in "handlep->packets_read", and use that
1987 * for "ps_recv" if we can't get the statistics from the kernel.
1988 * We do that because, if we *can* get the statistics from
1989 * the kernel, we use "handlep->stat.ps_recv" and
1990 * "handlep->stat.ps_drop" as running counts, as reading the
1991 * statistics from the kernel resets the kernel statistics,
1992 * and if we directly increment "handlep->stat.ps_recv" here,
1993 * that means it will count packets *twice* on systems where
1994 * we can get kernel statistics - once here, and once in
1995 * pcap_stats_linux().
1997 handlep
->packets_read
++;
1999 /* Call the user supplied callback function */
2000 callback(userdata
, &pcap_header
, bp
);
2006 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
2008 struct pcap_linux
*handlep
= handle
->priv
;
2011 #ifdef HAVE_PF_PACKET_SOCKETS
2012 if (!handlep
->sock_packet
) {
2013 /* PF_PACKET socket */
2014 if (handlep
->ifindex
== -1) {
2016 * We don't support sending on the "any" device.
2018 strlcpy(handle
->errbuf
,
2019 "Sending packets isn't supported on the \"any\" device",
2024 if (handlep
->cooked
) {
2026 * We don't support sending on the "any" device.
2028 * XXX - how do you send on a bound cooked-mode
2030 * Is a "sendto()" required there?
2032 strlcpy(handle
->errbuf
,
2033 "Sending packets isn't supported in cooked mode",
2040 ret
= send(handle
->fd
, buf
, size
, 0);
2042 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
2043 pcap_strerror(errno
));
2050 * Get the statistics for the given packet capture handle.
2051 * Reports the number of dropped packets iff the kernel supports
2052 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2053 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2054 * patches); otherwise, that information isn't available, and we lie
2055 * and report 0 as the count of dropped packets.
2058 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
2060 struct pcap_linux
*handlep
= handle
->priv
;
2061 #ifdef HAVE_TPACKET_STATS
2062 #ifdef HAVE_TPACKET3
2064 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2065 * stuff at the end of a struct tpacket_stats_v3 will not
2066 * be filled in, and we don't look at it so this is OK even
2067 * for those sockets. In addition, the PF_PACKET socket
2068 * code in the kernel only uses the length parameter to
2069 * compute how much data to copy out and to indicate how
2070 * much data was copied out, so it's OK to base it on the
2071 * size of a struct tpacket_stats.
2073 * XXX - it's probably OK, in fact, to just use a
2074 * struct tpacket_stats for V3 sockets, as we don't
2075 * care about the tp_freeze_q_cnt stat.
2077 struct tpacket_stats_v3 kstats
;
2078 #else /* HAVE_TPACKET3 */
2079 struct tpacket_stats kstats
;
2080 #endif /* HAVE_TPACKET3 */
2081 socklen_t len
= sizeof (struct tpacket_stats
);
2082 #endif /* HAVE_TPACKET_STATS */
2084 long if_dropped
= 0;
2087 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
2089 if (handle
->opt
.promisc
)
2091 if_dropped
= handlep
->proc_dropped
;
2092 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
2093 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
2096 #ifdef HAVE_TPACKET_STATS
2098 * Try to get the packet counts from the kernel.
2100 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
2101 &kstats
, &len
) > -1) {
2103 * On systems where the PACKET_STATISTICS "getsockopt()"
2104 * argument is supported on PF_PACKET sockets:
2106 * "ps_recv" counts only packets that *passed* the
2107 * filter, not packets that didn't pass the filter.
2108 * This includes packets later dropped because we
2109 * ran out of buffer space.
2111 * "ps_drop" counts packets dropped because we ran
2112 * out of buffer space. It doesn't count packets
2113 * dropped by the interface driver. It counts only
2114 * packets that passed the filter.
2116 * See above for ps_ifdrop.
2118 * Both statistics include packets not yet read from
2119 * the kernel by libpcap, and thus not yet seen by
2122 * In "linux/net/packet/af_packet.c", at least in the
2123 * 2.4.9 kernel, "tp_packets" is incremented for every
2124 * packet that passes the packet filter *and* is
2125 * successfully queued on the socket; "tp_drops" is
2126 * incremented for every packet dropped because there's
2127 * not enough free space in the socket buffer.
2129 * When the statistics are returned for a PACKET_STATISTICS
2130 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2131 * so that "tp_packets" counts all packets handed to
2132 * the PF_PACKET socket, including packets dropped because
2133 * there wasn't room on the socket buffer - but not
2134 * including packets that didn't pass the filter.
2136 * In the BSD BPF, the count of received packets is
2137 * incremented for every packet handed to BPF, regardless
2138 * of whether it passed the filter.
2140 * We can't make "pcap_stats()" work the same on both
2141 * platforms, but the best approximation is to return
2142 * "tp_packets" as the count of packets and "tp_drops"
2143 * as the count of drops.
2145 * Keep a running total because each call to
2146 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2147 * resets the counters to zero.
2149 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
2150 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
2151 *stats
= handlep
->stat
;
2157 * If the error was EOPNOTSUPP, fall through, so that
2158 * if you build the library on a system with
2159 * "struct tpacket_stats" and run it on a system
2160 * that doesn't, it works as it does if the library
2161 * is built on a system without "struct tpacket_stats".
2163 if (errno
!= EOPNOTSUPP
) {
2164 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2165 "pcap_stats: %s", pcap_strerror(errno
));
2171 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2172 * is not supported on PF_PACKET sockets:
2174 * "ps_recv" counts only packets that *passed* the filter,
2175 * not packets that didn't pass the filter. It does not
2176 * count packets dropped because we ran out of buffer
2179 * "ps_drop" is not supported.
2181 * "ps_ifdrop" is supported. It will return the number
2182 * of drops the interface reports in /proc/net/dev,
2183 * if that is available.
2185 * "ps_recv" doesn't include packets not yet read from
2186 * the kernel by libpcap.
2188 * We maintain the count of packets processed by libpcap in
2189 * "handlep->packets_read", for reasons described in the comment
2190 * at the end of pcap_read_packet(). We have no idea how many
2191 * packets were dropped by the kernel buffers -- but we know
2192 * how many the interface dropped, so we can return that.
2195 stats
->ps_recv
= handlep
->packets_read
;
2197 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2202 add_linux_if(pcap_if_t
**devlistp
, const char *ifname
, int fd
, char *errbuf
)
2205 char name
[512]; /* XXX - pick a size */
2207 struct ifreq ifrflags
;
2210 * Get the interface name.
2214 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2217 * This could be the separator between a
2218 * name and an alias number, or it could be
2219 * the separator between a name with no
2220 * alias number and the next field.
2222 * If there's a colon after digits, it
2223 * separates the name and the alias number,
2224 * otherwise it separates the name and the
2228 while (isascii(*p
) && isdigit(*p
))
2232 * That was the next field,
2233 * not the alias number.
2244 * Get the flags for this interface.
2246 strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2247 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2248 if (errno
== ENXIO
|| errno
== ENODEV
)
2249 return (0); /* device doesn't actually exist - ignore it */
2250 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2251 "SIOCGIFFLAGS: %.*s: %s",
2252 (int)sizeof(ifrflags
.ifr_name
),
2254 pcap_strerror(errno
));
2259 * Add an entry for this interface, with no addresses.
2261 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2273 * Get from "/sys/class/net" all interfaces listed there; if they're
2274 * already in the list of interfaces we have, that won't add another
2275 * instance, but if they're not, that'll add them.
2277 * We don't bother getting any addresses for them; it appears you can't
2278 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2279 * although some other types of addresses can be fetched with SIOCGIFADDR,
2280 * we don't bother with them for now.
2282 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2283 * the list of interfaces as is, and return 0, so that we can try
2284 * scanning /proc/net/dev.
2286 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2289 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
2291 DIR *sys_class_net_d
;
2294 char subsystem_path
[PATH_MAX
+1];
2298 sys_class_net_d
= opendir("/sys/class/net");
2299 if (sys_class_net_d
== NULL
) {
2301 * Don't fail if it doesn't exist at all.
2303 if (errno
== ENOENT
)
2307 * Fail if we got some other error.
2309 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2310 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
2315 * Create a socket from which to fetch interface information.
2317 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2319 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2320 "socket: %s", pcap_strerror(errno
));
2321 (void)closedir(sys_class_net_d
);
2327 ent
= readdir(sys_class_net_d
);
2330 * Error or EOF; if errno != 0, it's an error.
2336 * Ignore "." and "..".
2338 if (strcmp(ent
->d_name
, ".") == 0 ||
2339 strcmp(ent
->d_name
, "..") == 0)
2343 * Ignore plain files; they do not have subdirectories
2344 * and thus have no attributes.
2346 if (ent
->d_type
== DT_REG
)
2350 * Is there an "ifindex" file under that name?
2351 * (We don't care whether it's a directory or
2352 * a symlink; older kernels have directories
2353 * for devices, newer kernels have symlinks to
2356 snprintf(subsystem_path
, sizeof subsystem_path
,
2357 "/sys/class/net/%s/ifindex", ent
->d_name
);
2358 if (lstat(subsystem_path
, &statb
) != 0) {
2360 * Stat failed. Either there was an error
2361 * other than ENOENT, and we don't know if
2362 * this is an interface, or it's ENOENT,
2363 * and either some part of "/sys/class/net/{if}"
2364 * disappeared, in which case it probably means
2365 * the interface disappeared, or there's no
2366 * "ifindex" file, which means it's not a
2367 * network interface.
2373 * Attempt to add the interface.
2375 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2383 * Well, we didn't fail for any other reason; did we
2384 * fail due to an error reading the directory?
2387 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2388 "Error reading /sys/class/net: %s",
2389 pcap_strerror(errno
));
2395 (void)closedir(sys_class_net_d
);
2400 * Get from "/proc/net/dev" all interfaces listed there; if they're
2401 * already in the list of interfaces we have, that won't add another
2402 * instance, but if they're not, that'll add them.
2404 * See comments from scan_sys_class_net().
2407 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2416 proc_net_f
= fopen("/proc/net/dev", "r");
2417 if (proc_net_f
== NULL
) {
2419 * Don't fail if it doesn't exist at all.
2421 if (errno
== ENOENT
)
2425 * Fail if we got some other error.
2427 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2428 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2433 * Create a socket from which to fetch interface information.
2435 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2437 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2438 "socket: %s", pcap_strerror(errno
));
2439 (void)fclose(proc_net_f
);
2444 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2446 * Skip the first two lines - they're headers.
2454 * Skip leading white space.
2456 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2458 if (*p
== '\0' || *p
== '\n')
2459 continue; /* blank line */
2462 * Attempt to add the interface.
2464 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2472 * Well, we didn't fail for any other reason; did we
2473 * fail due to an error reading the file?
2475 if (ferror(proc_net_f
)) {
2476 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2477 "Error reading /proc/net/dev: %s",
2478 pcap_strerror(errno
));
2484 (void)fclose(proc_net_f
);
2489 * Description string for the "any" device.
2491 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2494 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2499 * Read "/sys/class/net", and add to the list of interfaces all
2500 * interfaces listed there that we don't already have, because,
2501 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2502 * and even getifaddrs() won't return information about
2503 * interfaces with no addresses, so you need to read "/sys/class/net"
2504 * to get the names of the rest of the interfaces.
2506 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2508 return (-1); /* failed */
2511 * No /sys/class/net; try reading /proc/net/dev instead.
2513 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2518 * Add the "any" device.
2520 if (pcap_add_if(alldevsp
, "any", IFF_UP
|IFF_RUNNING
,
2521 any_descr
, errbuf
) < 0)
2528 * Attach the given BPF code to the packet capture device.
2531 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2534 struct pcap_linux
*handlep
;
2535 #ifdef SO_ATTACH_FILTER
2536 struct sock_fprog fcode
;
2537 int can_filter_in_kernel
;
2544 strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2549 handlep
= handle
->priv
;
2551 /* Make our private copy of the filter */
2553 if (install_bpf_program(handle
, filter
) < 0)
2554 /* install_bpf_program() filled in errbuf */
2558 * Run user level packet filter by default. Will be overriden if
2559 * installing a kernel filter succeeds.
2561 handlep
->filter_in_userland
= 1;
2563 /* Install kernel level filter if possible */
2565 #ifdef SO_ATTACH_FILTER
2567 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2569 * fcode.len is an unsigned short for current kernel.
2570 * I have yet to see BPF-Code with that much
2571 * instructions but still it is possible. So for the
2572 * sake of correctness I added this check.
2574 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2576 fcode
.filter
= NULL
;
2577 can_filter_in_kernel
= 0;
2579 #endif /* USHRT_MAX */
2582 * Oh joy, the Linux kernel uses struct sock_fprog instead
2583 * of struct bpf_program and of course the length field is
2584 * of different size. Pointed out by Sebastian
2586 * Oh, and we also need to fix it up so that all "ret"
2587 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2588 * as the operand if we're not capturing in memory-mapped
2589 * mode, and so that, if we're in cooked mode, all memory-
2590 * reference instructions use special magic offsets in
2591 * references to the link-layer header and assume that the
2592 * link-layer payload begins at 0; "fix_program()" will do
2595 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2600 * Fatal error; just quit.
2601 * (The "default" case shouldn't happen; we
2602 * return -1 for that reason.)
2608 * The program performed checks that we can't make
2609 * work in the kernel.
2611 can_filter_in_kernel
= 0;
2616 * We have a filter that'll work in the kernel.
2618 can_filter_in_kernel
= 1;
2624 * NOTE: at this point, we've set both the "len" and "filter"
2625 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2626 * those are the only members of the "sock_fprog" structure,
2627 * so we initialize every member of that structure.
2629 * If there is anything in "fcode" that is not initialized,
2630 * it is either a field added in a later kernel, or it's
2633 * If a new field is added, this code needs to be updated
2634 * to set it correctly.
2636 * If there are no other fields, then:
2638 * if the Linux kernel looks at the padding, it's
2641 * if the Linux kernel doesn't look at the padding,
2642 * then if some tool complains that we're passing
2643 * uninitialized data to the kernel, then the tool
2644 * is buggy and needs to understand that it's just
2647 if (can_filter_in_kernel
) {
2648 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2651 * Installation succeded - using kernel filter,
2652 * so userland filtering not needed.
2654 handlep
->filter_in_userland
= 0;
2656 else if (err
== -1) /* Non-fatal error */
2659 * Print a warning if we weren't able to install
2660 * the filter for a reason other than "this kernel
2661 * isn't configured to support socket filters.
2663 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2665 "Warning: Kernel filter failed: %s\n",
2666 pcap_strerror(errno
));
2672 * If we're not using the kernel filter, get rid of any kernel
2673 * filter that might've been there before, e.g. because the
2674 * previous filter could work in the kernel, or because some other
2675 * code attached a filter to the socket by some means other than
2676 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2677 * filter out packets that would pass the new userland filter.
2679 if (handlep
->filter_in_userland
) {
2680 if (reset_kernel_filter(handle
) == -1) {
2681 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2682 "can't remove kernel filter: %s",
2683 pcap_strerror(errno
));
2684 err
= -2; /* fatal error */
2689 * Free up the copy of the filter that was made by "fix_program()".
2691 if (fcode
.filter
!= NULL
)
2697 #endif /* SO_ATTACH_FILTER */
2703 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2705 return pcap_setfilter_linux_common(handle
, filter
, 0);
2710 * Set direction flag: Which packets do we accept on a forwarding
2711 * single device? IN, OUT or both?
2714 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2716 #ifdef HAVE_PF_PACKET_SOCKETS
2717 struct pcap_linux
*handlep
= handle
->priv
;
2719 if (!handlep
->sock_packet
) {
2720 handle
->direction
= d
;
2725 * We're not using PF_PACKET sockets, so we can't determine
2726 * the direction of the packet.
2728 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2729 "Setting direction is not supported on SOCK_PACKET sockets");
2733 #ifdef HAVE_PF_PACKET_SOCKETS
2735 * Map the PACKET_ value to a LINUX_SLL_ value; we
2736 * want the same numerical value to be used in
2737 * the link-layer header even if the numerical values
2738 * for the PACKET_ #defines change, so that programs
2739 * that look at the packet type field will always be
2740 * able to handle DLT_LINUX_SLL captures.
2743 map_packet_type_to_sll_type(short int sll_pkttype
)
2745 switch (sll_pkttype
) {
2748 return htons(LINUX_SLL_HOST
);
2750 case PACKET_BROADCAST
:
2751 return htons(LINUX_SLL_BROADCAST
);
2753 case PACKET_MULTICAST
:
2754 return htons(LINUX_SLL_MULTICAST
);
2756 case PACKET_OTHERHOST
:
2757 return htons(LINUX_SLL_OTHERHOST
);
2759 case PACKET_OUTGOING
:
2760 return htons(LINUX_SLL_OUTGOING
);
2770 #ifndef IW_MODE_MONITOR
2773 , const char *device
)
2777 #ifdef IW_MODE_MONITOR
2778 char errbuf
[PCAP_ERRBUF_SIZE
];
2782 * See if there's a sysfs wireless directory for it.
2783 * If so, it's a wireless interface.
2785 if (asprintf(&pathstr
, "/sys/class/net/%s/wireless", device
) == -1) {
2787 * Just give up here.
2791 if (stat(pathstr
, &statb
) == 0) {
2797 #ifdef IW_MODE_MONITOR
2799 * OK, maybe it's not wireless, or maybe this kernel doesn't
2800 * support sysfs. Try the wireless extensions.
2802 if (has_wext(sock_fd
, device
, errbuf
) == 1) {
2804 * It supports the wireless extensions, so it's a Wi-Fi
2814 * Linux uses the ARP hardware type to identify the type of an
2815 * interface. pcap uses the DLT_xxx constants for this. This
2816 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2817 * constant, as arguments, and sets "handle->linktype" to the
2818 * appropriate DLT_XXX constant and sets "handle->offset" to
2819 * the appropriate value (to make "handle->offset" plus link-layer
2820 * header length be a multiple of 4, so that the link-layer payload
2821 * will be aligned on a 4-byte boundary when capturing packets).
2822 * (If the offset isn't set here, it'll be 0; add code as appropriate
2823 * for cases where it shouldn't be 0.)
2825 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2826 * in cooked mode; otherwise, we can't use cooked mode, so we have
2827 * to pick some type that works in raw mode, or fail.
2829 * Sets the link type to -1 if unable to map the type.
2831 static void map_arphrd_to_dlt(pcap_t
*handle
, int sock_fd
, int arptype
,
2832 const char *device
, int cooked_ok
)
2834 static const char cdma_rmnet
[] = "cdma_rmnet";
2840 * For various annoying reasons having to do with DHCP
2841 * software, some versions of Android give the mobile-
2842 * phone-network interface an ARPHRD_ value of
2843 * ARPHRD_ETHER, even though the packets supplied by
2844 * that interface have no link-layer header, and begin
2845 * with an IP header, so that the ARPHRD_ value should
2848 * Detect those devices by checking the device name, and
2849 * use DLT_RAW for them.
2851 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2852 handle
->linktype
= DLT_RAW
;
2857 * Is this a real Ethernet device? If so, give it a
2858 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2859 * that an application can let you choose it, in case you're
2860 * capturing DOCSIS traffic that a Cisco Cable Modem
2861 * Termination System is putting out onto an Ethernet (it
2862 * doesn't put an Ethernet header onto the wire, it puts raw
2863 * DOCSIS frames out on the wire inside the low-level
2864 * Ethernet framing).
2866 * XXX - are there any other sorts of "fake Ethernet" that
2867 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2868 * a Cisco CMTS won't put traffic onto it or get traffic
2869 * bridged onto it? ISDN is handled in "activate_new()",
2870 * as we fall back on cooked mode there, and we use
2871 * is_wifi() to check for 802.11 devices; are there any
2874 if (!is_wifi(sock_fd
, device
)) {
2876 * It's not a Wi-Fi device; offer DOCSIS.
2878 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2880 * If that fails, just leave the list empty.
2882 if (handle
->dlt_list
!= NULL
) {
2883 handle
->dlt_list
[0] = DLT_EN10MB
;
2884 handle
->dlt_list
[1] = DLT_DOCSIS
;
2885 handle
->dlt_count
= 2;
2890 case ARPHRD_METRICOM
:
2891 case ARPHRD_LOOPBACK
:
2892 handle
->linktype
= DLT_EN10MB
;
2897 handle
->linktype
= DLT_EN3MB
;
2901 handle
->linktype
= DLT_AX25_KISS
;
2905 handle
->linktype
= DLT_PRONET
;
2909 handle
->linktype
= DLT_CHAOS
;
2912 #define ARPHRD_CAN 280
2915 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2918 #ifndef ARPHRD_IEEE802_TR
2919 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2921 case ARPHRD_IEEE802_TR
:
2922 case ARPHRD_IEEE802
:
2923 handle
->linktype
= DLT_IEEE802
;
2928 handle
->linktype
= DLT_ARCNET_LINUX
;
2931 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2932 #define ARPHRD_FDDI 774
2935 handle
->linktype
= DLT_FDDI
;
2939 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2940 #define ARPHRD_ATM 19
2944 * The Classical IP implementation in ATM for Linux
2945 * supports both what RFC 1483 calls "LLC Encapsulation",
2946 * in which each packet has an LLC header, possibly
2947 * with a SNAP header as well, prepended to it, and
2948 * what RFC 1483 calls "VC Based Multiplexing", in which
2949 * different virtual circuits carry different network
2950 * layer protocols, and no header is prepended to packets.
2952 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2953 * you can't use the ARPHRD_ type to find out whether
2954 * captured packets will have an LLC header, and,
2955 * while there's a socket ioctl to *set* the encapsulation
2956 * type, there's no ioctl to *get* the encapsulation type.
2960 * programs that dissect Linux Classical IP frames
2961 * would have to check for an LLC header and,
2962 * depending on whether they see one or not, dissect
2963 * the frame as LLC-encapsulated or as raw IP (I
2964 * don't know whether there's any traffic other than
2965 * IP that would show up on the socket, or whether
2966 * there's any support for IPv6 in the Linux
2967 * Classical IP code);
2969 * filter expressions would have to compile into
2970 * code that checks for an LLC header and does
2973 * Both of those are a nuisance - and, at least on systems
2974 * that support PF_PACKET sockets, we don't have to put
2975 * up with those nuisances; instead, we can just capture
2976 * in cooked mode. That's what we'll do, if we can.
2977 * Otherwise, we'll just fail.
2980 handle
->linktype
= DLT_LINUX_SLL
;
2982 handle
->linktype
= -1;
2985 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2986 #define ARPHRD_IEEE80211 801
2988 case ARPHRD_IEEE80211
:
2989 handle
->linktype
= DLT_IEEE802_11
;
2992 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2993 #define ARPHRD_IEEE80211_PRISM 802
2995 case ARPHRD_IEEE80211_PRISM
:
2996 handle
->linktype
= DLT_PRISM_HEADER
;
2999 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
3000 #define ARPHRD_IEEE80211_RADIOTAP 803
3002 case ARPHRD_IEEE80211_RADIOTAP
:
3003 handle
->linktype
= DLT_IEEE802_11_RADIO
;
3008 * Some PPP code in the kernel supplies no link-layer
3009 * header whatsoever to PF_PACKET sockets; other PPP
3010 * code supplies PPP link-layer headers ("syncppp.c");
3011 * some PPP code might supply random link-layer
3012 * headers (PPP over ISDN - there's code in Ethereal,
3013 * for example, to cope with PPP-over-ISDN captures
3014 * with which the Ethereal developers have had to cope,
3015 * heuristically trying to determine which of the
3016 * oddball link-layer headers particular packets have).
3018 * As such, we just punt, and run all PPP interfaces
3019 * in cooked mode, if we can; otherwise, we just treat
3020 * it as DLT_RAW, for now - if somebody needs to capture,
3021 * on a 2.0[.x] kernel, on PPP devices that supply a
3022 * link-layer header, they'll have to add code here to
3023 * map to the appropriate DLT_ type (possibly adding a
3024 * new DLT_ type, if necessary).
3027 handle
->linktype
= DLT_LINUX_SLL
;
3030 * XXX - handle ISDN types here? We can't fall
3031 * back on cooked sockets, so we'd have to
3032 * figure out from the device name what type of
3033 * link-layer encapsulation it's using, and map
3034 * that to an appropriate DLT_ value, meaning
3035 * we'd map "isdnN" devices to DLT_RAW (they
3036 * supply raw IP packets with no link-layer
3037 * header) and "isdY" devices to a new DLT_I4L_IP
3038 * type that has only an Ethernet packet type as
3039 * a link-layer header.
3041 * But sometimes we seem to get random crap
3042 * in the link-layer header when capturing on
3045 handle
->linktype
= DLT_RAW
;
3049 #ifndef ARPHRD_CISCO
3050 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3053 handle
->linktype
= DLT_C_HDLC
;
3056 /* Not sure if this is correct for all tunnels, but it
3060 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3068 #ifndef ARPHRD_RAWHDLC
3069 #define ARPHRD_RAWHDLC 518
3071 case ARPHRD_RAWHDLC
:
3073 #define ARPHRD_DLCI 15
3077 * XXX - should some of those be mapped to DLT_LINUX_SLL
3078 * instead? Should we just map all of them to DLT_LINUX_SLL?
3080 handle
->linktype
= DLT_RAW
;
3084 #define ARPHRD_FRAD 770
3087 handle
->linktype
= DLT_FRELAY
;
3090 case ARPHRD_LOCALTLK
:
3091 handle
->linktype
= DLT_LTALK
;
3096 * RFC 4338 defines an encapsulation for IP and ARP
3097 * packets that's compatible with the RFC 2625
3098 * encapsulation, but that uses a different ARP
3099 * hardware type and hardware addresses. That
3100 * ARP hardware type is 18; Linux doesn't define
3101 * any ARPHRD_ value as 18, but if it ever officially
3102 * supports RFC 4338-style IP-over-FC, it should define
3105 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3106 * that this will encourage its use in the future,
3107 * should Linux ever officially support RFC 4338-style
3110 handle
->linktype
= DLT_IP_OVER_FC
;
3114 #define ARPHRD_FCPP 784
3118 #define ARPHRD_FCAL 785
3122 #define ARPHRD_FCPL 786
3125 #ifndef ARPHRD_FCFABRIC
3126 #define ARPHRD_FCFABRIC 787
3128 case ARPHRD_FCFABRIC
:
3130 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3133 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3135 * and one was assigned.
3137 * In a later private discussion (spun off from a message
3138 * on the ethereal-users list) on how to get that DLT_
3139 * value in libpcap on Linux, I ended up deciding that
3140 * the best thing to do would be to have him tweak the
3141 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3142 * type, and map all those types to DLT_IP_OVER_FC:
3144 * I've checked into the libpcap and tcpdump CVS tree
3145 * support for DLT_IP_OVER_FC. In order to use that,
3146 * you'd have to modify your modified driver to return
3147 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3148 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3149 * example (the exact value doesn't matter, it can be
3150 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3153 * 11 years later, Christian Svensson wanted to map
3154 * various ARPHRD_ values to DLT_FC_2 and
3155 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3158 * https://github.com/mcr/libpcap/pull/29
3160 * There doesn't seem to be any network drivers that uses
3161 * any of the ARPHRD_FC* values for IP-over-FC, and
3162 * it's not exactly clear what the "Dummy types for non
3163 * ARP hardware" are supposed to mean (link-layer
3164 * header type? Physical network type?), so it's
3165 * not exactly clear why the ARPHRD_FC* types exist
3166 * in the first place.
3168 * For now, we map them to DLT_FC_2, and provide an
3169 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3170 * DLT_IP_OVER_FC just in case there's some old
3171 * driver out there that uses one of those types for
3172 * IP-over-FC on which somebody wants to capture
3175 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
3177 * If that fails, just leave the list empty.
3179 if (handle
->dlt_list
!= NULL
) {
3180 handle
->dlt_list
[0] = DLT_FC_2
;
3181 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
3182 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
3183 handle
->dlt_count
= 3;
3185 handle
->linktype
= DLT_FC_2
;
3189 #define ARPHRD_IRDA 783
3192 /* Don't expect IP packet out of this interfaces... */
3193 handle
->linktype
= DLT_LINUX_IRDA
;
3194 /* We need to save packet direction for IrDA decoding,
3195 * so let's use "Linux-cooked" mode. Jean II
3197 * XXX - this is handled in activate_new(). */
3198 //handlep->cooked = 1;
3201 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3202 * is needed, please report it to <daniele@orlandi.com> */
3204 #define ARPHRD_LAPD 8445
3207 /* Don't expect IP packet out of this interfaces... */
3208 handle
->linktype
= DLT_LINUX_LAPD
;
3212 #define ARPHRD_NONE 0xFFFE
3216 * No link-layer header; packets are just IP
3217 * packets, so use DLT_RAW.
3219 handle
->linktype
= DLT_RAW
;
3222 #ifndef ARPHRD_IEEE802154
3223 #define ARPHRD_IEEE802154 804
3225 case ARPHRD_IEEE802154
:
3226 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
3229 #ifndef ARPHRD_NETLINK
3230 #define ARPHRD_NETLINK 824
3232 case ARPHRD_NETLINK
:
3233 handle
->linktype
= DLT_NETLINK
;
3235 * We need to use cooked mode, so that in sll_protocol we
3236 * pick up the netlink protocol type such as NETLINK_ROUTE,
3237 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3239 * XXX - this is handled in activate_new().
3241 //handlep->cooked = 1;
3245 handle
->linktype
= -1;
3250 /* ===== Functions to interface to the newer kernels ================== */
3253 * Try to open a packet socket using the new kernel PF_PACKET interface.
3254 * Returns 1 on success, 0 on an error that means the new interface isn't
3255 * present (so the old SOCK_PACKET interface should be tried), and a
3256 * PCAP_ERROR_ value on an error that means that the old mechanism won't
3257 * work either (so it shouldn't be tried).
3260 activate_new(pcap_t
*handle
)
3262 #ifdef HAVE_PF_PACKET_SOCKETS
3263 struct pcap_linux
*handlep
= handle
->priv
;
3264 const char *device
= handle
->opt
.source
;
3265 int is_any_device
= (strcmp(device
, "any") == 0);
3266 int sock_fd
= -1, arptype
;
3267 #ifdef HAVE_PACKET_AUXDATA
3271 struct packet_mreq mr
;
3272 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3274 socklen_t len
= sizeof(bpf_extensions
);
3278 * Open a socket with protocol family packet. If the
3279 * "any" device was specified, we open a SOCK_DGRAM
3280 * socket for the cooked interface, otherwise we first
3281 * try a SOCK_RAW socket for the raw interface.
3283 sock_fd
= is_any_device
?
3284 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
3285 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
3287 if (sock_fd
== -1) {
3288 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
3290 * We don't support PF_PACKET/SOCK_whatever
3291 * sockets; try the old mechanism.
3296 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
3297 pcap_strerror(errno
) );
3298 if (errno
== EPERM
|| errno
== EACCES
) {
3300 * You don't have permission to open the
3303 return PCAP_ERROR_PERM_DENIED
;
3312 /* It seems the kernel supports the new interface. */
3313 handlep
->sock_packet
= 0;
3316 * Get the interface index of the loopback device.
3317 * If the attempt fails, don't fail, just set the
3318 * "handlep->lo_ifindex" to -1.
3320 * XXX - can there be more than one device that loops
3321 * packets back, i.e. devices other than "lo"? If so,
3322 * we'd need to find them all, and have an array of
3323 * indices for them, and check all of them in
3324 * "pcap_read_packet()".
3326 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3329 * Default value for offset to align link-layer payload
3330 * on a 4-byte boundary.
3335 * What kind of frames do we have to deal with? Fall back
3336 * to cooked mode if we have an unknown interface type
3337 * or a type we know doesn't work well in raw mode.
3339 if (!is_any_device
) {
3340 /* Assume for now we don't need cooked mode. */
3341 handlep
->cooked
= 0;
3343 if (handle
->opt
.rfmon
) {
3345 * We were asked to turn on monitor mode.
3346 * Do so before we get the link-layer type,
3347 * because entering monitor mode could change
3348 * the link-layer type.
3350 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3358 * Nothing worked for turning monitor mode
3362 return PCAP_ERROR_RFMON_NOTSUP
;
3366 * Either monitor mode has been turned on for
3367 * the device, or we've been given a different
3368 * device to open for monitor mode. If we've
3369 * been given a different device, use it.
3371 if (handlep
->mondevice
!= NULL
)
3372 device
= handlep
->mondevice
;
3374 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3379 map_arphrd_to_dlt(handle
, sock_fd
, arptype
, device
, 1);
3380 if (handle
->linktype
== -1 ||
3381 handle
->linktype
== DLT_LINUX_SLL
||
3382 handle
->linktype
== DLT_LINUX_IRDA
||
3383 handle
->linktype
== DLT_LINUX_LAPD
||
3384 handle
->linktype
== DLT_NETLINK
||
3385 (handle
->linktype
== DLT_EN10MB
&&
3386 (strncmp("isdn", device
, 4) == 0 ||
3387 strncmp("isdY", device
, 4) == 0))) {
3389 * Unknown interface type (-1), or a
3390 * device we explicitly chose to run
3391 * in cooked mode (e.g., PPP devices),
3392 * or an ISDN device (whose link-layer
3393 * type we can only determine by using
3394 * APIs that may be different on different
3395 * kernels) - reopen in cooked mode.
3397 if (close(sock_fd
) == -1) {
3398 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3399 "close: %s", pcap_strerror(errno
));
3402 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3404 if (sock_fd
== -1) {
3405 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3406 "socket: %s", pcap_strerror(errno
));
3407 if (errno
== EPERM
|| errno
== EACCES
) {
3409 * You don't have permission to
3412 return PCAP_ERROR_PERM_DENIED
;
3420 handlep
->cooked
= 1;
3423 * Get rid of any link-layer type list
3424 * we allocated - this only supports cooked
3427 if (handle
->dlt_list
!= NULL
) {
3428 free(handle
->dlt_list
);
3429 handle
->dlt_list
= NULL
;
3430 handle
->dlt_count
= 0;
3433 if (handle
->linktype
== -1) {
3435 * Warn that we're falling back on
3436 * cooked mode; we may want to
3437 * update "map_arphrd_to_dlt()"
3438 * to handle the new type.
3440 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3442 "supported by libpcap - "
3443 "falling back to cooked "
3449 * IrDA capture is not a real "cooked" capture,
3450 * it's IrLAP frames, not IP packets. The
3451 * same applies to LAPD capture.
3453 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3454 handle
->linktype
!= DLT_LINUX_LAPD
&&
3455 handle
->linktype
!= DLT_NETLINK
)
3456 handle
->linktype
= DLT_LINUX_SLL
;
3459 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3461 if (handlep
->ifindex
== -1) {
3466 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3467 handle
->errbuf
)) != 1) {
3472 return 0; /* try old mechanism */
3478 if (handle
->opt
.rfmon
) {
3480 * It doesn't support monitor mode.
3483 return PCAP_ERROR_RFMON_NOTSUP
;
3487 * It uses cooked mode.
3489 handlep
->cooked
= 1;
3490 handle
->linktype
= DLT_LINUX_SLL
;
3493 * We're not bound to a device.
3494 * For now, we're using this as an indication
3495 * that we can't transmit; stop doing that only
3496 * if we figure out how to transmit in cooked
3499 handlep
->ifindex
= -1;
3503 * Select promiscuous mode on if "promisc" is set.
3505 * Do not turn allmulti mode on if we don't select
3506 * promiscuous mode - on some devices (e.g., Orinoco
3507 * wireless interfaces), allmulti mode isn't supported
3508 * and the driver implements it by turning promiscuous
3509 * mode on, and that screws up the operation of the
3510 * card as a normal networking interface, and on no
3511 * other platform I know of does starting a non-
3512 * promiscuous capture affect which multicast packets
3513 * are received by the interface.
3517 * Hmm, how can we set promiscuous mode on all interfaces?
3518 * I am not sure if that is possible at all. For now, we
3519 * silently ignore attempts to turn promiscuous mode on
3520 * for the "any" device (so you don't have to explicitly
3521 * disable it in programs such as tcpdump).
3524 if (!is_any_device
&& handle
->opt
.promisc
) {
3525 memset(&mr
, 0, sizeof(mr
));
3526 mr
.mr_ifindex
= handlep
->ifindex
;
3527 mr
.mr_type
= PACKET_MR_PROMISC
;
3528 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3529 &mr
, sizeof(mr
)) == -1) {
3530 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3531 "setsockopt: %s", pcap_strerror(errno
));
3537 /* Enable auxillary data if supported and reserve room for
3538 * reconstructing VLAN headers. */
3539 #ifdef HAVE_PACKET_AUXDATA
3541 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3542 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3543 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3544 "setsockopt: %s", pcap_strerror(errno
));
3548 handle
->offset
+= VLAN_TAG_LEN
;
3549 #endif /* HAVE_PACKET_AUXDATA */
3552 * This is a 2.2[.x] or later kernel (we know that
3553 * because we're not using a SOCK_PACKET socket -
3554 * PF_PACKET is supported only in 2.2 and later
3557 * We can safely pass "recvfrom()" a byte count
3558 * based on the snapshot length.
3560 * If we're in cooked mode, make the snapshot length
3561 * large enough to hold a "cooked mode" header plus
3562 * 1 byte of packet data (so we don't pass a byte
3563 * count of 0 to "recvfrom()").
3565 if (handlep
->cooked
) {
3566 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3567 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3569 handle
->bufsize
= handle
->snapshot
;
3572 * Set the offset at which to insert VLAN tags.
3574 switch (handle
->linktype
) {
3577 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3581 handlep
->vlan_offset
= 14;
3585 handlep
->vlan_offset
= -1; /* unknown */
3589 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3590 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3591 int nsec_tstamps
= 1;
3593 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3594 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3599 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3602 * We've succeeded. Save the socket FD in the pcap structure.
3604 handle
->fd
= sock_fd
;
3606 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3608 * Can we generate special code for VLAN checks?
3609 * (XXX - what if we need the special code but it's not supported
3610 * by the OS? Is that possible?)
3612 if (getsockopt(sock_fd
, SOL_SOCKET
, SO_BPF_EXTENSIONS
,
3613 &bpf_extensions
, &len
) == 0) {
3614 if (bpf_extensions
>= SKF_AD_VLAN_TAG_PRESENT
) {
3616 * Yes, we can. Request that we do so.
3618 handle
->bpf_codegen_flags
|= BPF_SPECIAL_VLAN_HANDLING
;
3621 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
3624 #else /* HAVE_PF_PACKET_SOCKETS */
3626 "New packet capturing interface not supported by build "
3627 "environment", PCAP_ERRBUF_SIZE
);
3629 #endif /* HAVE_PF_PACKET_SOCKETS */
3632 #ifdef HAVE_PACKET_RING
3634 * Attempt to activate with memory-mapped access.
3636 * On success, returns 1, and sets *status to 0 if there are no warnings
3637 * or to a PCAP_WARNING_ code if there is a warning.
3639 * On failure due to lack of support for memory-mapped capture, returns
3642 * On error, returns -1, and sets *status to the appropriate error code;
3643 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3646 activate_mmap(pcap_t
*handle
, int *status
)
3648 struct pcap_linux
*handlep
= handle
->priv
;
3652 * Attempt to allocate a buffer to hold the contents of one
3653 * packet, for use by the oneshot callback.
3655 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3656 if (handlep
->oneshot_buffer
== NULL
) {
3657 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3658 "can't allocate oneshot buffer: %s",
3659 pcap_strerror(errno
));
3660 *status
= PCAP_ERROR
;
3664 if (handle
->opt
.buffer_size
== 0) {
3665 /* by default request 2M for the ring buffer */
3666 handle
->opt
.buffer_size
= 2*1024*1024;
3668 ret
= prepare_tpacket_socket(handle
);
3670 free(handlep
->oneshot_buffer
);
3671 *status
= PCAP_ERROR
;
3674 ret
= create_ring(handle
, status
);
3677 * We don't support memory-mapped capture; our caller
3678 * will fall back on reading from the socket.
3680 free(handlep
->oneshot_buffer
);
3685 * Error attempting to enable memory-mapped capture;
3686 * fail. create_ring() has set *status.
3688 free(handlep
->oneshot_buffer
);
3693 * Success. *status has been set either to 0 if there are no
3694 * warnings or to a PCAP_WARNING_ value if there is a warning.
3696 * Override some defaults and inherit the other fields from
3698 * handle->offset is used to get the current position into the rx ring.
3699 * handle->cc is used to store the ring size.
3702 switch (handlep
->tp_version
) {
3704 handle
->read_op
= pcap_read_linux_mmap_v1
;
3707 handle
->read_op
= pcap_read_linux_mmap_v1_64
;
3709 #ifdef HAVE_TPACKET2
3711 handle
->read_op
= pcap_read_linux_mmap_v2
;
3714 #ifdef HAVE_TPACKET3
3716 handle
->read_op
= pcap_read_linux_mmap_v3
;
3720 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3721 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3722 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3723 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3724 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3725 handle
->selectable_fd
= handle
->fd
;
3728 #else /* HAVE_PACKET_RING */
3730 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3734 #endif /* HAVE_PACKET_RING */
3736 #ifdef HAVE_PACKET_RING
3738 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3740 * Attempt to set the socket to the specified version of the memory-mapped
3743 * Return 0 if we succeed; return 1 if we fail because that version isn't
3744 * supported; return -1 on any other error, and set handle->errbuf.
3747 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
3749 struct pcap_linux
*handlep
= handle
->priv
;
3751 socklen_t len
= sizeof(val
);
3754 * Probe whether kernel supports the specified TPACKET version;
3755 * this also gets the length of the header for that version.
3757 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3758 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
)
3761 /* Failed to even find out; this is a fatal error. */
3762 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3763 "can't get %s header len on packet socket: %s",
3765 pcap_strerror(errno
));
3768 handlep
->tp_hdrlen
= val
;
3771 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3773 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3774 "can't activate %s on packet socket: %s",
3776 pcap_strerror(errno
));
3779 handlep
->tp_version
= version
;
3781 /* Reserve space for VLAN tag reconstruction */
3783 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3785 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3786 "can't set up reserve on packet socket: %s",
3787 pcap_strerror(errno
));
3793 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3796 * If the instruction set for which we're compiling has both 32-bit
3797 * and 64-bit versions, and Linux support for the 64-bit version
3798 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
3799 * you get from uname() for the 64-bit version. Otherwise, leave
3800 * it undefined. (This includes ARM, which has a 64-bit version,
3801 * but Linux support for it appeared well after TPACKET_V2 support
3802 * did, so there should never be a case where 32-bit ARM code is
3803 * running o a 64-bit kernel that only supports TPACKET_V1.)
3805 * If we've omitted your favorite such architecture, please contribute
3806 * a patch. (No patch is needed for architectures that are 32-bit-only
3807 * or for which Linux has no support for 32-bit userland - or for which,
3808 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
3811 #if defined(__i386__)
3812 #define ISA_64_BIT "x86_64"
3813 #elif defined(__ppc__)
3814 #define ISA_64_BIT "ppc64"
3815 #elif defined(__sparc__)
3816 #define ISA_64_BIT "sparc64"
3817 #elif defined(__s390__)
3818 #define ISA_64_BIT "s390x"
3819 #elif defined(__mips__)
3820 #define ISA_64_BIT "mips64"
3821 #elif defined(__hppa__)
3822 #define ISA_64_BIT "parisc64"
3826 * Attempt to set the socket to version 3 of the memory-mapped header and,
3827 * if that fails because version 3 isn't supported, attempt to fall
3828 * back to version 2. If version 2 isn't supported, just leave it at
3831 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
3832 * supported; return -1 on any other error, and set handle->errbuf.
3835 prepare_tpacket_socket(pcap_t
*handle
)
3837 struct pcap_linux
*handlep
= handle
->priv
;
3838 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3842 #ifdef HAVE_TPACKET3
3844 * Try setting the version to TPACKET_V3.
3846 * The only mode in which buffering is done on PF_PACKET
3847 * sockets, so that packets might not be delivered
3848 * immediately, is TPACKET_V3 mode.
3850 * The buffering cannot be disabled in that mode, so
3851 * if the user has requested immediate mode, we don't
3854 if (!handle
->opt
.immediate
) {
3855 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
3864 * We failed for some reason other than "the
3865 * kernel doesn't support TPACKET_V3".
3870 #endif /* HAVE_TPACKET3 */
3872 #ifdef HAVE_TPACKET2
3874 * Try setting the version to TPACKET_V2.
3876 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
3885 * We failed for some reason other than "the
3886 * kernel doesn't support TPACKET_V2".
3890 #endif /* HAVE_TPACKET2 */
3893 * OK, we're using TPACKET_V1, as that's all the kernel supports.
3895 handlep
->tp_version
= TPACKET_V1
;
3896 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
3900 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
3901 * each other due to platform-dependent data type size differences.
3903 * If we have a 32-bit userland and a 64-bit kernel, use an
3904 * internally-defined TPACKET_V1_64, with which we use a 64-bit
3905 * version of the data structures.
3907 if (sizeof(long) == 4) {
3909 * This is 32-bit code.
3911 struct utsname utsname
;
3913 if (uname(&utsname
) == -1) {
3917 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3918 "uname failed: %s", pcap_strerror(errno
));
3921 if (strcmp(utsname
.machine
, ISA_64_BIT
) == 0) {
3923 * uname() tells us the machine is 64-bit,
3924 * so we presumably have a 64-bit kernel.
3926 * XXX - this presumes that uname() won't lie
3927 * in 32-bit code and claim that the machine
3928 * has the 32-bit version of the ISA.
3930 handlep
->tp_version
= TPACKET_V1_64
;
3931 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr_64
);
3940 * Attempt to set up memory-mapped access.
3942 * On success, returns 1, and sets *status to 0 if there are no warnings
3943 * or to a PCAP_WARNING_ code if there is a warning.
3945 * On failure due to lack of support for memory-mapped capture, returns
3948 * On error, returns -1, and sets *status to the appropriate error code;
3949 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3952 create_ring(pcap_t
*handle
, int *status
)
3954 struct pcap_linux
*handlep
= handle
->priv
;
3955 unsigned i
, j
, frames_per_block
;
3956 #ifdef HAVE_TPACKET3
3958 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
3959 * stuff at the end of a struct tpacket_req3 will be
3960 * ignored, so this is OK even for those sockets.
3962 struct tpacket_req3 req
;
3964 struct tpacket_req req
;
3967 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3968 unsigned int frame_size
;
3971 * Start out assuming no warnings or errors.
3975 switch (handlep
->tp_version
) {
3979 #ifdef HAVE_TPACKET2
3982 /* Note that with large snapshot length (say 64K, which is
3983 * the default for recent versions of tcpdump, the value that
3984 * "-s 0" has given for a long time with tcpdump, and the
3985 * default in Wireshark/TShark/dumpcap), if we use the snapshot
3986 * length to calculate the frame length, only a few frames
3987 * will be available in the ring even with pretty
3988 * large ring size (and a lot of memory will be unused).
3990 * Ideally, we should choose a frame length based on the
3991 * minimum of the specified snapshot length and the maximum
3992 * packet size. That's not as easy as it sounds; consider,
3993 * for example, an 802.11 interface in monitor mode, where
3994 * the frame would include a radiotap header, where the
3995 * maximum radiotap header length is device-dependent.
3997 * So, for now, we just do this for Ethernet devices, where
3998 * there's no metadata header, and the link-layer header is
3999 * fixed length. We can get the maximum packet size by
4000 * adding 18, the Ethernet header length plus the CRC length
4001 * (just in case we happen to get the CRC in the packet), to
4002 * the MTU of the interface; we fetch the MTU in the hopes
4003 * that it reflects support for jumbo frames. (Even if the
4004 * interface is just being used for passive snooping, the
4005 * driver might set the size of buffers in the receive ring
4006 * based on the MTU, so that the MTU limits the maximum size
4007 * of packets that we can receive.)
4009 * We don't do that if segmentation/fragmentation or receive
4010 * offload are enabled, so we don't get rudely surprised by
4011 * "packets" bigger than the MTU. */
4012 frame_size
= handle
->snapshot
;
4013 if (handle
->linktype
== DLT_EN10MB
) {
4017 offload
= iface_get_offload(handle
);
4018 if (offload
== -1) {
4019 *status
= PCAP_ERROR
;
4023 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
4026 *status
= PCAP_ERROR
;
4029 if (frame_size
> mtu
+ 18)
4030 frame_size
= mtu
+ 18;
4034 /* NOTE: calculus matching those in tpacket_rcv()
4035 * in linux-2.6/net/packet/af_packet.c
4037 len
= sizeof(sk_type
);
4038 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
4040 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4041 "getsockopt: %s", pcap_strerror(errno
));
4042 *status
= PCAP_ERROR
;
4045 #ifdef PACKET_RESERVE
4046 len
= sizeof(tp_reserve
);
4047 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
4048 &tp_reserve
, &len
) < 0) {
4049 if (errno
!= ENOPROTOOPT
) {
4051 * ENOPROTOOPT means "kernel doesn't support
4052 * PACKET_RESERVE", in which case we fall back
4055 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4056 "getsockopt: %s", pcap_strerror(errno
));
4057 *status
= PCAP_ERROR
;
4060 tp_reserve
= 0; /* older kernel, reserve not supported */
4063 tp_reserve
= 0; /* older kernel, reserve not supported */
4065 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
4066 /* XXX: in the kernel maclen is calculated from
4067 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4068 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4069 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4070 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4071 * but I see no way to get those sizes in userspace,
4072 * like for instance with an ifreq ioctl();
4073 * the best thing I've found so far is MAX_HEADER in
4074 * the kernel part of linux-2.6/include/linux/netdevice.h
4075 * which goes up to 128+48=176; since pcap-linux.c
4076 * defines a MAX_LINKHEADER_SIZE of 256 which is
4077 * greater than that, let's use it.. maybe is it even
4078 * large enough to directly replace macoff..
4080 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
4081 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
4082 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4083 * of netoff, which contradicts
4084 * linux-2.6/Documentation/networking/packet_mmap.txt
4086 * "- Gap, chosen so that packet data (Start+tp_net)
4087 * aligns to TPACKET_ALIGNMENT=16"
4089 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4090 * "CPUs often take a performance hit
4091 * when accessing unaligned memory locations"
4093 macoff
= netoff
- maclen
;
4094 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
4095 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
4098 #ifdef HAVE_TPACKET3
4100 /* The "frames" for this are actually buffers that
4101 * contain multiple variable-sized frames.
4103 * We pick a "frame" size of 128K to leave enough
4104 * room for at least one reasonably-sized packet
4105 * in the "frame". */
4106 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
4107 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
4111 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4112 "Internal error: unknown TPACKET_ value %u",
4113 handlep
->tp_version
);
4114 *status
= PCAP_ERROR
;
4118 /* compute the minumum block size that will handle this frame.
4119 * The block has to be page size aligned.
4120 * The max block size allowed by the kernel is arch-dependent and
4121 * it's not explicitly checked here. */
4122 req
.tp_block_size
= getpagesize();
4123 while (req
.tp_block_size
< req
.tp_frame_size
)
4124 req
.tp_block_size
<<= 1;
4126 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
4129 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4130 * so we check for PACKET_TIMESTAMP. We check for
4131 * linux/net_tstamp.h just in case a system somehow has
4132 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4135 * SIOCSHWTSTAMP was introduced in the patch that introduced
4136 * linux/net_tstamp.h, so we don't bother checking whether
4137 * SIOCSHWTSTAMP is defined (if your Linux system has
4138 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4139 * Linux system is badly broken).
4141 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4143 * If we were told to do so, ask the kernel and the driver
4144 * to use hardware timestamps.
4146 * Hardware timestamps are only supported with mmapped
4149 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
4150 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
4151 struct hwtstamp_config hwconfig
;
4156 * Ask for hardware time stamps on all packets,
4157 * including transmitted packets.
4159 memset(&hwconfig
, 0, sizeof(hwconfig
));
4160 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
4161 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
4163 memset(&ifr
, 0, sizeof(ifr
));
4164 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
4165 ifr
.ifr_data
= (void *)&hwconfig
;
4167 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
4172 * Treat this as an error, as the
4173 * user should try to run this
4174 * with the appropriate privileges -
4175 * and, if they can't, shouldn't
4176 * try requesting hardware time stamps.
4178 *status
= PCAP_ERROR_PERM_DENIED
;
4183 * Treat this as a warning, as the
4184 * only way to fix the warning is to
4185 * get an adapter that supports hardware
4186 * time stamps. We'll just fall back
4187 * on the standard host time stamps.
4189 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
4193 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4194 "SIOCSHWTSTAMP failed: %s",
4195 pcap_strerror(errno
));
4196 *status
= PCAP_ERROR
;
4201 * Well, that worked. Now specify the type of
4202 * hardware time stamp we want for this
4205 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
4207 * Hardware timestamp, synchronized
4208 * with the system clock.
4210 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
4213 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4214 * timestamp, not synchronized with the
4217 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
4219 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
4220 (void *)×ource
, sizeof(timesource
))) {
4221 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4222 "can't set PACKET_TIMESTAMP: %s",
4223 pcap_strerror(errno
));
4224 *status
= PCAP_ERROR
;
4229 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4231 /* ask the kernel to create the ring */
4233 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
4235 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4236 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
4238 #ifdef HAVE_TPACKET3
4239 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4240 req
.tp_retire_blk_tov
= (handlep
->timeout
>=0)?handlep
->timeout
:0;
4241 /* private data not used */
4242 req
.tp_sizeof_priv
= 0;
4243 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4244 req
.tp_feature_req_word
= 0;
4247 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4248 (void *) &req
, sizeof(req
))) {
4249 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
4251 * Memory failure; try to reduce the requested ring
4254 * We used to reduce this by half -- do 5% instead.
4255 * That may result in more iterations and a longer
4256 * startup, but the user will be much happier with
4257 * the resulting buffer size.
4259 if (req
.tp_frame_nr
< 20)
4260 req
.tp_frame_nr
-= 1;
4262 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
4265 if (errno
== ENOPROTOOPT
) {
4267 * We don't have ring buffer support in this kernel.
4271 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4272 "can't create rx ring on packet socket: %s",
4273 pcap_strerror(errno
));
4274 *status
= PCAP_ERROR
;
4278 /* memory map the rx ring */
4279 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
4280 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
4281 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
4282 if (handlep
->mmapbuf
== MAP_FAILED
) {
4283 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4284 "can't mmap rx ring: %s", pcap_strerror(errno
));
4286 /* clear the allocated ring on error*/
4287 destroy_ring(handle
);
4288 *status
= PCAP_ERROR
;
4292 /* allocate a ring for each frame header pointer*/
4293 handle
->cc
= req
.tp_frame_nr
;
4294 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
4295 if (!handle
->buffer
) {
4296 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4297 "can't allocate ring of frame headers: %s",
4298 pcap_strerror(errno
));
4300 destroy_ring(handle
);
4301 *status
= PCAP_ERROR
;
4305 /* fill the header ring with proper frame ptr*/
4307 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
4308 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
4309 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
4310 RING_GET_CURRENT_FRAME(handle
) = base
;
4311 base
+= req
.tp_frame_size
;
4315 handle
->bufsize
= req
.tp_frame_size
;
4320 /* free all ring related resources*/
4322 destroy_ring(pcap_t
*handle
)
4324 struct pcap_linux
*handlep
= handle
->priv
;
4326 /* tell the kernel to destroy the ring*/
4327 struct tpacket_req req
;
4328 memset(&req
, 0, sizeof(req
));
4329 /* do not test for setsockopt failure, as we can't recover from any error */
4330 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
4331 (void *) &req
, sizeof(req
));
4333 /* if ring is mapped, unmap it*/
4334 if (handlep
->mmapbuf
) {
4335 /* do not test for mmap failure, as we can't recover from any error */
4336 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
4337 handlep
->mmapbuf
= NULL
;
4342 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4343 * for Linux mmapped capture.
4345 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4346 * data handed to the callback to be valid after the callback returns,
4347 * but pcap_read_linux_mmap() has to release that packet as soon as
4348 * the callback returns (otherwise, the kernel thinks there's still
4349 * at least one unprocessed packet available in the ring, so a select()
4350 * will immediately return indicating that there's data to process), so,
4351 * in the callback, we have to make a copy of the packet.
4353 * Yes, this means that, if the capture is using the ring buffer, using
4354 * pcap_next() or pcap_next_ex() requires more copies than using
4355 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4356 * pcap_next() or pcap_next_ex().
4359 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
4360 const u_char
*bytes
)
4362 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
4363 pcap_t
*handle
= sp
->pd
;
4364 struct pcap_linux
*handlep
= handle
->priv
;
4367 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
4368 *sp
->pkt
= handlep
->oneshot_buffer
;
4372 pcap_cleanup_linux_mmap( pcap_t
*handle
)
4374 struct pcap_linux
*handlep
= handle
->priv
;
4376 destroy_ring(handle
);
4377 if (handlep
->oneshot_buffer
!= NULL
) {
4378 free(handlep
->oneshot_buffer
);
4379 handlep
->oneshot_buffer
= NULL
;
4381 pcap_cleanup_linux(handle
);
4386 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
4388 struct pcap_linux
*handlep
= p
->priv
;
4390 /* use negative value of timeout to indicate non blocking ops */
4391 return (handlep
->timeout
<0);
4395 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
4397 struct pcap_linux
*handlep
= p
->priv
;
4400 * Set the file descriptor to non-blocking mode, as we use
4401 * it for sending packets.
4403 if (pcap_setnonblock_fd(p
, nonblock
, errbuf
) == -1)
4407 * Map each value to their corresponding negation to
4408 * preserve the timeout value provided with pcap_set_timeout.
4411 if (handlep
->timeout
>= 0) {
4413 * Indicate that we're switching to
4414 * non-blocking mode.
4416 handlep
->timeout
= ~handlep
->timeout
;
4419 if (handlep
->timeout
< 0) {
4420 handlep
->timeout
= ~handlep
->timeout
;
4423 /* Update the timeout to use in poll(). */
4424 set_poll_timeout(handlep
);
4429 * Get the status field of the ring buffer frame at a specified offset.
4432 pcap_get_ring_frame_status(pcap_t
*handle
, int offset
)
4434 struct pcap_linux
*handlep
= handle
->priv
;
4437 h
.raw
= RING_GET_FRAME_AT(handle
, offset
);
4438 switch (handlep
->tp_version
) {
4440 return (h
.h1
->tp_status
);
4443 return (h
.h1_64
->tp_status
);
4445 #ifdef HAVE_TPACKET2
4447 return (h
.h2
->tp_status
);
4450 #ifdef HAVE_TPACKET3
4452 return (h
.h3
->hdr
.bh1
.block_status
);
4456 /* This should not happen. */
4465 * Block waiting for frames to be available.
4467 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4469 struct pcap_linux
*handlep
= handle
->priv
;
4471 struct pollfd pollinfo
;
4474 pollinfo
.fd
= handle
->fd
;
4475 pollinfo
.events
= POLLIN
;
4479 * Yes, we do this even in non-blocking mode, as it's
4480 * the only way to get error indications from a
4483 * The timeout is 0 in non-blocking mode, so poll()
4484 * returns immediately.
4486 ret
= poll(&pollinfo
, 1, handlep
->poll_timeout
);
4487 if (ret
< 0 && errno
!= EINTR
) {
4488 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4489 "can't poll on packet socket: %s",
4490 pcap_strerror(errno
));
4492 } else if (ret
> 0 &&
4493 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4495 * There's some indication other than
4496 * "you can read on this descriptor" on
4499 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
4500 snprintf(handle
->errbuf
,
4502 "Hangup on packet socket");
4505 if (pollinfo
.revents
& POLLERR
) {
4507 * A recv() will give us the actual error code.
4509 * XXX - make the socket non-blocking?
4511 if (recv(handle
->fd
, &c
, sizeof c
,
4513 continue; /* what, no error? */
4514 if (errno
== ENETDOWN
) {
4516 * The device on which we're
4517 * capturing went away.
4519 * XXX - we should really return
4520 * PCAP_ERROR_IFACE_NOT_UP, but
4521 * pcap_dispatch() etc. aren't
4522 * defined to return that.
4524 snprintf(handle
->errbuf
,
4526 "The interface went down");
4528 snprintf(handle
->errbuf
,
4530 "Error condition on packet socket: %s",
4535 if (pollinfo
.revents
& POLLNVAL
) {
4536 snprintf(handle
->errbuf
,
4538 "Invalid polling request on packet socket");
4542 /* check for break loop condition on interrupted syscall*/
4543 if (handle
->break_loop
) {
4544 handle
->break_loop
= 0;
4545 return PCAP_ERROR_BREAK
;
4551 /* handle a single memory mapped packet */
4552 static int pcap_handle_packet_mmap(
4554 pcap_handler callback
,
4556 unsigned char *frame
,
4557 unsigned int tp_len
,
4558 unsigned int tp_mac
,
4559 unsigned int tp_snaplen
,
4560 unsigned int tp_sec
,
4561 unsigned int tp_usec
,
4562 int tp_vlan_tci_valid
,
4566 struct pcap_linux
*handlep
= handle
->priv
;
4568 struct sockaddr_ll
*sll
;
4569 struct pcap_pkthdr pcaphdr
;
4571 /* perform sanity check on internal offset. */
4572 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
4573 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4574 "corrupted frame on kernel ring mac "
4575 "offset %u + caplen %u > frame len %d",
4576 tp_mac
, tp_snaplen
, handle
->bufsize
);
4580 /* run filter on received packet
4581 * If the kernel filtering is enabled we need to run the
4582 * filter until all the frames present into the ring
4583 * at filter creation time are processed.
4584 * In this case, blocks_to_filter_in_userland is used
4585 * as a counter for the packet we need to filter.
4586 * Note: alternatively it could be possible to stop applying
4587 * the filter when the ring became empty, but it can possibly
4588 * happen a lot later... */
4589 bp
= frame
+ tp_mac
;
4591 /* if required build in place the sll header*/
4592 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
4593 if (handlep
->cooked
) {
4594 struct sll_header
*hdrp
;
4597 * The kernel should have left us with enough
4598 * space for an sll header; back up the packet
4599 * data pointer into that space, as that'll be
4600 * the beginning of the packet we pass to the
4606 * Let's make sure that's past the end of
4607 * the tpacket header, i.e. >=
4608 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4609 * don't step on the header when we construct
4612 if (bp
< (u_char
*)frame
+
4613 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4614 sizeof(struct sockaddr_ll
)) {
4615 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4616 "cooked-mode frame doesn't have room for sll header");
4621 * OK, that worked; construct the sll header.
4623 hdrp
= (struct sll_header
*)bp
;
4624 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4626 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4627 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4628 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4629 hdrp
->sll_protocol
= sll
->sll_protocol
;
4632 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
4633 struct bpf_aux_data aux_data
;
4635 aux_data
.vlan_tag
= tp_vlan_tci
& 0x0fff;
4636 aux_data
.vlan_tag_present
= tp_vlan_tci_valid
;
4638 if (bpf_filter_with_aux_data(handle
->fcode
.bf_insns
, bp
,
4639 tp_len
, tp_snaplen
, &aux_data
) == 0)
4643 if (!linux_check_direction(handle
, sll
))
4646 /* get required packet info from ring header */
4647 pcaphdr
.ts
.tv_sec
= tp_sec
;
4648 pcaphdr
.ts
.tv_usec
= tp_usec
;
4649 pcaphdr
.caplen
= tp_snaplen
;
4650 pcaphdr
.len
= tp_len
;
4652 /* if required build in place the sll header*/
4653 if (handlep
->cooked
) {
4654 /* update packet len */
4655 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4656 pcaphdr
.len
+= SLL_HDR_LEN
;
4659 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4660 if (tp_vlan_tci_valid
&&
4661 handlep
->vlan_offset
!= -1 &&
4662 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4664 struct vlan_tag
*tag
;
4667 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4669 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4670 tag
->vlan_tpid
= htons(tp_vlan_tpid
);
4671 tag
->vlan_tci
= htons(tp_vlan_tci
);
4673 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4674 pcaphdr
.len
+= VLAN_TAG_LEN
;
4679 * The only way to tell the kernel to cut off the
4680 * packet at a snapshot length is with a filter program;
4681 * if there's no filter program, the kernel won't cut
4684 * Trim the snapshot length to be no longer than the
4685 * specified snapshot length.
4687 if (pcaphdr
.caplen
> handle
->snapshot
)
4688 pcaphdr
.caplen
= handle
->snapshot
;
4690 /* pass the packet to the user */
4691 callback(user
, &pcaphdr
, bp
);
4697 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4700 struct pcap_linux
*handlep
= handle
->priv
;
4705 /* wait for frames availability.*/
4706 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4707 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
) {
4709 * The current frame is owned by the kernel; wait for
4710 * a frame to be handed to us.
4712 ret
= pcap_wait_for_frames_mmap(handle
);
4718 /* non-positive values of max_packets are used to require all
4719 * packets currently available in the ring */
4720 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4722 * Get the current ring buffer frame, and break if
4723 * it's still owned by the kernel.
4725 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4726 if (h
.h1
->tp_status
== TP_STATUS_KERNEL
)
4729 ret
= pcap_handle_packet_mmap(
4744 handlep
->packets_read
++;
4745 } else if (ret
< 0) {
4750 * Hand this block back to the kernel, and, if we're
4751 * counting blocks that need to be filtered in userland
4752 * after having been filtered by the kernel, count
4753 * the one we've just processed.
4755 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4756 if (handlep
->blocks_to_filter_in_userland
> 0) {
4757 handlep
->blocks_to_filter_in_userland
--;
4758 if (handlep
->blocks_to_filter_in_userland
== 0) {
4760 * No more blocks need to be filtered
4763 handlep
->filter_in_userland
= 0;
4768 if (++handle
->offset
>= handle
->cc
)
4771 /* check for break loop condition*/
4772 if (handle
->break_loop
) {
4773 handle
->break_loop
= 0;
4774 return PCAP_ERROR_BREAK
;
4781 pcap_read_linux_mmap_v1_64(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4784 struct pcap_linux
*handlep
= handle
->priv
;
4789 /* wait for frames availability.*/
4790 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4791 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
) {
4793 * The current frame is owned by the kernel; wait for
4794 * a frame to be handed to us.
4796 ret
= pcap_wait_for_frames_mmap(handle
);
4802 /* non-positive values of max_packets are used to require all
4803 * packets currently available in the ring */
4804 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4806 * Get the current ring buffer frame, and break if
4807 * it's still owned by the kernel.
4809 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4810 if (h
.h1_64
->tp_status
== TP_STATUS_KERNEL
)
4813 ret
= pcap_handle_packet_mmap(
4820 h
.h1_64
->tp_snaplen
,
4828 handlep
->packets_read
++;
4829 } else if (ret
< 0) {
4834 * Hand this block back to the kernel, and, if we're
4835 * counting blocks that need to be filtered in userland
4836 * after having been filtered by the kernel, count
4837 * the one we've just processed.
4839 h
.h1_64
->tp_status
= TP_STATUS_KERNEL
;
4840 if (handlep
->blocks_to_filter_in_userland
> 0) {
4841 handlep
->blocks_to_filter_in_userland
--;
4842 if (handlep
->blocks_to_filter_in_userland
== 0) {
4844 * No more blocks need to be filtered
4847 handlep
->filter_in_userland
= 0;
4852 if (++handle
->offset
>= handle
->cc
)
4855 /* check for break loop condition*/
4856 if (handle
->break_loop
) {
4857 handle
->break_loop
= 0;
4858 return PCAP_ERROR_BREAK
;
4864 #ifdef HAVE_TPACKET2
4866 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4869 struct pcap_linux
*handlep
= handle
->priv
;
4874 /* wait for frames availability.*/
4875 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4876 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
) {
4878 * The current frame is owned by the kernel; wait for
4879 * a frame to be handed to us.
4881 ret
= pcap_wait_for_frames_mmap(handle
);
4887 /* non-positive values of max_packets are used to require all
4888 * packets currently available in the ring */
4889 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4891 * Get the current ring buffer frame, and break if
4892 * it's still owned by the kernel.
4894 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4895 if (h
.h2
->tp_status
== TP_STATUS_KERNEL
)
4898 ret
= pcap_handle_packet_mmap(
4907 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4908 #if defined(TP_STATUS_VLAN_VALID)
4909 (h
.h2
->tp_vlan_tci
|| (h
.h2
->tp_status
& TP_STATUS_VLAN_VALID
)),
4911 h
.h2
->tp_vlan_tci
!= 0,
4914 VLAN_TPID(h
.h2
, h
.h2
));
4917 handlep
->packets_read
++;
4918 } else if (ret
< 0) {
4923 * Hand this block back to the kernel, and, if we're
4924 * counting blocks that need to be filtered in userland
4925 * after having been filtered by the kernel, count
4926 * the one we've just processed.
4928 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4929 if (handlep
->blocks_to_filter_in_userland
> 0) {
4930 handlep
->blocks_to_filter_in_userland
--;
4931 if (handlep
->blocks_to_filter_in_userland
== 0) {
4933 * No more blocks need to be filtered
4936 handlep
->filter_in_userland
= 0;
4941 if (++handle
->offset
>= handle
->cc
)
4944 /* check for break loop condition*/
4945 if (handle
->break_loop
) {
4946 handle
->break_loop
= 0;
4947 return PCAP_ERROR_BREAK
;
4952 #endif /* HAVE_TPACKET2 */
4954 #ifdef HAVE_TPACKET3
4956 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4959 struct pcap_linux
*handlep
= handle
->priv
;
4965 if (handlep
->current_packet
== NULL
) {
4966 /* wait for frames availability.*/
4967 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4968 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4970 * The current frame is owned by the kernel; wait
4971 * for a frame to be handed to us.
4973 ret
= pcap_wait_for_frames_mmap(handle
);
4979 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4980 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
) {
4981 if (pkts
== 0 && handlep
->timeout
== 0) {
4982 /* Block until we see a packet. */
4988 /* non-positive values of max_packets are used to require all
4989 * packets currently available in the ring */
4990 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4991 int packets_to_read
;
4993 if (handlep
->current_packet
== NULL
) {
4994 h
.raw
= RING_GET_CURRENT_FRAME(handle
);
4995 if (h
.h3
->hdr
.bh1
.block_status
== TP_STATUS_KERNEL
)
4998 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4999 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
5001 packets_to_read
= handlep
->packets_left
;
5003 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) && packets_to_read
> max_packets
) {
5004 packets_to_read
= max_packets
;
5007 while(packets_to_read
--) {
5008 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
5009 ret
= pcap_handle_packet_mmap(
5013 handlep
->current_packet
,
5016 tp3_hdr
->tp_snaplen
,
5018 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
5019 #if defined(TP_STATUS_VLAN_VALID)
5020 (tp3_hdr
->hv1
.tp_vlan_tci
|| (tp3_hdr
->tp_status
& TP_STATUS_VLAN_VALID
)),
5022 tp3_hdr
->hv1
.tp_vlan_tci
!= 0,
5024 tp3_hdr
->hv1
.tp_vlan_tci
,
5025 VLAN_TPID(tp3_hdr
, &tp3_hdr
->hv1
));
5028 handlep
->packets_read
++;
5029 } else if (ret
< 0) {
5030 handlep
->current_packet
= NULL
;
5033 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
5034 handlep
->packets_left
--;
5037 if (handlep
->packets_left
<= 0) {
5039 * Hand this block back to the kernel, and, if
5040 * we're counting blocks that need to be
5041 * filtered in userland after having been
5042 * filtered by the kernel, count the one we've
5045 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
5046 if (handlep
->blocks_to_filter_in_userland
> 0) {
5047 handlep
->blocks_to_filter_in_userland
--;
5048 if (handlep
->blocks_to_filter_in_userland
== 0) {
5050 * No more blocks need to be filtered
5053 handlep
->filter_in_userland
= 0;
5058 if (++handle
->offset
>= handle
->cc
)
5061 handlep
->current_packet
= NULL
;
5064 /* check for break loop condition*/
5065 if (handle
->break_loop
) {
5066 handle
->break_loop
= 0;
5067 return PCAP_ERROR_BREAK
;
5070 if (pkts
== 0 && handlep
->timeout
== 0) {
5071 /* Block until we see a packet. */
5076 #endif /* HAVE_TPACKET3 */
5079 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
5081 struct pcap_linux
*handlep
= handle
->priv
;
5086 * Don't rewrite "ret" instructions; we don't need to, as
5087 * we're not reading packets with recvmsg(), and we don't
5088 * want to, as, by not rewriting them, the kernel can avoid
5089 * copying extra data.
5091 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
5096 * If we're filtering in userland, there's nothing to do;
5097 * the new filter will be used for the next packet.
5099 if (handlep
->filter_in_userland
)
5103 * We're filtering in the kernel; the packets present in
5104 * all blocks currently in the ring were already filtered
5105 * by the old filter, and so will need to be filtered in
5106 * userland by the new filter.
5108 * Get an upper bound for the number of such blocks; first,
5109 * walk the ring backward and count the free blocks.
5111 offset
= handle
->offset
;
5113 offset
= handle
->cc
- 1;
5114 for (n
=0; n
< handle
->cc
; ++n
) {
5116 offset
= handle
->cc
- 1;
5117 if (pcap_get_ring_frame_status(handle
, offset
) != TP_STATUS_KERNEL
)
5122 * If we found free blocks, decrement the count of free
5123 * blocks by 1, just in case we lost a race with another
5124 * thread of control that was adding a packet while
5125 * we were counting and that had run the filter before
5128 * XXX - could there be more than one block added in
5131 * XXX - is there a way to avoid that race, e.g. somehow
5132 * wait for all packets that passed the old filter to
5133 * be added to the ring?
5139 * Set the count of blocks worth of packets to filter
5140 * in userland to the total number of blocks in the
5141 * ring minus the number of free blocks we found, and
5142 * turn on userland filtering. (The count of blocks
5143 * worth of packets to filter in userland is guaranteed
5144 * not to be zero - n, above, couldn't be set to a
5145 * value > handle->cc, and if it were equal to
5146 * handle->cc, it wouldn't be zero, and thus would
5147 * be decremented to handle->cc - 1.)
5149 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
5150 handlep
->filter_in_userland
= 1;
5154 #endif /* HAVE_PACKET_RING */
5157 #ifdef HAVE_PF_PACKET_SOCKETS
5159 * Return the index of the given device name. Fill ebuf and return
5163 iface_get_id(int fd
, const char *device
, char *ebuf
)
5167 memset(&ifr
, 0, sizeof(ifr
));
5168 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5170 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
5171 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5172 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
5176 return ifr
.ifr_ifindex
;
5180 * Bind the socket associated with FD to the given device.
5181 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
5182 * or a PCAP_ERROR_ value on a hard error.
5185 iface_bind(int fd
, int ifindex
, char *ebuf
)
5187 struct sockaddr_ll sll
;
5189 socklen_t errlen
= sizeof(err
);
5191 memset(&sll
, 0, sizeof(sll
));
5192 sll
.sll_family
= AF_PACKET
;
5193 sll
.sll_ifindex
= ifindex
;
5194 sll
.sll_protocol
= htons(ETH_P_ALL
);
5196 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
5197 if (errno
== ENETDOWN
) {
5199 * Return a "network down" indication, so that
5200 * the application can report that rather than
5201 * saying we had a mysterious failure and
5202 * suggest that they report a problem to the
5203 * libpcap developers.
5205 return PCAP_ERROR_IFACE_NOT_UP
;
5207 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5208 "bind: %s", pcap_strerror(errno
));
5213 /* Any pending errors, e.g., network is down? */
5215 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5216 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5217 "getsockopt: %s", pcap_strerror(errno
));
5221 if (err
== ENETDOWN
) {
5223 * Return a "network down" indication, so that
5224 * the application can report that rather than
5225 * saying we had a mysterious failure and
5226 * suggest that they report a problem to the
5227 * libpcap developers.
5229 return PCAP_ERROR_IFACE_NOT_UP
;
5230 } else if (err
> 0) {
5231 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5232 "bind: %s", pcap_strerror(err
));
5239 #ifdef IW_MODE_MONITOR
5241 * Check whether the device supports the Wireless Extensions.
5242 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5243 * if the device doesn't even exist.
5246 has_wext(int sock_fd
, const char *device
, char *ebuf
)
5250 if (is_bonding_device(sock_fd
, device
))
5251 return 0; /* bonding device, so don't even try */
5253 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5254 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5255 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
5257 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5258 "%s: SIOCGIWNAME: %s", device
, pcap_strerror(errno
));
5259 if (errno
== ENODEV
)
5260 return PCAP_ERROR_NO_SUCH_DEVICE
;
5265 * Per me si va ne la citta dolente,
5266 * Per me si va ne l'etterno dolore,
5268 * Lasciate ogne speranza, voi ch'intrate.
5270 * XXX - airmon-ng does special stuff with the Orinoco driver and the
5286 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5287 * on if it's not already on.
5289 * Returns 1 on success, 0 if we don't support the Wireless Extensions
5290 * on this device, or a PCAP_ERROR_ value if we do support them but
5291 * we weren't able to turn monitor mode on.
5294 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
5297 * XXX - at least some adapters require non-Wireless Extensions
5298 * mechanisms to turn monitor mode on.
5300 * Atheros cards might require that a separate "monitor virtual access
5301 * point" be created, with later versions of the madwifi driver.
5302 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
5303 * monitor -bssid", which apparently spits out a line "athN"
5304 * where "athN" is the monitor mode device. To leave monitor
5305 * mode, it destroys the monitor mode device.
5307 * Some Intel Centrino adapters might require private ioctls to get
5308 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5309 * configure a separate "rtapN" interface to capture in monitor
5310 * mode without preventing the adapter from operating normally.
5311 * (airmon-ng doesn't appear to use that, though.)
5313 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5314 * up, and if all drivers were converted to mac80211 drivers.
5316 * If interface {if} is a mac80211 driver, the file
5317 * /sys/class/net/{if}/phy80211 is a symlink to
5318 * /sys/class/ieee80211/{phydev}, for some {phydev}.
5320 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5321 * least, has a "wmaster0" device and a "wlan0" device; the
5322 * latter is the one with the IP address. Both show up in
5323 * "tcpdump -D" output. Capturing on the wmaster0 device
5324 * captures with 802.11 headers.
5326 * airmon-ng searches through /sys/class/net for devices named
5327 * monN, starting with mon0; as soon as one *doesn't* exist,
5328 * it chooses that as the monitor device name. If the "iw"
5329 * command exists, it does "iw dev {if} interface add {monif}
5330 * type monitor", where {monif} is the monitor device. It
5331 * then (sigh) sleeps .1 second, and then configures the
5332 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
5333 * is a file, it writes {mondev}, without a newline, to that file,
5334 * and again (sigh) sleeps .1 second, and then iwconfig's that
5335 * device into monitor mode and configures it up. Otherwise,
5336 * you can't do monitor mode.
5338 * All these devices are "glued" together by having the
5339 * /sys/class/net/{device}/phy80211 links pointing to the same
5340 * place, so, given a wmaster, wlan, or mon device, you can
5341 * find the other devices by looking for devices with
5342 * the same phy80211 link.
5344 * To turn monitor mode off, delete the monitor interface,
5345 * either with "iw dev {monif} interface del" or by sending
5346 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
5348 * Note: if you try to create a monitor device named "monN", and
5349 * there's already a "monN" device, it fails, as least with
5350 * the netlink interface (which is what iw uses), with a return
5351 * value of -ENFILE. (Return values are negative errnos.) We
5352 * could probably use that to find an unused device.
5354 struct pcap_linux
*handlep
= handle
->priv
;
5357 struct iw_priv_args
*priv
;
5358 monitor_type montype
;
5367 * Does this device *support* the Wireless Extensions?
5369 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
5371 return err
; /* either it doesn't or the device doesn't even exist */
5373 * Start out assuming we have no private extensions to control
5376 montype
= MONITOR_WEXT
;
5380 * Try to get all the Wireless Extensions private ioctls
5381 * supported by this device.
5383 * First, get the size of the buffer we need, by supplying no
5384 * buffer and a length of 0. If the device supports private
5385 * ioctls, it should return E2BIG, with ireq.u.data.length set
5386 * to the length we need. If it doesn't support them, it should
5387 * return EOPNOTSUPP.
5389 memset(&ireq
, 0, sizeof ireq
);
5390 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5391 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5392 ireq
.u
.data
.pointer
= (void *)args
;
5393 ireq
.u
.data
.length
= 0;
5394 ireq
.u
.data
.flags
= 0;
5395 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
5396 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5397 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
5401 if (errno
!= EOPNOTSUPP
) {
5403 * OK, it's not as if there are no private ioctls.
5405 if (errno
!= E2BIG
) {
5409 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5410 "%s: SIOCGIWPRIV: %s", device
,
5411 pcap_strerror(errno
));
5416 * OK, try to get the list of private ioctls.
5418 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
5420 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5421 "malloc: %s", pcap_strerror(errno
));
5424 ireq
.u
.data
.pointer
= (void *)priv
;
5425 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
5426 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5427 "%s: SIOCGIWPRIV: %s", device
,
5428 pcap_strerror(errno
));
5434 * Look for private ioctls to turn monitor mode on or, if
5435 * monitor mode is on, to set the header type.
5437 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
5438 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
5440 * Hostap driver, use this one.
5441 * Set monitor mode first.
5442 * You can set it to 0 to get DLT_IEEE80211,
5443 * 1 to get DLT_PRISM, 2 to get
5444 * DLT_IEEE80211_RADIO_AVS, and, with more
5445 * recent versions of the driver, 3 to get
5446 * DLT_IEEE80211_RADIO.
5448 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5450 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5452 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5454 montype
= MONITOR_HOSTAP
;
5458 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
5460 * Prism54 driver, use this one.
5461 * Set monitor mode first.
5462 * You can set it to 2 to get DLT_IEEE80211
5463 * or 3 or get DLT_PRISM.
5465 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5467 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5469 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5471 montype
= MONITOR_PRISM54
;
5475 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
5477 * RT2570 driver, use this one.
5478 * Do this after turning monitor mode on.
5479 * You can set it to 1 to get DLT_PRISM or 2
5480 * to get DLT_IEEE80211.
5482 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5484 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5486 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5488 montype
= MONITOR_RT2570
;
5492 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
5494 * RT73 driver, use this one.
5495 * Do this after turning monitor mode on.
5496 * Its argument is a *string*; you can
5497 * set it to "1" to get DLT_PRISM or "2"
5498 * to get DLT_IEEE80211.
5500 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
5502 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
5504 montype
= MONITOR_RT73
;
5508 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
5510 * One of the RTL8xxx drivers, use this one.
5511 * It can only be done after monitor mode
5512 * has been turned on. You can set it to 1
5513 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5515 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5517 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5519 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5521 montype
= MONITOR_RTL8XXX
;
5525 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
5527 * RT2500 or RT61 driver, use this one.
5528 * It has one one-byte parameter; set
5529 * u.data.length to 1 and u.data.pointer to
5530 * point to the parameter.
5531 * It doesn't itself turn monitor mode on.
5532 * You can set it to 1 to allow transmitting
5533 * in monitor mode(?) and get DLT_IEEE80211,
5534 * or set it to 0 to disallow transmitting in
5535 * monitor mode(?) and get DLT_PRISM.
5537 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5539 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
5541 montype
= MONITOR_RT2500
;
5545 if (strcmp(priv
[i
].name
, "monitor") == 0) {
5547 * Either ACX100 or hostap, use this one.
5548 * It turns monitor mode on.
5549 * If it takes two arguments, it's ACX100;
5550 * the first argument is 1 for DLT_PRISM
5551 * or 2 for DLT_IEEE80211, and the second
5552 * argument is the channel on which to
5553 * run. If it takes one argument, it's
5554 * HostAP, and the argument is 2 for
5555 * DLT_IEEE80211 and 3 for DLT_PRISM.
5557 * If we see this, we don't quit, as this
5558 * might be a version of the hostap driver
5559 * that also supports "monitor_type".
5561 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5563 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5565 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5568 montype
= MONITOR_PRISM
;
5573 montype
= MONITOR_ACX100
;
5586 * XXX - ipw3945? islism?
5592 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5593 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5594 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
5596 * We probably won't be able to set the mode, either.
5598 return PCAP_ERROR_RFMON_NOTSUP
;
5602 * Is it currently in monitor mode?
5604 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
5606 * Yes. Just leave things as they are.
5607 * We don't offer multiple link-layer types, as
5608 * changing the link-layer type out from under
5609 * somebody else capturing in monitor mode would
5610 * be considered rude.
5615 * No. We have to put the adapter into rfmon mode.
5619 * If we haven't already done so, arrange to have
5620 * "pcap_close_all()" called when we exit.
5622 if (!pcap_do_addexit(handle
)) {
5624 * "atexit()" failed; don't put the interface
5625 * in rfmon mode, just give up.
5627 return PCAP_ERROR_RFMON_NOTSUP
;
5631 * Save the old mode.
5633 handlep
->oldmode
= ireq
.u
.mode
;
5636 * Put the adapter in rfmon mode. How we do this depends
5637 * on whether we have a special private ioctl or not.
5639 if (montype
== MONITOR_PRISM
) {
5641 * We have the "monitor" private ioctl, but none of
5642 * the other private ioctls. Use this, and select
5645 * If it fails, just fall back on SIOCSIWMODE.
5647 memset(&ireq
, 0, sizeof ireq
);
5648 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5649 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5650 ireq
.u
.data
.length
= 1; /* 1 argument */
5651 args
[0] = 3; /* request Prism header */
5652 memcpy(ireq
.u
.name
, args
, sizeof (int));
5653 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
5656 * Note that we have to put the old mode back
5657 * when we close the device.
5659 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5662 * Add this to the list of pcaps to close
5665 pcap_add_to_pcaps_to_close(handle
);
5671 * Failure. Fall back on SIOCSIWMODE.
5676 * First, take the interface down if it's up; otherwise, we
5679 memset(&ifr
, 0, sizeof(ifr
));
5680 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5681 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5682 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5683 "%s: Can't get flags: %s", device
, strerror(errno
));
5687 if (ifr
.ifr_flags
& IFF_UP
) {
5688 oldflags
= ifr
.ifr_flags
;
5689 ifr
.ifr_flags
&= ~IFF_UP
;
5690 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5691 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5692 "%s: Can't set flags: %s", device
, strerror(errno
));
5698 * Then turn monitor mode on.
5700 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5701 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5702 ireq
.u
.mode
= IW_MODE_MONITOR
;
5703 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
5705 * Scientist, you've failed.
5706 * Bring the interface back up if we shut it down.
5708 ifr
.ifr_flags
= oldflags
;
5709 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5710 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5711 "%s: Can't set flags: %s", device
, strerror(errno
));
5714 return PCAP_ERROR_RFMON_NOTSUP
;
5718 * XXX - airmon-ng does "iwconfig {if} key off" after setting
5719 * monitor mode and setting the channel, and then does
5724 * Now select the appropriate radio header.
5730 * We don't have any private ioctl to set the header.
5734 case MONITOR_HOSTAP
:
5736 * Try to select the radiotap header.
5738 memset(&ireq
, 0, sizeof ireq
);
5739 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5740 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5741 args
[0] = 3; /* request radiotap header */
5742 memcpy(ireq
.u
.name
, args
, sizeof (int));
5743 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5744 break; /* success */
5747 * That failed. Try to select the AVS header.
5749 memset(&ireq
, 0, sizeof ireq
);
5750 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5751 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5752 args
[0] = 2; /* request AVS header */
5753 memcpy(ireq
.u
.name
, args
, sizeof (int));
5754 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5755 break; /* success */
5758 * That failed. Try to select the Prism header.
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 memcpy(ireq
.u
.name
, args
, sizeof (int));
5765 ioctl(sock_fd
, cmd
, &ireq
);
5770 * The private ioctl failed.
5774 case MONITOR_PRISM54
:
5776 * Select the Prism header.
5778 memset(&ireq
, 0, sizeof ireq
);
5779 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5780 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5781 args
[0] = 3; /* request Prism header */
5782 memcpy(ireq
.u
.name
, args
, sizeof (int));
5783 ioctl(sock_fd
, cmd
, &ireq
);
5786 case MONITOR_ACX100
:
5788 * Get the current channel.
5790 memset(&ireq
, 0, sizeof ireq
);
5791 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5792 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5793 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
5794 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5795 "%s: SIOCGIWFREQ: %s", device
,
5796 pcap_strerror(errno
));
5799 channel
= ireq
.u
.freq
.m
;
5802 * Select the Prism header, and set the channel to the
5805 memset(&ireq
, 0, sizeof ireq
);
5806 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5807 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5808 args
[0] = 1; /* request Prism header */
5809 args
[1] = channel
; /* set channel */
5810 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
5811 ioctl(sock_fd
, cmd
, &ireq
);
5814 case MONITOR_RT2500
:
5816 * Disallow transmission - that turns on the
5819 memset(&ireq
, 0, sizeof ireq
);
5820 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5821 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5822 args
[0] = 0; /* disallow transmitting */
5823 memcpy(ireq
.u
.name
, args
, sizeof (int));
5824 ioctl(sock_fd
, cmd
, &ireq
);
5827 case MONITOR_RT2570
:
5829 * Force the Prism header.
5831 memset(&ireq
, 0, sizeof ireq
);
5832 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5833 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5834 args
[0] = 1; /* request Prism header */
5835 memcpy(ireq
.u
.name
, args
, sizeof (int));
5836 ioctl(sock_fd
, cmd
, &ireq
);
5841 * Force the Prism header.
5843 memset(&ireq
, 0, sizeof ireq
);
5844 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5845 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5846 ireq
.u
.data
.length
= 1; /* 1 argument */
5847 ireq
.u
.data
.pointer
= "1";
5848 ireq
.u
.data
.flags
= 0;
5849 ioctl(sock_fd
, cmd
, &ireq
);
5852 case MONITOR_RTL8XXX
:
5854 * Force the Prism header.
5856 memset(&ireq
, 0, sizeof ireq
);
5857 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5858 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5859 args
[0] = 1; /* request Prism header */
5860 memcpy(ireq
.u
.name
, args
, sizeof (int));
5861 ioctl(sock_fd
, cmd
, &ireq
);
5866 * Now bring the interface back up if we brought it down.
5868 if (oldflags
!= 0) {
5869 ifr
.ifr_flags
= oldflags
;
5870 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5871 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5872 "%s: Can't set flags: %s", device
, strerror(errno
));
5875 * At least try to restore the old mode on the
5878 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
5880 * Scientist, you've failed.
5883 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5884 "Please adjust manually.\n",
5892 * Note that we have to put the old mode back when we
5895 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5898 * Add this to the list of pcaps to close when we exit.
5900 pcap_add_to_pcaps_to_close(handle
);
5904 #endif /* IW_MODE_MONITOR */
5907 * Try various mechanisms to enter monitor mode.
5910 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
5912 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5917 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
5919 return ret
; /* error attempting to do so */
5921 return 1; /* success */
5922 #endif /* HAVE_LIBNL */
5924 #ifdef IW_MODE_MONITOR
5925 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
5927 return ret
; /* error attempting to do so */
5929 return 1; /* success */
5930 #endif /* IW_MODE_MONITOR */
5933 * Either none of the mechanisms we know about work or none
5934 * of those mechanisms are available, so we can't do monitor
5940 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5942 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5944 static const struct {
5945 int soft_timestamping_val
;
5946 int pcap_tstamp_val
;
5947 } sof_ts_type_map
[3] = {
5948 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5949 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5950 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5952 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5955 iface_set_default_ts_types(pcap_t
*handle
)
5959 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5960 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5961 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5962 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5965 #ifdef ETHTOOL_GET_TS_INFO
5967 * Get a list of time stamping capabilities.
5970 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
)
5974 struct ethtool_ts_info info
;
5979 * This doesn't apply to the "any" device; you have to ask
5980 * specific devices for their capabilities, so just default
5981 * to saying we support all of them.
5983 if (strcmp(handle
->opt
.source
, "any") == 0) {
5984 iface_set_default_ts_types(handle
);
5989 * Create a socket from which to fetch time stamping capabilities.
5991 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
5993 (void)snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5994 "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO): %s", pcap_strerror(errno
));
5998 memset(&ifr
, 0, sizeof(ifr
));
5999 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
6000 memset(&info
, 0, sizeof(info
));
6001 info
.cmd
= ETHTOOL_GET_TS_INFO
;
6002 ifr
.ifr_data
= (caddr_t
)&info
;
6003 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
6005 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
6007 * OK, let's just return all the possible time
6010 iface_set_default_ts_types(handle
);
6013 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6014 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: %s", handle
->opt
.source
,
6021 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6022 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
6025 handle
->tstamp_type_count
= num_ts_types
;
6026 if (num_ts_types
!= 0) {
6027 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
6028 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
6029 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
6030 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
6035 handle
->tstamp_type_list
= NULL
;
6039 #else /* ETHTOOL_GET_TS_INFO */
6041 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf _U_
)
6044 * We don't have an ioctl to use to ask what's supported,
6045 * so say we support everything.
6047 iface_set_default_ts_types(handle
);
6050 #endif /* ETHTOOL_GET_TS_INFO */
6052 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6054 #ifdef HAVE_PACKET_RING
6056 * Find out if we have any form of fragmentation/reassembly offloading.
6058 * We do so using SIOCETHTOOL checking for various types of offloading;
6059 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6060 * of the types of offloading, there's nothing we can do to check, so
6061 * we just say "no, we don't".
6063 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6065 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
6068 struct ethtool_value eval
;
6070 memset(&ifr
, 0, sizeof(ifr
));
6071 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
6074 ifr
.ifr_data
= (caddr_t
)&eval
;
6075 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
6076 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
6078 * OK, let's just return 0, which, in our
6079 * case, either means "no, what we're asking
6080 * about is not enabled" or "all the flags
6081 * are clear (i.e., nothing is enabled)".
6085 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6086 "%s: SIOCETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
6087 cmdname
, strerror(errno
));
6094 iface_get_offload(pcap_t
*handle
)
6099 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
6103 return 1; /* TCP segmentation offloading on */
6107 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
6111 return 1; /* UDP fragmentation offloading on */
6116 * XXX - will this cause large unsegmented packets to be
6117 * handed to PF_PACKET sockets on transmission? If not,
6118 * this need not be checked.
6120 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
6124 return 1; /* generic segmentation offloading on */
6127 #ifdef ETHTOOL_GFLAGS
6128 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
6131 if (ret
& ETH_FLAG_LRO
)
6132 return 1; /* large receive offloading on */
6137 * XXX - will this cause large reassembled packets to be
6138 * handed to PF_PACKET sockets on receipt? If not,
6139 * this need not be checked.
6141 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
6145 return 1; /* generic (large) receive offloading on */
6150 #else /* SIOCETHTOOL */
6152 iface_get_offload(pcap_t
*handle _U_
)
6155 * XXX - do we need to get this information if we don't
6156 * have the ethtool ioctls? If so, how do we do that?
6160 #endif /* SIOCETHTOOL */
6162 #endif /* HAVE_PACKET_RING */
6164 #endif /* HAVE_PF_PACKET_SOCKETS */
6166 /* ===== Functions to interface to the older kernels ================== */
6169 * Try to open a packet socket using the old kernel interface.
6170 * Returns 1 on success and a PCAP_ERROR_ value on an error.
6173 activate_old(pcap_t
*handle
)
6175 struct pcap_linux
*handlep
= handle
->priv
;
6178 const char *device
= handle
->opt
.source
;
6179 struct utsname utsname
;
6182 /* Open the socket */
6184 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
6185 if (handle
->fd
== -1) {
6186 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6187 "socket: %s", pcap_strerror(errno
));
6188 if (errno
== EPERM
|| errno
== EACCES
) {
6190 * You don't have permission to open the
6193 return PCAP_ERROR_PERM_DENIED
;
6202 /* It worked - we are using the old interface */
6203 handlep
->sock_packet
= 1;
6205 /* ...which means we get the link-layer header. */
6206 handlep
->cooked
= 0;
6208 /* Bind to the given device */
6210 if (strcmp(device
, "any") == 0) {
6211 strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
6215 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
6219 * Try to get the link-layer type.
6221 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
6226 * Try to find the DLT_ type corresponding to that
6229 map_arphrd_to_dlt(handle
, handle
->fd
, arptype
, device
, 0);
6230 if (handle
->linktype
== -1) {
6231 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6232 "unknown arptype %d", arptype
);
6236 /* Go to promisc mode if requested */
6238 if (handle
->opt
.promisc
) {
6239 memset(&ifr
, 0, sizeof(ifr
));
6240 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6241 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
6242 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6243 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
6246 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
6248 * Promiscuous mode isn't currently on,
6249 * so turn it on, and remember that
6250 * we should turn it off when the
6255 * If we haven't already done so, arrange
6256 * to have "pcap_close_all()" called when
6259 if (!pcap_do_addexit(handle
)) {
6261 * "atexit()" failed; don't put
6262 * the interface in promiscuous
6263 * mode, just give up.
6268 ifr
.ifr_flags
|= IFF_PROMISC
;
6269 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
6270 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6272 pcap_strerror(errno
));
6275 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
6278 * Add this to the list of pcaps
6279 * to close when we exit.
6281 pcap_add_to_pcaps_to_close(handle
);
6286 * Compute the buffer size.
6288 * We're using SOCK_PACKET, so this might be a 2.0[.x]
6289 * kernel, and might require special handling - check.
6291 if (uname(&utsname
) < 0 ||
6292 strncmp(utsname
.release
, "2.0", 3) == 0) {
6294 * Either we couldn't find out what kernel release
6295 * this is, or it's a 2.0[.x] kernel.
6297 * In the 2.0[.x] kernel, a "recvfrom()" on
6298 * a SOCK_PACKET socket, with MSG_TRUNC set, will
6299 * return the number of bytes read, so if we pass
6300 * a length based on the snapshot length, it'll
6301 * return the number of bytes from the packet
6302 * copied to userland, not the actual length
6305 * This means that, for example, the IP dissector
6306 * in tcpdump will get handed a packet length less
6307 * than the length in the IP header, and will
6308 * complain about "truncated-ip".
6310 * So we don't bother trying to copy from the
6311 * kernel only the bytes in which we're interested,
6312 * but instead copy them all, just as the older
6313 * versions of libpcap for Linux did.
6315 * The buffer therefore needs to be big enough to
6316 * hold the largest packet we can get from this
6317 * device. Unfortunately, we can't get the MRU
6318 * of the network; we can only get the MTU. The
6319 * MTU may be too small, in which case a packet larger
6320 * than the buffer size will be truncated *and* we
6321 * won't get the actual packet size.
6323 * However, if the snapshot length is larger than
6324 * the buffer size based on the MTU, we use the
6325 * snapshot length as the buffer size, instead;
6326 * this means that with a sufficiently large snapshot
6327 * length we won't artificially truncate packets
6328 * to the MTU-based size.
6330 * This mess just one of many problems with packet
6331 * capture on 2.0[.x] kernels; you really want a
6332 * 2.2[.x] or later kernel if you want packet capture
6335 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
6338 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
6339 if (handle
->bufsize
< handle
->snapshot
)
6340 handle
->bufsize
= handle
->snapshot
;
6343 * This is a 2.2[.x] or later kernel.
6345 * We can safely pass "recvfrom()" a byte count
6346 * based on the snapshot length.
6348 handle
->bufsize
= handle
->snapshot
;
6352 * Default value for offset to align link-layer payload
6353 * on a 4-byte boundary.
6358 * SOCK_PACKET sockets don't supply information from
6359 * stripped VLAN tags.
6361 handlep
->vlan_offset
= -1; /* unknown */
6367 * Bind the socket associated with FD to the given device using the
6368 * interface of the old kernels.
6371 iface_bind_old(int fd
, const char *device
, char *ebuf
)
6373 struct sockaddr saddr
;
6375 socklen_t errlen
= sizeof(err
);
6377 memset(&saddr
, 0, sizeof(saddr
));
6378 strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
6379 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
6380 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6381 "bind: %s", pcap_strerror(errno
));
6385 /* Any pending errors, e.g., network is down? */
6387 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
6388 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6389 "getsockopt: %s", pcap_strerror(errno
));
6394 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6395 "bind: %s", pcap_strerror(err
));
6403 /* ===== System calls available on all supported kernels ============== */
6406 * Query the kernel for the MTU of the given interface.
6409 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
6414 return BIGGER_THAN_ALL_MTUS
;
6416 memset(&ifr
, 0, sizeof(ifr
));
6417 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6419 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
6420 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6421 "SIOCGIFMTU: %s", pcap_strerror(errno
));
6429 * Get the hardware type of the given interface as ARPHRD_xxx constant.
6432 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
6436 memset(&ifr
, 0, sizeof(ifr
));
6437 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
6439 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
6440 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
6441 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
6442 if (errno
== ENODEV
) {
6446 return PCAP_ERROR_NO_SUCH_DEVICE
;
6451 return ifr
.ifr_hwaddr
.sa_family
;
6454 #ifdef SO_ATTACH_FILTER
6456 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
6458 struct pcap_linux
*handlep
= handle
->priv
;
6461 register struct bpf_insn
*p
;
6466 * Make a copy of the filter, and modify that copy if
6469 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
6470 len
= handle
->fcode
.bf_len
;
6471 f
= (struct bpf_insn
*)malloc(prog_size
);
6473 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6474 "malloc: %s", pcap_strerror(errno
));
6477 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
6479 fcode
->filter
= (struct sock_filter
*) f
;
6481 for (i
= 0; i
< len
; ++i
) {
6484 * What type of instruction is this?
6486 switch (BPF_CLASS(p
->code
)) {
6490 * It's a return instruction; are we capturing
6491 * in memory-mapped mode?
6495 * No; is the snapshot length a constant,
6496 * rather than the contents of the
6499 if (BPF_MODE(p
->code
) == BPF_K
) {
6501 * Yes - if the value to be returned,
6502 * i.e. the snapshot length, is
6503 * anything other than 0, make it
6504 * MAXIMUM_SNAPLEN, so that the packet
6505 * is truncated by "recvfrom()",
6506 * not by the filter.
6508 * XXX - there's nothing we can
6509 * easily do if it's getting the
6510 * value from the accumulator; we'd
6511 * have to insert code to force
6512 * non-zero values to be
6516 p
->k
= MAXIMUM_SNAPLEN
;
6524 * It's a load instruction; is it loading
6527 switch (BPF_MODE(p
->code
)) {
6533 * Yes; are we in cooked mode?
6535 if (handlep
->cooked
) {
6537 * Yes, so we need to fix this
6540 if (fix_offset(p
) < 0) {
6542 * We failed to do so.
6543 * Return 0, so our caller
6544 * knows to punt to userland.
6554 return 1; /* we succeeded */
6558 fix_offset(struct bpf_insn
*p
)
6561 * What's the offset?
6563 if (p
->k
>= SLL_HDR_LEN
) {
6565 * It's within the link-layer payload; that starts at an
6566 * offset of 0, as far as the kernel packet filter is
6567 * concerned, so subtract the length of the link-layer
6570 p
->k
-= SLL_HDR_LEN
;
6571 } else if (p
->k
== 0) {
6573 * It's the packet type field; map it to the special magic
6574 * kernel offset for that field.
6576 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6577 } else if (p
->k
== 14) {
6579 * It's the protocol field; map it to the special magic
6580 * kernel offset for that field.
6582 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6583 } else if ((bpf_int32
)(p
->k
) > 0) {
6585 * It's within the header, but it's not one of those
6586 * fields; we can't do that in the kernel, so punt
6595 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
6597 int total_filter_on
= 0;
6603 * The socket filter code doesn't discard all packets queued
6604 * up on the socket when the filter is changed; this means
6605 * that packets that don't match the new filter may show up
6606 * after the new filter is put onto the socket, if those
6607 * packets haven't yet been read.
6609 * This means, for example, that if you do a tcpdump capture
6610 * with a filter, the first few packets in the capture might
6611 * be packets that wouldn't have passed the filter.
6613 * We therefore discard all packets queued up on the socket
6614 * when setting a kernel filter. (This isn't an issue for
6615 * userland filters, as the userland filtering is done after
6616 * packets are queued up.)
6618 * To flush those packets, we put the socket in read-only mode,
6619 * and read packets from the socket until there are no more to
6622 * In order to keep that from being an infinite loop - i.e.,
6623 * to keep more packets from arriving while we're draining
6624 * the queue - we put the "total filter", which is a filter
6625 * that rejects all packets, onto the socket before draining
6628 * This code deliberately ignores any errors, so that you may
6629 * get bogus packets if an error occurs, rather than having
6630 * the filtering done in userland even if it could have been
6631 * done in the kernel.
6633 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6634 &total_fcode
, sizeof(total_fcode
)) == 0) {
6638 * Note that we've put the total filter onto the socket.
6640 total_filter_on
= 1;
6643 * Save the socket's current mode, and put it in
6644 * non-blocking mode; we drain it by reading packets
6645 * until we get an error (which is normally a
6646 * "nothing more to be read" error).
6648 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6649 if (save_mode
== -1) {
6650 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6651 "can't get FD flags when changing filter: %s",
6652 pcap_strerror(errno
));
6655 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
6656 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6657 "can't set nonblocking mode when changing filter: %s",
6658 pcap_strerror(errno
));
6661 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
6664 if (save_errno
!= EAGAIN
) {
6668 * If we can't restore the mode or reset the
6669 * kernel filter, there's nothing we can do.
6671 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
6672 (void)reset_kernel_filter(handle
);
6673 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6674 "recv failed when changing filter: %s",
6675 pcap_strerror(save_errno
));
6678 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
6679 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6680 "can't restore FD flags when changing filter: %s",
6681 pcap_strerror(save_errno
));
6687 * Now attach the new filter.
6689 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6690 fcode
, sizeof(*fcode
));
6691 if (ret
== -1 && total_filter_on
) {
6693 * Well, we couldn't set that filter on the socket,
6694 * but we could set the total filter on the socket.
6696 * This could, for example, mean that the filter was
6697 * too big to put into the kernel, so we'll have to
6698 * filter in userland; in any case, we'll be doing
6699 * filtering in userland, so we need to remove the
6700 * total filter so we see packets.
6705 * If this fails, we're really screwed; we have the
6706 * total filter on the socket, and it won't come off.
6707 * Report it as a fatal error.
6709 if (reset_kernel_filter(handle
) == -1) {
6710 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6711 "can't remove kernel total filter: %s",
6712 pcap_strerror(errno
));
6713 return -2; /* fatal error */
6722 reset_kernel_filter(pcap_t
*handle
)
6725 * setsockopt() barfs unless it get a dummy parameter.
6726 * valgrind whines unless the value is initialized,
6727 * as it has no idea that setsockopt() ignores its
6732 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6733 &dummy
, sizeof(dummy
));