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_UNSYNC
;
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 struct nl80211_state
{
531 struct nl_handle
*nl_handle
;
532 struct nl_cache
*nl_cache
;
533 struct genl_family
*nl80211
;
537 nl80211_init(pcap_t
*handle
, struct nl80211_state
*state
, const char *device
)
539 state
->nl_handle
= nl_handle_alloc();
540 if (!state
->nl_handle
) {
541 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
542 "%s: failed to allocate netlink handle", device
);
546 if (genl_connect(state
->nl_handle
)) {
547 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
548 "%s: failed to connect to generic netlink", device
);
549 goto out_handle_destroy
;
552 state
->nl_cache
= genl_ctrl_alloc_cache(state
->nl_handle
);
553 if (!state
->nl_cache
) {
554 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
555 "%s: failed to allocate generic netlink cache", device
);
556 goto out_handle_destroy
;
559 state
->nl80211
= genl_ctrl_search_by_name(state
->nl_cache
, "nl80211");
560 if (!state
->nl80211
) {
561 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
562 "%s: nl80211 not found", device
);
569 nl_cache_free(state
->nl_cache
);
571 nl_handle_destroy(state
->nl_handle
);
576 nl80211_cleanup(struct nl80211_state
*state
)
578 genl_family_put(state
->nl80211
);
579 nl_cache_free(state
->nl_cache
);
580 nl_handle_destroy(state
->nl_handle
);
584 add_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
585 const char *device
, const char *mondevice
)
591 ifindex
= iface_get_id(sock_fd
, device
, handle
->errbuf
);
597 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
598 "%s: failed to allocate netlink msg", device
);
602 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
603 0, NL80211_CMD_NEW_INTERFACE
, 0);
604 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
605 NLA_PUT_STRING(msg
, NL80211_ATTR_IFNAME
, mondevice
);
606 NLA_PUT_U32(msg
, NL80211_ATTR_IFTYPE
, NL80211_IFTYPE_MONITOR
);
608 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
610 if (err
== -ENFILE
) {
612 * Device not available; our caller should just
619 * Real failure, not just "that device is not
622 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
623 "%s: nl_send_auto_complete failed adding %s interface: %s",
624 device
, mondevice
, strerror(-err
));
629 err
= nl_wait_for_ack(state
->nl_handle
);
631 if (err
== -ENFILE
) {
633 * Device not available; our caller should just
640 * Real failure, not just "that device is not
643 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
644 "%s: nl_wait_for_ack failed adding %s interface: %s",
645 device
, mondevice
, strerror(-err
));
658 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
659 "%s: nl_put failed adding %s interface",
666 del_mon_if(pcap_t
*handle
, int sock_fd
, struct nl80211_state
*state
,
667 const char *device
, const char *mondevice
)
673 ifindex
= iface_get_id(sock_fd
, mondevice
, handle
->errbuf
);
679 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
680 "%s: failed to allocate netlink msg", device
);
684 genlmsg_put(msg
, 0, 0, genl_family_get_id(state
->nl80211
), 0,
685 0, NL80211_CMD_DEL_INTERFACE
, 0);
686 NLA_PUT_U32(msg
, NL80211_ATTR_IFINDEX
, ifindex
);
688 err
= nl_send_auto_complete(state
->nl_handle
, msg
);
690 if (err
== -ENFILE
) {
692 * Device not available; our caller should just
699 * Real failure, not just "that device is not
702 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
703 "%s: nl_send_auto_complete failed deleting %s interface: %s",
704 device
, mondevice
, strerror(-err
));
709 err
= nl_wait_for_ack(state
->nl_handle
);
711 if (err
== -ENFILE
) {
713 * Device not available; our caller should just
720 * Real failure, not just "that device is not
723 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
724 "%s: nl_wait_for_ack failed adding %s interface: %s",
725 device
, mondevice
, strerror(-err
));
738 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
739 "%s: nl_put failed deleting %s interface",
746 enter_rfmon_mode_mac80211(pcap_t
*handle
, int sock_fd
, const char *device
)
749 char phydev_path
[PATH_MAX
+1];
750 struct nl80211_state nlstate
;
755 * Is this a mac80211 device?
757 ret
= get_mac80211_phydev(handle
, device
, phydev_path
, PATH_MAX
);
759 return ret
; /* error */
761 return 0; /* no error, but not mac80211 device */
764 * XXX - is this already a monN device?
766 * Is that determined by old Wireless Extensions ioctls?
770 * OK, it's apparently a mac80211 device.
771 * Try to find an unused monN device for it.
773 ret
= nl80211_init(handle
, &nlstate
, device
);
776 for (n
= 0; n
< UINT_MAX
; n
++) {
780 char mondevice
[3+10+1]; /* mon{UINT_MAX}\0 */
782 snprintf(mondevice
, sizeof mondevice
, "mon%u", n
);
783 ret
= add_mon_if(handle
, sock_fd
, &nlstate
, device
, mondevice
);
785 handle
->md
.mondevice
= strdup(mondevice
);
790 * Hard failure. Just return ret; handle->errbuf
791 * has already been set.
793 nl80211_cleanup(&nlstate
);
798 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
799 "%s: No free monN interfaces", device
);
800 nl80211_cleanup(&nlstate
);
807 * Sleep for .1 seconds.
810 delay
.tv_nsec
= 500000000;
811 nanosleep(&delay
, NULL
);
815 * Now configure the monitor interface up.
817 memset(&ifr
, 0, sizeof(ifr
));
818 strncpy(ifr
.ifr_name
, handle
->md
.mondevice
, sizeof(ifr
.ifr_name
));
819 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
820 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
821 "%s: Can't get flags for %s: %s", device
,
822 handle
->md
.mondevice
, strerror(errno
));
823 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
824 handle
->md
.mondevice
);
825 nl80211_cleanup(&nlstate
);
828 ifr
.ifr_flags
|= IFF_UP
|IFF_RUNNING
;
829 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
830 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
831 "%s: Can't set flags for %s: %s", device
,
832 handle
->md
.mondevice
, strerror(errno
));
833 del_mon_if(handle
, sock_fd
, &nlstate
, device
,
834 handle
->md
.mondevice
);
835 nl80211_cleanup(&nlstate
);
840 * Success. Clean up the libnl state.
842 nl80211_cleanup(&nlstate
);
845 * Note that we have to delete the monitor device when we close
848 handle
->md
.must_do_on_close
|= MUST_DELETE_MONIF
;
851 * Add this to the list of pcaps to close when we exit.
853 pcap_add_to_pcaps_to_close(handle
);
857 #endif /* HAVE_LIBNL */
860 pcap_can_set_rfmon_linux(pcap_t
*handle
)
863 char phydev_path
[PATH_MAX
+1];
866 #ifdef IW_MODE_MONITOR
871 if (strcmp(handle
->opt
.source
, "any") == 0) {
873 * Monitor mode makes no sense on the "any" device.
880 * Bleah. There doesn't seem to be a way to ask a mac80211
881 * device, through libnl, whether it supports monitor mode;
882 * we'll just check whether the device appears to be a
883 * mac80211 device and, if so, assume the device supports
886 * wmaster devices don't appear to support the Wireless
887 * Extensions, but we can create a mon device for a
888 * wmaster device, so we don't bother checking whether
889 * a mac80211 device supports the Wireless Extensions.
891 ret
= get_mac80211_phydev(handle
, handle
->opt
.source
, phydev_path
,
894 return ret
; /* error */
896 return 1; /* mac80211 device */
899 #ifdef IW_MODE_MONITOR
901 * Bleah. There doesn't appear to be an ioctl to use to ask
902 * whether a device supports monitor mode; we'll just do
903 * SIOCGIWMODE and, if it succeeds, assume the device supports
906 * Open a socket on which to attempt to get the mode.
907 * (We assume that if we have Wireless Extensions support
908 * we also have PF_PACKET support.)
910 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
912 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
913 "socket: %s", pcap_strerror(errno
));
918 * Attempt to get the current mode.
920 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->opt
.source
,
921 sizeof ireq
.ifr_ifrn
.ifrn_name
);
922 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
923 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
925 * Well, we got the mode; assume we can set it.
930 if (errno
== ENODEV
) {
931 /* The device doesn't even exist. */
932 (void)snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
933 "SIOCGIWMODE failed: %s", pcap_strerror(errno
));
935 return PCAP_ERROR_NO_SUCH_DEVICE
;
943 * Grabs the number of dropped packets by the interface from /proc/net/dev.
945 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
946 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
948 * Or can we get them in binary form from netlink?
951 linux_if_drops(const char * if_name
)
956 int field_to_convert
= 3, if_name_sz
= strlen(if_name
);
957 long int dropped_pkts
= 0;
959 file
= fopen("/proc/net/dev", "r");
963 while (!dropped_pkts
&& fgets( buffer
, sizeof(buffer
), file
))
965 /* search for 'bytes' -- if its in there, then
966 that means we need to grab the fourth field. otherwise
967 grab the third field. */
968 if (field_to_convert
!= 4 && strstr(buffer
, "bytes"))
970 field_to_convert
= 4;
974 /* find iface and make sure it actually matches -- space before the name and : after it */
975 if ((bufptr
= strstr(buffer
, if_name
)) &&
976 (bufptr
== buffer
|| *(bufptr
-1) == ' ') &&
977 *(bufptr
+ if_name_sz
) == ':')
979 bufptr
= bufptr
+ if_name_sz
+ 1;
981 /* grab the nth field from it */
982 while( --field_to_convert
&& *bufptr
!= '\0')
984 while (*bufptr
!= '\0' && *(bufptr
++) == ' ');
985 while (*bufptr
!= '\0' && *(bufptr
++) != ' ');
988 /* get rid of any final spaces */
989 while (*bufptr
!= '\0' && *bufptr
== ' ') bufptr
++;
992 dropped_pkts
= strtol(bufptr
, NULL
, 10);
1004 * With older kernels promiscuous mode is kind of interesting because we
1005 * have to reset the interface before exiting. The problem can't really
1006 * be solved without some daemon taking care of managing usage counts.
1007 * If we put the interface into promiscuous mode, we set a flag indicating
1008 * that we must take it out of that mode when the interface is closed,
1009 * and, when closing the interface, if that flag is set we take it out
1010 * of promiscuous mode.
1012 * Even with newer kernels, we have the same issue with rfmon mode.
1015 static void pcap_cleanup_linux( pcap_t
*handle
)
1019 struct nl80211_state nlstate
;
1021 #endif /* HAVE_LIBNL */
1022 #ifdef IW_MODE_MONITOR
1024 #endif /* IW_MODE_MONITOR */
1026 if (handle
->md
.must_do_on_close
!= 0) {
1028 * There's something we have to do when closing this
1031 if (handle
->md
.must_do_on_close
& MUST_CLEAR_PROMISC
) {
1033 * We put the interface into promiscuous mode;
1034 * take it out of promiscuous mode.
1036 * XXX - if somebody else wants it in promiscuous
1037 * mode, this code cannot know that, so it'll take
1038 * it out of promiscuous mode. That's not fixable
1039 * in 2.0[.x] kernels.
1041 memset(&ifr
, 0, sizeof(ifr
));
1042 strncpy(ifr
.ifr_name
, handle
->md
.device
,
1043 sizeof(ifr
.ifr_name
));
1044 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1046 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1047 "Please adjust manually.\n"
1048 "Hint: This can't happen with Linux >= 2.2.0.\n",
1051 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1053 * Promiscuous mode is currently on;
1056 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1057 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
1060 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1061 "Please adjust manually.\n"
1062 "Hint: This can't happen with Linux >= 2.2.0.\n",
1070 if (handle
->md
.must_do_on_close
& MUST_DELETE_MONIF
) {
1071 ret
= nl80211_init(handle
, &nlstate
, handle
->md
.device
);
1073 ret
= del_mon_if(handle
, handle
->fd
, &nlstate
,
1074 handle
->md
.device
, handle
->md
.mondevice
);
1075 nl80211_cleanup(&nlstate
);
1079 "Can't delete monitor interface %s (%s).\n"
1080 "Please delete manually.\n",
1081 handle
->md
.mondevice
, handle
->errbuf
);
1084 #endif /* HAVE_LIBNL */
1086 #ifdef IW_MODE_MONITOR
1087 if (handle
->md
.must_do_on_close
& MUST_CLEAR_RFMON
) {
1089 * We put the interface into rfmon mode;
1090 * take it out of rfmon mode.
1092 * XXX - if somebody else wants it in rfmon
1093 * mode, this code cannot know that, so it'll take
1094 * it out of rfmon mode.
1096 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
1097 sizeof ireq
.ifr_ifrn
.ifrn_name
);
1098 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
1100 ireq
.u
.mode
= handle
->md
.oldmode
;
1101 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
1103 * Scientist, you've failed.
1106 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1107 "Please adjust manually.\n",
1111 #endif /* IW_MODE_MONITOR */
1114 * Take this pcap out of the list of pcaps for which we
1115 * have to take the interface out of some mode.
1117 pcap_remove_from_pcaps_to_close(handle
);
1120 if (handle
->md
.mondevice
!= NULL
) {
1121 free(handle
->md
.mondevice
);
1122 handle
->md
.mondevice
= NULL
;
1124 if (handle
->md
.device
!= NULL
) {
1125 free(handle
->md
.device
);
1126 handle
->md
.device
= NULL
;
1128 pcap_cleanup_live_common(handle
);
1132 * Get a handle for a live capture from the given device. You can
1133 * pass NULL as device to get all packages (without link level
1134 * information of course). If you pass 1 as promisc the interface
1135 * will be set to promiscous mode (XXX: I think this usage should
1136 * be deprecated and functions be added to select that later allow
1137 * modification of that values -- Torsten).
1140 pcap_activate_linux(pcap_t
*handle
)
1145 device
= handle
->opt
.source
;
1147 handle
->inject_op
= pcap_inject_linux
;
1148 handle
->setfilter_op
= pcap_setfilter_linux
;
1149 handle
->setdirection_op
= pcap_setdirection_linux
;
1150 handle
->set_datalink_op
= NULL
; /* can't change data link type */
1151 handle
->getnonblock_op
= pcap_getnonblock_fd
;
1152 handle
->setnonblock_op
= pcap_setnonblock_fd
;
1153 handle
->cleanup_op
= pcap_cleanup_linux
;
1154 handle
->read_op
= pcap_read_linux
;
1155 handle
->stats_op
= pcap_stats_linux
;
1158 * The "any" device is a special device which causes us not
1159 * to bind to a particular device and thus to look at all
1162 if (strcmp(device
, "any") == 0) {
1163 if (handle
->opt
.promisc
) {
1164 handle
->opt
.promisc
= 0;
1165 /* Just a warning. */
1166 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1167 "Promiscuous mode not supported on the \"any\" device");
1168 status
= PCAP_WARNING_PROMISC_NOTSUP
;
1172 handle
->md
.device
= strdup(device
);
1173 if (handle
->md
.device
== NULL
) {
1174 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
1175 pcap_strerror(errno
) );
1180 * If we're in promiscuous mode, then we probably want
1181 * to see when the interface drops packets too, so get an
1182 * initial count from /proc/net/dev
1184 if (handle
->opt
.promisc
)
1185 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1188 * Current Linux kernels use the protocol family PF_PACKET to
1189 * allow direct access to all packets on the network while
1190 * older kernels had a special socket type SOCK_PACKET to
1191 * implement this feature.
1192 * While this old implementation is kind of obsolete we need
1193 * to be compatible with older kernels for a while so we are
1194 * trying both methods with the newer method preferred.
1196 status
= activate_new(handle
);
1199 * Fatal error with the new way; just fail.
1200 * status has the error return; if it's PCAP_ERROR,
1201 * handle->errbuf has been set appropriately.
1208 * Try to use memory-mapped access.
1210 switch (activate_mmap(handle
, &status
)) {
1214 * We succeeded. status has been
1215 * set to the status to return,
1216 * which might be 0, or might be
1217 * a PCAP_WARNING_ value.
1223 * Kernel doesn't support it - just continue
1224 * with non-memory-mapped access.
1230 * We failed to set up to use it, or the kernel
1231 * supports it, but we failed to enable it.
1232 * status has been set to the error status to
1233 * return and, if it's PCAP_ERROR, handle->errbuf
1234 * contains the error message.
1239 else if (status
== 0) {
1240 /* Non-fatal error; try old way */
1241 if ((status
= activate_old(handle
)) != 1) {
1243 * Both methods to open the packet socket failed.
1244 * Tidy up and report our failure (handle->errbuf
1245 * is expected to be set by the functions above).
1252 * We set up the socket, but not with memory-mapped access.
1255 if (handle
->opt
.buffer_size
!= 0) {
1257 * Set the socket buffer size to the specified value.
1259 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
1260 &handle
->opt
.buffer_size
,
1261 sizeof(handle
->opt
.buffer_size
)) == -1) {
1262 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1263 "SO_RCVBUF: %s", pcap_strerror(errno
));
1264 status
= PCAP_ERROR
;
1269 /* Allocate the buffer */
1271 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
1272 if (!handle
->buffer
) {
1273 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1274 "malloc: %s", pcap_strerror(errno
));
1275 status
= PCAP_ERROR
;
1280 * "handle->fd" is a socket, so "select()" and "poll()"
1281 * should work on it.
1283 handle
->selectable_fd
= handle
->fd
;
1288 pcap_cleanup_linux(handle
);
1293 * Read at most max_packets from the capture stream and call the callback
1294 * for each of them. Returns the number of packets handled or -1 if an
1298 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
1301 * Currently, on Linux only one packet is delivered per read,
1304 return pcap_read_packet(handle
, callback
, user
);
1308 * Read a packet from the socket calling the handler provided by
1309 * the user. Returns the number of packets received or -1 if an
1313 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
1317 #ifdef HAVE_PF_PACKET_SOCKETS
1318 struct sockaddr_ll from
;
1319 struct sll_header
*hdrp
;
1321 struct sockaddr from
;
1323 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1326 struct cmsghdr
*cmsg
;
1328 struct cmsghdr cmsg
;
1329 char buf
[CMSG_SPACE(sizeof(struct tpacket_auxdata
))];
1331 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1333 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1334 int packet_len
, caplen
;
1335 struct pcap_pkthdr pcap_header
;
1337 #ifdef HAVE_PF_PACKET_SOCKETS
1339 * If this is a cooked device, leave extra room for a
1340 * fake packet header.
1342 if (handle
->md
.cooked
)
1343 offset
= SLL_HDR_LEN
;
1348 * This system doesn't have PF_PACKET sockets, so it doesn't
1349 * support cooked devices.
1355 * Receive a single packet from the kernel.
1356 * We ignore EINTR, as that might just be due to a signal
1357 * being delivered - if the signal should interrupt the
1358 * loop, the signal handler should call pcap_breakloop()
1359 * to set handle->break_loop (we ignore it on other
1360 * platforms as well).
1361 * We also ignore ENETDOWN, so that we can continue to
1362 * capture traffic if the interface goes down and comes
1363 * back up again; comments in the kernel indicate that
1364 * we'll just block waiting for packets if we try to
1365 * receive from a socket that delivered ENETDOWN, and,
1366 * if we're using a memory-mapped buffer, we won't even
1367 * get notified of "network down" events.
1369 bp
= handle
->buffer
+ handle
->offset
;
1371 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1372 msg
.msg_name
= &from
;
1373 msg
.msg_namelen
= sizeof(from
);
1376 msg
.msg_control
= &cmsg_buf
;
1377 msg
.msg_controllen
= sizeof(cmsg_buf
);
1380 iov
.iov_len
= handle
->bufsize
- offset
;
1381 iov
.iov_base
= bp
+ offset
;
1382 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1386 * Has "pcap_breakloop()" been called?
1388 if (handle
->break_loop
) {
1390 * Yes - clear the flag that indicates that it has,
1391 * and return PCAP_ERROR_BREAK as an indication that
1392 * we were told to break out of the loop.
1394 handle
->break_loop
= 0;
1395 return PCAP_ERROR_BREAK
;
1398 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1399 packet_len
= recvmsg(handle
->fd
, &msg
, MSG_TRUNC
);
1400 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1401 fromlen
= sizeof(from
);
1402 packet_len
= recvfrom(
1403 handle
->fd
, bp
+ offset
,
1404 handle
->bufsize
- offset
, MSG_TRUNC
,
1405 (struct sockaddr
*) &from
, &fromlen
);
1406 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1407 } while (packet_len
== -1 && errno
== EINTR
);
1409 /* Check if an error occured */
1411 if (packet_len
== -1) {
1415 return 0; /* no packet there */
1419 * The device on which we're capturing went away.
1421 * XXX - we should really return
1422 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1423 * etc. aren't defined to return that.
1425 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1426 "The interface went down");
1430 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1431 "recvfrom: %s", pcap_strerror(errno
));
1436 #ifdef HAVE_PF_PACKET_SOCKETS
1437 if (!handle
->md
.sock_packet
) {
1439 * Unfortunately, there is a window between socket() and
1440 * bind() where the kernel may queue packets from any
1441 * interface. If we're bound to a particular interface,
1442 * discard packets not from that interface.
1444 * (If socket filters are supported, we could do the
1445 * same thing we do when changing the filter; however,
1446 * that won't handle packet sockets without socket
1447 * filter support, and it's a bit more complicated.
1448 * It would save some instructions per packet, however.)
1450 if (handle
->md
.ifindex
!= -1 &&
1451 from
.sll_ifindex
!= handle
->md
.ifindex
)
1455 * Do checks based on packet direction.
1456 * We can only do this if we're using PF_PACKET; the
1457 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1458 * which lacks the relevant packet type information.
1460 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
1463 * If this is from the loopback device, reject it;
1464 * we'll see the packet as an incoming packet as well,
1465 * and we don't want to see it twice.
1467 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
1471 * If the user only wants incoming packets, reject it.
1473 if (handle
->direction
== PCAP_D_IN
)
1478 * If the user only wants outgoing packets, reject it.
1480 if (handle
->direction
== PCAP_D_OUT
)
1486 #ifdef HAVE_PF_PACKET_SOCKETS
1488 * If this is a cooked device, fill in the fake packet header.
1490 if (handle
->md
.cooked
) {
1492 * Add the length of the fake header to the length
1493 * of packet data we read.
1495 packet_len
+= SLL_HDR_LEN
;
1497 hdrp
= (struct sll_header
*)bp
;
1498 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
1499 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
1500 hdrp
->sll_halen
= htons(from
.sll_halen
);
1501 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
1502 (from
.sll_halen
> SLL_ADDRLEN
) ?
1505 hdrp
->sll_protocol
= from
.sll_protocol
;
1508 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1509 for (cmsg
= CMSG_FIRSTHDR(&msg
); cmsg
; cmsg
= CMSG_NXTHDR(&msg
, cmsg
)) {
1510 struct tpacket_auxdata
*aux
;
1512 struct vlan_tag
*tag
;
1514 if (cmsg
->cmsg_len
< CMSG_LEN(sizeof(struct tpacket_auxdata
)) ||
1515 cmsg
->cmsg_level
!= SOL_PACKET
||
1516 cmsg
->cmsg_type
!= PACKET_AUXDATA
)
1519 aux
= (struct tpacket_auxdata
*)CMSG_DATA(cmsg
);
1520 if (aux
->tp_vlan_tci
== 0)
1523 len
= packet_len
> iov
.iov_len
? iov
.iov_len
: packet_len
;
1524 if (len
< 2 * ETH_ALEN
)
1528 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
1530 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
1531 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
1532 tag
->vlan_tci
= htons(aux
->tp_vlan_tci
);
1534 packet_len
+= VLAN_TAG_LEN
;
1536 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1537 #endif /* HAVE_PF_PACKET_SOCKETS */
1540 * XXX: According to the kernel source we should get the real
1541 * packet len if calling recvfrom with MSG_TRUNC set. It does
1542 * not seem to work here :(, but it is supported by this code
1544 * To be honest the code RELIES on that feature so this is really
1545 * broken with 2.2.x kernels.
1546 * I spend a day to figure out what's going on and I found out
1547 * that the following is happening:
1549 * The packet comes from a random interface and the packet_rcv
1550 * hook is called with a clone of the packet. That code inserts
1551 * the packet into the receive queue of the packet socket.
1552 * If a filter is attached to that socket that filter is run
1553 * first - and there lies the problem. The default filter always
1554 * cuts the packet at the snaplen:
1559 * So the packet filter cuts down the packet. The recvfrom call
1560 * says "hey, it's only 68 bytes, it fits into the buffer" with
1561 * the result that we don't get the real packet length. This
1562 * is valid at least until kernel 2.2.17pre6.
1564 * We currently handle this by making a copy of the filter
1565 * program, fixing all "ret" instructions with non-zero
1566 * operands to have an operand of 65535 so that the filter
1567 * doesn't truncate the packet, and supplying that modified
1568 * filter to the kernel.
1571 caplen
= packet_len
;
1572 if (caplen
> handle
->snapshot
)
1573 caplen
= handle
->snapshot
;
1575 /* Run the packet filter if not using kernel filter */
1576 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
1577 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1578 packet_len
, caplen
) == 0)
1580 /* rejected by filter */
1585 /* Fill in our own header data */
1587 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
1588 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1589 "SIOCGSTAMP: %s", pcap_strerror(errno
));
1592 pcap_header
.caplen
= caplen
;
1593 pcap_header
.len
= packet_len
;
1598 * Arguably, we should count them before we check the filter,
1599 * as on many other platforms "ps_recv" counts packets
1600 * handed to the filter rather than packets that passed
1601 * the filter, but if filtering is done in the kernel, we
1602 * can't get a count of packets that passed the filter,
1603 * and that would mean the meaning of "ps_recv" wouldn't
1604 * be the same on all Linux systems.
1606 * XXX - it's not the same on all systems in any case;
1607 * ideally, we should have a "get the statistics" call
1608 * that supplies more counts and indicates which of them
1609 * it supplies, so that we supply a count of packets
1610 * handed to the filter only on platforms where that
1611 * information is available.
1613 * We count them here even if we can get the packet count
1614 * from the kernel, as we can only determine at run time
1615 * whether we'll be able to get it from the kernel (if
1616 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1617 * the kernel, but if it is defined, the library might
1618 * have been built with a 2.4 or later kernel, but we
1619 * might be running on a 2.2[.x] kernel without Alexey
1620 * Kuznetzov's turbopacket patches, and thus the kernel
1621 * might not be able to supply those statistics). We
1622 * could, I guess, try, when opening the socket, to get
1623 * the statistics, and if we can not increment the count
1624 * here, but it's not clear that always incrementing
1625 * the count is more expensive than always testing a flag
1628 * We keep the count in "md.packets_read", and use that for
1629 * "ps_recv" if we can't get the statistics from the kernel.
1630 * We do that because, if we *can* get the statistics from
1631 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1632 * as running counts, as reading the statistics from the
1633 * kernel resets the kernel statistics, and if we directly
1634 * increment "md.stat.ps_recv" here, that means it will
1635 * count packets *twice* on systems where we can get kernel
1636 * statistics - once here, and once in pcap_stats_linux().
1638 handle
->md
.packets_read
++;
1640 /* Call the user supplied callback function */
1641 callback(userdata
, &pcap_header
, bp
);
1647 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
1651 #ifdef HAVE_PF_PACKET_SOCKETS
1652 if (!handle
->md
.sock_packet
) {
1653 /* PF_PACKET socket */
1654 if (handle
->md
.ifindex
== -1) {
1656 * We don't support sending on the "any" device.
1658 strlcpy(handle
->errbuf
,
1659 "Sending packets isn't supported on the \"any\" device",
1664 if (handle
->md
.cooked
) {
1666 * We don't support sending on the "any" device.
1668 * XXX - how do you send on a bound cooked-mode
1670 * Is a "sendto()" required there?
1672 strlcpy(handle
->errbuf
,
1673 "Sending packets isn't supported in cooked mode",
1680 ret
= send(handle
->fd
, buf
, size
, 0);
1682 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
1683 pcap_strerror(errno
));
1690 * Get the statistics for the given packet capture handle.
1691 * Reports the number of dropped packets iff the kernel supports
1692 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1693 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1694 * patches); otherwise, that information isn't available, and we lie
1695 * and report 0 as the count of dropped packets.
1698 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
1700 #ifdef HAVE_TPACKET_STATS
1701 struct tpacket_stats kstats
;
1702 socklen_t len
= sizeof (struct tpacket_stats
);
1705 long if_dropped
= 0;
1708 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1710 if (handle
->opt
.promisc
)
1712 if_dropped
= handle
->md
.proc_dropped
;
1713 handle
->md
.proc_dropped
= linux_if_drops(handle
->md
.device
);
1714 handle
->md
.stat
.ps_ifdrop
+= (handle
->md
.proc_dropped
- if_dropped
);
1717 #ifdef HAVE_TPACKET_STATS
1719 * Try to get the packet counts from the kernel.
1721 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
1722 &kstats
, &len
) > -1) {
1724 * On systems where the PACKET_STATISTICS "getsockopt()"
1725 * argument is supported on PF_PACKET sockets:
1727 * "ps_recv" counts only packets that *passed* the
1728 * filter, not packets that didn't pass the filter.
1729 * This includes packets later dropped because we
1730 * ran out of buffer space.
1732 * "ps_drop" counts packets dropped because we ran
1733 * out of buffer space. It doesn't count packets
1734 * dropped by the interface driver. It counts only
1735 * packets that passed the filter.
1737 * See above for ps_ifdrop.
1739 * Both statistics include packets not yet read from
1740 * the kernel by libpcap, and thus not yet seen by
1743 * In "linux/net/packet/af_packet.c", at least in the
1744 * 2.4.9 kernel, "tp_packets" is incremented for every
1745 * packet that passes the packet filter *and* is
1746 * successfully queued on the socket; "tp_drops" is
1747 * incremented for every packet dropped because there's
1748 * not enough free space in the socket buffer.
1750 * When the statistics are returned for a PACKET_STATISTICS
1751 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1752 * so that "tp_packets" counts all packets handed to
1753 * the PF_PACKET socket, including packets dropped because
1754 * there wasn't room on the socket buffer - but not
1755 * including packets that didn't pass the filter.
1757 * In the BSD BPF, the count of received packets is
1758 * incremented for every packet handed to BPF, regardless
1759 * of whether it passed the filter.
1761 * We can't make "pcap_stats()" work the same on both
1762 * platforms, but the best approximation is to return
1763 * "tp_packets" as the count of packets and "tp_drops"
1764 * as the count of drops.
1766 * Keep a running total because each call to
1767 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1768 * resets the counters to zero.
1770 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
1771 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
1772 *stats
= handle
->md
.stat
;
1778 * If the error was EOPNOTSUPP, fall through, so that
1779 * if you build the library on a system with
1780 * "struct tpacket_stats" and run it on a system
1781 * that doesn't, it works as it does if the library
1782 * is built on a system without "struct tpacket_stats".
1784 if (errno
!= EOPNOTSUPP
) {
1785 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1786 "pcap_stats: %s", pcap_strerror(errno
));
1792 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1793 * is not supported on PF_PACKET sockets:
1795 * "ps_recv" counts only packets that *passed* the filter,
1796 * not packets that didn't pass the filter. It does not
1797 * count packets dropped because we ran out of buffer
1800 * "ps_drop" is not supported.
1802 * "ps_ifdrop" is supported. It will return the number
1803 * of drops the interface reports in /proc/net/dev,
1804 * if that is available.
1806 * "ps_recv" doesn't include packets not yet read from
1807 * the kernel by libpcap.
1809 * We maintain the count of packets processed by libpcap in
1810 * "md.packets_read", for reasons described in the comment
1811 * at the end of pcap_read_packet(). We have no idea how many
1812 * packets were dropped by the kernel buffers -- but we know
1813 * how many the interface dropped, so we can return that.
1816 stats
->ps_recv
= handle
->md
.packets_read
;
1818 stats
->ps_ifdrop
= handle
->md
.stat
.ps_ifdrop
;
1823 * Get from "/sys/class/net" all interfaces listed there; if they're
1824 * already in the list of interfaces we have, that won't add another
1825 * instance, but if they're not, that'll add them.
1827 * We don't bother getting any addresses for them; it appears you can't
1828 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1829 * although some other types of addresses can be fetched with SIOCGIFADDR,
1830 * we don't bother with them for now.
1832 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1833 * the list of interfaces as is, and return 0, so that we can try
1834 * scanning /proc/net/dev.
1837 scan_sys_class_net(pcap_if_t
**devlistp
, char *errbuf
)
1839 DIR *sys_class_net_d
;
1843 char name
[512]; /* XXX - pick a size */
1845 struct ifreq ifrflags
;
1848 sys_class_net_d
= opendir("/sys/class/net");
1849 if (sys_class_net_d
== NULL
&& errno
== ENOENT
)
1853 * Create a socket from which to fetch interface information.
1855 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1857 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1858 "socket: %s", pcap_strerror(errno
));
1864 ent
= readdir(sys_class_net_d
);
1867 * Error or EOF; if errno != 0, it's an error.
1873 * Ignore directories (".", "..", and any subdirectories).
1875 if (ent
->d_type
== DT_DIR
)
1879 * Get the interface name.
1881 p
= &ent
->d_name
[0];
1883 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
1886 * This could be the separator between a
1887 * name and an alias number, or it could be
1888 * the separator between a name with no
1889 * alias number and the next field.
1891 * If there's a colon after digits, it
1892 * separates the name and the alias number,
1893 * otherwise it separates the name and the
1897 while (isascii(*p
) && isdigit(*p
))
1901 * That was the next field,
1902 * not the alias number.
1913 * Get the flags for this interface, and skip it if
1916 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
1917 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
1918 if (errno
== ENXIO
|| errno
== ENODEV
)
1920 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1921 "SIOCGIFFLAGS: %.*s: %s",
1922 (int)sizeof(ifrflags
.ifr_name
),
1924 pcap_strerror(errno
));
1928 if (!(ifrflags
.ifr_flags
& IFF_UP
))
1932 * Add an entry for this interface, with no addresses.
1934 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
1945 * Well, we didn't fail for any other reason; did we
1946 * fail due to an error reading the directory?
1949 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1950 "Error reading /sys/class/net: %s",
1951 pcap_strerror(errno
));
1957 (void)closedir(sys_class_net_d
);
1962 * Get from "/proc/net/dev" all interfaces listed there; if they're
1963 * already in the list of interfaces we have, that won't add another
1964 * instance, but if they're not, that'll add them.
1966 * See comments from scan_sys_class_net().
1969 scan_proc_net_dev(pcap_if_t
**devlistp
, char *errbuf
)
1976 char name
[512]; /* XXX - pick a size */
1978 struct ifreq ifrflags
;
1981 proc_net_f
= fopen("/proc/net/dev", "r");
1982 if (proc_net_f
== NULL
&& errno
== ENOENT
)
1986 * Create a socket from which to fetch interface information.
1988 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1990 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1991 "socket: %s", pcap_strerror(errno
));
1996 fgets(linebuf
, sizeof linebuf
, proc_net_f
) != NULL
; linenum
++) {
1998 * Skip the first two lines - they're headers.
2006 * Skip leading white space.
2008 while (*p
!= '\0' && isascii(*p
) && isspace(*p
))
2010 if (*p
== '\0' || *p
== '\n')
2011 continue; /* blank line */
2014 * Get the interface name.
2017 while (*p
!= '\0' && isascii(*p
) && !isspace(*p
)) {
2020 * This could be the separator between a
2021 * name and an alias number, or it could be
2022 * the separator between a name with no
2023 * alias number and the next field.
2025 * If there's a colon after digits, it
2026 * separates the name and the alias number,
2027 * otherwise it separates the name and the
2031 while (isascii(*p
) && isdigit(*p
))
2035 * That was the next field,
2036 * not the alias number.
2047 * Get the flags for this interface, and skip it if
2050 strncpy(ifrflags
.ifr_name
, name
, sizeof(ifrflags
.ifr_name
));
2051 if (ioctl(fd
, SIOCGIFFLAGS
, (char *)&ifrflags
) < 0) {
2054 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2055 "SIOCGIFFLAGS: %.*s: %s",
2056 (int)sizeof(ifrflags
.ifr_name
),
2058 pcap_strerror(errno
));
2062 if (!(ifrflags
.ifr_flags
& IFF_UP
))
2066 * Add an entry for this interface, with no addresses.
2068 if (pcap_add_if(devlistp
, name
, ifrflags
.ifr_flags
, NULL
,
2079 * Well, we didn't fail for any other reason; did we
2080 * fail due to an error reading the file?
2082 if (ferror(proc_net_f
)) {
2083 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2084 "Error reading /proc/net/dev: %s",
2085 pcap_strerror(errno
));
2091 (void)fclose(proc_net_f
);
2096 * Description string for the "any" device.
2098 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
2101 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
2106 * Read "/sys/class/net", and add to the list of interfaces all
2107 * interfaces listed there that we don't already have, because,
2108 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2109 * and even getifaddrs() won't return information about
2110 * interfaces with no addresses, so you need to read "/sys/class/net"
2111 * to get the names of the rest of the interfaces.
2113 ret
= scan_sys_class_net(alldevsp
, errbuf
);
2115 return (-1); /* failed */
2118 * No /sys/class/net; try reading /proc/net/dev instead.
2120 if (scan_proc_net_dev(alldevsp
, errbuf
) == -1)
2125 * Add the "any" device.
2127 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
2134 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
2136 #endif /* HAVE_DAG_API */
2138 #ifdef HAVE_SEPTEL_API
2140 * Add Septel devices.
2142 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
2144 #endif /* HAVE_SEPTEL_API */
2147 if (snf_platform_finddevs(alldevsp
, errbuf
) < 0)
2149 #endif /* HAVE_SNF_API */
2151 #ifdef PCAP_SUPPORT_BT
2153 * Add Bluetooth devices.
2155 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
2159 #ifdef PCAP_SUPPORT_USB
2163 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
2171 * Attach the given BPF code to the packet capture device.
2174 pcap_setfilter_linux_common(pcap_t
*handle
, struct bpf_program
*filter
,
2177 #ifdef SO_ATTACH_FILTER
2178 struct sock_fprog fcode
;
2179 int can_filter_in_kernel
;
2186 strncpy(handle
->errbuf
, "setfilter: No filter specified",
2191 /* Make our private copy of the filter */
2193 if (install_bpf_program(handle
, filter
) < 0)
2194 /* install_bpf_program() filled in errbuf */
2198 * Run user level packet filter by default. Will be overriden if
2199 * installing a kernel filter succeeds.
2201 handle
->md
.use_bpf
= 0;
2203 /* Install kernel level filter if possible */
2205 #ifdef SO_ATTACH_FILTER
2207 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
2209 * fcode.len is an unsigned short for current kernel.
2210 * I have yet to see BPF-Code with that much
2211 * instructions but still it is possible. So for the
2212 * sake of correctness I added this check.
2214 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
2216 fcode
.filter
= NULL
;
2217 can_filter_in_kernel
= 0;
2219 #endif /* USHRT_MAX */
2222 * Oh joy, the Linux kernel uses struct sock_fprog instead
2223 * of struct bpf_program and of course the length field is
2224 * of different size. Pointed out by Sebastian
2226 * Oh, and we also need to fix it up so that all "ret"
2227 * instructions with non-zero operands have 65535 as the
2228 * operand if we're not capturing in memory-mapped modee,
2229 * and so that, if we're in cooked mode, all memory-reference
2230 * instructions use special magic offsets in references to
2231 * the link-layer header and assume that the link-layer
2232 * payload begins at 0; "fix_program()" will do that.
2234 switch (fix_program(handle
, &fcode
, is_mmapped
)) {
2239 * Fatal error; just quit.
2240 * (The "default" case shouldn't happen; we
2241 * return -1 for that reason.)
2247 * The program performed checks that we can't make
2248 * work in the kernel.
2250 can_filter_in_kernel
= 0;
2255 * We have a filter that'll work in the kernel.
2257 can_filter_in_kernel
= 1;
2262 if (can_filter_in_kernel
) {
2263 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
2265 /* Installation succeded - using kernel filter. */
2266 handle
->md
.use_bpf
= 1;
2268 else if (err
== -1) /* Non-fatal error */
2271 * Print a warning if we weren't able to install
2272 * the filter for a reason other than "this kernel
2273 * isn't configured to support socket filters.
2275 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
2277 "Warning: Kernel filter failed: %s\n",
2278 pcap_strerror(errno
));
2284 * If we're not using the kernel filter, get rid of any kernel
2285 * filter that might've been there before, e.g. because the
2286 * previous filter could work in the kernel, or because some other
2287 * code attached a filter to the socket by some means other than
2288 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2289 * filter out packets that would pass the new userland filter.
2291 if (!handle
->md
.use_bpf
)
2292 reset_kernel_filter(handle
);
2295 * Free up the copy of the filter that was made by "fix_program()".
2297 if (fcode
.filter
!= NULL
)
2303 #endif /* SO_ATTACH_FILTER */
2309 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
2311 return pcap_setfilter_linux_common(handle
, filter
, 0);
2316 * Set direction flag: Which packets do we accept on a forwarding
2317 * single device? IN, OUT or both?
2320 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
2322 #ifdef HAVE_PF_PACKET_SOCKETS
2323 if (!handle
->md
.sock_packet
) {
2324 handle
->direction
= d
;
2329 * We're not using PF_PACKET sockets, so we can't determine
2330 * the direction of the packet.
2332 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2333 "Setting direction is not supported on SOCK_PACKET sockets");
2337 #ifdef HAVE_PF_PACKET_SOCKETS
2339 * Map the PACKET_ value to a LINUX_SLL_ value; we
2340 * want the same numerical value to be used in
2341 * the link-layer header even if the numerical values
2342 * for the PACKET_ #defines change, so that programs
2343 * that look at the packet type field will always be
2344 * able to handle DLT_LINUX_SLL captures.
2347 map_packet_type_to_sll_type(short int sll_pkttype
)
2349 switch (sll_pkttype
) {
2352 return htons(LINUX_SLL_HOST
);
2354 case PACKET_BROADCAST
:
2355 return htons(LINUX_SLL_BROADCAST
);
2357 case PACKET_MULTICAST
:
2358 return htons(LINUX_SLL_MULTICAST
);
2360 case PACKET_OTHERHOST
:
2361 return htons(LINUX_SLL_OTHERHOST
);
2363 case PACKET_OUTGOING
:
2364 return htons(LINUX_SLL_OUTGOING
);
2373 * Linux uses the ARP hardware type to identify the type of an
2374 * interface. pcap uses the DLT_xxx constants for this. This
2375 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2376 * constant, as arguments, and sets "handle->linktype" to the
2377 * appropriate DLT_XXX constant and sets "handle->offset" to
2378 * the appropriate value (to make "handle->offset" plus link-layer
2379 * header length be a multiple of 4, so that the link-layer payload
2380 * will be aligned on a 4-byte boundary when capturing packets).
2381 * (If the offset isn't set here, it'll be 0; add code as appropriate
2382 * for cases where it shouldn't be 0.)
2384 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2385 * in cooked mode; otherwise, we can't use cooked mode, so we have
2386 * to pick some type that works in raw mode, or fail.
2388 * Sets the link type to -1 if unable to map the type.
2390 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
2396 * This is (presumably) a real Ethernet capture; give it a
2397 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2398 * that an application can let you choose it, in case you're
2399 * capturing DOCSIS traffic that a Cisco Cable Modem
2400 * Termination System is putting out onto an Ethernet (it
2401 * doesn't put an Ethernet header onto the wire, it puts raw
2402 * DOCSIS frames out on the wire inside the low-level
2403 * Ethernet framing).
2405 * XXX - are there any sorts of "fake Ethernet" that have
2406 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2407 * a Cisco CMTS won't put traffic onto it or get traffic
2408 * bridged onto it? ISDN is handled in "activate_new()",
2409 * as we fall back on cooked mode there; are there any
2412 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
2414 * If that fails, just leave the list empty.
2416 if (handle
->dlt_list
!= NULL
) {
2417 handle
->dlt_list
[0] = DLT_EN10MB
;
2418 handle
->dlt_list
[1] = DLT_DOCSIS
;
2419 handle
->dlt_count
= 2;
2423 case ARPHRD_METRICOM
:
2424 case ARPHRD_LOOPBACK
:
2425 handle
->linktype
= DLT_EN10MB
;
2430 handle
->linktype
= DLT_EN3MB
;
2434 handle
->linktype
= DLT_AX25_KISS
;
2438 handle
->linktype
= DLT_PRONET
;
2442 handle
->linktype
= DLT_CHAOS
;
2445 #define ARPHRD_CAN 280
2448 handle
->linktype
= DLT_CAN_SOCKETCAN
;
2451 #ifndef ARPHRD_IEEE802_TR
2452 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2454 case ARPHRD_IEEE802_TR
:
2455 case ARPHRD_IEEE802
:
2456 handle
->linktype
= DLT_IEEE802
;
2461 handle
->linktype
= DLT_ARCNET_LINUX
;
2464 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2465 #define ARPHRD_FDDI 774
2468 handle
->linktype
= DLT_FDDI
;
2472 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2473 #define ARPHRD_ATM 19
2477 * The Classical IP implementation in ATM for Linux
2478 * supports both what RFC 1483 calls "LLC Encapsulation",
2479 * in which each packet has an LLC header, possibly
2480 * with a SNAP header as well, prepended to it, and
2481 * what RFC 1483 calls "VC Based Multiplexing", in which
2482 * different virtual circuits carry different network
2483 * layer protocols, and no header is prepended to packets.
2485 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2486 * you can't use the ARPHRD_ type to find out whether
2487 * captured packets will have an LLC header, and,
2488 * while there's a socket ioctl to *set* the encapsulation
2489 * type, there's no ioctl to *get* the encapsulation type.
2493 * programs that dissect Linux Classical IP frames
2494 * would have to check for an LLC header and,
2495 * depending on whether they see one or not, dissect
2496 * the frame as LLC-encapsulated or as raw IP (I
2497 * don't know whether there's any traffic other than
2498 * IP that would show up on the socket, or whether
2499 * there's any support for IPv6 in the Linux
2500 * Classical IP code);
2502 * filter expressions would have to compile into
2503 * code that checks for an LLC header and does
2506 * Both of those are a nuisance - and, at least on systems
2507 * that support PF_PACKET sockets, we don't have to put
2508 * up with those nuisances; instead, we can just capture
2509 * in cooked mode. That's what we'll do, if we can.
2510 * Otherwise, we'll just fail.
2513 handle
->linktype
= DLT_LINUX_SLL
;
2515 handle
->linktype
= -1;
2518 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2519 #define ARPHRD_IEEE80211 801
2521 case ARPHRD_IEEE80211
:
2522 handle
->linktype
= DLT_IEEE802_11
;
2525 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2526 #define ARPHRD_IEEE80211_PRISM 802
2528 case ARPHRD_IEEE80211_PRISM
:
2529 handle
->linktype
= DLT_PRISM_HEADER
;
2532 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2533 #define ARPHRD_IEEE80211_RADIOTAP 803
2535 case ARPHRD_IEEE80211_RADIOTAP
:
2536 handle
->linktype
= DLT_IEEE802_11_RADIO
;
2541 * Some PPP code in the kernel supplies no link-layer
2542 * header whatsoever to PF_PACKET sockets; other PPP
2543 * code supplies PPP link-layer headers ("syncppp.c");
2544 * some PPP code might supply random link-layer
2545 * headers (PPP over ISDN - there's code in Ethereal,
2546 * for example, to cope with PPP-over-ISDN captures
2547 * with which the Ethereal developers have had to cope,
2548 * heuristically trying to determine which of the
2549 * oddball link-layer headers particular packets have).
2551 * As such, we just punt, and run all PPP interfaces
2552 * in cooked mode, if we can; otherwise, we just treat
2553 * it as DLT_RAW, for now - if somebody needs to capture,
2554 * on a 2.0[.x] kernel, on PPP devices that supply a
2555 * link-layer header, they'll have to add code here to
2556 * map to the appropriate DLT_ type (possibly adding a
2557 * new DLT_ type, if necessary).
2560 handle
->linktype
= DLT_LINUX_SLL
;
2563 * XXX - handle ISDN types here? We can't fall
2564 * back on cooked sockets, so we'd have to
2565 * figure out from the device name what type of
2566 * link-layer encapsulation it's using, and map
2567 * that to an appropriate DLT_ value, meaning
2568 * we'd map "isdnN" devices to DLT_RAW (they
2569 * supply raw IP packets with no link-layer
2570 * header) and "isdY" devices to a new DLT_I4L_IP
2571 * type that has only an Ethernet packet type as
2572 * a link-layer header.
2574 * But sometimes we seem to get random crap
2575 * in the link-layer header when capturing on
2578 handle
->linktype
= DLT_RAW
;
2582 #ifndef ARPHRD_CISCO
2583 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2586 handle
->linktype
= DLT_C_HDLC
;
2589 /* Not sure if this is correct for all tunnels, but it
2593 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2601 #ifndef ARPHRD_RAWHDLC
2602 #define ARPHRD_RAWHDLC 518
2604 case ARPHRD_RAWHDLC
:
2606 #define ARPHRD_DLCI 15
2610 * XXX - should some of those be mapped to DLT_LINUX_SLL
2611 * instead? Should we just map all of them to DLT_LINUX_SLL?
2613 handle
->linktype
= DLT_RAW
;
2617 #define ARPHRD_FRAD 770
2620 handle
->linktype
= DLT_FRELAY
;
2623 case ARPHRD_LOCALTLK
:
2624 handle
->linktype
= DLT_LTALK
;
2628 #define ARPHRD_FCPP 784
2632 #define ARPHRD_FCAL 785
2636 #define ARPHRD_FCPL 786
2639 #ifndef ARPHRD_FCFABRIC
2640 #define ARPHRD_FCFABRIC 787
2642 case ARPHRD_FCFABRIC
:
2644 * We assume that those all mean RFC 2625 IP-over-
2645 * Fibre Channel, with the RFC 2625 header at
2646 * the beginning of the packet.
2648 handle
->linktype
= DLT_IP_OVER_FC
;
2652 #define ARPHRD_IRDA 783
2655 /* Don't expect IP packet out of this interfaces... */
2656 handle
->linktype
= DLT_LINUX_IRDA
;
2657 /* We need to save packet direction for IrDA decoding,
2658 * so let's use "Linux-cooked" mode. Jean II */
2659 //handle->md.cooked = 1;
2662 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2663 * is needed, please report it to <daniele@orlandi.com> */
2665 #define ARPHRD_LAPD 8445
2668 /* Don't expect IP packet out of this interfaces... */
2669 handle
->linktype
= DLT_LINUX_LAPD
;
2673 #define ARPHRD_NONE 0xFFFE
2677 * No link-layer header; packets are just IP
2678 * packets, so use DLT_RAW.
2680 handle
->linktype
= DLT_RAW
;
2683 #ifndef ARPHRD_IEEE802154
2684 #define ARPHRD_IEEE802154 804
2686 case ARPHRD_IEEE802154
:
2687 handle
->linktype
= DLT_IEEE802_15_4_NOFCS
;
2691 handle
->linktype
= -1;
2696 /* ===== Functions to interface to the newer kernels ================== */
2699 * Try to open a packet socket using the new kernel PF_PACKET interface.
2700 * Returns 1 on success, 0 on an error that means the new interface isn't
2701 * present (so the old SOCK_PACKET interface should be tried), and a
2702 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2703 * work either (so it shouldn't be tried).
2706 activate_new(pcap_t
*handle
)
2708 #ifdef HAVE_PF_PACKET_SOCKETS
2709 const char *device
= handle
->opt
.source
;
2710 int is_any_device
= (strcmp(device
, "any") == 0);
2711 int sock_fd
= -1, arptype
;
2712 #ifdef HAVE_PACKET_AUXDATA
2716 struct packet_mreq mr
;
2719 * Open a socket with protocol family packet. If the
2720 * "any" device was specified, we open a SOCK_DGRAM
2721 * socket for the cooked interface, otherwise we first
2722 * try a SOCK_RAW socket for the raw interface.
2724 sock_fd
= is_any_device
?
2725 socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
)) :
2726 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
2728 if (sock_fd
== -1) {
2729 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
2730 pcap_strerror(errno
) );
2731 return 0; /* try old mechanism */
2734 /* It seems the kernel supports the new interface. */
2735 handle
->md
.sock_packet
= 0;
2738 * Get the interface index of the loopback device.
2739 * If the attempt fails, don't fail, just set the
2740 * "md.lo_ifindex" to -1.
2742 * XXX - can there be more than one device that loops
2743 * packets back, i.e. devices other than "lo"? If so,
2744 * we'd need to find them all, and have an array of
2745 * indices for them, and check all of them in
2746 * "pcap_read_packet()".
2748 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
2751 * Default value for offset to align link-layer payload
2752 * on a 4-byte boundary.
2757 * What kind of frames do we have to deal with? Fall back
2758 * to cooked mode if we have an unknown interface type
2759 * or a type we know doesn't work well in raw mode.
2761 if (!is_any_device
) {
2762 /* Assume for now we don't need cooked mode. */
2763 handle
->md
.cooked
= 0;
2765 if (handle
->opt
.rfmon
) {
2767 * We were asked to turn on monitor mode.
2768 * Do so before we get the link-layer type,
2769 * because entering monitor mode could change
2770 * the link-layer type.
2772 err
= enter_rfmon_mode(handle
, sock_fd
, device
);
2780 * Nothing worked for turning monitor mode
2784 return PCAP_ERROR_RFMON_NOTSUP
;
2788 * Either monitor mode has been turned on for
2789 * the device, or we've been given a different
2790 * device to open for monitor mode. If we've
2791 * been given a different device, use it.
2793 if (handle
->md
.mondevice
!= NULL
)
2794 device
= handle
->md
.mondevice
;
2796 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
2801 map_arphrd_to_dlt(handle
, arptype
, 1);
2802 if (handle
->linktype
== -1 ||
2803 handle
->linktype
== DLT_LINUX_SLL
||
2804 handle
->linktype
== DLT_LINUX_IRDA
||
2805 handle
->linktype
== DLT_LINUX_LAPD
||
2806 (handle
->linktype
== DLT_EN10MB
&&
2807 (strncmp("isdn", device
, 4) == 0 ||
2808 strncmp("isdY", device
, 4) == 0))) {
2810 * Unknown interface type (-1), or a
2811 * device we explicitly chose to run
2812 * in cooked mode (e.g., PPP devices),
2813 * or an ISDN device (whose link-layer
2814 * type we can only determine by using
2815 * APIs that may be different on different
2816 * kernels) - reopen in cooked mode.
2818 if (close(sock_fd
) == -1) {
2819 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2820 "close: %s", pcap_strerror(errno
));
2823 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
2825 if (sock_fd
== -1) {
2826 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2827 "socket: %s", pcap_strerror(errno
));
2830 handle
->md
.cooked
= 1;
2833 * Get rid of any link-layer type list
2834 * we allocated - this only supports cooked
2837 if (handle
->dlt_list
!= NULL
) {
2838 free(handle
->dlt_list
);
2839 handle
->dlt_list
= NULL
;
2840 handle
->dlt_count
= 0;
2843 if (handle
->linktype
== -1) {
2845 * Warn that we're falling back on
2846 * cooked mode; we may want to
2847 * update "map_arphrd_to_dlt()"
2848 * to handle the new type.
2850 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2852 "supported by libpcap - "
2853 "falling back to cooked "
2859 * IrDA capture is not a real "cooked" capture,
2860 * it's IrLAP frames, not IP packets. The
2861 * same applies to LAPD capture.
2863 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
2864 handle
->linktype
!= DLT_LINUX_LAPD
)
2865 handle
->linktype
= DLT_LINUX_SLL
;
2868 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
2870 if (handle
->md
.ifindex
== -1) {
2875 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
2876 handle
->errbuf
)) != 1) {
2881 return 0; /* try old mechanism */
2887 if (handle
->opt
.rfmon
) {
2889 * It doesn't support monitor mode.
2891 return PCAP_ERROR_RFMON_NOTSUP
;
2895 * It uses cooked mode.
2897 handle
->md
.cooked
= 1;
2898 handle
->linktype
= DLT_LINUX_SLL
;
2901 * We're not bound to a device.
2902 * For now, we're using this as an indication
2903 * that we can't transmit; stop doing that only
2904 * if we figure out how to transmit in cooked
2907 handle
->md
.ifindex
= -1;
2911 * Select promiscuous mode on if "promisc" is set.
2913 * Do not turn allmulti mode on if we don't select
2914 * promiscuous mode - on some devices (e.g., Orinoco
2915 * wireless interfaces), allmulti mode isn't supported
2916 * and the driver implements it by turning promiscuous
2917 * mode on, and that screws up the operation of the
2918 * card as a normal networking interface, and on no
2919 * other platform I know of does starting a non-
2920 * promiscuous capture affect which multicast packets
2921 * are received by the interface.
2925 * Hmm, how can we set promiscuous mode on all interfaces?
2926 * I am not sure if that is possible at all. For now, we
2927 * silently ignore attempts to turn promiscuous mode on
2928 * for the "any" device (so you don't have to explicitly
2929 * disable it in programs such as tcpdump).
2932 if (!is_any_device
&& handle
->opt
.promisc
) {
2933 memset(&mr
, 0, sizeof(mr
));
2934 mr
.mr_ifindex
= handle
->md
.ifindex
;
2935 mr
.mr_type
= PACKET_MR_PROMISC
;
2936 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
2937 &mr
, sizeof(mr
)) == -1) {
2938 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2939 "setsockopt: %s", pcap_strerror(errno
));
2945 /* Enable auxillary data if supported and reserve room for
2946 * reconstructing VLAN headers. */
2947 #ifdef HAVE_PACKET_AUXDATA
2949 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_AUXDATA
, &val
,
2950 sizeof(val
)) == -1 && errno
!= ENOPROTOOPT
) {
2951 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2952 "setsockopt: %s", pcap_strerror(errno
));
2956 handle
->offset
+= VLAN_TAG_LEN
;
2957 #endif /* HAVE_PACKET_AUXDATA */
2960 * This is a 2.2[.x] or later kernel (we know that
2961 * because we're not using a SOCK_PACKET socket -
2962 * PF_PACKET is supported only in 2.2 and later
2965 * We can safely pass "recvfrom()" a byte count
2966 * based on the snapshot length.
2968 * If we're in cooked mode, make the snapshot length
2969 * large enough to hold a "cooked mode" header plus
2970 * 1 byte of packet data (so we don't pass a byte
2971 * count of 0 to "recvfrom()").
2973 if (handle
->md
.cooked
) {
2974 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
2975 handle
->snapshot
= SLL_HDR_LEN
+ 1;
2977 handle
->bufsize
= handle
->snapshot
;
2979 /* Save the socket FD in the pcap structure */
2980 handle
->fd
= sock_fd
;
2985 "New packet capturing interface not supported by build "
2986 "environment", PCAP_ERRBUF_SIZE
);
2991 #ifdef HAVE_PACKET_RING
2993 * Attempt to activate with memory-mapped access.
2995 * On success, returns 1, and sets *status to 0 if there are no warnings
2996 * or to a PCAP_WARNING_ code if there is a warning.
2998 * On failure due to lack of support for memory-mapped capture, returns
3001 * On error, returns -1, and sets *status to the appropriate error code;
3002 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3005 activate_mmap(pcap_t
*handle
, int *status
)
3010 * Attempt to allocate a buffer to hold the contents of one
3011 * packet, for use by the oneshot callback.
3013 handle
->md
.oneshot_buffer
= malloc(handle
->snapshot
);
3014 if (handle
->md
.oneshot_buffer
== NULL
) {
3015 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3016 "can't allocate oneshot buffer: %s",
3017 pcap_strerror(errno
));
3018 *status
= PCAP_ERROR
;
3022 if (handle
->opt
.buffer_size
== 0) {
3023 /* by default request 2M for the ring buffer */
3024 handle
->opt
.buffer_size
= 2*1024*1024;
3026 ret
= prepare_tpacket_socket(handle
);
3028 free(handle
->md
.oneshot_buffer
);
3029 *status
= PCAP_ERROR
;
3032 ret
= create_ring(handle
, status
);
3035 * We don't support memory-mapped capture; our caller
3036 * will fall back on reading from the socket.
3038 free(handle
->md
.oneshot_buffer
);
3043 * Error attempting to enable memory-mapped capture;
3044 * fail. create_ring() has set *status.
3046 free(handle
->md
.oneshot_buffer
);
3051 * Success. *status has been set either to 0 if there are no
3052 * warnings or to a PCAP_WARNING_ value if there is a warning.
3054 * Override some defaults and inherit the other fields from
3056 * handle->offset is used to get the current position into the rx ring.
3057 * handle->cc is used to store the ring size.
3059 handle
->read_op
= pcap_read_linux_mmap
;
3060 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
3061 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
3062 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
3063 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
3064 handle
->oneshot_callback
= pcap_oneshot_mmap
;
3065 handle
->selectable_fd
= handle
->fd
;
3068 #else /* HAVE_PACKET_RING */
3070 activate_mmap(pcap_t
*handle _U_
, int *status _U_
)
3074 #endif /* HAVE_PACKET_RING */
3076 #ifdef HAVE_PACKET_RING
3078 * Attempt to set the socket to version 2 of the memory-mapped header.
3079 * Return 1 if we succeed or if we fail because version 2 isn't
3080 * supported; return -1 on any other error, and set handle->errbuf.
3083 prepare_tpacket_socket(pcap_t
*handle
)
3085 #ifdef HAVE_TPACKET2
3090 handle
->md
.tp_version
= TPACKET_V1
;
3091 handle
->md
.tp_hdrlen
= sizeof(struct tpacket_hdr
);
3093 #ifdef HAVE_TPACKET2
3094 /* Probe whether kernel supports TPACKET_V2 */
3097 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_HDRLEN
, &val
, &len
) < 0) {
3098 if (errno
== ENOPROTOOPT
)
3099 return 1; /* no - just drive on */
3101 /* Yes - treat as a failure. */
3102 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3103 "can't get TPACKET_V2 header len on packet socket: %s",
3104 pcap_strerror(errno
));
3107 handle
->md
.tp_hdrlen
= val
;
3110 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_VERSION
, &val
,
3112 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3113 "can't activate TPACKET_V2 on packet socket: %s",
3114 pcap_strerror(errno
));
3117 handle
->md
.tp_version
= TPACKET_V2
;
3119 /* Reserve space for VLAN tag reconstruction */
3121 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RESERVE
, &val
,
3123 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3124 "can't set up reserve on packet socket: %s",
3125 pcap_strerror(errno
));
3129 #endif /* HAVE_TPACKET2 */
3134 * Attempt to set up memory-mapped access.
3136 * On success, returns 1, and sets *status to 0 if there are no warnings
3137 * or to a PCAP_WARNING_ code if there is a warning.
3139 * On failure due to lack of support for memory-mapped capture, returns
3142 * On error, returns -1, and sets *status to the appropriate error code;
3143 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3146 create_ring(pcap_t
*handle
, int *status
)
3148 unsigned i
, j
, frames_per_block
;
3149 struct tpacket_req req
;
3152 * Start out assuming no warnings or errors.
3156 /* Note that with large snapshot (say 64K) only a few frames
3157 * will be available in the ring even with pretty large ring size
3158 * (and a lot of memory will be unused).
3159 * The snap len should be carefully chosen to achive best
3161 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+
3162 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3163 sizeof(struct sockaddr_ll
));
3164 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
3166 /* compute the minumum block size that will handle this frame.
3167 * The block has to be page size aligned.
3168 * The max block size allowed by the kernel is arch-dependent and
3169 * it's not explicitly checked here. */
3170 req
.tp_block_size
= getpagesize();
3171 while (req
.tp_block_size
< req
.tp_frame_size
)
3172 req
.tp_block_size
<<= 1;
3174 frames_per_block
= req
.tp_block_size
/req
.tp_frame_size
;
3177 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3178 * so we check for PACKET_TIMESTAMP. We check for
3179 * linux/net_tstamp.h just in case a system somehow has
3180 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3183 * SIOCSHWTSTAMP was introduced in the patch that introduced
3184 * linux/net_tstamp.h, so we don't bother checking whether
3185 * SIOCSHWTSTAMP is defined (if your Linux system has
3186 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3187 * Linux system is badly broken).
3189 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3191 * If we were told to do so, ask the kernel and the driver
3192 * to use hardware timestamps.
3194 * Hardware timestamps are only supported with mmapped
3197 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
||
3198 handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER_UNSYNCED
) {
3199 struct hwtstamp_config hwconfig
;
3204 * Ask for hardware time stamps on all packets,
3205 * including transmitted packets.
3207 memset(&hwconfig
, 0, sizeof(hwconfig
));
3208 hwconfig
.tx_type
= HWTSTAMP_TX_ON
;
3209 hwconfig
.rx_filter
= HWTSTAMP_FILTER_ALL
;
3211 memset(&ifr
, 0, sizeof(ifr
));
3212 strcpy(ifr
.ifr_name
, handle
->opt
.source
);
3213 ifr
.ifr_data
= (void *)&hwconfig
;
3215 if (ioctl(handle
->fd
, SIOCSHWTSTAMP
, &ifr
) < 0) {
3220 * Treat this as an error, as the
3221 * user should try to run this
3222 * with the appropriate privileges -
3223 * and, if they can't, shouldn't
3224 * try requesting hardware time stamps.
3226 *status
= PCAP_ERROR_PERM_DENIED
;
3231 * Treat this as a warning, as the
3232 * only way to fix the warning is to
3233 * get an adapter that supports hardware
3234 * time stamps. We'll just fall back
3235 * on the standard host time stamps.
3237 *status
= PCAP_WARNING_TSTAMP_TYPE_NOTSUP
:
3241 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3242 "SIOCSHWTSTAMP failed: %s",
3243 pcap_strerror(errno
));
3244 *status
= PCAP_ERROR
;
3249 * Well, that worked. Now specify the type of
3250 * hardware time stamp we want for this
3253 if (handle
->opt
.tstamp_type
== PCAP_TSTAMP_ADAPTER
) {
3255 * Hardware timestamp, synchronized
3256 * with the system clock.
3258 timesource
= SOF_TIMESTAMPING_SYS_HARDWARE
;
3261 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3262 * timestamp, not synchronized with the
3265 timesource
= SOF_TIMESTAMPING_RAW_HARDWARE
;
3267 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_TIMESTAMP
,
3268 (void *)×ource
, sizeof(timesource
))) {
3269 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3270 "can't set PACKET_TIMESTAMP: %s",
3271 pcap_strerror(errno
));
3272 *status
= PCAP_ERROR
;
3277 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3279 /* ask the kernel to create the ring */
3281 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
3283 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3284 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
3286 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3287 (void *) &req
, sizeof(req
))) {
3288 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
3290 * Memory failure; try to reduce the requested ring
3293 * We used to reduce this by half -- do 5% instead.
3294 * That may result in more iterations and a longer
3295 * startup, but the user will be much happier with
3296 * the resulting buffer size.
3298 if (req
.tp_frame_nr
< 20)
3299 req
.tp_frame_nr
-= 1;
3301 req
.tp_frame_nr
-= req
.tp_frame_nr
/20;
3304 if (errno
== ENOPROTOOPT
) {
3306 * We don't have ring buffer support in this kernel.
3310 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3311 "can't create rx ring on packet socket: %s",
3312 pcap_strerror(errno
));
3313 *status
= PCAP_ERROR
;
3317 /* memory map the rx ring */
3318 handle
->md
.mmapbuflen
= req
.tp_block_nr
* req
.tp_block_size
;
3319 handle
->md
.mmapbuf
= mmap(0, handle
->md
.mmapbuflen
,
3320 PROT_READ
|PROT_WRITE
, MAP_SHARED
, handle
->fd
, 0);
3321 if (handle
->md
.mmapbuf
== MAP_FAILED
) {
3322 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3323 "can't mmap rx ring: %s", pcap_strerror(errno
));
3325 /* clear the allocated ring on error*/
3326 destroy_ring(handle
);
3327 *status
= PCAP_ERROR
;
3331 /* allocate a ring for each frame header pointer*/
3332 handle
->cc
= req
.tp_frame_nr
;
3333 handle
->buffer
= malloc(handle
->cc
* sizeof(union thdr
*));
3334 if (!handle
->buffer
) {
3335 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3336 "can't allocate ring of frame headers: %s",
3337 pcap_strerror(errno
));
3339 destroy_ring(handle
);
3340 *status
= PCAP_ERROR
;
3344 /* fill the header ring with proper frame ptr*/
3346 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
3347 void *base
= &handle
->md
.mmapbuf
[i
*req
.tp_block_size
];
3348 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
3349 RING_GET_FRAME(handle
) = base
;
3350 base
+= req
.tp_frame_size
;
3354 handle
->bufsize
= req
.tp_frame_size
;
3359 /* free all ring related resources*/
3361 destroy_ring(pcap_t
*handle
)
3363 /* tell the kernel to destroy the ring*/
3364 struct tpacket_req req
;
3365 memset(&req
, 0, sizeof(req
));
3366 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
3367 (void *) &req
, sizeof(req
));
3369 /* if ring is mapped, unmap it*/
3370 if (handle
->md
.mmapbuf
) {
3371 /* do not test for mmap failure, as we can't recover from any error */
3372 munmap(handle
->md
.mmapbuf
, handle
->md
.mmapbuflen
);
3373 handle
->md
.mmapbuf
= NULL
;
3378 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3379 * for Linux mmapped capture.
3381 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3382 * data handed to the callback to be valid after the callback returns,
3383 * but pcap_read_linux_mmap() has to release that packet as soon as
3384 * the callback returns (otherwise, the kernel thinks there's still
3385 * at least one unprocessed packet available in the ring, so a select()
3386 * will immediately return indicating that there's data to process), so,
3387 * in the callback, we have to make a copy of the packet.
3389 * Yes, this means that, if the capture is using the ring buffer, using
3390 * pcap_next() or pcap_next_ex() requires more copies than using
3391 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3392 * pcap_next() or pcap_next_ex().
3395 pcap_oneshot_mmap(u_char
*user
, const struct pcap_pkthdr
*h
,
3396 const u_char
*bytes
)
3398 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
3401 memcpy(sp
->pd
->md
.oneshot_buffer
, bytes
, h
->caplen
);
3402 *sp
->pkt
= sp
->pd
->md
.oneshot_buffer
;
3406 pcap_cleanup_linux_mmap( pcap_t
*handle
)
3408 destroy_ring(handle
);
3409 if (handle
->md
.oneshot_buffer
!= NULL
) {
3410 free(handle
->md
.oneshot_buffer
);
3411 handle
->md
.oneshot_buffer
= NULL
;
3413 pcap_cleanup_linux(handle
);
3418 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
3420 /* use negative value of timeout to indicate non blocking ops */
3421 return (p
->md
.timeout
<0);
3425 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
3427 /* map each value to the corresponding 2's complement, to
3428 * preserve the timeout value provided with pcap_set_timeout */
3430 if (p
->md
.timeout
>= 0) {
3432 * Timeout is non-negative, so we're not already
3433 * in non-blocking mode; set it to the 2's
3434 * complement, to make it negative, as an
3435 * indication that we're in non-blocking mode.
3437 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
3440 if (p
->md
.timeout
< 0) {
3442 * Timeout is negative, so we're not already
3443 * in blocking mode; reverse the previous
3444 * operation, to make the timeout non-negative
3447 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
3453 static inline union thdr
*
3454 pcap_get_ring_frame(pcap_t
*handle
, int status
)
3458 h
.raw
= RING_GET_FRAME(handle
);
3459 switch (handle
->md
.tp_version
) {
3461 if (status
!= (h
.h1
->tp_status
? TP_STATUS_USER
:
3465 #ifdef HAVE_TPACKET2
3467 if (status
!= (h
.h2
->tp_status
? TP_STATUS_USER
:
3481 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
3488 /* wait for frames availability.*/
3489 if (!pcap_get_ring_frame(handle
, TP_STATUS_USER
)) {
3490 struct pollfd pollinfo
;
3493 pollinfo
.fd
= handle
->fd
;
3494 pollinfo
.events
= POLLIN
;
3496 if (handle
->md
.timeout
== 0)
3497 timeout
= -1; /* block forever */
3498 else if (handle
->md
.timeout
> 0)
3499 timeout
= handle
->md
.timeout
; /* block for that amount of time */
3501 timeout
= 0; /* non-blocking mode - poll to pick up errors */
3503 ret
= poll(&pollinfo
, 1, timeout
);
3504 if (ret
< 0 && errno
!= EINTR
) {
3505 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3506 "can't poll on packet socket: %s",
3507 pcap_strerror(errno
));
3509 } else if (ret
> 0 &&
3510 (pollinfo
.revents
& (POLLHUP
|POLLRDHUP
|POLLERR
|POLLNVAL
))) {
3512 * There's some indication other than
3513 * "you can read on this descriptor" on
3516 if (pollinfo
.revents
& (POLLHUP
| POLLRDHUP
)) {
3517 snprintf(handle
->errbuf
,
3519 "Hangup on packet socket");
3522 if (pollinfo
.revents
& POLLERR
) {
3524 * A recv() will give us the
3525 * actual error code.
3527 * XXX - make the socket non-blocking?
3529 if (recv(handle
->fd
, &c
, sizeof c
,
3531 continue; /* what, no error? */
3532 if (errno
== ENETDOWN
) {
3534 * The device on which we're
3535 * capturing went away.
3537 * XXX - we should really return
3538 * PCAP_ERROR_IFACE_NOT_UP,
3539 * but pcap_dispatch() etc.
3540 * aren't defined to return
3543 snprintf(handle
->errbuf
,
3545 "The interface went down");
3547 snprintf(handle
->errbuf
,
3549 "Error condition on packet socket: %s",
3554 if (pollinfo
.revents
& POLLNVAL
) {
3555 snprintf(handle
->errbuf
,
3557 "Invalid polling request on packet socket");
3561 /* check for break loop condition on interrupted syscall*/
3562 if (handle
->break_loop
) {
3563 handle
->break_loop
= 0;
3564 return PCAP_ERROR_BREAK
;
3569 /* non-positive values of max_packets are used to require all
3570 * packets currently available in the ring */
3571 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
3573 struct sockaddr_ll
*sll
;
3574 struct pcap_pkthdr pcaphdr
;
3577 unsigned int tp_len
;
3578 unsigned int tp_mac
;
3579 unsigned int tp_snaplen
;
3580 unsigned int tp_sec
;
3581 unsigned int tp_usec
;
3583 h
.raw
= pcap_get_ring_frame(handle
, TP_STATUS_USER
);
3587 switch (handle
->md
.tp_version
) {
3589 tp_len
= h
.h1
->tp_len
;
3590 tp_mac
= h
.h1
->tp_mac
;
3591 tp_snaplen
= h
.h1
->tp_snaplen
;
3592 tp_sec
= h
.h1
->tp_sec
;
3593 tp_usec
= h
.h1
->tp_usec
;
3595 #ifdef HAVE_TPACKET2
3597 tp_len
= h
.h2
->tp_len
;
3598 tp_mac
= h
.h2
->tp_mac
;
3599 tp_snaplen
= h
.h2
->tp_snaplen
;
3600 tp_sec
= h
.h2
->tp_sec
;
3601 tp_usec
= h
.h2
->tp_nsec
/ 1000;
3605 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3606 "unsupported tpacket version %d",
3607 handle
->md
.tp_version
);
3610 /* perform sanity check on internal offset. */
3611 if (tp_mac
+ tp_snaplen
> handle
->bufsize
) {
3612 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3613 "corrupted frame on kernel ring mac "
3614 "offset %d + caplen %d > frame len %d",
3615 tp_mac
, tp_snaplen
, handle
->bufsize
);
3619 /* run filter on received packet
3620 * If the kernel filtering is enabled we need to run the
3621 * filter until all the frames present into the ring
3622 * at filter creation time are processed.
3623 * In such case md.use_bpf is used as a counter for the
3624 * packet we need to filter.
3625 * Note: alternatively it could be possible to stop applying
3626 * the filter when the ring became empty, but it can possibly
3627 * happen a lot later... */
3628 bp
= (unsigned char*)h
.raw
+ tp_mac
;
3629 run_bpf
= (!handle
->md
.use_bpf
) ||
3630 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
3631 if (run_bpf
&& handle
->fcode
.bf_insns
&&
3632 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
3633 tp_len
, tp_snaplen
) == 0))
3637 * Do checks based on packet direction.
3639 sll
= (void *)h
.raw
+ TPACKET_ALIGN(handle
->md
.tp_hdrlen
);
3640 if (sll
->sll_pkttype
== PACKET_OUTGOING
) {
3643 * If this is from the loopback device, reject it;
3644 * we'll see the packet as an incoming packet as well,
3645 * and we don't want to see it twice.
3647 if (sll
->sll_ifindex
== handle
->md
.lo_ifindex
)
3651 * If the user only wants incoming packets, reject it.
3653 if (handle
->direction
== PCAP_D_IN
)
3658 * If the user only wants outgoing packets, reject it.
3660 if (handle
->direction
== PCAP_D_OUT
)
3664 /* get required packet info from ring header */
3665 pcaphdr
.ts
.tv_sec
= tp_sec
;
3666 pcaphdr
.ts
.tv_usec
= tp_usec
;
3667 pcaphdr
.caplen
= tp_snaplen
;
3668 pcaphdr
.len
= tp_len
;
3670 /* if required build in place the sll header*/
3671 if (handle
->md
.cooked
) {
3672 struct sll_header
*hdrp
;
3675 * The kernel should have left us with enough
3676 * space for an sll header; back up the packet
3677 * data pointer into that space, as that'll be
3678 * the beginning of the packet we pass to the
3684 * Let's make sure that's past the end of
3685 * the tpacket header, i.e. >=
3686 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3687 * don't step on the header when we construct
3690 if (bp
< (u_char
*)h
.raw
+
3691 TPACKET_ALIGN(handle
->md
.tp_hdrlen
) +
3692 sizeof(struct sockaddr_ll
)) {
3693 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3694 "cooked-mode frame doesn't have room for sll header");
3699 * OK, that worked; construct the sll header.
3701 hdrp
= (struct sll_header
*)bp
;
3702 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
3704 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
3705 hdrp
->sll_halen
= htons(sll
->sll_halen
);
3706 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
3707 hdrp
->sll_protocol
= sll
->sll_protocol
;
3709 /* update packet len */
3710 pcaphdr
.caplen
+= SLL_HDR_LEN
;
3711 pcaphdr
.len
+= SLL_HDR_LEN
;
3714 #ifdef HAVE_TPACKET2
3715 if (handle
->md
.tp_version
== TPACKET_V2
&& h
.h2
->tp_vlan_tci
&&
3716 tp_snaplen
>= 2 * ETH_ALEN
) {
3717 struct vlan_tag
*tag
;
3720 memmove(bp
, bp
+ VLAN_TAG_LEN
, 2 * ETH_ALEN
);
3722 tag
= (struct vlan_tag
*)(bp
+ 2 * ETH_ALEN
);
3723 tag
->vlan_tpid
= htons(ETH_P_8021Q
);
3724 tag
->vlan_tci
= htons(h
.h2
->tp_vlan_tci
);
3726 pcaphdr
.caplen
+= VLAN_TAG_LEN
;
3727 pcaphdr
.len
+= VLAN_TAG_LEN
;
3732 * The only way to tell the kernel to cut off the
3733 * packet at a snapshot length is with a filter program;
3734 * if there's no filter program, the kernel won't cut
3737 * Trim the snapshot length to be no longer than the
3738 * specified snapshot length.
3740 if (pcaphdr
.caplen
> handle
->snapshot
)
3741 pcaphdr
.caplen
= handle
->snapshot
;
3743 /* pass the packet to the user */
3745 callback(user
, &pcaphdr
, bp
);
3746 handle
->md
.packets_read
++;
3750 switch (handle
->md
.tp_version
) {
3752 h
.h1
->tp_status
= TP_STATUS_KERNEL
;
3754 #ifdef HAVE_TPACKET2
3756 h
.h2
->tp_status
= TP_STATUS_KERNEL
;
3760 if (++handle
->offset
>= handle
->cc
)
3763 /* check for break loop condition*/
3764 if (handle
->break_loop
) {
3765 handle
->break_loop
= 0;
3766 return PCAP_ERROR_BREAK
;
3773 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
3779 * Don't rewrite "ret" instructions; we don't need to, as
3780 * we're not reading packets with recvmsg(), and we don't
3781 * want to, as, by not rewriting them, the kernel can avoid
3782 * copying extra data.
3784 ret
= pcap_setfilter_linux_common(handle
, filter
, 1);
3788 /* if the kernel filter is enabled, we need to apply the filter on
3789 * all packets present into the ring. Get an upper bound of their number
3791 if (!handle
->md
.use_bpf
)
3794 /* walk the ring backward and count the free slot */
3795 offset
= handle
->offset
;
3796 if (--handle
->offset
< 0)
3797 handle
->offset
= handle
->cc
- 1;
3798 for (n
=0; n
< handle
->cc
; ++n
) {
3799 if (--handle
->offset
< 0)
3800 handle
->offset
= handle
->cc
- 1;
3801 if (!pcap_get_ring_frame(handle
, TP_STATUS_KERNEL
))
3805 /* be careful to not change current ring position */
3806 handle
->offset
= offset
;
3808 /* store the number of packets currently present in the ring */
3809 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
3813 #endif /* HAVE_PACKET_RING */
3816 #ifdef HAVE_PF_PACKET_SOCKETS
3818 * Return the index of the given device name. Fill ebuf and return
3822 iface_get_id(int fd
, const char *device
, char *ebuf
)
3826 memset(&ifr
, 0, sizeof(ifr
));
3827 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3829 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
3830 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3831 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
3835 return ifr
.ifr_ifindex
;
3839 * Bind the socket associated with FD to the given device.
3840 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3841 * or a PCAP_ERROR_ value on a hard error.
3844 iface_bind(int fd
, int ifindex
, char *ebuf
)
3846 struct sockaddr_ll sll
;
3848 socklen_t errlen
= sizeof(err
);
3850 memset(&sll
, 0, sizeof(sll
));
3851 sll
.sll_family
= AF_PACKET
;
3852 sll
.sll_ifindex
= ifindex
;
3853 sll
.sll_protocol
= htons(ETH_P_ALL
);
3855 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
3856 if (errno
== ENETDOWN
) {
3858 * Return a "network down" indication, so that
3859 * the application can report that rather than
3860 * saying we had a mysterious failure and
3861 * suggest that they report a problem to the
3862 * libpcap developers.
3864 return PCAP_ERROR_IFACE_NOT_UP
;
3866 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3867 "bind: %s", pcap_strerror(errno
));
3872 /* Any pending errors, e.g., network is down? */
3874 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
3875 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3876 "getsockopt: %s", pcap_strerror(errno
));
3880 if (err
== ENETDOWN
) {
3882 * Return a "network down" indication, so that
3883 * the application can report that rather than
3884 * saying we had a mysterious failure and
3885 * suggest that they report a problem to the
3886 * libpcap developers.
3888 return PCAP_ERROR_IFACE_NOT_UP
;
3889 } else if (err
> 0) {
3890 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3891 "bind: %s", pcap_strerror(err
));
3898 #ifdef IW_MODE_MONITOR
3900 * Check whether the device supports the Wireless Extensions.
3901 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3902 * if the device doesn't even exist.
3905 has_wext(int sock_fd
, const char *device
, char *ebuf
)
3909 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
3910 sizeof ireq
.ifr_ifrn
.ifrn_name
);
3911 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
3912 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
3914 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3915 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
3916 if (errno
== ENODEV
)
3917 return PCAP_ERROR_NO_SUCH_DEVICE
;
3922 * Per me si va ne la citta dolente,
3923 * Per me si va ne l'etterno dolore,
3925 * Lasciate ogne speranza, voi ch'intrate.
3927 * XXX - airmon-ng does special stuff with the Orinoco driver and the
3943 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3944 * on if it's not already on.
3946 * Returns 1 on success, 0 if we don't support the Wireless Extensions
3947 * on this device, or a PCAP_ERROR_ value if we do support them but
3948 * we weren't able to turn monitor mode on.
3951 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
3954 * XXX - at least some adapters require non-Wireless Extensions
3955 * mechanisms to turn monitor mode on.
3957 * Atheros cards might require that a separate "monitor virtual access
3958 * point" be created, with later versions of the madwifi driver.
3959 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3960 * monitor -bssid", which apparently spits out a line "athN"
3961 * where "athN" is the monitor mode device. To leave monitor
3962 * mode, it destroys the monitor mode device.
3964 * Some Intel Centrino adapters might require private ioctls to get
3965 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3966 * configure a separate "rtapN" interface to capture in monitor
3967 * mode without preventing the adapter from operating normally.
3968 * (airmon-ng doesn't appear to use that, though.)
3970 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3971 * up, and if all drivers were converted to mac80211 drivers.
3973 * If interface {if} is a mac80211 driver, the file
3974 * /sys/class/net/{if}/phy80211 is a symlink to
3975 * /sys/class/ieee80211/{phydev}, for some {phydev}.
3977 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
3978 * least, has a "wmaster0" device and a "wlan0" device; the
3979 * latter is the one with the IP address. Both show up in
3980 * "tcpdump -D" output. Capturing on the wmaster0 device
3981 * captures with 802.11 headers.
3983 * airmon-ng searches through /sys/class/net for devices named
3984 * monN, starting with mon0; as soon as one *doesn't* exist,
3985 * it chooses that as the monitor device name. If the "iw"
3986 * command exists, it does "iw dev {if} interface add {monif}
3987 * type monitor", where {monif} is the monitor device. It
3988 * then (sigh) sleeps .1 second, and then configures the
3989 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
3990 * is a file, it writes {mondev}, without a newline, to that file,
3991 * and again (sigh) sleeps .1 second, and then iwconfig's that
3992 * device into monitor mode and configures it up. Otherwise,
3993 * you can't do monitor mode.
3995 * All these devices are "glued" together by having the
3996 * /sys/class/net/{device}/phy80211 links pointing to the same
3997 * place, so, given a wmaster, wlan, or mon device, you can
3998 * find the other devices by looking for devices with
3999 * the same phy80211 link.
4001 * To turn monitor mode off, delete the monitor interface,
4002 * either with "iw dev {monif} interface del" or by sending
4003 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4005 * Note: if you try to create a monitor device named "monN", and
4006 * there's already a "monN" device, it fails, as least with
4007 * the netlink interface (which is what iw uses), with a return
4008 * value of -ENFILE. (Return values are negative errnos.) We
4009 * could probably use that to find an unused device.
4013 struct iw_priv_args
*priv
;
4014 monitor_type montype
;
4021 * Does this device *support* the Wireless Extensions?
4023 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
4025 return err
; /* either it doesn't or the device doesn't even exist */
4027 * Try to get all the Wireless Extensions private ioctls
4028 * supported by this device.
4030 * First, get the size of the buffer we need, by supplying no
4031 * buffer and a length of 0. If the device supports private
4032 * ioctls, it should return E2BIG, with ireq.u.data.length set
4033 * to the length we need. If it doesn't support them, it should
4034 * return EOPNOTSUPP.
4036 memset(&ireq
, 0, sizeof ireq
);
4037 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4038 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4039 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4040 ireq
.u
.data
.pointer
= (void *)args
;
4041 ireq
.u
.data
.length
= 0;
4042 ireq
.u
.data
.flags
= 0;
4043 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
4044 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4045 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4049 if (errno
== EOPNOTSUPP
) {
4051 * No private ioctls, so we assume that there's only one
4052 * DLT_ for monitor mode.
4056 if (errno
!= E2BIG
) {
4060 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4061 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4064 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
4066 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4067 "malloc: %s", pcap_strerror(errno
));
4070 ireq
.u
.data
.pointer
= (void *)priv
;
4071 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
4072 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4073 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
4079 * Look for private ioctls to turn monitor mode on or, if
4080 * monitor mode is on, to set the header type.
4082 montype
= MONITOR_WEXT
;
4084 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
4085 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
4087 * Hostap driver, use this one.
4088 * Set monitor mode first.
4089 * You can set it to 0 to get DLT_IEEE80211,
4090 * 1 to get DLT_PRISM, 2 to get
4091 * DLT_IEEE80211_RADIO_AVS, and, with more
4092 * recent versions of the driver, 3 to get
4093 * DLT_IEEE80211_RADIO.
4095 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4097 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4099 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4101 montype
= MONITOR_HOSTAP
;
4105 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
4107 * Prism54 driver, use this one.
4108 * Set monitor mode first.
4109 * You can set it to 2 to get DLT_IEEE80211
4110 * or 3 or get DLT_PRISM.
4112 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4114 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4116 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4118 montype
= MONITOR_PRISM54
;
4122 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
4124 * RT2570 driver, use this one.
4125 * Do this after turning monitor mode on.
4126 * You can set it to 1 to get DLT_PRISM or 2
4127 * to get DLT_IEEE80211.
4129 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4131 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4133 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4135 montype
= MONITOR_RT2570
;
4139 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
4141 * RT73 driver, use this one.
4142 * Do this after turning monitor mode on.
4143 * Its argument is a *string*; you can
4144 * set it to "1" to get DLT_PRISM or "2"
4145 * to get DLT_IEEE80211.
4147 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
4149 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
4151 montype
= MONITOR_RT73
;
4155 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
4157 * One of the RTL8xxx drivers, use this one.
4158 * It can only be done after monitor mode
4159 * has been turned on. You can set it to 1
4160 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4162 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4164 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4166 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
4168 montype
= MONITOR_RTL8XXX
;
4172 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
4174 * RT2500 or RT61 driver, use this one.
4175 * It has one one-byte parameter; set
4176 * u.data.length to 1 and u.data.pointer to
4177 * point to the parameter.
4178 * It doesn't itself turn monitor mode on.
4179 * You can set it to 1 to allow transmitting
4180 * in monitor mode(?) and get DLT_IEEE80211,
4181 * or set it to 0 to disallow transmitting in
4182 * monitor mode(?) and get DLT_PRISM.
4184 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4186 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
4188 montype
= MONITOR_RT2500
;
4192 if (strcmp(priv
[i
].name
, "monitor") == 0) {
4194 * Either ACX100 or hostap, use this one.
4195 * It turns monitor mode on.
4196 * If it takes two arguments, it's ACX100;
4197 * the first argument is 1 for DLT_PRISM
4198 * or 2 for DLT_IEEE80211, and the second
4199 * argument is the channel on which to
4200 * run. If it takes one argument, it's
4201 * HostAP, and the argument is 2 for
4202 * DLT_IEEE80211 and 3 for DLT_PRISM.
4204 * If we see this, we don't quit, as this
4205 * might be a version of the hostap driver
4206 * that also supports "monitor_type".
4208 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
4210 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
4212 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
4215 montype
= MONITOR_PRISM
;
4220 montype
= MONITOR_ACX100
;
4232 * XXX - ipw3945? islism?
4238 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4239 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4240 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4241 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
4243 * We probably won't be able to set the mode, either.
4245 return PCAP_ERROR_RFMON_NOTSUP
;
4249 * Is it currently in monitor mode?
4251 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
4253 * Yes. Just leave things as they are.
4254 * We don't offer multiple link-layer types, as
4255 * changing the link-layer type out from under
4256 * somebody else capturing in monitor mode would
4257 * be considered rude.
4262 * No. We have to put the adapter into rfmon mode.
4266 * If we haven't already done so, arrange to have
4267 * "pcap_close_all()" called when we exit.
4269 if (!pcap_do_addexit(handle
)) {
4271 * "atexit()" failed; don't put the interface
4272 * in rfmon mode, just give up.
4274 return PCAP_ERROR_RFMON_NOTSUP
;
4278 * Save the old mode.
4280 handle
->md
.oldmode
= ireq
.u
.mode
;
4283 * Put the adapter in rfmon mode. How we do this depends
4284 * on whether we have a special private ioctl or not.
4286 if (montype
== MONITOR_PRISM
) {
4288 * We have the "monitor" private ioctl, but none of
4289 * the other private ioctls. Use this, and select
4292 * If it fails, just fall back on SIOCSIWMODE.
4294 memset(&ireq
, 0, sizeof ireq
);
4295 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4296 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4297 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4298 ireq
.u
.data
.length
= 1; /* 1 argument */
4299 args
[0] = 3; /* request Prism header */
4300 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
4301 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
4304 * Note that we have to put the old mode back
4305 * when we close the device.
4307 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4310 * Add this to the list of pcaps to close
4313 pcap_add_to_pcaps_to_close(handle
);
4319 * Failure. Fall back on SIOCSIWMODE.
4324 * First, turn monitor mode on.
4326 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4327 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4328 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4329 ireq
.u
.mode
= IW_MODE_MONITOR
;
4330 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
4332 * Scientist, you've failed.
4334 return PCAP_ERROR_RFMON_NOTSUP
;
4338 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4339 * monitor mode and setting the channel, and then does
4344 * Now select the appropriate radio header.
4350 * We don't have any private ioctl to set the header.
4354 case MONITOR_HOSTAP
:
4356 * Try to select the radiotap header.
4358 memset(&ireq
, 0, sizeof ireq
);
4359 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4360 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4361 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4362 args
[0] = 3; /* request radiotap header */
4363 memcpy(ireq
.u
.name
, args
, sizeof (int));
4364 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4365 break; /* success */
4368 * That failed. Try to select the AVS header.
4370 memset(&ireq
, 0, sizeof ireq
);
4371 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4372 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4373 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4374 args
[0] = 2; /* request AVS header */
4375 memcpy(ireq
.u
.name
, args
, sizeof (int));
4376 if (ioctl(sock_fd
, cmd
, &ireq
) != -1)
4377 break; /* success */
4380 * That failed. Try to select the Prism header.
4382 memset(&ireq
, 0, sizeof ireq
);
4383 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4384 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4385 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4386 args
[0] = 1; /* request Prism header */
4387 memcpy(ireq
.u
.name
, args
, sizeof (int));
4388 ioctl(sock_fd
, cmd
, &ireq
);
4393 * The private ioctl failed.
4397 case MONITOR_PRISM54
:
4399 * Select the Prism header.
4401 memset(&ireq
, 0, sizeof ireq
);
4402 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4403 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4404 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4405 args
[0] = 3; /* request Prism header */
4406 memcpy(ireq
.u
.name
, args
, sizeof (int));
4407 ioctl(sock_fd
, cmd
, &ireq
);
4410 case MONITOR_ACX100
:
4412 * Get the current channel.
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 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
4419 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4420 "%s: SIOCGIWFREQ: %s", device
,
4421 pcap_strerror(errno
));
4424 channel
= ireq
.u
.freq
.m
;
4427 * Select the Prism header, and set the channel to the
4430 memset(&ireq
, 0, sizeof ireq
);
4431 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4432 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4433 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4434 args
[0] = 1; /* request Prism header */
4435 args
[1] = channel
; /* set channel */
4436 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
4437 ioctl(sock_fd
, cmd
, &ireq
);
4440 case MONITOR_RT2500
:
4442 * Disallow transmission - that turns on the
4445 memset(&ireq
, 0, sizeof ireq
);
4446 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4447 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4448 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4449 args
[0] = 0; /* disallow transmitting */
4450 memcpy(ireq
.u
.name
, args
, sizeof (int));
4451 ioctl(sock_fd
, cmd
, &ireq
);
4454 case MONITOR_RT2570
:
4456 * Force the Prism header.
4458 memset(&ireq
, 0, sizeof ireq
);
4459 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4460 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4461 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4462 args
[0] = 1; /* request Prism header */
4463 memcpy(ireq
.u
.name
, args
, sizeof (int));
4464 ioctl(sock_fd
, cmd
, &ireq
);
4469 * Force the Prism header.
4471 memset(&ireq
, 0, sizeof ireq
);
4472 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4473 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4474 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4475 ireq
.u
.data
.length
= 1; /* 1 argument */
4476 ireq
.u
.data
.pointer
= "1";
4477 ireq
.u
.data
.flags
= 0;
4478 ioctl(sock_fd
, cmd
, &ireq
);
4481 case MONITOR_RTL8XXX
:
4483 * Force the Prism header.
4485 memset(&ireq
, 0, sizeof ireq
);
4486 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
4487 sizeof ireq
.ifr_ifrn
.ifrn_name
);
4488 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
4489 args
[0] = 1; /* request Prism header */
4490 memcpy(ireq
.u
.name
, args
, sizeof (int));
4491 ioctl(sock_fd
, cmd
, &ireq
);
4496 * Note that we have to put the old mode back when we
4499 handle
->md
.must_do_on_close
|= MUST_CLEAR_RFMON
;
4502 * Add this to the list of pcaps to close when we exit.
4504 pcap_add_to_pcaps_to_close(handle
);
4508 #endif /* IW_MODE_MONITOR */
4511 * Try various mechanisms to enter monitor mode.
4514 enter_rfmon_mode(pcap_t
*handle
, int sock_fd
, const char *device
)
4516 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4521 ret
= enter_rfmon_mode_mac80211(handle
, sock_fd
, device
);
4523 return ret
; /* error attempting to do so */
4525 return 1; /* success */
4526 #endif /* HAVE_LIBNL */
4528 #ifdef IW_MODE_MONITOR
4529 ret
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
4531 return ret
; /* error attempting to do so */
4533 return 1; /* success */
4534 #endif /* IW_MODE_MONITOR */
4537 * Either none of the mechanisms we know about work or none
4538 * of those mechanisms are available, so we can't do monitor
4544 #endif /* HAVE_PF_PACKET_SOCKETS */
4546 /* ===== Functions to interface to the older kernels ================== */
4549 * Try to open a packet socket using the old kernel interface.
4550 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4553 activate_old(pcap_t
*handle
)
4557 const char *device
= handle
->opt
.source
;
4558 struct utsname utsname
;
4561 /* Open the socket */
4563 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
4564 if (handle
->fd
== -1) {
4565 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4566 "socket: %s", pcap_strerror(errno
));
4567 return PCAP_ERROR_PERM_DENIED
;
4570 /* It worked - we are using the old interface */
4571 handle
->md
.sock_packet
= 1;
4573 /* ...which means we get the link-layer header. */
4574 handle
->md
.cooked
= 0;
4576 /* Bind to the given device */
4578 if (strcmp(device
, "any") == 0) {
4579 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4583 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
4587 * Try to get the link-layer type.
4589 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
4594 * Try to find the DLT_ type corresponding to that
4597 map_arphrd_to_dlt(handle
, arptype
, 0);
4598 if (handle
->linktype
== -1) {
4599 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4600 "unknown arptype %d", arptype
);
4604 /* Go to promisc mode if requested */
4606 if (handle
->opt
.promisc
) {
4607 memset(&ifr
, 0, sizeof(ifr
));
4608 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4609 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
4610 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4611 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
4614 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
4616 * Promiscuous mode isn't currently on,
4617 * so turn it on, and remember that
4618 * we should turn it off when the
4623 * If we haven't already done so, arrange
4624 * to have "pcap_close_all()" called when
4627 if (!pcap_do_addexit(handle
)) {
4629 * "atexit()" failed; don't put
4630 * the interface in promiscuous
4631 * mode, just give up.
4636 ifr
.ifr_flags
|= IFF_PROMISC
;
4637 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
4638 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4640 pcap_strerror(errno
));
4643 handle
->md
.must_do_on_close
|= MUST_CLEAR_PROMISC
;
4646 * Add this to the list of pcaps
4647 * to close when we exit.
4649 pcap_add_to_pcaps_to_close(handle
);
4654 * Compute the buffer size.
4656 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4657 * kernel, and might require special handling - check.
4659 if (uname(&utsname
) < 0 ||
4660 strncmp(utsname
.release
, "2.0", 3) == 0) {
4662 * Either we couldn't find out what kernel release
4663 * this is, or it's a 2.0[.x] kernel.
4665 * In the 2.0[.x] kernel, a "recvfrom()" on
4666 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4667 * return the number of bytes read, so if we pass
4668 * a length based on the snapshot length, it'll
4669 * return the number of bytes from the packet
4670 * copied to userland, not the actual length
4673 * This means that, for example, the IP dissector
4674 * in tcpdump will get handed a packet length less
4675 * than the length in the IP header, and will
4676 * complain about "truncated-ip".
4678 * So we don't bother trying to copy from the
4679 * kernel only the bytes in which we're interested,
4680 * but instead copy them all, just as the older
4681 * versions of libpcap for Linux did.
4683 * The buffer therefore needs to be big enough to
4684 * hold the largest packet we can get from this
4685 * device. Unfortunately, we can't get the MRU
4686 * of the network; we can only get the MTU. The
4687 * MTU may be too small, in which case a packet larger
4688 * than the buffer size will be truncated *and* we
4689 * won't get the actual packet size.
4691 * However, if the snapshot length is larger than
4692 * the buffer size based on the MTU, we use the
4693 * snapshot length as the buffer size, instead;
4694 * this means that with a sufficiently large snapshot
4695 * length we won't artificially truncate packets
4696 * to the MTU-based size.
4698 * This mess just one of many problems with packet
4699 * capture on 2.0[.x] kernels; you really want a
4700 * 2.2[.x] or later kernel if you want packet capture
4703 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
4706 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
4707 if (handle
->bufsize
< handle
->snapshot
)
4708 handle
->bufsize
= handle
->snapshot
;
4711 * This is a 2.2[.x] or later kernel.
4713 * We can safely pass "recvfrom()" a byte count
4714 * based on the snapshot length.
4716 handle
->bufsize
= handle
->snapshot
;
4720 * Default value for offset to align link-layer payload
4721 * on a 4-byte boundary.
4729 * Bind the socket associated with FD to the given device using the
4730 * interface of the old kernels.
4733 iface_bind_old(int fd
, const char *device
, char *ebuf
)
4735 struct sockaddr saddr
;
4737 socklen_t errlen
= sizeof(err
);
4739 memset(&saddr
, 0, sizeof(saddr
));
4740 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
4741 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
4742 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4743 "bind: %s", pcap_strerror(errno
));
4747 /* Any pending errors, e.g., network is down? */
4749 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
4750 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4751 "getsockopt: %s", pcap_strerror(errno
));
4756 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4757 "bind: %s", pcap_strerror(err
));
4765 /* ===== System calls available on all supported kernels ============== */
4768 * Query the kernel for the MTU of the given interface.
4771 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
4776 return BIGGER_THAN_ALL_MTUS
;
4778 memset(&ifr
, 0, sizeof(ifr
));
4779 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4781 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
4782 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4783 "SIOCGIFMTU: %s", pcap_strerror(errno
));
4791 * Get the hardware type of the given interface as ARPHRD_xxx constant.
4794 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
4798 memset(&ifr
, 0, sizeof(ifr
));
4799 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
4801 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
4802 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
4803 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
4804 if (errno
== ENODEV
) {
4808 return PCAP_ERROR_NO_SUCH_DEVICE
;
4813 return ifr
.ifr_hwaddr
.sa_family
;
4816 #ifdef SO_ATTACH_FILTER
4818 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
, int is_mmapped
)
4822 register struct bpf_insn
*p
;
4827 * Make a copy of the filter, and modify that copy if
4830 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
4831 len
= handle
->fcode
.bf_len
;
4832 f
= (struct bpf_insn
*)malloc(prog_size
);
4834 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
4835 "malloc: %s", pcap_strerror(errno
));
4838 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
4840 fcode
->filter
= (struct sock_filter
*) f
;
4842 for (i
= 0; i
< len
; ++i
) {
4845 * What type of instruction is this?
4847 switch (BPF_CLASS(p
->code
)) {
4851 * It's a return instruction; are we capturing
4852 * in memory-mapped mode?
4856 * No; is the snapshot length a constant,
4857 * rather than the contents of the
4860 if (BPF_MODE(p
->code
) == BPF_K
) {
4862 * Yes - if the value to be returned,
4863 * i.e. the snapshot length, is
4864 * anything other than 0, make it
4865 * 65535, so that the packet is
4866 * truncated by "recvfrom()",
4867 * not by the filter.
4869 * XXX - there's nothing we can
4870 * easily do if it's getting the
4871 * value from the accumulator; we'd
4872 * have to insert code to force
4873 * non-zero values to be 65535.
4884 * It's a load instruction; is it loading
4887 switch (BPF_MODE(p
->code
)) {
4893 * Yes; are we in cooked mode?
4895 if (handle
->md
.cooked
) {
4897 * Yes, so we need to fix this
4900 if (fix_offset(p
) < 0) {
4902 * We failed to do so.
4903 * Return 0, so our caller
4904 * knows to punt to userland.
4914 return 1; /* we succeeded */
4918 fix_offset(struct bpf_insn
*p
)
4921 * What's the offset?
4923 if (p
->k
>= SLL_HDR_LEN
) {
4925 * It's within the link-layer payload; that starts at an
4926 * offset of 0, as far as the kernel packet filter is
4927 * concerned, so subtract the length of the link-layer
4930 p
->k
-= SLL_HDR_LEN
;
4931 } else if (p
->k
== 14) {
4933 * It's the protocol field; map it to the special magic
4934 * kernel offset for that field.
4936 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
4939 * It's within the header, but it's not one of those
4940 * fields; we can't do that in the kernel, so punt
4949 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
4951 int total_filter_on
= 0;
4957 * The socket filter code doesn't discard all packets queued
4958 * up on the socket when the filter is changed; this means
4959 * that packets that don't match the new filter may show up
4960 * after the new filter is put onto the socket, if those
4961 * packets haven't yet been read.
4963 * This means, for example, that if you do a tcpdump capture
4964 * with a filter, the first few packets in the capture might
4965 * be packets that wouldn't have passed the filter.
4967 * We therefore discard all packets queued up on the socket
4968 * when setting a kernel filter. (This isn't an issue for
4969 * userland filters, as the userland filtering is done after
4970 * packets are queued up.)
4972 * To flush those packets, we put the socket in read-only mode,
4973 * and read packets from the socket until there are no more to
4976 * In order to keep that from being an infinite loop - i.e.,
4977 * to keep more packets from arriving while we're draining
4978 * the queue - we put the "total filter", which is a filter
4979 * that rejects all packets, onto the socket before draining
4982 * This code deliberately ignores any errors, so that you may
4983 * get bogus packets if an error occurs, rather than having
4984 * the filtering done in userland even if it could have been
4985 * done in the kernel.
4987 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
4988 &total_fcode
, sizeof(total_fcode
)) == 0) {
4992 * Note that we've put the total filter onto the socket.
4994 total_filter_on
= 1;
4997 * Save the socket's current mode, and put it in
4998 * non-blocking mode; we drain it by reading packets
4999 * until we get an error (which is normally a
5000 * "nothing more to be read" error).
5002 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
5003 if (save_mode
!= -1 &&
5004 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
5005 while (recv(handle
->fd
, &drain
, sizeof drain
,
5009 fcntl(handle
->fd
, F_SETFL
, save_mode
);
5010 if (save_errno
!= EAGAIN
) {
5012 reset_kernel_filter(handle
);
5013 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
5014 "recv: %s", pcap_strerror(save_errno
));
5021 * Now attach the new filter.
5023 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
5024 fcode
, sizeof(*fcode
));
5025 if (ret
== -1 && total_filter_on
) {
5027 * Well, we couldn't set that filter on the socket,
5028 * but we could set the total filter on the socket.
5030 * This could, for example, mean that the filter was
5031 * too big to put into the kernel, so we'll have to
5032 * filter in userland; in any case, we'll be doing
5033 * filtering in userland, so we need to remove the
5034 * total filter so we see packets.
5039 * XXX - if this fails, we're really screwed;
5040 * we have the total filter on the socket,
5041 * and it won't come off. What do we do then?
5043 reset_kernel_filter(handle
);
5051 reset_kernel_filter(pcap_t
*handle
)
5054 * setsockopt() barfs unless it get a dummy parameter.
5055 * valgrind whines unless the value is initialized,
5056 * as it has no idea that setsockopt() ignores its
5061 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
5062 &dummy
, sizeof(dummy
));