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>
30 * based on previous works of:
31 * Simon Patarin <patarin@cs.unibo.it>
32 * Phil Wood <cpw@lanl.gov>
34 * Monitor-mode support for mac80211 includes code taken from the iw
35 * command; the copyright notice for that code is
37 * Copyright (c) 2007, 2008 Johannes Berg
38 * Copyright (c) 2007 Andy Lutomirski
39 * Copyright (c) 2007 Mike Kershaw
40 * Copyright (c) 2008 Gábor Stefanik
42 * All rights reserved.
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. The name of the author may not be used to endorse or promote products
53 * derived from this software without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
56 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
57 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
58 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
59 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
60 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
61 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
62 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
63 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 static const char rcsid
[] _U_
=
70 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.164 2008-12-14 22:00:57 guy Exp $ (LBL)";
74 * Known problems with 2.0[.x] kernels:
76 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
77 * if we use PF_PACKET, we can filter out the transmitted version
78 * of the packet by using data in the "sockaddr_ll" returned by
79 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
80 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
81 * "sockaddr_pkt" which doesn't give us enough information to let
84 * - We have to set the interface's IFF_PROMISC flag ourselves, if
85 * we're to run in promiscuous mode, which means we have to turn
86 * it off ourselves when we're done; the kernel doesn't keep track
87 * of how many sockets are listening promiscuously, which means
88 * it won't get turned off automatically when no sockets are
89 * listening promiscuously. We catch "pcap_close()" and, for
90 * interfaces we put into promiscuous mode, take them out of
91 * promiscuous mode - which isn't necessarily the right thing to
92 * do, if another socket also requested promiscuous mode between
93 * the time when we opened the socket and the time when we close
96 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
97 * return the amount of data that you could have read, rather than
98 * the amount that was returned, so we can't just allocate a buffer
99 * whose size is the snapshot length and pass the snapshot length
100 * as the byte count, and also pass MSG_TRUNC, so that the return
101 * value tells us how long the packet was on the wire.
103 * This means that, if we want to get the actual size of the packet,
104 * so we can return it in the "len" field of the packet header,
105 * we have to read the entire packet, not just the part that fits
106 * within the snapshot length, and thus waste CPU time copying data
107 * from the kernel that our caller won't see.
109 * We have to get the actual size, and supply it in "len", because
110 * otherwise, the IP dissector in tcpdump, for example, will complain
111 * about "truncated-ip", as the packet will appear to have been
112 * shorter, on the wire, than the IP header said it should have been.
130 #include <sys/socket.h>
131 #include <sys/ioctl.h>
132 #include <sys/utsname.h>
133 #include <sys/mman.h>
134 #include <linux/if.h>
135 #include <netinet/in.h>
136 #include <linux/if_ether.h>
137 #include <net/if_arp.h>
141 #ifdef HAVE_LINUX_NET_TSTAMP_H
142 #include <linux/net_tstamp.h>
143 #include <linux/sockios.h>
147 * Got Wireless Extensions?
149 #ifdef HAVE_LINUX_WIRELESS_H
150 #include <linux/wireless.h>
151 #endif /* HAVE_LINUX_WIRELESS_H */
157 #include <linux/nl80211.h>
159 #include <netlink/genl/genl.h>
160 #include <netlink/genl/family.h>
161 #include <netlink/genl/ctrl.h>
162 #include <netlink/msg.h>
163 #include <netlink/attr.h>
164 #endif /* HAVE_LIBNL */
167 * Got ethtool support?
169 #ifdef HAVE_LINUX_ETHTOOL_H
170 #include <linux/ethtool.h>
171 #include <linux/sockios.h>
172 #endif /* HAVE_LINUX_ETHTOOL_H */
174 #include "pcap-int.h"
175 #include "pcap/sll.h"
176 #include "pcap/vlan.h"
179 #include "pcap-dag.h"
180 #endif /* HAVE_DAG_API */
182 #ifdef HAVE_SEPTEL_API
183 #include "pcap-septel.h"
184 #endif /* HAVE_SEPTEL_API */
187 #include "pcap-snf.h"
188 #endif /* HAVE_SNF_API */
190 #ifdef PCAP_SUPPORT_USB
191 #include "pcap-usb-linux.h"
194 #ifdef PCAP_SUPPORT_BT
195 #include "pcap-bt-linux.h"
198 #ifdef PCAP_SUPPORT_CAN
199 #include "pcap-can-linux.h"
202 #ifdef PCAP_SUPPORT_NETFILTER
203 int netfilter_platform_finddevs(pcap_if_t
**alldevsp
, char *err_str
);
204 pcap_t
*nflog_create(const char *device
, char *ebuf
);
208 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
209 * sockets rather than SOCK_PACKET sockets.
211 * To use them, we include <linux/if_packet.h> rather than
212 * <netpacket/packet.h>; we do so because
214 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
215 * later kernels and libc5, and don't provide a <netpacket/packet.h>
218 * not all versions of glibc2 have a <netpacket/packet.h> file
219 * that defines stuff needed for some of the 2.4-or-later-kernel
220 * features, so if the system has a 2.4 or later kernel, we
221 * still can't use those features.
223 * We're already including a number of other <linux/XXX.h> headers, and
224 * this code is Linux-specific (no other OS has PF_PACKET sockets as
225 * a raw packet capture mechanism), so it's not as if you gain any
226 * useful portability by using <netpacket/packet.h>
228 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
229 * isn't defined? It only defines one data structure in 2.0.x, so
230 * it shouldn't cause any problems.
233 # include <linux/if_packet.h>
236 * On at least some Linux distributions (for example, Red Hat 5.2),
237 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
238 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
239 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
240 * the PACKET_xxx stuff.
242 * So we check whether PACKET_HOST is defined, and assume that we have
243 * PF_PACKET sockets only if it is defined.
246 # define HAVE_PF_PACKET_SOCKETS
247 # ifdef PACKET_AUXDATA
248 # define HAVE_PACKET_AUXDATA
249 # endif /* PACKET_AUXDATA */
250 # endif /* PACKET_HOST */
253 /* check for memory mapped access avaibility. We assume every needed
254 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
255 * uses many ring related structs and macros */
256 # ifdef TPACKET_HDRLEN
257 # define HAVE_PACKET_RING
258 # ifdef TPACKET2_HDRLEN
259 # define HAVE_TPACKET2
261 # define TPACKET_V1 0
262 # endif /* TPACKET2_HDRLEN */
263 # endif /* TPACKET_HDRLEN */
264 #endif /* PF_PACKET */
266 #ifdef SO_ATTACH_FILTER
267 #include <linux/types.h>
268 #include <linux/filter.h>
271 #ifndef HAVE_SOCKLEN_T
272 typedef int socklen_t
;
277 * This is being compiled on a system that lacks MSG_TRUNC; define it
278 * with the value it has in the 2.2 and later kernels, so that, on
279 * those kernels, when we pass it in the flags argument to "recvfrom()"
280 * we're passing the right value and thus get the MSG_TRUNC behavior
281 * we want. (We don't get that behavior on 2.0[.x] kernels, because
282 * they didn't support MSG_TRUNC.)
284 #define MSG_TRUNC 0x20
289 * This is being compiled on a system that lacks SOL_PACKET; define it
290 * with the value it has in the 2.2 and later kernels, so that we can
291 * set promiscuous mode in the good modern way rather than the old
292 * 2.0-kernel crappy way.
294 #define SOL_PACKET 263
297 #define MAX_LINKHEADER_SIZE 256
300 * When capturing on all interfaces we use this as the buffer size.
301 * Should be bigger then all MTUs that occur in real life.
302 * 64kB should be enough for now.
304 #define BIGGER_THAN_ALL_MTUS (64*1024)
307 * Prototypes for internal functions and methods.
309 static void map_arphrd_to_dlt(pcap_t
*, int, int);
310 #ifdef HAVE_PF_PACKET_SOCKETS
311 static short int map_packet_type_to_sll_type(short int);
313 static int pcap_activate_linux(pcap_t
*);
314 static int activate_old(pcap_t
*);
315 static int activate_new(pcap_t
*);
316 static int activate_mmap(pcap_t
*, int *);
317 static int pcap_can_set_rfmon_linux(pcap_t
*);
318 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
319 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
320 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
321 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
322 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
323 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
324 static void pcap_cleanup_linux(pcap_t
*);
327 struct tpacket_hdr
*h1
;
328 struct tpacket2_hdr
*h2
;
332 #ifdef HAVE_PACKET_RING
333 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
335 static void destroy_ring(pcap_t
*handle
);
336 static int create_ring(pcap_t
*handle
, int *status
);
337 static int prepare_tpacket_socket(pcap_t
*handle
);
338 static void pcap_cleanup_linux_mmap(pcap_t
*);
339 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
340 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
341 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
342 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
343 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
344 const u_char
*bytes
);
348 * Wrap some ioctl calls
350 #ifdef HAVE_PF_PACKET_SOCKETS
351 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
352 #endif /* HAVE_PF_PACKET_SOCKETS */
353 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
354 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
355 #ifdef HAVE_PF_PACKET_SOCKETS
356 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
357 #ifdef IW_MODE_MONITOR
358 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
359 #endif /* IW_MODE_MONITOR */
360 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
362 #endif /* HAVE_PF_PACKET_SOCKETS */
363 static int iface_get_offload(pcap_t
*handle
);
364 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
366 #ifdef SO_ATTACH_FILTER
367 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
369 static int fix_offset(struct bpf_insn
*p
);
370 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
371 static int reset_kernel_filter(pcap_t
*handle
);
373 static struct sock_filter total_insn
374 = BPF_STMT(BPF_RET
| BPF_K
, 0);
375 static struct sock_fprog total_fcode
376 = { 1, &total_insn
};
377 #endif /* SO_ATTACH_FILTER */
380 pcap_create(const char *device
, char *ebuf
)
385 * A null device name is equivalent to the "any" device.
391 if (strstr(device
, "dag")) {
392 return dag_create(device
, ebuf
);
394 #endif /* HAVE_DAG_API */
396 #ifdef HAVE_SEPTEL_API
397 if (strstr(device
, "septel")) {
398 return septel_create(device
, ebuf
);
400 #endif /* HAVE_SEPTEL_API */
403 handle
= snf_create(device
, ebuf
);
404 if (strstr(device
, "snf") || handle
!= NULL
)
407 #endif /* HAVE_SNF_API */
409 #ifdef PCAP_SUPPORT_BT
410 if (strstr(device
, "bluetooth")) {
411 return bt_create(device
, ebuf
);
415 #ifdef PCAP_SUPPORT_CAN
416 if (strstr(device
, "can") || strstr(device
, "vcan")) {
417 return can_create(device
, ebuf
);
421 #ifdef PCAP_SUPPORT_USB
422 if (strstr(device
, "usbmon")) {
423 return usb_create(device
, ebuf
);
427 #ifdef PCAP_SUPPORT_NETFILTER
428 if (strncmp(device
, "nflog", strlen("nflog")) == 0) {
429 return nflog_create(device
, ebuf
);
433 handle
= pcap_create_common(device
, ebuf
);
437 handle
->activate_op
= pcap_activate_linux
;
438 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
439 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
441 * We claim that we support:
443 * software time stamps, with no details about their precision;
444 * hardware time stamps, synced to the host time;
445 * hardware time stamps, not synced to the host time.
447 * XXX - we can't ask a device whether it supports
448 * hardware time stamps, so we just claim all devices do.
450 handle
->tstamp_type_count
= 3;
451 handle
->tstamp_type_list
= malloc(3 * sizeof(u_int
));
452 if (handle
->tstamp_type_list
== NULL
) {
456 handle
->tstamp_type_list
[0] = PCAP_TSTAMP_HOST
;
457 handle
->tstamp_type_list
[1] = PCAP_TSTAMP_ADAPTER
;
458 handle
->tstamp_type_list
[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED
;
466 * If interface {if} is a mac80211 driver, the file
467 * /sys/class/net/{if}/phy80211 is a symlink to
468 * /sys/class/ieee80211/{phydev}, for some {phydev}.
470 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
471 * least, has a "wmaster0" device and a "wlan0" device; the
472 * latter is the one with the IP address. Both show up in
473 * "tcpdump -D" output. Capturing on the wmaster0 device
474 * captures with 802.11 headers.
476 * airmon-ng searches through /sys/class/net for devices named
477 * monN, starting with mon0; as soon as one *doesn't* exist,
478 * it chooses that as the monitor device name. If the "iw"
479 * command exists, it does "iw dev {if} interface add {monif}
480 * type monitor", where {monif} is the monitor device. It
481 * then (sigh) sleeps .1 second, and then configures the
482 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
483 * is a file, it writes {mondev}, without a newline, to that file,
484 * and again (sigh) sleeps .1 second, and then iwconfig's that
485 * device into monitor mode and configures it up. Otherwise,
486 * you can't do monitor mode.
488 * All these devices are "glued" together by having the
489 * /sys/class/net/{device}/phy80211 links pointing to the same
490 * place, so, given a wmaster, wlan, or mon device, you can
491 * find the other devices by looking for devices with
492 * the same phy80211 link.
494 * To turn monitor mode off, delete the monitor interface,
495 * either with "iw dev {monif} interface del" or by sending
496 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
498 * Note: if you try to create a monitor device named "monN", and
499 * there's already a "monN" device, it fails, as least with
500 * the netlink interface (which is what iw uses), with a return
501 * value of -ENFILE. (Return values are negative errnos.) We
502 * could probably use that to find an unused device.
504 * Yes, you can have multiple monitor devices for a given
509 * Is this a mac80211 device? If so, fill in the physical device path and
510 * return 1; if not, return 0. On an error, fill in handle->errbuf and
514 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
515 size_t phydev_max_pathlen
)
521 * Generate the path string for the symlink to the physical device.
523 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
524 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
525 "%s: Can't generate path name string for /sys/class/net device",
529 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
530 if (bytes_read
== -1) {
531 if (errno
== ENOENT
|| errno
== EINVAL
) {
533 * Doesn't exist, or not a symlink; assume that
534 * means it's not a mac80211 device.
539 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
540 "%s: Can't readlink %s: %s", device
, pathstr
,
546 phydev_path
[bytes_read
] = '\0';
550 #ifdef HAVE_LIBNL_2_x
551 #define get_nl_errmsg nl_geterror
553 /* libnl 2.x compatibility code */
555 #define nl_sock nl_handle
557 static inline struct nl_handle
*
558 nl_socket_alloc(void)
560 return nl_handle_alloc();
564 nl_socket_free(struct nl_handle
*h
)
566 nl_handle_destroy(h
);
569 #define get_nl_errmsg strerror
572 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
574 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
580 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
581 #endif /* !HAVE_LIBNL_2_x */
583 struct nl80211_state
{
584 struct nl_sock
*nl_sock
;
585 struct nl_cache
*nl_cache
;
586 struct genl_family
*nl80211
;
590 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
594 state
->nl_sock
= nl_socket_alloc();
595 if (!state
->nl_sock
) {
596 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
597 "%s: failed to allocate netlink handle", device
);
601 if (genl_connect(state
->nl_sock
)) {
602 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
603 "%s: failed to connect to generic netlink", device
);
604 goto out_handle_destroy
;
607 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
609 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
610 "%s: failed to allocate generic netlink cache: %s",
611 device
, get_nl_errmsg(-err
));
612 goto out_handle_destroy
;
615 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
616 if (!state
->nl80211
) {
617 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
618 "%s: nl80211 not found", device
);
625 nl_cache_free(state
->nl_cache
);
627 nl_socket_free(state
->nl_sock
);
632 nl80211_cleanup(struct nl80211_state
*state
)
634 genl_family_put(state
->nl80211
);
635 nl_cache_free(state
->nl_cache
);
636 nl_socket_free(state
->nl_sock
);
640 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
641 const char *device
, const char *mondevice
)
647 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
653 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
654 "%s: failed to allocate netlink msg", device
);
658 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
659 0, NL80211_CMD_NEW_INTERFACE
, 0);
660 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
661 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
662 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
664 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
666 #ifdef HAVE_LIBNL_2_x
667 if (err
== -NLE_FAILURE
) {
669 if (err
== -ENFILE
) {
672 * Device not available; our caller should just
673 * keep trying. (libnl 2.x maps ENFILE to
674 * NLE_FAILURE; it can also map other errors
675 * to that, but there's not much we can do
682 * Real failure, not just "that device is not
685 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
686 "%s: nl_send_auto_complete failed adding %s interface: %s",
687 device
, mondevice
, get_nl_errmsg(-err
));
692 err
= nl_wait_for_ack(state
->nl_sock
);
694 #ifdef HAVE_LIBNL_2_x
695 if (err
== -NLE_FAILURE
) {
697 if (err
== -ENFILE
) {
700 * Device not available; our caller should just
701 * keep trying. (libnl 2.x maps ENFILE to
702 * NLE_FAILURE; it can also map other errors
703 * to that, but there's not much we can do
710 * Real failure, not just "that device is not
713 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
714 "%s: nl_wait_for_ack failed adding %s interface: %s",
715 device
, mondevice
, get_nl_errmsg(-err
));
728 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
729 "%s: nl_put failed adding %s interface",
736 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
737 const char *device
, const char *mondevice
)
743 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
749 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
750 "%s: failed to allocate netlink msg", device
);
754 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
755 0, NL80211_CMD_DEL_INTERFACE
, 0);
756 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
758 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
760 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
761 "%s: nl_send_auto_complete failed deleting %s interface: %s",
762 device
, mondevice
, get_nl_errmsg(-err
));
766 err
= nl_wait_for_ack(state
->nl_sock
);
768 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
769 "%s: nl_wait_for_ack failed adding %s interface: %s",
770 device
, mondevice
, get_nl_errmsg(-err
));
782 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
783 "%s: nl_put failed deleting %s interface",
790 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
793 char phydev_path
[PATH_MAX
+1];
794 struct nl80211_state nlstate
;
799 * Is this a mac80211 device?
801 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
803 return ret
; /* error */
805 return 0; /* no error, but not mac80211 device */
808 * XXX - is this already a monN device?
810 * Is that determined by old Wireless Extensions ioctls?
814 * OK, it's apparently a mac80211 device.
815 * Try to find an unused monN device for it.
817 ret
= nl80211_init(handle
, &nlstate
, device
);
820 for (n
= 0; n
< UINT_MAX
; n
++) {
824 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
826 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
827 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
829 handle
->md
.mondevice
= strdup(mondevice
);
834 * Hard failure. Just return ret; handle->errbuf
835 * has already been set.
837 nl80211_cleanup(&nlstate
);
842 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
843 "%s: No free monN interfaces", device
);
844 nl80211_cleanup(&nlstate
);
851 * Sleep for .1 seconds.
854 delay
.tv_nsec
= 500000000;
855 nanosleep(&delay
, NULL
);
859 * Now configure the monitor interface up.
861 memset(&ifr
, 0, sizeof(ifr
));
862 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
863 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
864 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
865 "%s: Can't get flags for %s: %s", device
,
866 handle
->md
.mondevice
, strerror(errno
));
867 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
868 handle
->md
.mondevice
);
869 nl80211_cleanup(&nlstate
);
872 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
873 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
874 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
875 "%s: Can't set flags for %s: %s", device
,
876 handle
->md
.mondevice
, strerror(errno
));
877 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
878 handle
->md
.mondevice
);
879 nl80211_cleanup(&nlstate
);
884 * Success. Clean up the libnl state.
886 nl80211_cleanup(&nlstate
);
889 * Note that we have to delete the monitor device when we close
892 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
895 * Add this to the list of pcaps to close when we exit.
897 pcap_add_to_pcaps_to_close(handle
);
901 #endif /* HAVE_LIBNL */
904 pcap_can_set_rfmon_linux(pcap_t
*handle
)
907 char phydev_path
[PATH_MAX
+1];
910 #ifdef IW_MODE_MONITOR
915 if (strcmp(handle
->opt
.source
, "any") == 0) {
917 * Monitor mode makes no sense on the "any" device.
924 * Bleah. There doesn't seem to be a way to ask a mac80211
925 * device, through libnl, whether it supports monitor mode;
926 * we'll just check whether the device appears to be a
927 * mac80211 device and, if so, assume the device supports
930 * wmaster devices don't appear to support the Wireless
931 * Extensions, but we can create a mon device for a
932 * wmaster device, so we don't bother checking whether
933 * a mac80211 device supports the Wireless Extensions.
935 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
938 return ret
; /* error */
940 return 1; /* mac80211 device */
943 #ifdef IW_MODE_MONITOR
945 * Bleah. There doesn't appear to be an ioctl to use to ask
946 * whether a device supports monitor mode; we'll just do
947 * SIOCGIWMODE and, if it succeeds, assume the device supports
950 * Open a socket on which to attempt to get the mode.
951 * (We assume that if we have Wireless Extensions support
952 * we also have PF_PACKET support.)
954 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
956 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
957 "socket: %s", pcap_strerror(errno
));
962 * Attempt to get the current mode.
964 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
965 sizeof ireq
.ifr_ifrn
.ifrn_name
);
966 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
967 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
969 * Well, we got the mode; assume we can set it.
974 if (errno
== ENODEV
) {
975 /* The device doesn't even exist. */
976 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
977 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
979 return PCAP_ERROR_NO_SUCH_DEVICE
;
987 * Grabs the number of dropped packets by the interface from /proc/net/dev.
989 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
990 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
992 * Or can we get them in binary form from netlink?
995 linux_if_drops(const char * if_name
)
1000 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
1001 long int dropped_pkts
= 0;
1003 file
= fopen("/proc/net/dev", "r");
1007 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
1009 /* search for 'bytes' -- if its in there, then
1010 that means we need to grab the fourth field. otherwise
1011 grab the third field. */
1012 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1014 field_to_convert
= 4;
1018 /* find iface and make sure it actually matches -- space before the name and : after it */
1019 if ((bufptr
= strstr(buffer
, if_name
)) &&
1020 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1021 *(bufptr
+ if_name_sz
) == ':')
1023 bufptr
= bufptr
+ if_name_sz
+ 1;
1025 /* grab the nth field from it */
1026 while( --field_to_convert
&& *bufptr
!= '\0')
1028 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1029 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1032 /* get rid of any final spaces */
1033 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1035 if (*bufptr
!= '\0')
1036 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1043 return dropped_pkts
;
1048 * With older kernels promiscuous mode is kind of interesting because we
1049 * have to reset the interface before exiting. The problem can't really
1050 * be solved without some daemon taking care of managing usage counts.
1051 * If we put the interface into promiscuous mode, we set a flag indicating
1052 * that we must take it out of that mode when the interface is closed,
1053 * and, when closing the interface, if that flag is set we take it out
1054 * of promiscuous mode.
1056 * Even with newer kernels, we have the same issue with rfmon mode.
1059 static void pcap_cleanup_linux( pcap_t
*handle
)
1063 struct nl80211_state nlstate
;
1065 #endif /* HAVE_LIBNL */
1066 #ifdef IW_MODE_MONITOR
1068 #endif /* IW_MODE_MONITOR */
1070 if (handle
->md
.must_do_on_close
!= 0) {
1072 * There's something we have to do when closing this
1075 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
1077 * We put the interface into promiscuous mode;
1078 * take it out of promiscuous mode.
1080 * XXX - if somebody else wants it in promiscuous
1081 * mode, this code cannot know that, so it'll take
1082 * it out of promiscuous mode. That's not fixable
1083 * in 2.0[.x] kernels.
1085 memset(&ifr
, 0, sizeof(ifr
));
1086 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1087 sizeof(ifr
.ifr_name
));
1088 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1090 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1091 "Please adjust manually.\n"
1092 "Hint: This can't happen with Linux >= 2.2.0.\n",
1095 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1097 * Promiscuous mode is currently on;
1100 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1101 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1104 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1105 "Please adjust manually.\n"
1106 "Hint: This can't happen with Linux >= 2.2.0.\n",
1114 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1115 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1117 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1118 handle
->md
.device
, handle
->md
.mondevice
);
1119 nl80211_cleanup(&nlstate
);
1123 "Can't delete monitor interface %s (%s).\n"
1124 "Please delete manually.\n",
1125 handle
->md
.mondevice
, handle
->errbuf
);
1128 #endif /* HAVE_LIBNL */
1130 #ifdef IW_MODE_MONITOR
1131 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1133 * We put the interface into rfmon mode;
1134 * take it out of rfmon mode.
1136 * XXX - if somebody else wants it in rfmon
1137 * mode, this code cannot know that, so it'll take
1138 * it out of rfmon mode.
1140 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1141 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1142 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1144 ireq
.u
.mode
= handle
->md
.oldmode
;
1145 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1147 * Scientist, you've failed.
1150 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1151 "Please adjust manually.\n",
1155 #endif /* IW_MODE_MONITOR */
1158 * Take this pcap out of the list of pcaps for which we
1159 * have to take the interface out of some mode.
1161 pcap_remove_from_pcaps_to_close(handle
);
1164 if (handle
->md
.mondevice
!= NULL
) {
1165 free(handle
->md
.mondevice
);
1166 handle
->md
.mondevice
= NULL
;
1168 if (handle
->md
.device
!= NULL
) {
1169 free(handle
->md
.device
);
1170 handle
->md
.device
= NULL
;
1172 pcap_cleanup_live_common(handle
);
1176 * Get a handle for a live capture from the given device. You can
1177 * pass NULL as device to get all packages (without link level
1178 * information of course). If you pass 1 as promisc the interface
1179 * will be set to promiscous mode (XXX: I think this usage should
1180 * be deprecated and functions be added to select that later allow
1181 * modification of that values -- Torsten).
1184 pcap_activate_linux(pcap_t
*handle
)
1189 device
= handle
->opt
.source
;
1191 handle
->inject_op
= pcap_inject_linux
;
1192 handle
->setfilter_op
= pcap_setfilter_linux
;
1193 handle
->setdirection_op
= pcap_setdirection_linux
;
1194 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1195 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1196 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1197 handle
->cleanup_op
= pcap_cleanup_linux
;
1198 handle
->read_op
= pcap_read_linux
;
1199 handle
->stats_op
= pcap_stats_linux
;
1202 * The "any" device is a special device which causes us not
1203 * to bind to a particular device and thus to look at all
1206 if (strcmp(device
, "any") == 0) {
1207 if (handle
->opt
.promisc
) {
1208 handle
->opt
.promisc
= 0;
1209 /* Just a warning. */
1210 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1211 "Promiscuous mode not supported on the \"any\" device");
1212 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1216 handle
->md
.device
= strdup(device
);
1217 if (handle
->md
.device
== NULL
) {
1218 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1219 pcap_strerror(errno
) );
1224 * If we're in promiscuous mode, then we probably want
1225 * to see when the interface drops packets too, so get an
1226 * initial count from /proc/net/dev
1228 if (handle
->opt
.promisc
)
1229 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1232 * Current Linux kernels use the protocol family PF_PACKET to
1233 * allow direct access to all packets on the network while
1234 * older kernels had a special socket type SOCK_PACKET to
1235 * implement this feature.
1236 * While this old implementation is kind of obsolete we need
1237 * to be compatible with older kernels for a while so we are
1238 * trying both methods with the newer method preferred.
1240 status
= activate_new(handle
);
1243 * Fatal error with the new way; just fail.
1244 * status has the error return; if it's PCAP_ERROR,
1245 * handle->errbuf has been set appropriately.
1252 * Try to use memory-mapped access.
1254 switch (activate_mmap(handle
, &status
)) {
1258 * We succeeded. status has been
1259 * set to the status to return,
1260 * which might be 0, or might be
1261 * a PCAP_WARNING_ value.
1267 * Kernel doesn't support it - just continue
1268 * with non-memory-mapped access.
1274 * We failed to set up to use it, or the kernel
1275 * supports it, but we failed to enable it.
1276 * status has been set to the error status to
1277 * return and, if it's PCAP_ERROR, handle->errbuf
1278 * contains the error message.
1283 else if (status
== 0) {
1284 /* Non-fatal error; try old way */
1285 if ((status
= activate_old(handle
)) != 1) {
1287 * Both methods to open the packet socket failed.
1288 * Tidy up and report our failure (handle->errbuf
1289 * is expected to be set by the functions above).
1296 * We set up the socket, but not with memory-mapped access.
1299 if (handle
->opt
.buffer_size
!= 0) {
1301 * Set the socket buffer size to the specified value.
1303 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1304 &handle
->opt
.buffer_size
,
1305 sizeof(handle
->opt
.buffer_size
)) == -1) {
1306 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1307 "SO_RCVBUF: %s", pcap_strerror(errno
));
1308 status
= PCAP_ERROR
;
1313 /* Allocate the buffer */
1315 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1316 if (!handle
->buffer
) {
1317 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1318 "malloc: %s", pcap_strerror(errno
));
1319 status
= PCAP_ERROR
;
1324 * "handle->fd" is a socket, so "select()" and "poll()"
1325 * should work on it.
1327 handle
->selectable_fd
= handle
->fd
;
1332 pcap_cleanup_linux(handle
);
1337 * Read at most max_packets from the capture stream and call the callback
1338 * for each of them. Returns the number of packets handled or -1 if an
1342 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1345 * Currently, on Linux only one packet is delivered per read,
1348 return pcap_read_packet(handle
, callback
, user
);
1352 * Read a packet from the socket calling the handler provided by
1353 * the user. Returns the number of packets received or -1 if an
1357 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1361 #ifdef HAVE_PF_PACKET_SOCKETS
1362 struct sockaddr_ll from
;
1363 struct sll_header
*hdrp
;
1365 struct sockaddr from
;
1367 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1370 struct cmsghdr
*cmsg
;
1372 struct cmsghdr cmsg
;
1373 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1375 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1377 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1378 int packet_len
, caplen
;
1379 struct pcap_pkthdr pcap_header
;
1381 #ifdef HAVE_PF_PACKET_SOCKETS
1383 * If this is a cooked device, leave extra room for a
1384 * fake packet header.
1386 if (handle
->md
.cooked
)
1387 offset
= SLL_HDR_LEN
;
1392 * This system doesn't have PF_PACKET sockets, so it doesn't
1393 * support cooked devices.
1399 * Receive a single packet from the kernel.
1400 * We ignore EINTR, as that might just be due to a signal
1401 * being delivered - if the signal should interrupt the
1402 * loop, the signal handler should call pcap_breakloop()
1403 * to set handle->break_loop (we ignore it on other
1404 * platforms as well).
1405 * We also ignore ENETDOWN, so that we can continue to
1406 * capture traffic if the interface goes down and comes
1407 * back up again; comments in the kernel indicate that
1408 * we'll just block waiting for packets if we try to
1409 * receive from a socket that delivered ENETDOWN, and,
1410 * if we're using a memory-mapped buffer, we won't even
1411 * get notified of "network down" events.
1413 bp
= handle
->buffer
+ handle
->offset
;
1415 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1416 msg
.msg_name
= &from
;
1417 msg
.msg_namelen
= sizeof(from
);
1420 msg
.msg_control
= &cmsg_buf
;
1421 msg
.msg_controllen
= sizeof(cmsg_buf
);
1424 iov
.iov_len
= handle
->bufsize
- offset
;
1425 iov
.iov_base
= bp
+ offset
;
1426 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1430 * Has "pcap_breakloop()" been called?
1432 if (handle
->break_loop
) {
1434 * Yes - clear the flag that indicates that it has,
1435 * and return PCAP_ERROR_BREAK as an indication that
1436 * we were told to break out of the loop.
1438 handle
->break_loop
= 0;
1439 return PCAP_ERROR_BREAK
;
1442 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1443 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1444 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1445 fromlen
= sizeof(from
);
1446 packet_len
= recvfrom(
1447 handle
->fd
, bp
+ offset
,
1448 handle
->bufsize
- offset
, MSG_TRUNC
,
1449 (struct sockaddr
*) &from
, &fromlen
);
1450 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1451 } while (packet_len
== -1 && errno
== EINTR
);
1453 /* Check if an error occured */
1455 if (packet_len
== -1) {
1459 return 0; /* no packet there */
1463 * The device on which we're capturing went away.
1465 * XXX - we should really return
1466 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1467 * etc. aren't defined to return that.
1469 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1470 "The interface went down");
1474 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1475 "recvfrom: %s", pcap_strerror(errno
));
1480 #ifdef HAVE_PF_PACKET_SOCKETS
1481 if (!handle
->md
.sock_packet
) {
1483 * Unfortunately, there is a window between socket() and
1484 * bind() where the kernel may queue packets from any
1485 * interface. If we're bound to a particular interface,
1486 * discard packets not from that interface.
1488 * (If socket filters are supported, we could do the
1489 * same thing we do when changing the filter; however,
1490 * that won't handle packet sockets without socket
1491 * filter support, and it's a bit more complicated.
1492 * It would save some instructions per packet, however.)
1494 if (handle
->md
.ifindex
!= -1 &&
1495 from
.sll_ifindex
!= handle
->md
.ifindex
)
1499 * Do checks based on packet direction.
1500 * We can only do this if we're using PF_PACKET; the
1501 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1502 * which lacks the relevant packet type information.
1504 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1507 * If this is from the loopback device, reject it;
1508 * we'll see the packet as an incoming packet as well,
1509 * and we don't want to see it twice.
1511 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1515 * If the user only wants incoming packets, reject it.
1517 if (handle
->direction
== PCAP_D_IN
)
1522 * If the user only wants outgoing packets, reject it.
1524 if (handle
->direction
== PCAP_D_OUT
)
1530 #ifdef HAVE_PF_PACKET_SOCKETS
1532 * If this is a cooked device, fill in the fake packet header.
1534 if (handle
->md
.cooked
) {
1536 * Add the length of the fake header to the length
1537 * of packet data we read.
1539 packet_len
+= SLL_HDR_LEN
;
1541 hdrp
= (struct sll_header
*)bp
;
1542 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1543 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1544 hdrp
->sll_halen
= htons(from
.sll_halen
);
1545 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1546 (from
.sll_halen
> SLL_ADDRLEN
) ?
1549 hdrp
->sll_protocol
= from
.sll_protocol
;
1552 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1553 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1554 struct tpacket_auxdata
*aux
;
1556 struct vlan_tag
*tag
;
1558 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1559 cmsg
->cmsg_level
!= SOL_PACKET
||
1560 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1563 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1564 if (aux
->tp_vlan_tci
== 0)
1567 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1568 if (len
< 2 * ETH_ALEN
)
1572 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1574 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1575 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1576 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1578 packet_len
+= VLAN_TAG_LEN
;
1580 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1581 #endif /* HAVE_PF_PACKET_SOCKETS */
1584 * XXX: According to the kernel source we should get the real
1585 * packet len if calling recvfrom with MSG_TRUNC set. It does
1586 * not seem to work here :(, but it is supported by this code
1588 * To be honest the code RELIES on that feature so this is really
1589 * broken with 2.2.x kernels.
1590 * I spend a day to figure out what's going on and I found out
1591 * that the following is happening:
1593 * The packet comes from a random interface and the packet_rcv
1594 * hook is called with a clone of the packet. That code inserts
1595 * the packet into the receive queue of the packet socket.
1596 * If a filter is attached to that socket that filter is run
1597 * first - and there lies the problem. The default filter always
1598 * cuts the packet at the snaplen:
1603 * So the packet filter cuts down the packet. The recvfrom call
1604 * says "hey, it's only 68 bytes, it fits into the buffer" with
1605 * the result that we don't get the real packet length. This
1606 * is valid at least until kernel 2.2.17pre6.
1608 * We currently handle this by making a copy of the filter
1609 * program, fixing all "ret" instructions with non-zero
1610 * operands to have an operand of 65535 so that the filter
1611 * doesn't truncate the packet, and supplying that modified
1612 * filter to the kernel.
1615 caplen
= packet_len
;
1616 if (caplen
> handle
->snapshot
)
1617 caplen
= handle
->snapshot
;
1619 /* Run the packet filter if not using kernel filter */
1620 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1621 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1622 packet_len
, caplen
) == 0)
1624 /* rejected by filter */
1629 /* Fill in our own header data */
1631 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1632 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1633 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1636 pcap_header
.caplen
= caplen
;
1637 pcap_header
.len
= packet_len
;
1642 * Arguably, we should count them before we check the filter,
1643 * as on many other platforms "ps_recv" counts packets
1644 * handed to the filter rather than packets that passed
1645 * the filter, but if filtering is done in the kernel, we
1646 * can't get a count of packets that passed the filter,
1647 * and that would mean the meaning of "ps_recv" wouldn't
1648 * be the same on all Linux systems.
1650 * XXX - it's not the same on all systems in any case;
1651 * ideally, we should have a "get the statistics" call
1652 * that supplies more counts and indicates which of them
1653 * it supplies, so that we supply a count of packets
1654 * handed to the filter only on platforms where that
1655 * information is available.
1657 * We count them here even if we can get the packet count
1658 * from the kernel, as we can only determine at run time
1659 * whether we'll be able to get it from the kernel (if
1660 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1661 * the kernel, but if it is defined, the library might
1662 * have been built with a 2.4 or later kernel, but we
1663 * might be running on a 2.2[.x] kernel without Alexey
1664 * Kuznetzov's turbopacket patches, and thus the kernel
1665 * might not be able to supply those statistics). We
1666 * could, I guess, try, when opening the socket, to get
1667 * the statistics, and if we can not increment the count
1668 * here, but it's not clear that always incrementing
1669 * the count is more expensive than always testing a flag
1672 * We keep the count in "md.packets_read", and use that for
1673 * "ps_recv" if we can't get the statistics from the kernel.
1674 * We do that because, if we *can* get the statistics from
1675 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1676 * as running counts, as reading the statistics from the
1677 * kernel resets the kernel statistics, and if we directly
1678 * increment "md.stat.ps_recv" here, that means it will
1679 * count packets *twice* on systems where we can get kernel
1680 * statistics - once here, and once in pcap_stats_linux().
1682 handle
->md
.packets_read
++;
1684 /* Call the user supplied callback function */
1685 callback(userdata
, &pcap_header
, bp
);
1691 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1695 #ifdef HAVE_PF_PACKET_SOCKETS
1696 if (!handle
->md
.sock_packet
) {
1697 /* PF_PACKET socket */
1698 if (handle
->md
.ifindex
== -1) {
1700 * We don't support sending on the "any" device.
1702 strlcpy(handle
->errbuf
,
1703 "Sending packets isn't supported on the \"any\" device",
1708 if (handle
->md
.cooked
) {
1710 * We don't support sending on the "any" device.
1712 * XXX - how do you send on a bound cooked-mode
1714 * Is a "sendto()" required there?
1716 strlcpy(handle
->errbuf
,
1717 "Sending packets isn't supported in cooked mode",
1724 ret
= send(handle
->fd
, buf
, size
, 0);
1726 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1727 pcap_strerror(errno
));
1734 * Get the statistics for the given packet capture handle.
1735 * Reports the number of dropped packets iff the kernel supports
1736 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1737 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1738 * patches); otherwise, that information isn't available, and we lie
1739 * and report 0 as the count of dropped packets.
1742 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1744 #ifdef HAVE_TPACKET_STATS
1745 struct tpacket_stats kstats
;
1746 socklen_t len
= sizeof (struct tpacket_stats
);
1749 long if_dropped
= 0;
1752 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1754 if (handle
->opt
.promisc
)
1756 if_dropped
= handle
->md
.proc_dropped
;
1757 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1758 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1761 #ifdef HAVE_TPACKET_STATS
1763 * Try to get the packet counts from the kernel.
1765 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1766 &kstats
, &len
) > -1) {
1768 * On systems where the PACKET_STATISTICS "getsockopt()"
1769 * argument is supported on PF_PACKET sockets:
1771 * "ps_recv" counts only packets that *passed* the
1772 * filter, not packets that didn't pass the filter.
1773 * This includes packets later dropped because we
1774 * ran out of buffer space.
1776 * "ps_drop" counts packets dropped because we ran
1777 * out of buffer space. It doesn't count packets
1778 * dropped by the interface driver. It counts only
1779 * packets that passed the filter.
1781 * See above for ps_ifdrop.
1783 * Both statistics include packets not yet read from
1784 * the kernel by libpcap, and thus not yet seen by
1787 * In "linux/net/packet/af_packet.c", at least in the
1788 * 2.4.9 kernel, "tp_packets" is incremented for every
1789 * packet that passes the packet filter *and* is
1790 * successfully queued on the socket; "tp_drops" is
1791 * incremented for every packet dropped because there's
1792 * not enough free space in the socket buffer.
1794 * When the statistics are returned for a PACKET_STATISTICS
1795 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1796 * so that "tp_packets" counts all packets handed to
1797 * the PF_PACKET socket, including packets dropped because
1798 * there wasn't room on the socket buffer - but not
1799 * including packets that didn't pass the filter.
1801 * In the BSD BPF, the count of received packets is
1802 * incremented for every packet handed to BPF, regardless
1803 * of whether it passed the filter.
1805 * We can't make "pcap_stats()" work the same on both
1806 * platforms, but the best approximation is to return
1807 * "tp_packets" as the count of packets and "tp_drops"
1808 * as the count of drops.
1810 * Keep a running total because each call to
1811 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1812 * resets the counters to zero.
1814 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1815 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1816 *stats
= handle
->md
.stat
;
1822 * If the error was EOPNOTSUPP, fall through, so that
1823 * if you build the library on a system with
1824 * "struct tpacket_stats" and run it on a system
1825 * that doesn't, it works as it does if the library
1826 * is built on a system without "struct tpacket_stats".
1828 if (errno
!= EOPNOTSUPP
) {
1829 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1830 "pcap_stats: %s", pcap_strerror(errno
));
1836 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1837 * is not supported on PF_PACKET sockets:
1839 * "ps_recv" counts only packets that *passed* the filter,
1840 * not packets that didn't pass the filter. It does not
1841 * count packets dropped because we ran out of buffer
1844 * "ps_drop" is not supported.
1846 * "ps_ifdrop" is supported. It will return the number
1847 * of drops the interface reports in /proc/net/dev,
1848 * if that is available.
1850 * "ps_recv" doesn't include packets not yet read from
1851 * the kernel by libpcap.
1853 * We maintain the count of packets processed by libpcap in
1854 * "md.packets_read", for reasons described in the comment
1855 * at the end of pcap_read_packet(). We have no idea how many
1856 * packets were dropped by the kernel buffers -- but we know
1857 * how many the interface dropped, so we can return that.
1860 stats
->ps_recv
= handle
->md
.packets_read
;
1862 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1867 * Get from "/sys/class/net" all interfaces listed there; if they're
1868 * already in the list of interfaces we have, that won't add another
1869 * instance, but if they're not, that'll add them.
1871 * We don't bother getting any addresses for them; it appears you can't
1872 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1873 * although some other types of addresses can be fetched with SIOCGIFADDR,
1874 * we don't bother with them for now.
1876 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1877 * the list of interfaces as is, and return 0, so that we can try
1878 * scanning /proc/net/dev.
1881 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1883 DIR *sys_class_net_d
;
1887 char name
[512]; /* XXX - pick a size */
1889 struct ifreq ifrflags
;
1892 sys_class_net_d
= opendir("/sys/class/net");
1893 if (sys_class_net_d
== NULL
&& errno
== ENOENT
)
1897 * Create a socket from which to fetch interface information.
1899 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1901 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1902 "socket: %s", pcap_strerror(errno
));
1903 (void)closedir(sys_class_net_d
);
1909 ent
= readdir(sys_class_net_d
);
1912 * Error or EOF; if errno != 0, it's an error.
1918 * Ignore directories (".", "..", and any subdirectories).
1920 if (ent
->d_type
== DT_DIR
)
1924 * Get the interface name.
1926 p
= &ent
->d_name
[0];
1928 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1931 * This could be the separator between a
1932 * name and an alias number, or it could be
1933 * the separator between a name with no
1934 * alias number and the next field.
1936 * If there's a colon after digits, it
1937 * separates the name and the alias number,
1938 * otherwise it separates the name and the
1942 while (isascii(*p
) && isdigit(*p
))
1946 * That was the next field,
1947 * not the alias number.
1958 * Get the flags for this interface, and skip it if
1961 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
1962 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
1963 if (errno
== ENXIO
|| errno
== ENODEV
)
1965 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1966 "SIOCGIFFLAGS: %.*s: %s",
1967 (int)sizeof(ifrflags
.ifr_name
),
1969 pcap_strerror(errno
));
1973 if (!(ifrflags
.ifr_flags
& IFF_UP
))
1977 * Add an entry for this interface, with no addresses.
1979 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
1990 * Well, we didn't fail for any other reason; did we
1991 * fail due to an error reading the directory?
1994 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1995 "Error reading /sys/class/net: %s",
1996 pcap_strerror(errno
));
2002 (void)closedir(sys_class_net_d
);
2007 * Get from "/proc/net/dev" all interfaces listed there; if they're
2008 * already in the list of interfaces we have, that won't add another
2009 * instance, but if they're not, that'll add them.
2011 * See comments from scan_sys_class_net().
2014 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2021 char name
[512]; /* XXX - pick a size */
2023 struct ifreq ifrflags
;
2026 proc_net_f
= fopen("/proc/net/dev", "r");
2027 if (proc_net_f
== NULL
&& errno
== ENOENT
)
2031 * Create a socket from which to fetch interface information.
2033 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2035 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2036 "socket: %s", pcap_strerror(errno
));
2037 (void)fclose(proc_net_f
);
2042 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2044 * Skip the first two lines - they're headers.
2052 * Skip leading white space.
2054 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2056 if (*p
== '\0' || *p
== '\n')
2057 continue; /* blank line */
2060 * Get the interface name.
2063 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2066 * This could be the separator between a
2067 * name and an alias number, or it could be
2068 * the separator between a name with no
2069 * alias number and the next field.
2071 * If there's a colon after digits, it
2072 * separates the name and the alias number,
2073 * otherwise it separates the name and the
2077 while (isascii(*p
) && isdigit(*p
))
2081 * That was the next field,
2082 * not the alias number.
2093 * Get the flags for this interface, and skip it if
2096 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2097 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2100 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2101 "SIOCGIFFLAGS: %.*s: %s",
2102 (int)sizeof(ifrflags
.ifr_name
),
2104 pcap_strerror(errno
));
2108 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2112 * Add an entry for this interface, with no addresses.
2114 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2125 * Well, we didn't fail for any other reason; did we
2126 * fail due to an error reading the file?
2128 if (ferror(proc_net_f
)) {
2129 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2130 "Error reading /proc/net/dev: %s",
2131 pcap_strerror(errno
));
2137 (void)fclose(proc_net_f
);
2142 * Description string for the "any" device.
2144 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2147 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2152 * Read "/sys/class/net", and add to the list of interfaces all
2153 * interfaces listed there that we don't already have, because,
2154 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2155 * and even getifaddrs() won't return information about
2156 * interfaces with no addresses, so you need to read "/sys/class/net"
2157 * to get the names of the rest of the interfaces.
2159 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2161 return (-1); /* failed */
2164 * No /sys/class/net; try reading /proc/net/dev instead.
2166 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2171 * Add the "any" device.
2173 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2180 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2182 #endif /* HAVE_DAG_API */
2184 #ifdef HAVE_SEPTEL_API
2186 * Add Septel devices.
2188 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2190 #endif /* HAVE_SEPTEL_API */
2193 if (snf_platform_finddevs(alldevsp
, errbuf
) < 0)
2195 #endif /* HAVE_SNF_API */
2197 #ifdef PCAP_SUPPORT_BT
2199 * Add Bluetooth devices.
2201 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2205 #ifdef PCAP_SUPPORT_USB
2209 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2213 #ifdef PCAP_SUPPORT_NETFILTER
2215 * Add netfilter devices.
2217 if (netfilter_platform_finddevs(alldevsp
, errbuf
) < 0)
2225 * Attach the given BPF code to the packet capture device.
2228 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2231 #ifdef SO_ATTACH_FILTER
2232 struct sock_fprog fcode
;
2233 int can_filter_in_kernel
;
2240 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2245 /* Make our private copy of the filter */
2247 if (install_bpf_program(handle
, filter
) < 0)
2248 /* install_bpf_program() filled in errbuf */
2252 * Run user level packet filter by default. Will be overriden if
2253 * installing a kernel filter succeeds.
2255 handle
->md
.use_bpf
= 0;
2257 /* Install kernel level filter if possible */
2259 #ifdef SO_ATTACH_FILTER
2261 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2263 * fcode.len is an unsigned short for current kernel.
2264 * I have yet to see BPF-Code with that much
2265 * instructions but still it is possible. So for the
2266 * sake of correctness I added this check.
2268 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2270 fcode
.filter
= NULL
;
2271 can_filter_in_kernel
= 0;
2273 #endif /* USHRT_MAX */
2276 * Oh joy, the Linux kernel uses struct sock_fprog instead
2277 * of struct bpf_program and of course the length field is
2278 * of different size. Pointed out by Sebastian
2280 * Oh, and we also need to fix it up so that all "ret"
2281 * instructions with non-zero operands have 65535 as the
2282 * operand if we're not capturing in memory-mapped modee,
2283 * and so that, if we're in cooked mode, all memory-reference
2284 * instructions use special magic offsets in references to
2285 * the link-layer header and assume that the link-layer
2286 * payload begins at 0; "fix_program()" will do that.
2288 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2293 * Fatal error; just quit.
2294 * (The "default" case shouldn't happen; we
2295 * return -1 for that reason.)
2301 * The program performed checks that we can't make
2302 * work in the kernel.
2304 can_filter_in_kernel
= 0;
2309 * We have a filter that'll work in the kernel.
2311 can_filter_in_kernel
= 1;
2317 * NOTE: at this point, we've set both the "len" and "filter"
2318 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2319 * those are the only members of the "sock_fprog" structure,
2320 * so we initialize every member of that structure.
2322 * If there is anything in "fcode" that is not initialized,
2323 * it is either a field added in a later kernel, or it's
2326 * If a new field is added, this code needs to be updated
2327 * to set it correctly.
2329 * If there are no other fields, then:
2331 * if the Linux kernel looks at the padding, it's
2334 * if the Linux kernel doesn't look at the padding,
2335 * then if some tool complains that we're passing
2336 * uninitialized data to the kernel, then the tool
2337 * is buggy and needs to understand that it's just
2340 if (can_filter_in_kernel
) {
2341 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2343 /* Installation succeded - using kernel filter. */
2344 handle
->md
.use_bpf
= 1;
2346 else if (err
== -1) /* Non-fatal error */
2349 * Print a warning if we weren't able to install
2350 * the filter for a reason other than "this kernel
2351 * isn't configured to support socket filters.
2353 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2355 "Warning: Kernel filter failed: %s\n",
2356 pcap_strerror(errno
));
2362 * If we're not using the kernel filter, get rid of any kernel
2363 * filter that might've been there before, e.g. because the
2364 * previous filter could work in the kernel, or because some other
2365 * code attached a filter to the socket by some means other than
2366 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2367 * filter out packets that would pass the new userland filter.
2369 if (!handle
->md
.use_bpf
)
2370 reset_kernel_filter(handle
);
2373 * Free up the copy of the filter that was made by "fix_program()".
2375 if (fcode
.filter
!= NULL
)
2381 #endif /* SO_ATTACH_FILTER */
2387 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2389 return pcap_setfilter_linux_common(handle
, filter
, 0);
2394 * Set direction flag: Which packets do we accept on a forwarding
2395 * single device? IN, OUT or both?
2398 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2400 #ifdef HAVE_PF_PACKET_SOCKETS
2401 if (!handle
->md
.sock_packet
) {
2402 handle
->direction
= d
;
2407 * We're not using PF_PACKET sockets, so we can't determine
2408 * the direction of the packet.
2410 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2411 "Setting direction is not supported on SOCK_PACKET sockets");
2415 #ifdef HAVE_PF_PACKET_SOCKETS
2417 * Map the PACKET_ value to a LINUX_SLL_ value; we
2418 * want the same numerical value to be used in
2419 * the link-layer header even if the numerical values
2420 * for the PACKET_ #defines change, so that programs
2421 * that look at the packet type field will always be
2422 * able to handle DLT_LINUX_SLL captures.
2425 map_packet_type_to_sll_type(short int sll_pkttype
)
2427 switch (sll_pkttype
) {
2430 return htons(LINUX_SLL_HOST
);
2432 case PACKET_BROADCAST
:
2433 return htons(LINUX_SLL_BROADCAST
);
2435 case PACKET_MULTICAST
:
2436 return htons(LINUX_SLL_MULTICAST
);
2438 case PACKET_OTHERHOST
:
2439 return htons(LINUX_SLL_OTHERHOST
);
2441 case PACKET_OUTGOING
:
2442 return htons(LINUX_SLL_OUTGOING
);
2451 * Linux uses the ARP hardware type to identify the type of an
2452 * interface. pcap uses the DLT_xxx constants for this. This
2453 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2454 * constant, as arguments, and sets "handle->linktype" to the
2455 * appropriate DLT_XXX constant and sets "handle->offset" to
2456 * the appropriate value (to make "handle->offset" plus link-layer
2457 * header length be a multiple of 4, so that the link-layer payload
2458 * will be aligned on a 4-byte boundary when capturing packets).
2459 * (If the offset isn't set here, it'll be 0; add code as appropriate
2460 * for cases where it shouldn't be 0.)
2462 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2463 * in cooked mode; otherwise, we can't use cooked mode, so we have
2464 * to pick some type that works in raw mode, or fail.
2466 * Sets the link type to -1 if unable to map the type.
2468 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2474 * This is (presumably) a real Ethernet capture; give it a
2475 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2476 * that an application can let you choose it, in case you're
2477 * capturing DOCSIS traffic that a Cisco Cable Modem
2478 * Termination System is putting out onto an Ethernet (it
2479 * doesn't put an Ethernet header onto the wire, it puts raw
2480 * DOCSIS frames out on the wire inside the low-level
2481 * Ethernet framing).
2483 * XXX - are there any sorts of "fake Ethernet" that have
2484 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2485 * a Cisco CMTS won't put traffic onto it or get traffic
2486 * bridged onto it? ISDN is handled in "activate_new()",
2487 * as we fall back on cooked mode there; are there any
2490 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2492 * If that fails, just leave the list empty.
2494 if (handle
->dlt_list
!= NULL
) {
2495 handle
->dlt_list
[0] = DLT_EN10MB
;
2496 handle
->dlt_list
[1] = DLT_DOCSIS
;
2497 handle
->dlt_count
= 2;
2501 case ARPHRD_METRICOM
:
2502 case ARPHRD_LOOPBACK
:
2503 handle
->linktype
= DLT_EN10MB
;
2508 handle
->linktype
= DLT_EN3MB
;
2512 handle
->linktype
= DLT_AX25_KISS
;
2516 handle
->linktype
= DLT_PRONET
;
2520 handle
->linktype
= DLT_CHAOS
;
2523 #define ARPHRD_CAN 280
2526 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2529 #ifndef ARPHRD_IEEE802_TR
2530 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2532 case ARPHRD_IEEE802_TR
:
2533 case ARPHRD_IEEE802
:
2534 handle
->linktype
= DLT_IEEE802
;
2539 handle
->linktype
= DLT_ARCNET_LINUX
;
2542 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2543 #define ARPHRD_FDDI 774
2546 handle
->linktype
= DLT_FDDI
;
2550 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2551 #define ARPHRD_ATM 19
2555 * The Classical IP implementation in ATM for Linux
2556 * supports both what RFC 1483 calls "LLC Encapsulation",
2557 * in which each packet has an LLC header, possibly
2558 * with a SNAP header as well, prepended to it, and
2559 * what RFC 1483 calls "VC Based Multiplexing", in which
2560 * different virtual circuits carry different network
2561 * layer protocols, and no header is prepended to packets.
2563 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2564 * you can't use the ARPHRD_ type to find out whether
2565 * captured packets will have an LLC header, and,
2566 * while there's a socket ioctl to *set* the encapsulation
2567 * type, there's no ioctl to *get* the encapsulation type.
2571 * programs that dissect Linux Classical IP frames
2572 * would have to check for an LLC header and,
2573 * depending on whether they see one or not, dissect
2574 * the frame as LLC-encapsulated or as raw IP (I
2575 * don't know whether there's any traffic other than
2576 * IP that would show up on the socket, or whether
2577 * there's any support for IPv6 in the Linux
2578 * Classical IP code);
2580 * filter expressions would have to compile into
2581 * code that checks for an LLC header and does
2584 * Both of those are a nuisance - and, at least on systems
2585 * that support PF_PACKET sockets, we don't have to put
2586 * up with those nuisances; instead, we can just capture
2587 * in cooked mode. That's what we'll do, if we can.
2588 * Otherwise, we'll just fail.
2591 handle
->linktype
= DLT_LINUX_SLL
;
2593 handle
->linktype
= -1;
2596 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2597 #define ARPHRD_IEEE80211 801
2599 case ARPHRD_IEEE80211
:
2600 handle
->linktype
= DLT_IEEE802_11
;
2603 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2604 #define ARPHRD_IEEE80211_PRISM 802
2606 case ARPHRD_IEEE80211_PRISM
:
2607 handle
->linktype
= DLT_PRISM_HEADER
;
2610 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2611 #define ARPHRD_IEEE80211_RADIOTAP 803
2613 case ARPHRD_IEEE80211_RADIOTAP
:
2614 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2619 * Some PPP code in the kernel supplies no link-layer
2620 * header whatsoever to PF_PACKET sockets; other PPP
2621 * code supplies PPP link-layer headers ("syncppp.c");
2622 * some PPP code might supply random link-layer
2623 * headers (PPP over ISDN - there's code in Ethereal,
2624 * for example, to cope with PPP-over-ISDN captures
2625 * with which the Ethereal developers have had to cope,
2626 * heuristically trying to determine which of the
2627 * oddball link-layer headers particular packets have).
2629 * As such, we just punt, and run all PPP interfaces
2630 * in cooked mode, if we can; otherwise, we just treat
2631 * it as DLT_RAW, for now - if somebody needs to capture,
2632 * on a 2.0[.x] kernel, on PPP devices that supply a
2633 * link-layer header, they'll have to add code here to
2634 * map to the appropriate DLT_ type (possibly adding a
2635 * new DLT_ type, if necessary).
2638 handle
->linktype
= DLT_LINUX_SLL
;
2641 * XXX - handle ISDN types here? We can't fall
2642 * back on cooked sockets, so we'd have to
2643 * figure out from the device name what type of
2644 * link-layer encapsulation it's using, and map
2645 * that to an appropriate DLT_ value, meaning
2646 * we'd map "isdnN" devices to DLT_RAW (they
2647 * supply raw IP packets with no link-layer
2648 * header) and "isdY" devices to a new DLT_I4L_IP
2649 * type that has only an Ethernet packet type as
2650 * a link-layer header.
2652 * But sometimes we seem to get random crap
2653 * in the link-layer header when capturing on
2656 handle
->linktype
= DLT_RAW
;
2660 #ifndef ARPHRD_CISCO
2661 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2664 handle
->linktype
= DLT_C_HDLC
;
2667 /* Not sure if this is correct for all tunnels, but it
2671 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2679 #ifndef ARPHRD_RAWHDLC
2680 #define ARPHRD_RAWHDLC 518
2682 case ARPHRD_RAWHDLC
:
2684 #define ARPHRD_DLCI 15
2688 * XXX - should some of those be mapped to DLT_LINUX_SLL
2689 * instead? Should we just map all of them to DLT_LINUX_SLL?
2691 handle
->linktype
= DLT_RAW
;
2695 #define ARPHRD_FRAD 770
2698 handle
->linktype
= DLT_FRELAY
;
2701 case ARPHRD_LOCALTLK
:
2702 handle
->linktype
= DLT_LTALK
;
2706 #define ARPHRD_FCPP 784
2710 #define ARPHRD_FCAL 785
2714 #define ARPHRD_FCPL 786
2717 #ifndef ARPHRD_FCFABRIC
2718 #define ARPHRD_FCFABRIC 787
2720 case ARPHRD_FCFABRIC
:
2722 * We assume that those all mean RFC 2625 IP-over-
2723 * Fibre Channel, with the RFC 2625 header at
2724 * the beginning of the packet.
2726 handle
->linktype
= DLT_IP_OVER_FC
;
2730 #define ARPHRD_IRDA 783
2733 /* Don't expect IP packet out of this interfaces... */
2734 handle
->linktype
= DLT_LINUX_IRDA
;
2735 /* We need to save packet direction for IrDA decoding,
2736 * so let's use "Linux-cooked" mode. Jean II */
2737 //handle->md.cooked = 1;
2740 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2741 * is needed, please report it to <daniele@orlandi.com> */
2743 #define ARPHRD_LAPD 8445
2746 /* Don't expect IP packet out of this interfaces... */
2747 handle
->linktype
= DLT_LINUX_LAPD
;
2751 #define ARPHRD_NONE 0xFFFE
2755 * No link-layer header; packets are just IP
2756 * packets, so use DLT_RAW.
2758 handle
->linktype
= DLT_RAW
;
2761 #ifndef ARPHRD_IEEE802154
2762 #define ARPHRD_IEEE802154 804
2764 case ARPHRD_IEEE802154
:
2765 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2769 handle
->linktype
= -1;
2774 /* ===== Functions to interface to the newer kernels ================== */
2777 * Try to open a packet socket using the new kernel PF_PACKET interface.
2778 * Returns 1 on success, 0 on an error that means the new interface isn't
2779 * present (so the old SOCK_PACKET interface should be tried), and a
2780 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2781 * work either (so it shouldn't be tried).
2784 activate_new(pcap_t
*handle
)
2786 #ifdef HAVE_PF_PACKET_SOCKETS
2787 const char *device
= handle
->opt
.source
;
2788 int is_any_device
= (strcmp(device
, "any") == 0);
2789 int sock_fd
= -1, arptype
;
2790 #ifdef HAVE_PACKET_AUXDATA
2794 struct packet_mreq mr
;
2797 * Open a socket with protocol family packet. If the
2798 * "any" device was specified, we open a SOCK_DGRAM
2799 * socket for the cooked interface, otherwise we first
2800 * try a SOCK_RAW socket for the raw interface.
2802 sock_fd
= is_any_device
?
2803 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2804 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2806 if (sock_fd
== -1) {
2807 if (errno
== EINVAL
|| errno
== EAFNOSUPPORT
) {
2809 * We don't support PF_PACKET/SOCK_whatever
2810 * sockets; try the old mechanism.
2815 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2816 pcap_strerror(errno
) );
2817 if (errno
== EPERM
|| errno
== EACCES
) {
2819 * You don't have permission to open the
2822 return PCAP_ERROR_PERM_DENIED
;
2831 /* It seems the kernel supports the new interface. */
2832 handle
->md
.sock_packet
= 0;
2835 * Get the interface index of the loopback device.
2836 * If the attempt fails, don't fail, just set the
2837 * "md.lo_ifindex" to -1.
2839 * XXX - can there be more than one device that loops
2840 * packets back, i.e. devices other than "lo"? If so,
2841 * we'd need to find them all, and have an array of
2842 * indices for them, and check all of them in
2843 * "pcap_read_packet()".
2845 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2848 * Default value for offset to align link-layer payload
2849 * on a 4-byte boundary.
2854 * What kind of frames do we have to deal with? Fall back
2855 * to cooked mode if we have an unknown interface type
2856 * or a type we know doesn't work well in raw mode.
2858 if (!is_any_device
) {
2859 /* Assume for now we don't need cooked mode. */
2860 handle
->md
.cooked
= 0;
2862 if (handle
->opt
.rfmon
) {
2864 * We were asked to turn on monitor mode.
2865 * Do so before we get the link-layer type,
2866 * because entering monitor mode could change
2867 * the link-layer type.
2869 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2877 * Nothing worked for turning monitor mode
2881 return PCAP_ERROR_RFMON_NOTSUP
;
2885 * Either monitor mode has been turned on for
2886 * the device, or we've been given a different
2887 * device to open for monitor mode. If we've
2888 * been given a different device, use it.
2890 if (handle
->md
.mondevice
!= NULL
)
2891 device
= handle
->md
.mondevice
;
2893 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2898 map_arphrd_to_dlt(handle
, arptype
, 1);
2899 if (handle
->linktype
== -1 ||
2900 handle
->linktype
== DLT_LINUX_SLL
||
2901 handle
->linktype
== DLT_LINUX_IRDA
||
2902 handle
->linktype
== DLT_LINUX_LAPD
||
2903 (handle
->linktype
== DLT_EN10MB
&&
2904 (strncmp("isdn", device
, 4) == 0 ||
2905 strncmp("isdY", device
, 4) == 0))) {
2907 * Unknown interface type (-1), or a
2908 * device we explicitly chose to run
2909 * in cooked mode (e.g., PPP devices),
2910 * or an ISDN device (whose link-layer
2911 * type we can only determine by using
2912 * APIs that may be different on different
2913 * kernels) - reopen in cooked mode.
2915 if (close(sock_fd
) == -1) {
2916 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2917 "close: %s", pcap_strerror(errno
));
2920 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2922 if (sock_fd
== -1) {
2923 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2924 "socket: %s", pcap_strerror(errno
));
2925 if (errno
== EPERM
|| errno
== EACCES
) {
2927 * You don't have permission to
2930 return PCAP_ERROR_PERM_DENIED
;
2938 handle
->md
.cooked
= 1;
2941 * Get rid of any link-layer type list
2942 * we allocated - this only supports cooked
2945 if (handle
->dlt_list
!= NULL
) {
2946 free(handle
->dlt_list
);
2947 handle
->dlt_list
= NULL
;
2948 handle
->dlt_count
= 0;
2951 if (handle
->linktype
== -1) {
2953 * Warn that we're falling back on
2954 * cooked mode; we may want to
2955 * update "map_arphrd_to_dlt()"
2956 * to handle the new type.
2958 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2960 "supported by libpcap - "
2961 "falling back to cooked "
2967 * IrDA capture is not a real "cooked" capture,
2968 * it's IrLAP frames, not IP packets. The
2969 * same applies to LAPD capture.
2971 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2972 handle
->linktype
!= DLT_LINUX_LAPD
)
2973 handle
->linktype
= DLT_LINUX_SLL
;
2976 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2978 if (handle
->md
.ifindex
== -1) {
2983 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2984 handle
->errbuf
)) != 1) {
2989 return 0; /* try old mechanism */
2995 if (handle
->opt
.rfmon
) {
2997 * It doesn't support monitor mode.
2999 return PCAP_ERROR_RFMON_NOTSUP
;
3003 * It uses cooked mode.
3005 handle
->md
.cooked
= 1;
3006 handle
->linktype
= DLT_LINUX_SLL
;
3009 * We're not bound to a device.
3010 * For now, we're using this as an indication
3011 * that we can't transmit; stop doing that only
3012 * if we figure out how to transmit in cooked
3015 handle
->md
.ifindex
= -1;
3019 * Select promiscuous mode on if "promisc" is set.
3021 * Do not turn allmulti mode on if we don't select
3022 * promiscuous mode - on some devices (e.g., Orinoco
3023 * wireless interfaces), allmulti mode isn't supported
3024 * and the driver implements it by turning promiscuous
3025 * mode on, and that screws up the operation of the
3026 * card as a normal networking interface, and on no
3027 * other platform I know of does starting a non-
3028 * promiscuous capture affect which multicast packets
3029 * are received by the interface.
3033 * Hmm, how can we set promiscuous mode on all interfaces?
3034 * I am not sure if that is possible at all. For now, we
3035 * silently ignore attempts to turn promiscuous mode on
3036 * for the "any" device (so you don't have to explicitly
3037 * disable it in programs such as tcpdump).
3040 if (!is_any_device
&& handle
->opt
.promisc
) {
3041 memset(&mr
, 0, sizeof(mr
));
3042 mr
.mr_ifindex
= handle
->md
.ifindex
;
3043 mr
.mr_type
= PACKET_MR_PROMISC
;
3044 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
3045 &mr
, sizeof(mr
)) == -1) {
3046 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3047 "setsockopt: %s", pcap_strerror(errno
));
3053 /* Enable auxillary data if supported and reserve room for
3054 * reconstructing VLAN headers. */
3055 #ifdef HAVE_PACKET_AUXDATA
3057 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
3058 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
3059 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3060 "setsockopt: %s", pcap_strerror(errno
));
3064 handle
->offset
+= VLAN_TAG_LEN
;
3065 #endif /* HAVE_PACKET_AUXDATA */
3068 * This is a 2.2[.x] or later kernel (we know that
3069 * because we're not using a SOCK_PACKET socket -
3070 * PF_PACKET is supported only in 2.2 and later
3073 * We can safely pass "recvfrom()" a byte count
3074 * based on the snapshot length.
3076 * If we're in cooked mode, make the snapshot length
3077 * large enough to hold a "cooked mode" header plus
3078 * 1 byte of packet data (so we don't pass a byte
3079 * count of 0 to "recvfrom()").
3081 if (handle
->md
.cooked
) {
3082 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3083 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3085 handle
->bufsize
= handle
->snapshot
;
3087 /* Save the socket FD in the pcap structure */
3088 handle
->fd
= sock_fd
;
3093 "New packet capturing interface not supported by build "
3094 "environment", PCAP_ERRBUF_SIZE
);
3099 #ifdef HAVE_PACKET_RING
3101 * Attempt to activate with memory-mapped access.
3103 * On success, returns 1, and sets *status to 0 if there are no warnings
3104 * or to a PCAP_WARNING_ code if there is a warning.
3106 * On failure due to lack of support for memory-mapped capture, returns
3109 * On error, returns -1, and sets *status to the appropriate error code;
3110 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3113 activate_mmap(pcap_t
*handle
, int *status
)
3118 * Attempt to allocate a buffer to hold the contents of one
3119 * packet, for use by the oneshot callback.
3121 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
3122 if (handle
->md
.oneshot_buffer
== NULL
) {
3123 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3124 "can't allocate oneshot buffer: %s",
3125 pcap_strerror(errno
));
3126 *status
= PCAP_ERROR
;
3130 if (handle
->opt
.buffer_size
== 0) {
3131 /* by default request 2M for the ring buffer */
3132 handle
->opt
.buffer_size
= 2*1024*1024;
3134 ret
= prepare_tpacket_socket(handle
);
3136 free(handle
->md
.oneshot_buffer
);
3137 *status
= PCAP_ERROR
;
3140 ret
= create_ring(handle
, status
);
3143 * We don't support memory-mapped capture; our caller
3144 * will fall back on reading from the socket.
3146 free(handle
->md
.oneshot_buffer
);
3151 * Error attempting to enable memory-mapped capture;
3152 * fail. create_ring() has set *status.
3154 free(handle
->md
.oneshot_buffer
);
3159 * Success. *status has been set either to 0 if there are no
3160 * warnings or to a PCAP_WARNING_ value if there is a warning.
3162 * Override some defaults and inherit the other fields from
3164 * handle->offset is used to get the current position into the rx ring.
3165 * handle->cc is used to store the ring size.
3167 handle
->read_op
= pcap_read_linux_mmap
;
3168 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3169 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3170 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3171 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3172 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3173 handle
->selectable_fd
= handle
->fd
;
3176 #else /* HAVE_PACKET_RING */
3178 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3182 #endif /* HAVE_PACKET_RING */
3184 #ifdef HAVE_PACKET_RING
3186 * Attempt to set the socket to version 2 of the memory-mapped header.
3187 * Return 1 if we succeed or if we fail because version 2 isn't
3188 * supported; return -1 on any other error, and set handle->errbuf.
3191 prepare_tpacket_socket(pcap_t
*handle
)
3193 #ifdef HAVE_TPACKET2
3198 handle
->md
.tp_version
= TPACKET_V1
;
3199 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
3201 #ifdef HAVE_TPACKET2
3202 /* Probe whether kernel supports TPACKET_V2 */
3205 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3206 if (errno
== ENOPROTOOPT
)
3207 return 1; /* no - just drive on */
3209 /* Yes - treat as a failure. */
3210 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3211 "can't get TPACKET_V2 header len on packet socket: %s",
3212 pcap_strerror(errno
));
3215 handle
->md
.tp_hdrlen
= val
;
3218 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3220 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3221 "can't activate TPACKET_V2 on packet socket: %s",
3222 pcap_strerror(errno
));
3225 handle
->md
.tp_version
= TPACKET_V2
;
3227 /* Reserve space for VLAN tag reconstruction */
3229 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3231 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3232 "can't set up reserve on packet socket: %s",
3233 pcap_strerror(errno
));
3237 #endif /* HAVE_TPACKET2 */
3242 * Attempt to set up memory-mapped access.
3244 * On success, returns 1, and sets *status to 0 if there are no warnings
3245 * or to a PCAP_WARNING_ code if there is a warning.
3247 * On failure due to lack of support for memory-mapped capture, returns
3250 * On error, returns -1, and sets *status to the appropriate error code;
3251 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3254 create_ring(pcap_t
*handle
, int *status
)
3256 unsigned i
, j
, frames_per_block
;
3257 struct tpacket_req req
;
3259 unsigned int sk_type
, tp_reserve
, maclen
, tp_hdrlen
, netoff
, macoff
;
3260 unsigned int frame_size
;
3263 * Start out assuming no warnings or errors.
3267 /* Note that with large snapshot length (say 64K, which is the default
3268 * for recent versions of tcpdump, the value that "-s 0" has given
3269 * for a long time with tcpdump, and the default in Wireshark/TShark),
3270 * if we use the snapshot length to calculate the frame length,
3271 * only a few frames will be available in the ring even with pretty
3272 * large ring size (and a lot of memory will be unused).
3274 * Ideally, we should choose a frame length based on the
3275 * minimum of the specified snapshot length and the maximum
3276 * packet size. That's not as easy as it sounds; consider, for
3277 * example, an 802.11 interface in monitor mode, where the
3278 * frame would include a radiotap header, where the maximum
3279 * radiotap header length is device-dependent.
3281 * So, for now, we just do this for Ethernet devices, where
3282 * there's no metadata header, and the link-layer header is
3283 * fixed length. We can get the maximum packet size by
3284 * adding 18, the Ethernet header length plus the CRC length
3285 * (just in case we happen to get the CRC in the packet), to
3286 * the MTU of the interface; we fetch the MTU in the hopes
3287 * that it reflects support for jumbo frames. (Even if the
3288 * interface is just being used for passive snooping, the driver
3289 * might set the size of buffers in the receive ring based on
3290 * the MTU, so that the MTU limits the maximum size of packets
3291 * that we can receive.)
3293 * We don't do that if segmentation/fragmentation or receive
3294 * offload are enabled, so we don't get rudely surprised by
3295 * "packets" bigger than the MTU. */
3296 frame_size
= handle
->snapshot
;
3297 if (handle
->linktype
== DLT_EN10MB
) {
3301 offload
= iface_get_offload(handle
);
3302 if (offload
== -1) {
3303 *status
= PCAP_ERROR
;
3307 mtu
= iface_get_mtu(handle
->fd
, handle
->opt
.source
,
3310 *status
= PCAP_ERROR
;
3313 if (frame_size
> mtu
+ 18)
3314 frame_size
= mtu
+ 18;
3318 /* NOTE: calculus matching those in tpacket_rcv()
3319 * in linux-2.6/net/packet/af_packet.c
3321 len
= sizeof(sk_type
);
3322 if (getsockopt(handle
->fd
, SOL_SOCKET
, SO_TYPE
, &sk_type
, &len
) < 0) {
3323 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "getsockopt: %s", pcap_strerror(errno
));
3324 *status
= PCAP_ERROR
;
3327 #ifdef PACKET_RESERVE
3328 len
= sizeof(tp_reserve
);
3329 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &tp_reserve
, &len
) < 0) {
3330 if (errno
!= ENOPROTOOPT
) {
3332 * ENOPROTOOPT means "kernel doesn't support
3333 * PACKET_RESERVE", in which case we fall back
3336 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "getsockopt: %s", pcap_strerror(errno
));
3337 *status
= PCAP_ERROR
;
3340 tp_reserve
= 0; /* older kernel, reserve not supported */
3343 tp_reserve
= 0; /* older kernel, reserve not supported */
3345 maclen
= (sk_type
== SOCK_DGRAM
) ? 0 : MAX_LINKHEADER_SIZE
;
3346 /* XXX: in the kernel maclen is calculated from
3347 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3348 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3349 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3350 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3351 * but I see no way to get those sizes in userspace,
3352 * like for instance with an ifreq ioctl();
3353 * the best thing I've found so far is MAX_HEADER in the kernel
3354 * part of linux-2.6/include/linux/netdevice.h
3355 * which goes up to 128+48=176; since pcap-linux.c defines
3356 * a MAX_LINKHEADER_SIZE of 256 which is greater than that,
3357 * let's use it.. maybe is it even large enough to directly
3360 tp_hdrlen
= TPACKET_ALIGN(handle
->md
.tp_hdrlen
) + sizeof(struct sockaddr_ll
) ;
3361 netoff
= TPACKET_ALIGN(tp_hdrlen
+ (maclen
< 16 ? 16 : maclen
)) + tp_reserve
;
3362 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN of
3363 * netoff, which contradicts
3364 * linux-2.6/Documentation/networking/packet_mmap.txt
3366 * "- Gap, chosen so that packet data (Start+tp_net)
3367 * aligns to TPACKET_ALIGNMENT=16"
3369 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3370 * "CPUs often take a performance hit
3371 * when accessing unaligned memory locations"
3373 macoff
= netoff
- maclen
;
3374 req
.tp_frame_size
= TPACKET_ALIGN(macoff
+ frame_size
);
3375 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3377 /* compute the minumum block size that will handle this frame.
3378 * The block has to be page size aligned.
3379 * The max block size allowed by the kernel is arch-dependent and
3380 * it's not explicitly checked here. */
3381 req
.tp_block_size
= getpagesize();
3382 while (req
.tp_block_size
< req
.tp_frame_size
)
3383 req
.tp_block_size
<<= 1;
3385 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3388 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3389 * so we check for PACKET_TIMESTAMP. We check for
3390 * linux/net_tstamp.h just in case a system somehow has
3391 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3394 * SIOCSHWTSTAMP was introduced in the patch that introduced
3395 * linux/net_tstamp.h, so we don't bother checking whether
3396 * SIOCSHWTSTAMP is defined (if your Linux system has
3397 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3398 * Linux system is badly broken).
3400 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3402 * If we were told to do so, ask the kernel and the driver
3403 * to use hardware timestamps.
3405 * Hardware timestamps are only supported with mmapped
3408 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3409 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3410 struct hwtstamp_config hwconfig
;
3415 * Ask for hardware time stamps on all packets,
3416 * including transmitted packets.
3418 memset(&hwconfig
, 0, sizeof(hwconfig
));
3419 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3420 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3422 memset(&ifr
, 0, sizeof(ifr
));
3423 strcpy(ifr
.ifr_name
, handle
->opt
.source
);
3424 ifr
.ifr_data
= (void *)&hwconfig
;
3426 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3431 * Treat this as an error, as the
3432 * user should try to run this
3433 * with the appropriate privileges -
3434 * and, if they can't, shouldn't
3435 * try requesting hardware time stamps.
3437 *status
= PCAP_ERROR_PERM_DENIED
;
3442 * Treat this as a warning, as the
3443 * only way to fix the warning is to
3444 * get an adapter that supports hardware
3445 * time stamps. We'll just fall back
3446 * on the standard host time stamps.
3448 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3452 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3453 "SIOCSHWTSTAMP failed: %s",
3454 pcap_strerror(errno
));
3455 *status
= PCAP_ERROR
;
3460 * Well, that worked. Now specify the type of
3461 * hardware time stamp we want for this
3464 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3466 * Hardware timestamp, synchronized
3467 * with the system clock.
3469 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3472 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3473 * timestamp, not synchronized with the
3476 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3478 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3479 (void *)×ource
, sizeof(timesource
))) {
3480 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3481 "can't set PACKET_TIMESTAMP: %s",
3482 pcap_strerror(errno
));
3483 *status
= PCAP_ERROR
;
3488 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3490 /* ask the kernel to create the ring */
3492 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3494 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3495 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3497 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3498 (void *) &req
, sizeof(req
))) {
3499 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3501 * Memory failure; try to reduce the requested ring
3504 * We used to reduce this by half -- do 5% instead.
3505 * That may result in more iterations and a longer
3506 * startup, but the user will be much happier with
3507 * the resulting buffer size.
3509 if (req
.tp_frame_nr
< 20)
3510 req
.tp_frame_nr
-= 1;
3512 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3515 if (errno
== ENOPROTOOPT
) {
3517 * We don't have ring buffer support in this kernel.
3521 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3522 "can't create rx ring on packet socket: %s",
3523 pcap_strerror(errno
));
3524 *status
= PCAP_ERROR
;
3528 /* memory map the rx ring */
3529 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3530 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3531 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3532 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3533 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3534 "can't mmap rx ring: %s", pcap_strerror(errno
));
3536 /* clear the allocated ring on error*/
3537 destroy_ring(handle
);
3538 *status
= PCAP_ERROR
;
3542 /* allocate a ring for each frame header pointer*/
3543 handle
->cc
= req
.tp_frame_nr
;
3544 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3545 if (!handle
->buffer
) {
3546 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3547 "can't allocate ring of frame headers: %s",
3548 pcap_strerror(errno
));
3550 destroy_ring(handle
);
3551 *status
= PCAP_ERROR
;
3555 /* fill the header ring with proper frame ptr*/
3557 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3558 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3559 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3560 RING_GET_FRAME(handle
) = base
;
3561 base
+= req
.tp_frame_size
;
3565 handle
->bufsize
= req
.tp_frame_size
;
3570 /* free all ring related resources*/
3572 destroy_ring(pcap_t
*handle
)
3574 /* tell the kernel to destroy the ring*/
3575 struct tpacket_req req
;
3576 memset(&req
, 0, sizeof(req
));
3577 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3578 (void *) &req
, sizeof(req
));
3580 /* if ring is mapped, unmap it*/
3581 if (handle
->md
.mmapbuf
) {
3582 /* do not test for mmap failure, as we can't recover from any error */
3583 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3584 handle
->md
.mmapbuf
= NULL
;
3589 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3590 * for Linux mmapped capture.
3592 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3593 * data handed to the callback to be valid after the callback returns,
3594 * but pcap_read_linux_mmap() has to release that packet as soon as
3595 * the callback returns (otherwise, the kernel thinks there's still
3596 * at least one unprocessed packet available in the ring, so a select()
3597 * will immediately return indicating that there's data to process), so,
3598 * in the callback, we have to make a copy of the packet.
3600 * Yes, this means that, if the capture is using the ring buffer, using
3601 * pcap_next() or pcap_next_ex() requires more copies than using
3602 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3603 * pcap_next() or pcap_next_ex().
3606 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3607 const u_char
*bytes
)
3609 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3612 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3613 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3617 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3619 destroy_ring(handle
);
3620 if (handle
->md
.oneshot_buffer
!= NULL
) {
3621 free(handle
->md
.oneshot_buffer
);
3622 handle
->md
.oneshot_buffer
= NULL
;
3624 pcap_cleanup_linux(handle
);
3629 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3631 /* use negative value of timeout to indicate non blocking ops */
3632 return (p
->md
.timeout
<0);
3636 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3638 /* map each value to the corresponding 2's complement, to
3639 * preserve the timeout value provided with pcap_set_timeout */
3641 if (p
->md
.timeout
>= 0) {
3643 * Timeout is non-negative, so we're not already
3644 * in non-blocking mode; set it to the 2's
3645 * complement, to make it negative, as an
3646 * indication that we're in non-blocking mode.
3648 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3651 if (p
->md
.timeout
< 0) {
3653 * Timeout is negative, so we're not already
3654 * in blocking mode; reverse the previous
3655 * operation, to make the timeout non-negative
3658 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3664 static inline union thdr
*
3665 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3669 h
.raw
= RING_GET_FRAME(handle
);
3670 switch (handle
->md
.tp_version
) {
3672 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3676 #ifdef HAVE_TPACKET2
3678 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3692 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3699 /* wait for frames availability.*/
3700 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3701 struct pollfd pollinfo
;
3704 pollinfo
.fd
= handle
->fd
;
3705 pollinfo
.events
= POLLIN
;
3707 if (handle
->md
.timeout
== 0)
3708 timeout
= -1; /* block forever */
3709 else if (handle
->md
.timeout
> 0)
3710 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3712 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3714 ret
= poll(&pollinfo
, 1, timeout
);
3715 if (ret
< 0 && errno
!= EINTR
) {
3716 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3717 "can't poll on packet socket: %s",
3718 pcap_strerror(errno
));
3720 } else if (ret
> 0 &&
3721 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3723 * There's some indication other than
3724 * "you can read on this descriptor" on
3727 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3728 snprintf(handle
->errbuf
,
3730 "Hangup on packet socket");
3733 if (pollinfo
.revents
& POLLERR
) {
3735 * A recv() will give us the
3736 * actual error code.
3738 * XXX - make the socket non-blocking?
3740 if (recv(handle
->fd
, &c
, sizeof c
,
3742 continue; /* what, no error? */
3743 if (errno
== ENETDOWN
) {
3745 * The device on which we're
3746 * capturing went away.
3748 * XXX - we should really return
3749 * PCAP_ERROR_IFACE_NOT_UP,
3750 * but pcap_dispatch() etc.
3751 * aren't defined to return
3754 snprintf(handle
->errbuf
,
3756 "The interface went down");
3758 snprintf(handle
->errbuf
,
3760 "Error condition on packet socket: %s",
3765 if (pollinfo
.revents
& POLLNVAL
) {
3766 snprintf(handle
->errbuf
,
3768 "Invalid polling request on packet socket");
3772 /* check for break loop condition on interrupted syscall*/
3773 if (handle
->break_loop
) {
3774 handle
->break_loop
= 0;
3775 return PCAP_ERROR_BREAK
;
3780 /* non-positive values of max_packets are used to require all
3781 * packets currently available in the ring */
3782 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3784 struct sockaddr_ll
*sll
;
3785 struct pcap_pkthdr pcaphdr
;
3788 unsigned int tp_len
;
3789 unsigned int tp_mac
;
3790 unsigned int tp_snaplen
;
3791 unsigned int tp_sec
;
3792 unsigned int tp_usec
;
3794 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3798 switch (handle
->md
.tp_version
) {
3800 tp_len
= h
.h1
->tp_len
;
3801 tp_mac
= h
.h1
->tp_mac
;
3802 tp_snaplen
= h
.h1
->tp_snaplen
;
3803 tp_sec
= h
.h1
->tp_sec
;
3804 tp_usec
= h
.h1
->tp_usec
;
3806 #ifdef HAVE_TPACKET2
3808 tp_len
= h
.h2
->tp_len
;
3809 tp_mac
= h
.h2
->tp_mac
;
3810 tp_snaplen
= h
.h2
->tp_snaplen
;
3811 tp_sec
= h
.h2
->tp_sec
;
3812 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3816 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3817 "unsupported tpacket version %d",
3818 handle
->md
.tp_version
);
3821 /* perform sanity check on internal offset. */
3822 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3823 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3824 "corrupted frame on kernel ring mac "
3825 "offset %d + caplen %d > frame len %d",
3826 tp_mac
, tp_snaplen
, handle
->bufsize
);
3830 /* run filter on received packet
3831 * If the kernel filtering is enabled we need to run the
3832 * filter until all the frames present into the ring
3833 * at filter creation time are processed.
3834 * In such case md.use_bpf is used as a counter for the
3835 * packet we need to filter.
3836 * Note: alternatively it could be possible to stop applying
3837 * the filter when the ring became empty, but it can possibly
3838 * happen a lot later... */
3839 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3840 run_bpf
= (!handle
->md
.use_bpf
) ||
3841 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
3842 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3843 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
3844 tp_len
, tp_snaplen
) == 0))
3848 * Do checks based on packet direction.
3850 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
3851 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
3854 * If this is from the loopback device, reject it;
3855 * we'll see the packet as an incoming packet as well,
3856 * and we don't want to see it twice.
3858 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
3862 * If the user only wants incoming packets, reject it.
3864 if (handle
->direction
== PCAP_D_IN
)
3869 * If the user only wants outgoing packets, reject it.
3871 if (handle
->direction
== PCAP_D_OUT
)
3875 /* get required packet info from ring header */
3876 pcaphdr
.ts
.tv_sec
= tp_sec
;
3877 pcaphdr
.ts
.tv_usec
= tp_usec
;
3878 pcaphdr
.caplen
= tp_snaplen
;
3879 pcaphdr
.len
= tp_len
;
3881 /* if required build in place the sll header*/
3882 if (handle
->md
.cooked
) {
3883 struct sll_header
*hdrp
;
3886 * The kernel should have left us with enough
3887 * space for an sll header; back up the packet
3888 * data pointer into that space, as that'll be
3889 * the beginning of the packet we pass to the
3895 * Let's make sure that's past the end of
3896 * the tpacket header, i.e. >=
3897 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3898 * don't step on the header when we construct
3901 if (bp
< (u_char
*)h
.raw
+
3902 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3903 sizeof(struct sockaddr_ll
)) {
3904 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3905 "cooked-mode frame doesn't have room for sll header");
3910 * OK, that worked; construct the sll header.
3912 hdrp
= (struct sll_header
*)bp
;
3913 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
3915 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3916 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3917 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3918 hdrp
->sll_protocol
= sll
->sll_protocol
;
3920 /* update packet len */
3921 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3922 pcaphdr
.len
+= SLL_HDR_LEN
;
3925 #ifdef HAVE_TPACKET2
3926 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3927 tp_snaplen
>= 2 * ETH_ALEN
) {
3928 struct vlan_tag
*tag
;
3931 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3933 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3934 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3935 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3937 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3938 pcaphdr
.len
+= VLAN_TAG_LEN
;
3943 * The only way to tell the kernel to cut off the
3944 * packet at a snapshot length is with a filter program;
3945 * if there's no filter program, the kernel won't cut
3948 * Trim the snapshot length to be no longer than the
3949 * specified snapshot length.
3951 if (pcaphdr
.caplen
> handle
->snapshot
)
3952 pcaphdr
.caplen
= handle
->snapshot
;
3954 /* pass the packet to the user */
3956 callback(user
, &pcaphdr
, bp
);
3957 handle
->md
.packets_read
++;
3961 switch (handle
->md
.tp_version
) {
3963 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3965 #ifdef HAVE_TPACKET2
3967 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3971 if (++handle
->offset
>= handle
->cc
)
3974 /* check for break loop condition*/
3975 if (handle
->break_loop
) {
3976 handle
->break_loop
= 0;
3977 return PCAP_ERROR_BREAK
;
3984 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3990 * Don't rewrite "ret" instructions; we don't need to, as
3991 * we're not reading packets with recvmsg(), and we don't
3992 * want to, as, by not rewriting them, the kernel can avoid
3993 * copying extra data.
3995 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3999 /* if the kernel filter is enabled, we need to apply the filter on
4000 * all packets present into the ring. Get an upper bound of their number
4002 if (!handle
->md
.use_bpf
)
4005 /* walk the ring backward and count the free slot */
4006 offset
= handle
->offset
;
4007 if (--handle
->offset
< 0)
4008 handle
->offset
= handle
->cc
- 1;
4009 for (n
=0; n
< handle
->cc
; ++n
) {
4010 if (--handle
->offset
< 0)
4011 handle
->offset
= handle
->cc
- 1;
4012 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
4016 /* be careful to not change current ring position */
4017 handle
->offset
= offset
;
4019 /* store the number of packets currently present in the ring */
4020 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
4024 #endif /* HAVE_PACKET_RING */
4027 #ifdef HAVE_PF_PACKET_SOCKETS
4029 * Return the index of the given device name. Fill ebuf and return
4033 iface_get_id(int fd
, const char *device
, char *ebuf
)
4037 memset(&ifr
, 0, sizeof(ifr
));
4038 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4040 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
4041 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4042 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
4046 return ifr
.ifr_ifindex
;
4050 * Bind the socket associated with FD to the given device.
4051 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4052 * or a PCAP_ERROR_ value on a hard error.
4055 iface_bind(int fd
, int ifindex
, char *ebuf
)
4057 struct sockaddr_ll sll
;
4059 socklen_t errlen
= sizeof(err
);
4061 memset(&sll
, 0, sizeof(sll
));
4062 sll
.sll_family
= AF_PACKET
;
4063 sll
.sll_ifindex
= ifindex
;
4064 sll
.sll_protocol
= htons(ETH_P_ALL
);
4066 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
4067 if (errno
== ENETDOWN
) {
4069 * Return a "network down" indication, so that
4070 * the application can report that rather than
4071 * saying we had a mysterious failure and
4072 * suggest that they report a problem to the
4073 * libpcap developers.
4075 return PCAP_ERROR_IFACE_NOT_UP
;
4077 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4078 "bind: %s", pcap_strerror(errno
));
4083 /* Any pending errors, e.g., network is down? */
4085 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4086 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4087 "getsockopt: %s", pcap_strerror(errno
));
4091 if (err
== ENETDOWN
) {
4093 * Return a "network down" indication, so that
4094 * the application can report that rather than
4095 * saying we had a mysterious failure and
4096 * suggest that they report a problem to the
4097 * libpcap developers.
4099 return PCAP_ERROR_IFACE_NOT_UP
;
4100 } else if (err
> 0) {
4101 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4102 "bind: %s", pcap_strerror(err
));
4109 #ifdef IW_MODE_MONITOR
4111 * Check whether the device supports the Wireless Extensions.
4112 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4113 * if the device doesn't even exist.
4116 has_wext(int sock_fd
, const char *device
, char *ebuf
)
4120 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4121 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4122 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4123 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
4125 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4126 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4127 if (errno
== ENODEV
)
4128 return PCAP_ERROR_NO_SUCH_DEVICE
;
4133 * Per me si va ne la citta dolente,
4134 * Per me si va ne l'etterno dolore,
4136 * Lasciate ogne speranza, voi ch'intrate.
4138 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4154 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4155 * on if it's not already on.
4157 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4158 * on this device, or a PCAP_ERROR_ value if we do support them but
4159 * we weren't able to turn monitor mode on.
4162 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
4165 * XXX - at least some adapters require non-Wireless Extensions
4166 * mechanisms to turn monitor mode on.
4168 * Atheros cards might require that a separate "monitor virtual access
4169 * point" be created, with later versions of the madwifi driver.
4170 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4171 * monitor -bssid", which apparently spits out a line "athN"
4172 * where "athN" is the monitor mode device. To leave monitor
4173 * mode, it destroys the monitor mode device.
4175 * Some Intel Centrino adapters might require private ioctls to get
4176 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4177 * configure a separate "rtapN" interface to capture in monitor
4178 * mode without preventing the adapter from operating normally.
4179 * (airmon-ng doesn't appear to use that, though.)
4181 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4182 * up, and if all drivers were converted to mac80211 drivers.
4184 * If interface {if} is a mac80211 driver, the file
4185 * /sys/class/net/{if}/phy80211 is a symlink to
4186 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4188 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4189 * least, has a "wmaster0" device and a "wlan0" device; the
4190 * latter is the one with the IP address. Both show up in
4191 * "tcpdump -D" output. Capturing on the wmaster0 device
4192 * captures with 802.11 headers.
4194 * airmon-ng searches through /sys/class/net for devices named
4195 * monN, starting with mon0; as soon as one *doesn't* exist,
4196 * it chooses that as the monitor device name. If the "iw"
4197 * command exists, it does "iw dev {if} interface add {monif}
4198 * type monitor", where {monif} is the monitor device. It
4199 * then (sigh) sleeps .1 second, and then configures the
4200 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4201 * is a file, it writes {mondev}, without a newline, to that file,
4202 * and again (sigh) sleeps .1 second, and then iwconfig's that
4203 * device into monitor mode and configures it up. Otherwise,
4204 * you can't do monitor mode.
4206 * All these devices are "glued" together by having the
4207 * /sys/class/net/{device}/phy80211 links pointing to the same
4208 * place, so, given a wmaster, wlan, or mon device, you can
4209 * find the other devices by looking for devices with
4210 * the same phy80211 link.
4212 * To turn monitor mode off, delete the monitor interface,
4213 * either with "iw dev {monif} interface del" or by sending
4214 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4216 * Note: if you try to create a monitor device named "monN", and
4217 * there's already a "monN" device, it fails, as least with
4218 * the netlink interface (which is what iw uses), with a return
4219 * value of -ENFILE. (Return values are negative errnos.) We
4220 * could probably use that to find an unused device.
4224 struct iw_priv_args
*priv
;
4225 monitor_type montype
;
4232 * Does this device *support* the Wireless Extensions?
4234 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4236 return err
; /* either it doesn't or the device doesn't even exist */
4238 * Try to get all the Wireless Extensions private ioctls
4239 * supported by this device.
4241 * First, get the size of the buffer we need, by supplying no
4242 * buffer and a length of 0. If the device supports private
4243 * ioctls, it should return E2BIG, with ireq.u.data.length set
4244 * to the length we need. If it doesn't support them, it should
4245 * return EOPNOTSUPP.
4247 memset(&ireq
, 0, sizeof ireq
);
4248 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4249 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4250 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4251 ireq
.u
.data
.pointer
= (void *)args
;
4252 ireq
.u
.data
.length
= 0;
4253 ireq
.u
.data
.flags
= 0;
4254 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4255 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4256 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4260 if (errno
== EOPNOTSUPP
) {
4262 * No private ioctls, so we assume that there's only one
4263 * DLT_ for monitor mode.
4267 if (errno
!= E2BIG
) {
4271 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4272 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4275 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4277 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4278 "malloc: %s", pcap_strerror(errno
));
4281 ireq
.u
.data
.pointer
= (void *)priv
;
4282 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4283 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4284 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4290 * Look for private ioctls to turn monitor mode on or, if
4291 * monitor mode is on, to set the header type.
4293 montype
= MONITOR_WEXT
;
4295 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4296 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4298 * Hostap driver, use this one.
4299 * Set monitor mode first.
4300 * You can set it to 0 to get DLT_IEEE80211,
4301 * 1 to get DLT_PRISM, 2 to get
4302 * DLT_IEEE80211_RADIO_AVS, and, with more
4303 * recent versions of the driver, 3 to get
4304 * DLT_IEEE80211_RADIO.
4306 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4308 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4310 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4312 montype
= MONITOR_HOSTAP
;
4316 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4318 * Prism54 driver, use this one.
4319 * Set monitor mode first.
4320 * You can set it to 2 to get DLT_IEEE80211
4321 * or 3 or get DLT_PRISM.
4323 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4325 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4327 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4329 montype
= MONITOR_PRISM54
;
4333 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4335 * RT2570 driver, use this one.
4336 * Do this after turning monitor mode on.
4337 * You can set it to 1 to get DLT_PRISM or 2
4338 * to get DLT_IEEE80211.
4340 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4342 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4344 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4346 montype
= MONITOR_RT2570
;
4350 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
4352 * RT73 driver, use this one.
4353 * Do this after turning monitor mode on.
4354 * Its argument is a *string*; you can
4355 * set it to "1" to get DLT_PRISM or "2"
4356 * to get DLT_IEEE80211.
4358 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
4360 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
4362 montype
= MONITOR_RT73
;
4366 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
4368 * One of the RTL8xxx drivers, use this one.
4369 * It can only be done after monitor mode
4370 * has been turned on. You can set it to 1
4371 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4373 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4375 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4377 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4379 montype
= MONITOR_RTL8XXX
;
4383 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
4385 * RT2500 or RT61 driver, use this one.
4386 * It has one one-byte parameter; set
4387 * u.data.length to 1 and u.data.pointer to
4388 * point to the parameter.
4389 * It doesn't itself turn monitor mode on.
4390 * You can set it to 1 to allow transmitting
4391 * in monitor mode(?) and get DLT_IEEE80211,
4392 * or set it to 0 to disallow transmitting in
4393 * monitor mode(?) and get DLT_PRISM.
4395 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4397 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
4399 montype
= MONITOR_RT2500
;
4403 if (strcmp(priv
[i
].name
, "monitor") == 0) {
4405 * Either ACX100 or hostap, use this one.
4406 * It turns monitor mode on.
4407 * If it takes two arguments, it's ACX100;
4408 * the first argument is 1 for DLT_PRISM
4409 * or 2 for DLT_IEEE80211, and the second
4410 * argument is the channel on which to
4411 * run. If it takes one argument, it's
4412 * HostAP, and the argument is 2 for
4413 * DLT_IEEE80211 and 3 for DLT_PRISM.
4415 * If we see this, we don't quit, as this
4416 * might be a version of the hostap driver
4417 * that also supports "monitor_type".
4419 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4421 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4423 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4426 montype
= MONITOR_PRISM
;
4431 montype
= MONITOR_ACX100
;
4443 * XXX - ipw3945? islism?
4449 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4450 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4451 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4452 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4454 * We probably won't be able to set the mode, either.
4456 return PCAP_ERROR_RFMON_NOTSUP
;
4460 * Is it currently in monitor mode?
4462 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4464 * Yes. Just leave things as they are.
4465 * We don't offer multiple link-layer types, as
4466 * changing the link-layer type out from under
4467 * somebody else capturing in monitor mode would
4468 * be considered rude.
4473 * No. We have to put the adapter into rfmon mode.
4477 * If we haven't already done so, arrange to have
4478 * "pcap_close_all()" called when we exit.
4480 if (!pcap_do_addexit(handle
)) {
4482 * "atexit()" failed; don't put the interface
4483 * in rfmon mode, just give up.
4485 return PCAP_ERROR_RFMON_NOTSUP
;
4489 * Save the old mode.
4491 handle
->md
.oldmode
= ireq
.u
.mode
;
4494 * Put the adapter in rfmon mode. How we do this depends
4495 * on whether we have a special private ioctl or not.
4497 if (montype
== MONITOR_PRISM
) {
4499 * We have the "monitor" private ioctl, but none of
4500 * the other private ioctls. Use this, and select
4503 * If it fails, just fall back on SIOCSIWMODE.
4505 memset(&ireq
, 0, sizeof ireq
);
4506 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4507 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4508 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4509 ireq
.u
.data
.length
= 1; /* 1 argument */
4510 args
[0] = 3; /* request Prism header */
4511 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4512 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4515 * Note that we have to put the old mode back
4516 * when we close the device.
4518 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4521 * Add this to the list of pcaps to close
4524 pcap_add_to_pcaps_to_close(handle
);
4530 * Failure. Fall back on SIOCSIWMODE.
4535 * First, turn monitor mode on.
4537 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4538 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4539 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4540 ireq
.u
.mode
= IW_MODE_MONITOR
;
4541 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4543 * Scientist, you've failed.
4545 return PCAP_ERROR_RFMON_NOTSUP
;
4549 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4550 * monitor mode and setting the channel, and then does
4555 * Now select the appropriate radio header.
4561 * We don't have any private ioctl to set the header.
4565 case MONITOR_HOSTAP
:
4567 * Try to select the radiotap header.
4569 memset(&ireq
, 0, sizeof ireq
);
4570 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4571 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4572 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4573 args
[0] = 3; /* request radiotap header */
4574 memcpy(ireq
.u
.name
, args
, sizeof (int));
4575 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4576 break; /* success */
4579 * That failed. Try to select the AVS header.
4581 memset(&ireq
, 0, sizeof ireq
);
4582 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4583 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4584 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4585 args
[0] = 2; /* request AVS header */
4586 memcpy(ireq
.u
.name
, args
, sizeof (int));
4587 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4588 break; /* success */
4591 * That failed. Try to select the Prism header.
4593 memset(&ireq
, 0, sizeof ireq
);
4594 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4595 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4596 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4597 args
[0] = 1; /* request Prism header */
4598 memcpy(ireq
.u
.name
, args
, sizeof (int));
4599 ioctl(sock_fd
, cmd
, &ireq
);
4604 * The private ioctl failed.
4608 case MONITOR_PRISM54
:
4610 * Select the Prism header.
4612 memset(&ireq
, 0, sizeof ireq
);
4613 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4614 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4615 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4616 args
[0] = 3; /* request Prism header */
4617 memcpy(ireq
.u
.name
, args
, sizeof (int));
4618 ioctl(sock_fd
, cmd
, &ireq
);
4621 case MONITOR_ACX100
:
4623 * Get the current channel.
4625 memset(&ireq
, 0, sizeof ireq
);
4626 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4627 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4628 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4629 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4630 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4631 "%s: SIOCGIWFREQ: %s", device
,
4632 pcap_strerror(errno
));
4635 channel
= ireq
.u
.freq
.m
;
4638 * Select the Prism header, and set the channel to the
4641 memset(&ireq
, 0, sizeof ireq
);
4642 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4643 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4644 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4645 args
[0] = 1; /* request Prism header */
4646 args
[1] = channel
; /* set channel */
4647 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4648 ioctl(sock_fd
, cmd
, &ireq
);
4651 case MONITOR_RT2500
:
4653 * Disallow transmission - that turns on the
4656 memset(&ireq
, 0, sizeof ireq
);
4657 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4658 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4659 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4660 args
[0] = 0; /* disallow transmitting */
4661 memcpy(ireq
.u
.name
, args
, sizeof (int));
4662 ioctl(sock_fd
, cmd
, &ireq
);
4665 case MONITOR_RT2570
:
4667 * Force the Prism header.
4669 memset(&ireq
, 0, sizeof ireq
);
4670 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4671 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4672 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4673 args
[0] = 1; /* request Prism header */
4674 memcpy(ireq
.u
.name
, args
, sizeof (int));
4675 ioctl(sock_fd
, cmd
, &ireq
);
4680 * Force the Prism header.
4682 memset(&ireq
, 0, sizeof ireq
);
4683 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4684 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4685 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4686 ireq
.u
.data
.length
= 1; /* 1 argument */
4687 ireq
.u
.data
.pointer
= "1";
4688 ireq
.u
.data
.flags
= 0;
4689 ioctl(sock_fd
, cmd
, &ireq
);
4692 case MONITOR_RTL8XXX
:
4694 * Force the Prism header.
4696 memset(&ireq
, 0, sizeof ireq
);
4697 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4698 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4699 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4700 args
[0] = 1; /* request Prism header */
4701 memcpy(ireq
.u
.name
, args
, sizeof (int));
4702 ioctl(sock_fd
, cmd
, &ireq
);
4707 * Note that we have to put the old mode back when we
4710 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4713 * Add this to the list of pcaps to close when we exit.
4715 pcap_add_to_pcaps_to_close(handle
);
4719 #endif /* IW_MODE_MONITOR */
4722 * Try various mechanisms to enter monitor mode.
4725 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4727 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4732 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4734 return ret
; /* error attempting to do so */
4736 return 1; /* success */
4737 #endif /* HAVE_LIBNL */
4739 #ifdef IW_MODE_MONITOR
4740 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4742 return ret
; /* error attempting to do so */
4744 return 1; /* success */
4745 #endif /* IW_MODE_MONITOR */
4748 * Either none of the mechanisms we know about work or none
4749 * of those mechanisms are available, so we can't do monitor
4756 * Find out if we have any form of fragmentation/reassembly offloading.
4760 iface_ethtool_ioctl(pcap_t
*handle
, int cmd
, const char *cmdname
)
4763 struct ethtool_value eval
;
4765 memset(&ifr
, 0, sizeof(ifr
));
4766 strncpy(ifr
.ifr_name
, handle
->opt
.source
, sizeof(ifr
.ifr_name
));
4768 ifr
.ifr_data
= (caddr_t
)&eval
;
4769 if (ioctl(handle
->fd
, SIOCETHTOOL
, &ifr
) == -1) {
4770 if (errno
== EOPNOTSUPP
) {
4772 * OK, let's just return 0, which, in our
4773 * case, either means "no, what we're asking
4774 * about is not enabled" or "all the flags
4775 * are clear (i.e., nothing is enabled)".
4779 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4780 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle
->opt
.source
,
4781 cmdname
, strerror(errno
));
4788 iface_get_offload(pcap_t
*handle
)
4792 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GTSO
, "ETHTOOL_GTSO");
4796 return 1; /* TCP segmentation offloading on */
4798 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GUFO
, "ETHTOOL_GUFO");
4802 return 1; /* UDP fragmentation offloading on */
4805 * XXX - will this cause large unsegmented packets to be
4806 * handed to PF_PACKET sockets on transmission? If not,
4807 * this need not be checked.
4809 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGSO
, "ETHTOOL_GGSO");
4813 return 1; /* generic segmentation offloading on */
4815 #ifdef ETHTOOL_GFLAGS
4816 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GFLAGS
, "ETHTOOL_GFLAGS");
4819 if (ret
& ETH_FLAG_LRO
)
4820 return 1; /* large receive offloading on */
4825 * XXX - will this cause large reassembled packets to be
4826 * handed to PF_PACKET sockets on receipt? If not,
4827 * this need not be checked.
4829 ret
= iface_ethtool_ioctl(handle
, ETHTOOL_GGRO
, "ETHTOOL_GGRO");
4833 return 1; /* generic (large) receive offloading on */
4838 #else /* SIOCETHTOOL */
4840 iface_get_offload(pcap_t
*handle _U_
)
4843 * XXX - do we need to get this information if we don't
4844 * have the ethtool ioctls? If so, how do we do that?
4848 #endif /* SIOCETHTOOL */
4850 #endif /* HAVE_PF_PACKET_SOCKETS */
4852 /* ===== Functions to interface to the older kernels ================== */
4855 * Try to open a packet socket using the old kernel interface.
4856 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4859 activate_old(pcap_t
*handle
)
4863 const char *device
= handle
->opt
.source
;
4864 struct utsname utsname
;
4867 /* Open the socket */
4869 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
4870 if (handle
->fd
== -1) {
4871 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4872 "socket: %s", pcap_strerror(errno
));
4873 if (errno
== EPERM
|| errno
== EACCES
) {
4875 * You don't have permission to open the
4878 return PCAP_ERROR_PERM_DENIED
;
4887 /* It worked - we are using the old interface */
4888 handle
->md
.sock_packet
= 1;
4890 /* ...which means we get the link-layer header. */
4891 handle
->md
.cooked
= 0;
4893 /* Bind to the given device */
4895 if (strcmp(device
, "any") == 0) {
4896 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4900 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
4904 * Try to get the link-layer type.
4906 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
4911 * Try to find the DLT_ type corresponding to that
4914 map_arphrd_to_dlt(handle
, arptype
, 0);
4915 if (handle
->linktype
== -1) {
4916 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4917 "unknown arptype %d", arptype
);
4921 /* Go to promisc mode if requested */
4923 if (handle
->opt
.promisc
) {
4924 memset(&ifr
, 0, sizeof(ifr
));
4925 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4926 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4927 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4928 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
4931 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
4933 * Promiscuous mode isn't currently on,
4934 * so turn it on, and remember that
4935 * we should turn it off when the
4940 * If we haven't already done so, arrange
4941 * to have "pcap_close_all()" called when
4944 if (!pcap_do_addexit(handle
)) {
4946 * "atexit()" failed; don't put
4947 * the interface in promiscuous
4948 * mode, just give up.
4953 ifr
.ifr_flags
|= IFF_PROMISC
;
4954 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4955 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4957 pcap_strerror(errno
));
4960 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
4963 * Add this to the list of pcaps
4964 * to close when we exit.
4966 pcap_add_to_pcaps_to_close(handle
);
4971 * Compute the buffer size.
4973 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4974 * kernel, and might require special handling - check.
4976 if (uname(&utsname
) < 0 ||
4977 strncmp(utsname
.release
, "2.0", 3) == 0) {
4979 * Either we couldn't find out what kernel release
4980 * this is, or it's a 2.0[.x] kernel.
4982 * In the 2.0[.x] kernel, a "recvfrom()" on
4983 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4984 * return the number of bytes read, so if we pass
4985 * a length based on the snapshot length, it'll
4986 * return the number of bytes from the packet
4987 * copied to userland, not the actual length
4990 * This means that, for example, the IP dissector
4991 * in tcpdump will get handed a packet length less
4992 * than the length in the IP header, and will
4993 * complain about "truncated-ip".
4995 * So we don't bother trying to copy from the
4996 * kernel only the bytes in which we're interested,
4997 * but instead copy them all, just as the older
4998 * versions of libpcap for Linux did.
5000 * The buffer therefore needs to be big enough to
5001 * hold the largest packet we can get from this
5002 * device. Unfortunately, we can't get the MRU
5003 * of the network; we can only get the MTU. The
5004 * MTU may be too small, in which case a packet larger
5005 * than the buffer size will be truncated *and* we
5006 * won't get the actual packet size.
5008 * However, if the snapshot length is larger than
5009 * the buffer size based on the MTU, we use the
5010 * snapshot length as the buffer size, instead;
5011 * this means that with a sufficiently large snapshot
5012 * length we won't artificially truncate packets
5013 * to the MTU-based size.
5015 * This mess just one of many problems with packet
5016 * capture on 2.0[.x] kernels; you really want a
5017 * 2.2[.x] or later kernel if you want packet capture
5020 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
5023 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
5024 if (handle
->bufsize
< handle
->snapshot
)
5025 handle
->bufsize
= handle
->snapshot
;
5028 * This is a 2.2[.x] or later kernel.
5030 * We can safely pass "recvfrom()" a byte count
5031 * based on the snapshot length.
5033 handle
->bufsize
= handle
->snapshot
;
5037 * Default value for offset to align link-layer payload
5038 * on a 4-byte boundary.
5046 * Bind the socket associated with FD to the given device using the
5047 * interface of the old kernels.
5050 iface_bind_old(int fd
, const char *device
, char *ebuf
)
5052 struct sockaddr saddr
;
5054 socklen_t errlen
= sizeof(err
);
5056 memset(&saddr
, 0, sizeof(saddr
));
5057 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
5058 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
5059 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5060 "bind: %s", pcap_strerror(errno
));
5064 /* Any pending errors, e.g., network is down? */
5066 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
5067 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5068 "getsockopt: %s", pcap_strerror(errno
));
5073 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5074 "bind: %s", pcap_strerror(err
));
5082 /* ===== System calls available on all supported kernels ============== */
5085 * Query the kernel for the MTU of the given interface.
5088 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
5093 return BIGGER_THAN_ALL_MTUS
;
5095 memset(&ifr
, 0, sizeof(ifr
));
5096 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5098 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
5099 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5100 "SIOCGIFMTU: %s", pcap_strerror(errno
));
5108 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5111 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
5115 memset(&ifr
, 0, sizeof(ifr
));
5116 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
5118 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
5119 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
5120 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
5121 if (errno
== ENODEV
) {
5125 return PCAP_ERROR_NO_SUCH_DEVICE
;
5130 return ifr
.ifr_hwaddr
.sa_family
;
5133 #ifdef SO_ATTACH_FILTER
5135 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
5139 register struct bpf_insn
*p
;
5144 * Make a copy of the filter, and modify that copy if
5147 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
5148 len
= handle
->fcode
.bf_len
;
5149 f
= (struct bpf_insn
*)malloc(prog_size
);
5151 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5152 "malloc: %s", pcap_strerror(errno
));
5155 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
5157 fcode
->filter
= (struct sock_filter
*) f
;
5159 for (i
= 0; i
< len
; ++i
) {
5162 * What type of instruction is this?
5164 switch (BPF_CLASS(p
->code
)) {
5168 * It's a return instruction; are we capturing
5169 * in memory-mapped mode?
5173 * No; is the snapshot length a constant,
5174 * rather than the contents of the
5177 if (BPF_MODE(p
->code
) == BPF_K
) {
5179 * Yes - if the value to be returned,
5180 * i.e. the snapshot length, is
5181 * anything other than 0, make it
5182 * 65535, so that the packet is
5183 * truncated by "recvfrom()",
5184 * not by the filter.
5186 * XXX - there's nothing we can
5187 * easily do if it's getting the
5188 * value from the accumulator; we'd
5189 * have to insert code to force
5190 * non-zero values to be 65535.
5201 * It's a load instruction; is it loading
5204 switch (BPF_MODE(p
->code
)) {
5210 * Yes; are we in cooked mode?
5212 if (handle
->md
.cooked
) {
5214 * Yes, so we need to fix this
5217 if (fix_offset(p
) < 0) {
5219 * We failed to do so.
5220 * Return 0, so our caller
5221 * knows to punt to userland.
5231 return 1; /* we succeeded */
5235 fix_offset(struct bpf_insn
*p
)
5238 * What's the offset?
5240 if (p
->k
>= SLL_HDR_LEN
) {
5242 * It's within the link-layer payload; that starts at an
5243 * offset of 0, as far as the kernel packet filter is
5244 * concerned, so subtract the length of the link-layer
5247 p
->k
-= SLL_HDR_LEN
;
5248 } else if (p
->k
== 14) {
5250 * It's the protocol field; map it to the special magic
5251 * kernel offset for that field.
5253 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
5256 * It's within the header, but it's not one of those
5257 * fields; we can't do that in the kernel, so punt
5266 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
5268 int total_filter_on
= 0;
5274 * The socket filter code doesn't discard all packets queued
5275 * up on the socket when the filter is changed; this means
5276 * that packets that don't match the new filter may show up
5277 * after the new filter is put onto the socket, if those
5278 * packets haven't yet been read.
5280 * This means, for example, that if you do a tcpdump capture
5281 * with a filter, the first few packets in the capture might
5282 * be packets that wouldn't have passed the filter.
5284 * We therefore discard all packets queued up on the socket
5285 * when setting a kernel filter. (This isn't an issue for
5286 * userland filters, as the userland filtering is done after
5287 * packets are queued up.)
5289 * To flush those packets, we put the socket in read-only mode,
5290 * and read packets from the socket until there are no more to
5293 * In order to keep that from being an infinite loop - i.e.,
5294 * to keep more packets from arriving while we're draining
5295 * the queue - we put the "total filter", which is a filter
5296 * that rejects all packets, onto the socket before draining
5299 * This code deliberately ignores any errors, so that you may
5300 * get bogus packets if an error occurs, rather than having
5301 * the filtering done in userland even if it could have been
5302 * done in the kernel.
5304 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5305 &total_fcode
, sizeof(total_fcode
)) == 0) {
5309 * Note that we've put the total filter onto the socket.
5311 total_filter_on
= 1;
5314 * Save the socket's current mode, and put it in
5315 * non-blocking mode; we drain it by reading packets
5316 * until we get an error (which is normally a
5317 * "nothing more to be read" error).
5319 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5320 if (save_mode
!= -1 &&
5321 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
5322 while (recv(handle
->fd
, &drain
, sizeof drain
,
5326 fcntl(handle
->fd
, F_SETFL
, save_mode
);
5327 if (save_errno
!= EAGAIN
) {
5329 reset_kernel_filter(handle
);
5330 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5331 "recv: %s", pcap_strerror(save_errno
));
5338 * Now attach the new filter.
5340 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5341 fcode
, sizeof(*fcode
));
5342 if (ret
== -1 && total_filter_on
) {
5344 * Well, we couldn't set that filter on the socket,
5345 * but we could set the total filter on the socket.
5347 * This could, for example, mean that the filter was
5348 * too big to put into the kernel, so we'll have to
5349 * filter in userland; in any case, we'll be doing
5350 * filtering in userland, so we need to remove the
5351 * total filter so we see packets.
5356 * XXX - if this fails, we're really screwed;
5357 * we have the total filter on the socket,
5358 * and it won't come off. What do we do then?
5360 reset_kernel_filter(handle
);
5368 reset_kernel_filter(pcap_t
*handle
)
5371 * setsockopt() barfs unless it get a dummy parameter.
5372 * valgrind whines unless the value is initialized,
5373 * as it has no idea that setsockopt() ignores its
5378 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5379 &dummy
, sizeof(dummy
));