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 */
166 #include "pcap-int.h"
167 #include "pcap/sll.h"
168 #include "pcap/vlan.h"
171 #include "pcap-dag.h"
172 #endif /* HAVE_DAG_API */
174 #ifdef HAVE_SEPTEL_API
175 #include "pcap-septel.h"
176 #endif /* HAVE_SEPTEL_API */
179 #include "pcap-snf.h"
180 #endif /* HAVE_SNF_API */
182 #ifdef PCAP_SUPPORT_USB
183 #include "pcap-usb-linux.h"
186 #ifdef PCAP_SUPPORT_BT
187 #include "pcap-bt-linux.h"
190 #ifdef PCAP_SUPPORT_CAN
191 #include "pcap-can-linux.h"
195 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
196 * sockets rather than SOCK_PACKET sockets.
198 * To use them, we include <linux/if_packet.h> rather than
199 * <netpacket/packet.h>; we do so because
201 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
202 * later kernels and libc5, and don't provide a <netpacket/packet.h>
205 * not all versions of glibc2 have a <netpacket/packet.h> file
206 * that defines stuff needed for some of the 2.4-or-later-kernel
207 * features, so if the system has a 2.4 or later kernel, we
208 * still can't use those features.
210 * We're already including a number of other <linux/XXX.h> headers, and
211 * this code is Linux-specific (no other OS has PF_PACKET sockets as
212 * a raw packet capture mechanism), so it's not as if you gain any
213 * useful portability by using <netpacket/packet.h>
215 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
216 * isn't defined? It only defines one data structure in 2.0.x, so
217 * it shouldn't cause any problems.
220 # include <linux/if_packet.h>
223 * On at least some Linux distributions (for example, Red Hat 5.2),
224 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
225 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
226 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
227 * the PACKET_xxx stuff.
229 * So we check whether PACKET_HOST is defined, and assume that we have
230 * PF_PACKET sockets only if it is defined.
233 # define HAVE_PF_PACKET_SOCKETS
234 # ifdef PACKET_AUXDATA
235 # define HAVE_PACKET_AUXDATA
236 # endif /* PACKET_AUXDATA */
237 # endif /* PACKET_HOST */
240 /* check for memory mapped access avaibility. We assume every needed
241 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
242 * uses many ring related structs and macros */
243 # ifdef TPACKET_HDRLEN
244 # define HAVE_PACKET_RING
245 # ifdef TPACKET2_HDRLEN
246 # define HAVE_TPACKET2
248 # define TPACKET_V1 0
249 # endif /* TPACKET2_HDRLEN */
250 # endif /* TPACKET_HDRLEN */
251 #endif /* PF_PACKET */
253 #ifdef SO_ATTACH_FILTER
254 #include <linux/types.h>
255 #include <linux/filter.h>
258 #ifndef HAVE_SOCKLEN_T
259 typedef int socklen_t
;
264 * This is being compiled on a system that lacks MSG_TRUNC; define it
265 * with the value it has in the 2.2 and later kernels, so that, on
266 * those kernels, when we pass it in the flags argument to "recvfrom()"
267 * we're passing the right value and thus get the MSG_TRUNC behavior
268 * we want. (We don't get that behavior on 2.0[.x] kernels, because
269 * they didn't support MSG_TRUNC.)
271 #define MSG_TRUNC 0x20
276 * This is being compiled on a system that lacks SOL_PACKET; define it
277 * with the value it has in the 2.2 and later kernels, so that we can
278 * set promiscuous mode in the good modern way rather than the old
279 * 2.0-kernel crappy way.
281 #define SOL_PACKET 263
284 #define MAX_LINKHEADER_SIZE 256
287 * When capturing on all interfaces we use this as the buffer size.
288 * Should be bigger then all MTUs that occur in real life.
289 * 64kB should be enough for now.
291 #define BIGGER_THAN_ALL_MTUS (64*1024)
294 * Prototypes for internal functions and methods.
296 static void map_arphrd_to_dlt(pcap_t
*, int, int);
297 #ifdef HAVE_PF_PACKET_SOCKETS
298 static short int map_packet_type_to_sll_type(short int);
300 static int pcap_activate_linux(pcap_t
*);
301 static int activate_old(pcap_t
*);
302 static int activate_new(pcap_t
*);
303 static int activate_mmap(pcap_t
*, int *);
304 static int pcap_can_set_rfmon_linux(pcap_t
*);
305 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
306 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
307 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
308 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
309 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
310 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
311 static void pcap_cleanup_linux(pcap_t
*);
314 struct tpacket_hdr
*h1
;
315 struct tpacket2_hdr
*h2
;
319 #ifdef HAVE_PACKET_RING
320 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
322 static void destroy_ring(pcap_t
*handle
);
323 static int create_ring(pcap_t
*handle
, int *status
);
324 static int prepare_tpacket_socket(pcap_t
*handle
);
325 static void pcap_cleanup_linux_mmap(pcap_t
*);
326 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
327 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
328 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
329 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
330 static void pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
331 const u_char
*bytes
);
335 * Wrap some ioctl calls
337 #ifdef HAVE_PF_PACKET_SOCKETS
338 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
340 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
341 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
342 #ifdef HAVE_PF_PACKET_SOCKETS
343 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
344 #ifdef IW_MODE_MONITOR
345 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
346 #endif /* IW_MODE_MONITOR */
347 static int enter_rfmon_mode(pcap_t
*handle
, int sock_fd
,
349 #endif /* HAVE_PF_PACKET_SOCKETS */
350 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
352 #ifdef SO_ATTACH_FILTER
353 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
,
355 static int fix_offset(struct bpf_insn
*p
);
356 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
357 static int reset_kernel_filter(pcap_t
*handle
);
359 static struct sock_filter total_insn
360 = BPF_STMT(BPF_RET
| BPF_K
, 0);
361 static struct sock_fprog total_fcode
362 = { 1, &total_insn
};
366 pcap_create(const char *device
, char *ebuf
)
371 * A null device name is equivalent to the "any" device.
377 if (strstr(device
, "dag")) {
378 return dag_create(device
, ebuf
);
380 #endif /* HAVE_DAG_API */
382 #ifdef HAVE_SEPTEL_API
383 if (strstr(device
, "septel")) {
384 return septel_create(device
, ebuf
);
386 #endif /* HAVE_SEPTEL_API */
389 handle
= snf_create(device
, ebuf
);
390 if (strstr(device
, "snf") || handle
!= NULL
)
393 #endif /* HAVE_SNF_API */
395 #ifdef PCAP_SUPPORT_BT
396 if (strstr(device
, "bluetooth")) {
397 return bt_create(device
, ebuf
);
401 #ifdef PCAP_SUPPORT_CAN
402 if (strstr(device
, "can") || strstr(device
, "vcan")) {
403 return can_create(device
, ebuf
);
407 #ifdef PCAP_SUPPORT_USB
408 if (strstr(device
, "usbmon")) {
409 return usb_create(device
, ebuf
);
413 handle
= pcap_create_common(device
, ebuf
);
417 handle
->activate_op
= pcap_activate_linux
;
418 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
419 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
421 * We claim that we support:
423 * software time stamps, with no details about their precision;
424 * hardware time stamps, synced to the host time;
425 * hardware time stamps, not synced to the host time.
427 * XXX - we can't ask a device whether it supports
428 * hardware time stamps, so we just claim all devices do.
430 handle
->tstamp_type_count
= 3;
431 handle
->tstamp_type_list
= malloc(3 * sizeof(u_int
));
432 if (handle
->tstamp_type_list
== NULL
) {
436 handle
->tstamp_type_list
[0] = PCAP_TSTAMP_HOST
;
437 handle
->tstamp_type_list
[1] = PCAP_TSTAMP_ADAPTER
;
438 handle
->tstamp_type_list
[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED
;
446 * If interface {if} is a mac80211 driver, the file
447 * /sys/class/net/{if}/phy80211 is a symlink to
448 * /sys/class/ieee80211/{phydev}, for some {phydev}.
450 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
451 * least, has a "wmaster0" device and a "wlan0" device; the
452 * latter is the one with the IP address. Both show up in
453 * "tcpdump -D" output. Capturing on the wmaster0 device
454 * captures with 802.11 headers.
456 * airmon-ng searches through /sys/class/net for devices named
457 * monN, starting with mon0; as soon as one *doesn't* exist,
458 * it chooses that as the monitor device name. If the "iw"
459 * command exists, it does "iw dev {if} interface add {monif}
460 * type monitor", where {monif} is the monitor device. It
461 * then (sigh) sleeps .1 second, and then configures the
462 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
463 * is a file, it writes {mondev}, without a newline, to that file,
464 * and again (sigh) sleeps .1 second, and then iwconfig's that
465 * device into monitor mode and configures it up. Otherwise,
466 * you can't do monitor mode.
468 * All these devices are "glued" together by having the
469 * /sys/class/net/{device}/phy80211 links pointing to the same
470 * place, so, given a wmaster, wlan, or mon device, you can
471 * find the other devices by looking for devices with
472 * the same phy80211 link.
474 * To turn monitor mode off, delete the monitor interface,
475 * either with "iw dev {monif} interface del" or by sending
476 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
478 * Note: if you try to create a monitor device named "monN", and
479 * there's already a "monN" device, it fails, as least with
480 * the netlink interface (which is what iw uses), with a return
481 * value of -ENFILE. (Return values are negative errnos.) We
482 * could probably use that to find an unused device.
484 * Yes, you can have multiple monitor devices for a given
489 * Is this a mac80211 device? If so, fill in the physical device path and
490 * return 1; if not, return 0. On an error, fill in handle->errbuf and
494 get_mac80211_phydev(pcap_t
*handle
, const char *device
, char *phydev_path
,
495 size_t phydev_max_pathlen
)
501 * Generate the path string for the symlink to the physical device.
503 if (asprintf(&pathstr
, "/sys/class/net/%s/phy80211", device
) == -1) {
504 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
505 "%s: Can't generate path name string for /sys/class/net device",
509 bytes_read
= readlink(pathstr
, phydev_path
, phydev_max_pathlen
);
510 if (bytes_read
== -1) {
511 if (errno
== ENOENT
|| errno
== EINVAL
) {
513 * Doesn't exist, or not a symlink; assume that
514 * means it's not a mac80211 device.
519 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
520 "%s: Can't readlink %s: %s", device
, pathstr
,
526 phydev_path
[bytes_read
] = '\0';
530 #ifdef HAVE_LIBNL_2_x
531 #define get_nl_errmsg nl_geterror
533 /* libnl 2.x compatibility code */
535 #define nl_sock nl_handle
537 static inline struct nl_handle
*
538 nl_socket_alloc(void)
540 return nl_handle_alloc();
544 nl_socket_free(struct nl_handle
*h
)
546 nl_handle_destroy(h
);
549 #define get_nl_errmsg strerror
552 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
554 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
560 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
561 #endif /* !HAVE_LIBNL_2_x */
563 struct nl80211_state
{
564 struct nl_sock
*nl_sock
;
565 struct nl_cache
*nl_cache
;
566 struct genl_family
*nl80211
;
570 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
574 state
->nl_sock
= nl_socket_alloc();
575 if (!state
->nl_sock
) {
576 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
577 "%s: failed to allocate netlink handle", device
);
581 if (genl_connect(state
->nl_sock
)) {
582 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
583 "%s: failed to connect to generic netlink", device
);
584 goto out_handle_destroy
;
587 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
589 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
590 "%s: failed to allocate generic netlink cache: %s",
591 device
, get_nl_errmsg(-err
));
592 goto out_handle_destroy
;
595 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
596 if (!state
->nl80211
) {
597 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
598 "%s: nl80211 not found", device
);
605 nl_cache_free(state
->nl_cache
);
607 nl_socket_free(state
->nl_sock
);
612 nl80211_cleanup(struct nl80211_state
*state
)
614 genl_family_put(state
->nl80211
);
615 nl_cache_free(state
->nl_cache
);
616 nl_socket_free(state
->nl_sock
);
620 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
621 const char *device
, const char *mondevice
)
627 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
633 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
634 "%s: failed to allocate netlink msg", device
);
638 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
639 0, NL80211_CMD_NEW_INTERFACE
, 0);
640 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
641 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
642 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
644 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
646 #ifdef HAVE_LIBNL_2_x
647 if (err
== -NLE_FAILURE
) {
649 if (err
== -ENFILE
) {
652 * Device not available; our caller should just
653 * keep trying. (libnl 2.x maps ENFILE to
654 * NLE_FAILURE; it can also map other errors
655 * to that, but there's not much we can do
662 * Real failure, not just "that device is not
665 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
666 "%s: nl_send_auto_complete failed adding %s interface: %s",
667 device
, mondevice
, get_nl_errmsg(-err
));
672 err
= nl_wait_for_ack(state
->nl_sock
);
674 #ifdef HAVE_LIBNL_2_x
675 if (err
== -NLE_FAILURE
) {
677 if (err
== -ENFILE
) {
680 * Device not available; our caller should just
681 * keep trying. (libnl 2.x maps ENFILE to
682 * NLE_FAILURE; it can also map other errors
683 * to that, but there's not much we can do
690 * Real failure, not just "that device is not
693 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
694 "%s: nl_wait_for_ack failed adding %s interface: %s",
695 device
, mondevice
, get_nl_errmsg(-err
));
708 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
709 "%s: nl_put failed adding %s interface",
716 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
717 const char *device
, const char *mondevice
)
723 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
729 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
730 "%s: failed to allocate netlink msg", device
);
734 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
735 0, NL80211_CMD_DEL_INTERFACE
, 0);
736 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
738 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
740 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
741 "%s: nl_send_auto_complete failed deleting %s interface: %s",
742 device
, mondevice
, get_nl_errmsg(-err
));
746 err
= nl_wait_for_ack(state
->nl_sock
);
748 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
749 "%s: nl_wait_for_ack failed adding %s interface: %s",
750 device
, mondevice
, get_nl_errmsg(-err
));
762 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
763 "%s: nl_put failed deleting %s interface",
770 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
773 char phydev_path
[PATH_MAX
+1];
774 struct nl80211_state nlstate
;
779 * Is this a mac80211 device?
781 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
783 return ret
; /* error */
785 return 0; /* no error, but not mac80211 device */
788 * XXX - is this already a monN device?
790 * Is that determined by old Wireless Extensions ioctls?
794 * OK, it's apparently a mac80211 device.
795 * Try to find an unused monN device for it.
797 ret
= nl80211_init(handle
, &nlstate
, device
);
800 for (n
= 0; n
< UINT_MAX
; n
++) {
804 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
806 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
807 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
809 handle
->md
.mondevice
= strdup(mondevice
);
814 * Hard failure. Just return ret; handle->errbuf
815 * has already been set.
817 nl80211_cleanup(&nlstate
);
822 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
823 "%s: No free monN interfaces", device
);
824 nl80211_cleanup(&nlstate
);
831 * Sleep for .1 seconds.
834 delay
.tv_nsec
= 500000000;
835 nanosleep(&delay
, NULL
);
839 * Now configure the monitor interface up.
841 memset(&ifr
, 0, sizeof(ifr
));
842 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
843 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
844 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
845 "%s: Can't get flags for %s: %s", device
,
846 handle
->md
.mondevice
, strerror(errno
));
847 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
848 handle
->md
.mondevice
);
849 nl80211_cleanup(&nlstate
);
852 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
853 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
854 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
855 "%s: Can't set flags for %s: %s", device
,
856 handle
->md
.mondevice
, strerror(errno
));
857 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
858 handle
->md
.mondevice
);
859 nl80211_cleanup(&nlstate
);
864 * Success. Clean up the libnl state.
866 nl80211_cleanup(&nlstate
);
869 * Note that we have to delete the monitor device when we close
872 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
875 * Add this to the list of pcaps to close when we exit.
877 pcap_add_to_pcaps_to_close(handle
);
881 #endif /* HAVE_LIBNL */
884 pcap_can_set_rfmon_linux(pcap_t
*handle
)
887 char phydev_path
[PATH_MAX
+1];
890 #ifdef IW_MODE_MONITOR
895 if (strcmp(handle
->opt
.source
, "any") == 0) {
897 * Monitor mode makes no sense on the "any" device.
904 * Bleah. There doesn't seem to be a way to ask a mac80211
905 * device, through libnl, whether it supports monitor mode;
906 * we'll just check whether the device appears to be a
907 * mac80211 device and, if so, assume the device supports
910 * wmaster devices don't appear to support the Wireless
911 * Extensions, but we can create a mon device for a
912 * wmaster device, so we don't bother checking whether
913 * a mac80211 device supports the Wireless Extensions.
915 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
918 return ret
; /* error */
920 return 1; /* mac80211 device */
923 #ifdef IW_MODE_MONITOR
925 * Bleah. There doesn't appear to be an ioctl to use to ask
926 * whether a device supports monitor mode; we'll just do
927 * SIOCGIWMODE and, if it succeeds, assume the device supports
930 * Open a socket on which to attempt to get the mode.
931 * (We assume that if we have Wireless Extensions support
932 * we also have PF_PACKET support.)
934 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
936 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
937 "socket: %s", pcap_strerror(errno
));
942 * Attempt to get the current mode.
944 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
945 sizeof ireq
.ifr_ifrn
.ifrn_name
);
946 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
947 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
949 * Well, we got the mode; assume we can set it.
954 if (errno
== ENODEV
) {
955 /* The device doesn't even exist. */
956 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
957 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
959 return PCAP_ERROR_NO_SUCH_DEVICE
;
967 * Grabs the number of dropped packets by the interface from /proc/net/dev.
969 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
970 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
972 * Or can we get them in binary form from netlink?
975 linux_if_drops(const char * if_name
)
980 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
981 long int dropped_pkts
= 0;
983 file
= fopen("/proc/net/dev", "r");
987 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
989 /* search for 'bytes' -- if its in there, then
990 that means we need to grab the fourth field. otherwise
991 grab the third field. */
992 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
994 field_to_convert
= 4;
998 /* find iface and make sure it actually matches -- space before the name and : after it */
999 if ((bufptr
= strstr(buffer
, if_name
)) &&
1000 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1001 *(bufptr
+ if_name_sz
) == ':')
1003 bufptr
= bufptr
+ if_name_sz
+ 1;
1005 /* grab the nth field from it */
1006 while( --field_to_convert
&& *bufptr
!= '\0')
1008 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1009 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1012 /* get rid of any final spaces */
1013 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1015 if (*bufptr
!= '\0')
1016 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1023 return dropped_pkts
;
1028 * With older kernels promiscuous mode is kind of interesting because we
1029 * have to reset the interface before exiting. The problem can't really
1030 * be solved without some daemon taking care of managing usage counts.
1031 * If we put the interface into promiscuous mode, we set a flag indicating
1032 * that we must take it out of that mode when the interface is closed,
1033 * and, when closing the interface, if that flag is set we take it out
1034 * of promiscuous mode.
1036 * Even with newer kernels, we have the same issue with rfmon mode.
1039 static void pcap_cleanup_linux( pcap_t
*handle
)
1043 struct nl80211_state nlstate
;
1045 #endif /* HAVE_LIBNL */
1046 #ifdef IW_MODE_MONITOR
1048 #endif /* IW_MODE_MONITOR */
1050 if (handle
->md
.must_do_on_close
!= 0) {
1052 * There's something we have to do when closing this
1055 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
1057 * We put the interface into promiscuous mode;
1058 * take it out of promiscuous mode.
1060 * XXX - if somebody else wants it in promiscuous
1061 * mode, this code cannot know that, so it'll take
1062 * it out of promiscuous mode. That's not fixable
1063 * in 2.0[.x] kernels.
1065 memset(&ifr
, 0, sizeof(ifr
));
1066 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1067 sizeof(ifr
.ifr_name
));
1068 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1070 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1071 "Please adjust manually.\n"
1072 "Hint: This can't happen with Linux >= 2.2.0.\n",
1075 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1077 * Promiscuous mode is currently on;
1080 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1081 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1084 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1085 "Please adjust manually.\n"
1086 "Hint: This can't happen with Linux >= 2.2.0.\n",
1094 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1095 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1097 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1098 handle
->md
.device
, handle
->md
.mondevice
);
1099 nl80211_cleanup(&nlstate
);
1103 "Can't delete monitor interface %s (%s).\n"
1104 "Please delete manually.\n",
1105 handle
->md
.mondevice
, handle
->errbuf
);
1108 #endif /* HAVE_LIBNL */
1110 #ifdef IW_MODE_MONITOR
1111 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1113 * We put the interface into rfmon mode;
1114 * take it out of rfmon mode.
1116 * XXX - if somebody else wants it in rfmon
1117 * mode, this code cannot know that, so it'll take
1118 * it out of rfmon mode.
1120 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1121 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1122 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1124 ireq
.u
.mode
= handle
->md
.oldmode
;
1125 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1127 * Scientist, you've failed.
1130 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1131 "Please adjust manually.\n",
1135 #endif /* IW_MODE_MONITOR */
1138 * Take this pcap out of the list of pcaps for which we
1139 * have to take the interface out of some mode.
1141 pcap_remove_from_pcaps_to_close(handle
);
1144 if (handle
->md
.mondevice
!= NULL
) {
1145 free(handle
->md
.mondevice
);
1146 handle
->md
.mondevice
= NULL
;
1148 if (handle
->md
.device
!= NULL
) {
1149 free(handle
->md
.device
);
1150 handle
->md
.device
= NULL
;
1152 pcap_cleanup_live_common(handle
);
1156 * Get a handle for a live capture from the given device. You can
1157 * pass NULL as device to get all packages (without link level
1158 * information of course). If you pass 1 as promisc the interface
1159 * will be set to promiscous mode (XXX: I think this usage should
1160 * be deprecated and functions be added to select that later allow
1161 * modification of that values -- Torsten).
1164 pcap_activate_linux(pcap_t
*handle
)
1169 device
= handle
->opt
.source
;
1171 handle
->inject_op
= pcap_inject_linux
;
1172 handle
->setfilter_op
= pcap_setfilter_linux
;
1173 handle
->setdirection_op
= pcap_setdirection_linux
;
1174 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1175 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1176 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1177 handle
->cleanup_op
= pcap_cleanup_linux
;
1178 handle
->read_op
= pcap_read_linux
;
1179 handle
->stats_op
= pcap_stats_linux
;
1182 * The "any" device is a special device which causes us not
1183 * to bind to a particular device and thus to look at all
1186 if (strcmp(device
, "any") == 0) {
1187 if (handle
->opt
.promisc
) {
1188 handle
->opt
.promisc
= 0;
1189 /* Just a warning. */
1190 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1191 "Promiscuous mode not supported on the \"any\" device");
1192 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1196 handle
->md
.device
= strdup(device
);
1197 if (handle
->md
.device
== NULL
) {
1198 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1199 pcap_strerror(errno
) );
1204 * If we're in promiscuous mode, then we probably want
1205 * to see when the interface drops packets too, so get an
1206 * initial count from /proc/net/dev
1208 if (handle
->opt
.promisc
)
1209 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1212 * Current Linux kernels use the protocol family PF_PACKET to
1213 * allow direct access to all packets on the network while
1214 * older kernels had a special socket type SOCK_PACKET to
1215 * implement this feature.
1216 * While this old implementation is kind of obsolete we need
1217 * to be compatible with older kernels for a while so we are
1218 * trying both methods with the newer method preferred.
1220 status
= activate_new(handle
);
1223 * Fatal error with the new way; just fail.
1224 * status has the error return; if it's PCAP_ERROR,
1225 * handle->errbuf has been set appropriately.
1232 * Try to use memory-mapped access.
1234 switch (activate_mmap(handle
, &status
)) {
1238 * We succeeded. status has been
1239 * set to the status to return,
1240 * which might be 0, or might be
1241 * a PCAP_WARNING_ value.
1247 * Kernel doesn't support it - just continue
1248 * with non-memory-mapped access.
1254 * We failed to set up to use it, or the kernel
1255 * supports it, but we failed to enable it.
1256 * status has been set to the error status to
1257 * return and, if it's PCAP_ERROR, handle->errbuf
1258 * contains the error message.
1263 else if (status
== 0) {
1264 /* Non-fatal error; try old way */
1265 if ((status
= activate_old(handle
)) != 1) {
1267 * Both methods to open the packet socket failed.
1268 * Tidy up and report our failure (handle->errbuf
1269 * is expected to be set by the functions above).
1276 * We set up the socket, but not with memory-mapped access.
1279 if (handle
->opt
.buffer_size
!= 0) {
1281 * Set the socket buffer size to the specified value.
1283 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1284 &handle
->opt
.buffer_size
,
1285 sizeof(handle
->opt
.buffer_size
)) == -1) {
1286 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1287 "SO_RCVBUF: %s", pcap_strerror(errno
));
1288 status
= PCAP_ERROR
;
1293 /* Allocate the buffer */
1295 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1296 if (!handle
->buffer
) {
1297 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1298 "malloc: %s", pcap_strerror(errno
));
1299 status
= PCAP_ERROR
;
1304 * "handle->fd" is a socket, so "select()" and "poll()"
1305 * should work on it.
1307 handle
->selectable_fd
= handle
->fd
;
1312 pcap_cleanup_linux(handle
);
1317 * Read at most max_packets from the capture stream and call the callback
1318 * for each of them. Returns the number of packets handled or -1 if an
1322 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1325 * Currently, on Linux only one packet is delivered per read,
1328 return pcap_read_packet(handle
, callback
, user
);
1332 * Read a packet from the socket calling the handler provided by
1333 * the user. Returns the number of packets received or -1 if an
1337 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1341 #ifdef HAVE_PF_PACKET_SOCKETS
1342 struct sockaddr_ll from
;
1343 struct sll_header
*hdrp
;
1345 struct sockaddr from
;
1347 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1350 struct cmsghdr
*cmsg
;
1352 struct cmsghdr cmsg
;
1353 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1355 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1357 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1358 int packet_len
, caplen
;
1359 struct pcap_pkthdr pcap_header
;
1361 #ifdef HAVE_PF_PACKET_SOCKETS
1363 * If this is a cooked device, leave extra room for a
1364 * fake packet header.
1366 if (handle
->md
.cooked
)
1367 offset
= SLL_HDR_LEN
;
1372 * This system doesn't have PF_PACKET sockets, so it doesn't
1373 * support cooked devices.
1379 * Receive a single packet from the kernel.
1380 * We ignore EINTR, as that might just be due to a signal
1381 * being delivered - if the signal should interrupt the
1382 * loop, the signal handler should call pcap_breakloop()
1383 * to set handle->break_loop (we ignore it on other
1384 * platforms as well).
1385 * We also ignore ENETDOWN, so that we can continue to
1386 * capture traffic if the interface goes down and comes
1387 * back up again; comments in the kernel indicate that
1388 * we'll just block waiting for packets if we try to
1389 * receive from a socket that delivered ENETDOWN, and,
1390 * if we're using a memory-mapped buffer, we won't even
1391 * get notified of "network down" events.
1393 bp
= handle
->buffer
+ handle
->offset
;
1395 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1396 msg
.msg_name
= &from
;
1397 msg
.msg_namelen
= sizeof(from
);
1400 msg
.msg_control
= &cmsg_buf
;
1401 msg
.msg_controllen
= sizeof(cmsg_buf
);
1404 iov
.iov_len
= handle
->bufsize
- offset
;
1405 iov
.iov_base
= bp
+ offset
;
1406 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1410 * Has "pcap_breakloop()" been called?
1412 if (handle
->break_loop
) {
1414 * Yes - clear the flag that indicates that it has,
1415 * and return PCAP_ERROR_BREAK as an indication that
1416 * we were told to break out of the loop.
1418 handle
->break_loop
= 0;
1419 return PCAP_ERROR_BREAK
;
1422 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1423 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1424 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1425 fromlen
= sizeof(from
);
1426 packet_len
= recvfrom(
1427 handle
->fd
, bp
+ offset
,
1428 handle
->bufsize
- offset
, MSG_TRUNC
,
1429 (struct sockaddr
*) &from
, &fromlen
);
1430 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1431 } while (packet_len
== -1 && errno
== EINTR
);
1433 /* Check if an error occured */
1435 if (packet_len
== -1) {
1439 return 0; /* no packet there */
1443 * The device on which we're capturing went away.
1445 * XXX - we should really return
1446 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1447 * etc. aren't defined to return that.
1449 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1450 "The interface went down");
1454 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1455 "recvfrom: %s", pcap_strerror(errno
));
1460 #ifdef HAVE_PF_PACKET_SOCKETS
1461 if (!handle
->md
.sock_packet
) {
1463 * Unfortunately, there is a window between socket() and
1464 * bind() where the kernel may queue packets from any
1465 * interface. If we're bound to a particular interface,
1466 * discard packets not from that interface.
1468 * (If socket filters are supported, we could do the
1469 * same thing we do when changing the filter; however,
1470 * that won't handle packet sockets without socket
1471 * filter support, and it's a bit more complicated.
1472 * It would save some instructions per packet, however.)
1474 if (handle
->md
.ifindex
!= -1 &&
1475 from
.sll_ifindex
!= handle
->md
.ifindex
)
1479 * Do checks based on packet direction.
1480 * We can only do this if we're using PF_PACKET; the
1481 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1482 * which lacks the relevant packet type information.
1484 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1487 * If this is from the loopback device, reject it;
1488 * we'll see the packet as an incoming packet as well,
1489 * and we don't want to see it twice.
1491 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1495 * If the user only wants incoming packets, reject it.
1497 if (handle
->direction
== PCAP_D_IN
)
1502 * If the user only wants outgoing packets, reject it.
1504 if (handle
->direction
== PCAP_D_OUT
)
1510 #ifdef HAVE_PF_PACKET_SOCKETS
1512 * If this is a cooked device, fill in the fake packet header.
1514 if (handle
->md
.cooked
) {
1516 * Add the length of the fake header to the length
1517 * of packet data we read.
1519 packet_len
+= SLL_HDR_LEN
;
1521 hdrp
= (struct sll_header
*)bp
;
1522 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1523 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1524 hdrp
->sll_halen
= htons(from
.sll_halen
);
1525 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1526 (from
.sll_halen
> SLL_ADDRLEN
) ?
1529 hdrp
->sll_protocol
= from
.sll_protocol
;
1532 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1533 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1534 struct tpacket_auxdata
*aux
;
1536 struct vlan_tag
*tag
;
1538 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1539 cmsg
->cmsg_level
!= SOL_PACKET
||
1540 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1543 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1544 if (aux
->tp_vlan_tci
== 0)
1547 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1548 if (len
< 2 * ETH_ALEN
)
1552 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1554 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1555 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1556 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1558 packet_len
+= VLAN_TAG_LEN
;
1560 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1561 #endif /* HAVE_PF_PACKET_SOCKETS */
1564 * XXX: According to the kernel source we should get the real
1565 * packet len if calling recvfrom with MSG_TRUNC set. It does
1566 * not seem to work here :(, but it is supported by this code
1568 * To be honest the code RELIES on that feature so this is really
1569 * broken with 2.2.x kernels.
1570 * I spend a day to figure out what's going on and I found out
1571 * that the following is happening:
1573 * The packet comes from a random interface and the packet_rcv
1574 * hook is called with a clone of the packet. That code inserts
1575 * the packet into the receive queue of the packet socket.
1576 * If a filter is attached to that socket that filter is run
1577 * first - and there lies the problem. The default filter always
1578 * cuts the packet at the snaplen:
1583 * So the packet filter cuts down the packet. The recvfrom call
1584 * says "hey, it's only 68 bytes, it fits into the buffer" with
1585 * the result that we don't get the real packet length. This
1586 * is valid at least until kernel 2.2.17pre6.
1588 * We currently handle this by making a copy of the filter
1589 * program, fixing all "ret" instructions with non-zero
1590 * operands to have an operand of 65535 so that the filter
1591 * doesn't truncate the packet, and supplying that modified
1592 * filter to the kernel.
1595 caplen
= packet_len
;
1596 if (caplen
> handle
->snapshot
)
1597 caplen
= handle
->snapshot
;
1599 /* Run the packet filter if not using kernel filter */
1600 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1601 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1602 packet_len
, caplen
) == 0)
1604 /* rejected by filter */
1609 /* Fill in our own header data */
1611 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1612 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1613 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1616 pcap_header
.caplen
= caplen
;
1617 pcap_header
.len
= packet_len
;
1622 * Arguably, we should count them before we check the filter,
1623 * as on many other platforms "ps_recv" counts packets
1624 * handed to the filter rather than packets that passed
1625 * the filter, but if filtering is done in the kernel, we
1626 * can't get a count of packets that passed the filter,
1627 * and that would mean the meaning of "ps_recv" wouldn't
1628 * be the same on all Linux systems.
1630 * XXX - it's not the same on all systems in any case;
1631 * ideally, we should have a "get the statistics" call
1632 * that supplies more counts and indicates which of them
1633 * it supplies, so that we supply a count of packets
1634 * handed to the filter only on platforms where that
1635 * information is available.
1637 * We count them here even if we can get the packet count
1638 * from the kernel, as we can only determine at run time
1639 * whether we'll be able to get it from the kernel (if
1640 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1641 * the kernel, but if it is defined, the library might
1642 * have been built with a 2.4 or later kernel, but we
1643 * might be running on a 2.2[.x] kernel without Alexey
1644 * Kuznetzov's turbopacket patches, and thus the kernel
1645 * might not be able to supply those statistics). We
1646 * could, I guess, try, when opening the socket, to get
1647 * the statistics, and if we can not increment the count
1648 * here, but it's not clear that always incrementing
1649 * the count is more expensive than always testing a flag
1652 * We keep the count in "md.packets_read", and use that for
1653 * "ps_recv" if we can't get the statistics from the kernel.
1654 * We do that because, if we *can* get the statistics from
1655 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1656 * as running counts, as reading the statistics from the
1657 * kernel resets the kernel statistics, and if we directly
1658 * increment "md.stat.ps_recv" here, that means it will
1659 * count packets *twice* on systems where we can get kernel
1660 * statistics - once here, and once in pcap_stats_linux().
1662 handle
->md
.packets_read
++;
1664 /* Call the user supplied callback function */
1665 callback(userdata
, &pcap_header
, bp
);
1671 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1675 #ifdef HAVE_PF_PACKET_SOCKETS
1676 if (!handle
->md
.sock_packet
) {
1677 /* PF_PACKET socket */
1678 if (handle
->md
.ifindex
== -1) {
1680 * We don't support sending on the "any" device.
1682 strlcpy(handle
->errbuf
,
1683 "Sending packets isn't supported on the \"any\" device",
1688 if (handle
->md
.cooked
) {
1690 * We don't support sending on the "any" device.
1692 * XXX - how do you send on a bound cooked-mode
1694 * Is a "sendto()" required there?
1696 strlcpy(handle
->errbuf
,
1697 "Sending packets isn't supported in cooked mode",
1704 ret
= send(handle
->fd
, buf
, size
, 0);
1706 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1707 pcap_strerror(errno
));
1714 * Get the statistics for the given packet capture handle.
1715 * Reports the number of dropped packets iff the kernel supports
1716 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1717 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1718 * patches); otherwise, that information isn't available, and we lie
1719 * and report 0 as the count of dropped packets.
1722 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1724 #ifdef HAVE_TPACKET_STATS
1725 struct tpacket_stats kstats
;
1726 socklen_t len
= sizeof (struct tpacket_stats
);
1729 long if_dropped
= 0;
1732 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1734 if (handle
->opt
.promisc
)
1736 if_dropped
= handle
->md
.proc_dropped
;
1737 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1738 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1741 #ifdef HAVE_TPACKET_STATS
1743 * Try to get the packet counts from the kernel.
1745 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1746 &kstats
, &len
) > -1) {
1748 * On systems where the PACKET_STATISTICS "getsockopt()"
1749 * argument is supported on PF_PACKET sockets:
1751 * "ps_recv" counts only packets that *passed* the
1752 * filter, not packets that didn't pass the filter.
1753 * This includes packets later dropped because we
1754 * ran out of buffer space.
1756 * "ps_drop" counts packets dropped because we ran
1757 * out of buffer space. It doesn't count packets
1758 * dropped by the interface driver. It counts only
1759 * packets that passed the filter.
1761 * See above for ps_ifdrop.
1763 * Both statistics include packets not yet read from
1764 * the kernel by libpcap, and thus not yet seen by
1767 * In "linux/net/packet/af_packet.c", at least in the
1768 * 2.4.9 kernel, "tp_packets" is incremented for every
1769 * packet that passes the packet filter *and* is
1770 * successfully queued on the socket; "tp_drops" is
1771 * incremented for every packet dropped because there's
1772 * not enough free space in the socket buffer.
1774 * When the statistics are returned for a PACKET_STATISTICS
1775 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1776 * so that "tp_packets" counts all packets handed to
1777 * the PF_PACKET socket, including packets dropped because
1778 * there wasn't room on the socket buffer - but not
1779 * including packets that didn't pass the filter.
1781 * In the BSD BPF, the count of received packets is
1782 * incremented for every packet handed to BPF, regardless
1783 * of whether it passed the filter.
1785 * We can't make "pcap_stats()" work the same on both
1786 * platforms, but the best approximation is to return
1787 * "tp_packets" as the count of packets and "tp_drops"
1788 * as the count of drops.
1790 * Keep a running total because each call to
1791 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1792 * resets the counters to zero.
1794 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1795 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1796 *stats
= handle
->md
.stat
;
1802 * If the error was EOPNOTSUPP, fall through, so that
1803 * if you build the library on a system with
1804 * "struct tpacket_stats" and run it on a system
1805 * that doesn't, it works as it does if the library
1806 * is built on a system without "struct tpacket_stats".
1808 if (errno
!= EOPNOTSUPP
) {
1809 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1810 "pcap_stats: %s", pcap_strerror(errno
));
1816 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1817 * is not supported on PF_PACKET sockets:
1819 * "ps_recv" counts only packets that *passed* the filter,
1820 * not packets that didn't pass the filter. It does not
1821 * count packets dropped because we ran out of buffer
1824 * "ps_drop" is not supported.
1826 * "ps_ifdrop" is supported. It will return the number
1827 * of drops the interface reports in /proc/net/dev,
1828 * if that is available.
1830 * "ps_recv" doesn't include packets not yet read from
1831 * the kernel by libpcap.
1833 * We maintain the count of packets processed by libpcap in
1834 * "md.packets_read", for reasons described in the comment
1835 * at the end of pcap_read_packet(). We have no idea how many
1836 * packets were dropped by the kernel buffers -- but we know
1837 * how many the interface dropped, so we can return that.
1840 stats
->ps_recv
= handle
->md
.packets_read
;
1842 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1847 * Get from "/sys/class/net" all interfaces listed there; if they're
1848 * already in the list of interfaces we have, that won't add another
1849 * instance, but if they're not, that'll add them.
1851 * We don't bother getting any addresses for them; it appears you can't
1852 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1853 * although some other types of addresses can be fetched with SIOCGIFADDR,
1854 * we don't bother with them for now.
1856 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1857 * the list of interfaces as is, and return 0, so that we can try
1858 * scanning /proc/net/dev.
1861 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1863 DIR *sys_class_net_d
;
1867 char name
[512]; /* XXX - pick a size */
1869 struct ifreq ifrflags
;
1872 sys_class_net_d
= opendir("/sys/class/net");
1873 if (sys_class_net_d
== NULL
&& errno
== ENOENT
)
1877 * Create a socket from which to fetch interface information.
1879 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1881 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1882 "socket: %s", pcap_strerror(errno
));
1883 (void)closedir(sys_class_net_d
);
1889 ent
= readdir(sys_class_net_d
);
1892 * Error or EOF; if errno != 0, it's an error.
1898 * Ignore directories (".", "..", and any subdirectories).
1900 if (ent
->d_type
== DT_DIR
)
1904 * Get the interface name.
1906 p
= &ent
->d_name
[0];
1908 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1911 * This could be the separator between a
1912 * name and an alias number, or it could be
1913 * the separator between a name with no
1914 * alias number and the next field.
1916 * If there's a colon after digits, it
1917 * separates the name and the alias number,
1918 * otherwise it separates the name and the
1922 while (isascii(*p
) && isdigit(*p
))
1926 * That was the next field,
1927 * not the alias number.
1938 * Get the flags for this interface, and skip it if
1941 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
1942 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
1943 if (errno
== ENXIO
|| errno
== ENODEV
)
1945 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1946 "SIOCGIFFLAGS: %.*s: %s",
1947 (int)sizeof(ifrflags
.ifr_name
),
1949 pcap_strerror(errno
));
1953 if (!(ifrflags
.ifr_flags
& IFF_UP
))
1957 * Add an entry for this interface, with no addresses.
1959 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
1970 * Well, we didn't fail for any other reason; did we
1971 * fail due to an error reading the directory?
1974 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1975 "Error reading /sys/class/net: %s",
1976 pcap_strerror(errno
));
1982 (void)closedir(sys_class_net_d
);
1987 * Get from "/proc/net/dev" all interfaces listed there; if they're
1988 * already in the list of interfaces we have, that won't add another
1989 * instance, but if they're not, that'll add them.
1991 * See comments from scan_sys_class_net().
1994 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2001 char name
[512]; /* XXX - pick a size */
2003 struct ifreq ifrflags
;
2006 proc_net_f
= fopen("/proc/net/dev", "r");
2007 if (proc_net_f
== NULL
&& errno
== ENOENT
)
2011 * Create a socket from which to fetch interface information.
2013 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2015 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2016 "socket: %s", pcap_strerror(errno
));
2017 (void)fclose(proc_net_f
);
2022 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2024 * Skip the first two lines - they're headers.
2032 * Skip leading white space.
2034 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2036 if (*p
== '\0' || *p
== '\n')
2037 continue; /* blank line */
2040 * Get the interface name.
2043 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2046 * This could be the separator between a
2047 * name and an alias number, or it could be
2048 * the separator between a name with no
2049 * alias number and the next field.
2051 * If there's a colon after digits, it
2052 * separates the name and the alias number,
2053 * otherwise it separates the name and the
2057 while (isascii(*p
) && isdigit(*p
))
2061 * That was the next field,
2062 * not the alias number.
2073 * Get the flags for this interface, and skip it if
2076 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2077 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2080 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2081 "SIOCGIFFLAGS: %.*s: %s",
2082 (int)sizeof(ifrflags
.ifr_name
),
2084 pcap_strerror(errno
));
2088 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2092 * Add an entry for this interface, with no addresses.
2094 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2105 * Well, we didn't fail for any other reason; did we
2106 * fail due to an error reading the file?
2108 if (ferror(proc_net_f
)) {
2109 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2110 "Error reading /proc/net/dev: %s",
2111 pcap_strerror(errno
));
2117 (void)fclose(proc_net_f
);
2122 * Description string for the "any" device.
2124 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2127 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2132 * Read "/sys/class/net", and add to the list of interfaces all
2133 * interfaces listed there that we don't already have, because,
2134 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2135 * and even getifaddrs() won't return information about
2136 * interfaces with no addresses, so you need to read "/sys/class/net"
2137 * to get the names of the rest of the interfaces.
2139 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2141 return (-1); /* failed */
2144 * No /sys/class/net; try reading /proc/net/dev instead.
2146 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2151 * Add the "any" device.
2153 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2160 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2162 #endif /* HAVE_DAG_API */
2164 #ifdef HAVE_SEPTEL_API
2166 * Add Septel devices.
2168 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2170 #endif /* HAVE_SEPTEL_API */
2173 if (snf_platform_finddevs(alldevsp
, errbuf
) < 0)
2175 #endif /* HAVE_SNF_API */
2177 #ifdef PCAP_SUPPORT_BT
2179 * Add Bluetooth devices.
2181 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2185 #ifdef PCAP_SUPPORT_USB
2189 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2197 * Attach the given BPF code to the packet capture device.
2200 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2203 #ifdef SO_ATTACH_FILTER
2204 struct sock_fprog fcode
;
2205 int can_filter_in_kernel
;
2212 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2217 /* Make our private copy of the filter */
2219 if (install_bpf_program(handle
, filter
) < 0)
2220 /* install_bpf_program() filled in errbuf */
2224 * Run user level packet filter by default. Will be overriden if
2225 * installing a kernel filter succeeds.
2227 handle
->md
.use_bpf
= 0;
2229 /* Install kernel level filter if possible */
2231 #ifdef SO_ATTACH_FILTER
2233 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2235 * fcode.len is an unsigned short for current kernel.
2236 * I have yet to see BPF-Code with that much
2237 * instructions but still it is possible. So for the
2238 * sake of correctness I added this check.
2240 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2242 fcode
.filter
= NULL
;
2243 can_filter_in_kernel
= 0;
2245 #endif /* USHRT_MAX */
2248 * Oh joy, the Linux kernel uses struct sock_fprog instead
2249 * of struct bpf_program and of course the length field is
2250 * of different size. Pointed out by Sebastian
2252 * Oh, and we also need to fix it up so that all "ret"
2253 * instructions with non-zero operands have 65535 as the
2254 * operand if we're not capturing in memory-mapped modee,
2255 * and so that, if we're in cooked mode, all memory-reference
2256 * instructions use special magic offsets in references to
2257 * the link-layer header and assume that the link-layer
2258 * payload begins at 0; "fix_program()" will do that.
2260 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2265 * Fatal error; just quit.
2266 * (The "default" case shouldn't happen; we
2267 * return -1 for that reason.)
2273 * The program performed checks that we can't make
2274 * work in the kernel.
2276 can_filter_in_kernel
= 0;
2281 * We have a filter that'll work in the kernel.
2283 can_filter_in_kernel
= 1;
2288 if (can_filter_in_kernel
) {
2289 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2291 /* Installation succeded - using kernel filter. */
2292 handle
->md
.use_bpf
= 1;
2294 else if (err
== -1) /* Non-fatal error */
2297 * Print a warning if we weren't able to install
2298 * the filter for a reason other than "this kernel
2299 * isn't configured to support socket filters.
2301 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2303 "Warning: Kernel filter failed: %s\n",
2304 pcap_strerror(errno
));
2310 * If we're not using the kernel filter, get rid of any kernel
2311 * filter that might've been there before, e.g. because the
2312 * previous filter could work in the kernel, or because some other
2313 * code attached a filter to the socket by some means other than
2314 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2315 * filter out packets that would pass the new userland filter.
2317 if (!handle
->md
.use_bpf
)
2318 reset_kernel_filter(handle
);
2321 * Free up the copy of the filter that was made by "fix_program()".
2323 if (fcode
.filter
!= NULL
)
2329 #endif /* SO_ATTACH_FILTER */
2335 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2337 return pcap_setfilter_linux_common(handle
, filter
, 0);
2342 * Set direction flag: Which packets do we accept on a forwarding
2343 * single device? IN, OUT or both?
2346 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2348 #ifdef HAVE_PF_PACKET_SOCKETS
2349 if (!handle
->md
.sock_packet
) {
2350 handle
->direction
= d
;
2355 * We're not using PF_PACKET sockets, so we can't determine
2356 * the direction of the packet.
2358 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2359 "Setting direction is not supported on SOCK_PACKET sockets");
2363 #ifdef HAVE_PF_PACKET_SOCKETS
2365 * Map the PACKET_ value to a LINUX_SLL_ value; we
2366 * want the same numerical value to be used in
2367 * the link-layer header even if the numerical values
2368 * for the PACKET_ #defines change, so that programs
2369 * that look at the packet type field will always be
2370 * able to handle DLT_LINUX_SLL captures.
2373 map_packet_type_to_sll_type(short int sll_pkttype
)
2375 switch (sll_pkttype
) {
2378 return htons(LINUX_SLL_HOST
);
2380 case PACKET_BROADCAST
:
2381 return htons(LINUX_SLL_BROADCAST
);
2383 case PACKET_MULTICAST
:
2384 return htons(LINUX_SLL_MULTICAST
);
2386 case PACKET_OTHERHOST
:
2387 return htons(LINUX_SLL_OTHERHOST
);
2389 case PACKET_OUTGOING
:
2390 return htons(LINUX_SLL_OUTGOING
);
2399 * Linux uses the ARP hardware type to identify the type of an
2400 * interface. pcap uses the DLT_xxx constants for this. This
2401 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2402 * constant, as arguments, and sets "handle->linktype" to the
2403 * appropriate DLT_XXX constant and sets "handle->offset" to
2404 * the appropriate value (to make "handle->offset" plus link-layer
2405 * header length be a multiple of 4, so that the link-layer payload
2406 * will be aligned on a 4-byte boundary when capturing packets).
2407 * (If the offset isn't set here, it'll be 0; add code as appropriate
2408 * for cases where it shouldn't be 0.)
2410 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2411 * in cooked mode; otherwise, we can't use cooked mode, so we have
2412 * to pick some type that works in raw mode, or fail.
2414 * Sets the link type to -1 if unable to map the type.
2416 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2422 * This is (presumably) a real Ethernet capture; give it a
2423 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2424 * that an application can let you choose it, in case you're
2425 * capturing DOCSIS traffic that a Cisco Cable Modem
2426 * Termination System is putting out onto an Ethernet (it
2427 * doesn't put an Ethernet header onto the wire, it puts raw
2428 * DOCSIS frames out on the wire inside the low-level
2429 * Ethernet framing).
2431 * XXX - are there any sorts of "fake Ethernet" that have
2432 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2433 * a Cisco CMTS won't put traffic onto it or get traffic
2434 * bridged onto it? ISDN is handled in "activate_new()",
2435 * as we fall back on cooked mode there; are there any
2438 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2440 * If that fails, just leave the list empty.
2442 if (handle
->dlt_list
!= NULL
) {
2443 handle
->dlt_list
[0] = DLT_EN10MB
;
2444 handle
->dlt_list
[1] = DLT_DOCSIS
;
2445 handle
->dlt_count
= 2;
2449 case ARPHRD_METRICOM
:
2450 case ARPHRD_LOOPBACK
:
2451 handle
->linktype
= DLT_EN10MB
;
2456 handle
->linktype
= DLT_EN3MB
;
2460 handle
->linktype
= DLT_AX25_KISS
;
2464 handle
->linktype
= DLT_PRONET
;
2468 handle
->linktype
= DLT_CHAOS
;
2471 #define ARPHRD_CAN 280
2474 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2477 #ifndef ARPHRD_IEEE802_TR
2478 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2480 case ARPHRD_IEEE802_TR
:
2481 case ARPHRD_IEEE802
:
2482 handle
->linktype
= DLT_IEEE802
;
2487 handle
->linktype
= DLT_ARCNET_LINUX
;
2490 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2491 #define ARPHRD_FDDI 774
2494 handle
->linktype
= DLT_FDDI
;
2498 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2499 #define ARPHRD_ATM 19
2503 * The Classical IP implementation in ATM for Linux
2504 * supports both what RFC 1483 calls "LLC Encapsulation",
2505 * in which each packet has an LLC header, possibly
2506 * with a SNAP header as well, prepended to it, and
2507 * what RFC 1483 calls "VC Based Multiplexing", in which
2508 * different virtual circuits carry different network
2509 * layer protocols, and no header is prepended to packets.
2511 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2512 * you can't use the ARPHRD_ type to find out whether
2513 * captured packets will have an LLC header, and,
2514 * while there's a socket ioctl to *set* the encapsulation
2515 * type, there's no ioctl to *get* the encapsulation type.
2519 * programs that dissect Linux Classical IP frames
2520 * would have to check for an LLC header and,
2521 * depending on whether they see one or not, dissect
2522 * the frame as LLC-encapsulated or as raw IP (I
2523 * don't know whether there's any traffic other than
2524 * IP that would show up on the socket, or whether
2525 * there's any support for IPv6 in the Linux
2526 * Classical IP code);
2528 * filter expressions would have to compile into
2529 * code that checks for an LLC header and does
2532 * Both of those are a nuisance - and, at least on systems
2533 * that support PF_PACKET sockets, we don't have to put
2534 * up with those nuisances; instead, we can just capture
2535 * in cooked mode. That's what we'll do, if we can.
2536 * Otherwise, we'll just fail.
2539 handle
->linktype
= DLT_LINUX_SLL
;
2541 handle
->linktype
= -1;
2544 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2545 #define ARPHRD_IEEE80211 801
2547 case ARPHRD_IEEE80211
:
2548 handle
->linktype
= DLT_IEEE802_11
;
2551 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2552 #define ARPHRD_IEEE80211_PRISM 802
2554 case ARPHRD_IEEE80211_PRISM
:
2555 handle
->linktype
= DLT_PRISM_HEADER
;
2558 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2559 #define ARPHRD_IEEE80211_RADIOTAP 803
2561 case ARPHRD_IEEE80211_RADIOTAP
:
2562 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2567 * Some PPP code in the kernel supplies no link-layer
2568 * header whatsoever to PF_PACKET sockets; other PPP
2569 * code supplies PPP link-layer headers ("syncppp.c");
2570 * some PPP code might supply random link-layer
2571 * headers (PPP over ISDN - there's code in Ethereal,
2572 * for example, to cope with PPP-over-ISDN captures
2573 * with which the Ethereal developers have had to cope,
2574 * heuristically trying to determine which of the
2575 * oddball link-layer headers particular packets have).
2577 * As such, we just punt, and run all PPP interfaces
2578 * in cooked mode, if we can; otherwise, we just treat
2579 * it as DLT_RAW, for now - if somebody needs to capture,
2580 * on a 2.0[.x] kernel, on PPP devices that supply a
2581 * link-layer header, they'll have to add code here to
2582 * map to the appropriate DLT_ type (possibly adding a
2583 * new DLT_ type, if necessary).
2586 handle
->linktype
= DLT_LINUX_SLL
;
2589 * XXX - handle ISDN types here? We can't fall
2590 * back on cooked sockets, so we'd have to
2591 * figure out from the device name what type of
2592 * link-layer encapsulation it's using, and map
2593 * that to an appropriate DLT_ value, meaning
2594 * we'd map "isdnN" devices to DLT_RAW (they
2595 * supply raw IP packets with no link-layer
2596 * header) and "isdY" devices to a new DLT_I4L_IP
2597 * type that has only an Ethernet packet type as
2598 * a link-layer header.
2600 * But sometimes we seem to get random crap
2601 * in the link-layer header when capturing on
2604 handle
->linktype
= DLT_RAW
;
2608 #ifndef ARPHRD_CISCO
2609 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2612 handle
->linktype
= DLT_C_HDLC
;
2615 /* Not sure if this is correct for all tunnels, but it
2619 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2627 #ifndef ARPHRD_RAWHDLC
2628 #define ARPHRD_RAWHDLC 518
2630 case ARPHRD_RAWHDLC
:
2632 #define ARPHRD_DLCI 15
2636 * XXX - should some of those be mapped to DLT_LINUX_SLL
2637 * instead? Should we just map all of them to DLT_LINUX_SLL?
2639 handle
->linktype
= DLT_RAW
;
2643 #define ARPHRD_FRAD 770
2646 handle
->linktype
= DLT_FRELAY
;
2649 case ARPHRD_LOCALTLK
:
2650 handle
->linktype
= DLT_LTALK
;
2654 #define ARPHRD_FCPP 784
2658 #define ARPHRD_FCAL 785
2662 #define ARPHRD_FCPL 786
2665 #ifndef ARPHRD_FCFABRIC
2666 #define ARPHRD_FCFABRIC 787
2668 case ARPHRD_FCFABRIC
:
2670 * We assume that those all mean RFC 2625 IP-over-
2671 * Fibre Channel, with the RFC 2625 header at
2672 * the beginning of the packet.
2674 handle
->linktype
= DLT_IP_OVER_FC
;
2678 #define ARPHRD_IRDA 783
2681 /* Don't expect IP packet out of this interfaces... */
2682 handle
->linktype
= DLT_LINUX_IRDA
;
2683 /* We need to save packet direction for IrDA decoding,
2684 * so let's use "Linux-cooked" mode. Jean II */
2685 //handle->md.cooked = 1;
2688 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2689 * is needed, please report it to <daniele@orlandi.com> */
2691 #define ARPHRD_LAPD 8445
2694 /* Don't expect IP packet out of this interfaces... */
2695 handle
->linktype
= DLT_LINUX_LAPD
;
2699 #define ARPHRD_NONE 0xFFFE
2703 * No link-layer header; packets are just IP
2704 * packets, so use DLT_RAW.
2706 handle
->linktype
= DLT_RAW
;
2709 #ifndef ARPHRD_IEEE802154
2710 #define ARPHRD_IEEE802154 804
2712 case ARPHRD_IEEE802154
:
2713 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2717 handle
->linktype
= -1;
2722 /* ===== Functions to interface to the newer kernels ================== */
2725 * Try to open a packet socket using the new kernel PF_PACKET interface.
2726 * Returns 1 on success, 0 on an error that means the new interface isn't
2727 * present (so the old SOCK_PACKET interface should be tried), and a
2728 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2729 * work either (so it shouldn't be tried).
2732 activate_new(pcap_t
*handle
)
2734 #ifdef HAVE_PF_PACKET_SOCKETS
2735 const char *device
= handle
->opt
.source
;
2736 int is_any_device
= (strcmp(device
, "any") == 0);
2737 int sock_fd
= -1, arptype
;
2738 #ifdef HAVE_PACKET_AUXDATA
2742 struct packet_mreq mr
;
2745 * Open a socket with protocol family packet. If the
2746 * "any" device was specified, we open a SOCK_DGRAM
2747 * socket for the cooked interface, otherwise we first
2748 * try a SOCK_RAW socket for the raw interface.
2750 sock_fd
= is_any_device
?
2751 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2752 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2754 if (sock_fd
== -1) {
2755 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2756 pcap_strerror(errno
) );
2757 return 0; /* try old mechanism */
2760 /* It seems the kernel supports the new interface. */
2761 handle
->md
.sock_packet
= 0;
2764 * Get the interface index of the loopback device.
2765 * If the attempt fails, don't fail, just set the
2766 * "md.lo_ifindex" to -1.
2768 * XXX - can there be more than one device that loops
2769 * packets back, i.e. devices other than "lo"? If so,
2770 * we'd need to find them all, and have an array of
2771 * indices for them, and check all of them in
2772 * "pcap_read_packet()".
2774 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2777 * Default value for offset to align link-layer payload
2778 * on a 4-byte boundary.
2783 * What kind of frames do we have to deal with? Fall back
2784 * to cooked mode if we have an unknown interface type
2785 * or a type we know doesn't work well in raw mode.
2787 if (!is_any_device
) {
2788 /* Assume for now we don't need cooked mode. */
2789 handle
->md
.cooked
= 0;
2791 if (handle
->opt
.rfmon
) {
2793 * We were asked to turn on monitor mode.
2794 * Do so before we get the link-layer type,
2795 * because entering monitor mode could change
2796 * the link-layer type.
2798 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2806 * Nothing worked for turning monitor mode
2810 return PCAP_ERROR_RFMON_NOTSUP
;
2814 * Either monitor mode has been turned on for
2815 * the device, or we've been given a different
2816 * device to open for monitor mode. If we've
2817 * been given a different device, use it.
2819 if (handle
->md
.mondevice
!= NULL
)
2820 device
= handle
->md
.mondevice
;
2822 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2827 map_arphrd_to_dlt(handle
, arptype
, 1);
2828 if (handle
->linktype
== -1 ||
2829 handle
->linktype
== DLT_LINUX_SLL
||
2830 handle
->linktype
== DLT_LINUX_IRDA
||
2831 handle
->linktype
== DLT_LINUX_LAPD
||
2832 (handle
->linktype
== DLT_EN10MB
&&
2833 (strncmp("isdn", device
, 4) == 0 ||
2834 strncmp("isdY", device
, 4) == 0))) {
2836 * Unknown interface type (-1), or a
2837 * device we explicitly chose to run
2838 * in cooked mode (e.g., PPP devices),
2839 * or an ISDN device (whose link-layer
2840 * type we can only determine by using
2841 * APIs that may be different on different
2842 * kernels) - reopen in cooked mode.
2844 if (close(sock_fd
) == -1) {
2845 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2846 "close: %s", pcap_strerror(errno
));
2849 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2851 if (sock_fd
== -1) {
2852 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2853 "socket: %s", pcap_strerror(errno
));
2856 handle
->md
.cooked
= 1;
2859 * Get rid of any link-layer type list
2860 * we allocated - this only supports cooked
2863 if (handle
->dlt_list
!= NULL
) {
2864 free(handle
->dlt_list
);
2865 handle
->dlt_list
= NULL
;
2866 handle
->dlt_count
= 0;
2869 if (handle
->linktype
== -1) {
2871 * Warn that we're falling back on
2872 * cooked mode; we may want to
2873 * update "map_arphrd_to_dlt()"
2874 * to handle the new type.
2876 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2878 "supported by libpcap - "
2879 "falling back to cooked "
2885 * IrDA capture is not a real "cooked" capture,
2886 * it's IrLAP frames, not IP packets. The
2887 * same applies to LAPD capture.
2889 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2890 handle
->linktype
!= DLT_LINUX_LAPD
)
2891 handle
->linktype
= DLT_LINUX_SLL
;
2894 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2896 if (handle
->md
.ifindex
== -1) {
2901 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2902 handle
->errbuf
)) != 1) {
2907 return 0; /* try old mechanism */
2913 if (handle
->opt
.rfmon
) {
2915 * It doesn't support monitor mode.
2917 return PCAP_ERROR_RFMON_NOTSUP
;
2921 * It uses cooked mode.
2923 handle
->md
.cooked
= 1;
2924 handle
->linktype
= DLT_LINUX_SLL
;
2927 * We're not bound to a device.
2928 * For now, we're using this as an indication
2929 * that we can't transmit; stop doing that only
2930 * if we figure out how to transmit in cooked
2933 handle
->md
.ifindex
= -1;
2937 * Select promiscuous mode on if "promisc" is set.
2939 * Do not turn allmulti mode on if we don't select
2940 * promiscuous mode - on some devices (e.g., Orinoco
2941 * wireless interfaces), allmulti mode isn't supported
2942 * and the driver implements it by turning promiscuous
2943 * mode on, and that screws up the operation of the
2944 * card as a normal networking interface, and on no
2945 * other platform I know of does starting a non-
2946 * promiscuous capture affect which multicast packets
2947 * are received by the interface.
2951 * Hmm, how can we set promiscuous mode on all interfaces?
2952 * I am not sure if that is possible at all. For now, we
2953 * silently ignore attempts to turn promiscuous mode on
2954 * for the "any" device (so you don't have to explicitly
2955 * disable it in programs such as tcpdump).
2958 if (!is_any_device
&& handle
->opt
.promisc
) {
2959 memset(&mr
, 0, sizeof(mr
));
2960 mr
.mr_ifindex
= handle
->md
.ifindex
;
2961 mr
.mr_type
= PACKET_MR_PROMISC
;
2962 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2963 &mr
, sizeof(mr
)) == -1) {
2964 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2965 "setsockopt: %s", pcap_strerror(errno
));
2971 /* Enable auxillary data if supported and reserve room for
2972 * reconstructing VLAN headers. */
2973 #ifdef HAVE_PACKET_AUXDATA
2975 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2976 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2977 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2978 "setsockopt: %s", pcap_strerror(errno
));
2982 handle
->offset
+= VLAN_TAG_LEN
;
2983 #endif /* HAVE_PACKET_AUXDATA */
2986 * This is a 2.2[.x] or later kernel (we know that
2987 * because we're not using a SOCK_PACKET socket -
2988 * PF_PACKET is supported only in 2.2 and later
2991 * We can safely pass "recvfrom()" a byte count
2992 * based on the snapshot length.
2994 * If we're in cooked mode, make the snapshot length
2995 * large enough to hold a "cooked mode" header plus
2996 * 1 byte of packet data (so we don't pass a byte
2997 * count of 0 to "recvfrom()").
2999 if (handle
->md
.cooked
) {
3000 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3001 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3003 handle
->bufsize
= handle
->snapshot
;
3005 /* Save the socket FD in the pcap structure */
3006 handle
->fd
= sock_fd
;
3011 "New packet capturing interface not supported by build "
3012 "environment", PCAP_ERRBUF_SIZE
);
3017 #ifdef HAVE_PACKET_RING
3019 * Attempt to activate with memory-mapped access.
3021 * On success, returns 1, and sets *status to 0 if there are no warnings
3022 * or to a PCAP_WARNING_ code if there is a warning.
3024 * On failure due to lack of support for memory-mapped capture, returns
3027 * On error, returns -1, and sets *status to the appropriate error code;
3028 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3031 activate_mmap(pcap_t
*handle
, int *status
)
3036 * Attempt to allocate a buffer to hold the contents of one
3037 * packet, for use by the oneshot callback.
3039 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
3040 if (handle
->md
.oneshot_buffer
== NULL
) {
3041 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3042 "can't allocate oneshot buffer: %s",
3043 pcap_strerror(errno
));
3044 *status
= PCAP_ERROR
;
3048 if (handle
->opt
.buffer_size
== 0) {
3049 /* by default request 2M for the ring buffer */
3050 handle
->opt
.buffer_size
= 2*1024*1024;
3052 ret
= prepare_tpacket_socket(handle
);
3054 free(handle
->md
.oneshot_buffer
);
3055 *status
= PCAP_ERROR
;
3058 ret
= create_ring(handle
, status
);
3061 * We don't support memory-mapped capture; our caller
3062 * will fall back on reading from the socket.
3064 free(handle
->md
.oneshot_buffer
);
3069 * Error attempting to enable memory-mapped capture;
3070 * fail. create_ring() has set *status.
3072 free(handle
->md
.oneshot_buffer
);
3077 * Success. *status has been set either to 0 if there are no
3078 * warnings or to a PCAP_WARNING_ value if there is a warning.
3080 * Override some defaults and inherit the other fields from
3082 * handle->offset is used to get the current position into the rx ring.
3083 * handle->cc is used to store the ring size.
3085 handle
->read_op
= pcap_read_linux_mmap
;
3086 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3087 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3088 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3089 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3090 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3091 handle
->selectable_fd
= handle
->fd
;
3094 #else /* HAVE_PACKET_RING */
3096 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3100 #endif /* HAVE_PACKET_RING */
3102 #ifdef HAVE_PACKET_RING
3104 * Attempt to set the socket to version 2 of the memory-mapped header.
3105 * Return 1 if we succeed or if we fail because version 2 isn't
3106 * supported; return -1 on any other error, and set handle->errbuf.
3109 prepare_tpacket_socket(pcap_t
*handle
)
3111 #ifdef HAVE_TPACKET2
3116 handle
->md
.tp_version
= TPACKET_V1
;
3117 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
3119 #ifdef HAVE_TPACKET2
3120 /* Probe whether kernel supports TPACKET_V2 */
3123 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3124 if (errno
== ENOPROTOOPT
)
3125 return 1; /* no - just drive on */
3127 /* Yes - treat as a failure. */
3128 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3129 "can't get TPACKET_V2 header len on packet socket: %s",
3130 pcap_strerror(errno
));
3133 handle
->md
.tp_hdrlen
= val
;
3136 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3138 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3139 "can't activate TPACKET_V2 on packet socket: %s",
3140 pcap_strerror(errno
));
3143 handle
->md
.tp_version
= TPACKET_V2
;
3145 /* Reserve space for VLAN tag reconstruction */
3147 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3149 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3150 "can't set up reserve on packet socket: %s",
3151 pcap_strerror(errno
));
3155 #endif /* HAVE_TPACKET2 */
3160 * Attempt to set up memory-mapped access.
3162 * On success, returns 1, and sets *status to 0 if there are no warnings
3163 * or to a PCAP_WARNING_ code if there is a warning.
3165 * On failure due to lack of support for memory-mapped capture, returns
3168 * On error, returns -1, and sets *status to the appropriate error code;
3169 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3172 create_ring(pcap_t
*handle
, int *status
)
3174 unsigned i
, j
, frames_per_block
;
3175 struct tpacket_req req
;
3178 * Start out assuming no warnings or errors.
3182 /* Note that with large snapshot (say 64K) only a few frames
3183 * will be available in the ring even with pretty large ring size
3184 * (and a lot of memory will be unused).
3185 * The snap len should be carefully chosen to achive best
3187 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
3188 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3189 sizeof(struct sockaddr_ll
));
3190 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3192 /* compute the minumum block size that will handle this frame.
3193 * The block has to be page size aligned.
3194 * The max block size allowed by the kernel is arch-dependent and
3195 * it's not explicitly checked here. */
3196 req
.tp_block_size
= getpagesize();
3197 while (req
.tp_block_size
< req
.tp_frame_size
)
3198 req
.tp_block_size
<<= 1;
3200 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3203 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3204 * so we check for PACKET_TIMESTAMP. We check for
3205 * linux/net_tstamp.h just in case a system somehow has
3206 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3209 * SIOCSHWTSTAMP was introduced in the patch that introduced
3210 * linux/net_tstamp.h, so we don't bother checking whether
3211 * SIOCSHWTSTAMP is defined (if your Linux system has
3212 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3213 * Linux system is badly broken).
3215 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3217 * If we were told to do so, ask the kernel and the driver
3218 * to use hardware timestamps.
3220 * Hardware timestamps are only supported with mmapped
3223 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3224 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3225 struct hwtstamp_config hwconfig
;
3230 * Ask for hardware time stamps on all packets,
3231 * including transmitted packets.
3233 memset(&hwconfig
, 0, sizeof(hwconfig
));
3234 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3235 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3237 memset(&ifr
, 0, sizeof(ifr
));
3238 strcpy(ifr
.ifr_name
, handle
->opt
.source
);
3239 ifr
.ifr_data
= (void *)&hwconfig
;
3241 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3246 * Treat this as an error, as the
3247 * user should try to run this
3248 * with the appropriate privileges -
3249 * and, if they can't, shouldn't
3250 * try requesting hardware time stamps.
3252 *status
= PCAP_ERROR_PERM_DENIED
;
3257 * Treat this as a warning, as the
3258 * only way to fix the warning is to
3259 * get an adapter that supports hardware
3260 * time stamps. We'll just fall back
3261 * on the standard host time stamps.
3263 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3267 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3268 "SIOCSHWTSTAMP failed: %s",
3269 pcap_strerror(errno
));
3270 *status
= PCAP_ERROR
;
3275 * Well, that worked. Now specify the type of
3276 * hardware time stamp we want for this
3279 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3281 * Hardware timestamp, synchronized
3282 * with the system clock.
3284 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3287 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3288 * timestamp, not synchronized with the
3291 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3293 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3294 (void *)×ource
, sizeof(timesource
))) {
3295 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3296 "can't set PACKET_TIMESTAMP: %s",
3297 pcap_strerror(errno
));
3298 *status
= PCAP_ERROR
;
3303 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3305 /* ask the kernel to create the ring */
3307 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3309 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3310 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3312 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3313 (void *) &req
, sizeof(req
))) {
3314 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3316 * Memory failure; try to reduce the requested ring
3319 * We used to reduce this by half -- do 5% instead.
3320 * That may result in more iterations and a longer
3321 * startup, but the user will be much happier with
3322 * the resulting buffer size.
3324 if (req
.tp_frame_nr
< 20)
3325 req
.tp_frame_nr
-= 1;
3327 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3330 if (errno
== ENOPROTOOPT
) {
3332 * We don't have ring buffer support in this kernel.
3336 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3337 "can't create rx ring on packet socket: %s",
3338 pcap_strerror(errno
));
3339 *status
= PCAP_ERROR
;
3343 /* memory map the rx ring */
3344 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3345 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3346 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3347 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3348 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3349 "can't mmap rx ring: %s", pcap_strerror(errno
));
3351 /* clear the allocated ring on error*/
3352 destroy_ring(handle
);
3353 *status
= PCAP_ERROR
;
3357 /* allocate a ring for each frame header pointer*/
3358 handle
->cc
= req
.tp_frame_nr
;
3359 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3360 if (!handle
->buffer
) {
3361 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3362 "can't allocate ring of frame headers: %s",
3363 pcap_strerror(errno
));
3365 destroy_ring(handle
);
3366 *status
= PCAP_ERROR
;
3370 /* fill the header ring with proper frame ptr*/
3372 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3373 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3374 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3375 RING_GET_FRAME(handle
) = base
;
3376 base
+= req
.tp_frame_size
;
3380 handle
->bufsize
= req
.tp_frame_size
;
3385 /* free all ring related resources*/
3387 destroy_ring(pcap_t
*handle
)
3389 /* tell the kernel to destroy the ring*/
3390 struct tpacket_req req
;
3391 memset(&req
, 0, sizeof(req
));
3392 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3393 (void *) &req
, sizeof(req
));
3395 /* if ring is mapped, unmap it*/
3396 if (handle
->md
.mmapbuf
) {
3397 /* do not test for mmap failure, as we can't recover from any error */
3398 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3399 handle
->md
.mmapbuf
= NULL
;
3404 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3405 * for Linux mmapped capture.
3407 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3408 * data handed to the callback to be valid after the callback returns,
3409 * but pcap_read_linux_mmap() has to release that packet as soon as
3410 * the callback returns (otherwise, the kernel thinks there's still
3411 * at least one unprocessed packet available in the ring, so a select()
3412 * will immediately return indicating that there's data to process), so,
3413 * in the callback, we have to make a copy of the packet.
3415 * Yes, this means that, if the capture is using the ring buffer, using
3416 * pcap_next() or pcap_next_ex() requires more copies than using
3417 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3418 * pcap_next() or pcap_next_ex().
3421 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3422 const u_char
*bytes
)
3424 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3427 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3428 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3432 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3434 destroy_ring(handle
);
3435 if (handle
->md
.oneshot_buffer
!= NULL
) {
3436 free(handle
->md
.oneshot_buffer
);
3437 handle
->md
.oneshot_buffer
= NULL
;
3439 pcap_cleanup_linux(handle
);
3444 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3446 /* use negative value of timeout to indicate non blocking ops */
3447 return (p
->md
.timeout
<0);
3451 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3453 /* map each value to the corresponding 2's complement, to
3454 * preserve the timeout value provided with pcap_set_timeout */
3456 if (p
->md
.timeout
>= 0) {
3458 * Timeout is non-negative, so we're not already
3459 * in non-blocking mode; set it to the 2's
3460 * complement, to make it negative, as an
3461 * indication that we're in non-blocking mode.
3463 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3466 if (p
->md
.timeout
< 0) {
3468 * Timeout is negative, so we're not already
3469 * in blocking mode; reverse the previous
3470 * operation, to make the timeout non-negative
3473 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3479 static inline union thdr
*
3480 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3484 h
.raw
= RING_GET_FRAME(handle
);
3485 switch (handle
->md
.tp_version
) {
3487 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3491 #ifdef HAVE_TPACKET2
3493 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3507 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3514 /* wait for frames availability.*/
3515 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3516 struct pollfd pollinfo
;
3519 pollinfo
.fd
= handle
->fd
;
3520 pollinfo
.events
= POLLIN
;
3522 if (handle
->md
.timeout
== 0)
3523 timeout
= -1; /* block forever */
3524 else if (handle
->md
.timeout
> 0)
3525 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3527 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3529 ret
= poll(&pollinfo
, 1, timeout
);
3530 if (ret
< 0 && errno
!= EINTR
) {
3531 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3532 "can't poll on packet socket: %s",
3533 pcap_strerror(errno
));
3535 } else if (ret
> 0 &&
3536 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3538 * There's some indication other than
3539 * "you can read on this descriptor" on
3542 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3543 snprintf(handle
->errbuf
,
3545 "Hangup on packet socket");
3548 if (pollinfo
.revents
& POLLERR
) {
3550 * A recv() will give us the
3551 * actual error code.
3553 * XXX - make the socket non-blocking?
3555 if (recv(handle
->fd
, &c
, sizeof c
,
3557 continue; /* what, no error? */
3558 if (errno
== ENETDOWN
) {
3560 * The device on which we're
3561 * capturing went away.
3563 * XXX - we should really return
3564 * PCAP_ERROR_IFACE_NOT_UP,
3565 * but pcap_dispatch() etc.
3566 * aren't defined to return
3569 snprintf(handle
->errbuf
,
3571 "The interface went down");
3573 snprintf(handle
->errbuf
,
3575 "Error condition on packet socket: %s",
3580 if (pollinfo
.revents
& POLLNVAL
) {
3581 snprintf(handle
->errbuf
,
3583 "Invalid polling request on packet socket");
3587 /* check for break loop condition on interrupted syscall*/
3588 if (handle
->break_loop
) {
3589 handle
->break_loop
= 0;
3590 return PCAP_ERROR_BREAK
;
3595 /* non-positive values of max_packets are used to require all
3596 * packets currently available in the ring */
3597 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3599 struct sockaddr_ll
*sll
;
3600 struct pcap_pkthdr pcaphdr
;
3603 unsigned int tp_len
;
3604 unsigned int tp_mac
;
3605 unsigned int tp_snaplen
;
3606 unsigned int tp_sec
;
3607 unsigned int tp_usec
;
3609 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3613 switch (handle
->md
.tp_version
) {
3615 tp_len
= h
.h1
->tp_len
;
3616 tp_mac
= h
.h1
->tp_mac
;
3617 tp_snaplen
= h
.h1
->tp_snaplen
;
3618 tp_sec
= h
.h1
->tp_sec
;
3619 tp_usec
= h
.h1
->tp_usec
;
3621 #ifdef HAVE_TPACKET2
3623 tp_len
= h
.h2
->tp_len
;
3624 tp_mac
= h
.h2
->tp_mac
;
3625 tp_snaplen
= h
.h2
->tp_snaplen
;
3626 tp_sec
= h
.h2
->tp_sec
;
3627 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3631 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3632 "unsupported tpacket version %d",
3633 handle
->md
.tp_version
);
3636 /* perform sanity check on internal offset. */
3637 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3638 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3639 "corrupted frame on kernel ring mac "
3640 "offset %d + caplen %d > frame len %d",
3641 tp_mac
, tp_snaplen
, handle
->bufsize
);
3645 /* run filter on received packet
3646 * If the kernel filtering is enabled we need to run the
3647 * filter until all the frames present into the ring
3648 * at filter creation time are processed.
3649 * In such case md.use_bpf is used as a counter for the
3650 * packet we need to filter.
3651 * Note: alternatively it could be possible to stop applying
3652 * the filter when the ring became empty, but it can possibly
3653 * happen a lot later... */
3654 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3655 run_bpf
= (!handle
->md
.use_bpf
) ||
3656 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
3657 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3658 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
3659 tp_len
, tp_snaplen
) == 0))
3663 * Do checks based on packet direction.
3665 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
3666 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
3669 * If this is from the loopback device, reject it;
3670 * we'll see the packet as an incoming packet as well,
3671 * and we don't want to see it twice.
3673 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
3677 * If the user only wants incoming packets, reject it.
3679 if (handle
->direction
== PCAP_D_IN
)
3684 * If the user only wants outgoing packets, reject it.
3686 if (handle
->direction
== PCAP_D_OUT
)
3690 /* get required packet info from ring header */
3691 pcaphdr
.ts
.tv_sec
= tp_sec
;
3692 pcaphdr
.ts
.tv_usec
= tp_usec
;
3693 pcaphdr
.caplen
= tp_snaplen
;
3694 pcaphdr
.len
= tp_len
;
3696 /* if required build in place the sll header*/
3697 if (handle
->md
.cooked
) {
3698 struct sll_header
*hdrp
;
3701 * The kernel should have left us with enough
3702 * space for an sll header; back up the packet
3703 * data pointer into that space, as that'll be
3704 * the beginning of the packet we pass to the
3710 * Let's make sure that's past the end of
3711 * the tpacket header, i.e. >=
3712 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3713 * don't step on the header when we construct
3716 if (bp
< (u_char
*)h
.raw
+
3717 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3718 sizeof(struct sockaddr_ll
)) {
3719 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3720 "cooked-mode frame doesn't have room for sll header");
3725 * OK, that worked; construct the sll header.
3727 hdrp
= (struct sll_header
*)bp
;
3728 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
3730 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3731 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3732 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3733 hdrp
->sll_protocol
= sll
->sll_protocol
;
3735 /* update packet len */
3736 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3737 pcaphdr
.len
+= SLL_HDR_LEN
;
3740 #ifdef HAVE_TPACKET2
3741 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3742 tp_snaplen
>= 2 * ETH_ALEN
) {
3743 struct vlan_tag
*tag
;
3746 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3748 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3749 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3750 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3752 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3753 pcaphdr
.len
+= VLAN_TAG_LEN
;
3758 * The only way to tell the kernel to cut off the
3759 * packet at a snapshot length is with a filter program;
3760 * if there's no filter program, the kernel won't cut
3763 * Trim the snapshot length to be no longer than the
3764 * specified snapshot length.
3766 if (pcaphdr
.caplen
> handle
->snapshot
)
3767 pcaphdr
.caplen
= handle
->snapshot
;
3769 /* pass the packet to the user */
3771 callback(user
, &pcaphdr
, bp
);
3772 handle
->md
.packets_read
++;
3776 switch (handle
->md
.tp_version
) {
3778 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3780 #ifdef HAVE_TPACKET2
3782 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3786 if (++handle
->offset
>= handle
->cc
)
3789 /* check for break loop condition*/
3790 if (handle
->break_loop
) {
3791 handle
->break_loop
= 0;
3792 return PCAP_ERROR_BREAK
;
3799 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3805 * Don't rewrite "ret" instructions; we don't need to, as
3806 * we're not reading packets with recvmsg(), and we don't
3807 * want to, as, by not rewriting them, the kernel can avoid
3808 * copying extra data.
3810 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3814 /* if the kernel filter is enabled, we need to apply the filter on
3815 * all packets present into the ring. Get an upper bound of their number
3817 if (!handle
->md
.use_bpf
)
3820 /* walk the ring backward and count the free slot */
3821 offset
= handle
->offset
;
3822 if (--handle
->offset
< 0)
3823 handle
->offset
= handle
->cc
- 1;
3824 for (n
=0; n
< handle
->cc
; ++n
) {
3825 if (--handle
->offset
< 0)
3826 handle
->offset
= handle
->cc
- 1;
3827 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
3831 /* be careful to not change current ring position */
3832 handle
->offset
= offset
;
3834 /* store the number of packets currently present in the ring */
3835 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
3839 #endif /* HAVE_PACKET_RING */
3842 #ifdef HAVE_PF_PACKET_SOCKETS
3844 * Return the index of the given device name. Fill ebuf and return
3848 iface_get_id(int fd
, const char *device
, char *ebuf
)
3852 memset(&ifr
, 0, sizeof(ifr
));
3853 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3855 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
3856 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3857 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
3861 return ifr
.ifr_ifindex
;
3865 * Bind the socket associated with FD to the given device.
3866 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3867 * or a PCAP_ERROR_ value on a hard error.
3870 iface_bind(int fd
, int ifindex
, char *ebuf
)
3872 struct sockaddr_ll sll
;
3874 socklen_t errlen
= sizeof(err
);
3876 memset(&sll
, 0, sizeof(sll
));
3877 sll
.sll_family
= AF_PACKET
;
3878 sll
.sll_ifindex
= ifindex
;
3879 sll
.sll_protocol
= htons(ETH_P_ALL
);
3881 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
3882 if (errno
== ENETDOWN
) {
3884 * Return a "network down" indication, so that
3885 * the application can report that rather than
3886 * saying we had a mysterious failure and
3887 * suggest that they report a problem to the
3888 * libpcap developers.
3890 return PCAP_ERROR_IFACE_NOT_UP
;
3892 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3893 "bind: %s", pcap_strerror(errno
));
3898 /* Any pending errors, e.g., network is down? */
3900 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3901 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3902 "getsockopt: %s", pcap_strerror(errno
));
3906 if (err
== ENETDOWN
) {
3908 * Return a "network down" indication, so that
3909 * the application can report that rather than
3910 * saying we had a mysterious failure and
3911 * suggest that they report a problem to the
3912 * libpcap developers.
3914 return PCAP_ERROR_IFACE_NOT_UP
;
3915 } else if (err
> 0) {
3916 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3917 "bind: %s", pcap_strerror(err
));
3924 #ifdef IW_MODE_MONITOR
3926 * Check whether the device supports the Wireless Extensions.
3927 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3928 * if the device doesn't even exist.
3931 has_wext(int sock_fd
, const char *device
, char *ebuf
)
3935 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3936 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3937 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3938 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
3940 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3941 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3942 if (errno
== ENODEV
)
3943 return PCAP_ERROR_NO_SUCH_DEVICE
;
3948 * Per me si va ne la citta dolente,
3949 * Per me si va ne l'etterno dolore,
3951 * Lasciate ogne speranza, voi ch'intrate.
3953 * XXX - airmon-ng does special stuff with the Orinoco driver and the
3969 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3970 * on if it's not already on.
3972 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3973 * on this device, or a PCAP_ERROR_ value if we do support them but
3974 * we weren't able to turn monitor mode on.
3977 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3980 * XXX - at least some adapters require non-Wireless Extensions
3981 * mechanisms to turn monitor mode on.
3983 * Atheros cards might require that a separate "monitor virtual access
3984 * point" be created, with later versions of the madwifi driver.
3985 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3986 * monitor -bssid", which apparently spits out a line "athN"
3987 * where "athN" is the monitor mode device. To leave monitor
3988 * mode, it destroys the monitor mode device.
3990 * Some Intel Centrino adapters might require private ioctls to get
3991 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3992 * configure a separate "rtapN" interface to capture in monitor
3993 * mode without preventing the adapter from operating normally.
3994 * (airmon-ng doesn't appear to use that, though.)
3996 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3997 * up, and if all drivers were converted to mac80211 drivers.
3999 * If interface {if} is a mac80211 driver, the file
4000 * /sys/class/net/{if}/phy80211 is a symlink to
4001 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4003 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4004 * least, has a "wmaster0" device and a "wlan0" device; the
4005 * latter is the one with the IP address. Both show up in
4006 * "tcpdump -D" output. Capturing on the wmaster0 device
4007 * captures with 802.11 headers.
4009 * airmon-ng searches through /sys/class/net for devices named
4010 * monN, starting with mon0; as soon as one *doesn't* exist,
4011 * it chooses that as the monitor device name. If the "iw"
4012 * command exists, it does "iw dev {if} interface add {monif}
4013 * type monitor", where {monif} is the monitor device. It
4014 * then (sigh) sleeps .1 second, and then configures the
4015 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4016 * is a file, it writes {mondev}, without a newline, to that file,
4017 * and again (sigh) sleeps .1 second, and then iwconfig's that
4018 * device into monitor mode and configures it up. Otherwise,
4019 * you can't do monitor mode.
4021 * All these devices are "glued" together by having the
4022 * /sys/class/net/{device}/phy80211 links pointing to the same
4023 * place, so, given a wmaster, wlan, or mon device, you can
4024 * find the other devices by looking for devices with
4025 * the same phy80211 link.
4027 * To turn monitor mode off, delete the monitor interface,
4028 * either with "iw dev {monif} interface del" or by sending
4029 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4031 * Note: if you try to create a monitor device named "monN", and
4032 * there's already a "monN" device, it fails, as least with
4033 * the netlink interface (which is what iw uses), with a return
4034 * value of -ENFILE. (Return values are negative errnos.) We
4035 * could probably use that to find an unused device.
4039 struct iw_priv_args
*priv
;
4040 monitor_type montype
;
4047 * Does this device *support* the Wireless Extensions?
4049 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4051 return err
; /* either it doesn't or the device doesn't even exist */
4053 * Try to get all the Wireless Extensions private ioctls
4054 * supported by this device.
4056 * First, get the size of the buffer we need, by supplying no
4057 * buffer and a length of 0. If the device supports private
4058 * ioctls, it should return E2BIG, with ireq.u.data.length set
4059 * to the length we need. If it doesn't support them, it should
4060 * return EOPNOTSUPP.
4062 memset(&ireq
, 0, sizeof ireq
);
4063 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4064 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4065 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4066 ireq
.u
.data
.pointer
= (void *)args
;
4067 ireq
.u
.data
.length
= 0;
4068 ireq
.u
.data
.flags
= 0;
4069 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4070 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4071 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4075 if (errno
== EOPNOTSUPP
) {
4077 * No private ioctls, so we assume that there's only one
4078 * DLT_ for monitor mode.
4082 if (errno
!= E2BIG
) {
4086 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4087 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4090 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4092 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4093 "malloc: %s", pcap_strerror(errno
));
4096 ireq
.u
.data
.pointer
= (void *)priv
;
4097 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4098 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4099 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4105 * Look for private ioctls to turn monitor mode on or, if
4106 * monitor mode is on, to set the header type.
4108 montype
= MONITOR_WEXT
;
4110 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4111 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4113 * Hostap driver, use this one.
4114 * Set monitor mode first.
4115 * You can set it to 0 to get DLT_IEEE80211,
4116 * 1 to get DLT_PRISM, 2 to get
4117 * DLT_IEEE80211_RADIO_AVS, and, with more
4118 * recent versions of the driver, 3 to get
4119 * DLT_IEEE80211_RADIO.
4121 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4123 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4125 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4127 montype
= MONITOR_HOSTAP
;
4131 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4133 * Prism54 driver, use this one.
4134 * Set monitor mode first.
4135 * You can set it to 2 to get DLT_IEEE80211
4136 * or 3 or get DLT_PRISM.
4138 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4140 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4142 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4144 montype
= MONITOR_PRISM54
;
4148 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4150 * RT2570 driver, use this one.
4151 * Do this after turning monitor mode on.
4152 * You can set it to 1 to get DLT_PRISM or 2
4153 * to get DLT_IEEE80211.
4155 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4157 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4159 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4161 montype
= MONITOR_RT2570
;
4165 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
4167 * RT73 driver, use this one.
4168 * Do this after turning monitor mode on.
4169 * Its argument is a *string*; you can
4170 * set it to "1" to get DLT_PRISM or "2"
4171 * to get DLT_IEEE80211.
4173 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
4175 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
4177 montype
= MONITOR_RT73
;
4181 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
4183 * One of the RTL8xxx drivers, use this one.
4184 * It can only be done after monitor mode
4185 * has been turned on. You can set it to 1
4186 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4188 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4190 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4192 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4194 montype
= MONITOR_RTL8XXX
;
4198 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
4200 * RT2500 or RT61 driver, use this one.
4201 * It has one one-byte parameter; set
4202 * u.data.length to 1 and u.data.pointer to
4203 * point to the parameter.
4204 * It doesn't itself turn monitor mode on.
4205 * You can set it to 1 to allow transmitting
4206 * in monitor mode(?) and get DLT_IEEE80211,
4207 * or set it to 0 to disallow transmitting in
4208 * monitor mode(?) and get DLT_PRISM.
4210 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4212 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
4214 montype
= MONITOR_RT2500
;
4218 if (strcmp(priv
[i
].name
, "monitor") == 0) {
4220 * Either ACX100 or hostap, use this one.
4221 * It turns monitor mode on.
4222 * If it takes two arguments, it's ACX100;
4223 * the first argument is 1 for DLT_PRISM
4224 * or 2 for DLT_IEEE80211, and the second
4225 * argument is the channel on which to
4226 * run. If it takes one argument, it's
4227 * HostAP, and the argument is 2 for
4228 * DLT_IEEE80211 and 3 for DLT_PRISM.
4230 * If we see this, we don't quit, as this
4231 * might be a version of the hostap driver
4232 * that also supports "monitor_type".
4234 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4236 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4238 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4241 montype
= MONITOR_PRISM
;
4246 montype
= MONITOR_ACX100
;
4258 * XXX - ipw3945? islism?
4264 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4265 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4266 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4267 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4269 * We probably won't be able to set the mode, either.
4271 return PCAP_ERROR_RFMON_NOTSUP
;
4275 * Is it currently in monitor mode?
4277 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4279 * Yes. Just leave things as they are.
4280 * We don't offer multiple link-layer types, as
4281 * changing the link-layer type out from under
4282 * somebody else capturing in monitor mode would
4283 * be considered rude.
4288 * No. We have to put the adapter into rfmon mode.
4292 * If we haven't already done so, arrange to have
4293 * "pcap_close_all()" called when we exit.
4295 if (!pcap_do_addexit(handle
)) {
4297 * "atexit()" failed; don't put the interface
4298 * in rfmon mode, just give up.
4300 return PCAP_ERROR_RFMON_NOTSUP
;
4304 * Save the old mode.
4306 handle
->md
.oldmode
= ireq
.u
.mode
;
4309 * Put the adapter in rfmon mode. How we do this depends
4310 * on whether we have a special private ioctl or not.
4312 if (montype
== MONITOR_PRISM
) {
4314 * We have the "monitor" private ioctl, but none of
4315 * the other private ioctls. Use this, and select
4318 * If it fails, just fall back on SIOCSIWMODE.
4320 memset(&ireq
, 0, sizeof ireq
);
4321 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4322 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4323 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4324 ireq
.u
.data
.length
= 1; /* 1 argument */
4325 args
[0] = 3; /* request Prism header */
4326 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4327 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4330 * Note that we have to put the old mode back
4331 * when we close the device.
4333 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4336 * Add this to the list of pcaps to close
4339 pcap_add_to_pcaps_to_close(handle
);
4345 * Failure. Fall back on SIOCSIWMODE.
4350 * First, turn monitor mode on.
4352 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4353 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4354 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4355 ireq
.u
.mode
= IW_MODE_MONITOR
;
4356 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4358 * Scientist, you've failed.
4360 return PCAP_ERROR_RFMON_NOTSUP
;
4364 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4365 * monitor mode and setting the channel, and then does
4370 * Now select the appropriate radio header.
4376 * We don't have any private ioctl to set the header.
4380 case MONITOR_HOSTAP
:
4382 * Try to select the radiotap header.
4384 memset(&ireq
, 0, sizeof ireq
);
4385 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4386 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4387 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4388 args
[0] = 3; /* request radiotap header */
4389 memcpy(ireq
.u
.name
, args
, sizeof (int));
4390 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4391 break; /* success */
4394 * That failed. Try to select the AVS header.
4396 memset(&ireq
, 0, sizeof ireq
);
4397 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4398 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4399 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4400 args
[0] = 2; /* request AVS header */
4401 memcpy(ireq
.u
.name
, args
, sizeof (int));
4402 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4403 break; /* success */
4406 * That failed. Try to select the Prism header.
4408 memset(&ireq
, 0, sizeof ireq
);
4409 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4410 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4411 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4412 args
[0] = 1; /* request Prism header */
4413 memcpy(ireq
.u
.name
, args
, sizeof (int));
4414 ioctl(sock_fd
, cmd
, &ireq
);
4419 * The private ioctl failed.
4423 case MONITOR_PRISM54
:
4425 * Select the Prism header.
4427 memset(&ireq
, 0, sizeof ireq
);
4428 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4429 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4430 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4431 args
[0] = 3; /* request Prism header */
4432 memcpy(ireq
.u
.name
, args
, sizeof (int));
4433 ioctl(sock_fd
, cmd
, &ireq
);
4436 case MONITOR_ACX100
:
4438 * Get the current channel.
4440 memset(&ireq
, 0, sizeof ireq
);
4441 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4442 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4443 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4444 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4445 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4446 "%s: SIOCGIWFREQ: %s", device
,
4447 pcap_strerror(errno
));
4450 channel
= ireq
.u
.freq
.m
;
4453 * Select the Prism header, and set the channel to the
4456 memset(&ireq
, 0, sizeof ireq
);
4457 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4458 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4459 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4460 args
[0] = 1; /* request Prism header */
4461 args
[1] = channel
; /* set channel */
4462 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4463 ioctl(sock_fd
, cmd
, &ireq
);
4466 case MONITOR_RT2500
:
4468 * Disallow transmission - that turns on the
4471 memset(&ireq
, 0, sizeof ireq
);
4472 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4473 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4474 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4475 args
[0] = 0; /* disallow transmitting */
4476 memcpy(ireq
.u
.name
, args
, sizeof (int));
4477 ioctl(sock_fd
, cmd
, &ireq
);
4480 case MONITOR_RT2570
:
4482 * Force the Prism header.
4484 memset(&ireq
, 0, sizeof ireq
);
4485 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4486 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4487 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4488 args
[0] = 1; /* request Prism header */
4489 memcpy(ireq
.u
.name
, args
, sizeof (int));
4490 ioctl(sock_fd
, cmd
, &ireq
);
4495 * Force the Prism header.
4497 memset(&ireq
, 0, sizeof ireq
);
4498 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4499 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4500 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4501 ireq
.u
.data
.length
= 1; /* 1 argument */
4502 ireq
.u
.data
.pointer
= "1";
4503 ireq
.u
.data
.flags
= 0;
4504 ioctl(sock_fd
, cmd
, &ireq
);
4507 case MONITOR_RTL8XXX
:
4509 * Force the Prism header.
4511 memset(&ireq
, 0, sizeof ireq
);
4512 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4513 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4514 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4515 args
[0] = 1; /* request Prism header */
4516 memcpy(ireq
.u
.name
, args
, sizeof (int));
4517 ioctl(sock_fd
, cmd
, &ireq
);
4522 * Note that we have to put the old mode back when we
4525 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4528 * Add this to the list of pcaps to close when we exit.
4530 pcap_add_to_pcaps_to_close(handle
);
4534 #endif /* IW_MODE_MONITOR */
4537 * Try various mechanisms to enter monitor mode.
4540 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4542 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4547 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4549 return ret
; /* error attempting to do so */
4551 return 1; /* success */
4552 #endif /* HAVE_LIBNL */
4554 #ifdef IW_MODE_MONITOR
4555 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4557 return ret
; /* error attempting to do so */
4559 return 1; /* success */
4560 #endif /* IW_MODE_MONITOR */
4563 * Either none of the mechanisms we know about work or none
4564 * of those mechanisms are available, so we can't do monitor
4570 #endif /* HAVE_PF_PACKET_SOCKETS */
4572 /* ===== Functions to interface to the older kernels ================== */
4575 * Try to open a packet socket using the old kernel interface.
4576 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4579 activate_old(pcap_t
*handle
)
4583 const char *device
= handle
->opt
.source
;
4584 struct utsname utsname
;
4587 /* Open the socket */
4589 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
4590 if (handle
->fd
== -1) {
4591 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4592 "socket: %s", pcap_strerror(errno
));
4593 return PCAP_ERROR_PERM_DENIED
;
4596 /* It worked - we are using the old interface */
4597 handle
->md
.sock_packet
= 1;
4599 /* ...which means we get the link-layer header. */
4600 handle
->md
.cooked
= 0;
4602 /* Bind to the given device */
4604 if (strcmp(device
, "any") == 0) {
4605 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4609 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
4613 * Try to get the link-layer type.
4615 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
4620 * Try to find the DLT_ type corresponding to that
4623 map_arphrd_to_dlt(handle
, arptype
, 0);
4624 if (handle
->linktype
== -1) {
4625 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4626 "unknown arptype %d", arptype
);
4630 /* Go to promisc mode if requested */
4632 if (handle
->opt
.promisc
) {
4633 memset(&ifr
, 0, sizeof(ifr
));
4634 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4635 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4636 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4637 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
4640 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
4642 * Promiscuous mode isn't currently on,
4643 * so turn it on, and remember that
4644 * we should turn it off when the
4649 * If we haven't already done so, arrange
4650 * to have "pcap_close_all()" called when
4653 if (!pcap_do_addexit(handle
)) {
4655 * "atexit()" failed; don't put
4656 * the interface in promiscuous
4657 * mode, just give up.
4662 ifr
.ifr_flags
|= IFF_PROMISC
;
4663 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4664 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4666 pcap_strerror(errno
));
4669 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
4672 * Add this to the list of pcaps
4673 * to close when we exit.
4675 pcap_add_to_pcaps_to_close(handle
);
4680 * Compute the buffer size.
4682 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4683 * kernel, and might require special handling - check.
4685 if (uname(&utsname
) < 0 ||
4686 strncmp(utsname
.release
, "2.0", 3) == 0) {
4688 * Either we couldn't find out what kernel release
4689 * this is, or it's a 2.0[.x] kernel.
4691 * In the 2.0[.x] kernel, a "recvfrom()" on
4692 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4693 * return the number of bytes read, so if we pass
4694 * a length based on the snapshot length, it'll
4695 * return the number of bytes from the packet
4696 * copied to userland, not the actual length
4699 * This means that, for example, the IP dissector
4700 * in tcpdump will get handed a packet length less
4701 * than the length in the IP header, and will
4702 * complain about "truncated-ip".
4704 * So we don't bother trying to copy from the
4705 * kernel only the bytes in which we're interested,
4706 * but instead copy them all, just as the older
4707 * versions of libpcap for Linux did.
4709 * The buffer therefore needs to be big enough to
4710 * hold the largest packet we can get from this
4711 * device. Unfortunately, we can't get the MRU
4712 * of the network; we can only get the MTU. The
4713 * MTU may be too small, in which case a packet larger
4714 * than the buffer size will be truncated *and* we
4715 * won't get the actual packet size.
4717 * However, if the snapshot length is larger than
4718 * the buffer size based on the MTU, we use the
4719 * snapshot length as the buffer size, instead;
4720 * this means that with a sufficiently large snapshot
4721 * length we won't artificially truncate packets
4722 * to the MTU-based size.
4724 * This mess just one of many problems with packet
4725 * capture on 2.0[.x] kernels; you really want a
4726 * 2.2[.x] or later kernel if you want packet capture
4729 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
4732 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
4733 if (handle
->bufsize
< handle
->snapshot
)
4734 handle
->bufsize
= handle
->snapshot
;
4737 * This is a 2.2[.x] or later kernel.
4739 * We can safely pass "recvfrom()" a byte count
4740 * based on the snapshot length.
4742 handle
->bufsize
= handle
->snapshot
;
4746 * Default value for offset to align link-layer payload
4747 * on a 4-byte boundary.
4755 * Bind the socket associated with FD to the given device using the
4756 * interface of the old kernels.
4759 iface_bind_old(int fd
, const char *device
, char *ebuf
)
4761 struct sockaddr saddr
;
4763 socklen_t errlen
= sizeof(err
);
4765 memset(&saddr
, 0, sizeof(saddr
));
4766 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
4767 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
4768 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4769 "bind: %s", pcap_strerror(errno
));
4773 /* Any pending errors, e.g., network is down? */
4775 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4776 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4777 "getsockopt: %s", pcap_strerror(errno
));
4782 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4783 "bind: %s", pcap_strerror(err
));
4791 /* ===== System calls available on all supported kernels ============== */
4794 * Query the kernel for the MTU of the given interface.
4797 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
4802 return BIGGER_THAN_ALL_MTUS
;
4804 memset(&ifr
, 0, sizeof(ifr
));
4805 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4807 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
4808 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4809 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4817 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4820 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4824 memset(&ifr
, 0, sizeof(ifr
));
4825 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4827 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4828 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4829 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4830 if (errno
== ENODEV
) {
4834 return PCAP_ERROR_NO_SUCH_DEVICE
;
4839 return ifr
.ifr_hwaddr
.sa_family
;
4842 #ifdef SO_ATTACH_FILTER
4844 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
4848 register struct bpf_insn
*p
;
4853 * Make a copy of the filter, and modify that copy if
4856 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4857 len
= handle
->fcode
.bf_len
;
4858 f
= (struct bpf_insn
*)malloc(prog_size
);
4860 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4861 "malloc: %s", pcap_strerror(errno
));
4864 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4866 fcode
->filter
= (struct sock_filter
*) f
;
4868 for (i
= 0; i
< len
; ++i
) {
4871 * What type of instruction is this?
4873 switch (BPF_CLASS(p
->code
)) {
4877 * It's a return instruction; are we capturing
4878 * in memory-mapped mode?
4882 * No; is the snapshot length a constant,
4883 * rather than the contents of the
4886 if (BPF_MODE(p
->code
) == BPF_K
) {
4888 * Yes - if the value to be returned,
4889 * i.e. the snapshot length, is
4890 * anything other than 0, make it
4891 * 65535, so that the packet is
4892 * truncated by "recvfrom()",
4893 * not by the filter.
4895 * XXX - there's nothing we can
4896 * easily do if it's getting the
4897 * value from the accumulator; we'd
4898 * have to insert code to force
4899 * non-zero values to be 65535.
4910 * It's a load instruction; is it loading
4913 switch (BPF_MODE(p
->code
)) {
4919 * Yes; are we in cooked mode?
4921 if (handle
->md
.cooked
) {
4923 * Yes, so we need to fix this
4926 if (fix_offset(p
) < 0) {
4928 * We failed to do so.
4929 * Return 0, so our caller
4930 * knows to punt to userland.
4940 return 1; /* we succeeded */
4944 fix_offset(struct bpf_insn
*p
)
4947 * What's the offset?
4949 if (p
->k
>= SLL_HDR_LEN
) {
4951 * It's within the link-layer payload; that starts at an
4952 * offset of 0, as far as the kernel packet filter is
4953 * concerned, so subtract the length of the link-layer
4956 p
->k
-= SLL_HDR_LEN
;
4957 } else if (p
->k
== 14) {
4959 * It's the protocol field; map it to the special magic
4960 * kernel offset for that field.
4962 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4965 * It's within the header, but it's not one of those
4966 * fields; we can't do that in the kernel, so punt
4975 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4977 int total_filter_on
= 0;
4983 * The socket filter code doesn't discard all packets queued
4984 * up on the socket when the filter is changed; this means
4985 * that packets that don't match the new filter may show up
4986 * after the new filter is put onto the socket, if those
4987 * packets haven't yet been read.
4989 * This means, for example, that if you do a tcpdump capture
4990 * with a filter, the first few packets in the capture might
4991 * be packets that wouldn't have passed the filter.
4993 * We therefore discard all packets queued up on the socket
4994 * when setting a kernel filter. (This isn't an issue for
4995 * userland filters, as the userland filtering is done after
4996 * packets are queued up.)
4998 * To flush those packets, we put the socket in read-only mode,
4999 * and read packets from the socket until there are no more to
5002 * In order to keep that from being an infinite loop - i.e.,
5003 * to keep more packets from arriving while we're draining
5004 * the queue - we put the "total filter", which is a filter
5005 * that rejects all packets, onto the socket before draining
5008 * This code deliberately ignores any errors, so that you may
5009 * get bogus packets if an error occurs, rather than having
5010 * the filtering done in userland even if it could have been
5011 * done in the kernel.
5013 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5014 &total_fcode
, sizeof(total_fcode
)) == 0) {
5018 * Note that we've put the total filter onto the socket.
5020 total_filter_on
= 1;
5023 * Save the socket's current mode, and put it in
5024 * non-blocking mode; we drain it by reading packets
5025 * until we get an error (which is normally a
5026 * "nothing more to be read" error).
5028 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5029 if (save_mode
!= -1 &&
5030 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
5031 while (recv(handle
->fd
, &drain
, sizeof drain
,
5035 fcntl(handle
->fd
, F_SETFL
, save_mode
);
5036 if (save_errno
!= EAGAIN
) {
5038 reset_kernel_filter(handle
);
5039 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5040 "recv: %s", pcap_strerror(save_errno
));
5047 * Now attach the new filter.
5049 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5050 fcode
, sizeof(*fcode
));
5051 if (ret
== -1 && total_filter_on
) {
5053 * Well, we couldn't set that filter on the socket,
5054 * but we could set the total filter on the socket.
5056 * This could, for example, mean that the filter was
5057 * too big to put into the kernel, so we'll have to
5058 * filter in userland; in any case, we'll be doing
5059 * filtering in userland, so we need to remove the
5060 * total filter so we see packets.
5065 * XXX - if this fails, we're really screwed;
5066 * we have the total filter on the socket,
5067 * and it won't come off. What do we do then?
5069 reset_kernel_filter(handle
);
5077 reset_kernel_filter(pcap_t
*handle
)
5080 * setsockopt() barfs unless it get a dummy parameter.
5081 * valgrind whines unless the value is initialized,
5082 * as it has no idea that setsockopt() ignores its
5087 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5088 &dummy
, sizeof(dummy
));