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 TPACKET_HDRLEN
195 # define HAVE_PACKET_RING
196 # ifdef TPACKET3_HDRLEN
197 # define HAVE_TPACKET3
198 # endif /* TPACKET3_HDRLEN */
199 # ifdef TPACKET2_HDRLEN
200 # define HAVE_TPACKET2
201 # else /* TPACKET2_HDRLEN */
202 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
203 # endif /* TPACKET2_HDRLEN */
204 # endif /* TPACKET_HDRLEN */
205 #endif /* PF_PACKET */
207 #ifdef SO_ATTACH_FILTER
208 #include <linux/types.h>
209 #include <linux/filter.h>
212 #ifdef HAVE_LINUX_NET_TSTAMP_H
213 #include <linux/net_tstamp.h>
217 * Got Wireless Extensions?
219 #ifdef HAVE_LINUX_WIRELESS_H
220 #include <linux/wireless.h>
221 #endif /* HAVE_LINUX_WIRELESS_H */
227 #include <linux/nl80211.h>
229 #include <netlink/genl/genl.h>
230 #include <netlink/genl/family.h>
231 #include <netlink/genl/ctrl.h>
232 #include <netlink/msg.h>
233 #include <netlink/attr.h>
234 #endif /* HAVE_LIBNL */
237 * Got ethtool support?
239 #ifdef HAVE_LINUX_ETHTOOL_H
240 #include <linux/ethtool.h>
243 #ifndef HAVE_SOCKLEN_T
244 typedef int socklen_t
;
249 * This is being compiled on a system that lacks MSG_TRUNC; define it
250 * with the value it has in the 2.2 and later kernels, so that, on
251 * those kernels, when we pass it in the flags argument to "recvfrom()"
252 * we're passing the right value and thus get the MSG_TRUNC behavior
253 * we want. (We don't get that behavior on 2.0[.x] kernels, because
254 * they didn't support MSG_TRUNC.)
256 #define MSG_TRUNC 0x20
261 * This is being compiled on a system that lacks SOL_PACKET; define it
262 * with the value it has in the 2.2 and later kernels, so that we can
263 * set promiscuous mode in the good modern way rather than the old
264 * 2.0-kernel crappy way.
266 #define SOL_PACKET 263
269 #define MAX_LINKHEADER_SIZE 256
272 * When capturing on all interfaces we use this as the buffer size.
273 * Should be bigger then all MTUs that occur in real life.
274 * 64kB should be enough for now.
276 #define BIGGER_THAN_ALL_MTUS (64*1024)
279 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
282 u_int packets_read
; /* count of packets read with recvfrom() */
283 long proc_dropped
; /* packets reported dropped by /proc/net/dev */
284 struct pcap_stat stat
;
286 char *device
; /* device name */
287 int filter_in_userland
; /* must filter in userland */
288 int blocks_to_filter_in_userland
;
289 int must_do_on_close
; /* stuff we must do when we close */
290 int timeout
; /* timeout for buffering */
291 int sock_packet
; /* using Linux 2.0 compatible interface */
292 int cooked
; /* using SOCK_DGRAM rather than SOCK_RAW */
293 int ifindex
; /* interface index of device we're bound to */
294 int lo_ifindex
; /* interface index of the loopback device */
295 bpf_u_int32 oldmode
; /* mode to restore when turning monitor mode off */
296 char *mondevice
; /* mac80211 monitor device we created */
297 u_char
*mmapbuf
; /* memory-mapped region pointer */
298 size_t mmapbuflen
; /* size of region */
299 int vlan_offset
; /* offset at which to insert vlan tags; if -1, don't insert */
300 u_int tp_version
; /* version of tpacket_hdr for mmaped ring */
301 u_int tp_hdrlen
; /* hdrlen of tpacket_hdr for mmaped ring */
302 u_char
*oneshot_buffer
; /* buffer for copy of packet */
304 unsigned char *current_packet
; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
305 int packets_left
; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
310 * Stuff to do when we close.
312 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
313 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
314 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
317 * Prototypes for internal functions and methods.
319 static void map_arphrd_to_dlt(pcap_t
*, int, const char *, int);
320 #ifdef HAVE_PF_PACKET_SOCKETS
321 static short int map_packet_type_to_sll_type(short int);
323 static int pcap_activate_linux(pcap_t
*);
324 static int activate_old(pcap_t
*);
325 static int activate_new(pcap_t
*);
326 static int activate_mmap(pcap_t
*, int *);
327 static int pcap_can_set_rfmon_linux(pcap_t
*);
328 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
329 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
330 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
331 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
332 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
333 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
334 static int pcap_set_datalink_linux(pcap_t
*, int);
335 static void pcap_cleanup_linux(pcap_t
*);
338 struct tpacket_hdr
*h1
;
340 struct tpacket2_hdr
*h2
;
343 struct tpacket_block_desc
*h3
;
348 #ifdef HAVE_PACKET_RING
349 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
351 static void destroy_ring(pcap_t
*handle
);
352 static int create_ring(pcap_t
*handle
, int *status
);
353 static int prepare_tpacket_socket(pcap_t
*handle
);
354 static void pcap_cleanup_linux_mmap(pcap_t
*);
355 static int pcap_read_linux_mmap_v1(pcap_t
*, int, pcap_handler
, u_char
*);
357 static int pcap_read_linux_mmap_v2(pcap_t
*, int, pcap_handler
, u_char
*);
360 static int pcap_read_linux_mmap_v3(pcap_t
*, int, pcap_handler
, u_char
*);
362 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
363 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
364 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
365 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
366 const u_char
*bytes
);
370 * Wrap some ioctl calls
372 #ifdef HAVE_PF_PACKET_SOCKETS
373 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
374 #endif /* HAVE_PF_PACKET_SOCKETS */
375 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
376 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
377 #ifdef HAVE_PF_PACKET_SOCKETS
378 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
379 #ifdef IW_MODE_MONITOR
380 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
381 #endif /* IW_MODE_MONITOR */
382 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
384 #endif /* HAVE_PF_PACKET_SOCKETS */
385 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
386 static int iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
);
388 static int iface_get_offload(pcap_t
*handle
);
389 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
391 #ifdef SO_ATTACH_FILTER
392 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
394 static int fix_offset(struct bpf_insn
*p
);
395 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
396 static int reset_kernel_filter(pcap_t
*handle
);
398 static struct sock_filter total_insn
399 = BPF_STMT(BPF_RET
| BPF_K
, 0);
400 static struct sock_fprog total_fcode
401 = { 1, &total_insn
};
402 #endif /* SO_ATTACH_FILTER */
405 pcap_create_interface(const char *device
, char *ebuf
)
409 handle
= pcap_create_common(device
, ebuf
, sizeof (struct pcap_linux
));
413 handle
->activate_op
= pcap_activate_linux
;
414 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
416 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
418 * See what time stamp types we support.
420 if (iface_ethtool_get_ts_info(handle
, ebuf
) == -1) {
426 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
428 * We claim that we support microsecond and nanosecond time
431 * XXX - with adapter-supplied time stamps, can we choose
432 * microsecond or nanosecond time stamps on arbitrary
435 handle
->tstamp_precision_count
= 2;
436 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
437 if (handle
->tstamp_precision_list
== NULL
) {
438 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
439 pcap_strerror(errno
));
440 if (handle
->tstamp_type_list
!= NULL
)
441 free(handle
->tstamp_type_list
);
445 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
446 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
447 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
454 * If interface {if} is a mac80211 driver, the file
455 * /sys/class/net/{if}/phy80211 is a symlink to
456 * /sys/class/ieee80211/{phydev}, for some {phydev}.
458 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
459 * least, has a "wmaster0" device and a "wlan0" device; the
460 * latter is the one with the IP address. Both show up in
461 * "tcpdump -D" output. Capturing on the wmaster0 device
462 * captures with 802.11 headers.
464 * airmon-ng searches through /sys/class/net for devices named
465 * monN, starting with mon0; as soon as one *doesn't* exist,
466 * it chooses that as the monitor device name. If the "iw"
467 * command exists, it does "iw dev {if} interface add {monif}
468 * type monitor", where {monif} is the monitor device. It
469 * then (sigh) sleeps .1 second, and then configures the
470 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
471 * is a file, it writes {mondev}, without a newline, to that file,
472 * and again (sigh) sleeps .1 second, and then iwconfig's that
473 * device into monitor mode and configures it up. Otherwise,
474 * you can't do monitor mode.
476 * All these devices are "glued" together by having the
477 * /sys/class/net/{device}/phy80211 links pointing to the same
478 * place, so, given a wmaster, wlan, or mon device, you can
479 * find the other devices by looking for devices with
480 * the same phy80211 link.
482 * To turn monitor mode off, delete the monitor interface,
483 * either with "iw dev {monif} interface del" or by sending
484 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
486 * Note: if you try to create a monitor device named "monN", and
487 * there's already a "monN" device, it fails, as least with
488 * the netlink interface (which is what iw uses), with a return
489 * value of -ENFILE. (Return values are negative errnos.) We
490 * could probably use that to find an unused device.
492 * Yes, you can have multiple monitor devices for a given
497 * Is this a mac80211 device? If so, fill in the physical device path and
498 * return 1; if not, return 0. On an error, fill in handle->errbuf and
502 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
503 size_t phydev_max_pathlen
)
509 * Generate the path string for the symlink to the physical device.
511 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
512 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
513 "%s: Can't generate path name string for /sys/class/net device",
517 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
518 if (bytes_read
== -1) {
519 if (errno
== ENOENT
|| errno
== EINVAL
) {
521 * Doesn't exist, or not a symlink; assume that
522 * means it's not a mac80211 device.
527 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
528 "%s: Can't readlink %s: %s", device
, pathstr
,
534 phydev_path
[bytes_read
] = '\0';
538 #ifdef HAVE_LIBNL_SOCKETS
539 #define get_nl_errmsg nl_geterror
541 /* libnl 2.x compatibility code */
543 #define nl_sock nl_handle
545 static inline struct nl_handle
*
546 nl_socket_alloc(void)
548 return nl_handle_alloc();
552 nl_socket_free(struct nl_handle
*h
)
554 nl_handle_destroy(h
);
557 #define get_nl_errmsg strerror
560 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
562 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
568 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
569 #endif /* !HAVE_LIBNL_SOCKETS */
571 struct nl80211_state
{
572 struct nl_sock
*nl_sock
;
573 struct nl_cache
*nl_cache
;
574 struct genl_family
*nl80211
;
578 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
582 state
->nl_sock
= nl_socket_alloc();
583 if (!state
->nl_sock
) {
584 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
585 "%s: failed to allocate netlink handle", device
);
589 if (genl_connect(state
->nl_sock
)) {
590 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
591 "%s: failed to connect to generic netlink", device
);
592 goto out_handle_destroy
;
595 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
597 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
598 "%s: failed to allocate generic netlink cache: %s",
599 device
, get_nl_errmsg(-err
));
600 goto out_handle_destroy
;
603 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
604 if (!state
->nl80211
) {
605 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
606 "%s: nl80211 not found", device
);
613 nl_cache_free(state
->nl_cache
);
615 nl_socket_free(state
->nl_sock
);
620 nl80211_cleanup(struct nl80211_state
*state
)
622 genl_family_put(state
->nl80211
);
623 nl_cache_free(state
->nl_cache
);
624 nl_socket_free(state
->nl_sock
);
628 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
629 const char *device
, const char *mondevice
)
635 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
641 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
642 "%s: failed to allocate netlink msg", device
);
646 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
647 0, NL80211_CMD_NEW_INTERFACE
, 0);
648 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
649 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
650 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
652 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
654 #if defined HAVE_LIBNL_NLE
655 if (err
== -NLE_FAILURE
) {
657 if (err
== -ENFILE
) {
660 * Device not available; our caller should just
661 * keep trying. (libnl 2.x maps ENFILE to
662 * NLE_FAILURE; it can also map other errors
663 * to that, but there's not much we can do
670 * Real failure, not just "that device is not
673 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
674 "%s: nl_send_auto_complete failed adding %s interface: %s",
675 device
, mondevice
, get_nl_errmsg(-err
));
680 err
= nl_wait_for_ack(state
->nl_sock
);
682 #if defined HAVE_LIBNL_NLE
683 if (err
== -NLE_FAILURE
) {
685 if (err
== -ENFILE
) {
688 * Device not available; our caller should just
689 * keep trying. (libnl 2.x maps ENFILE to
690 * NLE_FAILURE; it can also map other errors
691 * to that, but there's not much we can do
698 * Real failure, not just "that device is not
701 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
702 "%s: nl_wait_for_ack failed adding %s interface: %s",
703 device
, mondevice
, get_nl_errmsg(-err
));
716 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
717 "%s: nl_put failed adding %s interface",
724 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
725 const char *device
, const char *mondevice
)
731 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
737 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
738 "%s: failed to allocate netlink msg", device
);
742 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
743 0, NL80211_CMD_DEL_INTERFACE
, 0);
744 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
746 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
748 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
749 "%s: nl_send_auto_complete failed deleting %s interface: %s",
750 device
, mondevice
, get_nl_errmsg(-err
));
754 err
= nl_wait_for_ack(state
->nl_sock
);
756 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
757 "%s: nl_wait_for_ack failed adding %s interface: %s",
758 device
, mondevice
, get_nl_errmsg(-err
));
770 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
771 "%s: nl_put failed deleting %s interface",
778 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
780 struct pcap_linux
*handlep
= handle
->priv
;
782 char phydev_path
[PATH_MAX
+1];
783 struct nl80211_state nlstate
;
788 * Is this a mac80211 device?
790 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
792 return ret
; /* error */
794 return 0; /* no error, but not mac80211 device */
797 * XXX - is this already a monN device?
799 * Is that determined by old Wireless Extensions ioctls?
803 * OK, it's apparently a mac80211 device.
804 * Try to find an unused monN device for it.
806 ret
= nl80211_init(handle
, &nlstate
, device
);
809 for (n
= 0; n
< UINT_MAX
; n
++) {
813 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
815 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
816 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
818 handlep
->mondevice
= strdup(mondevice
);
823 * Hard failure. Just return ret; handle->errbuf
824 * has already been set.
826 nl80211_cleanup(&nlstate
);
831 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
832 "%s: No free monN interfaces", device
);
833 nl80211_cleanup(&nlstate
);
840 * Sleep for .1 seconds.
843 delay
.tv_nsec
= 500000000;
844 nanosleep(&delay
, NULL
);
848 * If we haven't already done so, arrange to have
849 * "pcap_close_all()" called when we exit.
851 if (!pcap_do_addexit(handle
)) {
853 * "atexit()" failed; don't put the interface
854 * in rfmon mode, just give up.
856 return PCAP_ERROR_RFMON_NOTSUP
;
860 * Now configure the monitor interface up.
862 memset(&ifr
, 0, sizeof(ifr
));
863 strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
864 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
865 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
866 "%s: Can't get flags for %s: %s", device
,
867 handlep
->mondevice
, strerror(errno
));
868 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
870 nl80211_cleanup(&nlstate
);
873 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
874 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
875 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
876 "%s: Can't set flags for %s: %s", device
,
877 handlep
->mondevice
, strerror(errno
));
878 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
880 nl80211_cleanup(&nlstate
);
885 * Success. Clean up the libnl state.
887 nl80211_cleanup(&nlstate
);
890 * Note that we have to delete the monitor device when we close
893 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
896 * Add this to the list of pcaps to close when we exit.
898 pcap_add_to_pcaps_to_close(handle
);
902 #endif /* HAVE_LIBNL */
905 pcap_can_set_rfmon_linux(pcap_t
*handle
)
908 char phydev_path
[PATH_MAX
+1];
911 #ifdef IW_MODE_MONITOR
916 if (strcmp(handle
->opt
.source
, "any") == 0) {
918 * Monitor mode makes no sense on the "any" device.
925 * Bleah. There doesn't seem to be a way to ask a mac80211
926 * device, through libnl, whether it supports monitor mode;
927 * we'll just check whether the device appears to be a
928 * mac80211 device and, if so, assume the device supports
931 * wmaster devices don't appear to support the Wireless
932 * Extensions, but we can create a mon device for a
933 * wmaster device, so we don't bother checking whether
934 * a mac80211 device supports the Wireless Extensions.
936 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
939 return ret
; /* error */
941 return 1; /* mac80211 device */
944 #ifdef IW_MODE_MONITOR
946 * Bleah. There doesn't appear to be an ioctl to use to ask
947 * whether a device supports monitor mode; we'll just do
948 * SIOCGIWMODE and, if it succeeds, assume the device supports
951 * Open a socket on which to attempt to get the mode.
952 * (We assume that if we have Wireless Extensions support
953 * we also have PF_PACKET support.)
955 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
957 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
958 "socket: %s", pcap_strerror(errno
));
963 * Attempt to get the current mode.
965 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
966 sizeof ireq
.ifr_ifrn
.ifrn_name
);
967 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
969 * Well, we got the mode; assume we can set it.
974 if (errno
== ENODEV
) {
975 /* The device doesn't even exist. */
976 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
977 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
979 return PCAP_ERROR_NO_SUCH_DEVICE
;
987 * Grabs the number of dropped packets by the interface from /proc/net/dev.
989 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
990 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
992 * Or can we get them in binary form from netlink?
995 linux_if_drops(const char * if_name
)
1000 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1001 long int dropped_pkts
= 0;
1003 file
= fopen("/proc/net/dev", "r");
1007 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1009 /* search for 'bytes' -- if its in there, then
1010 that means we need to grab the fourth field. otherwise
1011 grab the third field. */
1012 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1014 field_to_convert
= 4;
1018 /* find iface and make sure it actually matches -- space before the name and : after it */
1019 if ((bufptr
= strstr(buffer
, if_name
)) &&
1020 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1021 *(bufptr
+ if_name_sz
) == ':')
1023 bufptr
= bufptr
+ if_name_sz
+ 1;
1025 /* grab the nth field from it */
1026 while( --field_to_convert
&& *bufptr
!= '\0')
1028 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1029 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1032 /* get rid of any final spaces */
1033 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1035 if (*bufptr
!= '\0')
1036 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1043 return dropped_pkts
;
1048 * With older kernels promiscuous mode is kind of interesting because we
1049 * have to reset the interface before exiting. The problem can't really
1050 * be solved without some daemon taking care of managing usage counts.
1051 * If we put the interface into promiscuous mode, we set a flag indicating
1052 * that we must take it out of that mode when the interface is closed,
1053 * and, when closing the interface, if that flag is set we take it out
1054 * of promiscuous mode.
1056 * Even with newer kernels, we have the same issue with rfmon mode.
1059 static void pcap_cleanup_linux( pcap_t
*handle
)
1061 struct pcap_linux
*handlep
= handle
->priv
;
1064 struct nl80211_state nlstate
;
1066 #endif /* HAVE_LIBNL */
1067 #ifdef IW_MODE_MONITOR
1070 #endif /* IW_MODE_MONITOR */
1072 if (handlep
->must_do_on_close
!= 0) {
1074 * There's something we have to do when closing this
1077 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1079 * We put the interface into promiscuous mode;
1080 * take it out of promiscuous mode.
1082 * XXX - if somebody else wants it in promiscuous
1083 * mode, this code cannot know that, so it'll take
1084 * it out of promiscuous mode. That's not fixable
1085 * in 2.0[.x] kernels.
1087 memset(&ifr
, 0, sizeof(ifr
));
1088 strlcpy(ifr
.ifr_name
, handlep
->device
,
1089 sizeof(ifr
.ifr_name
));
1090 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1092 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1093 "Please adjust manually.\n"
1094 "Hint: This can't happen with Linux >= 2.2.0.\n",
1095 handlep
->device
, strerror(errno
));
1097 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1099 * Promiscuous mode is currently on;
1102 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1103 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1106 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1107 "Please adjust manually.\n"
1108 "Hint: This can't happen with Linux >= 2.2.0.\n",
1117 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1118 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1120 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1121 handlep
->device
, handlep
->mondevice
);
1122 nl80211_cleanup(&nlstate
);
1126 "Can't delete monitor interface %s (%s).\n"
1127 "Please delete manually.\n",
1128 handlep
->mondevice
, handle
->errbuf
);
1131 #endif /* HAVE_LIBNL */
1133 #ifdef IW_MODE_MONITOR
1134 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1136 * We put the interface into rfmon mode;
1137 * take it out of rfmon mode.
1139 * XXX - if somebody else wants it in rfmon
1140 * mode, this code cannot know that, so it'll take
1141 * it out of rfmon mode.
1145 * First, take the interface down if it's up;
1146 * otherwise, we might get EBUSY.
1147 * If we get errors, just drive on and print
1148 * a warning if we can't restore the mode.
1151 memset(&ifr
, 0, sizeof(ifr
));
1152 strlcpy(ifr
.ifr_name
, handlep
->device
,
1153 sizeof(ifr
.ifr_name
));
1154 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1155 if (ifr
.ifr_flags
& IFF_UP
) {
1156 oldflags
= ifr
.ifr_flags
;
1157 ifr
.ifr_flags
&= ~IFF_UP
;
1158 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1159 oldflags
= 0; /* didn't set, don't restore */
1164 * Now restore the mode.
1166 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1167 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1168 ireq
.u
.mode
= handlep
->oldmode
;
1169 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1171 * Scientist, you've failed.
1174 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1175 "Please adjust manually.\n",
1176 handlep
->device
, strerror(errno
));
1180 * Now bring the interface back up if we brought
1183 if (oldflags
!= 0) {
1184 ifr
.ifr_flags
= oldflags
;
1185 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1187 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1188 "Please adjust manually.\n",
1189 handlep
->device
, strerror(errno
));
1193 #endif /* IW_MODE_MONITOR */
1196 * Take this pcap out of the list of pcaps for which we
1197 * have to take the interface out of some mode.
1199 pcap_remove_from_pcaps_to_close(handle
);
1202 if (handlep
->mondevice
!= NULL
) {
1203 free(handlep
->mondevice
);
1204 handlep
->mondevice
= NULL
;
1206 if (handlep
->device
!= NULL
) {
1207 free(handlep
->device
);
1208 handlep
->device
= NULL
;
1210 pcap_cleanup_live_common(handle
);
1214 * Get a handle for a live capture from the given device. You can
1215 * pass NULL as device to get all packages (without link level
1216 * information of course). If you pass 1 as promisc the interface
1217 * will be set to promiscous mode (XXX: I think this usage should
1218 * be deprecated and functions be added to select that later allow
1219 * modification of that values -- Torsten).
1222 pcap_activate_linux(pcap_t
*handle
)
1224 struct pcap_linux
*handlep
= handle
->priv
;
1230 device
= handle
->opt
.source
;
1233 * Make sure the name we were handed will fit into the ioctls we
1234 * might perform on the device; if not, return a "No such device"
1235 * indication, as the Linux kernel shouldn't support creating
1236 * a device whose name won't fit into those ioctls.
1238 * "Will fit" means "will fit, complete with a null terminator",
1239 * so if the length, which does *not* include the null terminator,
1240 * is greater than *or equal to* the size of the field into which
1241 * we'll be copying it, that won't fit.
1243 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1244 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1248 handle
->inject_op
= pcap_inject_linux
;
1249 handle
->setfilter_op
= pcap_setfilter_linux
;
1250 handle
->setdirection_op
= pcap_setdirection_linux
;
1251 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1252 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1253 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1254 handle
->cleanup_op
= pcap_cleanup_linux
;
1255 handle
->read_op
= pcap_read_linux
;
1256 handle
->stats_op
= pcap_stats_linux
;
1259 * The "any" device is a special device which causes us not
1260 * to bind to a particular device and thus to look at all
1263 if (strcmp(device
, "any") == 0) {
1264 if (handle
->opt
.promisc
) {
1265 handle
->opt
.promisc
= 0;
1266 /* Just a warning. */
1267 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1268 "Promiscuous mode not supported on the \"any\" device");
1269 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1273 handlep
->device
= strdup(device
);
1274 if (handlep
->device
== NULL
) {
1275 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1276 pcap_strerror(errno
) );
1280 /* copy timeout value */
1281 handlep
->timeout
= handle
->opt
.timeout
;
1284 * If we're in promiscuous mode, then we probably want
1285 * to see when the interface drops packets too, so get an
1286 * initial count from /proc/net/dev
1288 if (handle
->opt
.promisc
)
1289 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1292 * Current Linux kernels use the protocol family PF_PACKET to
1293 * allow direct access to all packets on the network while
1294 * older kernels had a special socket type SOCK_PACKET to
1295 * implement this feature.
1296 * While this old implementation is kind of obsolete we need
1297 * to be compatible with older kernels for a while so we are
1298 * trying both methods with the newer method preferred.
1300 ret
= activate_new(handle
);
1303 * Fatal error with the new way; just fail.
1304 * ret has the error return; if it's PCAP_ERROR,
1305 * handle->errbuf has been set appropriately.
1313 * Try to use memory-mapped access.
1315 switch (activate_mmap(handle
, &status
)) {
1319 * We succeeded. status has been
1320 * set to the status to return,
1321 * which might be 0, or might be
1322 * a PCAP_WARNING_ value.
1328 * Kernel doesn't support it - just continue
1329 * with non-memory-mapped access.
1335 * We failed to set up to use it, or the kernel
1336 * supports it, but we failed to enable it.
1337 * ret has been set to the error status to
1338 * return and, if it's PCAP_ERROR, handle->errbuf
1339 * contains the error message.
1345 else if (ret
== 0) {
1346 /* Non-fatal error; try old way */
1347 if ((ret
= activate_old(handle
)) != 1) {
1349 * Both methods to open the packet socket failed.
1350 * Tidy up and report our failure (handle->errbuf
1351 * is expected to be set by the functions above).
1359 * We set up the socket, but not with memory-mapped access.
1361 if (handle
->opt
.buffer_size
!= 0) {
1363 * Set the socket buffer size to the specified value.
1365 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1366 &handle
->opt
.buffer_size
,
1367 sizeof(handle
->opt
.buffer_size
)) == -1) {
1368 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1369 "SO_RCVBUF: %s", pcap_strerror(errno
));
1370 status
= PCAP_ERROR
;
1375 /* Allocate the buffer */
1377 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1378 if (!handle
->buffer
) {
1379 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1380 "malloc: %s", pcap_strerror(errno
));
1381 status
= PCAP_ERROR
;
1386 * "handle->fd" is a socket, so "select()" and "poll()"
1387 * should work on it.
1389 handle
->selectable_fd
= handle
->fd
;
1394 pcap_cleanup_linux(handle
);
1399 * Read at most max_packets from the capture stream and call the callback
1400 * for each of them. Returns the number of packets handled or -1 if an
1404 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1407 * Currently, on Linux only one packet is delivered per read,
1410 return pcap_read_packet(handle
, callback
, user
);
1414 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1416 handle
->linktype
= dlt
;
1421 * linux_check_direction()
1423 * Do checks based on packet direction.
1426 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1428 struct pcap_linux
*handlep
= handle
->priv
;
1430 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1433 * If this is from the loopback device, reject it;
1434 * we'll see the packet as an incoming packet as well,
1435 * and we don't want to see it twice.
1437 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1441 * If the user only wants incoming packets, reject it.
1443 if (handle
->direction
== PCAP_D_IN
)
1448 * If the user only wants outgoing packets, reject it.
1450 if (handle
->direction
== PCAP_D_OUT
)
1457 * Read a packet from the socket calling the handler provided by
1458 * the user. Returns the number of packets received or -1 if an
1462 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1464 struct pcap_linux
*handlep
= handle
->priv
;
1467 #ifdef HAVE_PF_PACKET_SOCKETS
1468 struct sockaddr_ll from
;
1469 struct sll_header
*hdrp
;
1471 struct sockaddr from
;
1473 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1476 struct cmsghdr
*cmsg
;
1478 struct cmsghdr cmsg
;
1479 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1481 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1483 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1484 int packet_len
, caplen
;
1485 struct pcap_pkthdr pcap_header
;
1487 #ifdef HAVE_PF_PACKET_SOCKETS
1489 * If this is a cooked device, leave extra room for a
1490 * fake packet header.
1492 if (handlep
->cooked
)
1493 offset
= SLL_HDR_LEN
;
1498 * This system doesn't have PF_PACKET sockets, so it doesn't
1499 * support cooked devices.
1505 * Receive a single packet from the kernel.
1506 * We ignore EINTR, as that might just be due to a signal
1507 * being delivered - if the signal should interrupt the
1508 * loop, the signal handler should call pcap_breakloop()
1509 * to set handle->break_loop (we ignore it on other
1510 * platforms as well).
1511 * We also ignore ENETDOWN, so that we can continue to
1512 * capture traffic if the interface goes down and comes
1513 * back up again; comments in the kernel indicate that
1514 * we'll just block waiting for packets if we try to
1515 * receive from a socket that delivered ENETDOWN, and,
1516 * if we're using a memory-mapped buffer, we won't even
1517 * get notified of "network down" events.
1519 bp
= handle
->buffer
+ handle
->offset
;
1521 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1522 msg
.msg_name
= &from
;
1523 msg
.msg_namelen
= sizeof(from
);
1526 msg
.msg_control
= &cmsg_buf
;
1527 msg
.msg_controllen
= sizeof(cmsg_buf
);
1530 iov
.iov_len
= handle
->bufsize
- offset
;
1531 iov
.iov_base
= bp
+ offset
;
1532 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1536 * Has "pcap_breakloop()" been called?
1538 if (handle
->break_loop
) {
1540 * Yes - clear the flag that indicates that it has,
1541 * and return PCAP_ERROR_BREAK as an indication that
1542 * we were told to break out of the loop.
1544 handle
->break_loop
= 0;
1545 return PCAP_ERROR_BREAK
;
1548 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1549 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1550 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1551 fromlen
= sizeof(from
);
1552 packet_len
= recvfrom(
1553 handle
->fd
, bp
+ offset
,
1554 handle
->bufsize
- offset
, MSG_TRUNC
,
1555 (struct sockaddr
*) &from
, &fromlen
);
1556 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1557 } while (packet_len
== -1 && errno
== EINTR
);
1559 /* Check if an error occured */
1561 if (packet_len
== -1) {
1565 return 0; /* no packet there */
1569 * The device on which we're capturing went away.
1571 * XXX - we should really return
1572 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1573 * etc. aren't defined to return that.
1575 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1576 "The interface went down");
1580 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1581 "recvfrom: %s", pcap_strerror(errno
));
1586 #ifdef HAVE_PF_PACKET_SOCKETS
1587 if (!handlep
->sock_packet
) {
1589 * Unfortunately, there is a window between socket() and
1590 * bind() where the kernel may queue packets from any
1591 * interface. If we're bound to a particular interface,
1592 * discard packets not from that interface.
1594 * (If socket filters are supported, we could do the
1595 * same thing we do when changing the filter; however,
1596 * that won't handle packet sockets without socket
1597 * filter support, and it's a bit more complicated.
1598 * It would save some instructions per packet, however.)
1600 if (handlep
->ifindex
!= -1 &&
1601 from
.sll_ifindex
!= handlep
->ifindex
)
1605 * Do checks based on packet direction.
1606 * We can only do this if we're using PF_PACKET; the
1607 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1608 * which lacks the relevant packet type information.
1610 if (!linux_check_direction(handle
, &from
))
1615 #ifdef HAVE_PF_PACKET_SOCKETS
1617 * If this is a cooked device, fill in the fake packet header.
1619 if (handlep
->cooked
) {
1621 * Add the length of the fake header to the length
1622 * of packet data we read.
1624 packet_len
+= SLL_HDR_LEN
;
1626 hdrp
= (struct sll_header
*)bp
;
1627 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1628 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1629 hdrp
->sll_halen
= htons(from
.sll_halen
);
1630 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1631 (from
.sll_halen
> SLL_ADDRLEN
) ?
1634 hdrp
->sll_protocol
= from
.sll_protocol
;
1637 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1638 if (handlep
->vlan_offset
!= -1) {
1639 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1640 struct tpacket_auxdata
*aux
;
1642 struct vlan_tag
*tag
;
1644 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1645 cmsg
->cmsg_level
!= SOL_PACKET
||
1646 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1649 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1650 #if defined(TP_STATUS_VLAN_VALID)
1651 if ((aux
->tp_vlan_tci
== 0) && !(aux
->tp_status
& TP_STATUS_VLAN_VALID
))
1653 if (aux
->tp_vlan_tci
== 0) /* this is ambigious but without the
1654 TP_STATUS_VLAN_VALID flag, there is
1655 nothing that we can do */
1659 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1660 if (len
< (unsigned int) handlep
->vlan_offset
)
1664 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1666 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1667 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1668 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1670 packet_len
+= VLAN_TAG_LEN
;
1673 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1674 #endif /* HAVE_PF_PACKET_SOCKETS */
1677 * XXX: According to the kernel source we should get the real
1678 * packet len if calling recvfrom with MSG_TRUNC set. It does
1679 * not seem to work here :(, but it is supported by this code
1681 * To be honest the code RELIES on that feature so this is really
1682 * broken with 2.2.x kernels.
1683 * I spend a day to figure out what's going on and I found out
1684 * that the following is happening:
1686 * The packet comes from a random interface and the packet_rcv
1687 * hook is called with a clone of the packet. That code inserts
1688 * the packet into the receive queue of the packet socket.
1689 * If a filter is attached to that socket that filter is run
1690 * first - and there lies the problem. The default filter always
1691 * cuts the packet at the snaplen:
1696 * So the packet filter cuts down the packet. The recvfrom call
1697 * says "hey, it's only 68 bytes, it fits into the buffer" with
1698 * the result that we don't get the real packet length. This
1699 * is valid at least until kernel 2.2.17pre6.
1701 * We currently handle this by making a copy of the filter
1702 * program, fixing all "ret" instructions with non-zero
1703 * operands to have an operand of MAXIMUM_SNAPLEN so that the
1704 * filter doesn't truncate the packet, and supplying that modified
1705 * filter to the kernel.
1708 caplen
= packet_len
;
1709 if (caplen
> handle
->snapshot
)
1710 caplen
= handle
->snapshot
;
1712 /* Run the packet filter if not using kernel filter */
1713 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
1714 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1715 packet_len
, caplen
) == 0)
1717 /* rejected by filter */
1722 /* Fill in our own header data */
1724 /* get timestamp for this packet */
1725 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1726 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
1727 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
1728 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1729 "SIOCGSTAMPNS: %s", pcap_strerror(errno
));
1735 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1736 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1737 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1742 pcap_header
.caplen
= caplen
;
1743 pcap_header
.len
= packet_len
;
1748 * Arguably, we should count them before we check the filter,
1749 * as on many other platforms "ps_recv" counts packets
1750 * handed to the filter rather than packets that passed
1751 * the filter, but if filtering is done in the kernel, we
1752 * can't get a count of packets that passed the filter,
1753 * and that would mean the meaning of "ps_recv" wouldn't
1754 * be the same on all Linux systems.
1756 * XXX - it's not the same on all systems in any case;
1757 * ideally, we should have a "get the statistics" call
1758 * that supplies more counts and indicates which of them
1759 * it supplies, so that we supply a count of packets
1760 * handed to the filter only on platforms where that
1761 * information is available.
1763 * We count them here even if we can get the packet count
1764 * from the kernel, as we can only determine at run time
1765 * whether we'll be able to get it from the kernel (if
1766 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1767 * the kernel, but if it is defined, the library might
1768 * have been built with a 2.4 or later kernel, but we
1769 * might be running on a 2.2[.x] kernel without Alexey
1770 * Kuznetzov's turbopacket patches, and thus the kernel
1771 * might not be able to supply those statistics). We
1772 * could, I guess, try, when opening the socket, to get
1773 * the statistics, and if we can not increment the count
1774 * here, but it's not clear that always incrementing
1775 * the count is more expensive than always testing a flag
1778 * We keep the count in "handlep->packets_read", and use that
1779 * for "ps_recv" if we can't get the statistics from the kernel.
1780 * We do that because, if we *can* get the statistics from
1781 * the kernel, we use "handlep->stat.ps_recv" and
1782 * "handlep->stat.ps_drop" as running counts, as reading the
1783 * statistics from the kernel resets the kernel statistics,
1784 * and if we directly increment "handlep->stat.ps_recv" here,
1785 * that means it will count packets *twice* on systems where
1786 * we can get kernel statistics - once here, and once in
1787 * pcap_stats_linux().
1789 handlep
->packets_read
++;
1791 /* Call the user supplied callback function */
1792 callback(userdata
, &pcap_header
, bp
);
1798 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1800 struct pcap_linux
*handlep
= handle
->priv
;
1803 #ifdef HAVE_PF_PACKET_SOCKETS
1804 if (!handlep
->sock_packet
) {
1805 /* PF_PACKET socket */
1806 if (handlep
->ifindex
== -1) {
1808 * We don't support sending on the "any" device.
1810 strlcpy(handle
->errbuf
,
1811 "Sending packets isn't supported on the \"any\" device",
1816 if (handlep
->cooked
) {
1818 * We don't support sending on the "any" device.
1820 * XXX - how do you send on a bound cooked-mode
1822 * Is a "sendto()" required there?
1824 strlcpy(handle
->errbuf
,
1825 "Sending packets isn't supported in cooked mode",
1832 ret
= send(handle
->fd
, buf
, size
, 0);
1834 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1835 pcap_strerror(errno
));
1842 * Get the statistics for the given packet capture handle.
1843 * Reports the number of dropped packets iff the kernel supports
1844 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1845 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1846 * patches); otherwise, that information isn't available, and we lie
1847 * and report 0 as the count of dropped packets.
1850 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1852 struct pcap_linux
*handlep
= handle
->priv
;
1853 #ifdef HAVE_TPACKET_STATS
1854 #ifdef HAVE_TPACKET3
1856 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
1857 * stuff at the end of a struct tpacket_stats_v3 will not
1858 * be filled in, and we don't look at it so this is OK even
1859 * for those sockets. In addition, the PF_PACKET socket
1860 * code in the kernel only uses the length parameter to
1861 * compute how much data to copy out and to indicate how
1862 * much data was copied out, so it's OK to base it on the
1863 * size of a struct tpacket_stats.
1865 * XXX - it's probably OK, in fact, to just use a
1866 * struct tpacket_stats for V3 sockets, as we don't
1867 * care about the tp_freeze_q_cnt stat.
1869 struct tpacket_stats_v3 kstats
;
1870 #else /* HAVE_TPACKET3 */
1871 struct tpacket_stats kstats
;
1872 #endif /* HAVE_TPACKET3 */
1873 socklen_t len
= sizeof (struct tpacket_stats
);
1874 #endif /* HAVE_TPACKET_STATS */
1876 long if_dropped
= 0;
1879 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1881 if (handle
->opt
.promisc
)
1883 if_dropped
= handlep
->proc_dropped
;
1884 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1885 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
1888 #ifdef HAVE_TPACKET_STATS
1890 * Try to get the packet counts from the kernel.
1892 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1893 &kstats
, &len
) > -1) {
1895 * On systems where the PACKET_STATISTICS "getsockopt()"
1896 * argument is supported on PF_PACKET sockets:
1898 * "ps_recv" counts only packets that *passed* the
1899 * filter, not packets that didn't pass the filter.
1900 * This includes packets later dropped because we
1901 * ran out of buffer space.
1903 * "ps_drop" counts packets dropped because we ran
1904 * out of buffer space. It doesn't count packets
1905 * dropped by the interface driver. It counts only
1906 * packets that passed the filter.
1908 * See above for ps_ifdrop.
1910 * Both statistics include packets not yet read from
1911 * the kernel by libpcap, and thus not yet seen by
1914 * In "linux/net/packet/af_packet.c", at least in the
1915 * 2.4.9 kernel, "tp_packets" is incremented for every
1916 * packet that passes the packet filter *and* is
1917 * successfully queued on the socket; "tp_drops" is
1918 * incremented for every packet dropped because there's
1919 * not enough free space in the socket buffer.
1921 * When the statistics are returned for a PACKET_STATISTICS
1922 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1923 * so that "tp_packets" counts all packets handed to
1924 * the PF_PACKET socket, including packets dropped because
1925 * there wasn't room on the socket buffer - but not
1926 * including packets that didn't pass the filter.
1928 * In the BSD BPF, the count of received packets is
1929 * incremented for every packet handed to BPF, regardless
1930 * of whether it passed the filter.
1932 * We can't make "pcap_stats()" work the same on both
1933 * platforms, but the best approximation is to return
1934 * "tp_packets" as the count of packets and "tp_drops"
1935 * as the count of drops.
1937 * Keep a running total because each call to
1938 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1939 * resets the counters to zero.
1941 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1942 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1943 *stats
= handlep
->stat
;
1949 * If the error was EOPNOTSUPP, fall through, so that
1950 * if you build the library on a system with
1951 * "struct tpacket_stats" and run it on a system
1952 * that doesn't, it works as it does if the library
1953 * is built on a system without "struct tpacket_stats".
1955 if (errno
!= EOPNOTSUPP
) {
1956 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1957 "pcap_stats: %s", pcap_strerror(errno
));
1963 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1964 * is not supported on PF_PACKET sockets:
1966 * "ps_recv" counts only packets that *passed* the filter,
1967 * not packets that didn't pass the filter. It does not
1968 * count packets dropped because we ran out of buffer
1971 * "ps_drop" is not supported.
1973 * "ps_ifdrop" is supported. It will return the number
1974 * of drops the interface reports in /proc/net/dev,
1975 * if that is available.
1977 * "ps_recv" doesn't include packets not yet read from
1978 * the kernel by libpcap.
1980 * We maintain the count of packets processed by libpcap in
1981 * "handlep->packets_read", for reasons described in the comment
1982 * at the end of pcap_read_packet(). We have no idea how many
1983 * packets were dropped by the kernel buffers -- but we know
1984 * how many the interface dropped, so we can return that.
1987 stats
->ps_recv
= handlep
->packets_read
;
1989 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
1994 add_linux_if(pcap_if_t
**devlistp
, const char *ifname
, int fd
, char *errbuf
)
1997 char name
[512]; /* XXX - pick a size */
1999 struct ifreq ifrflags
;
2002 * Get the interface name.
2006 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2009 * This could be the separator between a
2010 * name and an alias number, or it could be
2011 * the separator between a name with no
2012 * alias number and the next field.
2014 * If there's a colon after digits, it
2015 * separates the name and the alias number,
2016 * otherwise it separates the name and the
2020 while (isascii(*p
) && isdigit(*p
))
2024 * That was the next field,
2025 * not the alias number.
2036 * Get the flags for this interface.
2038 strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2039 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2040 if (errno
== ENXIO
|| errno
== ENODEV
)
2041 return (0); /* device doesn't actually exist - ignore it */
2042 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2043 "SIOCGIFFLAGS: %.*s: %s",
2044 (int)sizeof(ifrflags
.ifr_name
),
2046 pcap_strerror(errno
));
2051 * Add an entry for this interface, with no addresses.
2053 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2065 * Get from "/sys/class/net" all interfaces listed there; if they're
2066 * already in the list of interfaces we have, that won't add another
2067 * instance, but if they're not, that'll add them.
2069 * We don't bother getting any addresses for them; it appears you can't
2070 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2071 * although some other types of addresses can be fetched with SIOCGIFADDR,
2072 * we don't bother with them for now.
2074 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2075 * the list of interfaces as is, and return 0, so that we can try
2076 * scanning /proc/net/dev.
2078 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2081 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
2083 DIR *sys_class_net_d
;
2086 char subsystem_path
[PATH_MAX
+1];
2090 sys_class_net_d
= opendir("/sys/class/net");
2091 if (sys_class_net_d
== NULL
) {
2093 * Don't fail if it doesn't exist at all.
2095 if (errno
== ENOENT
)
2099 * Fail if we got some other error.
2101 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2102 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
2107 * Create a socket from which to fetch interface information.
2109 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2111 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2112 "socket: %s", pcap_strerror(errno
));
2113 (void)closedir(sys_class_net_d
);
2119 ent
= readdir(sys_class_net_d
);
2122 * Error or EOF; if errno != 0, it's an error.
2128 * Ignore "." and "..".
2130 if (strcmp(ent
->d_name
, ".") == 0 ||
2131 strcmp(ent
->d_name
, "..") == 0)
2135 * Ignore plain files; they do not have subdirectories
2136 * and thus have no attributes.
2138 if (ent
->d_type
== DT_REG
)
2142 * Is there an "ifindex" file under that name?
2143 * (We don't care whether it's a directory or
2144 * a symlink; older kernels have directories
2145 * for devices, newer kernels have symlinks to
2148 snprintf(subsystem_path
, sizeof subsystem_path
,
2149 "/sys/class/net/%s/ifindex", ent
->d_name
);
2150 if (lstat(subsystem_path
, &statb
) != 0) {
2152 * Stat failed. Either there was an error
2153 * other than ENOENT, and we don't know if
2154 * this is an interface, or it's ENOENT,
2155 * and either some part of "/sys/class/net/{if}"
2156 * disappeared, in which case it probably means
2157 * the interface disappeared, or there's no
2158 * "ifindex" file, which means it's not a
2159 * network interface.
2165 * Attempt to add the interface.
2167 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2175 * Well, we didn't fail for any other reason; did we
2176 * fail due to an error reading the directory?
2179 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2180 "Error reading /sys/class/net: %s",
2181 pcap_strerror(errno
));
2187 (void)closedir(sys_class_net_d
);
2192 * Get from "/proc/net/dev" all interfaces listed there; if they're
2193 * already in the list of interfaces we have, that won't add another
2194 * instance, but if they're not, that'll add them.
2196 * See comments from scan_sys_class_net().
2199 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2208 proc_net_f
= fopen("/proc/net/dev", "r");
2209 if (proc_net_f
== NULL
) {
2211 * Don't fail if it doesn't exist at all.
2213 if (errno
== ENOENT
)
2217 * Fail if we got some other error.
2219 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2220 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2225 * Create a socket from which to fetch interface information.
2227 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2229 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2230 "socket: %s", pcap_strerror(errno
));
2231 (void)fclose(proc_net_f
);
2236 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2238 * Skip the first two lines - they're headers.
2246 * Skip leading white space.
2248 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2250 if (*p
== '\0' || *p
== '\n')
2251 continue; /* blank line */
2254 * Attempt to add the interface.
2256 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2264 * Well, we didn't fail for any other reason; did we
2265 * fail due to an error reading the file?
2267 if (ferror(proc_net_f
)) {
2268 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2269 "Error reading /proc/net/dev: %s",
2270 pcap_strerror(errno
));
2276 (void)fclose(proc_net_f
);
2281 * Description string for the "any" device.
2283 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2286 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2291 * Read "/sys/class/net", and add to the list of interfaces all
2292 * interfaces listed there that we don't already have, because,
2293 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2294 * and even getifaddrs() won't return information about
2295 * interfaces with no addresses, so you need to read "/sys/class/net"
2296 * to get the names of the rest of the interfaces.
2298 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2300 return (-1); /* failed */
2303 * No /sys/class/net; try reading /proc/net/dev instead.
2305 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2310 * Add the "any" device.
2312 if (pcap_add_if(alldevsp
, "any", IFF_UP
|IFF_RUNNING
,
2313 any_descr
, errbuf
) < 0)
2320 * Attach the given BPF code to the packet capture device.
2323 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2326 struct pcap_linux
*handlep
;
2327 #ifdef SO_ATTACH_FILTER
2328 struct sock_fprog fcode
;
2329 int can_filter_in_kernel
;
2336 strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2341 handlep
= handle
->priv
;
2343 /* Make our private copy of the filter */
2345 if (install_bpf_program(handle
, filter
) < 0)
2346 /* install_bpf_program() filled in errbuf */
2350 * Run user level packet filter by default. Will be overriden if
2351 * installing a kernel filter succeeds.
2353 handlep
->filter_in_userland
= 1;
2355 /* Install kernel level filter if possible */
2357 #ifdef SO_ATTACH_FILTER
2359 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2361 * fcode.len is an unsigned short for current kernel.
2362 * I have yet to see BPF-Code with that much
2363 * instructions but still it is possible. So for the
2364 * sake of correctness I added this check.
2366 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2368 fcode
.filter
= NULL
;
2369 can_filter_in_kernel
= 0;
2371 #endif /* USHRT_MAX */
2374 * Oh joy, the Linux kernel uses struct sock_fprog instead
2375 * of struct bpf_program and of course the length field is
2376 * of different size. Pointed out by Sebastian
2378 * Oh, and we also need to fix it up so that all "ret"
2379 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2380 * as the operand if we're not capturing in memory-mapped
2381 * mode, and so that, if we're in cooked mode, all memory-
2382 * reference instructions use special magic offsets in
2383 * references to the link-layer header and assume that the
2384 * link-layer payload begins at 0; "fix_program()" will do
2387 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2392 * Fatal error; just quit.
2393 * (The "default" case shouldn't happen; we
2394 * return -1 for that reason.)
2400 * The program performed checks that we can't make
2401 * work in the kernel.
2403 can_filter_in_kernel
= 0;
2408 * We have a filter that'll work in the kernel.
2410 can_filter_in_kernel
= 1;
2416 * NOTE: at this point, we've set both the "len" and "filter"
2417 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2418 * those are the only members of the "sock_fprog" structure,
2419 * so we initialize every member of that structure.
2421 * If there is anything in "fcode" that is not initialized,
2422 * it is either a field added in a later kernel, or it's
2425 * If a new field is added, this code needs to be updated
2426 * to set it correctly.
2428 * If there are no other fields, then:
2430 * if the Linux kernel looks at the padding, it's
2433 * if the Linux kernel doesn't look at the padding,
2434 * then if some tool complains that we're passing
2435 * uninitialized data to the kernel, then the tool
2436 * is buggy and needs to understand that it's just
2439 if (can_filter_in_kernel
) {
2440 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2443 * Installation succeded - using kernel filter,
2444 * so userland filtering not needed.
2446 handlep
->filter_in_userland
= 0;
2448 else if (err
== -1) /* Non-fatal error */
2451 * Print a warning if we weren't able to install
2452 * the filter for a reason other than "this kernel
2453 * isn't configured to support socket filters.
2455 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2457 "Warning: Kernel filter failed: %s\n",
2458 pcap_strerror(errno
));
2464 * If we're not using the kernel filter, get rid of any kernel
2465 * filter that might've been there before, e.g. because the
2466 * previous filter could work in the kernel, or because some other
2467 * code attached a filter to the socket by some means other than
2468 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2469 * filter out packets that would pass the new userland filter.
2471 if (handlep
->filter_in_userland
) {
2472 if (reset_kernel_filter(handle
) == -1) {
2473 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2474 "can't remove kernel filter: %s",
2475 pcap_strerror(errno
));
2476 err
= -2; /* fatal error */
2481 * Free up the copy of the filter that was made by "fix_program()".
2483 if (fcode
.filter
!= NULL
)
2489 #endif /* SO_ATTACH_FILTER */
2495 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2497 return pcap_setfilter_linux_common(handle
, filter
, 0);
2502 * Set direction flag: Which packets do we accept on a forwarding
2503 * single device? IN, OUT or both?
2506 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2508 #ifdef HAVE_PF_PACKET_SOCKETS
2509 struct pcap_linux
*handlep
= handle
->priv
;
2511 if (!handlep
->sock_packet
) {
2512 handle
->direction
= d
;
2517 * We're not using PF_PACKET sockets, so we can't determine
2518 * the direction of the packet.
2520 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2521 "Setting direction is not supported on SOCK_PACKET sockets");
2525 #ifdef HAVE_PF_PACKET_SOCKETS
2527 * Map the PACKET_ value to a LINUX_SLL_ value; we
2528 * want the same numerical value to be used in
2529 * the link-layer header even if the numerical values
2530 * for the PACKET_ #defines change, so that programs
2531 * that look at the packet type field will always be
2532 * able to handle DLT_LINUX_SLL captures.
2535 map_packet_type_to_sll_type(short int sll_pkttype
)
2537 switch (sll_pkttype
) {
2540 return htons(LINUX_SLL_HOST
);
2542 case PACKET_BROADCAST
:
2543 return htons(LINUX_SLL_BROADCAST
);
2545 case PACKET_MULTICAST
:
2546 return htons(LINUX_SLL_MULTICAST
);
2548 case PACKET_OTHERHOST
:
2549 return htons(LINUX_SLL_OTHERHOST
);
2551 case PACKET_OUTGOING
:
2552 return htons(LINUX_SLL_OUTGOING
);
2561 * Linux uses the ARP hardware type to identify the type of an
2562 * interface. pcap uses the DLT_xxx constants for this. This
2563 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2564 * constant, as arguments, and sets "handle->linktype" to the
2565 * appropriate DLT_XXX constant and sets "handle->offset" to
2566 * the appropriate value (to make "handle->offset" plus link-layer
2567 * header length be a multiple of 4, so that the link-layer payload
2568 * will be aligned on a 4-byte boundary when capturing packets).
2569 * (If the offset isn't set here, it'll be 0; add code as appropriate
2570 * for cases where it shouldn't be 0.)
2572 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2573 * in cooked mode; otherwise, we can't use cooked mode, so we have
2574 * to pick some type that works in raw mode, or fail.
2576 * Sets the link type to -1 if unable to map the type.
2578 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, const char *device
,
2581 static const char cdma_rmnet
[] = "cdma_rmnet";
2587 * For various annoying reasons having to do with DHCP
2588 * software, some versions of Android give the mobile-
2589 * phone-network interface an ARPHRD_ value of
2590 * ARPHRD_ETHER, even though the packet supplied by
2591 * that interface have no link-layer header, and begin
2592 * with an IP header, so that the ARPHRD_ value should
2595 * Detect those devices by checking the device name, and
2596 * use DLT_RAW for them.
2598 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2599 handle
->linktype
= DLT_RAW
;
2604 * This is (presumably) a real Ethernet capture; give it a
2605 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2606 * that an application can let you choose it, in case you're
2607 * capturing DOCSIS traffic that a Cisco Cable Modem
2608 * Termination System is putting out onto an Ethernet (it
2609 * doesn't put an Ethernet header onto the wire, it puts raw
2610 * DOCSIS frames out on the wire inside the low-level
2611 * Ethernet framing).
2613 * XXX - are there any sorts of "fake Ethernet" that have
2614 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2615 * a Cisco CMTS won't put traffic onto it or get traffic
2616 * bridged onto it? ISDN is handled in "activate_new()",
2617 * as we fall back on cooked mode there; are there any
2620 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2622 * If that fails, just leave the list empty.
2624 if (handle
->dlt_list
!= NULL
) {
2625 handle
->dlt_list
[0] = DLT_EN10MB
;
2626 handle
->dlt_list
[1] = DLT_DOCSIS
;
2627 handle
->dlt_count
= 2;
2631 case ARPHRD_METRICOM
:
2632 case ARPHRD_LOOPBACK
:
2633 handle
->linktype
= DLT_EN10MB
;
2638 handle
->linktype
= DLT_EN3MB
;
2642 handle
->linktype
= DLT_AX25_KISS
;
2646 handle
->linktype
= DLT_PRONET
;
2650 handle
->linktype
= DLT_CHAOS
;
2653 #define ARPHRD_CAN 280
2656 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2659 #ifndef ARPHRD_IEEE802_TR
2660 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2662 case ARPHRD_IEEE802_TR
:
2663 case ARPHRD_IEEE802
:
2664 handle
->linktype
= DLT_IEEE802
;
2669 handle
->linktype
= DLT_ARCNET_LINUX
;
2672 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2673 #define ARPHRD_FDDI 774
2676 handle
->linktype
= DLT_FDDI
;
2680 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2681 #define ARPHRD_ATM 19
2685 * The Classical IP implementation in ATM for Linux
2686 * supports both what RFC 1483 calls "LLC Encapsulation",
2687 * in which each packet has an LLC header, possibly
2688 * with a SNAP header as well, prepended to it, and
2689 * what RFC 1483 calls "VC Based Multiplexing", in which
2690 * different virtual circuits carry different network
2691 * layer protocols, and no header is prepended to packets.
2693 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2694 * you can't use the ARPHRD_ type to find out whether
2695 * captured packets will have an LLC header, and,
2696 * while there's a socket ioctl to *set* the encapsulation
2697 * type, there's no ioctl to *get* the encapsulation type.
2701 * programs that dissect Linux Classical IP frames
2702 * would have to check for an LLC header and,
2703 * depending on whether they see one or not, dissect
2704 * the frame as LLC-encapsulated or as raw IP (I
2705 * don't know whether there's any traffic other than
2706 * IP that would show up on the socket, or whether
2707 * there's any support for IPv6 in the Linux
2708 * Classical IP code);
2710 * filter expressions would have to compile into
2711 * code that checks for an LLC header and does
2714 * Both of those are a nuisance - and, at least on systems
2715 * that support PF_PACKET sockets, we don't have to put
2716 * up with those nuisances; instead, we can just capture
2717 * in cooked mode. That's what we'll do, if we can.
2718 * Otherwise, we'll just fail.
2721 handle
->linktype
= DLT_LINUX_SLL
;
2723 handle
->linktype
= -1;
2726 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2727 #define ARPHRD_IEEE80211 801
2729 case ARPHRD_IEEE80211
:
2730 handle
->linktype
= DLT_IEEE802_11
;
2733 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2734 #define ARPHRD_IEEE80211_PRISM 802
2736 case ARPHRD_IEEE80211_PRISM
:
2737 handle
->linktype
= DLT_PRISM_HEADER
;
2740 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2741 #define ARPHRD_IEEE80211_RADIOTAP 803
2743 case ARPHRD_IEEE80211_RADIOTAP
:
2744 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2749 * Some PPP code in the kernel supplies no link-layer
2750 * header whatsoever to PF_PACKET sockets; other PPP
2751 * code supplies PPP link-layer headers ("syncppp.c");
2752 * some PPP code might supply random link-layer
2753 * headers (PPP over ISDN - there's code in Ethereal,
2754 * for example, to cope with PPP-over-ISDN captures
2755 * with which the Ethereal developers have had to cope,
2756 * heuristically trying to determine which of the
2757 * oddball link-layer headers particular packets have).
2759 * As such, we just punt, and run all PPP interfaces
2760 * in cooked mode, if we can; otherwise, we just treat
2761 * it as DLT_RAW, for now - if somebody needs to capture,
2762 * on a 2.0[.x] kernel, on PPP devices that supply a
2763 * link-layer header, they'll have to add code here to
2764 * map to the appropriate DLT_ type (possibly adding a
2765 * new DLT_ type, if necessary).
2768 handle
->linktype
= DLT_LINUX_SLL
;
2771 * XXX - handle ISDN types here? We can't fall
2772 * back on cooked sockets, so we'd have to
2773 * figure out from the device name what type of
2774 * link-layer encapsulation it's using, and map
2775 * that to an appropriate DLT_ value, meaning
2776 * we'd map "isdnN" devices to DLT_RAW (they
2777 * supply raw IP packets with no link-layer
2778 * header) and "isdY" devices to a new DLT_I4L_IP
2779 * type that has only an Ethernet packet type as
2780 * a link-layer header.
2782 * But sometimes we seem to get random crap
2783 * in the link-layer header when capturing on
2786 handle
->linktype
= DLT_RAW
;
2790 #ifndef ARPHRD_CISCO
2791 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2794 handle
->linktype
= DLT_C_HDLC
;
2797 /* Not sure if this is correct for all tunnels, but it
2801 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2809 #ifndef ARPHRD_RAWHDLC
2810 #define ARPHRD_RAWHDLC 518
2812 case ARPHRD_RAWHDLC
:
2814 #define ARPHRD_DLCI 15
2818 * XXX - should some of those be mapped to DLT_LINUX_SLL
2819 * instead? Should we just map all of them to DLT_LINUX_SLL?
2821 handle
->linktype
= DLT_RAW
;
2825 #define ARPHRD_FRAD 770
2828 handle
->linktype
= DLT_FRELAY
;
2831 case ARPHRD_LOCALTLK
:
2832 handle
->linktype
= DLT_LTALK
;
2837 * RFC 4338 defines an encapsulation for IP and ARP
2838 * packets that's compatible with the RFC 2625
2839 * encapsulation, but that uses a different ARP
2840 * hardware type and hardware addresses. That
2841 * ARP hardware type is 18; Linux doesn't define
2842 * any ARPHRD_ value as 18, but if it ever officially
2843 * supports RFC 4338-style IP-over-FC, it should define
2846 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2847 * that this will encourage its use in the future,
2848 * should Linux ever officially support RFC 4338-style
2851 handle
->linktype
= DLT_IP_OVER_FC
;
2855 #define ARPHRD_FCPP 784
2859 #define ARPHRD_FCAL 785
2863 #define ARPHRD_FCPL 786
2866 #ifndef ARPHRD_FCFABRIC
2867 #define ARPHRD_FCFABRIC 787
2869 case ARPHRD_FCFABRIC
:
2871 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2874 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2876 * and one was assigned.
2878 * In a later private discussion (spun off from a message
2879 * on the ethereal-users list) on how to get that DLT_
2880 * value in libpcap on Linux, I ended up deciding that
2881 * the best thing to do would be to have him tweak the
2882 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2883 * type, and map all those types to DLT_IP_OVER_FC:
2885 * I've checked into the libpcap and tcpdump CVS tree
2886 * support for DLT_IP_OVER_FC. In order to use that,
2887 * you'd have to modify your modified driver to return
2888 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2889 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2890 * example (the exact value doesn't matter, it can be
2891 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2894 * 11 years later, Christian Svensson wanted to map
2895 * various ARPHRD_ values to DLT_FC_2 and
2896 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2899 * https://github.com/mcr/libpcap/pull/29
2901 * There doesn't seem to be any network drivers that uses
2902 * any of the ARPHRD_FC* values for IP-over-FC, and
2903 * it's not exactly clear what the "Dummy types for non
2904 * ARP hardware" are supposed to mean (link-layer
2905 * header type? Physical network type?), so it's
2906 * not exactly clear why the ARPHRD_FC* types exist
2907 * in the first place.
2909 * For now, we map them to DLT_FC_2, and provide an
2910 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2911 * DLT_IP_OVER_FC just in case there's some old
2912 * driver out there that uses one of those types for
2913 * IP-over-FC on which somebody wants to capture
2916 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2918 * If that fails, just leave the list empty.
2920 if (handle
->dlt_list
!= NULL
) {
2921 handle
->dlt_list
[0] = DLT_FC_2
;
2922 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2923 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2924 handle
->dlt_count
= 3;
2926 handle
->linktype
= DLT_FC_2
;
2930 #define ARPHRD_IRDA 783
2933 /* Don't expect IP packet out of this interfaces... */
2934 handle
->linktype
= DLT_LINUX_IRDA
;
2935 /* We need to save packet direction for IrDA decoding,
2936 * so let's use "Linux-cooked" mode. Jean II
2938 * XXX - this is handled in activate_new(). */
2939 //handlep->cooked = 1;
2942 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2943 * is needed, please report it to <daniele@orlandi.com> */
2945 #define ARPHRD_LAPD 8445
2948 /* Don't expect IP packet out of this interfaces... */
2949 handle
->linktype
= DLT_LINUX_LAPD
;
2953 #define ARPHRD_NONE 0xFFFE
2957 * No link-layer header; packets are just IP
2958 * packets, so use DLT_RAW.
2960 handle
->linktype
= DLT_RAW
;
2963 #ifndef ARPHRD_IEEE802154
2964 #define ARPHRD_IEEE802154 804
2966 case ARPHRD_IEEE802154
:
2967 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2970 #ifndef ARPHRD_NETLINK
2971 #define ARPHRD_NETLINK 824
2973 case ARPHRD_NETLINK
:
2974 handle
->linktype
= DLT_NETLINK
;
2976 * We need to use cooked mode, so that in sll_protocol we
2977 * pick up the netlink protocol type such as NETLINK_ROUTE,
2978 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2980 * XXX - this is handled in activate_new().
2982 //handlep->cooked = 1;
2986 handle
->linktype
= -1;
2991 /* ===== Functions to interface to the newer kernels ================== */
2994 * Try to open a packet socket using the new kernel PF_PACKET interface.
2995 * Returns 1 on success, 0 on an error that means the new interface isn't
2996 * present (so the old SOCK_PACKET interface should be tried), and a
2997 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2998 * work either (so it shouldn't be tried).
3001 activate_new(pcap_t
*handle
)
3003 #ifdef HAVE_PF_PACKET_SOCKETS
3004 struct pcap_linux
*handlep
= handle
->priv
;
3005 const char *device
= handle
->opt
.source
;
3006 int is_any_device
= (strcmp(device
, "any") == 0);
3007 int sock_fd
= -1, arptype
;
3008 #ifdef HAVE_PACKET_AUXDATA
3012 struct packet_mreq mr
;
3015 * Open a socket with protocol family packet. If the
3016 * "any" device was specified, we open a SOCK_DGRAM
3017 * socket for the cooked interface, otherwise we first
3018 * try a SOCK_RAW socket for the raw interface.
3020 sock_fd
= is_any_device
?
3021 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
3022 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
3024 if (sock_fd
== -1) {
3025 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
3027 * We don't support PF_PACKET/SOCK_whatever
3028 * sockets; try the old mechanism.
3033 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
3034 pcap_strerror(errno
) );
3035 if (errno
== EPERM
|| errno
== EACCES
) {
3037 * You don't have permission to open the
3040 return PCAP_ERROR_PERM_DENIED
;
3049 /* It seems the kernel supports the new interface. */
3050 handlep
->sock_packet
= 0;
3053 * Get the interface index of the loopback device.
3054 * If the attempt fails, don't fail, just set the
3055 * "handlep->lo_ifindex" to -1.
3057 * XXX - can there be more than one device that loops
3058 * packets back, i.e. devices other than "lo"? If so,
3059 * we'd need to find them all, and have an array of
3060 * indices for them, and check all of them in
3061 * "pcap_read_packet()".
3063 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3066 * Default value for offset to align link-layer payload
3067 * on a 4-byte boundary.
3072 * What kind of frames do we have to deal with? Fall back
3073 * to cooked mode if we have an unknown interface type
3074 * or a type we know doesn't work well in raw mode.
3076 if (!is_any_device
) {
3077 /* Assume for now we don't need cooked mode. */
3078 handlep
->cooked
= 0;
3080 if (handle
->opt
.rfmon
) {
3082 * We were asked to turn on monitor mode.
3083 * Do so before we get the link-layer type,
3084 * because entering monitor mode could change
3085 * the link-layer type.
3087 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3095 * Nothing worked for turning monitor mode
3099 return PCAP_ERROR_RFMON_NOTSUP
;
3103 * Either monitor mode has been turned on for
3104 * the device, or we've been given a different
3105 * device to open for monitor mode. If we've
3106 * been given a different device, use it.
3108 if (handlep
->mondevice
!= NULL
)
3109 device
= handlep
->mondevice
;
3111 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3116 map_arphrd_to_dlt(handle
, arptype
, device
, 1);
3117 if (handle
->linktype
== -1 ||
3118 handle
->linktype
== DLT_LINUX_SLL
||
3119 handle
->linktype
== DLT_LINUX_IRDA
||
3120 handle
->linktype
== DLT_LINUX_LAPD
||
3121 handle
->linktype
== DLT_NETLINK
||
3122 (handle
->linktype
== DLT_EN10MB
&&
3123 (strncmp("isdn", device
, 4) == 0 ||
3124 strncmp("isdY", device
, 4) == 0))) {
3126 * Unknown interface type (-1), or a
3127 * device we explicitly chose to run
3128 * in cooked mode (e.g., PPP devices),
3129 * or an ISDN device (whose link-layer
3130 * type we can only determine by using
3131 * APIs that may be different on different
3132 * kernels) - reopen in cooked mode.
3134 if (close(sock_fd
) == -1) {
3135 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3136 "close: %s", pcap_strerror(errno
));
3139 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3141 if (sock_fd
== -1) {
3142 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3143 "socket: %s", pcap_strerror(errno
));
3144 if (errno
== EPERM
|| errno
== EACCES
) {
3146 * You don't have permission to
3149 return PCAP_ERROR_PERM_DENIED
;
3157 handlep
->cooked
= 1;
3160 * Get rid of any link-layer type list
3161 * we allocated - this only supports cooked
3164 if (handle
->dlt_list
!= NULL
) {
3165 free(handle
->dlt_list
);
3166 handle
->dlt_list
= NULL
;
3167 handle
->dlt_count
= 0;
3170 if (handle
->linktype
== -1) {
3172 * Warn that we're falling back on
3173 * cooked mode; we may want to
3174 * update "map_arphrd_to_dlt()"
3175 * to handle the new type.
3177 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3179 "supported by libpcap - "
3180 "falling back to cooked "
3186 * IrDA capture is not a real "cooked" capture,
3187 * it's IrLAP frames, not IP packets. The
3188 * same applies to LAPD capture.
3190 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3191 handle
->linktype
!= DLT_LINUX_LAPD
&&
3192 handle
->linktype
!= DLT_NETLINK
)
3193 handle
->linktype
= DLT_LINUX_SLL
;
3196 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3198 if (handlep
->ifindex
== -1) {
3203 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3204 handle
->errbuf
)) != 1) {
3209 return 0; /* try old mechanism */
3215 if (handle
->opt
.rfmon
) {
3217 * It doesn't support monitor mode.
3220 return PCAP_ERROR_RFMON_NOTSUP
;
3224 * It uses cooked mode.
3226 handlep
->cooked
= 1;
3227 handle
->linktype
= DLT_LINUX_SLL
;
3230 * We're not bound to a device.
3231 * For now, we're using this as an indication
3232 * that we can't transmit; stop doing that only
3233 * if we figure out how to transmit in cooked
3236 handlep
->ifindex
= -1;
3240 * Select promiscuous mode on if "promisc" is set.
3242 * Do not turn allmulti mode on if we don't select
3243 * promiscuous mode - on some devices (e.g., Orinoco
3244 * wireless interfaces), allmulti mode isn't supported
3245 * and the driver implements it by turning promiscuous
3246 * mode on, and that screws up the operation of the
3247 * card as a normal networking interface, and on no
3248 * other platform I know of does starting a non-
3249 * promiscuous capture affect which multicast packets
3250 * are received by the interface.
3254 * Hmm, how can we set promiscuous mode on all interfaces?
3255 * I am not sure if that is possible at all. For now, we
3256 * silently ignore attempts to turn promiscuous mode on
3257 * for the "any" device (so you don't have to explicitly
3258 * disable it in programs such as tcpdump).
3261 if (!is_any_device
&& handle
->opt
.promisc
) {
3262 memset(&mr
, 0, sizeof(mr
));
3263 mr
.mr_ifindex
= handlep
->ifindex
;
3264 mr
.mr_type
= PACKET_MR_PROMISC
;
3265 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3266 &mr
, sizeof(mr
)) == -1) {
3267 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3268 "setsockopt: %s", pcap_strerror(errno
));
3274 /* Enable auxillary data if supported and reserve room for
3275 * reconstructing VLAN headers. */
3276 #ifdef HAVE_PACKET_AUXDATA
3278 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3279 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3280 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3281 "setsockopt: %s", pcap_strerror(errno
));
3285 handle
->offset
+= VLAN_TAG_LEN
;
3286 #endif /* HAVE_PACKET_AUXDATA */
3289 * This is a 2.2[.x] or later kernel (we know that
3290 * because we're not using a SOCK_PACKET socket -
3291 * PF_PACKET is supported only in 2.2 and later
3294 * We can safely pass "recvfrom()" a byte count
3295 * based on the snapshot length.
3297 * If we're in cooked mode, make the snapshot length
3298 * large enough to hold a "cooked mode" header plus
3299 * 1 byte of packet data (so we don't pass a byte
3300 * count of 0 to "recvfrom()").
3302 if (handlep
->cooked
) {
3303 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3304 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3306 handle
->bufsize
= handle
->snapshot
;
3309 * Set the offset at which to insert VLAN tags.
3311 switch (handle
->linktype
) {
3314 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3318 handlep
->vlan_offset
= 14;
3322 handlep
->vlan_offset
= -1; /* unknown */
3326 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3327 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3328 int nsec_tstamps
= 1;
3330 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3331 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3336 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3339 * We've succeeded. Save the socket FD in the pcap structure.
3341 handle
->fd
= sock_fd
;
3344 #else /* HAVE_PF_PACKET_SOCKETS */
3346 "New packet capturing interface not supported by build "
3347 "environment", PCAP_ERRBUF_SIZE
);
3349 #endif /* HAVE_PF_PACKET_SOCKETS */
3352 #ifdef HAVE_PACKET_RING
3354 * Attempt to activate with memory-mapped access.
3356 * On success, returns 1, and sets *status to 0 if there are no warnings
3357 * or to a PCAP_WARNING_ code if there is a warning.
3359 * On failure due to lack of support for memory-mapped capture, returns
3362 * On error, returns -1, and sets *status to the appropriate error code;
3363 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3366 activate_mmap(pcap_t
*handle
, int *status
)
3368 struct pcap_linux
*handlep
= handle
->priv
;
3372 * Attempt to allocate a buffer to hold the contents of one
3373 * packet, for use by the oneshot callback.
3375 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3376 if (handlep
->oneshot_buffer
== NULL
) {
3377 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3378 "can't allocate oneshot buffer: %s",
3379 pcap_strerror(errno
));
3380 *status
= PCAP_ERROR
;
3384 if (handle
->opt
.buffer_size
== 0) {
3385 /* by default request 2M for the ring buffer */
3386 handle
->opt
.buffer_size
= 2*1024*1024;
3388 ret
= prepare_tpacket_socket(handle
);
3390 free(handlep
->oneshot_buffer
);
3391 *status
= PCAP_ERROR
;
3394 ret
= create_ring(handle
, status
);
3397 * We don't support memory-mapped capture; our caller
3398 * will fall back on reading from the socket.
3400 free(handlep
->oneshot_buffer
);
3405 * Error attempting to enable memory-mapped capture;
3406 * fail. create_ring() has set *status.
3408 free(handlep
->oneshot_buffer
);
3413 * Success. *status has been set either to 0 if there are no
3414 * warnings or to a PCAP_WARNING_ value if there is a warning.
3416 * Override some defaults and inherit the other fields from
3418 * handle->offset is used to get the current position into the rx ring.
3419 * handle->cc is used to store the ring size.
3422 switch (handlep
->tp_version
) {
3424 handle
->read_op
= pcap_read_linux_mmap_v1
;
3426 #ifdef HAVE_TPACKET2
3428 handle
->read_op
= pcap_read_linux_mmap_v2
;
3431 #ifdef HAVE_TPACKET3
3433 handle
->read_op
= pcap_read_linux_mmap_v3
;
3437 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3438 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3439 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3440 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3441 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3442 handle
->selectable_fd
= handle
->fd
;
3445 #else /* HAVE_PACKET_RING */
3447 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3451 #endif /* HAVE_PACKET_RING */
3453 #ifdef HAVE_PACKET_RING
3455 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3457 * Attempt to set the socket to the specified version of the memory-mapped
3460 * Return 0 if we succeed; return 1 if we fail because that version isn't
3461 * supported; return -1 on any other error, and set handle->errbuf.
3464 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
3466 struct pcap_linux
*handlep
= handle
->priv
;
3468 socklen_t len
= sizeof(val
);
3470 /* Probe whether kernel supports the specified TPACKET version */
3471 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3472 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
)
3475 /* Failed to even find out; this is a fatal error. */
3476 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3477 "can't get %s header len on packet socket: %s",
3479 pcap_strerror(errno
));
3482 handlep
->tp_hdrlen
= val
;
3485 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3487 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3488 "can't activate %s on packet socket: %s",
3490 pcap_strerror(errno
));
3493 handlep
->tp_version
= version
;
3495 /* Reserve space for VLAN tag reconstruction */
3497 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3499 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3500 "can't set up reserve on packet socket: %s",
3501 pcap_strerror(errno
));
3507 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3510 * Attempt to set the socket to version 3 of the memory-mapped header and,
3511 * if that fails because version 3 isn't supported, attempt to fall
3512 * back to version 2. If version 2 isn't supported, just leave it at
3515 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
3516 * supported; return -1 on any other error, and set handle->errbuf.
3519 prepare_tpacket_socket(pcap_t
*handle
)
3521 struct pcap_linux
*handlep
= handle
->priv
;
3522 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3526 handlep
->tp_version
= TPACKET_V1
;
3527 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
3529 #ifdef HAVE_TPACKET3
3531 * The only mode in which buffering is done on PF_PACKET
3532 * sockets, so that packets might not be delivered
3533 * immediately, is TPACKET_V3 mode.
3535 * The buffering cannot be disabled in that mode, so
3536 * if the user has requested immediate mode, we don't
3539 if (handle
->opt
.immediate
)
3540 ret
= 1; /* pretend TPACKET_V3 couldn't be set */
3542 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
3544 /* Error during setting up TPACKET_V3. */
3546 } else if (1 == ret
) {
3547 /* TPACKET_V3 not supported - fall back to TPACKET_V2. */
3548 #endif /* HAVE_TPACKET3 */
3550 #ifdef HAVE_TPACKET2
3551 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
3553 /* Error during setting up TPACKET_V2. */
3556 #endif /* HAVE_TPACKET2 */
3558 #ifdef HAVE_TPACKET3
3560 #endif /* HAVE_TPACKET3 */
3566 * Attempt to set up memory-mapped access.
3568 * On success, returns 1, and sets *status to 0 if there are no warnings
3569 * or to a PCAP_WARNING_ code if there is a warning.
3571 * On failure due to lack of support for memory-mapped capture, returns
3574 * On error, returns -1, and sets *status to the appropriate error code;
3575 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3578 create_ring(pcap_t
*handle
, int *status
)
3580 struct pcap_linux
*handlep
= handle
->priv
;
3581 unsigned i
, j
, frames_per_block
;
3582 #ifdef HAVE_TPACKET3
3584 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
3585 * stuff at the end of a struct tpacket_req3 will be
3586 * ignored, so this is OK even for those sockets.
3588 struct tpacket_req3 req
;
3590 struct tpacket_req req
;
3593 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3594 unsigned int frame_size
;
3597 * Start out assuming no warnings or errors.
3601 switch (handlep
->tp_version
) {
3604 #ifdef HAVE_TPACKET2
3607 /* Note that with large snapshot length (say 64K, which is
3608 * the default for recent versions of tcpdump, the value that
3609 * "-s 0" has given for a long time with tcpdump, and the
3610 * default in Wireshark/TShark/dumpcap), if we use the snapshot
3611 * length to calculate the frame length, only a few frames
3612 * will be available in the ring even with pretty
3613 * large ring size (and a lot of memory will be unused).
3615 * Ideally, we should choose a frame length based on the
3616 * minimum of the specified snapshot length and the maximum
3617 * packet size. That's not as easy as it sounds; consider,
3618 * for example, an 802.11 interface in monitor mode, where
3619 * the frame would include a radiotap header, where the
3620 * maximum radiotap header length is device-dependent.
3622 * So, for now, we just do this for Ethernet devices, where
3623 * there's no metadata header, and the link-layer header is
3624 * fixed length. We can get the maximum packet size by
3625 * adding 18, the Ethernet header length plus the CRC length
3626 * (just in case we happen to get the CRC in the packet), to
3627 * the MTU of the interface; we fetch the MTU in the hopes
3628 * that it reflects support for jumbo frames. (Even if the
3629 * interface is just being used for passive snooping, the
3630 * driver might set the size of buffers in the receive ring
3631 * based on the MTU, so that the MTU limits the maximum size
3632 * of packets that we can receive.)
3634 * We don't do that if segmentation/fragmentation or receive
3635 * offload are enabled, so we don't get rudely surprised by
3636 * "packets" bigger than the MTU. */
3637 frame_size
= handle
->snapshot
;
3638 if (handle
->linktype
== DLT_EN10MB
) {
3642 offload
= iface_get_offload(handle
);
3643 if (offload
== -1) {
3644 *status
= PCAP_ERROR
;
3648 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
3651 *status
= PCAP_ERROR
;
3654 if (frame_size
> mtu
+ 18)
3655 frame_size
= mtu
+ 18;
3659 /* NOTE: calculus matching those in tpacket_rcv()
3660 * in linux-2.6/net/packet/af_packet.c
3662 len
= sizeof(sk_type
);
3663 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
3665 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3666 "getsockopt: %s", pcap_strerror(errno
));
3667 *status
= PCAP_ERROR
;
3670 #ifdef PACKET_RESERVE
3671 len
= sizeof(tp_reserve
);
3672 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
3673 &tp_reserve
, &len
) < 0) {
3674 if (errno
!= ENOPROTOOPT
) {
3676 * ENOPROTOOPT means "kernel doesn't support
3677 * PACKET_RESERVE", in which case we fall back
3680 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3681 "getsockopt: %s", pcap_strerror(errno
));
3682 *status
= PCAP_ERROR
;
3685 tp_reserve
= 0; /* older kernel, reserve not supported */
3688 tp_reserve
= 0; /* older kernel, reserve not supported */
3690 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3691 /* XXX: in the kernel maclen is calculated from
3692 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3693 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3694 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3695 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3696 * but I see no way to get those sizes in userspace,
3697 * like for instance with an ifreq ioctl();
3698 * the best thing I've found so far is MAX_HEADER in
3699 * the kernel part of linux-2.6/include/linux/netdevice.h
3700 * which goes up to 128+48=176; since pcap-linux.c
3701 * defines a MAX_LINKHEADER_SIZE of 256 which is
3702 * greater than that, let's use it.. maybe is it even
3703 * large enough to directly replace macoff..
3705 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3706 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3707 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3708 * of netoff, which contradicts
3709 * linux-2.6/Documentation/networking/packet_mmap.txt
3711 * "- Gap, chosen so that packet data (Start+tp_net)
3712 * aligns to TPACKET_ALIGNMENT=16"
3714 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3715 * "CPUs often take a performance hit
3716 * when accessing unaligned memory locations"
3718 macoff
= netoff
- maclen
;
3719 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3720 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3723 #ifdef HAVE_TPACKET3
3725 /* The "frames" for this are actually buffers that
3726 * contain multiple variable-sized frames.
3728 * We pick a "frame" size of 128K to leave enough
3729 * room for at least one reasonably-sized packet
3730 * in the "frame". */
3731 req
.tp_frame_size
= MAXIMUM_SNAPLEN
;
3732 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3737 /* compute the minumum block size that will handle this frame.
3738 * The block has to be page size aligned.
3739 * The max block size allowed by the kernel is arch-dependent and
3740 * it's not explicitly checked here. */
3741 req
.tp_block_size
= getpagesize();
3742 while (req
.tp_block_size
< req
.tp_frame_size
)
3743 req
.tp_block_size
<<= 1;
3745 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3748 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3749 * so we check for PACKET_TIMESTAMP. We check for
3750 * linux/net_tstamp.h just in case a system somehow has
3751 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3754 * SIOCSHWTSTAMP was introduced in the patch that introduced
3755 * linux/net_tstamp.h, so we don't bother checking whether
3756 * SIOCSHWTSTAMP is defined (if your Linux system has
3757 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3758 * Linux system is badly broken).
3760 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3762 * If we were told to do so, ask the kernel and the driver
3763 * to use hardware timestamps.
3765 * Hardware timestamps are only supported with mmapped
3768 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3769 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3770 struct hwtstamp_config hwconfig
;
3775 * Ask for hardware time stamps on all packets,
3776 * including transmitted packets.
3778 memset(&hwconfig
, 0, sizeof(hwconfig
));
3779 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3780 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3782 memset(&ifr
, 0, sizeof(ifr
));
3783 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
3784 ifr
.ifr_data
= (void *)&hwconfig
;
3786 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3791 * Treat this as an error, as the
3792 * user should try to run this
3793 * with the appropriate privileges -
3794 * and, if they can't, shouldn't
3795 * try requesting hardware time stamps.
3797 *status
= PCAP_ERROR_PERM_DENIED
;
3802 * Treat this as a warning, as the
3803 * only way to fix the warning is to
3804 * get an adapter that supports hardware
3805 * time stamps. We'll just fall back
3806 * on the standard host time stamps.
3808 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3812 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3813 "SIOCSHWTSTAMP failed: %s",
3814 pcap_strerror(errno
));
3815 *status
= PCAP_ERROR
;
3820 * Well, that worked. Now specify the type of
3821 * hardware time stamp we want for this
3824 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3826 * Hardware timestamp, synchronized
3827 * with the system clock.
3829 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3832 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3833 * timestamp, not synchronized with the
3836 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3838 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3839 (void *)×ource
, sizeof(timesource
))) {
3840 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3841 "can't set PACKET_TIMESTAMP: %s",
3842 pcap_strerror(errno
));
3843 *status
= PCAP_ERROR
;
3848 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3850 /* ask the kernel to create the ring */
3852 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3854 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3855 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3857 #ifdef HAVE_TPACKET3
3858 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3859 req
.tp_retire_blk_tov
= (handlep
->timeout
>=0)?handlep
->timeout
:0;
3860 /* private data not used */
3861 req
.tp_sizeof_priv
= 0;
3862 /* Rx ring - feature request bits - none (rxhash will not be filled) */
3863 req
.tp_feature_req_word
= 0;
3866 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3867 (void *) &req
, sizeof(req
))) {
3868 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3870 * Memory failure; try to reduce the requested ring
3873 * We used to reduce this by half -- do 5% instead.
3874 * That may result in more iterations and a longer
3875 * startup, but the user will be much happier with
3876 * the resulting buffer size.
3878 if (req
.tp_frame_nr
< 20)
3879 req
.tp_frame_nr
-= 1;
3881 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3884 if (errno
== ENOPROTOOPT
) {
3886 * We don't have ring buffer support in this kernel.
3890 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3891 "can't create rx ring on packet socket: %s",
3892 pcap_strerror(errno
));
3893 *status
= PCAP_ERROR
;
3897 /* memory map the rx ring */
3898 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3899 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
3900 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3901 if (handlep
->mmapbuf
== MAP_FAILED
) {
3902 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3903 "can't mmap rx ring: %s", pcap_strerror(errno
));
3905 /* clear the allocated ring on error*/
3906 destroy_ring(handle
);
3907 *status
= PCAP_ERROR
;
3911 /* allocate a ring for each frame header pointer*/
3912 handle
->cc
= req
.tp_frame_nr
;
3913 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3914 if (!handle
->buffer
) {
3915 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3916 "can't allocate ring of frame headers: %s",
3917 pcap_strerror(errno
));
3919 destroy_ring(handle
);
3920 *status
= PCAP_ERROR
;
3924 /* fill the header ring with proper frame ptr*/
3926 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3927 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3928 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3929 RING_GET_FRAME(handle
) = base
;
3930 base
+= req
.tp_frame_size
;
3934 handle
->bufsize
= req
.tp_frame_size
;
3939 /* free all ring related resources*/
3941 destroy_ring(pcap_t
*handle
)
3943 struct pcap_linux
*handlep
= handle
->priv
;
3945 /* tell the kernel to destroy the ring*/
3946 struct tpacket_req req
;
3947 memset(&req
, 0, sizeof(req
));
3948 /* do not test for setsockopt failure, as we can't recover from any error */
3949 (void)setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3950 (void *) &req
, sizeof(req
));
3952 /* if ring is mapped, unmap it*/
3953 if (handlep
->mmapbuf
) {
3954 /* do not test for mmap failure, as we can't recover from any error */
3955 (void)munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3956 handlep
->mmapbuf
= NULL
;
3961 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3962 * for Linux mmapped capture.
3964 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3965 * data handed to the callback to be valid after the callback returns,
3966 * but pcap_read_linux_mmap() has to release that packet as soon as
3967 * the callback returns (otherwise, the kernel thinks there's still
3968 * at least one unprocessed packet available in the ring, so a select()
3969 * will immediately return indicating that there's data to process), so,
3970 * in the callback, we have to make a copy of the packet.
3972 * Yes, this means that, if the capture is using the ring buffer, using
3973 * pcap_next() or pcap_next_ex() requires more copies than using
3974 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3975 * pcap_next() or pcap_next_ex().
3978 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3979 const u_char
*bytes
)
3981 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3982 pcap_t
*handle
= sp
->pd
;
3983 struct pcap_linux
*handlep
= handle
->priv
;
3986 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3987 *sp
->pkt
= handlep
->oneshot_buffer
;
3991 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3993 struct pcap_linux
*handlep
= handle
->priv
;
3995 destroy_ring(handle
);
3996 if (handlep
->oneshot_buffer
!= NULL
) {
3997 free(handlep
->oneshot_buffer
);
3998 handlep
->oneshot_buffer
= NULL
;
4000 pcap_cleanup_linux(handle
);
4005 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
4007 struct pcap_linux
*handlep
= p
->priv
;
4009 /* use negative value of timeout to indicate non blocking ops */
4010 return (handlep
->timeout
<0);
4014 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
4016 struct pcap_linux
*handlep
= p
->priv
;
4019 * Set the file descriptor to non-blocking mode, as we use
4020 * it for sending packets.
4022 if (pcap_setnonblock_fd(p
, nonblock
, errbuf
) == -1)
4026 * Map each value to their corresponding negation to
4027 * preserve the timeout value provided with pcap_set_timeout.
4030 if (handlep
->timeout
>= 0) {
4032 * Indicate that we're switching to
4033 * non-blocking mode.
4035 handlep
->timeout
= ~handlep
->timeout
;
4038 if (handlep
->timeout
< 0) {
4039 handlep
->timeout
= ~handlep
->timeout
;
4045 static inline union thdr
*
4046 pcap_get_ring_frame(pcap_t
*handle
, int status
)
4048 struct pcap_linux
*handlep
= handle
->priv
;
4051 h
.raw
= RING_GET_FRAME(handle
);
4052 switch (handlep
->tp_version
) {
4054 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
4058 #ifdef HAVE_TPACKET2
4060 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
4065 #ifdef HAVE_TPACKET3
4067 if (status
!= (h
.h3
->hdr
.bh1
.block_status
? TP_STATUS_USER
:
4080 /* wait for frames availability.*/
4081 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4083 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
4084 struct pcap_linux
*handlep
= handle
->priv
;
4087 struct pollfd pollinfo
;
4090 pollinfo
.fd
= handle
->fd
;
4091 pollinfo
.events
= POLLIN
;
4093 if (handlep
->timeout
== 0) {
4094 #ifdef HAVE_TPACKET3
4096 * XXX - due to a set of (mis)features in the
4097 * TPACKET_V3 kernel code, blocking forever with
4098 * a TPACKET_V3 socket can, if few packets
4099 * are arriving and passing the socket filter,
4100 * cause most packets to be dropped. See
4101 * libpcap issue #335 for the full painful
4102 * story. The workaround is to have poll()
4103 * time out very quickly, so we grab the
4104 * frames handed to us, and return them to
4107 * If those issues are ever fixed, we might
4108 * want to check the kernel version and block
4109 * forever with TPACKET_V3 if we're running
4110 * with a kernel that has the fix.
4112 if (handlep
->tp_version
== TPACKET_V3
)
4113 timeout
= 1; /* don't block for very long */
4116 timeout
= -1; /* block forever */
4117 } else if (handlep
->timeout
> 0)
4118 timeout
= handlep
->timeout
; /* block for that amount of time */
4120 timeout
= 0; /* non-blocking mode - poll to pick up errors */
4122 ret
= poll(&pollinfo
, 1, timeout
);
4123 if (ret
< 0 && errno
!= EINTR
) {
4124 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4125 "can't poll on packet socket: %s",
4126 pcap_strerror(errno
));
4128 } else if (ret
> 0 &&
4129 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4131 * There's some indication other than
4132 * "you can read on this descriptor" on
4135 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
4136 snprintf(handle
->errbuf
,
4138 "Hangup on packet socket");
4141 if (pollinfo
.revents
& POLLERR
) {
4143 * A recv() will give us the
4144 * actual error code.
4146 * XXX - make the socket non-blocking?
4148 if (recv(handle
->fd
, &c
, sizeof c
,
4150 continue; /* what, no error? */
4151 if (errno
== ENETDOWN
) {
4153 * The device on which we're
4154 * capturing went away.
4156 * XXX - we should really return
4157 * PCAP_ERROR_IFACE_NOT_UP,
4158 * but pcap_dispatch() etc.
4159 * aren't defined to return
4162 snprintf(handle
->errbuf
,
4164 "The interface went down");
4166 snprintf(handle
->errbuf
,
4168 "Error condition on packet socket: %s",
4173 if (pollinfo
.revents
& POLLNVAL
) {
4174 snprintf(handle
->errbuf
,
4176 "Invalid polling request on packet socket");
4180 /* check for break loop condition on interrupted syscall*/
4181 if (handle
->break_loop
) {
4182 handle
->break_loop
= 0;
4183 return PCAP_ERROR_BREAK
;
4190 /* handle a single memory mapped packet */
4191 static int pcap_handle_packet_mmap(
4193 pcap_handler callback
,
4195 unsigned char *frame
,
4196 unsigned int tp_len
,
4197 unsigned int tp_mac
,
4198 unsigned int tp_snaplen
,
4199 unsigned int tp_sec
,
4200 unsigned int tp_usec
,
4201 int tp_vlan_tci_valid
,
4204 struct pcap_linux
*handlep
= handle
->priv
;
4206 struct sockaddr_ll
*sll
;
4207 struct pcap_pkthdr pcaphdr
;
4209 /* perform sanity check on internal offset. */
4210 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
4211 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4212 "corrupted frame on kernel ring mac "
4213 "offset %d + caplen %d > frame len %d",
4214 tp_mac
, tp_snaplen
, handle
->bufsize
);
4218 /* run filter on received packet
4219 * If the kernel filtering is enabled we need to run the
4220 * filter until all the frames present into the ring
4221 * at filter creation time are processed.
4222 * In this case, blocks_to_filter_in_userland is used
4223 * as a counter for the packet we need to filter.
4224 * Note: alternatively it could be possible to stop applying
4225 * the filter when the ring became empty, but it can possibly
4226 * happen a lot later... */
4227 bp
= frame
+ tp_mac
;
4228 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
&&
4229 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
4230 tp_len
, tp_snaplen
) == 0))
4233 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
4234 if (!linux_check_direction(handle
, sll
))
4237 /* get required packet info from ring header */
4238 pcaphdr
.ts
.tv_sec
= tp_sec
;
4239 pcaphdr
.ts
.tv_usec
= tp_usec
;
4240 pcaphdr
.caplen
= tp_snaplen
;
4241 pcaphdr
.len
= tp_len
;
4243 /* if required build in place the sll header*/
4244 if (handlep
->cooked
) {
4245 struct sll_header
*hdrp
;
4248 * The kernel should have left us with enough
4249 * space for an sll header; back up the packet
4250 * data pointer into that space, as that'll be
4251 * the beginning of the packet we pass to the
4257 * Let's make sure that's past the end of
4258 * the tpacket header, i.e. >=
4259 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4260 * don't step on the header when we construct
4263 if (bp
< (u_char
*)frame
+
4264 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4265 sizeof(struct sockaddr_ll
)) {
4266 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4267 "cooked-mode frame doesn't have room for sll header");
4272 * OK, that worked; construct the sll header.
4274 hdrp
= (struct sll_header
*)bp
;
4275 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4277 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4278 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4279 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4280 hdrp
->sll_protocol
= sll
->sll_protocol
;
4282 /* update packet len */
4283 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4284 pcaphdr
.len
+= SLL_HDR_LEN
;
4287 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4288 if (tp_vlan_tci_valid
&&
4289 handlep
->vlan_offset
!= -1 &&
4290 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4292 struct vlan_tag
*tag
;
4295 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4297 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4298 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
4299 tag
->vlan_tci
= htons(tp_vlan_tci
);
4301 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4302 pcaphdr
.len
+= VLAN_TAG_LEN
;
4307 * The only way to tell the kernel to cut off the
4308 * packet at a snapshot length is with a filter program;
4309 * if there's no filter program, the kernel won't cut
4312 * Trim the snapshot length to be no longer than the
4313 * specified snapshot length.
4315 if (pcaphdr
.caplen
> handle
->snapshot
)
4316 pcaphdr
.caplen
= handle
->snapshot
;
4318 /* pass the packet to the user */
4319 callback(user
, &pcaphdr
, bp
);
4325 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4328 struct pcap_linux
*handlep
= handle
->priv
;
4332 /* wait for frames availability.*/
4333 ret
= pcap_wait_for_frames_mmap(handle
);
4338 /* non-positive values of max_packets are used to require all
4339 * packets currently available in the ring */
4340 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4343 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4347 ret
= pcap_handle_packet_mmap(
4361 handlep
->packets_read
++;
4362 } else if (ret
< 0) {
4367 * Hand this block back to the kernel, and, if we're
4368 * counting blocks that need to be filtered in userland
4369 * after having been filtered by the kernel, count
4370 * the one we've just processed.
4372 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4373 if (handlep
->blocks_to_filter_in_userland
> 0) {
4374 handlep
->blocks_to_filter_in_userland
--;
4375 if (handlep
->blocks_to_filter_in_userland
== 0) {
4377 * No more blocks need to be filtered
4380 handlep
->filter_in_userland
= 0;
4385 if (++handle
->offset
>= handle
->cc
)
4388 /* check for break loop condition*/
4389 if (handle
->break_loop
) {
4390 handle
->break_loop
= 0;
4391 return PCAP_ERROR_BREAK
;
4397 #ifdef HAVE_TPACKET2
4399 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4402 struct pcap_linux
*handlep
= handle
->priv
;
4406 /* wait for frames availability.*/
4407 ret
= pcap_wait_for_frames_mmap(handle
);
4412 /* non-positive values of max_packets are used to require all
4413 * packets currently available in the ring */
4414 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4417 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4421 ret
= pcap_handle_packet_mmap(
4430 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4431 #if defined(TP_STATUS_VLAN_VALID)
4432 (h
.h2
->tp_vlan_tci
|| (h
.h2
->tp_status
& TP_STATUS_VLAN_VALID
)),
4434 h
.h2
->tp_vlan_tci
!= 0,
4439 handlep
->packets_read
++;
4440 } else if (ret
< 0) {
4445 * Hand this block back to the kernel, and, if we're
4446 * counting blocks that need to be filtered in userland
4447 * after having been filtered by the kernel, count
4448 * the one we've just processed.
4450 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4451 if (handlep
->blocks_to_filter_in_userland
> 0) {
4452 handlep
->blocks_to_filter_in_userland
--;
4453 if (handlep
->blocks_to_filter_in_userland
== 0) {
4455 * No more blocks need to be filtered
4458 handlep
->filter_in_userland
= 0;
4463 if (++handle
->offset
>= handle
->cc
)
4466 /* check for break loop condition*/
4467 if (handle
->break_loop
) {
4468 handle
->break_loop
= 0;
4469 return PCAP_ERROR_BREAK
;
4474 #endif /* HAVE_TPACKET2 */
4476 #ifdef HAVE_TPACKET3
4478 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4481 struct pcap_linux
*handlep
= handle
->priv
;
4487 if (handlep
->current_packet
== NULL
) {
4488 /* wait for frames availability.*/
4489 ret
= pcap_wait_for_frames_mmap(handle
);
4494 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4496 if (pkts
== 0 && handlep
->timeout
== 0) {
4497 /* Block until we see a packet. */
4503 /* non-positive values of max_packets are used to require all
4504 * packets currently available in the ring */
4505 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4506 if (handlep
->current_packet
== NULL
) {
4507 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4511 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4512 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4514 int packets_to_read
= handlep
->packets_left
;
4516 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) && packets_to_read
> max_packets
) {
4517 packets_to_read
= max_packets
;
4520 while(packets_to_read
--) {
4521 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4522 ret
= pcap_handle_packet_mmap(
4526 handlep
->current_packet
,
4529 tp3_hdr
->tp_snaplen
,
4531 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4532 #if defined(TP_STATUS_VLAN_VALID)
4533 (tp3_hdr
->hv1
.tp_vlan_tci
|| (tp3_hdr
->tp_status
& TP_STATUS_VLAN_VALID
)),
4535 tp3_hdr
->hv1
.tp_vlan_tci
!= 0,
4537 tp3_hdr
->hv1
.tp_vlan_tci
);
4540 handlep
->packets_read
++;
4541 } else if (ret
< 0) {
4542 handlep
->current_packet
= NULL
;
4545 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4546 handlep
->packets_left
--;
4549 if (handlep
->packets_left
<= 0) {
4551 * Hand this block back to the kernel, and, if
4552 * we're counting blocks that need to be
4553 * filtered in userland after having been
4554 * filtered by the kernel, count the one we've
4557 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
4558 if (handlep
->blocks_to_filter_in_userland
> 0) {
4559 handlep
->blocks_to_filter_in_userland
--;
4560 if (handlep
->blocks_to_filter_in_userland
== 0) {
4562 * No more blocks need to be filtered
4565 handlep
->filter_in_userland
= 0;
4570 if (++handle
->offset
>= handle
->cc
)
4573 handlep
->current_packet
= NULL
;
4576 /* check for break loop condition*/
4577 if (handle
->break_loop
) {
4578 handle
->break_loop
= 0;
4579 return PCAP_ERROR_BREAK
;
4582 if (pkts
== 0 && handlep
->timeout
== 0) {
4583 /* Block until we see a packet. */
4588 #endif /* HAVE_TPACKET3 */
4591 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
4593 struct pcap_linux
*handlep
= handle
->priv
;
4598 * Don't rewrite "ret" instructions; we don't need to, as
4599 * we're not reading packets with recvmsg(), and we don't
4600 * want to, as, by not rewriting them, the kernel can avoid
4601 * copying extra data.
4603 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
4608 * If we're filtering in userland, there's nothing to do;
4609 * the new filter will be used for the next packet.
4611 if (handlep
->filter_in_userland
)
4615 * We're filtering in the kernel; the packets present in
4616 * all blocks currently in the ring were already filtered
4617 * by the old filter, and so will need to be filtered in
4618 * userland by the new filter.
4620 * Get an upper bound for the number of such blocks; first,
4621 * walk the ring backward and count the free blocks.
4623 offset
= handle
->offset
;
4624 if (--handle
->offset
< 0)
4625 handle
->offset
= handle
->cc
- 1;
4626 for (n
=0; n
< handle
->cc
; ++n
) {
4627 if (--handle
->offset
< 0)
4628 handle
->offset
= handle
->cc
- 1;
4629 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
4634 * If we found free blocks, decrement the count of free
4635 * blocks by 1, just in case we lost a race with another
4636 * thread of control that was adding a packet while
4637 * we were counting and that had run the filter before
4640 * XXX - could there be more than one block added in
4643 * XXX - is there a way to avoid that race, e.g. somehow
4644 * wait for all packets that passed the old filter to
4645 * be added to the ring?
4650 /* be careful to not change current ring position */
4651 handle
->offset
= offset
;
4654 * Set the count of blocks worth of packets to filter
4655 * in userland to the total number of blocks in the
4656 * ring minus the number of free blocks we found, and
4657 * turn on userland filtering. (The count of blocks
4658 * worth of packets to filter in userland is guaranteed
4659 * not to be zero - n, above, couldn't be set to a
4660 * value > handle->cc, and if it were equal to
4661 * handle->cc, it wouldn't be zero, and thus would
4662 * be decremented to handle->cc - 1.)
4664 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4665 handlep
->filter_in_userland
= 1;
4669 #endif /* HAVE_PACKET_RING */
4672 #ifdef HAVE_PF_PACKET_SOCKETS
4674 * Return the index of the given device name. Fill ebuf and return
4678 iface_get_id(int fd
, const char *device
, char *ebuf
)
4682 memset(&ifr
, 0, sizeof(ifr
));
4683 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4685 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4686 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4687 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
4691 return ifr
.ifr_ifindex
;
4695 * Bind the socket associated with FD to the given device.
4696 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4697 * or a PCAP_ERROR_ value on a hard error.
4700 iface_bind(int fd
, int ifindex
, char *ebuf
)
4702 struct sockaddr_ll sll
;
4704 socklen_t errlen
= sizeof(err
);
4706 memset(&sll
, 0, sizeof(sll
));
4707 sll
.sll_family
= AF_PACKET
;
4708 sll
.sll_ifindex
= ifindex
;
4709 sll
.sll_protocol
= htons(ETH_P_ALL
);
4711 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4712 if (errno
== ENETDOWN
) {
4714 * Return a "network down" indication, so that
4715 * the application can report that rather than
4716 * saying we had a mysterious failure and
4717 * suggest that they report a problem to the
4718 * libpcap developers.
4720 return PCAP_ERROR_IFACE_NOT_UP
;
4722 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4723 "bind: %s", pcap_strerror(errno
));
4728 /* Any pending errors, e.g., network is down? */
4730 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4731 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4732 "getsockopt: %s", pcap_strerror(errno
));
4736 if (err
== ENETDOWN
) {
4738 * Return a "network down" indication, so that
4739 * the application can report that rather than
4740 * saying we had a mysterious failure and
4741 * suggest that they report a problem to the
4742 * libpcap developers.
4744 return PCAP_ERROR_IFACE_NOT_UP
;
4745 } else if (err
> 0) {
4746 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4747 "bind: %s", pcap_strerror(err
));
4754 #ifdef IW_MODE_MONITOR
4756 * Check whether the device supports the Wireless Extensions.
4757 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4758 * if the device doesn't even exist.
4761 has_wext(int sock_fd
, const char *device
, char *ebuf
)
4765 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4766 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4767 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
4769 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4770 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4771 if (errno
== ENODEV
)
4772 return PCAP_ERROR_NO_SUCH_DEVICE
;
4777 * Per me si va ne la citta dolente,
4778 * Per me si va ne l'etterno dolore,
4780 * Lasciate ogne speranza, voi ch'intrate.
4782 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4798 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4799 * on if it's not already on.
4801 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4802 * on this device, or a PCAP_ERROR_ value if we do support them but
4803 * we weren't able to turn monitor mode on.
4806 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
4809 * XXX - at least some adapters require non-Wireless Extensions
4810 * mechanisms to turn monitor mode on.
4812 * Atheros cards might require that a separate "monitor virtual access
4813 * point" be created, with later versions of the madwifi driver.
4814 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4815 * monitor -bssid", which apparently spits out a line "athN"
4816 * where "athN" is the monitor mode device. To leave monitor
4817 * mode, it destroys the monitor mode device.
4819 * Some Intel Centrino adapters might require private ioctls to get
4820 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4821 * configure a separate "rtapN" interface to capture in monitor
4822 * mode without preventing the adapter from operating normally.
4823 * (airmon-ng doesn't appear to use that, though.)
4825 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4826 * up, and if all drivers were converted to mac80211 drivers.
4828 * If interface {if} is a mac80211 driver, the file
4829 * /sys/class/net/{if}/phy80211 is a symlink to
4830 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4832 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4833 * least, has a "wmaster0" device and a "wlan0" device; the
4834 * latter is the one with the IP address. Both show up in
4835 * "tcpdump -D" output. Capturing on the wmaster0 device
4836 * captures with 802.11 headers.
4838 * airmon-ng searches through /sys/class/net for devices named
4839 * monN, starting with mon0; as soon as one *doesn't* exist,
4840 * it chooses that as the monitor device name. If the "iw"
4841 * command exists, it does "iw dev {if} interface add {monif}
4842 * type monitor", where {monif} is the monitor device. It
4843 * then (sigh) sleeps .1 second, and then configures the
4844 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4845 * is a file, it writes {mondev}, without a newline, to that file,
4846 * and again (sigh) sleeps .1 second, and then iwconfig's that
4847 * device into monitor mode and configures it up. Otherwise,
4848 * you can't do monitor mode.
4850 * All these devices are "glued" together by having the
4851 * /sys/class/net/{device}/phy80211 links pointing to the same
4852 * place, so, given a wmaster, wlan, or mon device, you can
4853 * find the other devices by looking for devices with
4854 * the same phy80211 link.
4856 * To turn monitor mode off, delete the monitor interface,
4857 * either with "iw dev {monif} interface del" or by sending
4858 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4860 * Note: if you try to create a monitor device named "monN", and
4861 * there's already a "monN" device, it fails, as least with
4862 * the netlink interface (which is what iw uses), with a return
4863 * value of -ENFILE. (Return values are negative errnos.) We
4864 * could probably use that to find an unused device.
4866 struct pcap_linux
*handlep
= handle
->priv
;
4869 struct iw_priv_args
*priv
;
4870 monitor_type montype
;
4879 * Does this device *support* the Wireless Extensions?
4881 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4883 return err
; /* either it doesn't or the device doesn't even exist */
4885 * Start out assuming we have no private extensions to control
4888 montype
= MONITOR_WEXT
;
4892 * Try to get all the Wireless Extensions private ioctls
4893 * supported by this device.
4895 * First, get the size of the buffer we need, by supplying no
4896 * buffer and a length of 0. If the device supports private
4897 * ioctls, it should return E2BIG, with ireq.u.data.length set
4898 * to the length we need. If it doesn't support them, it should
4899 * return EOPNOTSUPP.
4901 memset(&ireq
, 0, sizeof ireq
);
4902 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4903 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4904 ireq
.u
.data
.pointer
= (void *)args
;
4905 ireq
.u
.data
.length
= 0;
4906 ireq
.u
.data
.flags
= 0;
4907 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4908 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4909 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4913 if (errno
!= EOPNOTSUPP
) {
4915 * OK, it's not as if there are no private ioctls.
4917 if (errno
!= E2BIG
) {
4921 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4922 "%s: SIOCGIWPRIV: %s", device
,
4923 pcap_strerror(errno
));
4928 * OK, try to get the list of private ioctls.
4930 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4932 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4933 "malloc: %s", pcap_strerror(errno
));
4936 ireq
.u
.data
.pointer
= (void *)priv
;
4937 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4938 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4939 "%s: SIOCGIWPRIV: %s", device
,
4940 pcap_strerror(errno
));
4946 * Look for private ioctls to turn monitor mode on or, if
4947 * monitor mode is on, to set the header type.
4949 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4950 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4952 * Hostap driver, use this one.
4953 * Set monitor mode first.
4954 * You can set it to 0 to get DLT_IEEE80211,
4955 * 1 to get DLT_PRISM, 2 to get
4956 * DLT_IEEE80211_RADIO_AVS, and, with more
4957 * recent versions of the driver, 3 to get
4958 * DLT_IEEE80211_RADIO.
4960 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4962 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4964 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4966 montype
= MONITOR_HOSTAP
;
4970 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4972 * Prism54 driver, use this one.
4973 * Set monitor mode first.
4974 * You can set it to 2 to get DLT_IEEE80211
4975 * or 3 or get DLT_PRISM.
4977 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4979 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4981 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4983 montype
= MONITOR_PRISM54
;
4987 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4989 * RT2570 driver, use this one.
4990 * Do this after turning monitor mode on.
4991 * You can set it to 1 to get DLT_PRISM or 2
4992 * to get DLT_IEEE80211.
4994 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4996 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4998 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5000 montype
= MONITOR_RT2570
;
5004 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
5006 * RT73 driver, use this one.
5007 * Do this after turning monitor mode on.
5008 * Its argument is a *string*; you can
5009 * set it to "1" to get DLT_PRISM or "2"
5010 * to get DLT_IEEE80211.
5012 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
5014 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
5016 montype
= MONITOR_RT73
;
5020 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
5022 * One of the RTL8xxx drivers, use this one.
5023 * It can only be done after monitor mode
5024 * has been turned on. You can set it to 1
5025 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5027 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5029 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5031 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5033 montype
= MONITOR_RTL8XXX
;
5037 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
5039 * RT2500 or RT61 driver, use this one.
5040 * It has one one-byte parameter; set
5041 * u.data.length to 1 and u.data.pointer to
5042 * point to the parameter.
5043 * It doesn't itself turn monitor mode on.
5044 * You can set it to 1 to allow transmitting
5045 * in monitor mode(?) and get DLT_IEEE80211,
5046 * or set it to 0 to disallow transmitting in
5047 * monitor mode(?) and get DLT_PRISM.
5049 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5051 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
5053 montype
= MONITOR_RT2500
;
5057 if (strcmp(priv
[i
].name
, "monitor") == 0) {
5059 * Either ACX100 or hostap, use this one.
5060 * It turns monitor mode on.
5061 * If it takes two arguments, it's ACX100;
5062 * the first argument is 1 for DLT_PRISM
5063 * or 2 for DLT_IEEE80211, and the second
5064 * argument is the channel on which to
5065 * run. If it takes one argument, it's
5066 * HostAP, and the argument is 2 for
5067 * DLT_IEEE80211 and 3 for DLT_PRISM.
5069 * If we see this, we don't quit, as this
5070 * might be a version of the hostap driver
5071 * that also supports "monitor_type".
5073 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5075 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5077 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5080 montype
= MONITOR_PRISM
;
5085 montype
= MONITOR_ACX100
;
5098 * XXX - ipw3945? islism?
5104 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5105 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5106 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
5108 * We probably won't be able to set the mode, either.
5110 return PCAP_ERROR_RFMON_NOTSUP
;
5114 * Is it currently in monitor mode?
5116 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
5118 * Yes. Just leave things as they are.
5119 * We don't offer multiple link-layer types, as
5120 * changing the link-layer type out from under
5121 * somebody else capturing in monitor mode would
5122 * be considered rude.
5127 * No. We have to put the adapter into rfmon mode.
5131 * If we haven't already done so, arrange to have
5132 * "pcap_close_all()" called when we exit.
5134 if (!pcap_do_addexit(handle
)) {
5136 * "atexit()" failed; don't put the interface
5137 * in rfmon mode, just give up.
5139 return PCAP_ERROR_RFMON_NOTSUP
;
5143 * Save the old mode.
5145 handlep
->oldmode
= ireq
.u
.mode
;
5148 * Put the adapter in rfmon mode. How we do this depends
5149 * on whether we have a special private ioctl or not.
5151 if (montype
== MONITOR_PRISM
) {
5153 * We have the "monitor" private ioctl, but none of
5154 * the other private ioctls. Use this, and select
5157 * If it fails, just fall back on SIOCSIWMODE.
5159 memset(&ireq
, 0, sizeof ireq
);
5160 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5161 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5162 ireq
.u
.data
.length
= 1; /* 1 argument */
5163 args
[0] = 3; /* request Prism header */
5164 memcpy(ireq
.u
.name
, args
, sizeof (int));
5165 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
5168 * Note that we have to put the old mode back
5169 * when we close the device.
5171 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5174 * Add this to the list of pcaps to close
5177 pcap_add_to_pcaps_to_close(handle
);
5183 * Failure. Fall back on SIOCSIWMODE.
5188 * First, take the interface down if it's up; otherwise, we
5191 memset(&ifr
, 0, sizeof(ifr
));
5192 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5193 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5194 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5195 "%s: Can't get flags: %s", device
, strerror(errno
));
5199 if (ifr
.ifr_flags
& IFF_UP
) {
5200 oldflags
= ifr
.ifr_flags
;
5201 ifr
.ifr_flags
&= ~IFF_UP
;
5202 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5203 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5204 "%s: Can't set flags: %s", device
, strerror(errno
));
5210 * Then turn monitor mode on.
5212 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5213 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5214 ireq
.u
.mode
= IW_MODE_MONITOR
;
5215 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
5217 * Scientist, you've failed.
5218 * Bring the interface back up if we shut it down.
5220 ifr
.ifr_flags
= oldflags
;
5221 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5222 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5223 "%s: Can't set flags: %s", device
, strerror(errno
));
5226 return PCAP_ERROR_RFMON_NOTSUP
;
5230 * XXX - airmon-ng does "iwconfig {if} key off" after setting
5231 * monitor mode and setting the channel, and then does
5236 * Now select the appropriate radio header.
5242 * We don't have any private ioctl to set the header.
5246 case MONITOR_HOSTAP
:
5248 * Try to select the radiotap header.
5250 memset(&ireq
, 0, sizeof ireq
);
5251 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5252 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5253 args
[0] = 3; /* request radiotap header */
5254 memcpy(ireq
.u
.name
, args
, sizeof (int));
5255 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5256 break; /* success */
5259 * That failed. Try to select the AVS header.
5261 memset(&ireq
, 0, sizeof ireq
);
5262 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5263 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5264 args
[0] = 2; /* request AVS header */
5265 memcpy(ireq
.u
.name
, args
, sizeof (int));
5266 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5267 break; /* success */
5270 * That failed. Try to select the Prism header.
5272 memset(&ireq
, 0, sizeof ireq
);
5273 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5274 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5275 args
[0] = 1; /* request Prism header */
5276 memcpy(ireq
.u
.name
, args
, sizeof (int));
5277 ioctl(sock_fd
, cmd
, &ireq
);
5282 * The private ioctl failed.
5286 case MONITOR_PRISM54
:
5288 * Select the Prism header.
5290 memset(&ireq
, 0, sizeof ireq
);
5291 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5292 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5293 args
[0] = 3; /* request Prism header */
5294 memcpy(ireq
.u
.name
, args
, sizeof (int));
5295 ioctl(sock_fd
, cmd
, &ireq
);
5298 case MONITOR_ACX100
:
5300 * Get the current channel.
5302 memset(&ireq
, 0, sizeof ireq
);
5303 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5304 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5305 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
5306 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5307 "%s: SIOCGIWFREQ: %s", device
,
5308 pcap_strerror(errno
));
5311 channel
= ireq
.u
.freq
.m
;
5314 * Select the Prism header, and set the channel to the
5317 memset(&ireq
, 0, sizeof ireq
);
5318 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5319 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5320 args
[0] = 1; /* request Prism header */
5321 args
[1] = channel
; /* set channel */
5322 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
5323 ioctl(sock_fd
, cmd
, &ireq
);
5326 case MONITOR_RT2500
:
5328 * Disallow transmission - that turns on the
5331 memset(&ireq
, 0, sizeof ireq
);
5332 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5333 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5334 args
[0] = 0; /* disallow transmitting */
5335 memcpy(ireq
.u
.name
, args
, sizeof (int));
5336 ioctl(sock_fd
, cmd
, &ireq
);
5339 case MONITOR_RT2570
:
5341 * Force the Prism header.
5343 memset(&ireq
, 0, sizeof ireq
);
5344 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5345 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5346 args
[0] = 1; /* request Prism header */
5347 memcpy(ireq
.u
.name
, args
, sizeof (int));
5348 ioctl(sock_fd
, cmd
, &ireq
);
5353 * Force the Prism header.
5355 memset(&ireq
, 0, sizeof ireq
);
5356 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5357 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5358 ireq
.u
.data
.length
= 1; /* 1 argument */
5359 ireq
.u
.data
.pointer
= "1";
5360 ireq
.u
.data
.flags
= 0;
5361 ioctl(sock_fd
, cmd
, &ireq
);
5364 case MONITOR_RTL8XXX
:
5366 * Force the Prism header.
5368 memset(&ireq
, 0, sizeof ireq
);
5369 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5370 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5371 args
[0] = 1; /* request Prism header */
5372 memcpy(ireq
.u
.name
, args
, sizeof (int));
5373 ioctl(sock_fd
, cmd
, &ireq
);
5378 * Now bring the interface back up if we brought it down.
5380 if (oldflags
!= 0) {
5381 ifr
.ifr_flags
= oldflags
;
5382 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5383 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5384 "%s: Can't set flags: %s", device
, strerror(errno
));
5387 * At least try to restore the old mode on the
5390 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
5392 * Scientist, you've failed.
5395 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5396 "Please adjust manually.\n",
5404 * Note that we have to put the old mode back when we
5407 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5410 * Add this to the list of pcaps to close when we exit.
5412 pcap_add_to_pcaps_to_close(handle
);
5416 #endif /* IW_MODE_MONITOR */
5419 * Try various mechanisms to enter monitor mode.
5422 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
5424 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5429 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
5431 return ret
; /* error attempting to do so */
5433 return 1; /* success */
5434 #endif /* HAVE_LIBNL */
5436 #ifdef IW_MODE_MONITOR
5437 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
5439 return ret
; /* error attempting to do so */
5441 return 1; /* success */
5442 #endif /* IW_MODE_MONITOR */
5445 * Either none of the mechanisms we know about work or none
5446 * of those mechanisms are available, so we can't do monitor
5452 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5454 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5456 static const struct {
5457 int soft_timestamping_val
;
5458 int pcap_tstamp_val
;
5459 } sof_ts_type_map
[3] = {
5460 { SOF_TIMESTAMPING_SOFTWARE
, PCAP_TSTAMP_HOST
},
5461 { SOF_TIMESTAMPING_SYS_HARDWARE
, PCAP_TSTAMP_ADAPTER
},
5462 { SOF_TIMESTAMPING_RAW_HARDWARE
, PCAP_TSTAMP_ADAPTER_UNSYNCED
}
5464 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5466 #ifdef ETHTOOL_GET_TS_INFO
5468 * Get a list of time stamping capabilities.
5471 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf
)
5475 struct ethtool_ts_info info
;
5480 * Create a socket from which to fetch time stamping capabilities.
5482 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
5484 (void)snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5485 "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO): %s", pcap_strerror(errno
));
5489 memset(&ifr
, 0, sizeof(ifr
));
5490 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5491 memset(&info
, 0, sizeof(info
));
5492 info
.cmd
= ETHTOOL_GET_TS_INFO
;
5493 ifr
.ifr_data
= (caddr_t
)&info
;
5494 if (ioctl(fd
, SIOCETHTOOL
, &ifr
) == -1) {
5495 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
5497 * OK, let's just return all the possible time
5500 return SOF_TIMESTAMPING_SOFTWARE
|SOF_TIMESTAMPING_SYS_HARDWARE
|SOF_TIMESTAMPING_RAW_HARDWARE
;
5502 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5503 "%s: SIOETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: %s", handle
->opt
.source
,
5511 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5512 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
)
5515 handle
->tstamp_type_count
= num_ts_types
;
5516 if (num_ts_types
!= 0) {
5517 handle
->tstamp_type_list
= malloc(num_ts_types
* sizeof(u_int
));
5518 for (i
= 0, j
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++) {
5519 if (info
.so_timestamping
& sof_ts_type_map
[i
].soft_timestamping_val
) {
5520 handle
->tstamp_type_list
[j
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5525 handle
->tstamp_type_list
= NULL
;
5529 #else /* ETHTOOL_GET_TS_INFO */
5531 iface_ethtool_get_ts_info(pcap_t
*handle
, char *ebuf _U_
)
5536 * We don't have an ioctl to use to ask what's supported,
5537 * so say we support everything.
5539 handle
->tstamp_type_count
= NUM_SOF_TIMESTAMPING_TYPES
;
5540 handle
->tstamp_type_list
= malloc(NUM_SOF_TIMESTAMPING_TYPES
* sizeof(u_int
));
5541 for (i
= 0; i
< NUM_SOF_TIMESTAMPING_TYPES
; i
++)
5542 handle
->tstamp_type_list
[i
] = sof_ts_type_map
[i
].pcap_tstamp_val
;
5545 #endif /* ETHTOOL_GET_TS_INFO */
5547 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5550 * Find out if we have any form of fragmentation/reassembly offloading.
5552 * We do so using SIOCETHTOOL checking for various types of offloading;
5553 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5554 * of the types of offloading, there's nothing we can do to check, so
5555 * we just say "no, we don't".
5557 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5559 iface_ethtool_flag_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
5562 struct ethtool_value eval
;
5564 memset(&ifr
, 0, sizeof(ifr
));
5565 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5568 ifr
.ifr_data
= (caddr_t
)&eval
;
5569 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5570 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
5572 * OK, let's just return 0, which, in our
5573 * case, either means "no, what we're asking
5574 * about is not enabled" or "all the flags
5575 * are clear (i.e., nothing is enabled)".
5579 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5580 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
5581 cmdname
, strerror(errno
));
5588 iface_get_offload(pcap_t
*handle
)
5593 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
5597 return 1; /* TCP segmentation offloading on */
5601 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
5605 return 1; /* UDP fragmentation offloading on */
5610 * XXX - will this cause large unsegmented packets to be
5611 * handed to PF_PACKET sockets on transmission? If not,
5612 * this need not be checked.
5614 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
5618 return 1; /* generic segmentation offloading on */
5621 #ifdef ETHTOOL_GFLAGS
5622 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
5625 if (ret
& ETH_FLAG_LRO
)
5626 return 1; /* large receive offloading on */
5631 * XXX - will this cause large reassembled packets to be
5632 * handed to PF_PACKET sockets on receipt? If not,
5633 * this need not be checked.
5635 ret
= iface_ethtool_flag_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
5639 return 1; /* generic (large) receive offloading on */
5644 #else /* SIOCETHTOOL */
5646 iface_get_offload(pcap_t
*handle _U_
)
5649 * XXX - do we need to get this information if we don't
5650 * have the ethtool ioctls? If so, how do we do that?
5654 #endif /* SIOCETHTOOL */
5656 #endif /* HAVE_PF_PACKET_SOCKETS */
5658 /* ===== Functions to interface to the older kernels ================== */
5661 * Try to open a packet socket using the old kernel interface.
5662 * Returns 1 on success and a PCAP_ERROR_ value on an error.
5665 activate_old(pcap_t
*handle
)
5667 struct pcap_linux
*handlep
= handle
->priv
;
5670 const char *device
= handle
->opt
.source
;
5671 struct utsname utsname
;
5674 /* Open the socket */
5676 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
5677 if (handle
->fd
== -1) {
5678 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5679 "socket: %s", pcap_strerror(errno
));
5680 if (errno
== EPERM
|| errno
== EACCES
) {
5682 * You don't have permission to open the
5685 return PCAP_ERROR_PERM_DENIED
;
5694 /* It worked - we are using the old interface */
5695 handlep
->sock_packet
= 1;
5697 /* ...which means we get the link-layer header. */
5698 handlep
->cooked
= 0;
5700 /* Bind to the given device */
5702 if (strcmp(device
, "any") == 0) {
5703 strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
5707 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
5711 * Try to get the link-layer type.
5713 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
5718 * Try to find the DLT_ type corresponding to that
5721 map_arphrd_to_dlt(handle
, arptype
, device
, 0);
5722 if (handle
->linktype
== -1) {
5723 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5724 "unknown arptype %d", arptype
);
5728 /* Go to promisc mode if requested */
5730 if (handle
->opt
.promisc
) {
5731 memset(&ifr
, 0, sizeof(ifr
));
5732 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5733 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5734 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5735 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
5738 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
5740 * Promiscuous mode isn't currently on,
5741 * so turn it on, and remember that
5742 * we should turn it off when the
5747 * If we haven't already done so, arrange
5748 * to have "pcap_close_all()" called when
5751 if (!pcap_do_addexit(handle
)) {
5753 * "atexit()" failed; don't put
5754 * the interface in promiscuous
5755 * mode, just give up.
5760 ifr
.ifr_flags
|= IFF_PROMISC
;
5761 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5762 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5764 pcap_strerror(errno
));
5767 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
5770 * Add this to the list of pcaps
5771 * to close when we exit.
5773 pcap_add_to_pcaps_to_close(handle
);
5778 * Compute the buffer size.
5780 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5781 * kernel, and might require special handling - check.
5783 if (uname(&utsname
) < 0 ||
5784 strncmp(utsname
.release
, "2.0", 3) == 0) {
5786 * Either we couldn't find out what kernel release
5787 * this is, or it's a 2.0[.x] kernel.
5789 * In the 2.0[.x] kernel, a "recvfrom()" on
5790 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5791 * return the number of bytes read, so if we pass
5792 * a length based on the snapshot length, it'll
5793 * return the number of bytes from the packet
5794 * copied to userland, not the actual length
5797 * This means that, for example, the IP dissector
5798 * in tcpdump will get handed a packet length less
5799 * than the length in the IP header, and will
5800 * complain about "truncated-ip".
5802 * So we don't bother trying to copy from the
5803 * kernel only the bytes in which we're interested,
5804 * but instead copy them all, just as the older
5805 * versions of libpcap for Linux did.
5807 * The buffer therefore needs to be big enough to
5808 * hold the largest packet we can get from this
5809 * device. Unfortunately, we can't get the MRU
5810 * of the network; we can only get the MTU. The
5811 * MTU may be too small, in which case a packet larger
5812 * than the buffer size will be truncated *and* we
5813 * won't get the actual packet size.
5815 * However, if the snapshot length is larger than
5816 * the buffer size based on the MTU, we use the
5817 * snapshot length as the buffer size, instead;
5818 * this means that with a sufficiently large snapshot
5819 * length we won't artificially truncate packets
5820 * to the MTU-based size.
5822 * This mess just one of many problems with packet
5823 * capture on 2.0[.x] kernels; you really want a
5824 * 2.2[.x] or later kernel if you want packet capture
5827 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
5830 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
5831 if (handle
->bufsize
< handle
->snapshot
)
5832 handle
->bufsize
= handle
->snapshot
;
5835 * This is a 2.2[.x] or later kernel.
5837 * We can safely pass "recvfrom()" a byte count
5838 * based on the snapshot length.
5840 handle
->bufsize
= handle
->snapshot
;
5844 * Default value for offset to align link-layer payload
5845 * on a 4-byte boundary.
5850 * SOCK_PACKET sockets don't supply information from
5851 * stripped VLAN tags.
5853 handlep
->vlan_offset
= -1; /* unknown */
5859 * Bind the socket associated with FD to the given device using the
5860 * interface of the old kernels.
5863 iface_bind_old(int fd
, const char *device
, char *ebuf
)
5865 struct sockaddr saddr
;
5867 socklen_t errlen
= sizeof(err
);
5869 memset(&saddr
, 0, sizeof(saddr
));
5870 strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
5871 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
5872 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5873 "bind: %s", pcap_strerror(errno
));
5877 /* Any pending errors, e.g., network is down? */
5879 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5880 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5881 "getsockopt: %s", pcap_strerror(errno
));
5886 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5887 "bind: %s", pcap_strerror(err
));
5895 /* ===== System calls available on all supported kernels ============== */
5898 * Query the kernel for the MTU of the given interface.
5901 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5906 return BIGGER_THAN_ALL_MTUS
;
5908 memset(&ifr
, 0, sizeof(ifr
));
5909 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5911 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5912 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5913 "SIOCGIFMTU: %s", pcap_strerror(errno
));
5921 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5924 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5928 memset(&ifr
, 0, sizeof(ifr
));
5929 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5931 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5932 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5933 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
5934 if (errno
== ENODEV
) {
5938 return PCAP_ERROR_NO_SUCH_DEVICE
;
5943 return ifr
.ifr_hwaddr
.sa_family
;
5946 #ifdef SO_ATTACH_FILTER
5948 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
5950 struct pcap_linux
*handlep
= handle
->priv
;
5953 register struct bpf_insn
*p
;
5958 * Make a copy of the filter, and modify that copy if
5961 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5962 len
= handle
->fcode
.bf_len
;
5963 f
= (struct bpf_insn
*)malloc(prog_size
);
5965 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5966 "malloc: %s", pcap_strerror(errno
));
5969 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5971 fcode
->filter
= (struct sock_filter
*) f
;
5973 for (i
= 0; i
< len
; ++i
) {
5976 * What type of instruction is this?
5978 switch (BPF_CLASS(p
->code
)) {
5982 * It's a return instruction; are we capturing
5983 * in memory-mapped mode?
5987 * No; is the snapshot length a constant,
5988 * rather than the contents of the
5991 if (BPF_MODE(p
->code
) == BPF_K
) {
5993 * Yes - if the value to be returned,
5994 * i.e. the snapshot length, is
5995 * anything other than 0, make it
5996 * MAXIMUM_SNAPLEN, so that the packet
5997 * is truncated by "recvfrom()",
5998 * not by the filter.
6000 * XXX - there's nothing we can
6001 * easily do if it's getting the
6002 * value from the accumulator; we'd
6003 * have to insert code to force
6004 * non-zero values to be
6008 p
->k
= MAXIMUM_SNAPLEN
;
6016 * It's a load instruction; is it loading
6019 switch (BPF_MODE(p
->code
)) {
6025 * Yes; are we in cooked mode?
6027 if (handlep
->cooked
) {
6029 * Yes, so we need to fix this
6032 if (fix_offset(p
) < 0) {
6034 * We failed to do so.
6035 * Return 0, so our caller
6036 * knows to punt to userland.
6046 return 1; /* we succeeded */
6050 fix_offset(struct bpf_insn
*p
)
6053 * What's the offset?
6055 if (p
->k
>= SLL_HDR_LEN
) {
6057 * It's within the link-layer payload; that starts at an
6058 * offset of 0, as far as the kernel packet filter is
6059 * concerned, so subtract the length of the link-layer
6062 p
->k
-= SLL_HDR_LEN
;
6063 } else if (p
->k
== 0) {
6065 * It's the packet type field; map it to the special magic
6066 * kernel offset for that field.
6068 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
6069 } else if (p
->k
== 14) {
6071 * It's the protocol field; map it to the special magic
6072 * kernel offset for that field.
6074 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
6075 } else if ((bpf_int32
)(p
->k
) > 0) {
6077 * It's within the header, but it's not one of those
6078 * fields; we can't do that in the kernel, so punt
6087 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
6089 int total_filter_on
= 0;
6095 * The socket filter code doesn't discard all packets queued
6096 * up on the socket when the filter is changed; this means
6097 * that packets that don't match the new filter may show up
6098 * after the new filter is put onto the socket, if those
6099 * packets haven't yet been read.
6101 * This means, for example, that if you do a tcpdump capture
6102 * with a filter, the first few packets in the capture might
6103 * be packets that wouldn't have passed the filter.
6105 * We therefore discard all packets queued up on the socket
6106 * when setting a kernel filter. (This isn't an issue for
6107 * userland filters, as the userland filtering is done after
6108 * packets are queued up.)
6110 * To flush those packets, we put the socket in read-only mode,
6111 * and read packets from the socket until there are no more to
6114 * In order to keep that from being an infinite loop - i.e.,
6115 * to keep more packets from arriving while we're draining
6116 * the queue - we put the "total filter", which is a filter
6117 * that rejects all packets, onto the socket before draining
6120 * This code deliberately ignores any errors, so that you may
6121 * get bogus packets if an error occurs, rather than having
6122 * the filtering done in userland even if it could have been
6123 * done in the kernel.
6125 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6126 &total_fcode
, sizeof(total_fcode
)) == 0) {
6130 * Note that we've put the total filter onto the socket.
6132 total_filter_on
= 1;
6135 * Save the socket's current mode, and put it in
6136 * non-blocking mode; we drain it by reading packets
6137 * until we get an error (which is normally a
6138 * "nothing more to be read" error).
6140 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6141 if (save_mode
== -1) {
6142 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6143 "can't get FD flags when changing filter: %s",
6144 pcap_strerror(errno
));
6147 if (fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) < 0) {
6148 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6149 "can't set nonblocking mode when changing filter: %s",
6150 pcap_strerror(errno
));
6153 while (recv(handle
->fd
, &drain
, sizeof drain
, MSG_TRUNC
) >= 0)
6156 if (save_errno
!= EAGAIN
) {
6160 * If we can't restore the mode or reset the
6161 * kernel filter, there's nothing we can do.
6163 (void)fcntl(handle
->fd
, F_SETFL
, save_mode
);
6164 (void)reset_kernel_filter(handle
);
6165 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6166 "recv failed when changing filter: %s",
6167 pcap_strerror(save_errno
));
6170 if (fcntl(handle
->fd
, F_SETFL
, save_mode
) == -1) {
6171 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6172 "can't restore FD flags when changing filter: %s",
6173 pcap_strerror(save_errno
));
6179 * Now attach the new filter.
6181 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6182 fcode
, sizeof(*fcode
));
6183 if (ret
== -1 && total_filter_on
) {
6185 * Well, we couldn't set that filter on the socket,
6186 * but we could set the total filter on the socket.
6188 * This could, for example, mean that the filter was
6189 * too big to put into the kernel, so we'll have to
6190 * filter in userland; in any case, we'll be doing
6191 * filtering in userland, so we need to remove the
6192 * total filter so we see packets.
6197 * If this fails, we're really screwed; we have the
6198 * total filter on the socket, and it won't come off.
6199 * Report it as a fatal error.
6201 if (reset_kernel_filter(handle
) == -1) {
6202 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6203 "can't remove kernel total filter: %s",
6204 pcap_strerror(errno
));
6205 return -2; /* fatal error */
6214 reset_kernel_filter(pcap_t
*handle
)
6217 * setsockopt() barfs unless it get a dummy parameter.
6218 * valgrind whines unless the value is initialized,
6219 * as it has no idea that setsockopt() ignores its
6224 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6225 &dummy
, sizeof(dummy
));