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 static int iface_get_offload(pcap_t
*handle
);
386 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
388 #ifdef SO_ATTACH_FILTER
389 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
391 static int fix_offset(struct bpf_insn
*p
);
392 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
393 static int reset_kernel_filter(pcap_t
*handle
);
395 static struct sock_filter total_insn
396 = BPF_STMT(BPF_RET
| BPF_K
, 0);
397 static struct sock_fprog total_fcode
398 = { 1, &total_insn
};
399 #endif /* SO_ATTACH_FILTER */
402 pcap_create_interface(const char *device
, char *ebuf
)
406 handle
= pcap_create_common(device
, ebuf
, sizeof (struct pcap_linux
));
410 handle
->activate_op
= pcap_activate_linux
;
411 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
412 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
414 * We claim that we support:
416 * software time stamps, with no details about their precision;
417 * hardware time stamps, synced to the host time;
418 * hardware time stamps, not synced to the host time.
420 * XXX - we can't ask a device whether it supports
421 * hardware time stamps, so we just claim all devices do.
423 handle
->tstamp_type_count
= 3;
424 handle
->tstamp_type_list
= malloc(3 * sizeof(u_int
));
425 if (handle
->tstamp_type_list
== NULL
) {
426 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
427 pcap_strerror(errno
));
431 handle
->tstamp_type_list
[0] = PCAP_TSTAMP_HOST
;
432 handle
->tstamp_type_list
[1] = PCAP_TSTAMP_ADAPTER
;
433 handle
->tstamp_type_list
[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED
;
436 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
438 * We claim that we support microsecond and nanosecond time
441 * XXX - with adapter-supplied time stamps, can we choose
442 * microsecond or nanosecond time stamps on arbitrary
445 handle
->tstamp_precision_count
= 2;
446 handle
->tstamp_precision_list
= malloc(2 * sizeof(u_int
));
447 if (handle
->tstamp_precision_list
== NULL
) {
448 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
449 pcap_strerror(errno
));
450 if (handle
->tstamp_type_list
!= NULL
)
451 free(handle
->tstamp_type_list
);
455 handle
->tstamp_precision_list
[0] = PCAP_TSTAMP_PRECISION_MICRO
;
456 handle
->tstamp_precision_list
[1] = PCAP_TSTAMP_PRECISION_NANO
;
457 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
464 * If interface {if} is a mac80211 driver, the file
465 * /sys/class/net/{if}/phy80211 is a symlink to
466 * /sys/class/ieee80211/{phydev}, for some {phydev}.
468 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
469 * least, has a "wmaster0" device and a "wlan0" device; the
470 * latter is the one with the IP address. Both show up in
471 * "tcpdump -D" output. Capturing on the wmaster0 device
472 * captures with 802.11 headers.
474 * airmon-ng searches through /sys/class/net for devices named
475 * monN, starting with mon0; as soon as one *doesn't* exist,
476 * it chooses that as the monitor device name. If the "iw"
477 * command exists, it does "iw dev {if} interface add {monif}
478 * type monitor", where {monif} is the monitor device. It
479 * then (sigh) sleeps .1 second, and then configures the
480 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
481 * is a file, it writes {mondev}, without a newline, to that file,
482 * and again (sigh) sleeps .1 second, and then iwconfig's that
483 * device into monitor mode and configures it up. Otherwise,
484 * you can't do monitor mode.
486 * All these devices are "glued" together by having the
487 * /sys/class/net/{device}/phy80211 links pointing to the same
488 * place, so, given a wmaster, wlan, or mon device, you can
489 * find the other devices by looking for devices with
490 * the same phy80211 link.
492 * To turn monitor mode off, delete the monitor interface,
493 * either with "iw dev {monif} interface del" or by sending
494 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
496 * Note: if you try to create a monitor device named "monN", and
497 * there's already a "monN" device, it fails, as least with
498 * the netlink interface (which is what iw uses), with a return
499 * value of -ENFILE. (Return values are negative errnos.) We
500 * could probably use that to find an unused device.
502 * Yes, you can have multiple monitor devices for a given
507 * Is this a mac80211 device? If so, fill in the physical device path and
508 * return 1; if not, return 0. On an error, fill in handle->errbuf and
512 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
513 size_t phydev_max_pathlen
)
519 * Generate the path string for the symlink to the physical device.
521 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
522 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
523 "%s: Can't generate path name string for /sys/class/net device",
527 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
528 if (bytes_read
== -1) {
529 if (errno
== ENOENT
|| errno
== EINVAL
) {
531 * Doesn't exist, or not a symlink; assume that
532 * means it's not a mac80211 device.
537 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
538 "%s: Can't readlink %s: %s", device
, pathstr
,
544 phydev_path
[bytes_read
] = '\0';
548 #ifdef HAVE_LIBNL_SOCKETS
549 #define get_nl_errmsg nl_geterror
551 /* libnl 2.x compatibility code */
553 #define nl_sock nl_handle
555 static inline struct nl_handle
*
556 nl_socket_alloc(void)
558 return nl_handle_alloc();
562 nl_socket_free(struct nl_handle
*h
)
564 nl_handle_destroy(h
);
567 #define get_nl_errmsg strerror
570 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
572 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
578 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
579 #endif /* !HAVE_LIBNL_SOCKETS */
581 struct nl80211_state
{
582 struct nl_sock
*nl_sock
;
583 struct nl_cache
*nl_cache
;
584 struct genl_family
*nl80211
;
588 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
592 state
->nl_sock
= nl_socket_alloc();
593 if (!state
->nl_sock
) {
594 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
595 "%s: failed to allocate netlink handle", device
);
599 if (genl_connect(state
->nl_sock
)) {
600 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
601 "%s: failed to connect to generic netlink", device
);
602 goto out_handle_destroy
;
605 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
607 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
608 "%s: failed to allocate generic netlink cache: %s",
609 device
, get_nl_errmsg(-err
));
610 goto out_handle_destroy
;
613 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
614 if (!state
->nl80211
) {
615 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
616 "%s: nl80211 not found", device
);
623 nl_cache_free(state
->nl_cache
);
625 nl_socket_free(state
->nl_sock
);
630 nl80211_cleanup(struct nl80211_state
*state
)
632 genl_family_put(state
->nl80211
);
633 nl_cache_free(state
->nl_cache
);
634 nl_socket_free(state
->nl_sock
);
638 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
639 const char *device
, const char *mondevice
)
645 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
651 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
652 "%s: failed to allocate netlink msg", device
);
656 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
657 0, NL80211_CMD_NEW_INTERFACE
, 0);
658 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
659 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
660 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
662 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
664 #if defined HAVE_LIBNL_NLE
665 if (err
== -NLE_FAILURE
) {
667 if (err
== -ENFILE
) {
670 * Device not available; our caller should just
671 * keep trying. (libnl 2.x maps ENFILE to
672 * NLE_FAILURE; it can also map other errors
673 * to that, but there's not much we can do
680 * Real failure, not just "that device is not
683 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
684 "%s: nl_send_auto_complete failed adding %s interface: %s",
685 device
, mondevice
, get_nl_errmsg(-err
));
690 err
= nl_wait_for_ack(state
->nl_sock
);
692 #if defined HAVE_LIBNL_NLE
693 if (err
== -NLE_FAILURE
) {
695 if (err
== -ENFILE
) {
698 * Device not available; our caller should just
699 * keep trying. (libnl 2.x maps ENFILE to
700 * NLE_FAILURE; it can also map other errors
701 * to that, but there's not much we can do
708 * Real failure, not just "that device is not
711 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
712 "%s: nl_wait_for_ack failed adding %s interface: %s",
713 device
, mondevice
, get_nl_errmsg(-err
));
726 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
727 "%s: nl_put failed adding %s interface",
734 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
735 const char *device
, const char *mondevice
)
741 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
747 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
748 "%s: failed to allocate netlink msg", device
);
752 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
753 0, NL80211_CMD_DEL_INTERFACE
, 0);
754 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
756 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
758 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
759 "%s: nl_send_auto_complete failed deleting %s interface: %s",
760 device
, mondevice
, get_nl_errmsg(-err
));
764 err
= nl_wait_for_ack(state
->nl_sock
);
766 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
767 "%s: nl_wait_for_ack failed adding %s interface: %s",
768 device
, mondevice
, get_nl_errmsg(-err
));
780 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
781 "%s: nl_put failed deleting %s interface",
788 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
790 struct pcap_linux
*handlep
= handle
->priv
;
792 char phydev_path
[PATH_MAX
+1];
793 struct nl80211_state nlstate
;
798 * Is this a mac80211 device?
800 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
802 return ret
; /* error */
804 return 0; /* no error, but not mac80211 device */
807 * XXX - is this already a monN device?
809 * Is that determined by old Wireless Extensions ioctls?
813 * OK, it's apparently a mac80211 device.
814 * Try to find an unused monN device for it.
816 ret
= nl80211_init(handle
, &nlstate
, device
);
819 for (n
= 0; n
< UINT_MAX
; n
++) {
823 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
825 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
826 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
828 handlep
->mondevice
= strdup(mondevice
);
833 * Hard failure. Just return ret; handle->errbuf
834 * has already been set.
836 nl80211_cleanup(&nlstate
);
841 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
842 "%s: No free monN interfaces", device
);
843 nl80211_cleanup(&nlstate
);
850 * Sleep for .1 seconds.
853 delay
.tv_nsec
= 500000000;
854 nanosleep(&delay
, NULL
);
858 * If we haven't already done so, arrange to have
859 * "pcap_close_all()" called when we exit.
861 if (!pcap_do_addexit(handle
)) {
863 * "atexit()" failed; don't put the interface
864 * in rfmon mode, just give up.
866 return PCAP_ERROR_RFMON_NOTSUP
;
870 * Now configure the monitor interface up.
872 memset(&ifr
, 0, sizeof(ifr
));
873 strlcpy(ifr
.ifr_name
, handlep
->mondevice
, sizeof(ifr
.ifr_name
));
874 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
875 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
876 "%s: Can't get flags for %s: %s", device
,
877 handlep
->mondevice
, strerror(errno
));
878 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
880 nl80211_cleanup(&nlstate
);
883 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
884 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
885 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
886 "%s: Can't set flags for %s: %s", device
,
887 handlep
->mondevice
, strerror(errno
));
888 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
890 nl80211_cleanup(&nlstate
);
895 * Success. Clean up the libnl state.
897 nl80211_cleanup(&nlstate
);
900 * Note that we have to delete the monitor device when we close
903 handlep
->must_do_on_close
|= MUST_DELETE_MONIF
;
906 * Add this to the list of pcaps to close when we exit.
908 pcap_add_to_pcaps_to_close(handle
);
912 #endif /* HAVE_LIBNL */
915 pcap_can_set_rfmon_linux(pcap_t
*handle
)
918 char phydev_path
[PATH_MAX
+1];
921 #ifdef IW_MODE_MONITOR
926 if (strcmp(handle
->opt
.source
, "any") == 0) {
928 * Monitor mode makes no sense on the "any" device.
935 * Bleah. There doesn't seem to be a way to ask a mac80211
936 * device, through libnl, whether it supports monitor mode;
937 * we'll just check whether the device appears to be a
938 * mac80211 device and, if so, assume the device supports
941 * wmaster devices don't appear to support the Wireless
942 * Extensions, but we can create a mon device for a
943 * wmaster device, so we don't bother checking whether
944 * a mac80211 device supports the Wireless Extensions.
946 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
949 return ret
; /* error */
951 return 1; /* mac80211 device */
954 #ifdef IW_MODE_MONITOR
956 * Bleah. There doesn't appear to be an ioctl to use to ask
957 * whether a device supports monitor mode; we'll just do
958 * SIOCGIWMODE and, if it succeeds, assume the device supports
961 * Open a socket on which to attempt to get the mode.
962 * (We assume that if we have Wireless Extensions support
963 * we also have PF_PACKET support.)
965 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
967 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
968 "socket: %s", pcap_strerror(errno
));
973 * Attempt to get the current mode.
975 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
976 sizeof ireq
.ifr_ifrn
.ifrn_name
);
977 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
979 * Well, we got the mode; assume we can set it.
984 if (errno
== ENODEV
) {
985 /* The device doesn't even exist. */
986 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
987 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
989 return PCAP_ERROR_NO_SUCH_DEVICE
;
997 * Grabs the number of dropped packets by the interface from /proc/net/dev.
999 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1000 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1002 * Or can we get them in binary form from netlink?
1005 linux_if_drops(const char * if_name
)
1010 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1011 long int dropped_pkts
= 0;
1013 file
= fopen("/proc/net/dev", "r");
1017 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1019 /* search for 'bytes' -- if its in there, then
1020 that means we need to grab the fourth field. otherwise
1021 grab the third field. */
1022 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1024 field_to_convert
= 4;
1028 /* find iface and make sure it actually matches -- space before the name and : after it */
1029 if ((bufptr
= strstr(buffer
, if_name
)) &&
1030 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1031 *(bufptr
+ if_name_sz
) == ':')
1033 bufptr
= bufptr
+ if_name_sz
+ 1;
1035 /* grab the nth field from it */
1036 while( --field_to_convert
&& *bufptr
!= '\0')
1038 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1039 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1042 /* get rid of any final spaces */
1043 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1045 if (*bufptr
!= '\0')
1046 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1053 return dropped_pkts
;
1058 * With older kernels promiscuous mode is kind of interesting because we
1059 * have to reset the interface before exiting. The problem can't really
1060 * be solved without some daemon taking care of managing usage counts.
1061 * If we put the interface into promiscuous mode, we set a flag indicating
1062 * that we must take it out of that mode when the interface is closed,
1063 * and, when closing the interface, if that flag is set we take it out
1064 * of promiscuous mode.
1066 * Even with newer kernels, we have the same issue with rfmon mode.
1069 static void pcap_cleanup_linux( pcap_t
*handle
)
1071 struct pcap_linux
*handlep
= handle
->priv
;
1074 struct nl80211_state nlstate
;
1076 #endif /* HAVE_LIBNL */
1077 #ifdef IW_MODE_MONITOR
1080 #endif /* IW_MODE_MONITOR */
1082 if (handlep
->must_do_on_close
!= 0) {
1084 * There's something we have to do when closing this
1087 if (handlep
->must_do_on_close
& MUST_CLEAR_PROMISC
) {
1089 * We put the interface into promiscuous mode;
1090 * take it out of promiscuous mode.
1092 * XXX - if somebody else wants it in promiscuous
1093 * mode, this code cannot know that, so it'll take
1094 * it out of promiscuous mode. That's not fixable
1095 * in 2.0[.x] kernels.
1097 memset(&ifr
, 0, sizeof(ifr
));
1098 strlcpy(ifr
.ifr_name
, handlep
->device
,
1099 sizeof(ifr
.ifr_name
));
1100 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1102 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1103 "Please adjust manually.\n"
1104 "Hint: This can't happen with Linux >= 2.2.0.\n",
1105 handlep
->device
, strerror(errno
));
1107 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1109 * Promiscuous mode is currently on;
1112 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1113 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1116 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1117 "Please adjust manually.\n"
1118 "Hint: This can't happen with Linux >= 2.2.0.\n",
1127 if (handlep
->must_do_on_close
& MUST_DELETE_MONIF
) {
1128 ret
= nl80211_init(handle
, &nlstate
, handlep
->device
);
1130 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1131 handlep
->device
, handlep
->mondevice
);
1132 nl80211_cleanup(&nlstate
);
1136 "Can't delete monitor interface %s (%s).\n"
1137 "Please delete manually.\n",
1138 handlep
->mondevice
, handle
->errbuf
);
1141 #endif /* HAVE_LIBNL */
1143 #ifdef IW_MODE_MONITOR
1144 if (handlep
->must_do_on_close
& MUST_CLEAR_RFMON
) {
1146 * We put the interface into rfmon mode;
1147 * take it out of rfmon mode.
1149 * XXX - if somebody else wants it in rfmon
1150 * mode, this code cannot know that, so it'll take
1151 * it out of rfmon mode.
1155 * First, take the interface down if it's up;
1156 * otherwise, we might get EBUSY.
1157 * If we get errors, just drive on and print
1158 * a warning if we can't restore the mode.
1161 memset(&ifr
, 0, sizeof(ifr
));
1162 strlcpy(ifr
.ifr_name
, handlep
->device
,
1163 sizeof(ifr
.ifr_name
));
1164 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) != -1) {
1165 if (ifr
.ifr_flags
& IFF_UP
) {
1166 oldflags
= ifr
.ifr_flags
;
1167 ifr
.ifr_flags
&= ~IFF_UP
;
1168 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1)
1169 oldflags
= 0; /* didn't set, don't restore */
1174 * Now restore the mode.
1176 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, handlep
->device
,
1177 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1178 ireq
.u
.mode
= handlep
->oldmode
;
1179 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1181 * Scientist, you've failed.
1184 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1185 "Please adjust manually.\n",
1186 handlep
->device
, strerror(errno
));
1190 * Now bring the interface back up if we brought
1193 if (oldflags
!= 0) {
1194 ifr
.ifr_flags
= oldflags
;
1195 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1197 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1198 "Please adjust manually.\n",
1199 handlep
->device
, strerror(errno
));
1203 #endif /* IW_MODE_MONITOR */
1206 * Take this pcap out of the list of pcaps for which we
1207 * have to take the interface out of some mode.
1209 pcap_remove_from_pcaps_to_close(handle
);
1212 if (handlep
->mondevice
!= NULL
) {
1213 free(handlep
->mondevice
);
1214 handlep
->mondevice
= NULL
;
1216 if (handlep
->device
!= NULL
) {
1217 free(handlep
->device
);
1218 handlep
->device
= NULL
;
1220 pcap_cleanup_live_common(handle
);
1224 * Get a handle for a live capture from the given device. You can
1225 * pass NULL as device to get all packages (without link level
1226 * information of course). If you pass 1 as promisc the interface
1227 * will be set to promiscous mode (XXX: I think this usage should
1228 * be deprecated and functions be added to select that later allow
1229 * modification of that values -- Torsten).
1232 pcap_activate_linux(pcap_t
*handle
)
1234 struct pcap_linux
*handlep
= handle
->priv
;
1240 device
= handle
->opt
.source
;
1243 * Make sure the name we were handed will fit into the ioctls we
1244 * might perform on the device; if not, return a "No such device"
1245 * indication, as the Linux kernel shouldn't support creating
1246 * a device whose name won't fit into those ioctls.
1248 * "Will fit" means "will fit, complete with a null terminator",
1249 * so if the length, which does *not* include the null terminator,
1250 * is greater than *or equal to* the size of the field into which
1251 * we'll be copying it, that won't fit.
1253 if (strlen(device
) >= sizeof(ifr
.ifr_name
)) {
1254 status
= PCAP_ERROR_NO_SUCH_DEVICE
;
1258 handle
->inject_op
= pcap_inject_linux
;
1259 handle
->setfilter_op
= pcap_setfilter_linux
;
1260 handle
->setdirection_op
= pcap_setdirection_linux
;
1261 handle
->set_datalink_op
= pcap_set_datalink_linux
;
1262 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1263 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1264 handle
->cleanup_op
= pcap_cleanup_linux
;
1265 handle
->read_op
= pcap_read_linux
;
1266 handle
->stats_op
= pcap_stats_linux
;
1269 * The "any" device is a special device which causes us not
1270 * to bind to a particular device and thus to look at all
1273 if (strcmp(device
, "any") == 0) {
1274 if (handle
->opt
.promisc
) {
1275 handle
->opt
.promisc
= 0;
1276 /* Just a warning. */
1277 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1278 "Promiscuous mode not supported on the \"any\" device");
1279 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1283 handlep
->device
= strdup(device
);
1284 if (handlep
->device
== NULL
) {
1285 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1286 pcap_strerror(errno
) );
1290 /* copy timeout value */
1291 handlep
->timeout
= handle
->opt
.timeout
;
1294 * If we're in promiscuous mode, then we probably want
1295 * to see when the interface drops packets too, so get an
1296 * initial count from /proc/net/dev
1298 if (handle
->opt
.promisc
)
1299 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1302 * Current Linux kernels use the protocol family PF_PACKET to
1303 * allow direct access to all packets on the network while
1304 * older kernels had a special socket type SOCK_PACKET to
1305 * implement this feature.
1306 * While this old implementation is kind of obsolete we need
1307 * to be compatible with older kernels for a while so we are
1308 * trying both methods with the newer method preferred.
1310 ret
= activate_new(handle
);
1313 * Fatal error with the new way; just fail.
1314 * ret has the error return; if it's PCAP_ERROR,
1315 * handle->errbuf has been set appropriately.
1323 * Try to use memory-mapped access.
1325 switch (activate_mmap(handle
, &status
)) {
1329 * We succeeded. status has been
1330 * set to the status to return,
1331 * which might be 0, or might be
1332 * a PCAP_WARNING_ value.
1338 * Kernel doesn't support it - just continue
1339 * with non-memory-mapped access.
1345 * We failed to set up to use it, or the kernel
1346 * supports it, but we failed to enable it.
1347 * ret has been set to the error status to
1348 * return and, if it's PCAP_ERROR, handle->errbuf
1349 * contains the error message.
1355 else if (ret
== 0) {
1356 /* Non-fatal error; try old way */
1357 if ((ret
= activate_old(handle
)) != 1) {
1359 * Both methods to open the packet socket failed.
1360 * Tidy up and report our failure (handle->errbuf
1361 * is expected to be set by the functions above).
1369 * We set up the socket, but not with memory-mapped access.
1371 if (handle
->opt
.buffer_size
!= 0) {
1373 * Set the socket buffer size to the specified value.
1375 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1376 &handle
->opt
.buffer_size
,
1377 sizeof(handle
->opt
.buffer_size
)) == -1) {
1378 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1379 "SO_RCVBUF: %s", pcap_strerror(errno
));
1380 status
= PCAP_ERROR
;
1385 /* Allocate the buffer */
1387 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1388 if (!handle
->buffer
) {
1389 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1390 "malloc: %s", pcap_strerror(errno
));
1391 status
= PCAP_ERROR
;
1396 * "handle->fd" is a socket, so "select()" and "poll()"
1397 * should work on it.
1399 handle
->selectable_fd
= handle
->fd
;
1404 pcap_cleanup_linux(handle
);
1409 * Read at most max_packets from the capture stream and call the callback
1410 * for each of them. Returns the number of packets handled or -1 if an
1414 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1417 * Currently, on Linux only one packet is delivered per read,
1420 return pcap_read_packet(handle
, callback
, user
);
1424 pcap_set_datalink_linux(pcap_t
*handle
, int dlt
)
1426 handle
->linktype
= dlt
;
1431 * linux_check_direction()
1433 * Do checks based on packet direction.
1436 linux_check_direction(const pcap_t
*handle
, const struct sockaddr_ll
*sll
)
1438 struct pcap_linux
*handlep
= handle
->priv
;
1440 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
1443 * If this is from the loopback device, reject it;
1444 * we'll see the packet as an incoming packet as well,
1445 * and we don't want to see it twice.
1447 if (sll
->sll_ifindex
== handlep
->lo_ifindex
)
1451 * If the user only wants incoming packets, reject it.
1453 if (handle
->direction
== PCAP_D_IN
)
1458 * If the user only wants outgoing packets, reject it.
1460 if (handle
->direction
== PCAP_D_OUT
)
1467 * Read a packet from the socket calling the handler provided by
1468 * the user. Returns the number of packets received or -1 if an
1472 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1474 struct pcap_linux
*handlep
= handle
->priv
;
1477 #ifdef HAVE_PF_PACKET_SOCKETS
1478 struct sockaddr_ll from
;
1479 struct sll_header
*hdrp
;
1481 struct sockaddr from
;
1483 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1486 struct cmsghdr
*cmsg
;
1488 struct cmsghdr cmsg
;
1489 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1491 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1493 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1494 int packet_len
, caplen
;
1495 struct pcap_pkthdr pcap_header
;
1497 #ifdef HAVE_PF_PACKET_SOCKETS
1499 * If this is a cooked device, leave extra room for a
1500 * fake packet header.
1502 if (handlep
->cooked
)
1503 offset
= SLL_HDR_LEN
;
1508 * This system doesn't have PF_PACKET sockets, so it doesn't
1509 * support cooked devices.
1515 * Receive a single packet from the kernel.
1516 * We ignore EINTR, as that might just be due to a signal
1517 * being delivered - if the signal should interrupt the
1518 * loop, the signal handler should call pcap_breakloop()
1519 * to set handle->break_loop (we ignore it on other
1520 * platforms as well).
1521 * We also ignore ENETDOWN, so that we can continue to
1522 * capture traffic if the interface goes down and comes
1523 * back up again; comments in the kernel indicate that
1524 * we'll just block waiting for packets if we try to
1525 * receive from a socket that delivered ENETDOWN, and,
1526 * if we're using a memory-mapped buffer, we won't even
1527 * get notified of "network down" events.
1529 bp
= handle
->buffer
+ handle
->offset
;
1531 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1532 msg
.msg_name
= &from
;
1533 msg
.msg_namelen
= sizeof(from
);
1536 msg
.msg_control
= &cmsg_buf
;
1537 msg
.msg_controllen
= sizeof(cmsg_buf
);
1540 iov
.iov_len
= handle
->bufsize
- offset
;
1541 iov
.iov_base
= bp
+ offset
;
1542 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1546 * Has "pcap_breakloop()" been called?
1548 if (handle
->break_loop
) {
1550 * Yes - clear the flag that indicates that it has,
1551 * and return PCAP_ERROR_BREAK as an indication that
1552 * we were told to break out of the loop.
1554 handle
->break_loop
= 0;
1555 return PCAP_ERROR_BREAK
;
1558 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1559 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1560 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1561 fromlen
= sizeof(from
);
1562 packet_len
= recvfrom(
1563 handle
->fd
, bp
+ offset
,
1564 handle
->bufsize
- offset
, MSG_TRUNC
,
1565 (struct sockaddr
*) &from
, &fromlen
);
1566 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1567 } while (packet_len
== -1 && errno
== EINTR
);
1569 /* Check if an error occured */
1571 if (packet_len
== -1) {
1575 return 0; /* no packet there */
1579 * The device on which we're capturing went away.
1581 * XXX - we should really return
1582 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1583 * etc. aren't defined to return that.
1585 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1586 "The interface went down");
1590 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1591 "recvfrom: %s", pcap_strerror(errno
));
1596 #ifdef HAVE_PF_PACKET_SOCKETS
1597 if (!handlep
->sock_packet
) {
1599 * Unfortunately, there is a window between socket() and
1600 * bind() where the kernel may queue packets from any
1601 * interface. If we're bound to a particular interface,
1602 * discard packets not from that interface.
1604 * (If socket filters are supported, we could do the
1605 * same thing we do when changing the filter; however,
1606 * that won't handle packet sockets without socket
1607 * filter support, and it's a bit more complicated.
1608 * It would save some instructions per packet, however.)
1610 if (handlep
->ifindex
!= -1 &&
1611 from
.sll_ifindex
!= handlep
->ifindex
)
1615 * Do checks based on packet direction.
1616 * We can only do this if we're using PF_PACKET; the
1617 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1618 * which lacks the relevant packet type information.
1620 if (!linux_check_direction(handle
, &from
))
1625 #ifdef HAVE_PF_PACKET_SOCKETS
1627 * If this is a cooked device, fill in the fake packet header.
1629 if (handlep
->cooked
) {
1631 * Add the length of the fake header to the length
1632 * of packet data we read.
1634 packet_len
+= SLL_HDR_LEN
;
1636 hdrp
= (struct sll_header
*)bp
;
1637 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1638 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1639 hdrp
->sll_halen
= htons(from
.sll_halen
);
1640 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1641 (from
.sll_halen
> SLL_ADDRLEN
) ?
1644 hdrp
->sll_protocol
= from
.sll_protocol
;
1647 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1648 if (handlep
->vlan_offset
!= -1) {
1649 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1650 struct tpacket_auxdata
*aux
;
1652 struct vlan_tag
*tag
;
1654 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1655 cmsg
->cmsg_level
!= SOL_PACKET
||
1656 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1659 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1660 #if defined(TP_STATUS_VLAN_VALID)
1661 if ((aux
->tp_vlan_tci
== 0) && !(aux
->tp_status
& TP_STATUS_VLAN_VALID
))
1663 if (aux
->tp_vlan_tci
== 0) /* this is ambigious but without the
1664 TP_STATUS_VLAN_VALID flag, there is
1665 nothing that we can do */
1669 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1670 if (len
< (unsigned int) handlep
->vlan_offset
)
1674 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
1676 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
1677 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1678 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1680 packet_len
+= VLAN_TAG_LEN
;
1683 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1684 #endif /* HAVE_PF_PACKET_SOCKETS */
1687 * XXX: According to the kernel source we should get the real
1688 * packet len if calling recvfrom with MSG_TRUNC set. It does
1689 * not seem to work here :(, but it is supported by this code
1691 * To be honest the code RELIES on that feature so this is really
1692 * broken with 2.2.x kernels.
1693 * I spend a day to figure out what's going on and I found out
1694 * that the following is happening:
1696 * The packet comes from a random interface and the packet_rcv
1697 * hook is called with a clone of the packet. That code inserts
1698 * the packet into the receive queue of the packet socket.
1699 * If a filter is attached to that socket that filter is run
1700 * first - and there lies the problem. The default filter always
1701 * cuts the packet at the snaplen:
1706 * So the packet filter cuts down the packet. The recvfrom call
1707 * says "hey, it's only 68 bytes, it fits into the buffer" with
1708 * the result that we don't get the real packet length. This
1709 * is valid at least until kernel 2.2.17pre6.
1711 * We currently handle this by making a copy of the filter
1712 * program, fixing all "ret" instructions with non-zero
1713 * operands to have an operand of 65535 so that the filter
1714 * doesn't truncate the packet, and supplying that modified
1715 * filter to the kernel.
1718 caplen
= packet_len
;
1719 if (caplen
> handle
->snapshot
)
1720 caplen
= handle
->snapshot
;
1722 /* Run the packet filter if not using kernel filter */
1723 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
) {
1724 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1725 packet_len
, caplen
) == 0)
1727 /* rejected by filter */
1732 /* Fill in our own header data */
1734 /* get timestamp for this packet */
1735 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1736 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
1737 if (ioctl(handle
->fd
, SIOCGSTAMPNS
, &pcap_header
.ts
) == -1) {
1738 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1739 "SIOCGSTAMPNS: %s", pcap_strerror(errno
));
1745 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1746 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1747 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1752 pcap_header
.caplen
= caplen
;
1753 pcap_header
.len
= packet_len
;
1758 * Arguably, we should count them before we check the filter,
1759 * as on many other platforms "ps_recv" counts packets
1760 * handed to the filter rather than packets that passed
1761 * the filter, but if filtering is done in the kernel, we
1762 * can't get a count of packets that passed the filter,
1763 * and that would mean the meaning of "ps_recv" wouldn't
1764 * be the same on all Linux systems.
1766 * XXX - it's not the same on all systems in any case;
1767 * ideally, we should have a "get the statistics" call
1768 * that supplies more counts and indicates which of them
1769 * it supplies, so that we supply a count of packets
1770 * handed to the filter only on platforms where that
1771 * information is available.
1773 * We count them here even if we can get the packet count
1774 * from the kernel, as we can only determine at run time
1775 * whether we'll be able to get it from the kernel (if
1776 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1777 * the kernel, but if it is defined, the library might
1778 * have been built with a 2.4 or later kernel, but we
1779 * might be running on a 2.2[.x] kernel without Alexey
1780 * Kuznetzov's turbopacket patches, and thus the kernel
1781 * might not be able to supply those statistics). We
1782 * could, I guess, try, when opening the socket, to get
1783 * the statistics, and if we can not increment the count
1784 * here, but it's not clear that always incrementing
1785 * the count is more expensive than always testing a flag
1788 * We keep the count in "handlep->packets_read", and use that
1789 * for "ps_recv" if we can't get the statistics from the kernel.
1790 * We do that because, if we *can* get the statistics from
1791 * the kernel, we use "handlep->stat.ps_recv" and
1792 * "handlep->stat.ps_drop" as running counts, as reading the
1793 * statistics from the kernel resets the kernel statistics,
1794 * and if we directly increment "handlep->stat.ps_recv" here,
1795 * that means it will count packets *twice* on systems where
1796 * we can get kernel statistics - once here, and once in
1797 * pcap_stats_linux().
1799 handlep
->packets_read
++;
1801 /* Call the user supplied callback function */
1802 callback(userdata
, &pcap_header
, bp
);
1808 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1810 struct pcap_linux
*handlep
= handle
->priv
;
1813 #ifdef HAVE_PF_PACKET_SOCKETS
1814 if (!handlep
->sock_packet
) {
1815 /* PF_PACKET socket */
1816 if (handlep
->ifindex
== -1) {
1818 * We don't support sending on the "any" device.
1820 strlcpy(handle
->errbuf
,
1821 "Sending packets isn't supported on the \"any\" device",
1826 if (handlep
->cooked
) {
1828 * We don't support sending on the "any" device.
1830 * XXX - how do you send on a bound cooked-mode
1832 * Is a "sendto()" required there?
1834 strlcpy(handle
->errbuf
,
1835 "Sending packets isn't supported in cooked mode",
1842 ret
= send(handle
->fd
, buf
, size
, 0);
1844 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1845 pcap_strerror(errno
));
1852 * Get the statistics for the given packet capture handle.
1853 * Reports the number of dropped packets iff the kernel supports
1854 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1855 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1856 * patches); otherwise, that information isn't available, and we lie
1857 * and report 0 as the count of dropped packets.
1860 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1862 struct pcap_linux
*handlep
= handle
->priv
;
1863 #ifdef HAVE_TPACKET_STATS
1864 #ifdef HAVE_TPACKET3
1866 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
1867 * stuff at the end of a struct tpacket_stats_v3 will not
1868 * be filled in, and we don't look at it so this is OK even
1869 * for those sockets. In addition, the PF_PACKET socket
1870 * code in the kernel only uses the length parameter to
1871 * compute how much data to copy out and to indicate how
1872 * much data was copied out, so it's OK to base it on the
1873 * size of a struct tpacket_stats.
1875 * XXX - it's probably OK, in fact, to just use a
1876 * struct tpacket_stats for V3 sockets, as we don't
1877 * care about the tp_freeze_q_cnt stat.
1879 struct tpacket_stats_v3 kstats
;
1880 #else /* HAVE_TPACKET3 */
1881 struct tpacket_stats kstats
;
1882 #endif /* HAVE_TPACKET3 */
1883 socklen_t len
= sizeof (struct tpacket_stats
);
1884 #endif /* HAVE_TPACKET_STATS */
1886 long if_dropped
= 0;
1889 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1891 if (handle
->opt
.promisc
)
1893 if_dropped
= handlep
->proc_dropped
;
1894 handlep
->proc_dropped
= linux_if_drops(handlep
->device
);
1895 handlep
->stat
.ps_ifdrop
+= (handlep
->proc_dropped
- if_dropped
);
1898 #ifdef HAVE_TPACKET_STATS
1900 * Try to get the packet counts from the kernel.
1902 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1903 &kstats
, &len
) > -1) {
1905 * On systems where the PACKET_STATISTICS "getsockopt()"
1906 * argument is supported on PF_PACKET sockets:
1908 * "ps_recv" counts only packets that *passed* the
1909 * filter, not packets that didn't pass the filter.
1910 * This includes packets later dropped because we
1911 * ran out of buffer space.
1913 * "ps_drop" counts packets dropped because we ran
1914 * out of buffer space. It doesn't count packets
1915 * dropped by the interface driver. It counts only
1916 * packets that passed the filter.
1918 * See above for ps_ifdrop.
1920 * Both statistics include packets not yet read from
1921 * the kernel by libpcap, and thus not yet seen by
1924 * In "linux/net/packet/af_packet.c", at least in the
1925 * 2.4.9 kernel, "tp_packets" is incremented for every
1926 * packet that passes the packet filter *and* is
1927 * successfully queued on the socket; "tp_drops" is
1928 * incremented for every packet dropped because there's
1929 * not enough free space in the socket buffer.
1931 * When the statistics are returned for a PACKET_STATISTICS
1932 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1933 * so that "tp_packets" counts all packets handed to
1934 * the PF_PACKET socket, including packets dropped because
1935 * there wasn't room on the socket buffer - but not
1936 * including packets that didn't pass the filter.
1938 * In the BSD BPF, the count of received packets is
1939 * incremented for every packet handed to BPF, regardless
1940 * of whether it passed the filter.
1942 * We can't make "pcap_stats()" work the same on both
1943 * platforms, but the best approximation is to return
1944 * "tp_packets" as the count of packets and "tp_drops"
1945 * as the count of drops.
1947 * Keep a running total because each call to
1948 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1949 * resets the counters to zero.
1951 handlep
->stat
.ps_recv
+= kstats
.tp_packets
;
1952 handlep
->stat
.ps_drop
+= kstats
.tp_drops
;
1953 *stats
= handlep
->stat
;
1959 * If the error was EOPNOTSUPP, fall through, so that
1960 * if you build the library on a system with
1961 * "struct tpacket_stats" and run it on a system
1962 * that doesn't, it works as it does if the library
1963 * is built on a system without "struct tpacket_stats".
1965 if (errno
!= EOPNOTSUPP
) {
1966 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1967 "pcap_stats: %s", pcap_strerror(errno
));
1973 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1974 * is not supported on PF_PACKET sockets:
1976 * "ps_recv" counts only packets that *passed* the filter,
1977 * not packets that didn't pass the filter. It does not
1978 * count packets dropped because we ran out of buffer
1981 * "ps_drop" is not supported.
1983 * "ps_ifdrop" is supported. It will return the number
1984 * of drops the interface reports in /proc/net/dev,
1985 * if that is available.
1987 * "ps_recv" doesn't include packets not yet read from
1988 * the kernel by libpcap.
1990 * We maintain the count of packets processed by libpcap in
1991 * "handlep->packets_read", for reasons described in the comment
1992 * at the end of pcap_read_packet(). We have no idea how many
1993 * packets were dropped by the kernel buffers -- but we know
1994 * how many the interface dropped, so we can return that.
1997 stats
->ps_recv
= handlep
->packets_read
;
1999 stats
->ps_ifdrop
= handlep
->stat
.ps_ifdrop
;
2004 add_linux_if(pcap_if_t
**devlistp
, const char *ifname
, int fd
, char *errbuf
)
2007 char name
[512]; /* XXX - pick a size */
2009 struct ifreq ifrflags
;
2012 * Get the interface name.
2016 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2019 * This could be the separator between a
2020 * name and an alias number, or it could be
2021 * the separator between a name with no
2022 * alias number and the next field.
2024 * If there's a colon after digits, it
2025 * separates the name and the alias number,
2026 * otherwise it separates the name and the
2030 while (isascii(*p
) && isdigit(*p
))
2034 * That was the next field,
2035 * not the alias number.
2046 * Get the flags for this interface.
2048 strlcpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2049 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2050 if (errno
== ENXIO
|| errno
== ENODEV
)
2051 return (0); /* device doesn't actually exist - ignore it */
2052 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2053 "SIOCGIFFLAGS: %.*s: %s",
2054 (int)sizeof(ifrflags
.ifr_name
),
2056 pcap_strerror(errno
));
2061 * Add an entry for this interface, with no addresses.
2063 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2075 * Get from "/sys/class/net" all interfaces listed there; if they're
2076 * already in the list of interfaces we have, that won't add another
2077 * instance, but if they're not, that'll add them.
2079 * We don't bother getting any addresses for them; it appears you can't
2080 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2081 * although some other types of addresses can be fetched with SIOCGIFADDR,
2082 * we don't bother with them for now.
2084 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2085 * the list of interfaces as is, and return 0, so that we can try
2086 * scanning /proc/net/dev.
2088 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2091 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
2093 DIR *sys_class_net_d
;
2096 char subsystem_path
[PATH_MAX
+1];
2100 sys_class_net_d
= opendir("/sys/class/net");
2101 if (sys_class_net_d
== NULL
) {
2103 * Don't fail if it doesn't exist at all.
2105 if (errno
== ENOENT
)
2109 * Fail if we got some other error.
2111 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2112 "Can't open /sys/class/net: %s", pcap_strerror(errno
));
2117 * Create a socket from which to fetch interface information.
2119 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2121 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2122 "socket: %s", pcap_strerror(errno
));
2123 (void)closedir(sys_class_net_d
);
2129 ent
= readdir(sys_class_net_d
);
2132 * Error or EOF; if errno != 0, it's an error.
2138 * Ignore "." and "..".
2140 if (strcmp(ent
->d_name
, ".") == 0 ||
2141 strcmp(ent
->d_name
, "..") == 0)
2145 * Ignore plain files; they do not have subdirectories
2146 * and thus have no attributes.
2148 if (ent
->d_type
== DT_REG
)
2152 * Is there an "ifindex" file under that name?
2153 * (We don't care whether it's a directory or
2154 * a symlink; older kernels have directories
2155 * for devices, newer kernels have symlinks to
2158 snprintf(subsystem_path
, sizeof subsystem_path
,
2159 "/sys/class/net/%s/ifindex", ent
->d_name
);
2160 if (lstat(subsystem_path
, &statb
) != 0) {
2162 * Stat failed. Either there was an error
2163 * other than ENOENT, and we don't know if
2164 * this is an interface, or it's ENOENT,
2165 * and either some part of "/sys/class/net/{if}"
2166 * disappeared, in which case it probably means
2167 * the interface disappeared, or there's no
2168 * "ifindex" file, which means it's not a
2169 * network interface.
2175 * Attempt to add the interface.
2177 if (add_linux_if(devlistp
, &ent
->d_name
[0], fd
, errbuf
) == -1) {
2185 * Well, we didn't fail for any other reason; did we
2186 * fail due to an error reading the directory?
2189 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2190 "Error reading /sys/class/net: %s",
2191 pcap_strerror(errno
));
2197 (void)closedir(sys_class_net_d
);
2202 * Get from "/proc/net/dev" all interfaces listed there; if they're
2203 * already in the list of interfaces we have, that won't add another
2204 * instance, but if they're not, that'll add them.
2206 * See comments from scan_sys_class_net().
2209 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2218 proc_net_f
= fopen("/proc/net/dev", "r");
2219 if (proc_net_f
== NULL
) {
2221 * Don't fail if it doesn't exist at all.
2223 if (errno
== ENOENT
)
2227 * Fail if we got some other error.
2229 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2230 "Can't open /proc/net/dev: %s", pcap_strerror(errno
));
2235 * Create a socket from which to fetch interface information.
2237 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2239 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2240 "socket: %s", pcap_strerror(errno
));
2241 (void)fclose(proc_net_f
);
2246 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2248 * Skip the first two lines - they're headers.
2256 * Skip leading white space.
2258 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2260 if (*p
== '\0' || *p
== '\n')
2261 continue; /* blank line */
2264 * Attempt to add the interface.
2266 if (add_linux_if(devlistp
, p
, fd
, errbuf
) == -1) {
2274 * Well, we didn't fail for any other reason; did we
2275 * fail due to an error reading the file?
2277 if (ferror(proc_net_f
)) {
2278 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2279 "Error reading /proc/net/dev: %s",
2280 pcap_strerror(errno
));
2286 (void)fclose(proc_net_f
);
2291 * Description string for the "any" device.
2293 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2296 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2301 * Read "/sys/class/net", and add to the list of interfaces all
2302 * interfaces listed there that we don't already have, because,
2303 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2304 * and even getifaddrs() won't return information about
2305 * interfaces with no addresses, so you need to read "/sys/class/net"
2306 * to get the names of the rest of the interfaces.
2308 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2310 return (-1); /* failed */
2313 * No /sys/class/net; try reading /proc/net/dev instead.
2315 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2320 * Add the "any" device.
2322 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2329 * Attach the given BPF code to the packet capture device.
2332 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2335 struct pcap_linux
*handlep
;
2336 #ifdef SO_ATTACH_FILTER
2337 struct sock_fprog fcode
;
2338 int can_filter_in_kernel
;
2345 strlcpy(handle
->errbuf
, "setfilter: No filter specified",
2350 handlep
= handle
->priv
;
2352 /* Make our private copy of the filter */
2354 if (install_bpf_program(handle
, filter
) < 0)
2355 /* install_bpf_program() filled in errbuf */
2359 * Run user level packet filter by default. Will be overriden if
2360 * installing a kernel filter succeeds.
2362 handlep
->filter_in_userland
= 1;
2364 /* Install kernel level filter if possible */
2366 #ifdef SO_ATTACH_FILTER
2368 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2370 * fcode.len is an unsigned short for current kernel.
2371 * I have yet to see BPF-Code with that much
2372 * instructions but still it is possible. So for the
2373 * sake of correctness I added this check.
2375 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2377 fcode
.filter
= NULL
;
2378 can_filter_in_kernel
= 0;
2380 #endif /* USHRT_MAX */
2383 * Oh joy, the Linux kernel uses struct sock_fprog instead
2384 * of struct bpf_program and of course the length field is
2385 * of different size. Pointed out by Sebastian
2387 * Oh, and we also need to fix it up so that all "ret"
2388 * instructions with non-zero operands have 65535 as the
2389 * operand if we're not capturing in memory-mapped modee,
2390 * and so that, if we're in cooked mode, all memory-reference
2391 * instructions use special magic offsets in references to
2392 * the link-layer header and assume that the link-layer
2393 * payload begins at 0; "fix_program()" will do that.
2395 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2400 * Fatal error; just quit.
2401 * (The "default" case shouldn't happen; we
2402 * return -1 for that reason.)
2408 * The program performed checks that we can't make
2409 * work in the kernel.
2411 can_filter_in_kernel
= 0;
2416 * We have a filter that'll work in the kernel.
2418 can_filter_in_kernel
= 1;
2424 * NOTE: at this point, we've set both the "len" and "filter"
2425 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2426 * those are the only members of the "sock_fprog" structure,
2427 * so we initialize every member of that structure.
2429 * If there is anything in "fcode" that is not initialized,
2430 * it is either a field added in a later kernel, or it's
2433 * If a new field is added, this code needs to be updated
2434 * to set it correctly.
2436 * If there are no other fields, then:
2438 * if the Linux kernel looks at the padding, it's
2441 * if the Linux kernel doesn't look at the padding,
2442 * then if some tool complains that we're passing
2443 * uninitialized data to the kernel, then the tool
2444 * is buggy and needs to understand that it's just
2447 if (can_filter_in_kernel
) {
2448 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2451 * Installation succeded - using kernel filter,
2452 * so userland filtering not needed.
2454 handlep
->filter_in_userland
= 0;
2456 else if (err
== -1) /* Non-fatal error */
2459 * Print a warning if we weren't able to install
2460 * the filter for a reason other than "this kernel
2461 * isn't configured to support socket filters.
2463 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2465 "Warning: Kernel filter failed: %s\n",
2466 pcap_strerror(errno
));
2472 * If we're not using the kernel filter, get rid of any kernel
2473 * filter that might've been there before, e.g. because the
2474 * previous filter could work in the kernel, or because some other
2475 * code attached a filter to the socket by some means other than
2476 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2477 * filter out packets that would pass the new userland filter.
2479 if (handlep
->filter_in_userland
)
2480 reset_kernel_filter(handle
);
2483 * Free up the copy of the filter that was made by "fix_program()".
2485 if (fcode
.filter
!= NULL
)
2491 #endif /* SO_ATTACH_FILTER */
2497 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2499 return pcap_setfilter_linux_common(handle
, filter
, 0);
2504 * Set direction flag: Which packets do we accept on a forwarding
2505 * single device? IN, OUT or both?
2508 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2510 #ifdef HAVE_PF_PACKET_SOCKETS
2511 struct pcap_linux
*handlep
= handle
->priv
;
2513 if (!handlep
->sock_packet
) {
2514 handle
->direction
= d
;
2519 * We're not using PF_PACKET sockets, so we can't determine
2520 * the direction of the packet.
2522 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2523 "Setting direction is not supported on SOCK_PACKET sockets");
2527 #ifdef HAVE_PF_PACKET_SOCKETS
2529 * Map the PACKET_ value to a LINUX_SLL_ value; we
2530 * want the same numerical value to be used in
2531 * the link-layer header even if the numerical values
2532 * for the PACKET_ #defines change, so that programs
2533 * that look at the packet type field will always be
2534 * able to handle DLT_LINUX_SLL captures.
2537 map_packet_type_to_sll_type(short int sll_pkttype
)
2539 switch (sll_pkttype
) {
2542 return htons(LINUX_SLL_HOST
);
2544 case PACKET_BROADCAST
:
2545 return htons(LINUX_SLL_BROADCAST
);
2547 case PACKET_MULTICAST
:
2548 return htons(LINUX_SLL_MULTICAST
);
2550 case PACKET_OTHERHOST
:
2551 return htons(LINUX_SLL_OTHERHOST
);
2553 case PACKET_OUTGOING
:
2554 return htons(LINUX_SLL_OUTGOING
);
2563 * Linux uses the ARP hardware type to identify the type of an
2564 * interface. pcap uses the DLT_xxx constants for this. This
2565 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2566 * constant, as arguments, and sets "handle->linktype" to the
2567 * appropriate DLT_XXX constant and sets "handle->offset" to
2568 * the appropriate value (to make "handle->offset" plus link-layer
2569 * header length be a multiple of 4, so that the link-layer payload
2570 * will be aligned on a 4-byte boundary when capturing packets).
2571 * (If the offset isn't set here, it'll be 0; add code as appropriate
2572 * for cases where it shouldn't be 0.)
2574 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2575 * in cooked mode; otherwise, we can't use cooked mode, so we have
2576 * to pick some type that works in raw mode, or fail.
2578 * Sets the link type to -1 if unable to map the type.
2580 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, const char *device
,
2583 static const char cdma_rmnet
[] = "cdma_rmnet";
2589 * For various annoying reasons having to do with DHCP
2590 * software, some versions of Android give the mobile-
2591 * phone-network interface an ARPHRD_ value of
2592 * ARPHRD_ETHER, even though the packet supplied by
2593 * that interface have no link-layer header, and begin
2594 * with an IP header, so that the ARPHRD_ value should
2597 * Detect those devices by checking the device name, and
2598 * use DLT_RAW for them.
2600 if (strncmp(device
, cdma_rmnet
, sizeof cdma_rmnet
- 1) == 0) {
2601 handle
->linktype
= DLT_RAW
;
2606 * This is (presumably) a real Ethernet capture; give it a
2607 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2608 * that an application can let you choose it, in case you're
2609 * capturing DOCSIS traffic that a Cisco Cable Modem
2610 * Termination System is putting out onto an Ethernet (it
2611 * doesn't put an Ethernet header onto the wire, it puts raw
2612 * DOCSIS frames out on the wire inside the low-level
2613 * Ethernet framing).
2615 * XXX - are there any sorts of "fake Ethernet" that have
2616 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2617 * a Cisco CMTS won't put traffic onto it or get traffic
2618 * bridged onto it? ISDN is handled in "activate_new()",
2619 * as we fall back on cooked mode there; are there any
2622 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2624 * If that fails, just leave the list empty.
2626 if (handle
->dlt_list
!= NULL
) {
2627 handle
->dlt_list
[0] = DLT_EN10MB
;
2628 handle
->dlt_list
[1] = DLT_DOCSIS
;
2629 handle
->dlt_count
= 2;
2633 case ARPHRD_METRICOM
:
2634 case ARPHRD_LOOPBACK
:
2635 handle
->linktype
= DLT_EN10MB
;
2640 handle
->linktype
= DLT_EN3MB
;
2644 handle
->linktype
= DLT_AX25_KISS
;
2648 handle
->linktype
= DLT_PRONET
;
2652 handle
->linktype
= DLT_CHAOS
;
2655 #define ARPHRD_CAN 280
2658 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2661 #ifndef ARPHRD_IEEE802_TR
2662 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2664 case ARPHRD_IEEE802_TR
:
2665 case ARPHRD_IEEE802
:
2666 handle
->linktype
= DLT_IEEE802
;
2671 handle
->linktype
= DLT_ARCNET_LINUX
;
2674 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2675 #define ARPHRD_FDDI 774
2678 handle
->linktype
= DLT_FDDI
;
2682 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2683 #define ARPHRD_ATM 19
2687 * The Classical IP implementation in ATM for Linux
2688 * supports both what RFC 1483 calls "LLC Encapsulation",
2689 * in which each packet has an LLC header, possibly
2690 * with a SNAP header as well, prepended to it, and
2691 * what RFC 1483 calls "VC Based Multiplexing", in which
2692 * different virtual circuits carry different network
2693 * layer protocols, and no header is prepended to packets.
2695 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2696 * you can't use the ARPHRD_ type to find out whether
2697 * captured packets will have an LLC header, and,
2698 * while there's a socket ioctl to *set* the encapsulation
2699 * type, there's no ioctl to *get* the encapsulation type.
2703 * programs that dissect Linux Classical IP frames
2704 * would have to check for an LLC header and,
2705 * depending on whether they see one or not, dissect
2706 * the frame as LLC-encapsulated or as raw IP (I
2707 * don't know whether there's any traffic other than
2708 * IP that would show up on the socket, or whether
2709 * there's any support for IPv6 in the Linux
2710 * Classical IP code);
2712 * filter expressions would have to compile into
2713 * code that checks for an LLC header and does
2716 * Both of those are a nuisance - and, at least on systems
2717 * that support PF_PACKET sockets, we don't have to put
2718 * up with those nuisances; instead, we can just capture
2719 * in cooked mode. That's what we'll do, if we can.
2720 * Otherwise, we'll just fail.
2723 handle
->linktype
= DLT_LINUX_SLL
;
2725 handle
->linktype
= -1;
2728 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2729 #define ARPHRD_IEEE80211 801
2731 case ARPHRD_IEEE80211
:
2732 handle
->linktype
= DLT_IEEE802_11
;
2735 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2736 #define ARPHRD_IEEE80211_PRISM 802
2738 case ARPHRD_IEEE80211_PRISM
:
2739 handle
->linktype
= DLT_PRISM_HEADER
;
2742 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2743 #define ARPHRD_IEEE80211_RADIOTAP 803
2745 case ARPHRD_IEEE80211_RADIOTAP
:
2746 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2751 * Some PPP code in the kernel supplies no link-layer
2752 * header whatsoever to PF_PACKET sockets; other PPP
2753 * code supplies PPP link-layer headers ("syncppp.c");
2754 * some PPP code might supply random link-layer
2755 * headers (PPP over ISDN - there's code in Ethereal,
2756 * for example, to cope with PPP-over-ISDN captures
2757 * with which the Ethereal developers have had to cope,
2758 * heuristically trying to determine which of the
2759 * oddball link-layer headers particular packets have).
2761 * As such, we just punt, and run all PPP interfaces
2762 * in cooked mode, if we can; otherwise, we just treat
2763 * it as DLT_RAW, for now - if somebody needs to capture,
2764 * on a 2.0[.x] kernel, on PPP devices that supply a
2765 * link-layer header, they'll have to add code here to
2766 * map to the appropriate DLT_ type (possibly adding a
2767 * new DLT_ type, if necessary).
2770 handle
->linktype
= DLT_LINUX_SLL
;
2773 * XXX - handle ISDN types here? We can't fall
2774 * back on cooked sockets, so we'd have to
2775 * figure out from the device name what type of
2776 * link-layer encapsulation it's using, and map
2777 * that to an appropriate DLT_ value, meaning
2778 * we'd map "isdnN" devices to DLT_RAW (they
2779 * supply raw IP packets with no link-layer
2780 * header) and "isdY" devices to a new DLT_I4L_IP
2781 * type that has only an Ethernet packet type as
2782 * a link-layer header.
2784 * But sometimes we seem to get random crap
2785 * in the link-layer header when capturing on
2788 handle
->linktype
= DLT_RAW
;
2792 #ifndef ARPHRD_CISCO
2793 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2796 handle
->linktype
= DLT_C_HDLC
;
2799 /* Not sure if this is correct for all tunnels, but it
2803 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2811 #ifndef ARPHRD_RAWHDLC
2812 #define ARPHRD_RAWHDLC 518
2814 case ARPHRD_RAWHDLC
:
2816 #define ARPHRD_DLCI 15
2820 * XXX - should some of those be mapped to DLT_LINUX_SLL
2821 * instead? Should we just map all of them to DLT_LINUX_SLL?
2823 handle
->linktype
= DLT_RAW
;
2827 #define ARPHRD_FRAD 770
2830 handle
->linktype
= DLT_FRELAY
;
2833 case ARPHRD_LOCALTLK
:
2834 handle
->linktype
= DLT_LTALK
;
2839 * RFC 4338 defines an encapsulation for IP and ARP
2840 * packets that's compatible with the RFC 2625
2841 * encapsulation, but that uses a different ARP
2842 * hardware type and hardware addresses. That
2843 * ARP hardware type is 18; Linux doesn't define
2844 * any ARPHRD_ value as 18, but if it ever officially
2845 * supports RFC 4338-style IP-over-FC, it should define
2848 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2849 * that this will encourage its use in the future,
2850 * should Linux ever officially support RFC 4338-style
2853 handle
->linktype
= DLT_IP_OVER_FC
;
2857 #define ARPHRD_FCPP 784
2861 #define ARPHRD_FCAL 785
2865 #define ARPHRD_FCPL 786
2868 #ifndef ARPHRD_FCFABRIC
2869 #define ARPHRD_FCFABRIC 787
2871 case ARPHRD_FCFABRIC
:
2873 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2876 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2878 * and one was assigned.
2880 * In a later private discussion (spun off from a message
2881 * on the ethereal-users list) on how to get that DLT_
2882 * value in libpcap on Linux, I ended up deciding that
2883 * the best thing to do would be to have him tweak the
2884 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2885 * type, and map all those types to DLT_IP_OVER_FC:
2887 * I've checked into the libpcap and tcpdump CVS tree
2888 * support for DLT_IP_OVER_FC. In order to use that,
2889 * you'd have to modify your modified driver to return
2890 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2891 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
2892 * example (the exact value doesn't matter, it can be
2893 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2896 * 11 years later, Christian Svensson wanted to map
2897 * various ARPHRD_ values to DLT_FC_2 and
2898 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2901 * https://github.com/mcr/libpcap/pull/29
2903 * There doesn't seem to be any network drivers that uses
2904 * any of the ARPHRD_FC* values for IP-over-FC, and
2905 * it's not exactly clear what the "Dummy types for non
2906 * ARP hardware" are supposed to mean (link-layer
2907 * header type? Physical network type?), so it's
2908 * not exactly clear why the ARPHRD_FC* types exist
2909 * in the first place.
2911 * For now, we map them to DLT_FC_2, and provide an
2912 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
2913 * DLT_IP_OVER_FC just in case there's some old
2914 * driver out there that uses one of those types for
2915 * IP-over-FC on which somebody wants to capture
2918 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2920 * If that fails, just leave the list empty.
2922 if (handle
->dlt_list
!= NULL
) {
2923 handle
->dlt_list
[0] = DLT_FC_2
;
2924 handle
->dlt_list
[1] = DLT_FC_2_WITH_FRAME_DELIMS
;
2925 handle
->dlt_list
[2] = DLT_IP_OVER_FC
;
2926 handle
->dlt_count
= 3;
2928 handle
->linktype
= DLT_FC_2
;
2932 #define ARPHRD_IRDA 783
2935 /* Don't expect IP packet out of this interfaces... */
2936 handle
->linktype
= DLT_LINUX_IRDA
;
2937 /* We need to save packet direction for IrDA decoding,
2938 * so let's use "Linux-cooked" mode. Jean II
2940 * XXX - this is handled in activate_new(). */
2941 //handlep->cooked = 1;
2944 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2945 * is needed, please report it to <daniele@orlandi.com> */
2947 #define ARPHRD_LAPD 8445
2950 /* Don't expect IP packet out of this interfaces... */
2951 handle
->linktype
= DLT_LINUX_LAPD
;
2955 #define ARPHRD_NONE 0xFFFE
2959 * No link-layer header; packets are just IP
2960 * packets, so use DLT_RAW.
2962 handle
->linktype
= DLT_RAW
;
2965 #ifndef ARPHRD_IEEE802154
2966 #define ARPHRD_IEEE802154 804
2968 case ARPHRD_IEEE802154
:
2969 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2972 #ifndef ARPHRD_NETLINK
2973 #define ARPHRD_NETLINK 824
2975 case ARPHRD_NETLINK
:
2976 handle
->linktype
= DLT_NETLINK
;
2978 * We need to use cooked mode, so that in sll_protocol we
2979 * pick up the netlink protocol type such as NETLINK_ROUTE,
2980 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
2982 * XXX - this is handled in activate_new().
2984 //handlep->cooked = 1;
2988 handle
->linktype
= -1;
2993 /* ===== Functions to interface to the newer kernels ================== */
2996 * Try to open a packet socket using the new kernel PF_PACKET interface.
2997 * Returns 1 on success, 0 on an error that means the new interface isn't
2998 * present (so the old SOCK_PACKET interface should be tried), and a
2999 * PCAP_ERROR_ value on an error that means that the old mechanism won't
3000 * work either (so it shouldn't be tried).
3003 activate_new(pcap_t
*handle
)
3005 #ifdef HAVE_PF_PACKET_SOCKETS
3006 struct pcap_linux
*handlep
= handle
->priv
;
3007 const char *device
= handle
->opt
.source
;
3008 int is_any_device
= (strcmp(device
, "any") == 0);
3009 int sock_fd
= -1, arptype
;
3010 #ifdef HAVE_PACKET_AUXDATA
3014 struct packet_mreq mr
;
3017 * Open a socket with protocol family packet. If the
3018 * "any" device was specified, we open a SOCK_DGRAM
3019 * socket for the cooked interface, otherwise we first
3020 * try a SOCK_RAW socket for the raw interface.
3022 sock_fd
= is_any_device
?
3023 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
3024 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
3026 if (sock_fd
== -1) {
3027 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
3029 * We don't support PF_PACKET/SOCK_whatever
3030 * sockets; try the old mechanism.
3035 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
3036 pcap_strerror(errno
) );
3037 if (errno
== EPERM
|| errno
== EACCES
) {
3039 * You don't have permission to open the
3042 return PCAP_ERROR_PERM_DENIED
;
3051 /* It seems the kernel supports the new interface. */
3052 handlep
->sock_packet
= 0;
3055 * Get the interface index of the loopback device.
3056 * If the attempt fails, don't fail, just set the
3057 * "handlep->lo_ifindex" to -1.
3059 * XXX - can there be more than one device that loops
3060 * packets back, i.e. devices other than "lo"? If so,
3061 * we'd need to find them all, and have an array of
3062 * indices for them, and check all of them in
3063 * "pcap_read_packet()".
3065 handlep
->lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
3068 * Default value for offset to align link-layer payload
3069 * on a 4-byte boundary.
3074 * What kind of frames do we have to deal with? Fall back
3075 * to cooked mode if we have an unknown interface type
3076 * or a type we know doesn't work well in raw mode.
3078 if (!is_any_device
) {
3079 /* Assume for now we don't need cooked mode. */
3080 handlep
->cooked
= 0;
3082 if (handle
->opt
.rfmon
) {
3084 * We were asked to turn on monitor mode.
3085 * Do so before we get the link-layer type,
3086 * because entering monitor mode could change
3087 * the link-layer type.
3089 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
3097 * Nothing worked for turning monitor mode
3101 return PCAP_ERROR_RFMON_NOTSUP
;
3105 * Either monitor mode has been turned on for
3106 * the device, or we've been given a different
3107 * device to open for monitor mode. If we've
3108 * been given a different device, use it.
3110 if (handlep
->mondevice
!= NULL
)
3111 device
= handlep
->mondevice
;
3113 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
3118 map_arphrd_to_dlt(handle
, arptype
, device
, 1);
3119 if (handle
->linktype
== -1 ||
3120 handle
->linktype
== DLT_LINUX_SLL
||
3121 handle
->linktype
== DLT_LINUX_IRDA
||
3122 handle
->linktype
== DLT_LINUX_LAPD
||
3123 handle
->linktype
== DLT_NETLINK
||
3124 (handle
->linktype
== DLT_EN10MB
&&
3125 (strncmp("isdn", device
, 4) == 0 ||
3126 strncmp("isdY", device
, 4) == 0))) {
3128 * Unknown interface type (-1), or a
3129 * device we explicitly chose to run
3130 * in cooked mode (e.g., PPP devices),
3131 * or an ISDN device (whose link-layer
3132 * type we can only determine by using
3133 * APIs that may be different on different
3134 * kernels) - reopen in cooked mode.
3136 if (close(sock_fd
) == -1) {
3137 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3138 "close: %s", pcap_strerror(errno
));
3141 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
3143 if (sock_fd
== -1) {
3144 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3145 "socket: %s", pcap_strerror(errno
));
3146 if (errno
== EPERM
|| errno
== EACCES
) {
3148 * You don't have permission to
3151 return PCAP_ERROR_PERM_DENIED
;
3159 handlep
->cooked
= 1;
3162 * Get rid of any link-layer type list
3163 * we allocated - this only supports cooked
3166 if (handle
->dlt_list
!= NULL
) {
3167 free(handle
->dlt_list
);
3168 handle
->dlt_list
= NULL
;
3169 handle
->dlt_count
= 0;
3172 if (handle
->linktype
== -1) {
3174 * Warn that we're falling back on
3175 * cooked mode; we may want to
3176 * update "map_arphrd_to_dlt()"
3177 * to handle the new type.
3179 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3181 "supported by libpcap - "
3182 "falling back to cooked "
3188 * IrDA capture is not a real "cooked" capture,
3189 * it's IrLAP frames, not IP packets. The
3190 * same applies to LAPD capture.
3192 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
3193 handle
->linktype
!= DLT_LINUX_LAPD
&&
3194 handle
->linktype
!= DLT_NETLINK
)
3195 handle
->linktype
= DLT_LINUX_SLL
;
3198 handlep
->ifindex
= iface_get_id(sock_fd
, device
,
3200 if (handlep
->ifindex
== -1) {
3205 if ((err
= iface_bind(sock_fd
, handlep
->ifindex
,
3206 handle
->errbuf
)) != 1) {
3211 return 0; /* try old mechanism */
3217 if (handle
->opt
.rfmon
) {
3219 * It doesn't support monitor mode.
3222 return PCAP_ERROR_RFMON_NOTSUP
;
3226 * It uses cooked mode.
3228 handlep
->cooked
= 1;
3229 handle
->linktype
= DLT_LINUX_SLL
;
3232 * We're not bound to a device.
3233 * For now, we're using this as an indication
3234 * that we can't transmit; stop doing that only
3235 * if we figure out how to transmit in cooked
3238 handlep
->ifindex
= -1;
3242 * Select promiscuous mode on if "promisc" is set.
3244 * Do not turn allmulti mode on if we don't select
3245 * promiscuous mode - on some devices (e.g., Orinoco
3246 * wireless interfaces), allmulti mode isn't supported
3247 * and the driver implements it by turning promiscuous
3248 * mode on, and that screws up the operation of the
3249 * card as a normal networking interface, and on no
3250 * other platform I know of does starting a non-
3251 * promiscuous capture affect which multicast packets
3252 * are received by the interface.
3256 * Hmm, how can we set promiscuous mode on all interfaces?
3257 * I am not sure if that is possible at all. For now, we
3258 * silently ignore attempts to turn promiscuous mode on
3259 * for the "any" device (so you don't have to explicitly
3260 * disable it in programs such as tcpdump).
3263 if (!is_any_device
&& handle
->opt
.promisc
) {
3264 memset(&mr
, 0, sizeof(mr
));
3265 mr
.mr_ifindex
= handlep
->ifindex
;
3266 mr
.mr_type
= PACKET_MR_PROMISC
;
3267 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3268 &mr
, sizeof(mr
)) == -1) {
3269 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3270 "setsockopt: %s", pcap_strerror(errno
));
3276 /* Enable auxillary data if supported and reserve room for
3277 * reconstructing VLAN headers. */
3278 #ifdef HAVE_PACKET_AUXDATA
3280 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3281 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3282 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3283 "setsockopt: %s", pcap_strerror(errno
));
3287 handle
->offset
+= VLAN_TAG_LEN
;
3288 #endif /* HAVE_PACKET_AUXDATA */
3291 * This is a 2.2[.x] or later kernel (we know that
3292 * because we're not using a SOCK_PACKET socket -
3293 * PF_PACKET is supported only in 2.2 and later
3296 * We can safely pass "recvfrom()" a byte count
3297 * based on the snapshot length.
3299 * If we're in cooked mode, make the snapshot length
3300 * large enough to hold a "cooked mode" header plus
3301 * 1 byte of packet data (so we don't pass a byte
3302 * count of 0 to "recvfrom()").
3304 if (handlep
->cooked
) {
3305 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3306 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3308 handle
->bufsize
= handle
->snapshot
;
3311 * Set the offset at which to insert VLAN tags.
3313 switch (handle
->linktype
) {
3316 handlep
->vlan_offset
= 2 * ETH_ALEN
;
3320 handlep
->vlan_offset
= 14;
3324 handlep
->vlan_offset
= -1; /* unknown */
3328 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3329 if (handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
) {
3330 int nsec_tstamps
= 1;
3332 if (setsockopt(sock_fd
, SOL_SOCKET
, SO_TIMESTAMPNS
, &nsec_tstamps
, sizeof(nsec_tstamps
)) < 0) {
3333 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "setsockopt: unable to set SO_TIMESTAMPNS");
3338 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3341 * We've succeeded. Save the socket FD in the pcap structure.
3343 handle
->fd
= sock_fd
;
3346 #else /* HAVE_PF_PACKET_SOCKETS */
3348 "New packet capturing interface not supported by build "
3349 "environment", PCAP_ERRBUF_SIZE
);
3351 #endif /* HAVE_PF_PACKET_SOCKETS */
3354 #ifdef HAVE_PACKET_RING
3356 * Attempt to activate with memory-mapped access.
3358 * On success, returns 1, and sets *status to 0 if there are no warnings
3359 * or to a PCAP_WARNING_ code if there is a warning.
3361 * On failure due to lack of support for memory-mapped capture, returns
3364 * On error, returns -1, and sets *status to the appropriate error code;
3365 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3368 activate_mmap(pcap_t
*handle
, int *status
)
3370 struct pcap_linux
*handlep
= handle
->priv
;
3374 * Attempt to allocate a buffer to hold the contents of one
3375 * packet, for use by the oneshot callback.
3377 handlep
->oneshot_buffer
= malloc(handle
->snapshot
);
3378 if (handlep
->oneshot_buffer
== NULL
) {
3379 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3380 "can't allocate oneshot buffer: %s",
3381 pcap_strerror(errno
));
3382 *status
= PCAP_ERROR
;
3386 if (handle
->opt
.buffer_size
== 0) {
3387 /* by default request 2M for the ring buffer */
3388 handle
->opt
.buffer_size
= 2*1024*1024;
3390 ret
= prepare_tpacket_socket(handle
);
3392 free(handlep
->oneshot_buffer
);
3393 *status
= PCAP_ERROR
;
3396 ret
= create_ring(handle
, status
);
3399 * We don't support memory-mapped capture; our caller
3400 * will fall back on reading from the socket.
3402 free(handlep
->oneshot_buffer
);
3407 * Error attempting to enable memory-mapped capture;
3408 * fail. create_ring() has set *status.
3410 free(handlep
->oneshot_buffer
);
3415 * Success. *status has been set either to 0 if there are no
3416 * warnings or to a PCAP_WARNING_ value if there is a warning.
3418 * Override some defaults and inherit the other fields from
3420 * handle->offset is used to get the current position into the rx ring.
3421 * handle->cc is used to store the ring size.
3424 switch (handlep
->tp_version
) {
3426 handle
->read_op
= pcap_read_linux_mmap_v1
;
3428 #ifdef HAVE_TPACKET2
3430 handle
->read_op
= pcap_read_linux_mmap_v2
;
3433 #ifdef HAVE_TPACKET3
3435 handle
->read_op
= pcap_read_linux_mmap_v3
;
3439 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3440 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3441 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3442 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3443 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3444 handle
->selectable_fd
= handle
->fd
;
3447 #else /* HAVE_PACKET_RING */
3449 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3453 #endif /* HAVE_PACKET_RING */
3455 #ifdef HAVE_PACKET_RING
3457 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3459 * Attempt to set the socket to the specified version of the memory-mapped
3462 * Return 0 if we succeed; return 1 if we fail because that version isn't
3463 * supported; return -1 on any other error, and set handle->errbuf.
3466 init_tpacket(pcap_t
*handle
, int version
, const char *version_str
)
3468 struct pcap_linux
*handlep
= handle
->priv
;
3470 socklen_t len
= sizeof(val
);
3472 /* Probe whether kernel supports the specified TPACKET version */
3473 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3474 if (errno
== ENOPROTOOPT
|| errno
== EINVAL
)
3477 /* Failed to even find out; this is a fatal error. */
3478 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3479 "can't get %s header len on packet socket: %s",
3481 pcap_strerror(errno
));
3484 handlep
->tp_hdrlen
= val
;
3487 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3489 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3490 "can't activate %s on packet socket: %s",
3492 pcap_strerror(errno
));
3495 handlep
->tp_version
= version
;
3497 /* Reserve space for VLAN tag reconstruction */
3499 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3501 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3502 "can't set up reserve on packet socket: %s",
3503 pcap_strerror(errno
));
3509 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3512 * Attempt to set the socket to version 3 of the memory-mapped header and,
3513 * if that fails because version 3 isn't supported, attempt to fall
3514 * back to version 2. If version 2 isn't supported, just leave it at
3517 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
3518 * supported; return -1 on any other error, and set handle->errbuf.
3521 prepare_tpacket_socket(pcap_t
*handle
)
3523 struct pcap_linux
*handlep
= handle
->priv
;
3524 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3528 handlep
->tp_version
= TPACKET_V1
;
3529 handlep
->tp_hdrlen
= sizeof(struct tpacket_hdr
);
3531 #ifdef HAVE_TPACKET3
3533 * The only mode in which buffering is done on PF_PACKET
3534 * sockets, so that packets might not be delivered
3535 * immediately, is TPACKET_V3 mode.
3537 * The buffering cannot be disabled in that mode, so
3538 * if the user has requested immediate mode, we don't
3541 if (handle
->opt
.immediate
)
3542 ret
= 1; /* pretend TPACKET_V3 couldn't be set */
3544 ret
= init_tpacket(handle
, TPACKET_V3
, "TPACKET_V3");
3546 /* Error during setting up TPACKET_V3. */
3548 } else if (1 == ret
) {
3549 /* TPACKET_V3 not supported - fall back to TPACKET_V2. */
3550 #endif /* HAVE_TPACKET3 */
3552 #ifdef HAVE_TPACKET2
3553 ret
= init_tpacket(handle
, TPACKET_V2
, "TPACKET_V2");
3555 /* Error during setting up TPACKET_V2. */
3558 #endif /* HAVE_TPACKET2 */
3560 #ifdef HAVE_TPACKET3
3562 #endif /* HAVE_TPACKET3 */
3568 * Attempt to set up memory-mapped access.
3570 * On success, returns 1, and sets *status to 0 if there are no warnings
3571 * or to a PCAP_WARNING_ code if there is a warning.
3573 * On failure due to lack of support for memory-mapped capture, returns
3576 * On error, returns -1, and sets *status to the appropriate error code;
3577 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3580 create_ring(pcap_t
*handle
, int *status
)
3582 struct pcap_linux
*handlep
= handle
->priv
;
3583 unsigned i
, j
, frames_per_block
;
3584 #ifdef HAVE_TPACKET3
3586 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
3587 * stuff at the end of a struct tpacket_req3 will be
3588 * ignored, so this is OK even for those sockets.
3590 struct tpacket_req3 req
;
3592 struct tpacket_req req
;
3595 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3596 unsigned int frame_size
;
3599 * Start out assuming no warnings or errors.
3603 switch (handlep
->tp_version
) {
3606 #ifdef HAVE_TPACKET2
3609 /* Note that with large snapshot length (say 64K, which is
3610 * the default for recent versions of tcpdump, the value that
3611 * "-s 0" has given for a long time with tcpdump, and the
3612 * default in Wireshark/TShark/dumpcap), if we use the snapshot
3613 * length to calculate the frame length, only a few frames
3614 * will be available in the ring even with pretty
3615 * large ring size (and a lot of memory will be unused).
3617 * Ideally, we should choose a frame length based on the
3618 * minimum of the specified snapshot length and the maximum
3619 * packet size. That's not as easy as it sounds; consider,
3620 * for example, an 802.11 interface in monitor mode, where
3621 * the frame would include a radiotap header, where the
3622 * maximum radiotap header length is device-dependent.
3624 * So, for now, we just do this for Ethernet devices, where
3625 * there's no metadata header, and the link-layer header is
3626 * fixed length. We can get the maximum packet size by
3627 * adding 18, the Ethernet header length plus the CRC length
3628 * (just in case we happen to get the CRC in the packet), to
3629 * the MTU of the interface; we fetch the MTU in the hopes
3630 * that it reflects support for jumbo frames. (Even if the
3631 * interface is just being used for passive snooping, the
3632 * driver might set the size of buffers in the receive ring
3633 * based on the MTU, so that the MTU limits the maximum size
3634 * of packets that we can receive.)
3636 * We don't do that if segmentation/fragmentation or receive
3637 * offload are enabled, so we don't get rudely surprised by
3638 * "packets" bigger than the MTU. */
3639 frame_size
= handle
->snapshot
;
3640 if (handle
->linktype
== DLT_EN10MB
) {
3644 offload
= iface_get_offload(handle
);
3645 if (offload
== -1) {
3646 *status
= PCAP_ERROR
;
3650 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
3653 *status
= PCAP_ERROR
;
3656 if (frame_size
> mtu
+ 18)
3657 frame_size
= mtu
+ 18;
3661 /* NOTE: calculus matching those in tpacket_rcv()
3662 * in linux-2.6/net/packet/af_packet.c
3664 len
= sizeof(sk_type
);
3665 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
,
3667 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3668 "getsockopt: %s", pcap_strerror(errno
));
3669 *status
= PCAP_ERROR
;
3672 #ifdef PACKET_RESERVE
3673 len
= sizeof(tp_reserve
);
3674 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
,
3675 &tp_reserve
, &len
) < 0) {
3676 if (errno
!= ENOPROTOOPT
) {
3678 * ENOPROTOOPT means "kernel doesn't support
3679 * PACKET_RESERVE", in which case we fall back
3682 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3683 "getsockopt: %s", pcap_strerror(errno
));
3684 *status
= PCAP_ERROR
;
3687 tp_reserve
= 0; /* older kernel, reserve not supported */
3690 tp_reserve
= 0; /* older kernel, reserve not supported */
3692 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3693 /* XXX: in the kernel maclen is calculated from
3694 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3695 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3696 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3697 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3698 * but I see no way to get those sizes in userspace,
3699 * like for instance with an ifreq ioctl();
3700 * the best thing I've found so far is MAX_HEADER in
3701 * the kernel part of linux-2.6/include/linux/netdevice.h
3702 * which goes up to 128+48=176; since pcap-linux.c
3703 * defines a MAX_LINKHEADER_SIZE of 256 which is
3704 * greater than that, let's use it.. maybe is it even
3705 * large enough to directly replace macoff..
3707 tp_hdrlen
= TPACKET_ALIGN(handlep
->tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3708 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3709 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3710 * of netoff, which contradicts
3711 * linux-2.6/Documentation/networking/packet_mmap.txt
3713 * "- Gap, chosen so that packet data (Start+tp_net)
3714 * aligns to TPACKET_ALIGNMENT=16"
3716 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3717 * "CPUs often take a performance hit
3718 * when accessing unaligned memory locations"
3720 macoff
= netoff
- maclen
;
3721 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3722 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3725 #ifdef HAVE_TPACKET3
3727 /* The "frames" for this are actually buffers that
3728 * contain multiple variable-sized frames.
3730 * We pick a "frame" size of 128K to leave enough
3731 * room for at least one reasonably-sized packet
3732 * in the "frame". */
3733 req
.tp_frame_size
= 131072;
3734 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3739 /* compute the minumum block size that will handle this frame.
3740 * The block has to be page size aligned.
3741 * The max block size allowed by the kernel is arch-dependent and
3742 * it's not explicitly checked here. */
3743 req
.tp_block_size
= getpagesize();
3744 while (req
.tp_block_size
< req
.tp_frame_size
)
3745 req
.tp_block_size
<<= 1;
3747 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3750 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3751 * so we check for PACKET_TIMESTAMP. We check for
3752 * linux/net_tstamp.h just in case a system somehow has
3753 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3756 * SIOCSHWTSTAMP was introduced in the patch that introduced
3757 * linux/net_tstamp.h, so we don't bother checking whether
3758 * SIOCSHWTSTAMP is defined (if your Linux system has
3759 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3760 * Linux system is badly broken).
3762 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3764 * If we were told to do so, ask the kernel and the driver
3765 * to use hardware timestamps.
3767 * Hardware timestamps are only supported with mmapped
3770 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3771 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3772 struct hwtstamp_config hwconfig
;
3777 * Ask for hardware time stamps on all packets,
3778 * including transmitted packets.
3780 memset(&hwconfig
, 0, sizeof(hwconfig
));
3781 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3782 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3784 memset(&ifr
, 0, sizeof(ifr
));
3785 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
3786 ifr
.ifr_data
= (void *)&hwconfig
;
3788 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3793 * Treat this as an error, as the
3794 * user should try to run this
3795 * with the appropriate privileges -
3796 * and, if they can't, shouldn't
3797 * try requesting hardware time stamps.
3799 *status
= PCAP_ERROR_PERM_DENIED
;
3804 * Treat this as a warning, as the
3805 * only way to fix the warning is to
3806 * get an adapter that supports hardware
3807 * time stamps. We'll just fall back
3808 * on the standard host time stamps.
3810 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3814 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3815 "SIOCSHWTSTAMP failed: %s",
3816 pcap_strerror(errno
));
3817 *status
= PCAP_ERROR
;
3822 * Well, that worked. Now specify the type of
3823 * hardware time stamp we want for this
3826 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3828 * Hardware timestamp, synchronized
3829 * with the system clock.
3831 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3834 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3835 * timestamp, not synchronized with the
3838 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3840 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3841 (void *)×ource
, sizeof(timesource
))) {
3842 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3843 "can't set PACKET_TIMESTAMP: %s",
3844 pcap_strerror(errno
));
3845 *status
= PCAP_ERROR
;
3850 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3852 /* ask the kernel to create the ring */
3854 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3856 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3857 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3859 #ifdef HAVE_TPACKET3
3860 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
3861 req
.tp_retire_blk_tov
= (handlep
->timeout
>=0)?handlep
->timeout
:0;
3862 /* private data not used */
3863 req
.tp_sizeof_priv
= 0;
3864 /* Rx ring - feature request bits - none (rxhash will not be filled) */
3865 req
.tp_feature_req_word
= 0;
3868 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3869 (void *) &req
, sizeof(req
))) {
3870 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3872 * Memory failure; try to reduce the requested ring
3875 * We used to reduce this by half -- do 5% instead.
3876 * That may result in more iterations and a longer
3877 * startup, but the user will be much happier with
3878 * the resulting buffer size.
3880 if (req
.tp_frame_nr
< 20)
3881 req
.tp_frame_nr
-= 1;
3883 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3886 if (errno
== ENOPROTOOPT
) {
3888 * We don't have ring buffer support in this kernel.
3892 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3893 "can't create rx ring on packet socket: %s",
3894 pcap_strerror(errno
));
3895 *status
= PCAP_ERROR
;
3899 /* memory map the rx ring */
3900 handlep
->mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3901 handlep
->mmapbuf
= mmap(0, handlep
->mmapbuflen
,
3902 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3903 if (handlep
->mmapbuf
== MAP_FAILED
) {
3904 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3905 "can't mmap rx ring: %s", pcap_strerror(errno
));
3907 /* clear the allocated ring on error*/
3908 destroy_ring(handle
);
3909 *status
= PCAP_ERROR
;
3913 /* allocate a ring for each frame header pointer*/
3914 handle
->cc
= req
.tp_frame_nr
;
3915 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3916 if (!handle
->buffer
) {
3917 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3918 "can't allocate ring of frame headers: %s",
3919 pcap_strerror(errno
));
3921 destroy_ring(handle
);
3922 *status
= PCAP_ERROR
;
3926 /* fill the header ring with proper frame ptr*/
3928 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3929 void *base
= &handlep
->mmapbuf
[i
*req
.tp_block_size
];
3930 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3931 RING_GET_FRAME(handle
) = base
;
3932 base
+= req
.tp_frame_size
;
3936 handle
->bufsize
= req
.tp_frame_size
;
3941 /* free all ring related resources*/
3943 destroy_ring(pcap_t
*handle
)
3945 struct pcap_linux
*handlep
= handle
->priv
;
3947 /* tell the kernel to destroy the ring*/
3948 struct tpacket_req req
;
3949 memset(&req
, 0, sizeof(req
));
3950 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3951 (void *) &req
, sizeof(req
));
3953 /* if ring is mapped, unmap it*/
3954 if (handlep
->mmapbuf
) {
3955 /* do not test for mmap failure, as we can't recover from any error */
3956 munmap(handlep
->mmapbuf
, handlep
->mmapbuflen
);
3957 handlep
->mmapbuf
= NULL
;
3962 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3963 * for Linux mmapped capture.
3965 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3966 * data handed to the callback to be valid after the callback returns,
3967 * but pcap_read_linux_mmap() has to release that packet as soon as
3968 * the callback returns (otherwise, the kernel thinks there's still
3969 * at least one unprocessed packet available in the ring, so a select()
3970 * will immediately return indicating that there's data to process), so,
3971 * in the callback, we have to make a copy of the packet.
3973 * Yes, this means that, if the capture is using the ring buffer, using
3974 * pcap_next() or pcap_next_ex() requires more copies than using
3975 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3976 * pcap_next() or pcap_next_ex().
3979 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3980 const u_char
*bytes
)
3982 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3983 pcap_t
*handle
= sp
->pd
;
3984 struct pcap_linux
*handlep
= handle
->priv
;
3987 memcpy(handlep
->oneshot_buffer
, bytes
, h
->caplen
);
3988 *sp
->pkt
= handlep
->oneshot_buffer
;
3992 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3994 struct pcap_linux
*handlep
= handle
->priv
;
3996 destroy_ring(handle
);
3997 if (handlep
->oneshot_buffer
!= NULL
) {
3998 free(handlep
->oneshot_buffer
);
3999 handlep
->oneshot_buffer
= NULL
;
4001 pcap_cleanup_linux(handle
);
4006 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
4008 struct pcap_linux
*handlep
= p
->priv
;
4010 /* use negative value of timeout to indicate non blocking ops */
4011 return (handlep
->timeout
<0);
4015 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
4017 struct pcap_linux
*handlep
= p
->priv
;
4020 * Map each value to their corresponding negation to
4021 * preserve the timeout value provided with pcap_set_timeout.
4024 if (handlep
->timeout
>= 0) {
4026 * Indicate that we're switching to
4027 * non-blocking mode.
4029 handlep
->timeout
= ~handlep
->timeout
;
4032 if (handlep
->timeout
< 0) {
4033 handlep
->timeout
= ~handlep
->timeout
;
4039 static inline union thdr
*
4040 pcap_get_ring_frame(pcap_t
*handle
, int status
)
4042 struct pcap_linux
*handlep
= handle
->priv
;
4045 h
.raw
= RING_GET_FRAME(handle
);
4046 switch (handlep
->tp_version
) {
4048 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
4052 #ifdef HAVE_TPACKET2
4054 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
4059 #ifdef HAVE_TPACKET3
4061 if (status
!= (h
.h3
->hdr
.bh1
.block_status
? TP_STATUS_USER
:
4074 /* wait for frames availability.*/
4075 static int pcap_wait_for_frames_mmap(pcap_t
*handle
)
4077 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
4078 struct pcap_linux
*handlep
= handle
->priv
;
4081 struct pollfd pollinfo
;
4084 pollinfo
.fd
= handle
->fd
;
4085 pollinfo
.events
= POLLIN
;
4087 if (handlep
->timeout
== 0) {
4088 #ifdef HAVE_TPACKET3
4090 * XXX - due to a set of (mis)features in the
4091 * TPACKET_V3 kernel code, blocking forever with
4092 * a TPACKET_V3 socket can, if few packets
4093 * are arriving and passing the socket filter,
4094 * cause most packets to be dropped. See
4095 * libpcap issue #335 for the full painful
4096 * story. The workaround is to have poll()
4097 * time out very quickly, so we grab the
4098 * frames handed to us, and return them to
4101 * If those issues are ever fixed, we might
4102 * want to check the kernel version and block
4103 * forever with TPACKET_V3 if we're running
4104 * with a kernel that has the fix.
4106 if (handlep
->tp_version
== TPACKET_V3
)
4107 timeout
= 1; /* don't block for very long */
4110 timeout
= -1; /* block forever */
4111 } else if (handlep
->timeout
> 0)
4112 timeout
= handlep
->timeout
; /* block for that amount of time */
4114 timeout
= 0; /* non-blocking mode - poll to pick up errors */
4116 ret
= poll(&pollinfo
, 1, timeout
);
4117 if (ret
< 0 && errno
!= EINTR
) {
4118 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4119 "can't poll on packet socket: %s",
4120 pcap_strerror(errno
));
4122 } else if (ret
> 0 &&
4123 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
4125 * There's some indication other than
4126 * "you can read on this descriptor" on
4129 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
4130 snprintf(handle
->errbuf
,
4132 "Hangup on packet socket");
4135 if (pollinfo
.revents
& POLLERR
) {
4137 * A recv() will give us the
4138 * actual error code.
4140 * XXX - make the socket non-blocking?
4142 if (recv(handle
->fd
, &c
, sizeof c
,
4144 continue; /* what, no error? */
4145 if (errno
== ENETDOWN
) {
4147 * The device on which we're
4148 * capturing went away.
4150 * XXX - we should really return
4151 * PCAP_ERROR_IFACE_NOT_UP,
4152 * but pcap_dispatch() etc.
4153 * aren't defined to return
4156 snprintf(handle
->errbuf
,
4158 "The interface went down");
4160 snprintf(handle
->errbuf
,
4162 "Error condition on packet socket: %s",
4167 if (pollinfo
.revents
& POLLNVAL
) {
4168 snprintf(handle
->errbuf
,
4170 "Invalid polling request on packet socket");
4174 /* check for break loop condition on interrupted syscall*/
4175 if (handle
->break_loop
) {
4176 handle
->break_loop
= 0;
4177 return PCAP_ERROR_BREAK
;
4184 /* handle a single memory mapped packet */
4185 static int pcap_handle_packet_mmap(
4187 pcap_handler callback
,
4189 unsigned char *frame
,
4190 unsigned int tp_len
,
4191 unsigned int tp_mac
,
4192 unsigned int tp_snaplen
,
4193 unsigned int tp_sec
,
4194 unsigned int tp_usec
,
4195 int tp_vlan_tci_valid
,
4198 struct pcap_linux
*handlep
= handle
->priv
;
4200 struct sockaddr_ll
*sll
;
4201 struct pcap_pkthdr pcaphdr
;
4203 /* perform sanity check on internal offset. */
4204 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
4205 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4206 "corrupted frame on kernel ring mac "
4207 "offset %d + caplen %d > frame len %d",
4208 tp_mac
, tp_snaplen
, handle
->bufsize
);
4212 /* run filter on received packet
4213 * If the kernel filtering is enabled we need to run the
4214 * filter until all the frames present into the ring
4215 * at filter creation time are processed.
4216 * In this case, blocks_to_filter_in_userland is used
4217 * as a counter for the packet we need to filter.
4218 * Note: alternatively it could be possible to stop applying
4219 * the filter when the ring became empty, but it can possibly
4220 * happen a lot later... */
4221 bp
= frame
+ tp_mac
;
4222 if (handlep
->filter_in_userland
&& handle
->fcode
.bf_insns
&&
4223 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
4224 tp_len
, tp_snaplen
) == 0))
4227 sll
= (void *)frame
+ TPACKET_ALIGN(handlep
->tp_hdrlen
);
4228 if (!linux_check_direction(handle
, sll
))
4231 /* get required packet info from ring header */
4232 pcaphdr
.ts
.tv_sec
= tp_sec
;
4233 pcaphdr
.ts
.tv_usec
= tp_usec
;
4234 pcaphdr
.caplen
= tp_snaplen
;
4235 pcaphdr
.len
= tp_len
;
4237 /* if required build in place the sll header*/
4238 if (handlep
->cooked
) {
4239 struct sll_header
*hdrp
;
4242 * The kernel should have left us with enough
4243 * space for an sll header; back up the packet
4244 * data pointer into that space, as that'll be
4245 * the beginning of the packet we pass to the
4251 * Let's make sure that's past the end of
4252 * the tpacket header, i.e. >=
4253 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4254 * don't step on the header when we construct
4257 if (bp
< (u_char
*)frame
+
4258 TPACKET_ALIGN(handlep
->tp_hdrlen
) +
4259 sizeof(struct sockaddr_ll
)) {
4260 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4261 "cooked-mode frame doesn't have room for sll header");
4266 * OK, that worked; construct the sll header.
4268 hdrp
= (struct sll_header
*)bp
;
4269 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
4271 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
4272 hdrp
->sll_halen
= htons(sll
->sll_halen
);
4273 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
4274 hdrp
->sll_protocol
= sll
->sll_protocol
;
4276 /* update packet len */
4277 pcaphdr
.caplen
+= SLL_HDR_LEN
;
4278 pcaphdr
.len
+= SLL_HDR_LEN
;
4281 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4282 if (tp_vlan_tci_valid
&&
4283 handlep
->vlan_offset
!= -1 &&
4284 tp_snaplen
>= (unsigned int) handlep
->vlan_offset
)
4286 struct vlan_tag
*tag
;
4289 memmove(bp
, bp
+ VLAN_TAG_LEN
, handlep
->vlan_offset
);
4291 tag
= (struct vlan_tag
*)(bp
+ handlep
->vlan_offset
);
4292 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
4293 tag
->vlan_tci
= htons(tp_vlan_tci
);
4295 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
4296 pcaphdr
.len
+= VLAN_TAG_LEN
;
4301 * The only way to tell the kernel to cut off the
4302 * packet at a snapshot length is with a filter program;
4303 * if there's no filter program, the kernel won't cut
4306 * Trim the snapshot length to be no longer than the
4307 * specified snapshot length.
4309 if (pcaphdr
.caplen
> handle
->snapshot
)
4310 pcaphdr
.caplen
= handle
->snapshot
;
4312 /* pass the packet to the user */
4313 callback(user
, &pcaphdr
, bp
);
4319 pcap_read_linux_mmap_v1(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4322 struct pcap_linux
*handlep
= handle
->priv
;
4326 /* wait for frames availability.*/
4327 ret
= pcap_wait_for_frames_mmap(handle
);
4332 /* non-positive values of max_packets are used to require all
4333 * packets currently available in the ring */
4334 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4337 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4341 ret
= pcap_handle_packet_mmap(
4355 handlep
->packets_read
++;
4356 } else if (ret
< 0) {
4361 * Hand this block back to the kernel, and, if we're
4362 * counting blocks that need to be filtered in userland
4363 * after having been filtered by the kernel, count
4364 * the one we've just processed.
4366 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
4367 if (handlep
->blocks_to_filter_in_userland
> 0) {
4368 handlep
->blocks_to_filter_in_userland
--;
4369 if (handlep
->blocks_to_filter_in_userland
== 0) {
4371 * No more blocks need to be filtered
4374 handlep
->filter_in_userland
= 0;
4379 if (++handle
->offset
>= handle
->cc
)
4382 /* check for break loop condition*/
4383 if (handle
->break_loop
) {
4384 handle
->break_loop
= 0;
4385 return PCAP_ERROR_BREAK
;
4391 #ifdef HAVE_TPACKET2
4393 pcap_read_linux_mmap_v2(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4396 struct pcap_linux
*handlep
= handle
->priv
;
4400 /* wait for frames availability.*/
4401 ret
= pcap_wait_for_frames_mmap(handle
);
4406 /* non-positive values of max_packets are used to require all
4407 * packets currently available in the ring */
4408 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4411 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4415 ret
= pcap_handle_packet_mmap(
4424 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? h
.h2
->tp_nsec
: h
.h2
->tp_nsec
/ 1000,
4425 #if defined(TP_STATUS_VLAN_VALID)
4426 (h
.h2
->tp_vlan_tci
|| (h
.h2
->tp_status
& TP_STATUS_VLAN_VALID
)),
4428 h
.h2
->tp_vlan_tci
!= 0,
4433 handlep
->packets_read
++;
4434 } else if (ret
< 0) {
4439 * Hand this block back to the kernel, and, if we're
4440 * counting blocks that need to be filtered in userland
4441 * after having been filtered by the kernel, count
4442 * the one we've just processed.
4444 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
4445 if (handlep
->blocks_to_filter_in_userland
> 0) {
4446 handlep
->blocks_to_filter_in_userland
--;
4447 if (handlep
->blocks_to_filter_in_userland
== 0) {
4449 * No more blocks need to be filtered
4452 handlep
->filter_in_userland
= 0;
4457 if (++handle
->offset
>= handle
->cc
)
4460 /* check for break loop condition*/
4461 if (handle
->break_loop
) {
4462 handle
->break_loop
= 0;
4463 return PCAP_ERROR_BREAK
;
4468 #endif /* HAVE_TPACKET2 */
4470 #ifdef HAVE_TPACKET3
4472 pcap_read_linux_mmap_v3(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
4475 struct pcap_linux
*handlep
= handle
->priv
;
4481 if (handlep
->current_packet
== NULL
) {
4482 /* wait for frames availability.*/
4483 ret
= pcap_wait_for_frames_mmap(handle
);
4488 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4490 if (pkts
== 0 && handlep
->timeout
== 0) {
4491 /* Block until we see a packet. */
4497 /* non-positive values of max_packets are used to require all
4498 * packets currently available in the ring */
4499 while ((pkts
< max_packets
) || PACKET_COUNT_IS_UNLIMITED(max_packets
)) {
4500 if (handlep
->current_packet
== NULL
) {
4501 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
4505 handlep
->current_packet
= h
.raw
+ h
.h3
->hdr
.bh1
.offset_to_first_pkt
;
4506 handlep
->packets_left
= h
.h3
->hdr
.bh1
.num_pkts
;
4508 int packets_to_read
= handlep
->packets_left
;
4510 if (!PACKET_COUNT_IS_UNLIMITED(max_packets
) && packets_to_read
> max_packets
) {
4511 packets_to_read
= max_packets
;
4514 while(packets_to_read
--) {
4515 struct tpacket3_hdr
* tp3_hdr
= (struct tpacket3_hdr
*) handlep
->current_packet
;
4516 ret
= pcap_handle_packet_mmap(
4520 handlep
->current_packet
,
4523 tp3_hdr
->tp_snaplen
,
4525 handle
->opt
.tstamp_precision
== PCAP_TSTAMP_PRECISION_NANO
? tp3_hdr
->tp_nsec
: tp3_hdr
->tp_nsec
/ 1000,
4526 #if defined(TP_STATUS_VLAN_VALID)
4527 (tp3_hdr
->hv1
.tp_vlan_tci
|| (tp3_hdr
->tp_status
& TP_STATUS_VLAN_VALID
)),
4529 tp3_hdr
->hv1
.tp_vlan_tci
!= 0,
4531 tp3_hdr
->hv1
.tp_vlan_tci
);
4534 handlep
->packets_read
++;
4535 } else if (ret
< 0) {
4536 handlep
->current_packet
= NULL
;
4539 handlep
->current_packet
+= tp3_hdr
->tp_next_offset
;
4540 handlep
->packets_left
--;
4543 if (handlep
->packets_left
<= 0) {
4545 * Hand this block back to the kernel, and, if
4546 * we're counting blocks that need to be
4547 * filtered in userland after having been
4548 * filtered by the kernel, count the one we've
4551 h
.h3
->hdr
.bh1
.block_status
= TP_STATUS_KERNEL
;
4552 if (handlep
->blocks_to_filter_in_userland
> 0) {
4553 handlep
->blocks_to_filter_in_userland
--;
4554 if (handlep
->blocks_to_filter_in_userland
== 0) {
4556 * No more blocks need to be filtered
4559 handlep
->filter_in_userland
= 0;
4564 if (++handle
->offset
>= handle
->cc
)
4567 handlep
->current_packet
= NULL
;
4570 /* check for break loop condition*/
4571 if (handle
->break_loop
) {
4572 handle
->break_loop
= 0;
4573 return PCAP_ERROR_BREAK
;
4576 if (pkts
== 0 && handlep
->timeout
== 0) {
4577 /* Block until we see a packet. */
4582 #endif /* HAVE_TPACKET3 */
4585 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
4587 struct pcap_linux
*handlep
= handle
->priv
;
4592 * Don't rewrite "ret" instructions; we don't need to, as
4593 * we're not reading packets with recvmsg(), and we don't
4594 * want to, as, by not rewriting them, the kernel can avoid
4595 * copying extra data.
4597 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
4602 * If we're filtering in userland, there's nothing to do;
4603 * the new filter will be used for the next packet.
4605 if (handlep
->filter_in_userland
)
4609 * We're filtering in the kernel; the packets present in
4610 * all blocks currently in the ring were already filtered
4611 * by the old filter, and so will need to be filtered in
4612 * userland by the new filter.
4614 * Get an upper bound for the number of such blocks; first,
4615 * walk the ring backward and count the free blocks.
4617 offset
= handle
->offset
;
4618 if (--handle
->offset
< 0)
4619 handle
->offset
= handle
->cc
- 1;
4620 for (n
=0; n
< handle
->cc
; ++n
) {
4621 if (--handle
->offset
< 0)
4622 handle
->offset
= handle
->cc
- 1;
4623 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
4628 * If we found free blocks, decrement the count of free
4629 * blocks by 1, just in case we lost a race with another
4630 * thread of control that was adding a packet while
4631 * we were counting and that had run the filter before
4634 * XXX - could there be more than one block added in
4637 * XXX - is there a way to avoid that race, e.g. somehow
4638 * wait for all packets that passed the old filter to
4639 * be added to the ring?
4644 /* be careful to not change current ring position */
4645 handle
->offset
= offset
;
4648 * Set the count of blocks worth of packets to filter
4649 * in userland to the total number of blocks in the
4650 * ring minus the number of free blocks we found, and
4651 * turn on userland filtering. (The count of blocks
4652 * worth of packets to filter in userland is guaranteed
4653 * not to be zero - n, above, couldn't be set to a
4654 * value > handle->cc, and if it were equal to
4655 * handle->cc, it wouldn't be zero, and thus would
4656 * be decremented to handle->cc - 1.)
4658 handlep
->blocks_to_filter_in_userland
= handle
->cc
- n
;
4659 handlep
->filter_in_userland
= 1;
4663 #endif /* HAVE_PACKET_RING */
4666 #ifdef HAVE_PF_PACKET_SOCKETS
4668 * Return the index of the given device name. Fill ebuf and return
4672 iface_get_id(int fd
, const char *device
, char *ebuf
)
4676 memset(&ifr
, 0, sizeof(ifr
));
4677 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4679 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4680 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4681 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
4685 return ifr
.ifr_ifindex
;
4689 * Bind the socket associated with FD to the given device.
4690 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4691 * or a PCAP_ERROR_ value on a hard error.
4694 iface_bind(int fd
, int ifindex
, char *ebuf
)
4696 struct sockaddr_ll sll
;
4698 socklen_t errlen
= sizeof(err
);
4700 memset(&sll
, 0, sizeof(sll
));
4701 sll
.sll_family
= AF_PACKET
;
4702 sll
.sll_ifindex
= ifindex
;
4703 sll
.sll_protocol
= htons(ETH_P_ALL
);
4705 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4706 if (errno
== ENETDOWN
) {
4708 * Return a "network down" indication, so that
4709 * the application can report that rather than
4710 * saying we had a mysterious failure and
4711 * suggest that they report a problem to the
4712 * libpcap developers.
4714 return PCAP_ERROR_IFACE_NOT_UP
;
4716 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4717 "bind: %s", pcap_strerror(errno
));
4722 /* Any pending errors, e.g., network is down? */
4724 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4725 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4726 "getsockopt: %s", pcap_strerror(errno
));
4730 if (err
== ENETDOWN
) {
4732 * Return a "network down" indication, so that
4733 * the application can report that rather than
4734 * saying we had a mysterious failure and
4735 * suggest that they report a problem to the
4736 * libpcap developers.
4738 return PCAP_ERROR_IFACE_NOT_UP
;
4739 } else if (err
> 0) {
4740 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4741 "bind: %s", pcap_strerror(err
));
4748 #ifdef IW_MODE_MONITOR
4750 * Check whether the device supports the Wireless Extensions.
4751 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4752 * if the device doesn't even exist.
4755 has_wext(int sock_fd
, const char *device
, char *ebuf
)
4759 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4760 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4761 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
4763 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4764 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4765 if (errno
== ENODEV
)
4766 return PCAP_ERROR_NO_SUCH_DEVICE
;
4771 * Per me si va ne la citta dolente,
4772 * Per me si va ne l'etterno dolore,
4774 * Lasciate ogne speranza, voi ch'intrate.
4776 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4792 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4793 * on if it's not already on.
4795 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4796 * on this device, or a PCAP_ERROR_ value if we do support them but
4797 * we weren't able to turn monitor mode on.
4800 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
4803 * XXX - at least some adapters require non-Wireless Extensions
4804 * mechanisms to turn monitor mode on.
4806 * Atheros cards might require that a separate "monitor virtual access
4807 * point" be created, with later versions of the madwifi driver.
4808 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4809 * monitor -bssid", which apparently spits out a line "athN"
4810 * where "athN" is the monitor mode device. To leave monitor
4811 * mode, it destroys the monitor mode device.
4813 * Some Intel Centrino adapters might require private ioctls to get
4814 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4815 * configure a separate "rtapN" interface to capture in monitor
4816 * mode without preventing the adapter from operating normally.
4817 * (airmon-ng doesn't appear to use that, though.)
4819 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4820 * up, and if all drivers were converted to mac80211 drivers.
4822 * If interface {if} is a mac80211 driver, the file
4823 * /sys/class/net/{if}/phy80211 is a symlink to
4824 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4826 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4827 * least, has a "wmaster0" device and a "wlan0" device; the
4828 * latter is the one with the IP address. Both show up in
4829 * "tcpdump -D" output. Capturing on the wmaster0 device
4830 * captures with 802.11 headers.
4832 * airmon-ng searches through /sys/class/net for devices named
4833 * monN, starting with mon0; as soon as one *doesn't* exist,
4834 * it chooses that as the monitor device name. If the "iw"
4835 * command exists, it does "iw dev {if} interface add {monif}
4836 * type monitor", where {monif} is the monitor device. It
4837 * then (sigh) sleeps .1 second, and then configures the
4838 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4839 * is a file, it writes {mondev}, without a newline, to that file,
4840 * and again (sigh) sleeps .1 second, and then iwconfig's that
4841 * device into monitor mode and configures it up. Otherwise,
4842 * you can't do monitor mode.
4844 * All these devices are "glued" together by having the
4845 * /sys/class/net/{device}/phy80211 links pointing to the same
4846 * place, so, given a wmaster, wlan, or mon device, you can
4847 * find the other devices by looking for devices with
4848 * the same phy80211 link.
4850 * To turn monitor mode off, delete the monitor interface,
4851 * either with "iw dev {monif} interface del" or by sending
4852 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4854 * Note: if you try to create a monitor device named "monN", and
4855 * there's already a "monN" device, it fails, as least with
4856 * the netlink interface (which is what iw uses), with a return
4857 * value of -ENFILE. (Return values are negative errnos.) We
4858 * could probably use that to find an unused device.
4860 struct pcap_linux
*handlep
= handle
->priv
;
4863 struct iw_priv_args
*priv
;
4864 monitor_type montype
;
4873 * Does this device *support* the Wireless Extensions?
4875 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4877 return err
; /* either it doesn't or the device doesn't even exist */
4879 * Start out assuming we have no private extensions to control
4882 montype
= MONITOR_WEXT
;
4886 * Try to get all the Wireless Extensions private ioctls
4887 * supported by this device.
4889 * First, get the size of the buffer we need, by supplying no
4890 * buffer and a length of 0. If the device supports private
4891 * ioctls, it should return E2BIG, with ireq.u.data.length set
4892 * to the length we need. If it doesn't support them, it should
4893 * return EOPNOTSUPP.
4895 memset(&ireq
, 0, sizeof ireq
);
4896 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4897 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4898 ireq
.u
.data
.pointer
= (void *)args
;
4899 ireq
.u
.data
.length
= 0;
4900 ireq
.u
.data
.flags
= 0;
4901 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4902 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4903 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4907 if (errno
!= EOPNOTSUPP
) {
4909 * OK, it's not as if there are no private ioctls.
4911 if (errno
!= E2BIG
) {
4915 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4916 "%s: SIOCGIWPRIV: %s", device
,
4917 pcap_strerror(errno
));
4922 * OK, try to get the list of private ioctls.
4924 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4926 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4927 "malloc: %s", pcap_strerror(errno
));
4930 ireq
.u
.data
.pointer
= (void *)priv
;
4931 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4932 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4933 "%s: SIOCGIWPRIV: %s", device
,
4934 pcap_strerror(errno
));
4940 * Look for private ioctls to turn monitor mode on or, if
4941 * monitor mode is on, to set the header type.
4943 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4944 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4946 * Hostap driver, use this one.
4947 * Set monitor mode first.
4948 * You can set it to 0 to get DLT_IEEE80211,
4949 * 1 to get DLT_PRISM, 2 to get
4950 * DLT_IEEE80211_RADIO_AVS, and, with more
4951 * recent versions of the driver, 3 to get
4952 * DLT_IEEE80211_RADIO.
4954 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4956 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4958 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4960 montype
= MONITOR_HOSTAP
;
4964 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4966 * Prism54 driver, use this one.
4967 * Set monitor mode first.
4968 * You can set it to 2 to get DLT_IEEE80211
4969 * or 3 or get DLT_PRISM.
4971 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4973 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4975 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4977 montype
= MONITOR_PRISM54
;
4981 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4983 * RT2570 driver, use this one.
4984 * Do this after turning monitor mode on.
4985 * You can set it to 1 to get DLT_PRISM or 2
4986 * to get DLT_IEEE80211.
4988 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4990 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4992 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4994 montype
= MONITOR_RT2570
;
4998 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
5000 * RT73 driver, use this one.
5001 * Do this after turning monitor mode on.
5002 * Its argument is a *string*; you can
5003 * set it to "1" to get DLT_PRISM or "2"
5004 * to get DLT_IEEE80211.
5006 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
5008 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
5010 montype
= MONITOR_RT73
;
5014 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
5016 * One of the RTL8xxx drivers, use this one.
5017 * It can only be done after monitor mode
5018 * has been turned on. You can set it to 1
5019 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5021 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5023 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5025 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
5027 montype
= MONITOR_RTL8XXX
;
5031 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
5033 * RT2500 or RT61 driver, use this one.
5034 * It has one one-byte parameter; set
5035 * u.data.length to 1 and u.data.pointer to
5036 * point to the parameter.
5037 * It doesn't itself turn monitor mode on.
5038 * You can set it to 1 to allow transmitting
5039 * in monitor mode(?) and get DLT_IEEE80211,
5040 * or set it to 0 to disallow transmitting in
5041 * monitor mode(?) and get DLT_PRISM.
5043 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5045 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
5047 montype
= MONITOR_RT2500
;
5051 if (strcmp(priv
[i
].name
, "monitor") == 0) {
5053 * Either ACX100 or hostap, use this one.
5054 * It turns monitor mode on.
5055 * If it takes two arguments, it's ACX100;
5056 * the first argument is 1 for DLT_PRISM
5057 * or 2 for DLT_IEEE80211, and the second
5058 * argument is the channel on which to
5059 * run. If it takes one argument, it's
5060 * HostAP, and the argument is 2 for
5061 * DLT_IEEE80211 and 3 for DLT_PRISM.
5063 * If we see this, we don't quit, as this
5064 * might be a version of the hostap driver
5065 * that also supports "monitor_type".
5067 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
5069 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
5071 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
5074 montype
= MONITOR_PRISM
;
5079 montype
= MONITOR_ACX100
;
5092 * XXX - ipw3945? islism?
5098 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5099 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5100 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
5102 * We probably won't be able to set the mode, either.
5104 return PCAP_ERROR_RFMON_NOTSUP
;
5108 * Is it currently in monitor mode?
5110 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
5112 * Yes. Just leave things as they are.
5113 * We don't offer multiple link-layer types, as
5114 * changing the link-layer type out from under
5115 * somebody else capturing in monitor mode would
5116 * be considered rude.
5121 * No. We have to put the adapter into rfmon mode.
5125 * If we haven't already done so, arrange to have
5126 * "pcap_close_all()" called when we exit.
5128 if (!pcap_do_addexit(handle
)) {
5130 * "atexit()" failed; don't put the interface
5131 * in rfmon mode, just give up.
5133 return PCAP_ERROR_RFMON_NOTSUP
;
5137 * Save the old mode.
5139 handlep
->oldmode
= ireq
.u
.mode
;
5142 * Put the adapter in rfmon mode. How we do this depends
5143 * on whether we have a special private ioctl or not.
5145 if (montype
== MONITOR_PRISM
) {
5147 * We have the "monitor" private ioctl, but none of
5148 * the other private ioctls. Use this, and select
5151 * If it fails, just fall back on SIOCSIWMODE.
5153 memset(&ireq
, 0, sizeof ireq
);
5154 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5155 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5156 ireq
.u
.data
.length
= 1; /* 1 argument */
5157 args
[0] = 3; /* request Prism header */
5158 memcpy(ireq
.u
.name
, args
, sizeof (int));
5159 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
5162 * Note that we have to put the old mode back
5163 * when we close the device.
5165 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5168 * Add this to the list of pcaps to close
5171 pcap_add_to_pcaps_to_close(handle
);
5177 * Failure. Fall back on SIOCSIWMODE.
5182 * First, take the interface down if it's up; otherwise, we
5185 memset(&ifr
, 0, sizeof(ifr
));
5186 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5187 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5188 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5189 "%s: Can't get flags: %s", device
, strerror(errno
));
5193 if (ifr
.ifr_flags
& IFF_UP
) {
5194 oldflags
= ifr
.ifr_flags
;
5195 ifr
.ifr_flags
&= ~IFF_UP
;
5196 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5197 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5198 "%s: Can't set flags: %s", device
, strerror(errno
));
5204 * Then turn monitor mode on.
5206 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5207 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5208 ireq
.u
.mode
= IW_MODE_MONITOR
;
5209 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
5211 * Scientist, you've failed.
5212 * Bring the interface back up if we shut it down.
5214 ifr
.ifr_flags
= oldflags
;
5215 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5216 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5217 "%s: Can't set flags: %s", device
, strerror(errno
));
5220 return PCAP_ERROR_RFMON_NOTSUP
;
5224 * XXX - airmon-ng does "iwconfig {if} key off" after setting
5225 * monitor mode and setting the channel, and then does
5230 * Now select the appropriate radio header.
5236 * We don't have any private ioctl to set the header.
5240 case MONITOR_HOSTAP
:
5242 * Try to select the radiotap header.
5244 memset(&ireq
, 0, sizeof ireq
);
5245 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5246 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5247 args
[0] = 3; /* request radiotap header */
5248 memcpy(ireq
.u
.name
, args
, sizeof (int));
5249 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5250 break; /* success */
5253 * That failed. Try to select the AVS header.
5255 memset(&ireq
, 0, sizeof ireq
);
5256 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5257 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5258 args
[0] = 2; /* request AVS header */
5259 memcpy(ireq
.u
.name
, args
, sizeof (int));
5260 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
5261 break; /* success */
5264 * That failed. Try to select the Prism header.
5266 memset(&ireq
, 0, sizeof ireq
);
5267 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5268 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5269 args
[0] = 1; /* request Prism header */
5270 memcpy(ireq
.u
.name
, args
, sizeof (int));
5271 ioctl(sock_fd
, cmd
, &ireq
);
5276 * The private ioctl failed.
5280 case MONITOR_PRISM54
:
5282 * Select the Prism header.
5284 memset(&ireq
, 0, sizeof ireq
);
5285 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5286 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5287 args
[0] = 3; /* request Prism header */
5288 memcpy(ireq
.u
.name
, args
, sizeof (int));
5289 ioctl(sock_fd
, cmd
, &ireq
);
5292 case MONITOR_ACX100
:
5294 * Get the current channel.
5296 memset(&ireq
, 0, sizeof ireq
);
5297 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5298 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5299 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
5300 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5301 "%s: SIOCGIWFREQ: %s", device
,
5302 pcap_strerror(errno
));
5305 channel
= ireq
.u
.freq
.m
;
5308 * Select the Prism header, and set the channel to the
5311 memset(&ireq
, 0, sizeof ireq
);
5312 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5313 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5314 args
[0] = 1; /* request Prism header */
5315 args
[1] = channel
; /* set channel */
5316 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
5317 ioctl(sock_fd
, cmd
, &ireq
);
5320 case MONITOR_RT2500
:
5322 * Disallow transmission - that turns on the
5325 memset(&ireq
, 0, sizeof ireq
);
5326 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5327 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5328 args
[0] = 0; /* disallow transmitting */
5329 memcpy(ireq
.u
.name
, args
, sizeof (int));
5330 ioctl(sock_fd
, cmd
, &ireq
);
5333 case MONITOR_RT2570
:
5335 * Force the Prism header.
5337 memset(&ireq
, 0, sizeof ireq
);
5338 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5339 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5340 args
[0] = 1; /* request Prism header */
5341 memcpy(ireq
.u
.name
, args
, sizeof (int));
5342 ioctl(sock_fd
, cmd
, &ireq
);
5347 * Force the Prism header.
5349 memset(&ireq
, 0, sizeof ireq
);
5350 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5351 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5352 ireq
.u
.data
.length
= 1; /* 1 argument */
5353 ireq
.u
.data
.pointer
= "1";
5354 ireq
.u
.data
.flags
= 0;
5355 ioctl(sock_fd
, cmd
, &ireq
);
5358 case MONITOR_RTL8XXX
:
5360 * Force the Prism header.
5362 memset(&ireq
, 0, sizeof ireq
);
5363 strlcpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
5364 sizeof ireq
.ifr_ifrn
.ifrn_name
);
5365 args
[0] = 1; /* request Prism header */
5366 memcpy(ireq
.u
.name
, args
, sizeof (int));
5367 ioctl(sock_fd
, cmd
, &ireq
);
5372 * Now bring the interface back up if we brought it down.
5374 if (oldflags
!= 0) {
5375 ifr
.ifr_flags
= oldflags
;
5376 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5377 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5378 "%s: Can't set flags: %s", device
, strerror(errno
));
5381 * At least try to restore the old mode on the
5384 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
5386 * Scientist, you've failed.
5389 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5390 "Please adjust manually.\n",
5398 * Note that we have to put the old mode back when we
5401 handlep
->must_do_on_close
|= MUST_CLEAR_RFMON
;
5404 * Add this to the list of pcaps to close when we exit.
5406 pcap_add_to_pcaps_to_close(handle
);
5410 #endif /* IW_MODE_MONITOR */
5413 * Try various mechanisms to enter monitor mode.
5416 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
5418 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5423 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
5425 return ret
; /* error attempting to do so */
5427 return 1; /* success */
5428 #endif /* HAVE_LIBNL */
5430 #ifdef IW_MODE_MONITOR
5431 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
5433 return ret
; /* error attempting to do so */
5435 return 1; /* success */
5436 #endif /* IW_MODE_MONITOR */
5439 * Either none of the mechanisms we know about work or none
5440 * of those mechanisms are available, so we can't do monitor
5447 * Find out if we have any form of fragmentation/reassembly offloading.
5449 * We do so using SIOCETHTOOL checking for various types of offloading;
5450 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5451 * of the types of offloading, there's nothing we can do to check, so
5452 * we just say "no, we don't".
5454 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5456 iface_ethtool_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
5459 struct ethtool_value eval
;
5461 memset(&ifr
, 0, sizeof(ifr
));
5462 strlcpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
5465 ifr
.ifr_data
= (caddr_t
)&eval
;
5466 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
5467 if (errno
== EOPNOTSUPP
|| errno
== EINVAL
) {
5469 * OK, let's just return 0, which, in our
5470 * case, either means "no, what we're asking
5471 * about is not enabled" or "all the flags
5472 * are clear (i.e., nothing is enabled)".
5476 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5477 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
5478 cmdname
, strerror(errno
));
5485 iface_get_offload(pcap_t
*handle
)
5490 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
5494 return 1; /* TCP segmentation offloading on */
5498 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
5502 return 1; /* UDP fragmentation offloading on */
5507 * XXX - will this cause large unsegmented packets to be
5508 * handed to PF_PACKET sockets on transmission? If not,
5509 * this need not be checked.
5511 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
5515 return 1; /* generic segmentation offloading on */
5518 #ifdef ETHTOOL_GFLAGS
5519 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
5522 if (ret
& ETH_FLAG_LRO
)
5523 return 1; /* large receive offloading on */
5528 * XXX - will this cause large reassembled packets to be
5529 * handed to PF_PACKET sockets on receipt? If not,
5530 * this need not be checked.
5532 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
5536 return 1; /* generic (large) receive offloading on */
5541 #else /* SIOCETHTOOL */
5543 iface_get_offload(pcap_t
*handle _U_
)
5546 * XXX - do we need to get this information if we don't
5547 * have the ethtool ioctls? If so, how do we do that?
5551 #endif /* SIOCETHTOOL */
5553 #endif /* HAVE_PF_PACKET_SOCKETS */
5555 /* ===== Functions to interface to the older kernels ================== */
5558 * Try to open a packet socket using the old kernel interface.
5559 * Returns 1 on success and a PCAP_ERROR_ value on an error.
5562 activate_old(pcap_t
*handle
)
5564 struct pcap_linux
*handlep
= handle
->priv
;
5567 const char *device
= handle
->opt
.source
;
5568 struct utsname utsname
;
5571 /* Open the socket */
5573 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
5574 if (handle
->fd
== -1) {
5575 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5576 "socket: %s", pcap_strerror(errno
));
5577 if (errno
== EPERM
|| errno
== EACCES
) {
5579 * You don't have permission to open the
5582 return PCAP_ERROR_PERM_DENIED
;
5591 /* It worked - we are using the old interface */
5592 handlep
->sock_packet
= 1;
5594 /* ...which means we get the link-layer header. */
5595 handlep
->cooked
= 0;
5597 /* Bind to the given device */
5599 if (strcmp(device
, "any") == 0) {
5600 strlcpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
5604 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
5608 * Try to get the link-layer type.
5610 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
5615 * Try to find the DLT_ type corresponding to that
5618 map_arphrd_to_dlt(handle
, arptype
, device
, 0);
5619 if (handle
->linktype
== -1) {
5620 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5621 "unknown arptype %d", arptype
);
5625 /* Go to promisc mode if requested */
5627 if (handle
->opt
.promisc
) {
5628 memset(&ifr
, 0, sizeof(ifr
));
5629 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5630 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
5631 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5632 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
5635 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
5637 * Promiscuous mode isn't currently on,
5638 * so turn it on, and remember that
5639 * we should turn it off when the
5644 * If we haven't already done so, arrange
5645 * to have "pcap_close_all()" called when
5648 if (!pcap_do_addexit(handle
)) {
5650 * "atexit()" failed; don't put
5651 * the interface in promiscuous
5652 * mode, just give up.
5657 ifr
.ifr_flags
|= IFF_PROMISC
;
5658 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
5659 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5661 pcap_strerror(errno
));
5664 handlep
->must_do_on_close
|= MUST_CLEAR_PROMISC
;
5667 * Add this to the list of pcaps
5668 * to close when we exit.
5670 pcap_add_to_pcaps_to_close(handle
);
5675 * Compute the buffer size.
5677 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5678 * kernel, and might require special handling - check.
5680 if (uname(&utsname
) < 0 ||
5681 strncmp(utsname
.release
, "2.0", 3) == 0) {
5683 * Either we couldn't find out what kernel release
5684 * this is, or it's a 2.0[.x] kernel.
5686 * In the 2.0[.x] kernel, a "recvfrom()" on
5687 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5688 * return the number of bytes read, so if we pass
5689 * a length based on the snapshot length, it'll
5690 * return the number of bytes from the packet
5691 * copied to userland, not the actual length
5694 * This means that, for example, the IP dissector
5695 * in tcpdump will get handed a packet length less
5696 * than the length in the IP header, and will
5697 * complain about "truncated-ip".
5699 * So we don't bother trying to copy from the
5700 * kernel only the bytes in which we're interested,
5701 * but instead copy them all, just as the older
5702 * versions of libpcap for Linux did.
5704 * The buffer therefore needs to be big enough to
5705 * hold the largest packet we can get from this
5706 * device. Unfortunately, we can't get the MRU
5707 * of the network; we can only get the MTU. The
5708 * MTU may be too small, in which case a packet larger
5709 * than the buffer size will be truncated *and* we
5710 * won't get the actual packet size.
5712 * However, if the snapshot length is larger than
5713 * the buffer size based on the MTU, we use the
5714 * snapshot length as the buffer size, instead;
5715 * this means that with a sufficiently large snapshot
5716 * length we won't artificially truncate packets
5717 * to the MTU-based size.
5719 * This mess just one of many problems with packet
5720 * capture on 2.0[.x] kernels; you really want a
5721 * 2.2[.x] or later kernel if you want packet capture
5724 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
5727 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
5728 if (handle
->bufsize
< handle
->snapshot
)
5729 handle
->bufsize
= handle
->snapshot
;
5732 * This is a 2.2[.x] or later kernel.
5734 * We can safely pass "recvfrom()" a byte count
5735 * based on the snapshot length.
5737 handle
->bufsize
= handle
->snapshot
;
5741 * Default value for offset to align link-layer payload
5742 * on a 4-byte boundary.
5747 * SOCK_PACKET sockets don't supply information from
5748 * stripped VLAN tags.
5750 handlep
->vlan_offset
= -1; /* unknown */
5756 * Bind the socket associated with FD to the given device using the
5757 * interface of the old kernels.
5760 iface_bind_old(int fd
, const char *device
, char *ebuf
)
5762 struct sockaddr saddr
;
5764 socklen_t errlen
= sizeof(err
);
5766 memset(&saddr
, 0, sizeof(saddr
));
5767 strlcpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
5768 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
5769 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5770 "bind: %s", pcap_strerror(errno
));
5774 /* Any pending errors, e.g., network is down? */
5776 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5777 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5778 "getsockopt: %s", pcap_strerror(errno
));
5783 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5784 "bind: %s", pcap_strerror(err
));
5792 /* ===== System calls available on all supported kernels ============== */
5795 * Query the kernel for the MTU of the given interface.
5798 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5803 return BIGGER_THAN_ALL_MTUS
;
5805 memset(&ifr
, 0, sizeof(ifr
));
5806 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5808 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5809 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5810 "SIOCGIFMTU: %s", pcap_strerror(errno
));
5818 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5821 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5825 memset(&ifr
, 0, sizeof(ifr
));
5826 strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5828 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5829 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5830 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
5831 if (errno
== ENODEV
) {
5835 return PCAP_ERROR_NO_SUCH_DEVICE
;
5840 return ifr
.ifr_hwaddr
.sa_family
;
5843 #ifdef SO_ATTACH_FILTER
5845 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
5847 struct pcap_linux
*handlep
= handle
->priv
;
5850 register struct bpf_insn
*p
;
5855 * Make a copy of the filter, and modify that copy if
5858 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5859 len
= handle
->fcode
.bf_len
;
5860 f
= (struct bpf_insn
*)malloc(prog_size
);
5862 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5863 "malloc: %s", pcap_strerror(errno
));
5866 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5868 fcode
->filter
= (struct sock_filter
*) f
;
5870 for (i
= 0; i
< len
; ++i
) {
5873 * What type of instruction is this?
5875 switch (BPF_CLASS(p
->code
)) {
5879 * It's a return instruction; are we capturing
5880 * in memory-mapped mode?
5884 * No; is the snapshot length a constant,
5885 * rather than the contents of the
5888 if (BPF_MODE(p
->code
) == BPF_K
) {
5890 * Yes - if the value to be returned,
5891 * i.e. the snapshot length, is
5892 * anything other than 0, make it
5893 * 65535, so that the packet is
5894 * truncated by "recvfrom()",
5895 * not by the filter.
5897 * XXX - there's nothing we can
5898 * easily do if it's getting the
5899 * value from the accumulator; we'd
5900 * have to insert code to force
5901 * non-zero values to be 65535.
5912 * It's a load instruction; is it loading
5915 switch (BPF_MODE(p
->code
)) {
5921 * Yes; are we in cooked mode?
5923 if (handlep
->cooked
) {
5925 * Yes, so we need to fix this
5928 if (fix_offset(p
) < 0) {
5930 * We failed to do so.
5931 * Return 0, so our caller
5932 * knows to punt to userland.
5942 return 1; /* we succeeded */
5946 fix_offset(struct bpf_insn
*p
)
5949 * What's the offset?
5951 if (p
->k
>= SLL_HDR_LEN
) {
5953 * It's within the link-layer payload; that starts at an
5954 * offset of 0, as far as the kernel packet filter is
5955 * concerned, so subtract the length of the link-layer
5958 p
->k
-= SLL_HDR_LEN
;
5959 } else if (p
->k
== 0) {
5961 * It's the packet type field; map it to the special magic
5962 * kernel offset for that field.
5964 p
->k
= SKF_AD_OFF
+ SKF_AD_PKTTYPE
;
5965 } else if (p
->k
== 14) {
5967 * It's the protocol field; map it to the special magic
5968 * kernel offset for that field.
5970 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5971 } else if ((bpf_int32
)(p
->k
) > 0) {
5973 * It's within the header, but it's not one of those
5974 * fields; we can't do that in the kernel, so punt
5983 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5985 int total_filter_on
= 0;
5991 * The socket filter code doesn't discard all packets queued
5992 * up on the socket when the filter is changed; this means
5993 * that packets that don't match the new filter may show up
5994 * after the new filter is put onto the socket, if those
5995 * packets haven't yet been read.
5997 * This means, for example, that if you do a tcpdump capture
5998 * with a filter, the first few packets in the capture might
5999 * be packets that wouldn't have passed the filter.
6001 * We therefore discard all packets queued up on the socket
6002 * when setting a kernel filter. (This isn't an issue for
6003 * userland filters, as the userland filtering is done after
6004 * packets are queued up.)
6006 * To flush those packets, we put the socket in read-only mode,
6007 * and read packets from the socket until there are no more to
6010 * In order to keep that from being an infinite loop - i.e.,
6011 * to keep more packets from arriving while we're draining
6012 * the queue - we put the "total filter", which is a filter
6013 * that rejects all packets, onto the socket before draining
6016 * This code deliberately ignores any errors, so that you may
6017 * get bogus packets if an error occurs, rather than having
6018 * the filtering done in userland even if it could have been
6019 * done in the kernel.
6021 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6022 &total_fcode
, sizeof(total_fcode
)) == 0) {
6026 * Note that we've put the total filter onto the socket.
6028 total_filter_on
= 1;
6031 * Save the socket's current mode, and put it in
6032 * non-blocking mode; we drain it by reading packets
6033 * until we get an error (which is normally a
6034 * "nothing more to be read" error).
6036 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
6037 if (save_mode
!= -1 &&
6038 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
6039 while (recv(handle
->fd
, &drain
, sizeof drain
,
6043 fcntl(handle
->fd
, F_SETFL
, save_mode
);
6044 if (save_errno
!= EAGAIN
) {
6046 reset_kernel_filter(handle
);
6047 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
6048 "recv: %s", pcap_strerror(save_errno
));
6055 * Now attach the new filter.
6057 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
6058 fcode
, sizeof(*fcode
));
6059 if (ret
== -1 && total_filter_on
) {
6061 * Well, we couldn't set that filter on the socket,
6062 * but we could set the total filter on the socket.
6064 * This could, for example, mean that the filter was
6065 * too big to put into the kernel, so we'll have to
6066 * filter in userland; in any case, we'll be doing
6067 * filtering in userland, so we need to remove the
6068 * total filter so we see packets.
6073 * XXX - if this fails, we're really screwed;
6074 * we have the total filter on the socket,
6075 * and it won't come off. What do we do then?
6077 reset_kernel_filter(handle
);
6085 reset_kernel_filter(pcap_t
*handle
)
6088 * setsockopt() barfs unless it get a dummy parameter.
6089 * valgrind whines unless the value is initialized,
6090 * as it has no idea that setsockopt() ignores its
6095 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
6096 &dummy
, sizeof(dummy
));