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 #ifndef HAVE_LIBNL_2_x
531 /* libnl 2.x compatibility code */
533 #define nl_sock nl_handle
535 static inline struct nl_handle
*
536 nl_socket_alloc(void)
538 return nl_handle_alloc();
542 nl_socket_free(struct nl_handle
*h
)
544 nl_handle_destroy(h
);
548 __genl_ctrl_alloc_cache(struct nl_handle
*h
, struct nl_cache
**cache
)
550 struct nl_cache
*tmp
= genl_ctrl_alloc_cache(h
);
556 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
557 #endif /* !HAVE_LIBNL_2_x */
559 struct nl80211_state
{
560 struct nl_sock
*nl_sock
;
561 struct nl_cache
*nl_cache
;
562 struct genl_family
*nl80211
;
566 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
570 state
->nl_sock
= nl_socket_alloc();
571 if (!state
->nl_sock
) {
572 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
573 "%s: failed to allocate netlink handle", device
);
577 if (genl_connect(state
->nl_sock
)) {
578 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
579 "%s: failed to connect to generic netlink", device
);
580 goto out_handle_destroy
;
583 err
= genl_ctrl_alloc_cache(state
->nl_sock
, &state
->nl_cache
);
585 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
586 "%s: failed to allocate generic netlink cache: %s",
587 device
, strerror(-err
));
588 goto out_handle_destroy
;
591 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
592 if (!state
->nl80211
) {
593 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
594 "%s: nl80211 not found", device
);
601 nl_cache_free(state
->nl_cache
);
603 nl_socket_free(state
->nl_sock
);
608 nl80211_cleanup(struct nl80211_state
*state
)
610 genl_family_put(state
->nl80211
);
611 nl_cache_free(state
->nl_cache
);
612 nl_socket_free(state
->nl_sock
);
616 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
617 const char *device
, const char *mondevice
)
623 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
629 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
630 "%s: failed to allocate netlink msg", device
);
634 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
635 0, NL80211_CMD_NEW_INTERFACE
, 0);
636 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
637 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
638 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
640 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
642 if (err
== -ENFILE
) {
644 * Device not available; our caller should just
651 * Real failure, not just "that device is not
654 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
655 "%s: nl_send_auto_complete failed adding %s interface: %s",
656 device
, mondevice
, strerror(-err
));
661 err
= nl_wait_for_ack(state
->nl_sock
);
663 if (err
== -ENFILE
) {
665 * Device not available; our caller should just
672 * Real failure, not just "that device is not
675 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
676 "%s: nl_wait_for_ack failed adding %s interface: %s",
677 device
, mondevice
, strerror(-err
));
690 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
691 "%s: nl_put failed adding %s interface",
698 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
699 const char *device
, const char *mondevice
)
705 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
711 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
712 "%s: failed to allocate netlink msg", device
);
716 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
717 0, NL80211_CMD_DEL_INTERFACE
, 0);
718 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
720 err
= nl_send_auto_complete(state
->nl_sock
, msg
);
722 if (err
== -ENFILE
) {
724 * Device not available; our caller should just
731 * Real failure, not just "that device is not
734 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
735 "%s: nl_send_auto_complete failed deleting %s interface: %s",
736 device
, mondevice
, strerror(-err
));
741 err
= nl_wait_for_ack(state
->nl_sock
);
743 if (err
== -ENFILE
) {
745 * Device not available; our caller should just
752 * Real failure, not just "that device is not
755 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
756 "%s: nl_wait_for_ack failed adding %s interface: %s",
757 device
, mondevice
, strerror(-err
));
770 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
771 "%s: nl_put failed deleting %s interface",
778 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
781 char phydev_path
[PATH_MAX
+1];
782 struct nl80211_state nlstate
;
787 * Is this a mac80211 device?
789 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
791 return ret
; /* error */
793 return 0; /* no error, but not mac80211 device */
796 * XXX - is this already a monN device?
798 * Is that determined by old Wireless Extensions ioctls?
802 * OK, it's apparently a mac80211 device.
803 * Try to find an unused monN device for it.
805 ret
= nl80211_init(handle
, &nlstate
, device
);
808 for (n
= 0; n
< UINT_MAX
; n
++) {
812 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
814 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
815 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
817 handle
->md
.mondevice
= strdup(mondevice
);
822 * Hard failure. Just return ret; handle->errbuf
823 * has already been set.
825 nl80211_cleanup(&nlstate
);
830 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
831 "%s: No free monN interfaces", device
);
832 nl80211_cleanup(&nlstate
);
839 * Sleep for .1 seconds.
842 delay
.tv_nsec
= 500000000;
843 nanosleep(&delay
, NULL
);
847 * Now configure the monitor interface up.
849 memset(&ifr
, 0, sizeof(ifr
));
850 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
851 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
852 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
853 "%s: Can't get flags for %s: %s", device
,
854 handle
->md
.mondevice
, strerror(errno
));
855 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
856 handle
->md
.mondevice
);
857 nl80211_cleanup(&nlstate
);
860 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
861 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
862 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
863 "%s: Can't set flags for %s: %s", device
,
864 handle
->md
.mondevice
, strerror(errno
));
865 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
866 handle
->md
.mondevice
);
867 nl80211_cleanup(&nlstate
);
872 * Success. Clean up the libnl state.
874 nl80211_cleanup(&nlstate
);
877 * Note that we have to delete the monitor device when we close
880 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
883 * Add this to the list of pcaps to close when we exit.
885 pcap_add_to_pcaps_to_close(handle
);
889 #endif /* HAVE_LIBNL */
892 pcap_can_set_rfmon_linux(pcap_t
*handle
)
895 char phydev_path
[PATH_MAX
+1];
898 #ifdef IW_MODE_MONITOR
903 if (strcmp(handle
->opt
.source
, "any") == 0) {
905 * Monitor mode makes no sense on the "any" device.
912 * Bleah. There doesn't seem to be a way to ask a mac80211
913 * device, through libnl, whether it supports monitor mode;
914 * we'll just check whether the device appears to be a
915 * mac80211 device and, if so, assume the device supports
918 * wmaster devices don't appear to support the Wireless
919 * Extensions, but we can create a mon device for a
920 * wmaster device, so we don't bother checking whether
921 * a mac80211 device supports the Wireless Extensions.
923 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
926 return ret
; /* error */
928 return 1; /* mac80211 device */
931 #ifdef IW_MODE_MONITOR
933 * Bleah. There doesn't appear to be an ioctl to use to ask
934 * whether a device supports monitor mode; we'll just do
935 * SIOCGIWMODE and, if it succeeds, assume the device supports
938 * Open a socket on which to attempt to get the mode.
939 * (We assume that if we have Wireless Extensions support
940 * we also have PF_PACKET support.)
942 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
944 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
945 "socket: %s", pcap_strerror(errno
));
950 * Attempt to get the current mode.
952 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
953 sizeof ireq
.ifr_ifrn
.ifrn_name
);
954 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
955 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
957 * Well, we got the mode; assume we can set it.
962 if (errno
== ENODEV
) {
963 /* The device doesn't even exist. */
964 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
965 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
967 return PCAP_ERROR_NO_SUCH_DEVICE
;
975 * Grabs the number of dropped packets by the interface from /proc/net/dev.
977 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
978 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
980 * Or can we get them in binary form from netlink?
983 linux_if_drops(const char * if_name
)
988 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
989 long int dropped_pkts
= 0;
991 file
= fopen("/proc/net/dev", "r");
995 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
997 /* search for 'bytes' -- if its in there, then
998 that means we need to grab the fourth field. otherwise
999 grab the third field. */
1000 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
1002 field_to_convert
= 4;
1006 /* find iface and make sure it actually matches -- space before the name and : after it */
1007 if ((bufptr
= strstr(buffer
, if_name
)) &&
1008 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
1009 *(bufptr
+ if_name_sz
) == ':')
1011 bufptr
= bufptr
+ if_name_sz
+ 1;
1013 /* grab the nth field from it */
1014 while( --field_to_convert
&& *bufptr
!= '\0')
1016 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
1017 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
1020 /* get rid of any final spaces */
1021 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
1023 if (*bufptr
!= '\0')
1024 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1031 return dropped_pkts
;
1036 * With older kernels promiscuous mode is kind of interesting because we
1037 * have to reset the interface before exiting. The problem can't really
1038 * be solved without some daemon taking care of managing usage counts.
1039 * If we put the interface into promiscuous mode, we set a flag indicating
1040 * that we must take it out of that mode when the interface is closed,
1041 * and, when closing the interface, if that flag is set we take it out
1042 * of promiscuous mode.
1044 * Even with newer kernels, we have the same issue with rfmon mode.
1047 static void pcap_cleanup_linux( pcap_t
*handle
)
1051 struct nl80211_state nlstate
;
1053 #endif /* HAVE_LIBNL */
1054 #ifdef IW_MODE_MONITOR
1056 #endif /* IW_MODE_MONITOR */
1058 if (handle
->md
.must_do_on_close
!= 0) {
1060 * There's something we have to do when closing this
1063 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
1065 * We put the interface into promiscuous mode;
1066 * take it out of promiscuous mode.
1068 * XXX - if somebody else wants it in promiscuous
1069 * mode, this code cannot know that, so it'll take
1070 * it out of promiscuous mode. That's not fixable
1071 * in 2.0[.x] kernels.
1073 memset(&ifr
, 0, sizeof(ifr
));
1074 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1075 sizeof(ifr
.ifr_name
));
1076 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1078 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1079 "Please adjust manually.\n"
1080 "Hint: This can't happen with Linux >= 2.2.0.\n",
1083 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1085 * Promiscuous mode is currently on;
1088 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1089 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1092 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1093 "Please adjust manually.\n"
1094 "Hint: This can't happen with Linux >= 2.2.0.\n",
1102 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1103 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1105 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1106 handle
->md
.device
, handle
->md
.mondevice
);
1107 nl80211_cleanup(&nlstate
);
1111 "Can't delete monitor interface %s (%s).\n"
1112 "Please delete manually.\n",
1113 handle
->md
.mondevice
, handle
->errbuf
);
1116 #endif /* HAVE_LIBNL */
1118 #ifdef IW_MODE_MONITOR
1119 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1121 * We put the interface into rfmon mode;
1122 * take it out of rfmon mode.
1124 * XXX - if somebody else wants it in rfmon
1125 * mode, this code cannot know that, so it'll take
1126 * it out of rfmon mode.
1128 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1129 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1130 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1132 ireq
.u
.mode
= handle
->md
.oldmode
;
1133 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1135 * Scientist, you've failed.
1138 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1139 "Please adjust manually.\n",
1143 #endif /* IW_MODE_MONITOR */
1146 * Take this pcap out of the list of pcaps for which we
1147 * have to take the interface out of some mode.
1149 pcap_remove_from_pcaps_to_close(handle
);
1152 if (handle
->md
.mondevice
!= NULL
) {
1153 free(handle
->md
.mondevice
);
1154 handle
->md
.mondevice
= NULL
;
1156 if (handle
->md
.device
!= NULL
) {
1157 free(handle
->md
.device
);
1158 handle
->md
.device
= NULL
;
1160 pcap_cleanup_live_common(handle
);
1164 * Get a handle for a live capture from the given device. You can
1165 * pass NULL as device to get all packages (without link level
1166 * information of course). If you pass 1 as promisc the interface
1167 * will be set to promiscous mode (XXX: I think this usage should
1168 * be deprecated and functions be added to select that later allow
1169 * modification of that values -- Torsten).
1172 pcap_activate_linux(pcap_t
*handle
)
1177 device
= handle
->opt
.source
;
1179 handle
->inject_op
= pcap_inject_linux
;
1180 handle
->setfilter_op
= pcap_setfilter_linux
;
1181 handle
->setdirection_op
= pcap_setdirection_linux
;
1182 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1183 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1184 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1185 handle
->cleanup_op
= pcap_cleanup_linux
;
1186 handle
->read_op
= pcap_read_linux
;
1187 handle
->stats_op
= pcap_stats_linux
;
1190 * The "any" device is a special device which causes us not
1191 * to bind to a particular device and thus to look at all
1194 if (strcmp(device
, "any") == 0) {
1195 if (handle
->opt
.promisc
) {
1196 handle
->opt
.promisc
= 0;
1197 /* Just a warning. */
1198 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1199 "Promiscuous mode not supported on the \"any\" device");
1200 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1204 handle
->md
.device
= strdup(device
);
1205 if (handle
->md
.device
== NULL
) {
1206 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1207 pcap_strerror(errno
) );
1212 * If we're in promiscuous mode, then we probably want
1213 * to see when the interface drops packets too, so get an
1214 * initial count from /proc/net/dev
1216 if (handle
->opt
.promisc
)
1217 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1220 * Current Linux kernels use the protocol family PF_PACKET to
1221 * allow direct access to all packets on the network while
1222 * older kernels had a special socket type SOCK_PACKET to
1223 * implement this feature.
1224 * While this old implementation is kind of obsolete we need
1225 * to be compatible with older kernels for a while so we are
1226 * trying both methods with the newer method preferred.
1228 status
= activate_new(handle
);
1231 * Fatal error with the new way; just fail.
1232 * status has the error return; if it's PCAP_ERROR,
1233 * handle->errbuf has been set appropriately.
1240 * Try to use memory-mapped access.
1242 switch (activate_mmap(handle
, &status
)) {
1246 * We succeeded. status has been
1247 * set to the status to return,
1248 * which might be 0, or might be
1249 * a PCAP_WARNING_ value.
1255 * Kernel doesn't support it - just continue
1256 * with non-memory-mapped access.
1262 * We failed to set up to use it, or the kernel
1263 * supports it, but we failed to enable it.
1264 * status has been set to the error status to
1265 * return and, if it's PCAP_ERROR, handle->errbuf
1266 * contains the error message.
1271 else if (status
== 0) {
1272 /* Non-fatal error; try old way */
1273 if ((status
= activate_old(handle
)) != 1) {
1275 * Both methods to open the packet socket failed.
1276 * Tidy up and report our failure (handle->errbuf
1277 * is expected to be set by the functions above).
1284 * We set up the socket, but not with memory-mapped access.
1287 if (handle
->opt
.buffer_size
!= 0) {
1289 * Set the socket buffer size to the specified value.
1291 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1292 &handle
->opt
.buffer_size
,
1293 sizeof(handle
->opt
.buffer_size
)) == -1) {
1294 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1295 "SO_RCVBUF: %s", pcap_strerror(errno
));
1296 status
= PCAP_ERROR
;
1301 /* Allocate the buffer */
1303 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1304 if (!handle
->buffer
) {
1305 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1306 "malloc: %s", pcap_strerror(errno
));
1307 status
= PCAP_ERROR
;
1312 * "handle->fd" is a socket, so "select()" and "poll()"
1313 * should work on it.
1315 handle
->selectable_fd
= handle
->fd
;
1320 pcap_cleanup_linux(handle
);
1325 * Read at most max_packets from the capture stream and call the callback
1326 * for each of them. Returns the number of packets handled or -1 if an
1330 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1333 * Currently, on Linux only one packet is delivered per read,
1336 return pcap_read_packet(handle
, callback
, user
);
1340 * Read a packet from the socket calling the handler provided by
1341 * the user. Returns the number of packets received or -1 if an
1345 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1349 #ifdef HAVE_PF_PACKET_SOCKETS
1350 struct sockaddr_ll from
;
1351 struct sll_header
*hdrp
;
1353 struct sockaddr from
;
1355 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1358 struct cmsghdr
*cmsg
;
1360 struct cmsghdr cmsg
;
1361 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1363 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1365 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1366 int packet_len
, caplen
;
1367 struct pcap_pkthdr pcap_header
;
1369 #ifdef HAVE_PF_PACKET_SOCKETS
1371 * If this is a cooked device, leave extra room for a
1372 * fake packet header.
1374 if (handle
->md
.cooked
)
1375 offset
= SLL_HDR_LEN
;
1380 * This system doesn't have PF_PACKET sockets, so it doesn't
1381 * support cooked devices.
1387 * Receive a single packet from the kernel.
1388 * We ignore EINTR, as that might just be due to a signal
1389 * being delivered - if the signal should interrupt the
1390 * loop, the signal handler should call pcap_breakloop()
1391 * to set handle->break_loop (we ignore it on other
1392 * platforms as well).
1393 * We also ignore ENETDOWN, so that we can continue to
1394 * capture traffic if the interface goes down and comes
1395 * back up again; comments in the kernel indicate that
1396 * we'll just block waiting for packets if we try to
1397 * receive from a socket that delivered ENETDOWN, and,
1398 * if we're using a memory-mapped buffer, we won't even
1399 * get notified of "network down" events.
1401 bp
= handle
->buffer
+ handle
->offset
;
1403 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1404 msg
.msg_name
= &from
;
1405 msg
.msg_namelen
= sizeof(from
);
1408 msg
.msg_control
= &cmsg_buf
;
1409 msg
.msg_controllen
= sizeof(cmsg_buf
);
1412 iov
.iov_len
= handle
->bufsize
- offset
;
1413 iov
.iov_base
= bp
+ offset
;
1414 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1418 * Has "pcap_breakloop()" been called?
1420 if (handle
->break_loop
) {
1422 * Yes - clear the flag that indicates that it has,
1423 * and return PCAP_ERROR_BREAK as an indication that
1424 * we were told to break out of the loop.
1426 handle
->break_loop
= 0;
1427 return PCAP_ERROR_BREAK
;
1430 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1431 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1432 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1433 fromlen
= sizeof(from
);
1434 packet_len
= recvfrom(
1435 handle
->fd
, bp
+ offset
,
1436 handle
->bufsize
- offset
, MSG_TRUNC
,
1437 (struct sockaddr
*) &from
, &fromlen
);
1438 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1439 } while (packet_len
== -1 && errno
== EINTR
);
1441 /* Check if an error occured */
1443 if (packet_len
== -1) {
1447 return 0; /* no packet there */
1451 * The device on which we're capturing went away.
1453 * XXX - we should really return
1454 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1455 * etc. aren't defined to return that.
1457 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1458 "The interface went down");
1462 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1463 "recvfrom: %s", pcap_strerror(errno
));
1468 #ifdef HAVE_PF_PACKET_SOCKETS
1469 if (!handle
->md
.sock_packet
) {
1471 * Unfortunately, there is a window between socket() and
1472 * bind() where the kernel may queue packets from any
1473 * interface. If we're bound to a particular interface,
1474 * discard packets not from that interface.
1476 * (If socket filters are supported, we could do the
1477 * same thing we do when changing the filter; however,
1478 * that won't handle packet sockets without socket
1479 * filter support, and it's a bit more complicated.
1480 * It would save some instructions per packet, however.)
1482 if (handle
->md
.ifindex
!= -1 &&
1483 from
.sll_ifindex
!= handle
->md
.ifindex
)
1487 * Do checks based on packet direction.
1488 * We can only do this if we're using PF_PACKET; the
1489 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1490 * which lacks the relevant packet type information.
1492 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1495 * If this is from the loopback device, reject it;
1496 * we'll see the packet as an incoming packet as well,
1497 * and we don't want to see it twice.
1499 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1503 * If the user only wants incoming packets, reject it.
1505 if (handle
->direction
== PCAP_D_IN
)
1510 * If the user only wants outgoing packets, reject it.
1512 if (handle
->direction
== PCAP_D_OUT
)
1518 #ifdef HAVE_PF_PACKET_SOCKETS
1520 * If this is a cooked device, fill in the fake packet header.
1522 if (handle
->md
.cooked
) {
1524 * Add the length of the fake header to the length
1525 * of packet data we read.
1527 packet_len
+= SLL_HDR_LEN
;
1529 hdrp
= (struct sll_header
*)bp
;
1530 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1531 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1532 hdrp
->sll_halen
= htons(from
.sll_halen
);
1533 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1534 (from
.sll_halen
> SLL_ADDRLEN
) ?
1537 hdrp
->sll_protocol
= from
.sll_protocol
;
1540 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1541 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1542 struct tpacket_auxdata
*aux
;
1544 struct vlan_tag
*tag
;
1546 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1547 cmsg
->cmsg_level
!= SOL_PACKET
||
1548 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1551 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1552 if (aux
->tp_vlan_tci
== 0)
1555 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1556 if (len
< 2 * ETH_ALEN
)
1560 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1562 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1563 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1564 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1566 packet_len
+= VLAN_TAG_LEN
;
1568 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1569 #endif /* HAVE_PF_PACKET_SOCKETS */
1572 * XXX: According to the kernel source we should get the real
1573 * packet len if calling recvfrom with MSG_TRUNC set. It does
1574 * not seem to work here :(, but it is supported by this code
1576 * To be honest the code RELIES on that feature so this is really
1577 * broken with 2.2.x kernels.
1578 * I spend a day to figure out what's going on and I found out
1579 * that the following is happening:
1581 * The packet comes from a random interface and the packet_rcv
1582 * hook is called with a clone of the packet. That code inserts
1583 * the packet into the receive queue of the packet socket.
1584 * If a filter is attached to that socket that filter is run
1585 * first - and there lies the problem. The default filter always
1586 * cuts the packet at the snaplen:
1591 * So the packet filter cuts down the packet. The recvfrom call
1592 * says "hey, it's only 68 bytes, it fits into the buffer" with
1593 * the result that we don't get the real packet length. This
1594 * is valid at least until kernel 2.2.17pre6.
1596 * We currently handle this by making a copy of the filter
1597 * program, fixing all "ret" instructions with non-zero
1598 * operands to have an operand of 65535 so that the filter
1599 * doesn't truncate the packet, and supplying that modified
1600 * filter to the kernel.
1603 caplen
= packet_len
;
1604 if (caplen
> handle
->snapshot
)
1605 caplen
= handle
->snapshot
;
1607 /* Run the packet filter if not using kernel filter */
1608 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1609 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1610 packet_len
, caplen
) == 0)
1612 /* rejected by filter */
1617 /* Fill in our own header data */
1619 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1620 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1621 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1624 pcap_header
.caplen
= caplen
;
1625 pcap_header
.len
= packet_len
;
1630 * Arguably, we should count them before we check the filter,
1631 * as on many other platforms "ps_recv" counts packets
1632 * handed to the filter rather than packets that passed
1633 * the filter, but if filtering is done in the kernel, we
1634 * can't get a count of packets that passed the filter,
1635 * and that would mean the meaning of "ps_recv" wouldn't
1636 * be the same on all Linux systems.
1638 * XXX - it's not the same on all systems in any case;
1639 * ideally, we should have a "get the statistics" call
1640 * that supplies more counts and indicates which of them
1641 * it supplies, so that we supply a count of packets
1642 * handed to the filter only on platforms where that
1643 * information is available.
1645 * We count them here even if we can get the packet count
1646 * from the kernel, as we can only determine at run time
1647 * whether we'll be able to get it from the kernel (if
1648 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1649 * the kernel, but if it is defined, the library might
1650 * have been built with a 2.4 or later kernel, but we
1651 * might be running on a 2.2[.x] kernel without Alexey
1652 * Kuznetzov's turbopacket patches, and thus the kernel
1653 * might not be able to supply those statistics). We
1654 * could, I guess, try, when opening the socket, to get
1655 * the statistics, and if we can not increment the count
1656 * here, but it's not clear that always incrementing
1657 * the count is more expensive than always testing a flag
1660 * We keep the count in "md.packets_read", and use that for
1661 * "ps_recv" if we can't get the statistics from the kernel.
1662 * We do that because, if we *can* get the statistics from
1663 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1664 * as running counts, as reading the statistics from the
1665 * kernel resets the kernel statistics, and if we directly
1666 * increment "md.stat.ps_recv" here, that means it will
1667 * count packets *twice* on systems where we can get kernel
1668 * statistics - once here, and once in pcap_stats_linux().
1670 handle
->md
.packets_read
++;
1672 /* Call the user supplied callback function */
1673 callback(userdata
, &pcap_header
, bp
);
1679 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1683 #ifdef HAVE_PF_PACKET_SOCKETS
1684 if (!handle
->md
.sock_packet
) {
1685 /* PF_PACKET socket */
1686 if (handle
->md
.ifindex
== -1) {
1688 * We don't support sending on the "any" device.
1690 strlcpy(handle
->errbuf
,
1691 "Sending packets isn't supported on the \"any\" device",
1696 if (handle
->md
.cooked
) {
1698 * We don't support sending on the "any" device.
1700 * XXX - how do you send on a bound cooked-mode
1702 * Is a "sendto()" required there?
1704 strlcpy(handle
->errbuf
,
1705 "Sending packets isn't supported in cooked mode",
1712 ret
= send(handle
->fd
, buf
, size
, 0);
1714 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1715 pcap_strerror(errno
));
1722 * Get the statistics for the given packet capture handle.
1723 * Reports the number of dropped packets iff the kernel supports
1724 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1725 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1726 * patches); otherwise, that information isn't available, and we lie
1727 * and report 0 as the count of dropped packets.
1730 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1732 #ifdef HAVE_TPACKET_STATS
1733 struct tpacket_stats kstats
;
1734 socklen_t len
= sizeof (struct tpacket_stats
);
1737 long if_dropped
= 0;
1740 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1742 if (handle
->opt
.promisc
)
1744 if_dropped
= handle
->md
.proc_dropped
;
1745 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1746 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1749 #ifdef HAVE_TPACKET_STATS
1751 * Try to get the packet counts from the kernel.
1753 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1754 &kstats
, &len
) > -1) {
1756 * On systems where the PACKET_STATISTICS "getsockopt()"
1757 * argument is supported on PF_PACKET sockets:
1759 * "ps_recv" counts only packets that *passed* the
1760 * filter, not packets that didn't pass the filter.
1761 * This includes packets later dropped because we
1762 * ran out of buffer space.
1764 * "ps_drop" counts packets dropped because we ran
1765 * out of buffer space. It doesn't count packets
1766 * dropped by the interface driver. It counts only
1767 * packets that passed the filter.
1769 * See above for ps_ifdrop.
1771 * Both statistics include packets not yet read from
1772 * the kernel by libpcap, and thus not yet seen by
1775 * In "linux/net/packet/af_packet.c", at least in the
1776 * 2.4.9 kernel, "tp_packets" is incremented for every
1777 * packet that passes the packet filter *and* is
1778 * successfully queued on the socket; "tp_drops" is
1779 * incremented for every packet dropped because there's
1780 * not enough free space in the socket buffer.
1782 * When the statistics are returned for a PACKET_STATISTICS
1783 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1784 * so that "tp_packets" counts all packets handed to
1785 * the PF_PACKET socket, including packets dropped because
1786 * there wasn't room on the socket buffer - but not
1787 * including packets that didn't pass the filter.
1789 * In the BSD BPF, the count of received packets is
1790 * incremented for every packet handed to BPF, regardless
1791 * of whether it passed the filter.
1793 * We can't make "pcap_stats()" work the same on both
1794 * platforms, but the best approximation is to return
1795 * "tp_packets" as the count of packets and "tp_drops"
1796 * as the count of drops.
1798 * Keep a running total because each call to
1799 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1800 * resets the counters to zero.
1802 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1803 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1804 *stats
= handle
->md
.stat
;
1810 * If the error was EOPNOTSUPP, fall through, so that
1811 * if you build the library on a system with
1812 * "struct tpacket_stats" and run it on a system
1813 * that doesn't, it works as it does if the library
1814 * is built on a system without "struct tpacket_stats".
1816 if (errno
!= EOPNOTSUPP
) {
1817 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1818 "pcap_stats: %s", pcap_strerror(errno
));
1824 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1825 * is not supported on PF_PACKET sockets:
1827 * "ps_recv" counts only packets that *passed* the filter,
1828 * not packets that didn't pass the filter. It does not
1829 * count packets dropped because we ran out of buffer
1832 * "ps_drop" is not supported.
1834 * "ps_ifdrop" is supported. It will return the number
1835 * of drops the interface reports in /proc/net/dev,
1836 * if that is available.
1838 * "ps_recv" doesn't include packets not yet read from
1839 * the kernel by libpcap.
1841 * We maintain the count of packets processed by libpcap in
1842 * "md.packets_read", for reasons described in the comment
1843 * at the end of pcap_read_packet(). We have no idea how many
1844 * packets were dropped by the kernel buffers -- but we know
1845 * how many the interface dropped, so we can return that.
1848 stats
->ps_recv
= handle
->md
.packets_read
;
1850 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1855 * Get from "/sys/class/net" all interfaces listed there; if they're
1856 * already in the list of interfaces we have, that won't add another
1857 * instance, but if they're not, that'll add them.
1859 * We don't bother getting any addresses for them; it appears you can't
1860 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1861 * although some other types of addresses can be fetched with SIOCGIFADDR,
1862 * we don't bother with them for now.
1864 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1865 * the list of interfaces as is, and return 0, so that we can try
1866 * scanning /proc/net/dev.
1869 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1871 DIR *sys_class_net_d
;
1875 char name
[512]; /* XXX - pick a size */
1877 struct ifreq ifrflags
;
1880 sys_class_net_d
= opendir("/sys/class/net");
1881 if (sys_class_net_d
== NULL
&& errno
== ENOENT
)
1885 * Create a socket from which to fetch interface information.
1887 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1889 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1890 "socket: %s", pcap_strerror(errno
));
1896 ent
= readdir(sys_class_net_d
);
1899 * Error or EOF; if errno != 0, it's an error.
1905 * Ignore directories (".", "..", and any subdirectories).
1907 if (ent
->d_type
== DT_DIR
)
1911 * Get the interface name.
1913 p
= &ent
->d_name
[0];
1915 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1918 * This could be the separator between a
1919 * name and an alias number, or it could be
1920 * the separator between a name with no
1921 * alias number and the next field.
1923 * If there's a colon after digits, it
1924 * separates the name and the alias number,
1925 * otherwise it separates the name and the
1929 while (isascii(*p
) && isdigit(*p
))
1933 * That was the next field,
1934 * not the alias number.
1945 * Get the flags for this interface, and skip it if
1948 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
1949 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
1950 if (errno
== ENXIO
|| errno
== ENODEV
)
1952 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1953 "SIOCGIFFLAGS: %.*s: %s",
1954 (int)sizeof(ifrflags
.ifr_name
),
1956 pcap_strerror(errno
));
1960 if (!(ifrflags
.ifr_flags
& IFF_UP
))
1964 * Add an entry for this interface, with no addresses.
1966 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
1977 * Well, we didn't fail for any other reason; did we
1978 * fail due to an error reading the directory?
1981 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1982 "Error reading /sys/class/net: %s",
1983 pcap_strerror(errno
));
1989 (void)closedir(sys_class_net_d
);
1994 * Get from "/proc/net/dev" all interfaces listed there; if they're
1995 * already in the list of interfaces we have, that won't add another
1996 * instance, but if they're not, that'll add them.
1998 * See comments from scan_sys_class_net().
2001 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
2008 char name
[512]; /* XXX - pick a size */
2010 struct ifreq ifrflags
;
2013 proc_net_f
= fopen("/proc/net/dev", "r");
2014 if (proc_net_f
== NULL
&& errno
== ENOENT
)
2018 * Create a socket from which to fetch interface information.
2020 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
2022 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2023 "socket: %s", pcap_strerror(errno
));
2028 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
2030 * Skip the first two lines - they're headers.
2038 * Skip leading white space.
2040 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2042 if (*p
== '\0' || *p
== '\n')
2043 continue; /* blank line */
2046 * Get the interface name.
2049 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2052 * This could be the separator between a
2053 * name and an alias number, or it could be
2054 * the separator between a name with no
2055 * alias number and the next field.
2057 * If there's a colon after digits, it
2058 * separates the name and the alias number,
2059 * otherwise it separates the name and the
2063 while (isascii(*p
) && isdigit(*p
))
2067 * That was the next field,
2068 * not the alias number.
2079 * Get the flags for this interface, and skip it if
2082 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2083 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2086 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2087 "SIOCGIFFLAGS: %.*s: %s",
2088 (int)sizeof(ifrflags
.ifr_name
),
2090 pcap_strerror(errno
));
2094 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2098 * Add an entry for this interface, with no addresses.
2100 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2111 * Well, we didn't fail for any other reason; did we
2112 * fail due to an error reading the file?
2114 if (ferror(proc_net_f
)) {
2115 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2116 "Error reading /proc/net/dev: %s",
2117 pcap_strerror(errno
));
2123 (void)fclose(proc_net_f
);
2128 * Description string for the "any" device.
2130 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2133 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2138 * Read "/sys/class/net", and add to the list of interfaces all
2139 * interfaces listed there that we don't already have, because,
2140 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2141 * and even getifaddrs() won't return information about
2142 * interfaces with no addresses, so you need to read "/sys/class/net"
2143 * to get the names of the rest of the interfaces.
2145 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2147 return (-1); /* failed */
2150 * No /sys/class/net; try reading /proc/net/dev instead.
2152 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2157 * Add the "any" device.
2159 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2166 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2168 #endif /* HAVE_DAG_API */
2170 #ifdef HAVE_SEPTEL_API
2172 * Add Septel devices.
2174 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2176 #endif /* HAVE_SEPTEL_API */
2179 if (snf_platform_finddevs(alldevsp
, errbuf
) < 0)
2181 #endif /* HAVE_SNF_API */
2183 #ifdef PCAP_SUPPORT_BT
2185 * Add Bluetooth devices.
2187 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2191 #ifdef PCAP_SUPPORT_USB
2195 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2203 * Attach the given BPF code to the packet capture device.
2206 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2209 #ifdef SO_ATTACH_FILTER
2210 struct sock_fprog fcode
;
2211 int can_filter_in_kernel
;
2218 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2223 /* Make our private copy of the filter */
2225 if (install_bpf_program(handle
, filter
) < 0)
2226 /* install_bpf_program() filled in errbuf */
2230 * Run user level packet filter by default. Will be overriden if
2231 * installing a kernel filter succeeds.
2233 handle
->md
.use_bpf
= 0;
2235 /* Install kernel level filter if possible */
2237 #ifdef SO_ATTACH_FILTER
2239 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2241 * fcode.len is an unsigned short for current kernel.
2242 * I have yet to see BPF-Code with that much
2243 * instructions but still it is possible. So for the
2244 * sake of correctness I added this check.
2246 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2248 fcode
.filter
= NULL
;
2249 can_filter_in_kernel
= 0;
2251 #endif /* USHRT_MAX */
2254 * Oh joy, the Linux kernel uses struct sock_fprog instead
2255 * of struct bpf_program and of course the length field is
2256 * of different size. Pointed out by Sebastian
2258 * Oh, and we also need to fix it up so that all "ret"
2259 * instructions with non-zero operands have 65535 as the
2260 * operand if we're not capturing in memory-mapped modee,
2261 * and so that, if we're in cooked mode, all memory-reference
2262 * instructions use special magic offsets in references to
2263 * the link-layer header and assume that the link-layer
2264 * payload begins at 0; "fix_program()" will do that.
2266 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2271 * Fatal error; just quit.
2272 * (The "default" case shouldn't happen; we
2273 * return -1 for that reason.)
2279 * The program performed checks that we can't make
2280 * work in the kernel.
2282 can_filter_in_kernel
= 0;
2287 * We have a filter that'll work in the kernel.
2289 can_filter_in_kernel
= 1;
2294 if (can_filter_in_kernel
) {
2295 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2297 /* Installation succeded - using kernel filter. */
2298 handle
->md
.use_bpf
= 1;
2300 else if (err
== -1) /* Non-fatal error */
2303 * Print a warning if we weren't able to install
2304 * the filter for a reason other than "this kernel
2305 * isn't configured to support socket filters.
2307 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2309 "Warning: Kernel filter failed: %s\n",
2310 pcap_strerror(errno
));
2316 * If we're not using the kernel filter, get rid of any kernel
2317 * filter that might've been there before, e.g. because the
2318 * previous filter could work in the kernel, or because some other
2319 * code attached a filter to the socket by some means other than
2320 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2321 * filter out packets that would pass the new userland filter.
2323 if (!handle
->md
.use_bpf
)
2324 reset_kernel_filter(handle
);
2327 * Free up the copy of the filter that was made by "fix_program()".
2329 if (fcode
.filter
!= NULL
)
2335 #endif /* SO_ATTACH_FILTER */
2341 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2343 return pcap_setfilter_linux_common(handle
, filter
, 0);
2348 * Set direction flag: Which packets do we accept on a forwarding
2349 * single device? IN, OUT or both?
2352 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2354 #ifdef HAVE_PF_PACKET_SOCKETS
2355 if (!handle
->md
.sock_packet
) {
2356 handle
->direction
= d
;
2361 * We're not using PF_PACKET sockets, so we can't determine
2362 * the direction of the packet.
2364 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2365 "Setting direction is not supported on SOCK_PACKET sockets");
2369 #ifdef HAVE_PF_PACKET_SOCKETS
2371 * Map the PACKET_ value to a LINUX_SLL_ value; we
2372 * want the same numerical value to be used in
2373 * the link-layer header even if the numerical values
2374 * for the PACKET_ #defines change, so that programs
2375 * that look at the packet type field will always be
2376 * able to handle DLT_LINUX_SLL captures.
2379 map_packet_type_to_sll_type(short int sll_pkttype
)
2381 switch (sll_pkttype
) {
2384 return htons(LINUX_SLL_HOST
);
2386 case PACKET_BROADCAST
:
2387 return htons(LINUX_SLL_BROADCAST
);
2389 case PACKET_MULTICAST
:
2390 return htons(LINUX_SLL_MULTICAST
);
2392 case PACKET_OTHERHOST
:
2393 return htons(LINUX_SLL_OTHERHOST
);
2395 case PACKET_OUTGOING
:
2396 return htons(LINUX_SLL_OUTGOING
);
2405 * Linux uses the ARP hardware type to identify the type of an
2406 * interface. pcap uses the DLT_xxx constants for this. This
2407 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2408 * constant, as arguments, and sets "handle->linktype" to the
2409 * appropriate DLT_XXX constant and sets "handle->offset" to
2410 * the appropriate value (to make "handle->offset" plus link-layer
2411 * header length be a multiple of 4, so that the link-layer payload
2412 * will be aligned on a 4-byte boundary when capturing packets).
2413 * (If the offset isn't set here, it'll be 0; add code as appropriate
2414 * for cases where it shouldn't be 0.)
2416 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2417 * in cooked mode; otherwise, we can't use cooked mode, so we have
2418 * to pick some type that works in raw mode, or fail.
2420 * Sets the link type to -1 if unable to map the type.
2422 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2428 * This is (presumably) a real Ethernet capture; give it a
2429 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2430 * that an application can let you choose it, in case you're
2431 * capturing DOCSIS traffic that a Cisco Cable Modem
2432 * Termination System is putting out onto an Ethernet (it
2433 * doesn't put an Ethernet header onto the wire, it puts raw
2434 * DOCSIS frames out on the wire inside the low-level
2435 * Ethernet framing).
2437 * XXX - are there any sorts of "fake Ethernet" that have
2438 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2439 * a Cisco CMTS won't put traffic onto it or get traffic
2440 * bridged onto it? ISDN is handled in "activate_new()",
2441 * as we fall back on cooked mode there; are there any
2444 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2446 * If that fails, just leave the list empty.
2448 if (handle
->dlt_list
!= NULL
) {
2449 handle
->dlt_list
[0] = DLT_EN10MB
;
2450 handle
->dlt_list
[1] = DLT_DOCSIS
;
2451 handle
->dlt_count
= 2;
2455 case ARPHRD_METRICOM
:
2456 case ARPHRD_LOOPBACK
:
2457 handle
->linktype
= DLT_EN10MB
;
2462 handle
->linktype
= DLT_EN3MB
;
2466 handle
->linktype
= DLT_AX25_KISS
;
2470 handle
->linktype
= DLT_PRONET
;
2474 handle
->linktype
= DLT_CHAOS
;
2477 #define ARPHRD_CAN 280
2480 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2483 #ifndef ARPHRD_IEEE802_TR
2484 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2486 case ARPHRD_IEEE802_TR
:
2487 case ARPHRD_IEEE802
:
2488 handle
->linktype
= DLT_IEEE802
;
2493 handle
->linktype
= DLT_ARCNET_LINUX
;
2496 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2497 #define ARPHRD_FDDI 774
2500 handle
->linktype
= DLT_FDDI
;
2504 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2505 #define ARPHRD_ATM 19
2509 * The Classical IP implementation in ATM for Linux
2510 * supports both what RFC 1483 calls "LLC Encapsulation",
2511 * in which each packet has an LLC header, possibly
2512 * with a SNAP header as well, prepended to it, and
2513 * what RFC 1483 calls "VC Based Multiplexing", in which
2514 * different virtual circuits carry different network
2515 * layer protocols, and no header is prepended to packets.
2517 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2518 * you can't use the ARPHRD_ type to find out whether
2519 * captured packets will have an LLC header, and,
2520 * while there's a socket ioctl to *set* the encapsulation
2521 * type, there's no ioctl to *get* the encapsulation type.
2525 * programs that dissect Linux Classical IP frames
2526 * would have to check for an LLC header and,
2527 * depending on whether they see one or not, dissect
2528 * the frame as LLC-encapsulated or as raw IP (I
2529 * don't know whether there's any traffic other than
2530 * IP that would show up on the socket, or whether
2531 * there's any support for IPv6 in the Linux
2532 * Classical IP code);
2534 * filter expressions would have to compile into
2535 * code that checks for an LLC header and does
2538 * Both of those are a nuisance - and, at least on systems
2539 * that support PF_PACKET sockets, we don't have to put
2540 * up with those nuisances; instead, we can just capture
2541 * in cooked mode. That's what we'll do, if we can.
2542 * Otherwise, we'll just fail.
2545 handle
->linktype
= DLT_LINUX_SLL
;
2547 handle
->linktype
= -1;
2550 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2551 #define ARPHRD_IEEE80211 801
2553 case ARPHRD_IEEE80211
:
2554 handle
->linktype
= DLT_IEEE802_11
;
2557 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2558 #define ARPHRD_IEEE80211_PRISM 802
2560 case ARPHRD_IEEE80211_PRISM
:
2561 handle
->linktype
= DLT_PRISM_HEADER
;
2564 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2565 #define ARPHRD_IEEE80211_RADIOTAP 803
2567 case ARPHRD_IEEE80211_RADIOTAP
:
2568 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2573 * Some PPP code in the kernel supplies no link-layer
2574 * header whatsoever to PF_PACKET sockets; other PPP
2575 * code supplies PPP link-layer headers ("syncppp.c");
2576 * some PPP code might supply random link-layer
2577 * headers (PPP over ISDN - there's code in Ethereal,
2578 * for example, to cope with PPP-over-ISDN captures
2579 * with which the Ethereal developers have had to cope,
2580 * heuristically trying to determine which of the
2581 * oddball link-layer headers particular packets have).
2583 * As such, we just punt, and run all PPP interfaces
2584 * in cooked mode, if we can; otherwise, we just treat
2585 * it as DLT_RAW, for now - if somebody needs to capture,
2586 * on a 2.0[.x] kernel, on PPP devices that supply a
2587 * link-layer header, they'll have to add code here to
2588 * map to the appropriate DLT_ type (possibly adding a
2589 * new DLT_ type, if necessary).
2592 handle
->linktype
= DLT_LINUX_SLL
;
2595 * XXX - handle ISDN types here? We can't fall
2596 * back on cooked sockets, so we'd have to
2597 * figure out from the device name what type of
2598 * link-layer encapsulation it's using, and map
2599 * that to an appropriate DLT_ value, meaning
2600 * we'd map "isdnN" devices to DLT_RAW (they
2601 * supply raw IP packets with no link-layer
2602 * header) and "isdY" devices to a new DLT_I4L_IP
2603 * type that has only an Ethernet packet type as
2604 * a link-layer header.
2606 * But sometimes we seem to get random crap
2607 * in the link-layer header when capturing on
2610 handle
->linktype
= DLT_RAW
;
2614 #ifndef ARPHRD_CISCO
2615 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2618 handle
->linktype
= DLT_C_HDLC
;
2621 /* Not sure if this is correct for all tunnels, but it
2625 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2633 #ifndef ARPHRD_RAWHDLC
2634 #define ARPHRD_RAWHDLC 518
2636 case ARPHRD_RAWHDLC
:
2638 #define ARPHRD_DLCI 15
2642 * XXX - should some of those be mapped to DLT_LINUX_SLL
2643 * instead? Should we just map all of them to DLT_LINUX_SLL?
2645 handle
->linktype
= DLT_RAW
;
2649 #define ARPHRD_FRAD 770
2652 handle
->linktype
= DLT_FRELAY
;
2655 case ARPHRD_LOCALTLK
:
2656 handle
->linktype
= DLT_LTALK
;
2660 #define ARPHRD_FCPP 784
2664 #define ARPHRD_FCAL 785
2668 #define ARPHRD_FCPL 786
2671 #ifndef ARPHRD_FCFABRIC
2672 #define ARPHRD_FCFABRIC 787
2674 case ARPHRD_FCFABRIC
:
2676 * We assume that those all mean RFC 2625 IP-over-
2677 * Fibre Channel, with the RFC 2625 header at
2678 * the beginning of the packet.
2680 handle
->linktype
= DLT_IP_OVER_FC
;
2684 #define ARPHRD_IRDA 783
2687 /* Don't expect IP packet out of this interfaces... */
2688 handle
->linktype
= DLT_LINUX_IRDA
;
2689 /* We need to save packet direction for IrDA decoding,
2690 * so let's use "Linux-cooked" mode. Jean II */
2691 //handle->md.cooked = 1;
2694 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2695 * is needed, please report it to <daniele@orlandi.com> */
2697 #define ARPHRD_LAPD 8445
2700 /* Don't expect IP packet out of this interfaces... */
2701 handle
->linktype
= DLT_LINUX_LAPD
;
2705 #define ARPHRD_NONE 0xFFFE
2709 * No link-layer header; packets are just IP
2710 * packets, so use DLT_RAW.
2712 handle
->linktype
= DLT_RAW
;
2715 #ifndef ARPHRD_IEEE802154
2716 #define ARPHRD_IEEE802154 804
2718 case ARPHRD_IEEE802154
:
2719 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2723 handle
->linktype
= -1;
2728 /* ===== Functions to interface to the newer kernels ================== */
2731 * Try to open a packet socket using the new kernel PF_PACKET interface.
2732 * Returns 1 on success, 0 on an error that means the new interface isn't
2733 * present (so the old SOCK_PACKET interface should be tried), and a
2734 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2735 * work either (so it shouldn't be tried).
2738 activate_new(pcap_t
*handle
)
2740 #ifdef HAVE_PF_PACKET_SOCKETS
2741 const char *device
= handle
->opt
.source
;
2742 int is_any_device
= (strcmp(device
, "any") == 0);
2743 int sock_fd
= -1, arptype
;
2744 #ifdef HAVE_PACKET_AUXDATA
2748 struct packet_mreq mr
;
2751 * Open a socket with protocol family packet. If the
2752 * "any" device was specified, we open a SOCK_DGRAM
2753 * socket for the cooked interface, otherwise we first
2754 * try a SOCK_RAW socket for the raw interface.
2756 sock_fd
= is_any_device
?
2757 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2758 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2760 if (sock_fd
== -1) {
2761 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2762 pcap_strerror(errno
) );
2763 return 0; /* try old mechanism */
2766 /* It seems the kernel supports the new interface. */
2767 handle
->md
.sock_packet
= 0;
2770 * Get the interface index of the loopback device.
2771 * If the attempt fails, don't fail, just set the
2772 * "md.lo_ifindex" to -1.
2774 * XXX - can there be more than one device that loops
2775 * packets back, i.e. devices other than "lo"? If so,
2776 * we'd need to find them all, and have an array of
2777 * indices for them, and check all of them in
2778 * "pcap_read_packet()".
2780 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2783 * Default value for offset to align link-layer payload
2784 * on a 4-byte boundary.
2789 * What kind of frames do we have to deal with? Fall back
2790 * to cooked mode if we have an unknown interface type
2791 * or a type we know doesn't work well in raw mode.
2793 if (!is_any_device
) {
2794 /* Assume for now we don't need cooked mode. */
2795 handle
->md
.cooked
= 0;
2797 if (handle
->opt
.rfmon
) {
2799 * We were asked to turn on monitor mode.
2800 * Do so before we get the link-layer type,
2801 * because entering monitor mode could change
2802 * the link-layer type.
2804 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2812 * Nothing worked for turning monitor mode
2816 return PCAP_ERROR_RFMON_NOTSUP
;
2820 * Either monitor mode has been turned on for
2821 * the device, or we've been given a different
2822 * device to open for monitor mode. If we've
2823 * been given a different device, use it.
2825 if (handle
->md
.mondevice
!= NULL
)
2826 device
= handle
->md
.mondevice
;
2828 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2833 map_arphrd_to_dlt(handle
, arptype
, 1);
2834 if (handle
->linktype
== -1 ||
2835 handle
->linktype
== DLT_LINUX_SLL
||
2836 handle
->linktype
== DLT_LINUX_IRDA
||
2837 handle
->linktype
== DLT_LINUX_LAPD
||
2838 (handle
->linktype
== DLT_EN10MB
&&
2839 (strncmp("isdn", device
, 4) == 0 ||
2840 strncmp("isdY", device
, 4) == 0))) {
2842 * Unknown interface type (-1), or a
2843 * device we explicitly chose to run
2844 * in cooked mode (e.g., PPP devices),
2845 * or an ISDN device (whose link-layer
2846 * type we can only determine by using
2847 * APIs that may be different on different
2848 * kernels) - reopen in cooked mode.
2850 if (close(sock_fd
) == -1) {
2851 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2852 "close: %s", pcap_strerror(errno
));
2855 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2857 if (sock_fd
== -1) {
2858 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2859 "socket: %s", pcap_strerror(errno
));
2862 handle
->md
.cooked
= 1;
2865 * Get rid of any link-layer type list
2866 * we allocated - this only supports cooked
2869 if (handle
->dlt_list
!= NULL
) {
2870 free(handle
->dlt_list
);
2871 handle
->dlt_list
= NULL
;
2872 handle
->dlt_count
= 0;
2875 if (handle
->linktype
== -1) {
2877 * Warn that we're falling back on
2878 * cooked mode; we may want to
2879 * update "map_arphrd_to_dlt()"
2880 * to handle the new type.
2882 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2884 "supported by libpcap - "
2885 "falling back to cooked "
2891 * IrDA capture is not a real "cooked" capture,
2892 * it's IrLAP frames, not IP packets. The
2893 * same applies to LAPD capture.
2895 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2896 handle
->linktype
!= DLT_LINUX_LAPD
)
2897 handle
->linktype
= DLT_LINUX_SLL
;
2900 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2902 if (handle
->md
.ifindex
== -1) {
2907 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2908 handle
->errbuf
)) != 1) {
2913 return 0; /* try old mechanism */
2919 if (handle
->opt
.rfmon
) {
2921 * It doesn't support monitor mode.
2923 return PCAP_ERROR_RFMON_NOTSUP
;
2927 * It uses cooked mode.
2929 handle
->md
.cooked
= 1;
2930 handle
->linktype
= DLT_LINUX_SLL
;
2933 * We're not bound to a device.
2934 * For now, we're using this as an indication
2935 * that we can't transmit; stop doing that only
2936 * if we figure out how to transmit in cooked
2939 handle
->md
.ifindex
= -1;
2943 * Select promiscuous mode on if "promisc" is set.
2945 * Do not turn allmulti mode on if we don't select
2946 * promiscuous mode - on some devices (e.g., Orinoco
2947 * wireless interfaces), allmulti mode isn't supported
2948 * and the driver implements it by turning promiscuous
2949 * mode on, and that screws up the operation of the
2950 * card as a normal networking interface, and on no
2951 * other platform I know of does starting a non-
2952 * promiscuous capture affect which multicast packets
2953 * are received by the interface.
2957 * Hmm, how can we set promiscuous mode on all interfaces?
2958 * I am not sure if that is possible at all. For now, we
2959 * silently ignore attempts to turn promiscuous mode on
2960 * for the "any" device (so you don't have to explicitly
2961 * disable it in programs such as tcpdump).
2964 if (!is_any_device
&& handle
->opt
.promisc
) {
2965 memset(&mr
, 0, sizeof(mr
));
2966 mr
.mr_ifindex
= handle
->md
.ifindex
;
2967 mr
.mr_type
= PACKET_MR_PROMISC
;
2968 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2969 &mr
, sizeof(mr
)) == -1) {
2970 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2971 "setsockopt: %s", pcap_strerror(errno
));
2977 /* Enable auxillary data if supported and reserve room for
2978 * reconstructing VLAN headers. */
2979 #ifdef HAVE_PACKET_AUXDATA
2981 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2982 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2983 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2984 "setsockopt: %s", pcap_strerror(errno
));
2988 handle
->offset
+= VLAN_TAG_LEN
;
2989 #endif /* HAVE_PACKET_AUXDATA */
2992 * This is a 2.2[.x] or later kernel (we know that
2993 * because we're not using a SOCK_PACKET socket -
2994 * PF_PACKET is supported only in 2.2 and later
2997 * We can safely pass "recvfrom()" a byte count
2998 * based on the snapshot length.
3000 * If we're in cooked mode, make the snapshot length
3001 * large enough to hold a "cooked mode" header plus
3002 * 1 byte of packet data (so we don't pass a byte
3003 * count of 0 to "recvfrom()").
3005 if (handle
->md
.cooked
) {
3006 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
3007 handle
->snapshot
= SLL_HDR_LEN
+ 1;
3009 handle
->bufsize
= handle
->snapshot
;
3011 /* Save the socket FD in the pcap structure */
3012 handle
->fd
= sock_fd
;
3017 "New packet capturing interface not supported by build "
3018 "environment", PCAP_ERRBUF_SIZE
);
3023 #ifdef HAVE_PACKET_RING
3025 * Attempt to activate with memory-mapped access.
3027 * On success, returns 1, and sets *status to 0 if there are no warnings
3028 * or to a PCAP_WARNING_ code if there is a warning.
3030 * On failure due to lack of support for memory-mapped capture, returns
3033 * On error, returns -1, and sets *status to the appropriate error code;
3034 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3037 activate_mmap(pcap_t
*handle
, int *status
)
3042 * Attempt to allocate a buffer to hold the contents of one
3043 * packet, for use by the oneshot callback.
3045 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
3046 if (handle
->md
.oneshot_buffer
== NULL
) {
3047 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3048 "can't allocate oneshot buffer: %s",
3049 pcap_strerror(errno
));
3050 *status
= PCAP_ERROR
;
3054 if (handle
->opt
.buffer_size
== 0) {
3055 /* by default request 2M for the ring buffer */
3056 handle
->opt
.buffer_size
= 2*1024*1024;
3058 ret
= prepare_tpacket_socket(handle
);
3060 free(handle
->md
.oneshot_buffer
);
3061 *status
= PCAP_ERROR
;
3064 ret
= create_ring(handle
, status
);
3067 * We don't support memory-mapped capture; our caller
3068 * will fall back on reading from the socket.
3070 free(handle
->md
.oneshot_buffer
);
3075 * Error attempting to enable memory-mapped capture;
3076 * fail. create_ring() has set *status.
3078 free(handle
->md
.oneshot_buffer
);
3083 * Success. *status has been set either to 0 if there are no
3084 * warnings or to a PCAP_WARNING_ value if there is a warning.
3086 * Override some defaults and inherit the other fields from
3088 * handle->offset is used to get the current position into the rx ring.
3089 * handle->cc is used to store the ring size.
3091 handle
->read_op
= pcap_read_linux_mmap
;
3092 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3093 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3094 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3095 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3096 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3097 handle
->selectable_fd
= handle
->fd
;
3100 #else /* HAVE_PACKET_RING */
3102 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3106 #endif /* HAVE_PACKET_RING */
3108 #ifdef HAVE_PACKET_RING
3110 * Attempt to set the socket to version 2 of the memory-mapped header.
3111 * Return 1 if we succeed or if we fail because version 2 isn't
3112 * supported; return -1 on any other error, and set handle->errbuf.
3115 prepare_tpacket_socket(pcap_t
*handle
)
3117 #ifdef HAVE_TPACKET2
3122 handle
->md
.tp_version
= TPACKET_V1
;
3123 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
3125 #ifdef HAVE_TPACKET2
3126 /* Probe whether kernel supports TPACKET_V2 */
3129 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3130 if (errno
== ENOPROTOOPT
)
3131 return 1; /* no - just drive on */
3133 /* Yes - treat as a failure. */
3134 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3135 "can't get TPACKET_V2 header len on packet socket: %s",
3136 pcap_strerror(errno
));
3139 handle
->md
.tp_hdrlen
= val
;
3142 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3144 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3145 "can't activate TPACKET_V2 on packet socket: %s",
3146 pcap_strerror(errno
));
3149 handle
->md
.tp_version
= TPACKET_V2
;
3151 /* Reserve space for VLAN tag reconstruction */
3153 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3155 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3156 "can't set up reserve on packet socket: %s",
3157 pcap_strerror(errno
));
3161 #endif /* HAVE_TPACKET2 */
3166 * Attempt to set up memory-mapped access.
3168 * On success, returns 1, and sets *status to 0 if there are no warnings
3169 * or to a PCAP_WARNING_ code if there is a warning.
3171 * On failure due to lack of support for memory-mapped capture, returns
3174 * On error, returns -1, and sets *status to the appropriate error code;
3175 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3178 create_ring(pcap_t
*handle
, int *status
)
3180 unsigned i
, j
, frames_per_block
;
3181 struct tpacket_req req
;
3184 * Start out assuming no warnings or errors.
3188 /* Note that with large snapshot (say 64K) only a few frames
3189 * will be available in the ring even with pretty large ring size
3190 * (and a lot of memory will be unused).
3191 * The snap len should be carefully chosen to achive best
3193 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
3194 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3195 sizeof(struct sockaddr_ll
));
3196 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3198 /* compute the minumum block size that will handle this frame.
3199 * The block has to be page size aligned.
3200 * The max block size allowed by the kernel is arch-dependent and
3201 * it's not explicitly checked here. */
3202 req
.tp_block_size
= getpagesize();
3203 while (req
.tp_block_size
< req
.tp_frame_size
)
3204 req
.tp_block_size
<<= 1;
3206 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3209 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3210 * so we check for PACKET_TIMESTAMP. We check for
3211 * linux/net_tstamp.h just in case a system somehow has
3212 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3215 * SIOCSHWTSTAMP was introduced in the patch that introduced
3216 * linux/net_tstamp.h, so we don't bother checking whether
3217 * SIOCSHWTSTAMP is defined (if your Linux system has
3218 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3219 * Linux system is badly broken).
3221 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3223 * If we were told to do so, ask the kernel and the driver
3224 * to use hardware timestamps.
3226 * Hardware timestamps are only supported with mmapped
3229 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3230 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3231 struct hwtstamp_config hwconfig
;
3236 * Ask for hardware time stamps on all packets,
3237 * including transmitted packets.
3239 memset(&hwconfig
, 0, sizeof(hwconfig
));
3240 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3241 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3243 memset(&ifr
, 0, sizeof(ifr
));
3244 strcpy(ifr
.ifr_name
, handle
->opt
.source
);
3245 ifr
.ifr_data
= (void *)&hwconfig
;
3247 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3252 * Treat this as an error, as the
3253 * user should try to run this
3254 * with the appropriate privileges -
3255 * and, if they can't, shouldn't
3256 * try requesting hardware time stamps.
3258 *status
= PCAP_ERROR_PERM_DENIED
;
3263 * Treat this as a warning, as the
3264 * only way to fix the warning is to
3265 * get an adapter that supports hardware
3266 * time stamps. We'll just fall back
3267 * on the standard host time stamps.
3269 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
;
3273 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3274 "SIOCSHWTSTAMP failed: %s",
3275 pcap_strerror(errno
));
3276 *status
= PCAP_ERROR
;
3281 * Well, that worked. Now specify the type of
3282 * hardware time stamp we want for this
3285 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3287 * Hardware timestamp, synchronized
3288 * with the system clock.
3290 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3293 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3294 * timestamp, not synchronized with the
3297 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3299 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3300 (void *)×ource
, sizeof(timesource
))) {
3301 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3302 "can't set PACKET_TIMESTAMP: %s",
3303 pcap_strerror(errno
));
3304 *status
= PCAP_ERROR
;
3309 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3311 /* ask the kernel to create the ring */
3313 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3315 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3316 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3318 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3319 (void *) &req
, sizeof(req
))) {
3320 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3322 * Memory failure; try to reduce the requested ring
3325 * We used to reduce this by half -- do 5% instead.
3326 * That may result in more iterations and a longer
3327 * startup, but the user will be much happier with
3328 * the resulting buffer size.
3330 if (req
.tp_frame_nr
< 20)
3331 req
.tp_frame_nr
-= 1;
3333 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3336 if (errno
== ENOPROTOOPT
) {
3338 * We don't have ring buffer support in this kernel.
3342 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3343 "can't create rx ring on packet socket: %s",
3344 pcap_strerror(errno
));
3345 *status
= PCAP_ERROR
;
3349 /* memory map the rx ring */
3350 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3351 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3352 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3353 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3354 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3355 "can't mmap rx ring: %s", pcap_strerror(errno
));
3357 /* clear the allocated ring on error*/
3358 destroy_ring(handle
);
3359 *status
= PCAP_ERROR
;
3363 /* allocate a ring for each frame header pointer*/
3364 handle
->cc
= req
.tp_frame_nr
;
3365 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3366 if (!handle
->buffer
) {
3367 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3368 "can't allocate ring of frame headers: %s",
3369 pcap_strerror(errno
));
3371 destroy_ring(handle
);
3372 *status
= PCAP_ERROR
;
3376 /* fill the header ring with proper frame ptr*/
3378 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3379 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3380 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3381 RING_GET_FRAME(handle
) = base
;
3382 base
+= req
.tp_frame_size
;
3386 handle
->bufsize
= req
.tp_frame_size
;
3391 /* free all ring related resources*/
3393 destroy_ring(pcap_t
*handle
)
3395 /* tell the kernel to destroy the ring*/
3396 struct tpacket_req req
;
3397 memset(&req
, 0, sizeof(req
));
3398 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3399 (void *) &req
, sizeof(req
));
3401 /* if ring is mapped, unmap it*/
3402 if (handle
->md
.mmapbuf
) {
3403 /* do not test for mmap failure, as we can't recover from any error */
3404 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3405 handle
->md
.mmapbuf
= NULL
;
3410 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3411 * for Linux mmapped capture.
3413 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3414 * data handed to the callback to be valid after the callback returns,
3415 * but pcap_read_linux_mmap() has to release that packet as soon as
3416 * the callback returns (otherwise, the kernel thinks there's still
3417 * at least one unprocessed packet available in the ring, so a select()
3418 * will immediately return indicating that there's data to process), so,
3419 * in the callback, we have to make a copy of the packet.
3421 * Yes, this means that, if the capture is using the ring buffer, using
3422 * pcap_next() or pcap_next_ex() requires more copies than using
3423 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3424 * pcap_next() or pcap_next_ex().
3427 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3428 const u_char
*bytes
)
3430 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3433 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3434 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3438 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3440 destroy_ring(handle
);
3441 if (handle
->md
.oneshot_buffer
!= NULL
) {
3442 free(handle
->md
.oneshot_buffer
);
3443 handle
->md
.oneshot_buffer
= NULL
;
3445 pcap_cleanup_linux(handle
);
3450 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3452 /* use negative value of timeout to indicate non blocking ops */
3453 return (p
->md
.timeout
<0);
3457 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3459 /* map each value to the corresponding 2's complement, to
3460 * preserve the timeout value provided with pcap_set_timeout */
3462 if (p
->md
.timeout
>= 0) {
3464 * Timeout is non-negative, so we're not already
3465 * in non-blocking mode; set it to the 2's
3466 * complement, to make it negative, as an
3467 * indication that we're in non-blocking mode.
3469 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3472 if (p
->md
.timeout
< 0) {
3474 * Timeout is negative, so we're not already
3475 * in blocking mode; reverse the previous
3476 * operation, to make the timeout non-negative
3479 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3485 static inline union thdr
*
3486 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3490 h
.raw
= RING_GET_FRAME(handle
);
3491 switch (handle
->md
.tp_version
) {
3493 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3497 #ifdef HAVE_TPACKET2
3499 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3513 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3520 /* wait for frames availability.*/
3521 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3522 struct pollfd pollinfo
;
3525 pollinfo
.fd
= handle
->fd
;
3526 pollinfo
.events
= POLLIN
;
3528 if (handle
->md
.timeout
== 0)
3529 timeout
= -1; /* block forever */
3530 else if (handle
->md
.timeout
> 0)
3531 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3533 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3535 ret
= poll(&pollinfo
, 1, timeout
);
3536 if (ret
< 0 && errno
!= EINTR
) {
3537 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3538 "can't poll on packet socket: %s",
3539 pcap_strerror(errno
));
3541 } else if (ret
> 0 &&
3542 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3544 * There's some indication other than
3545 * "you can read on this descriptor" on
3548 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3549 snprintf(handle
->errbuf
,
3551 "Hangup on packet socket");
3554 if (pollinfo
.revents
& POLLERR
) {
3556 * A recv() will give us the
3557 * actual error code.
3559 * XXX - make the socket non-blocking?
3561 if (recv(handle
->fd
, &c
, sizeof c
,
3563 continue; /* what, no error? */
3564 if (errno
== ENETDOWN
) {
3566 * The device on which we're
3567 * capturing went away.
3569 * XXX - we should really return
3570 * PCAP_ERROR_IFACE_NOT_UP,
3571 * but pcap_dispatch() etc.
3572 * aren't defined to return
3575 snprintf(handle
->errbuf
,
3577 "The interface went down");
3579 snprintf(handle
->errbuf
,
3581 "Error condition on packet socket: %s",
3586 if (pollinfo
.revents
& POLLNVAL
) {
3587 snprintf(handle
->errbuf
,
3589 "Invalid polling request on packet socket");
3593 /* check for break loop condition on interrupted syscall*/
3594 if (handle
->break_loop
) {
3595 handle
->break_loop
= 0;
3596 return PCAP_ERROR_BREAK
;
3601 /* non-positive values of max_packets are used to require all
3602 * packets currently available in the ring */
3603 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3605 struct sockaddr_ll
*sll
;
3606 struct pcap_pkthdr pcaphdr
;
3609 unsigned int tp_len
;
3610 unsigned int tp_mac
;
3611 unsigned int tp_snaplen
;
3612 unsigned int tp_sec
;
3613 unsigned int tp_usec
;
3615 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3619 switch (handle
->md
.tp_version
) {
3621 tp_len
= h
.h1
->tp_len
;
3622 tp_mac
= h
.h1
->tp_mac
;
3623 tp_snaplen
= h
.h1
->tp_snaplen
;
3624 tp_sec
= h
.h1
->tp_sec
;
3625 tp_usec
= h
.h1
->tp_usec
;
3627 #ifdef HAVE_TPACKET2
3629 tp_len
= h
.h2
->tp_len
;
3630 tp_mac
= h
.h2
->tp_mac
;
3631 tp_snaplen
= h
.h2
->tp_snaplen
;
3632 tp_sec
= h
.h2
->tp_sec
;
3633 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3637 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3638 "unsupported tpacket version %d",
3639 handle
->md
.tp_version
);
3642 /* perform sanity check on internal offset. */
3643 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3644 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3645 "corrupted frame on kernel ring mac "
3646 "offset %d + caplen %d > frame len %d",
3647 tp_mac
, tp_snaplen
, handle
->bufsize
);
3651 /* run filter on received packet
3652 * If the kernel filtering is enabled we need to run the
3653 * filter until all the frames present into the ring
3654 * at filter creation time are processed.
3655 * In such case md.use_bpf is used as a counter for the
3656 * packet we need to filter.
3657 * Note: alternatively it could be possible to stop applying
3658 * the filter when the ring became empty, but it can possibly
3659 * happen a lot later... */
3660 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3661 run_bpf
= (!handle
->md
.use_bpf
) ||
3662 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
3663 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3664 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
3665 tp_len
, tp_snaplen
) == 0))
3669 * Do checks based on packet direction.
3671 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
3672 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
3675 * If this is from the loopback device, reject it;
3676 * we'll see the packet as an incoming packet as well,
3677 * and we don't want to see it twice.
3679 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
3683 * If the user only wants incoming packets, reject it.
3685 if (handle
->direction
== PCAP_D_IN
)
3690 * If the user only wants outgoing packets, reject it.
3692 if (handle
->direction
== PCAP_D_OUT
)
3696 /* get required packet info from ring header */
3697 pcaphdr
.ts
.tv_sec
= tp_sec
;
3698 pcaphdr
.ts
.tv_usec
= tp_usec
;
3699 pcaphdr
.caplen
= tp_snaplen
;
3700 pcaphdr
.len
= tp_len
;
3702 /* if required build in place the sll header*/
3703 if (handle
->md
.cooked
) {
3704 struct sll_header
*hdrp
;
3707 * The kernel should have left us with enough
3708 * space for an sll header; back up the packet
3709 * data pointer into that space, as that'll be
3710 * the beginning of the packet we pass to the
3716 * Let's make sure that's past the end of
3717 * the tpacket header, i.e. >=
3718 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3719 * don't step on the header when we construct
3722 if (bp
< (u_char
*)h
.raw
+
3723 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3724 sizeof(struct sockaddr_ll
)) {
3725 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3726 "cooked-mode frame doesn't have room for sll header");
3731 * OK, that worked; construct the sll header.
3733 hdrp
= (struct sll_header
*)bp
;
3734 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
3736 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3737 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3738 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3739 hdrp
->sll_protocol
= sll
->sll_protocol
;
3741 /* update packet len */
3742 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3743 pcaphdr
.len
+= SLL_HDR_LEN
;
3746 #ifdef HAVE_TPACKET2
3747 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3748 tp_snaplen
>= 2 * ETH_ALEN
) {
3749 struct vlan_tag
*tag
;
3752 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3754 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3755 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3756 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3758 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3759 pcaphdr
.len
+= VLAN_TAG_LEN
;
3764 * The only way to tell the kernel to cut off the
3765 * packet at a snapshot length is with a filter program;
3766 * if there's no filter program, the kernel won't cut
3769 * Trim the snapshot length to be no longer than the
3770 * specified snapshot length.
3772 if (pcaphdr
.caplen
> handle
->snapshot
)
3773 pcaphdr
.caplen
= handle
->snapshot
;
3775 /* pass the packet to the user */
3777 callback(user
, &pcaphdr
, bp
);
3778 handle
->md
.packets_read
++;
3782 switch (handle
->md
.tp_version
) {
3784 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3786 #ifdef HAVE_TPACKET2
3788 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3792 if (++handle
->offset
>= handle
->cc
)
3795 /* check for break loop condition*/
3796 if (handle
->break_loop
) {
3797 handle
->break_loop
= 0;
3798 return PCAP_ERROR_BREAK
;
3805 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3811 * Don't rewrite "ret" instructions; we don't need to, as
3812 * we're not reading packets with recvmsg(), and we don't
3813 * want to, as, by not rewriting them, the kernel can avoid
3814 * copying extra data.
3816 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3820 /* if the kernel filter is enabled, we need to apply the filter on
3821 * all packets present into the ring. Get an upper bound of their number
3823 if (!handle
->md
.use_bpf
)
3826 /* walk the ring backward and count the free slot */
3827 offset
= handle
->offset
;
3828 if (--handle
->offset
< 0)
3829 handle
->offset
= handle
->cc
- 1;
3830 for (n
=0; n
< handle
->cc
; ++n
) {
3831 if (--handle
->offset
< 0)
3832 handle
->offset
= handle
->cc
- 1;
3833 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
3837 /* be careful to not change current ring position */
3838 handle
->offset
= offset
;
3840 /* store the number of packets currently present in the ring */
3841 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
3845 #endif /* HAVE_PACKET_RING */
3848 #ifdef HAVE_PF_PACKET_SOCKETS
3850 * Return the index of the given device name. Fill ebuf and return
3854 iface_get_id(int fd
, const char *device
, char *ebuf
)
3858 memset(&ifr
, 0, sizeof(ifr
));
3859 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3861 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
3862 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3863 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
3867 return ifr
.ifr_ifindex
;
3871 * Bind the socket associated with FD to the given device.
3872 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3873 * or a PCAP_ERROR_ value on a hard error.
3876 iface_bind(int fd
, int ifindex
, char *ebuf
)
3878 struct sockaddr_ll sll
;
3880 socklen_t errlen
= sizeof(err
);
3882 memset(&sll
, 0, sizeof(sll
));
3883 sll
.sll_family
= AF_PACKET
;
3884 sll
.sll_ifindex
= ifindex
;
3885 sll
.sll_protocol
= htons(ETH_P_ALL
);
3887 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
3888 if (errno
== ENETDOWN
) {
3890 * Return a "network down" indication, so that
3891 * the application can report that rather than
3892 * saying we had a mysterious failure and
3893 * suggest that they report a problem to the
3894 * libpcap developers.
3896 return PCAP_ERROR_IFACE_NOT_UP
;
3898 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3899 "bind: %s", pcap_strerror(errno
));
3904 /* Any pending errors, e.g., network is down? */
3906 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3907 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3908 "getsockopt: %s", pcap_strerror(errno
));
3912 if (err
== ENETDOWN
) {
3914 * Return a "network down" indication, so that
3915 * the application can report that rather than
3916 * saying we had a mysterious failure and
3917 * suggest that they report a problem to the
3918 * libpcap developers.
3920 return PCAP_ERROR_IFACE_NOT_UP
;
3921 } else if (err
> 0) {
3922 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3923 "bind: %s", pcap_strerror(err
));
3930 #ifdef IW_MODE_MONITOR
3932 * Check whether the device supports the Wireless Extensions.
3933 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3934 * if the device doesn't even exist.
3937 has_wext(int sock_fd
, const char *device
, char *ebuf
)
3941 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3942 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3943 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3944 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
3946 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3947 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3948 if (errno
== ENODEV
)
3949 return PCAP_ERROR_NO_SUCH_DEVICE
;
3954 * Per me si va ne la citta dolente,
3955 * Per me si va ne l'etterno dolore,
3957 * Lasciate ogne speranza, voi ch'intrate.
3959 * XXX - airmon-ng does special stuff with the Orinoco driver and the
3975 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3976 * on if it's not already on.
3978 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3979 * on this device, or a PCAP_ERROR_ value if we do support them but
3980 * we weren't able to turn monitor mode on.
3983 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3986 * XXX - at least some adapters require non-Wireless Extensions
3987 * mechanisms to turn monitor mode on.
3989 * Atheros cards might require that a separate "monitor virtual access
3990 * point" be created, with later versions of the madwifi driver.
3991 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3992 * monitor -bssid", which apparently spits out a line "athN"
3993 * where "athN" is the monitor mode device. To leave monitor
3994 * mode, it destroys the monitor mode device.
3996 * Some Intel Centrino adapters might require private ioctls to get
3997 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3998 * configure a separate "rtapN" interface to capture in monitor
3999 * mode without preventing the adapter from operating normally.
4000 * (airmon-ng doesn't appear to use that, though.)
4002 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4003 * up, and if all drivers were converted to mac80211 drivers.
4005 * If interface {if} is a mac80211 driver, the file
4006 * /sys/class/net/{if}/phy80211 is a symlink to
4007 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4009 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4010 * least, has a "wmaster0" device and a "wlan0" device; the
4011 * latter is the one with the IP address. Both show up in
4012 * "tcpdump -D" output. Capturing on the wmaster0 device
4013 * captures with 802.11 headers.
4015 * airmon-ng searches through /sys/class/net for devices named
4016 * monN, starting with mon0; as soon as one *doesn't* exist,
4017 * it chooses that as the monitor device name. If the "iw"
4018 * command exists, it does "iw dev {if} interface add {monif}
4019 * type monitor", where {monif} is the monitor device. It
4020 * then (sigh) sleeps .1 second, and then configures the
4021 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4022 * is a file, it writes {mondev}, without a newline, to that file,
4023 * and again (sigh) sleeps .1 second, and then iwconfig's that
4024 * device into monitor mode and configures it up. Otherwise,
4025 * you can't do monitor mode.
4027 * All these devices are "glued" together by having the
4028 * /sys/class/net/{device}/phy80211 links pointing to the same
4029 * place, so, given a wmaster, wlan, or mon device, you can
4030 * find the other devices by looking for devices with
4031 * the same phy80211 link.
4033 * To turn monitor mode off, delete the monitor interface,
4034 * either with "iw dev {monif} interface del" or by sending
4035 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4037 * Note: if you try to create a monitor device named "monN", and
4038 * there's already a "monN" device, it fails, as least with
4039 * the netlink interface (which is what iw uses), with a return
4040 * value of -ENFILE. (Return values are negative errnos.) We
4041 * could probably use that to find an unused device.
4045 struct iw_priv_args
*priv
;
4046 monitor_type montype
;
4053 * Does this device *support* the Wireless Extensions?
4055 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4057 return err
; /* either it doesn't or the device doesn't even exist */
4059 * Try to get all the Wireless Extensions private ioctls
4060 * supported by this device.
4062 * First, get the size of the buffer we need, by supplying no
4063 * buffer and a length of 0. If the device supports private
4064 * ioctls, it should return E2BIG, with ireq.u.data.length set
4065 * to the length we need. If it doesn't support them, it should
4066 * return EOPNOTSUPP.
4068 memset(&ireq
, 0, sizeof ireq
);
4069 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4070 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4071 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4072 ireq
.u
.data
.pointer
= (void *)args
;
4073 ireq
.u
.data
.length
= 0;
4074 ireq
.u
.data
.flags
= 0;
4075 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4076 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4077 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4081 if (errno
== EOPNOTSUPP
) {
4083 * No private ioctls, so we assume that there's only one
4084 * DLT_ for monitor mode.
4088 if (errno
!= E2BIG
) {
4092 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4093 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4096 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4098 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4099 "malloc: %s", pcap_strerror(errno
));
4102 ireq
.u
.data
.pointer
= (void *)priv
;
4103 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4104 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4105 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4111 * Look for private ioctls to turn monitor mode on or, if
4112 * monitor mode is on, to set the header type.
4114 montype
= MONITOR_WEXT
;
4116 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4117 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4119 * Hostap driver, use this one.
4120 * Set monitor mode first.
4121 * You can set it to 0 to get DLT_IEEE80211,
4122 * 1 to get DLT_PRISM, 2 to get
4123 * DLT_IEEE80211_RADIO_AVS, and, with more
4124 * recent versions of the driver, 3 to get
4125 * DLT_IEEE80211_RADIO.
4127 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4129 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4131 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4133 montype
= MONITOR_HOSTAP
;
4137 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4139 * Prism54 driver, use this one.
4140 * Set monitor mode first.
4141 * You can set it to 2 to get DLT_IEEE80211
4142 * or 3 or get DLT_PRISM.
4144 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4146 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4148 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4150 montype
= MONITOR_PRISM54
;
4154 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4156 * RT2570 driver, use this one.
4157 * Do this after turning monitor mode on.
4158 * You can set it to 1 to get DLT_PRISM or 2
4159 * to get DLT_IEEE80211.
4161 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4163 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4165 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4167 montype
= MONITOR_RT2570
;
4171 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
4173 * RT73 driver, use this one.
4174 * Do this after turning monitor mode on.
4175 * Its argument is a *string*; you can
4176 * set it to "1" to get DLT_PRISM or "2"
4177 * to get DLT_IEEE80211.
4179 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
4181 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
4183 montype
= MONITOR_RT73
;
4187 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
4189 * One of the RTL8xxx drivers, use this one.
4190 * It can only be done after monitor mode
4191 * has been turned on. You can set it to 1
4192 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4194 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4196 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4198 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4200 montype
= MONITOR_RTL8XXX
;
4204 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
4206 * RT2500 or RT61 driver, use this one.
4207 * It has one one-byte parameter; set
4208 * u.data.length to 1 and u.data.pointer to
4209 * point to the parameter.
4210 * It doesn't itself turn monitor mode on.
4211 * You can set it to 1 to allow transmitting
4212 * in monitor mode(?) and get DLT_IEEE80211,
4213 * or set it to 0 to disallow transmitting in
4214 * monitor mode(?) and get DLT_PRISM.
4216 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4218 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
4220 montype
= MONITOR_RT2500
;
4224 if (strcmp(priv
[i
].name
, "monitor") == 0) {
4226 * Either ACX100 or hostap, use this one.
4227 * It turns monitor mode on.
4228 * If it takes two arguments, it's ACX100;
4229 * the first argument is 1 for DLT_PRISM
4230 * or 2 for DLT_IEEE80211, and the second
4231 * argument is the channel on which to
4232 * run. If it takes one argument, it's
4233 * HostAP, and the argument is 2 for
4234 * DLT_IEEE80211 and 3 for DLT_PRISM.
4236 * If we see this, we don't quit, as this
4237 * might be a version of the hostap driver
4238 * that also supports "monitor_type".
4240 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4242 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4244 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4247 montype
= MONITOR_PRISM
;
4252 montype
= MONITOR_ACX100
;
4264 * XXX - ipw3945? islism?
4270 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4271 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4272 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4273 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4275 * We probably won't be able to set the mode, either.
4277 return PCAP_ERROR_RFMON_NOTSUP
;
4281 * Is it currently in monitor mode?
4283 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4285 * Yes. Just leave things as they are.
4286 * We don't offer multiple link-layer types, as
4287 * changing the link-layer type out from under
4288 * somebody else capturing in monitor mode would
4289 * be considered rude.
4294 * No. We have to put the adapter into rfmon mode.
4298 * If we haven't already done so, arrange to have
4299 * "pcap_close_all()" called when we exit.
4301 if (!pcap_do_addexit(handle
)) {
4303 * "atexit()" failed; don't put the interface
4304 * in rfmon mode, just give up.
4306 return PCAP_ERROR_RFMON_NOTSUP
;
4310 * Save the old mode.
4312 handle
->md
.oldmode
= ireq
.u
.mode
;
4315 * Put the adapter in rfmon mode. How we do this depends
4316 * on whether we have a special private ioctl or not.
4318 if (montype
== MONITOR_PRISM
) {
4320 * We have the "monitor" private ioctl, but none of
4321 * the other private ioctls. Use this, and select
4324 * If it fails, just fall back on SIOCSIWMODE.
4326 memset(&ireq
, 0, sizeof ireq
);
4327 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4328 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4329 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4330 ireq
.u
.data
.length
= 1; /* 1 argument */
4331 args
[0] = 3; /* request Prism header */
4332 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4333 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4336 * Note that we have to put the old mode back
4337 * when we close the device.
4339 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4342 * Add this to the list of pcaps to close
4345 pcap_add_to_pcaps_to_close(handle
);
4351 * Failure. Fall back on SIOCSIWMODE.
4356 * First, turn monitor mode on.
4358 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4359 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4360 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4361 ireq
.u
.mode
= IW_MODE_MONITOR
;
4362 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4364 * Scientist, you've failed.
4366 return PCAP_ERROR_RFMON_NOTSUP
;
4370 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4371 * monitor mode and setting the channel, and then does
4376 * Now select the appropriate radio header.
4382 * We don't have any private ioctl to set the header.
4386 case MONITOR_HOSTAP
:
4388 * Try to select the radiotap header.
4390 memset(&ireq
, 0, sizeof ireq
);
4391 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4392 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4393 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4394 args
[0] = 3; /* request radiotap header */
4395 memcpy(ireq
.u
.name
, args
, sizeof (int));
4396 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4397 break; /* success */
4400 * That failed. Try to select the AVS header.
4402 memset(&ireq
, 0, sizeof ireq
);
4403 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4404 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4405 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4406 args
[0] = 2; /* request AVS header */
4407 memcpy(ireq
.u
.name
, args
, sizeof (int));
4408 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4409 break; /* success */
4412 * That failed. Try to select the Prism header.
4414 memset(&ireq
, 0, sizeof ireq
);
4415 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4416 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4417 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4418 args
[0] = 1; /* request Prism header */
4419 memcpy(ireq
.u
.name
, args
, sizeof (int));
4420 ioctl(sock_fd
, cmd
, &ireq
);
4425 * The private ioctl failed.
4429 case MONITOR_PRISM54
:
4431 * Select the Prism header.
4433 memset(&ireq
, 0, sizeof ireq
);
4434 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4435 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4436 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4437 args
[0] = 3; /* request Prism header */
4438 memcpy(ireq
.u
.name
, args
, sizeof (int));
4439 ioctl(sock_fd
, cmd
, &ireq
);
4442 case MONITOR_ACX100
:
4444 * Get the current channel.
4446 memset(&ireq
, 0, sizeof ireq
);
4447 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4448 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4449 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4450 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4451 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4452 "%s: SIOCGIWFREQ: %s", device
,
4453 pcap_strerror(errno
));
4456 channel
= ireq
.u
.freq
.m
;
4459 * Select the Prism header, and set the channel to the
4462 memset(&ireq
, 0, sizeof ireq
);
4463 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4464 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4465 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4466 args
[0] = 1; /* request Prism header */
4467 args
[1] = channel
; /* set channel */
4468 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4469 ioctl(sock_fd
, cmd
, &ireq
);
4472 case MONITOR_RT2500
:
4474 * Disallow transmission - that turns on the
4477 memset(&ireq
, 0, sizeof ireq
);
4478 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4479 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4480 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4481 args
[0] = 0; /* disallow transmitting */
4482 memcpy(ireq
.u
.name
, args
, sizeof (int));
4483 ioctl(sock_fd
, cmd
, &ireq
);
4486 case MONITOR_RT2570
:
4488 * Force the Prism header.
4490 memset(&ireq
, 0, sizeof ireq
);
4491 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4492 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4493 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4494 args
[0] = 1; /* request Prism header */
4495 memcpy(ireq
.u
.name
, args
, sizeof (int));
4496 ioctl(sock_fd
, cmd
, &ireq
);
4501 * Force the Prism header.
4503 memset(&ireq
, 0, sizeof ireq
);
4504 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4505 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4506 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4507 ireq
.u
.data
.length
= 1; /* 1 argument */
4508 ireq
.u
.data
.pointer
= "1";
4509 ireq
.u
.data
.flags
= 0;
4510 ioctl(sock_fd
, cmd
, &ireq
);
4513 case MONITOR_RTL8XXX
:
4515 * Force the Prism header.
4517 memset(&ireq
, 0, sizeof ireq
);
4518 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4519 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4520 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4521 args
[0] = 1; /* request Prism header */
4522 memcpy(ireq
.u
.name
, args
, sizeof (int));
4523 ioctl(sock_fd
, cmd
, &ireq
);
4528 * Note that we have to put the old mode back when we
4531 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4534 * Add this to the list of pcaps to close when we exit.
4536 pcap_add_to_pcaps_to_close(handle
);
4540 #endif /* IW_MODE_MONITOR */
4543 * Try various mechanisms to enter monitor mode.
4546 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4548 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4553 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4555 return ret
; /* error attempting to do so */
4557 return 1; /* success */
4558 #endif /* HAVE_LIBNL */
4560 #ifdef IW_MODE_MONITOR
4561 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4563 return ret
; /* error attempting to do so */
4565 return 1; /* success */
4566 #endif /* IW_MODE_MONITOR */
4569 * Either none of the mechanisms we know about work or none
4570 * of those mechanisms are available, so we can't do monitor
4576 #endif /* HAVE_PF_PACKET_SOCKETS */
4578 /* ===== Functions to interface to the older kernels ================== */
4581 * Try to open a packet socket using the old kernel interface.
4582 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4585 activate_old(pcap_t
*handle
)
4589 const char *device
= handle
->opt
.source
;
4590 struct utsname utsname
;
4593 /* Open the socket */
4595 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
4596 if (handle
->fd
== -1) {
4597 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4598 "socket: %s", pcap_strerror(errno
));
4599 return PCAP_ERROR_PERM_DENIED
;
4602 /* It worked - we are using the old interface */
4603 handle
->md
.sock_packet
= 1;
4605 /* ...which means we get the link-layer header. */
4606 handle
->md
.cooked
= 0;
4608 /* Bind to the given device */
4610 if (strcmp(device
, "any") == 0) {
4611 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4615 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
4619 * Try to get the link-layer type.
4621 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
4626 * Try to find the DLT_ type corresponding to that
4629 map_arphrd_to_dlt(handle
, arptype
, 0);
4630 if (handle
->linktype
== -1) {
4631 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4632 "unknown arptype %d", arptype
);
4636 /* Go to promisc mode if requested */
4638 if (handle
->opt
.promisc
) {
4639 memset(&ifr
, 0, sizeof(ifr
));
4640 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4641 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4642 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4643 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
4646 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
4648 * Promiscuous mode isn't currently on,
4649 * so turn it on, and remember that
4650 * we should turn it off when the
4655 * If we haven't already done so, arrange
4656 * to have "pcap_close_all()" called when
4659 if (!pcap_do_addexit(handle
)) {
4661 * "atexit()" failed; don't put
4662 * the interface in promiscuous
4663 * mode, just give up.
4668 ifr
.ifr_flags
|= IFF_PROMISC
;
4669 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4670 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4672 pcap_strerror(errno
));
4675 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
4678 * Add this to the list of pcaps
4679 * to close when we exit.
4681 pcap_add_to_pcaps_to_close(handle
);
4686 * Compute the buffer size.
4688 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4689 * kernel, and might require special handling - check.
4691 if (uname(&utsname
) < 0 ||
4692 strncmp(utsname
.release
, "2.0", 3) == 0) {
4694 * Either we couldn't find out what kernel release
4695 * this is, or it's a 2.0[.x] kernel.
4697 * In the 2.0[.x] kernel, a "recvfrom()" on
4698 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4699 * return the number of bytes read, so if we pass
4700 * a length based on the snapshot length, it'll
4701 * return the number of bytes from the packet
4702 * copied to userland, not the actual length
4705 * This means that, for example, the IP dissector
4706 * in tcpdump will get handed a packet length less
4707 * than the length in the IP header, and will
4708 * complain about "truncated-ip".
4710 * So we don't bother trying to copy from the
4711 * kernel only the bytes in which we're interested,
4712 * but instead copy them all, just as the older
4713 * versions of libpcap for Linux did.
4715 * The buffer therefore needs to be big enough to
4716 * hold the largest packet we can get from this
4717 * device. Unfortunately, we can't get the MRU
4718 * of the network; we can only get the MTU. The
4719 * MTU may be too small, in which case a packet larger
4720 * than the buffer size will be truncated *and* we
4721 * won't get the actual packet size.
4723 * However, if the snapshot length is larger than
4724 * the buffer size based on the MTU, we use the
4725 * snapshot length as the buffer size, instead;
4726 * this means that with a sufficiently large snapshot
4727 * length we won't artificially truncate packets
4728 * to the MTU-based size.
4730 * This mess just one of many problems with packet
4731 * capture on 2.0[.x] kernels; you really want a
4732 * 2.2[.x] or later kernel if you want packet capture
4735 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
4738 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
4739 if (handle
->bufsize
< handle
->snapshot
)
4740 handle
->bufsize
= handle
->snapshot
;
4743 * This is a 2.2[.x] or later kernel.
4745 * We can safely pass "recvfrom()" a byte count
4746 * based on the snapshot length.
4748 handle
->bufsize
= handle
->snapshot
;
4752 * Default value for offset to align link-layer payload
4753 * on a 4-byte boundary.
4761 * Bind the socket associated with FD to the given device using the
4762 * interface of the old kernels.
4765 iface_bind_old(int fd
, const char *device
, char *ebuf
)
4767 struct sockaddr saddr
;
4769 socklen_t errlen
= sizeof(err
);
4771 memset(&saddr
, 0, sizeof(saddr
));
4772 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
4773 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
4774 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4775 "bind: %s", pcap_strerror(errno
));
4779 /* Any pending errors, e.g., network is down? */
4781 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4782 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4783 "getsockopt: %s", pcap_strerror(errno
));
4788 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4789 "bind: %s", pcap_strerror(err
));
4797 /* ===== System calls available on all supported kernels ============== */
4800 * Query the kernel for the MTU of the given interface.
4803 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
4808 return BIGGER_THAN_ALL_MTUS
;
4810 memset(&ifr
, 0, sizeof(ifr
));
4811 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4813 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
4814 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4815 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4823 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4826 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4830 memset(&ifr
, 0, sizeof(ifr
));
4831 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4833 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4834 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4835 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4836 if (errno
== ENODEV
) {
4840 return PCAP_ERROR_NO_SUCH_DEVICE
;
4845 return ifr
.ifr_hwaddr
.sa_family
;
4848 #ifdef SO_ATTACH_FILTER
4850 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
4854 register struct bpf_insn
*p
;
4859 * Make a copy of the filter, and modify that copy if
4862 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4863 len
= handle
->fcode
.bf_len
;
4864 f
= (struct bpf_insn
*)malloc(prog_size
);
4866 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4867 "malloc: %s", pcap_strerror(errno
));
4870 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4872 fcode
->filter
= (struct sock_filter
*) f
;
4874 for (i
= 0; i
< len
; ++i
) {
4877 * What type of instruction is this?
4879 switch (BPF_CLASS(p
->code
)) {
4883 * It's a return instruction; are we capturing
4884 * in memory-mapped mode?
4888 * No; is the snapshot length a constant,
4889 * rather than the contents of the
4892 if (BPF_MODE(p
->code
) == BPF_K
) {
4894 * Yes - if the value to be returned,
4895 * i.e. the snapshot length, is
4896 * anything other than 0, make it
4897 * 65535, so that the packet is
4898 * truncated by "recvfrom()",
4899 * not by the filter.
4901 * XXX - there's nothing we can
4902 * easily do if it's getting the
4903 * value from the accumulator; we'd
4904 * have to insert code to force
4905 * non-zero values to be 65535.
4916 * It's a load instruction; is it loading
4919 switch (BPF_MODE(p
->code
)) {
4925 * Yes; are we in cooked mode?
4927 if (handle
->md
.cooked
) {
4929 * Yes, so we need to fix this
4932 if (fix_offset(p
) < 0) {
4934 * We failed to do so.
4935 * Return 0, so our caller
4936 * knows to punt to userland.
4946 return 1; /* we succeeded */
4950 fix_offset(struct bpf_insn
*p
)
4953 * What's the offset?
4955 if (p
->k
>= SLL_HDR_LEN
) {
4957 * It's within the link-layer payload; that starts at an
4958 * offset of 0, as far as the kernel packet filter is
4959 * concerned, so subtract the length of the link-layer
4962 p
->k
-= SLL_HDR_LEN
;
4963 } else if (p
->k
== 14) {
4965 * It's the protocol field; map it to the special magic
4966 * kernel offset for that field.
4968 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4971 * It's within the header, but it's not one of those
4972 * fields; we can't do that in the kernel, so punt
4981 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4983 int total_filter_on
= 0;
4989 * The socket filter code doesn't discard all packets queued
4990 * up on the socket when the filter is changed; this means
4991 * that packets that don't match the new filter may show up
4992 * after the new filter is put onto the socket, if those
4993 * packets haven't yet been read.
4995 * This means, for example, that if you do a tcpdump capture
4996 * with a filter, the first few packets in the capture might
4997 * be packets that wouldn't have passed the filter.
4999 * We therefore discard all packets queued up on the socket
5000 * when setting a kernel filter. (This isn't an issue for
5001 * userland filters, as the userland filtering is done after
5002 * packets are queued up.)
5004 * To flush those packets, we put the socket in read-only mode,
5005 * and read packets from the socket until there are no more to
5008 * In order to keep that from being an infinite loop - i.e.,
5009 * to keep more packets from arriving while we're draining
5010 * the queue - we put the "total filter", which is a filter
5011 * that rejects all packets, onto the socket before draining
5014 * This code deliberately ignores any errors, so that you may
5015 * get bogus packets if an error occurs, rather than having
5016 * the filtering done in userland even if it could have been
5017 * done in the kernel.
5019 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5020 &total_fcode
, sizeof(total_fcode
)) == 0) {
5024 * Note that we've put the total filter onto the socket.
5026 total_filter_on
= 1;
5029 * Save the socket's current mode, and put it in
5030 * non-blocking mode; we drain it by reading packets
5031 * until we get an error (which is normally a
5032 * "nothing more to be read" error).
5034 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5035 if (save_mode
!= -1 &&
5036 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
5037 while (recv(handle
->fd
, &drain
, sizeof drain
,
5041 fcntl(handle
->fd
, F_SETFL
, save_mode
);
5042 if (save_errno
!= EAGAIN
) {
5044 reset_kernel_filter(handle
);
5045 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5046 "recv: %s", pcap_strerror(save_errno
));
5053 * Now attach the new filter.
5055 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5056 fcode
, sizeof(*fcode
));
5057 if (ret
== -1 && total_filter_on
) {
5059 * Well, we couldn't set that filter on the socket,
5060 * but we could set the total filter on the socket.
5062 * This could, for example, mean that the filter was
5063 * too big to put into the kernel, so we'll have to
5064 * filter in userland; in any case, we'll be doing
5065 * filtering in userland, so we need to remove the
5066 * total filter so we see packets.
5071 * XXX - if this fails, we're really screwed;
5072 * we have the total filter on the socket,
5073 * and it won't come off. What do we do then?
5075 reset_kernel_filter(handle
);
5083 reset_kernel_filter(pcap_t
*handle
)
5086 * setsockopt() barfs unless it get a dummy parameter.
5087 * valgrind whines unless the value is initialized,
5088 * as it has no idea that setsockopt() ignores its
5093 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5094 &dummy
, sizeof(dummy
));