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/stat.h>
131 #include <sys/socket.h>
132 #include <sys/ioctl.h>
133 #include <sys/utsname.h>
134 #include <sys/mman.h>
135 #include <linux/if.h>
136 #include <linux/if_packet.h>
137 #include <netinet/in.h>
138 #include <linux/if_ether.h>
139 #include <net/if_arp.h>
143 #include "pcap-int.h"
144 #include "pcap/sll.h"
145 #include "pcap/vlan.h"
148 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
149 * sockets rather than SOCK_PACKET sockets.
151 * To use them, we include <linux/if_packet.h> rather than
152 * <netpacket/packet.h>; we do so because
154 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
155 * later kernels and libc5, and don't provide a <netpacket/packet.h>
158 * not all versions of glibc2 have a <netpacket/packet.h> file
159 * that defines stuff needed for some of the 2.4-or-later-kernel
160 * features, so if the system has a 2.4 or later kernel, we
161 * still can't use those features.
163 * We're already including a number of other <linux/XXX.h> headers, and
164 * this code is Linux-specific (no other OS has PF_PACKET sockets as
165 * a raw packet capture mechanism), so it's not as if you gain any
166 * useful portability by using <netpacket/packet.h>
168 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
169 * isn't defined? It only defines one data structure in 2.0.x, so
170 * it shouldn't cause any problems.
173 # include <linux/if_packet.h>
176 * On at least some Linux distributions (for example, Red Hat 5.2),
177 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
178 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
179 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
180 * the PACKET_xxx stuff.
182 * So we check whether PACKET_HOST is defined, and assume that we have
183 * PF_PACKET sockets only if it is defined.
186 # define HAVE_PF_PACKET_SOCKETS
187 # ifdef PACKET_AUXDATA
188 # define HAVE_PACKET_AUXDATA
189 # endif /* PACKET_AUXDATA */
190 # endif /* PACKET_HOST */
193 /* check for memory mapped access avaibility. We assume every needed
194 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
195 * uses many ring related structs and macros */
196 # ifdef TPACKET_HDRLEN
197 # define HAVE_PACKET_RING
198 # ifdef TPACKET2_HDRLEN
199 # define HAVE_TPACKET2
201 # define TPACKET_V1 0
202 # endif /* TPACKET2_HDRLEN */
203 # endif /* TPACKET_HDRLEN */
204 #endif /* PF_PACKET */
206 #ifdef SO_ATTACH_FILTER
207 #include <linux/types.h>
208 #include <linux/filter.h>
212 * We need linux/sockios.h if we have linux/net_tstamp.h (for time stamp
213 * specification) or linux/ethtool.h (for ethtool ioctls to get offloading
216 #if defined(HAVE_LINUX_NET_TSTAMP_H) || defined(HAVE_LINUX_ETHTOOL_H)
217 #include <linux/sockios.h>
220 #ifdef HAVE_LINUX_NET_TSTAMP_H
221 #include <linux/net_tstamp.h>
225 * Got Wireless Extensions?
227 #ifdef HAVE_LINUX_WIRELESS_H
228 #include <linux/wireless.h>
229 #endif /* HAVE_LINUX_WIRELESS_H */
235 #include <linux/nl80211.h>
237 #include <netlink/genl/genl.h>
238 #include <netlink/genl/family.h>
239 #include <netlink/genl/ctrl.h>
240 #include <netlink/msg.h>
241 #include <netlink/attr.h>
242 #endif /* HAVE_LIBNL */
245 * Got ethtool support?
247 #ifdef HAVE_LINUX_ETHTOOL_H
248 #include <linux/ethtool.h>
251 #ifndef HAVE_SOCKLEN_T
252 typedef int socklen_t;
257 * This is being compiled on a system that lacks MSG_TRUNC; define it
258 * with the value it has in the 2.2 and later kernels, so that, on
259 * those kernels, when we pass it in the flags argument to "recvfrom()"
260 * we're passing the right value and thus get the MSG_TRUNC behavior
261 * we want. (We don't get that behavior on 2.0[.x] kernels, because
262 * they didn't support MSG_TRUNC.)
264 #define MSG_TRUNC 0x20
269 * This is being compiled on a system that lacks SOL_PACKET; define it
270 * with the value it has in the 2.2 and later kernels, so that we can
271 * set promiscuous mode in the good modern way rather than the old
272 * 2.0-kernel crappy way.
274 #define SOL_PACKET 263
277 #define MAX_LINKHEADER_SIZE 256
280 * When capturing on all interfaces we use this as the buffer size.
281 * Should be bigger then all MTUs that occur in real life.
282 * 64kB should be enough for now.
284 #define BIGGER_THAN_ALL_MTUS (64*1024)
287 * Prototypes for internal functions and methods.
289 static void map_arphrd_to_dlt(pcap_t *, int, int);
290 #ifdef HAVE_PF_PACKET_SOCKETS
291 static short int map_packet_type_to_sll_type(short int);
293 static int pcap_activate_linux(pcap_t *);
294 static int activate_old(pcap_t *);
295 static int activate_new(pcap_t *);
296 static int activate_mmap(pcap_t *, int *);
297 static int pcap_can_set_rfmon_linux(pcap_t *);
298 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
299 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
300 static int pcap_inject_linux(pcap_t *, const void *, size_t);
301 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
302 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
303 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
304 static void pcap_cleanup_linux(pcap_t *);
307 struct tpacket_hdr *h1;
308 struct tpacket2_hdr *h2;
312 #ifdef HAVE_PACKET_RING
313 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
315 static void destroy_ring(pcap_t *handle);
316 static int create_ring(pcap_t *handle, int *status);
317 static int prepare_tpacket_socket(pcap_t *handle);
318 static void pcap_cleanup_linux_mmap(pcap_t *);
319 static int pcap_read_linux_mmap(pcap_t *, int, pcap_handler , u_char *);
320 static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
321 static int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
322 static int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
323 static void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
324 const u_char *bytes);
328 * Wrap some ioctl calls
330 #ifdef HAVE_PF_PACKET_SOCKETS
331 static int iface_get_id(int fd, const char *device, char *ebuf);
332 #endif /* HAVE_PF_PACKET_SOCKETS */
333 static int iface_get_mtu(int fd, const char *device, char *ebuf);
334 static int iface_get_arptype(int fd, const char *device, char *ebuf);
335 #ifdef HAVE_PF_PACKET_SOCKETS
336 static int iface_bind(int fd, int ifindex, char *ebuf);
337 #ifdef IW_MODE_MONITOR
338 static int has_wext(int sock_fd, const char *device, char *ebuf);
339 #endif /* IW_MODE_MONITOR */
340 static int enter_rfmon_mode(pcap_t *handle, int sock_fd,
342 #endif /* HAVE_PF_PACKET_SOCKETS */
343 static int iface_get_offload(pcap_t *handle);
344 static int iface_bind_old(int fd, const char *device, char *ebuf);
346 #ifdef SO_ATTACH_FILTER
347 static int fix_program(pcap_t *handle, struct sock_fprog *fcode,
349 static int fix_offset(struct bpf_insn *p);
350 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
351 static int reset_kernel_filter(pcap_t *handle);
353 static struct sock_filter total_insn
354 = BPF_STMT(BPF_RET | BPF_K, 0);
355 static struct sock_fprog total_fcode
356 = { 1, &total_insn };
357 #endif /* SO_ATTACH_FILTER */
360 pcap_create_interface(const char *device, char *ebuf)
364 handle = pcap_create_common(device, ebuf);
368 handle->activate_op = pcap_activate_linux;
369 handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
370 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
372 * We claim that we support:
374 * software time stamps, with no details about their precision;
375 * hardware time stamps, synced to the host time;
376 * hardware time stamps, not synced to the host time.
378 * XXX - we can't ask a device whether it supports
379 * hardware time stamps, so we just claim all devices do.
381 handle->tstamp_type_count = 3;
382 handle->tstamp_type_list = malloc(3 * sizeof(u_int));
383 if (handle->tstamp_type_list == NULL) {
387 handle->tstamp_type_list[0] = PCAP_TSTAMP_HOST;
388 handle->tstamp_type_list[1] = PCAP_TSTAMP_ADAPTER;
389 handle->tstamp_type_list[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED;
397 * If interface {if} is a mac80211 driver, the file
398 * /sys/class/net/{if}/phy80211 is a symlink to
399 * /sys/class/ieee80211/{phydev}, for some {phydev}.
401 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
402 * least, has a "wmaster0" device and a "wlan0" device; the
403 * latter is the one with the IP address. Both show up in
404 * "tcpdump -D" output. Capturing on the wmaster0 device
405 * captures with 802.11 headers.
407 * airmon-ng searches through /sys/class/net for devices named
408 * monN, starting with mon0; as soon as one *doesn't* exist,
409 * it chooses that as the monitor device name. If the "iw"
410 * command exists, it does "iw dev {if} interface add {monif}
411 * type monitor", where {monif} is the monitor device. It
412 * then (sigh) sleeps .1 second, and then configures the
413 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
414 * is a file, it writes {mondev}, without a newline, to that file,
415 * and again (sigh) sleeps .1 second, and then iwconfig's that
416 * device into monitor mode and configures it up. Otherwise,
417 * you can't do monitor mode.
419 * All these devices are "glued" together by having the
420 * /sys/class/net/{device}/phy80211 links pointing to the same
421 * place, so, given a wmaster, wlan, or mon device, you can
422 * find the other devices by looking for devices with
423 * the same phy80211 link.
425 * To turn monitor mode off, delete the monitor interface,
426 * either with "iw dev {monif} interface del" or by sending
427 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
429 * Note: if you try to create a monitor device named "monN", and
430 * there's already a "monN" device, it fails, as least with
431 * the netlink interface (which is what iw uses), with a return
432 * value of -ENFILE. (Return values are negative errnos.) We
433 * could probably use that to find an unused device.
435 * Yes, you can have multiple monitor devices for a given
440 * Is this a mac80211 device? If so, fill in the physical device path and
441 * return 1; if not, return 0. On an error, fill in handle->errbuf and
445 get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
446 size_t phydev_max_pathlen)
452 * Generate the path string for the symlink to the physical device.
454 if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
455 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
456 "%s: Can't generate path name string for /sys/class/net device",
460 bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
461 if (bytes_read == -1) {
462 if (errno == ENOENT || errno == EINVAL) {
464 * Doesn't exist, or not a symlink; assume that
465 * means it's not a mac80211 device.
470 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
471 "%s: Can't readlink %s: %s", device, pathstr,
477 phydev_path[bytes_read] = '\0';
481 #ifdef HAVE_LIBNL_SOCKETS
482 #define get_nl_errmsg nl_geterror
484 /* libnl 2.x compatibility code */
486 #define nl_sock nl_handle
488 static inline struct nl_handle *
489 nl_socket_alloc(void)
491 return nl_handle_alloc();
495 nl_socket_free(struct nl_handle *h)
497 nl_handle_destroy(h);
500 #define get_nl_errmsg strerror
503 __genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
505 struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
511 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
512 #endif /* !HAVE_LIBNL_SOCKETS */
514 struct nl80211_state {
515 struct nl_sock *nl_sock;
516 struct nl_cache *nl_cache;
517 struct genl_family *nl80211;
521 nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
525 state->nl_sock = nl_socket_alloc();
526 if (!state->nl_sock) {
527 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
528 "%s: failed to allocate netlink handle", device);
532 if (genl_connect(state->nl_sock)) {
533 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
534 "%s: failed to connect to generic netlink", device);
535 goto out_handle_destroy;
538 err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
540 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
541 "%s: failed to allocate generic netlink cache: %s",
542 device, get_nl_errmsg(-err));
543 goto out_handle_destroy;
546 state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
547 if (!state->nl80211) {
548 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
549 "%s: nl80211 not found", device);
556 nl_cache_free(state->nl_cache);
558 nl_socket_free(state->nl_sock);
563 nl80211_cleanup(struct nl80211_state *state)
565 genl_family_put(state->nl80211);
566 nl_cache_free(state->nl_cache);
567 nl_socket_free(state->nl_sock);
571 add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
572 const char *device, const char *mondevice)
578 ifindex = iface_get_id(sock_fd, device, handle->errbuf);
584 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
585 "%s: failed to allocate netlink msg", device);
589 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
590 0, NL80211_CMD_NEW_INTERFACE, 0);
591 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
592 NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
593 NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
595 err = nl_send_auto_complete(state->nl_sock, msg);
597 #if defined HAVE_LIBNL_NLE
598 if (err == -NLE_FAILURE) {
600 if (err == -ENFILE) {
603 * Device not available; our caller should just
604 * keep trying. (libnl 2.x maps ENFILE to
605 * NLE_FAILURE; it can also map other errors
606 * to that, but there's not much we can do
613 * Real failure, not just "that device is not
616 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
617 "%s: nl_send_auto_complete failed adding %s interface: %s",
618 device, mondevice, get_nl_errmsg(-err));
623 err = nl_wait_for_ack(state->nl_sock);
625 #if defined HAVE_LIBNL_NLE
626 if (err == -NLE_FAILURE) {
628 if (err == -ENFILE) {
631 * Device not available; our caller should just
632 * keep trying. (libnl 2.x maps ENFILE to
633 * NLE_FAILURE; it can also map other errors
634 * to that, but there's not much we can do
641 * Real failure, not just "that device is not
644 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
645 "%s: nl_wait_for_ack failed adding %s interface: %s",
646 device, mondevice, get_nl_errmsg(-err));
659 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
660 "%s: nl_put failed adding %s interface",
667 del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
668 const char *device, const char *mondevice)
674 ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
680 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
681 "%s: failed to allocate netlink msg", device);
685 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
686 0, NL80211_CMD_DEL_INTERFACE, 0);
687 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
689 err = nl_send_auto_complete(state->nl_sock, msg);
691 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
692 "%s: nl_send_auto_complete failed deleting %s interface: %s",
693 device, mondevice, get_nl_errmsg(-err));
697 err = nl_wait_for_ack(state->nl_sock);
699 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
700 "%s: nl_wait_for_ack failed adding %s interface: %s",
701 device, mondevice, get_nl_errmsg(-err));
713 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
714 "%s: nl_put failed deleting %s interface",
721 enter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
724 char phydev_path[PATH_MAX+1];
725 struct nl80211_state nlstate;
730 * Is this a mac80211 device?
732 ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
734 return ret; /* error */
736 return 0; /* no error, but not mac80211 device */
739 * XXX - is this already a monN device?
741 * Is that determined by old Wireless Extensions ioctls?
745 * OK, it's apparently a mac80211 device.
746 * Try to find an unused monN device for it.
748 ret = nl80211_init(handle, &nlstate, device);
751 for (n = 0; n < UINT_MAX; n++) {
755 char mondevice[3+10+1]; /* mon{UINT_MAX}\0 */
757 snprintf(mondevice, sizeof mondevice, "mon%u", n);
758 ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
760 handle->md.mondevice = strdup(mondevice);
765 * Hard failure. Just return ret; handle->errbuf
766 * has already been set.
768 nl80211_cleanup(&nlstate);
773 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
774 "%s: No free monN interfaces", device);
775 nl80211_cleanup(&nlstate);
782 * Sleep for .1 seconds.
785 delay.tv_nsec = 500000000;
786 nanosleep(&delay, NULL);
790 * If we haven't already done so, arrange to have
791 * "pcap_close_all()" called when we exit.
793 if (!pcap_do_addexit(handle)) {
795 * "atexit()" failed; don't put the interface
796 * in rfmon mode, just give up.
798 return PCAP_ERROR_RFMON_NOTSUP;
802 * Now configure the monitor interface up.
804 memset(&ifr, 0, sizeof(ifr));
805 strncpy(ifr.ifr_name, handle->md.mondevice, sizeof(ifr.ifr_name));
806 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
807 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
808 "%s: Can't get flags for %s: %s", device,
809 handle->md.mondevice, strerror(errno));
810 del_mon_if(handle, sock_fd, &nlstate, device,
811 handle->md.mondevice);
812 nl80211_cleanup(&nlstate);
815 ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
816 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
817 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
818 "%s: Can't set flags for %s: %s", device,
819 handle->md.mondevice, strerror(errno));
820 del_mon_if(handle, sock_fd, &nlstate, device,
821 handle->md.mondevice);
822 nl80211_cleanup(&nlstate);
827 * Success. Clean up the libnl state.
829 nl80211_cleanup(&nlstate);
832 * Note that we have to delete the monitor device when we close
835 handle->md.must_do_on_close |= MUST_DELETE_MONIF;
838 * Add this to the list of pcaps to close when we exit.
840 pcap_add_to_pcaps_to_close(handle);
844 #endif /* HAVE_LIBNL */
847 pcap_can_set_rfmon_linux(pcap_t *handle)
850 char phydev_path[PATH_MAX+1];
853 #ifdef IW_MODE_MONITOR
858 if (strcmp(handle->opt.source, "any") == 0) {
860 * Monitor mode makes no sense on the "any" device.
867 * Bleah. There doesn't seem to be a way to ask a mac80211
868 * device, through libnl, whether it supports monitor mode;
869 * we'll just check whether the device appears to be a
870 * mac80211 device and, if so, assume the device supports
873 * wmaster devices don't appear to support the Wireless
874 * Extensions, but we can create a mon device for a
875 * wmaster device, so we don't bother checking whether
876 * a mac80211 device supports the Wireless Extensions.
878 ret = get_mac80211_phydev(handle, handle->opt.source, phydev_path,
881 return ret; /* error */
883 return 1; /* mac80211 device */
886 #ifdef IW_MODE_MONITOR
888 * Bleah. There doesn't appear to be an ioctl to use to ask
889 * whether a device supports monitor mode; we'll just do
890 * SIOCGIWMODE and, if it succeeds, assume the device supports
893 * Open a socket on which to attempt to get the mode.
894 * (We assume that if we have Wireless Extensions support
895 * we also have PF_PACKET support.)
897 sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
899 (void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
900 "socket: %s", pcap_strerror(errno));
905 * Attempt to get the current mode.
907 strncpy(ireq.ifr_ifrn.ifrn_name, handle->opt.source,
908 sizeof ireq.ifr_ifrn.ifrn_name);
909 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
910 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
912 * Well, we got the mode; assume we can set it.
917 if (errno == ENODEV) {
918 /* The device doesn't even exist. */
919 (void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
920 "SIOCGIWMODE failed: %s", pcap_strerror(errno));
922 return PCAP_ERROR_NO_SUCH_DEVICE;
930 * Grabs the number of dropped packets by the interface from /proc/net/dev.
932 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
933 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
935 * Or can we get them in binary form from netlink?
938 linux_if_drops(const char * if_name)
943 int field_to_convert = 3, if_name_sz = strlen(if_name);
944 long int dropped_pkts = 0;
946 file = fopen("/proc/net/dev", "r");
950 while (!dropped_pkts && fgets( buffer, sizeof(buffer), file ))
952 /* search for 'bytes' -- if its in there, then
953 that means we need to grab the fourth field. otherwise
954 grab the third field. */
955 if (field_to_convert != 4 && strstr(buffer, "bytes"))
957 field_to_convert = 4;
961 /* find iface and make sure it actually matches -- space before the name and : after it */
962 if ((bufptr = strstr(buffer, if_name)) &&
963 (bufptr == buffer || *(bufptr-1) == ' ') &&
964 *(bufptr + if_name_sz) == ':')
966 bufptr = bufptr + if_name_sz + 1;
968 /* grab the nth field from it */
969 while( --field_to_convert && *bufptr != '\0')
971 while (*bufptr != '\0' && *(bufptr++) == ' ');
972 while (*bufptr != '\0' && *(bufptr++) != ' ');
975 /* get rid of any final spaces */
976 while (*bufptr != '\0' && *bufptr == ' ') bufptr++;
979 dropped_pkts = strtol(bufptr, NULL, 10);
991 * With older kernels promiscuous mode is kind of interesting because we
992 * have to reset the interface before exiting. The problem can't really
993 * be solved without some daemon taking care of managing usage counts.
994 * If we put the interface into promiscuous mode, we set a flag indicating
995 * that we must take it out of that mode when the interface is closed,
996 * and, when closing the interface, if that flag is set we take it out
997 * of promiscuous mode.
999 * Even with newer kernels, we have the same issue with rfmon mode.
1002 static void pcap_cleanup_linux( pcap_t *handle )
1006 struct nl80211_state nlstate;
1008 #endif /* HAVE_LIBNL */
1009 #ifdef IW_MODE_MONITOR
1012 #endif /* IW_MODE_MONITOR */
1014 if (handle->md.must_do_on_close != 0) {
1016 * There's something we have to do when closing this
1019 if (handle->md.must_do_on_close & MUST_CLEAR_PROMISC) {
1021 * We put the interface into promiscuous mode;
1022 * take it out of promiscuous mode.
1024 * XXX - if somebody else wants it in promiscuous
1025 * mode, this code cannot know that, so it'll take
1026 * it out of promiscuous mode. That's not fixable
1027 * in 2.0[.x] kernels.
1029 memset(&ifr, 0, sizeof(ifr));
1030 strncpy(ifr.ifr_name, handle->md.device,
1031 sizeof(ifr.ifr_name));
1032 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1034 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1035 "Please adjust manually.\n"
1036 "Hint: This can't happen with Linux >= 2.2.0.\n",
1037 handle->md.device, strerror(errno));
1039 if (ifr.ifr_flags & IFF_PROMISC) {
1041 * Promiscuous mode is currently on;
1044 ifr.ifr_flags &= ~IFF_PROMISC;
1045 if (ioctl(handle->fd, SIOCSIFFLAGS,
1048 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1049 "Please adjust manually.\n"
1050 "Hint: This can't happen with Linux >= 2.2.0.\n",
1059 if (handle->md.must_do_on_close & MUST_DELETE_MONIF) {
1060 ret = nl80211_init(handle, &nlstate, handle->md.device);
1062 ret = del_mon_if(handle, handle->fd, &nlstate,
1063 handle->md.device, handle->md.mondevice);
1064 nl80211_cleanup(&nlstate);
1068 "Can't delete monitor interface %s (%s).\n"
1069 "Please delete manually.\n",
1070 handle->md.mondevice, handle->errbuf);
1073 #endif /* HAVE_LIBNL */
1075 #ifdef IW_MODE_MONITOR
1076 if (handle->md.must_do_on_close & MUST_CLEAR_RFMON) {
1078 * We put the interface into rfmon mode;
1079 * take it out of rfmon mode.
1081 * XXX - if somebody else wants it in rfmon
1082 * mode, this code cannot know that, so it'll take
1083 * it out of rfmon mode.
1087 * First, take the interface down if it's up;
1088 * otherwise, we might get EBUSY.
1089 * If we get errors, just drive on and print
1090 * a warning if we can't restore the mode.
1093 memset(&ifr, 0, sizeof(ifr));
1094 strncpy(ifr.ifr_name, handle->md.device,
1095 sizeof(ifr.ifr_name));
1096 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
1097 if (ifr.ifr_flags & IFF_UP) {
1098 oldflags = ifr.ifr_flags;
1099 ifr.ifr_flags &= ~IFF_UP;
1100 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
1101 oldflags = 0; /* didn't set, don't restore */
1106 * Now restore the mode.
1108 strncpy(ireq.ifr_ifrn.ifrn_name, handle->md.device,
1109 sizeof ireq.ifr_ifrn.ifrn_name);
1110 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1]
1112 ireq.u.mode = handle->md.oldmode;
1113 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
1115 * Scientist, you've failed.
1118 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1119 "Please adjust manually.\n",
1120 handle->md.device, strerror(errno));
1124 * Now bring the interface back up if we brought
1127 if (oldflags != 0) {
1128 ifr.ifr_flags = oldflags;
1129 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1131 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1132 "Please adjust manually.\n",
1133 handle->md.device, strerror(errno));
1137 #endif /* IW_MODE_MONITOR */
1140 * Take this pcap out of the list of pcaps for which we
1141 * have to take the interface out of some mode.
1143 pcap_remove_from_pcaps_to_close(handle);
1146 if (handle->md.mondevice != NULL) {
1147 free(handle->md.mondevice);
1148 handle->md.mondevice = NULL;
1150 if (handle->md.device != NULL) {
1151 free(handle->md.device);
1152 handle->md.device = NULL;
1154 pcap_cleanup_live_common(handle);
1158 * Get a handle for a live capture from the given device. You can
1159 * pass NULL as device to get all packages (without link level
1160 * information of course). If you pass 1 as promisc the interface
1161 * will be set to promiscous mode (XXX: I think this usage should
1162 * be deprecated and functions be added to select that later allow
1163 * modification of that values -- Torsten).
1166 pcap_activate_linux(pcap_t *handle)
1171 device = handle->opt.source;
1173 handle->inject_op = pcap_inject_linux;
1174 handle->setfilter_op = pcap_setfilter_linux;
1175 handle->setdirection_op = pcap_setdirection_linux;
1176 handle->set_datalink_op = NULL; /* can't change data link type */
1177 handle->getnonblock_op = pcap_getnonblock_fd;
1178 handle->setnonblock_op = pcap_setnonblock_fd;
1179 handle->cleanup_op = pcap_cleanup_linux;
1180 handle->read_op = pcap_read_linux;
1181 handle->stats_op = pcap_stats_linux;
1184 * The "any" device is a special device which causes us not
1185 * to bind to a particular device and thus to look at all
1188 if (strcmp(device, "any") == 0) {
1189 if (handle->opt.promisc) {
1190 handle->opt.promisc = 0;
1191 /* Just a warning. */
1192 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1193 "Promiscuous mode not supported on the \"any\" device");
1194 status = PCAP_WARNING_PROMISC_NOTSUP;
1198 handle->md.device = strdup(device);
1199 if (handle->md.device == NULL) {
1200 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1201 pcap_strerror(errno) );
1206 * If we're in promiscuous mode, then we probably want
1207 * to see when the interface drops packets too, so get an
1208 * initial count from /proc/net/dev
1210 if (handle->opt.promisc)
1211 handle->md.proc_dropped = linux_if_drops(handle->md.device);
1214 * Current Linux kernels use the protocol family PF_PACKET to
1215 * allow direct access to all packets on the network while
1216 * older kernels had a special socket type SOCK_PACKET to
1217 * implement this feature.
1218 * While this old implementation is kind of obsolete we need
1219 * to be compatible with older kernels for a while so we are
1220 * trying both methods with the newer method preferred.
1222 status = activate_new(handle);
1225 * Fatal error with the new way; just fail.
1226 * status has the error return; if it's PCAP_ERROR,
1227 * handle->errbuf has been set appropriately.
1234 * Try to use memory-mapped access.
1236 switch (activate_mmap(handle, &status)) {
1240 * We succeeded. status has been
1241 * set to the status to return,
1242 * which might be 0, or might be
1243 * a PCAP_WARNING_ value.
1249 * Kernel doesn't support it - just continue
1250 * with non-memory-mapped access.
1256 * We failed to set up to use it, or the kernel
1257 * supports it, but we failed to enable it.
1258 * status has been set to the error status to
1259 * return and, if it's PCAP_ERROR, handle->errbuf
1260 * contains the error message.
1265 else if (status == 0) {
1266 /* Non-fatal error; try old way */
1267 if ((status = activate_old(handle)) != 1) {
1269 * Both methods to open the packet socket failed.
1270 * Tidy up and report our failure (handle->errbuf
1271 * is expected to be set by the functions above).
1278 * We set up the socket, but not with memory-mapped access.
1281 if (handle->opt.buffer_size != 0) {
1283 * Set the socket buffer size to the specified value.
1285 if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
1286 &handle->opt.buffer_size,
1287 sizeof(handle->opt.buffer_size)) == -1) {
1288 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1289 "SO_RCVBUF: %s", pcap_strerror(errno));
1290 status = PCAP_ERROR;
1295 /* Allocate the buffer */
1297 handle->buffer = malloc(handle->bufsize + handle->offset);
1298 if (!handle->buffer) {
1299 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1300 "malloc: %s", pcap_strerror(errno));
1301 status = PCAP_ERROR;
1306 * "handle->fd" is a socket, so "select()" and "poll()"
1307 * should work on it.
1309 handle->selectable_fd = handle->fd;
1314 pcap_cleanup_linux(handle);
1319 * Read at most max_packets from the capture stream and call the callback
1320 * for each of them. Returns the number of packets handled or -1 if an
1324 pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1327 * Currently, on Linux only one packet is delivered per read,
1330 return pcap_read_packet(handle, callback, user);
1334 * Read a packet from the socket calling the handler provided by
1335 * the user. Returns the number of packets received or -1 if an
1339 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
1343 #ifdef HAVE_PF_PACKET_SOCKETS
1344 struct sockaddr_ll from;
1345 struct sll_header *hdrp;
1347 struct sockaddr from;
1349 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1352 struct cmsghdr *cmsg;
1354 struct cmsghdr cmsg;
1355 char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
1357 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1359 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1360 int packet_len, caplen;
1361 struct pcap_pkthdr pcap_header;
1363 #ifdef HAVE_PF_PACKET_SOCKETS
1365 * If this is a cooked device, leave extra room for a
1366 * fake packet header.
1368 if (handle->md.cooked)
1369 offset = SLL_HDR_LEN;
1374 * This system doesn't have PF_PACKET sockets, so it doesn't
1375 * support cooked devices.
1381 * Receive a single packet from the kernel.
1382 * We ignore EINTR, as that might just be due to a signal
1383 * being delivered - if the signal should interrupt the
1384 * loop, the signal handler should call pcap_breakloop()
1385 * to set handle->break_loop (we ignore it on other
1386 * platforms as well).
1387 * We also ignore ENETDOWN, so that we can continue to
1388 * capture traffic if the interface goes down and comes
1389 * back up again; comments in the kernel indicate that
1390 * we'll just block waiting for packets if we try to
1391 * receive from a socket that delivered ENETDOWN, and,
1392 * if we're using a memory-mapped buffer, we won't even
1393 * get notified of "network down" events.
1395 bp = handle->buffer + handle->offset;
1397 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1398 msg.msg_name = &from;
1399 msg.msg_namelen = sizeof(from);
1402 msg.msg_control = &cmsg_buf;
1403 msg.msg_controllen = sizeof(cmsg_buf);
1406 iov.iov_len = handle->bufsize - offset;
1407 iov.iov_base = bp + offset;
1408 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1412 * Has "pcap_breakloop()" been called?
1414 if (handle->break_loop) {
1416 * Yes - clear the flag that indicates that it has,
1417 * and return PCAP_ERROR_BREAK as an indication that
1418 * we were told to break out of the loop.
1420 handle->break_loop = 0;
1421 return PCAP_ERROR_BREAK;
1424 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1425 packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
1426 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1427 fromlen = sizeof(from);
1428 packet_len = recvfrom(
1429 handle->fd, bp + offset,
1430 handle->bufsize - offset, MSG_TRUNC,
1431 (struct sockaddr *) &from, &fromlen);
1432 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1433 } while (packet_len == -1 && errno == EINTR);
1435 /* Check if an error occured */
1437 if (packet_len == -1) {
1441 return 0; /* no packet there */
1445 * The device on which we're capturing went away.
1447 * XXX - we should really return
1448 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1449 * etc. aren't defined to return that.
1451 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1452 "The interface went down");
1456 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1457 "recvfrom: %s", pcap_strerror(errno));
1462 #ifdef HAVE_PF_PACKET_SOCKETS
1463 if (!handle->md.sock_packet) {
1465 * Unfortunately, there is a window between socket() and
1466 * bind() where the kernel may queue packets from any
1467 * interface. If we're bound to a particular interface,
1468 * discard packets not from that interface.
1470 * (If socket filters are supported, we could do the
1471 * same thing we do when changing the filter; however,
1472 * that won't handle packet sockets without socket
1473 * filter support, and it's a bit more complicated.
1474 * It would save some instructions per packet, however.)
1476 if (handle->md.ifindex != -1 &&
1477 from.sll_ifindex != handle->md.ifindex)
1481 * Do checks based on packet direction.
1482 * We can only do this if we're using PF_PACKET; the
1483 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1484 * which lacks the relevant packet type information.
1486 if (from.sll_pkttype == PACKET_OUTGOING) {
1489 * If this is from the loopback device, reject it;
1490 * we'll see the packet as an incoming packet as well,
1491 * and we don't want to see it twice.
1493 if (from.sll_ifindex == handle->md.lo_ifindex)
1497 * If the user only wants incoming packets, reject it.
1499 if (handle->direction == PCAP_D_IN)
1504 * If the user only wants outgoing packets, reject it.
1506 if (handle->direction == PCAP_D_OUT)
1512 #ifdef HAVE_PF_PACKET_SOCKETS
1514 * If this is a cooked device, fill in the fake packet header.
1516 if (handle->md.cooked) {
1518 * Add the length of the fake header to the length
1519 * of packet data we read.
1521 packet_len += SLL_HDR_LEN;
1523 hdrp = (struct sll_header *)bp;
1524 hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
1525 hdrp->sll_hatype = htons(from.sll_hatype);
1526 hdrp->sll_halen = htons(from.sll_halen);
1527 memcpy(hdrp->sll_addr, from.sll_addr,
1528 (from.sll_halen > SLL_ADDRLEN) ?
1531 hdrp->sll_protocol = from.sll_protocol;
1534 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1535 if (handle->md.vlan_offset != -1) {
1536 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1537 struct tpacket_auxdata *aux;
1539 struct vlan_tag *tag;
1541 if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
1542 cmsg->cmsg_level != SOL_PACKET ||
1543 cmsg->cmsg_type != PACKET_AUXDATA)
1546 aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
1547 #if defined(TP_STATUS_VLAN_VALID)
1548 if ((aux->tp_vlan_tci == 0) && !(aux->tp_status & TP_STATUS_VLAN_VALID))
1550 if (aux->tp_vlan_tci == 0) /* this is ambigious but without the
1551 TP_STATUS_VLAN_VALID flag, there is
1552 nothing that we can do */
1556 len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
1557 if (len < (unsigned int) handle->md.vlan_offset)
1561 memmove(bp, bp + VLAN_TAG_LEN, handle->md.vlan_offset);
1563 tag = (struct vlan_tag *)(bp + handle->md.vlan_offset);
1564 tag->vlan_tpid = htons(ETH_P_8021Q);
1565 tag->vlan_tci = htons(aux->tp_vlan_tci);
1567 packet_len += VLAN_TAG_LEN;
1570 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1571 #endif /* HAVE_PF_PACKET_SOCKETS */
1574 * XXX: According to the kernel source we should get the real
1575 * packet len if calling recvfrom with MSG_TRUNC set. It does
1576 * not seem to work here :(, but it is supported by this code
1578 * To be honest the code RELIES on that feature so this is really
1579 * broken with 2.2.x kernels.
1580 * I spend a day to figure out what's going on and I found out
1581 * that the following is happening:
1583 * The packet comes from a random interface and the packet_rcv
1584 * hook is called with a clone of the packet. That code inserts
1585 * the packet into the receive queue of the packet socket.
1586 * If a filter is attached to that socket that filter is run
1587 * first - and there lies the problem. The default filter always
1588 * cuts the packet at the snaplen:
1593 * So the packet filter cuts down the packet. The recvfrom call
1594 * says "hey, it's only 68 bytes, it fits into the buffer" with
1595 * the result that we don't get the real packet length. This
1596 * is valid at least until kernel 2.2.17pre6.
1598 * We currently handle this by making a copy of the filter
1599 * program, fixing all "ret" instructions with non-zero
1600 * operands to have an operand of 65535 so that the filter
1601 * doesn't truncate the packet, and supplying that modified
1602 * filter to the kernel.
1605 caplen = packet_len;
1606 if (caplen > handle->snapshot)
1607 caplen = handle->snapshot;
1609 /* Run the packet filter if not using kernel filter */
1610 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
1611 if (bpf_filter(handle->fcode.bf_insns, bp,
1612 packet_len, caplen) == 0)
1614 /* rejected by filter */
1619 /* Fill in our own header data */
1621 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
1622 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1623 "SIOCGSTAMP: %s", pcap_strerror(errno));
1626 pcap_header.caplen = caplen;
1627 pcap_header.len = packet_len;
1632 * Arguably, we should count them before we check the filter,
1633 * as on many other platforms "ps_recv" counts packets
1634 * handed to the filter rather than packets that passed
1635 * the filter, but if filtering is done in the kernel, we
1636 * can't get a count of packets that passed the filter,
1637 * and that would mean the meaning of "ps_recv" wouldn't
1638 * be the same on all Linux systems.
1640 * XXX - it's not the same on all systems in any case;
1641 * ideally, we should have a "get the statistics" call
1642 * that supplies more counts and indicates which of them
1643 * it supplies, so that we supply a count of packets
1644 * handed to the filter only on platforms where that
1645 * information is available.
1647 * We count them here even if we can get the packet count
1648 * from the kernel, as we can only determine at run time
1649 * whether we'll be able to get it from the kernel (if
1650 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1651 * the kernel, but if it is defined, the library might
1652 * have been built with a 2.4 or later kernel, but we
1653 * might be running on a 2.2[.x] kernel without Alexey
1654 * Kuznetzov's turbopacket patches, and thus the kernel
1655 * might not be able to supply those statistics). We
1656 * could, I guess, try, when opening the socket, to get
1657 * the statistics, and if we can not increment the count
1658 * here, but it's not clear that always incrementing
1659 * the count is more expensive than always testing a flag
1662 * We keep the count in "md.packets_read", and use that for
1663 * "ps_recv" if we can't get the statistics from the kernel.
1664 * We do that because, if we *can* get the statistics from
1665 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1666 * as running counts, as reading the statistics from the
1667 * kernel resets the kernel statistics, and if we directly
1668 * increment "md.stat.ps_recv" here, that means it will
1669 * count packets *twice* on systems where we can get kernel
1670 * statistics - once here, and once in pcap_stats_linux().
1672 handle->md.packets_read++;
1674 /* Call the user supplied callback function */
1675 callback(userdata, &pcap_header, bp);
1681 pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
1685 #ifdef HAVE_PF_PACKET_SOCKETS
1686 if (!handle->md.sock_packet) {
1687 /* PF_PACKET socket */
1688 if (handle->md.ifindex == -1) {
1690 * We don't support sending on the "any" device.
1692 strlcpy(handle->errbuf,
1693 "Sending packets isn't supported on the \"any\" device",
1698 if (handle->md.cooked) {
1700 * We don't support sending on the "any" device.
1702 * XXX - how do you send on a bound cooked-mode
1704 * Is a "sendto()" required there?
1706 strlcpy(handle->errbuf,
1707 "Sending packets isn't supported in cooked mode",
1714 ret = send(handle->fd, buf, size, 0);
1716 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1717 pcap_strerror(errno));
1724 * Get the statistics for the given packet capture handle.
1725 * Reports the number of dropped packets iff the kernel supports
1726 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1727 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1728 * patches); otherwise, that information isn't available, and we lie
1729 * and report 0 as the count of dropped packets.
1732 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
1734 #ifdef HAVE_TPACKET_STATS
1735 struct tpacket_stats kstats;
1736 socklen_t len = sizeof (struct tpacket_stats);
1739 long if_dropped = 0;
1742 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1744 if (handle->opt.promisc)
1746 if_dropped = handle->md.proc_dropped;
1747 handle->md.proc_dropped = linux_if_drops(handle->md.device);
1748 handle->md.stat.ps_ifdrop += (handle->md.proc_dropped - if_dropped);
1751 #ifdef HAVE_TPACKET_STATS
1753 * Try to get the packet counts from the kernel.
1755 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
1756 &kstats, &len) > -1) {
1758 * On systems where the PACKET_STATISTICS "getsockopt()"
1759 * argument is supported on PF_PACKET sockets:
1761 * "ps_recv" counts only packets that *passed* the
1762 * filter, not packets that didn't pass the filter.
1763 * This includes packets later dropped because we
1764 * ran out of buffer space.
1766 * "ps_drop" counts packets dropped because we ran
1767 * out of buffer space. It doesn't count packets
1768 * dropped by the interface driver. It counts only
1769 * packets that passed the filter.
1771 * See above for ps_ifdrop.
1773 * Both statistics include packets not yet read from
1774 * the kernel by libpcap, and thus not yet seen by
1777 * In "linux/net/packet/af_packet.c", at least in the
1778 * 2.4.9 kernel, "tp_packets" is incremented for every
1779 * packet that passes the packet filter *and* is
1780 * successfully queued on the socket; "tp_drops" is
1781 * incremented for every packet dropped because there's
1782 * not enough free space in the socket buffer.
1784 * When the statistics are returned for a PACKET_STATISTICS
1785 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1786 * so that "tp_packets" counts all packets handed to
1787 * the PF_PACKET socket, including packets dropped because
1788 * there wasn't room on the socket buffer - but not
1789 * including packets that didn't pass the filter.
1791 * In the BSD BPF, the count of received packets is
1792 * incremented for every packet handed to BPF, regardless
1793 * of whether it passed the filter.
1795 * We can't make "pcap_stats()" work the same on both
1796 * platforms, but the best approximation is to return
1797 * "tp_packets" as the count of packets and "tp_drops"
1798 * as the count of drops.
1800 * Keep a running total because each call to
1801 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1802 * resets the counters to zero.
1804 handle->md.stat.ps_recv += kstats.tp_packets;
1805 handle->md.stat.ps_drop += kstats.tp_drops;
1806 *stats = handle->md.stat;
1812 * If the error was EOPNOTSUPP, fall through, so that
1813 * if you build the library on a system with
1814 * "struct tpacket_stats" and run it on a system
1815 * that doesn't, it works as it does if the library
1816 * is built on a system without "struct tpacket_stats".
1818 if (errno != EOPNOTSUPP) {
1819 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1820 "pcap_stats: %s", pcap_strerror(errno));
1826 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1827 * is not supported on PF_PACKET sockets:
1829 * "ps_recv" counts only packets that *passed* the filter,
1830 * not packets that didn't pass the filter. It does not
1831 * count packets dropped because we ran out of buffer
1834 * "ps_drop" is not supported.
1836 * "ps_ifdrop" is supported. It will return the number
1837 * of drops the interface reports in /proc/net/dev,
1838 * if that is available.
1840 * "ps_recv" doesn't include packets not yet read from
1841 * the kernel by libpcap.
1843 * We maintain the count of packets processed by libpcap in
1844 * "md.packets_read", for reasons described in the comment
1845 * at the end of pcap_read_packet(). We have no idea how many
1846 * packets were dropped by the kernel buffers -- but we know
1847 * how many the interface dropped, so we can return that.
1850 stats->ps_recv = handle->md.packets_read;
1852 stats->ps_ifdrop = handle->md.stat.ps_ifdrop;
1857 * Get from "/sys/class/net" all interfaces listed there; if they're
1858 * already in the list of interfaces we have, that won't add another
1859 * instance, but if they're not, that'll add them.
1861 * We don't bother getting any addresses for them; it appears you can't
1862 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1863 * although some other types of addresses can be fetched with SIOCGIFADDR,
1864 * we don't bother with them for now.
1866 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1867 * the list of interfaces as is, and return 0, so that we can try
1868 * scanning /proc/net/dev.
1871 scan_sys_class_net(pcap_if_t **devlistp, char *errbuf)
1873 DIR *sys_class_net_d;
1876 char subsystem_path[PATH_MAX+1];
1879 char name[512]; /* XXX - pick a size */
1881 struct ifreq ifrflags;
1884 sys_class_net_d = opendir("/sys/class/net");
1885 if (sys_class_net_d == NULL) {
1887 * Don't fail if it doesn't exist at all.
1889 if (errno == ENOENT)
1893 * Fail if we got some other error.
1895 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1896 "Can't open /sys/class/net: %s", pcap_strerror(errno));
1901 * Create a socket from which to fetch interface information.
1903 fd = socket(AF_INET, SOCK_DGRAM, 0);
1905 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1906 "socket: %s", pcap_strerror(errno));
1907 (void)closedir(sys_class_net_d);
1913 ent = readdir(sys_class_net_d);
1916 * Error or EOF; if errno != 0, it's an error.
1922 * Ignore "." and "..".
1924 if (strcmp(ent->d_name, ".") == 0 ||
1925 strcmp(ent->d_name, "..") == 0)
1929 * Ignore plain files; they do not have subdirectories
1930 * and thus have no attributes.
1932 if (ent->d_type == DT_REG)
1936 * Is there an "ifindex" file under that name?
1937 * (We don't care whether it's a directory or
1938 * a symlink; older kernels have directories
1939 * for devices, newer kernels have symlinks to
1942 snprintf(subsystem_path, sizeof subsystem_path,
1943 "/sys/class/net/%s/ifindex", ent->d_name);
1944 if (lstat(subsystem_path, &statb) != 0) {
1946 * Stat failed. Either there was an error
1947 * other than ENOENT, and we don't know if
1948 * this is an interface, or it's ENOENT,
1949 * and either some part of "/sys/class/net/{if}"
1950 * disappeared, in which case it probably means
1951 * the interface disappeared, or there's no
1952 * "ifindex" file, which means it's not a
1953 * network interface.
1959 * Get the interface name.
1961 p = &ent->d_name[0];
1963 while (*p != '\0' && isascii(*p) && !isspace(*p)) {
1966 * This could be the separator between a
1967 * name and an alias number, or it could be
1968 * the separator between a name with no
1969 * alias number and the next field.
1971 * If there's a colon after digits, it
1972 * separates the name and the alias number,
1973 * otherwise it separates the name and the
1977 while (isascii(*p) && isdigit(*p))
1981 * That was the next field,
1982 * not the alias number.
1993 * Get the flags for this interface, and skip it if
1996 strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
1997 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
1998 if (errno == ENXIO || errno == ENODEV)
2000 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2001 "SIOCGIFFLAGS: %.*s: %s",
2002 (int)sizeof(ifrflags.ifr_name),
2004 pcap_strerror(errno));
2008 if (!(ifrflags.ifr_flags & IFF_UP))
2012 * Add an entry for this interface, with no addresses.
2014 if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2025 * Well, we didn't fail for any other reason; did we
2026 * fail due to an error reading the directory?
2029 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2030 "Error reading /sys/class/net: %s",
2031 pcap_strerror(errno));
2037 (void)closedir(sys_class_net_d);
2042 * Get from "/proc/net/dev" all interfaces listed there; if they're
2043 * already in the list of interfaces we have, that won't add another
2044 * instance, but if they're not, that'll add them.
2046 * See comments from scan_sys_class_net().
2049 scan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
2056 char name[512]; /* XXX - pick a size */
2058 struct ifreq ifrflags;
2061 proc_net_f = fopen("/proc/net/dev", "r");
2062 if (proc_net_f == NULL) {
2064 * Don't fail if it doesn't exist at all.
2066 if (errno == ENOENT)
2070 * Fail if we got some other error.
2072 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2073 "Can't open /proc/net/dev: %s", pcap_strerror(errno));
2078 * Create a socket from which to fetch interface information.
2080 fd = socket(AF_INET, SOCK_DGRAM, 0);
2082 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2083 "socket: %s", pcap_strerror(errno));
2084 (void)fclose(proc_net_f);
2089 fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
2091 * Skip the first two lines - they're headers.
2099 * Skip leading white space.
2101 while (*p != '\0' && isascii(*p) && isspace(*p))
2103 if (*p == '\0' || *p == '\n')
2104 continue; /* blank line */
2107 * Get the interface name.
2110 while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2113 * This could be the separator between a
2114 * name and an alias number, or it could be
2115 * the separator between a name with no
2116 * alias number and the next field.
2118 * If there's a colon after digits, it
2119 * separates the name and the alias number,
2120 * otherwise it separates the name and the
2124 while (isascii(*p) && isdigit(*p))
2128 * That was the next field,
2129 * not the alias number.
2140 * Get the flags for this interface, and skip it if
2143 strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2144 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2147 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2148 "SIOCGIFFLAGS: %.*s: %s",
2149 (int)sizeof(ifrflags.ifr_name),
2151 pcap_strerror(errno));
2155 if (!(ifrflags.ifr_flags & IFF_UP))
2159 * Add an entry for this interface, with no addresses.
2161 if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2172 * Well, we didn't fail for any other reason; did we
2173 * fail due to an error reading the file?
2175 if (ferror(proc_net_f)) {
2176 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2177 "Error reading /proc/net/dev: %s",
2178 pcap_strerror(errno));
2184 (void)fclose(proc_net_f);
2189 * Description string for the "any" device.
2191 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
2194 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2199 * Read "/sys/class/net", and add to the list of interfaces all
2200 * interfaces listed there that we don't already have, because,
2201 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2202 * and even getifaddrs() won't return information about
2203 * interfaces with no addresses, so you need to read "/sys/class/net"
2204 * to get the names of the rest of the interfaces.
2206 ret = scan_sys_class_net(alldevsp, errbuf);
2208 return (-1); /* failed */
2211 * No /sys/class/net; try reading /proc/net/dev instead.
2213 if (scan_proc_net_dev(alldevsp, errbuf) == -1)
2218 * Add the "any" device.
2220 if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
2227 * Attach the given BPF code to the packet capture device.
2230 pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
2233 #ifdef SO_ATTACH_FILTER
2234 struct sock_fprog fcode;
2235 int can_filter_in_kernel;
2242 strncpy(handle->errbuf, "setfilter: No filter specified",
2247 /* Make our private copy of the filter */
2249 if (install_bpf_program(handle, filter) < 0)
2250 /* install_bpf_program() filled in errbuf */
2254 * Run user level packet filter by default. Will be overriden if
2255 * installing a kernel filter succeeds.
2257 handle->md.use_bpf = 0;
2259 /* Install kernel level filter if possible */
2261 #ifdef SO_ATTACH_FILTER
2263 if (handle->fcode.bf_len > USHRT_MAX) {
2265 * fcode.len is an unsigned short for current kernel.
2266 * I have yet to see BPF-Code with that much
2267 * instructions but still it is possible. So for the
2268 * sake of correctness I added this check.
2270 fprintf(stderr, "Warning: Filter too complex for kernel\n");
2272 fcode.filter = NULL;
2273 can_filter_in_kernel = 0;
2275 #endif /* USHRT_MAX */
2278 * Oh joy, the Linux kernel uses struct sock_fprog instead
2279 * of struct bpf_program and of course the length field is
2280 * of different size. Pointed out by Sebastian
2282 * Oh, and we also need to fix it up so that all "ret"
2283 * instructions with non-zero operands have 65535 as the
2284 * operand if we're not capturing in memory-mapped modee,
2285 * and so that, if we're in cooked mode, all memory-reference
2286 * instructions use special magic offsets in references to
2287 * the link-layer header and assume that the link-layer
2288 * payload begins at 0; "fix_program()" will do that.
2290 switch (fix_program(handle, &fcode, is_mmapped)) {
2295 * Fatal error; just quit.
2296 * (The "default" case shouldn't happen; we
2297 * return -1 for that reason.)
2303 * The program performed checks that we can't make
2304 * work in the kernel.
2306 can_filter_in_kernel = 0;
2311 * We have a filter that'll work in the kernel.
2313 can_filter_in_kernel = 1;
2319 * NOTE: at this point, we've set both the "len" and "filter"
2320 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2321 * those are the only members of the "sock_fprog" structure,
2322 * so we initialize every member of that structure.
2324 * If there is anything in "fcode" that is not initialized,
2325 * it is either a field added in a later kernel, or it's
2328 * If a new field is added, this code needs to be updated
2329 * to set it correctly.
2331 * If there are no other fields, then:
2333 * if the Linux kernel looks at the padding, it's
2336 * if the Linux kernel doesn't look at the padding,
2337 * then if some tool complains that we're passing
2338 * uninitialized data to the kernel, then the tool
2339 * is buggy and needs to understand that it's just
2342 if (can_filter_in_kernel) {
2343 if ((err = set_kernel_filter(handle, &fcode)) == 0)
2345 /* Installation succeded - using kernel filter. */
2346 handle->md.use_bpf = 1;
2348 else if (err == -1) /* Non-fatal error */
2351 * Print a warning if we weren't able to install
2352 * the filter for a reason other than "this kernel
2353 * isn't configured to support socket filters.
2355 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
2357 "Warning: Kernel filter failed: %s\n",
2358 pcap_strerror(errno));
2364 * If we're not using the kernel filter, get rid of any kernel
2365 * filter that might've been there before, e.g. because the
2366 * previous filter could work in the kernel, or because some other
2367 * code attached a filter to the socket by some means other than
2368 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2369 * filter out packets that would pass the new userland filter.
2371 if (!handle->md.use_bpf)
2372 reset_kernel_filter(handle);
2375 * Free up the copy of the filter that was made by "fix_program()".
2377 if (fcode.filter != NULL)
2383 #endif /* SO_ATTACH_FILTER */
2389 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
2391 return pcap_setfilter_linux_common(handle, filter, 0);
2396 * Set direction flag: Which packets do we accept on a forwarding
2397 * single device? IN, OUT or both?
2400 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
2402 #ifdef HAVE_PF_PACKET_SOCKETS
2403 if (!handle->md.sock_packet) {
2404 handle->direction = d;
2409 * We're not using PF_PACKET sockets, so we can't determine
2410 * the direction of the packet.
2412 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2413 "Setting direction is not supported on SOCK_PACKET sockets");
2417 #ifdef HAVE_PF_PACKET_SOCKETS
2419 * Map the PACKET_ value to a LINUX_SLL_ value; we
2420 * want the same numerical value to be used in
2421 * the link-layer header even if the numerical values
2422 * for the PACKET_ #defines change, so that programs
2423 * that look at the packet type field will always be
2424 * able to handle DLT_LINUX_SLL captures.
2427 map_packet_type_to_sll_type(short int sll_pkttype)
2429 switch (sll_pkttype) {
2432 return htons(LINUX_SLL_HOST);
2434 case PACKET_BROADCAST:
2435 return htons(LINUX_SLL_BROADCAST);
2437 case PACKET_MULTICAST:
2438 return htons(LINUX_SLL_MULTICAST);
2440 case PACKET_OTHERHOST:
2441 return htons(LINUX_SLL_OTHERHOST);
2443 case PACKET_OUTGOING:
2444 return htons(LINUX_SLL_OUTGOING);
2453 * Linux uses the ARP hardware type to identify the type of an
2454 * interface. pcap uses the DLT_xxx constants for this. This
2455 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2456 * constant, as arguments, and sets "handle->linktype" to the
2457 * appropriate DLT_XXX constant and sets "handle->offset" to
2458 * the appropriate value (to make "handle->offset" plus link-layer
2459 * header length be a multiple of 4, so that the link-layer payload
2460 * will be aligned on a 4-byte boundary when capturing packets).
2461 * (If the offset isn't set here, it'll be 0; add code as appropriate
2462 * for cases where it shouldn't be 0.)
2464 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2465 * in cooked mode; otherwise, we can't use cooked mode, so we have
2466 * to pick some type that works in raw mode, or fail.
2468 * Sets the link type to -1 if unable to map the type.
2470 static void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
2476 * This is (presumably) a real Ethernet capture; give it a
2477 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2478 * that an application can let you choose it, in case you're
2479 * capturing DOCSIS traffic that a Cisco Cable Modem
2480 * Termination System is putting out onto an Ethernet (it
2481 * doesn't put an Ethernet header onto the wire, it puts raw
2482 * DOCSIS frames out on the wire inside the low-level
2483 * Ethernet framing).
2485 * XXX - are there any sorts of "fake Ethernet" that have
2486 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2487 * a Cisco CMTS won't put traffic onto it or get traffic
2488 * bridged onto it? ISDN is handled in "activate_new()",
2489 * as we fall back on cooked mode there; are there any
2492 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2494 * If that fails, just leave the list empty.
2496 if (handle->dlt_list != NULL) {
2497 handle->dlt_list[0] = DLT_EN10MB;
2498 handle->dlt_list[1] = DLT_DOCSIS;
2499 handle->dlt_count = 2;
2503 case ARPHRD_METRICOM:
2504 case ARPHRD_LOOPBACK:
2505 handle->linktype = DLT_EN10MB;
2510 handle->linktype = DLT_EN3MB;
2514 handle->linktype = DLT_AX25_KISS;
2518 handle->linktype = DLT_PRONET;
2522 handle->linktype = DLT_CHAOS;
2525 #define ARPHRD_CAN 280
2528 handle->linktype = DLT_CAN_SOCKETCAN;
2531 #ifndef ARPHRD_IEEE802_TR
2532 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2534 case ARPHRD_IEEE802_TR:
2535 case ARPHRD_IEEE802:
2536 handle->linktype = DLT_IEEE802;
2541 handle->linktype = DLT_ARCNET_LINUX;
2544 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2545 #define ARPHRD_FDDI 774
2548 handle->linktype = DLT_FDDI;
2552 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2553 #define ARPHRD_ATM 19
2557 * The Classical IP implementation in ATM for Linux
2558 * supports both what RFC 1483 calls "LLC Encapsulation",
2559 * in which each packet has an LLC header, possibly
2560 * with a SNAP header as well, prepended to it, and
2561 * what RFC 1483 calls "VC Based Multiplexing", in which
2562 * different virtual circuits carry different network
2563 * layer protocols, and no header is prepended to packets.
2565 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2566 * you can't use the ARPHRD_ type to find out whether
2567 * captured packets will have an LLC header, and,
2568 * while there's a socket ioctl to *set* the encapsulation
2569 * type, there's no ioctl to *get* the encapsulation type.
2573 * programs that dissect Linux Classical IP frames
2574 * would have to check for an LLC header and,
2575 * depending on whether they see one or not, dissect
2576 * the frame as LLC-encapsulated or as raw IP (I
2577 * don't know whether there's any traffic other than
2578 * IP that would show up on the socket, or whether
2579 * there's any support for IPv6 in the Linux
2580 * Classical IP code);
2582 * filter expressions would have to compile into
2583 * code that checks for an LLC header and does
2586 * Both of those are a nuisance - and, at least on systems
2587 * that support PF_PACKET sockets, we don't have to put
2588 * up with those nuisances; instead, we can just capture
2589 * in cooked mode. That's what we'll do, if we can.
2590 * Otherwise, we'll just fail.
2593 handle->linktype = DLT_LINUX_SLL;
2595 handle->linktype = -1;
2598 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2599 #define ARPHRD_IEEE80211 801
2601 case ARPHRD_IEEE80211:
2602 handle->linktype = DLT_IEEE802_11;
2605 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2606 #define ARPHRD_IEEE80211_PRISM 802
2608 case ARPHRD_IEEE80211_PRISM:
2609 handle->linktype = DLT_PRISM_HEADER;
2612 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2613 #define ARPHRD_IEEE80211_RADIOTAP 803
2615 case ARPHRD_IEEE80211_RADIOTAP:
2616 handle->linktype = DLT_IEEE802_11_RADIO;
2621 * Some PPP code in the kernel supplies no link-layer
2622 * header whatsoever to PF_PACKET sockets; other PPP
2623 * code supplies PPP link-layer headers ("syncppp.c");
2624 * some PPP code might supply random link-layer
2625 * headers (PPP over ISDN - there's code in Ethereal,
2626 * for example, to cope with PPP-over-ISDN captures
2627 * with which the Ethereal developers have had to cope,
2628 * heuristically trying to determine which of the
2629 * oddball link-layer headers particular packets have).
2631 * As such, we just punt, and run all PPP interfaces
2632 * in cooked mode, if we can; otherwise, we just treat
2633 * it as DLT_RAW, for now - if somebody needs to capture,
2634 * on a 2.0[.x] kernel, on PPP devices that supply a
2635 * link-layer header, they'll have to add code here to
2636 * map to the appropriate DLT_ type (possibly adding a
2637 * new DLT_ type, if necessary).
2640 handle->linktype = DLT_LINUX_SLL;
2643 * XXX - handle ISDN types here? We can't fall
2644 * back on cooked sockets, so we'd have to
2645 * figure out from the device name what type of
2646 * link-layer encapsulation it's using, and map
2647 * that to an appropriate DLT_ value, meaning
2648 * we'd map "isdnN" devices to DLT_RAW (they
2649 * supply raw IP packets with no link-layer
2650 * header) and "isdY" devices to a new DLT_I4L_IP
2651 * type that has only an Ethernet packet type as
2652 * a link-layer header.
2654 * But sometimes we seem to get random crap
2655 * in the link-layer header when capturing on
2658 handle->linktype = DLT_RAW;
2662 #ifndef ARPHRD_CISCO
2663 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2666 handle->linktype = DLT_C_HDLC;
2669 /* Not sure if this is correct for all tunnels, but it
2673 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2681 #ifndef ARPHRD_RAWHDLC
2682 #define ARPHRD_RAWHDLC 518
2684 case ARPHRD_RAWHDLC:
2686 #define ARPHRD_DLCI 15
2690 * XXX - should some of those be mapped to DLT_LINUX_SLL
2691 * instead? Should we just map all of them to DLT_LINUX_SLL?
2693 handle->linktype = DLT_RAW;
2697 #define ARPHRD_FRAD 770
2700 handle->linktype = DLT_FRELAY;
2703 case ARPHRD_LOCALTLK:
2704 handle->linktype = DLT_LTALK;
2708 #define ARPHRD_FCPP 784
2712 #define ARPHRD_FCAL 785
2716 #define ARPHRD_FCPL 786
2719 #ifndef ARPHRD_FCFABRIC
2720 #define ARPHRD_FCFABRIC 787
2722 case ARPHRD_FCFABRIC:
2724 * We assume that those all mean RFC 2625 IP-over-
2725 * Fibre Channel, with the RFC 2625 header at
2726 * the beginning of the packet.
2728 handle->linktype = DLT_IP_OVER_FC;
2732 #define ARPHRD_IRDA 783
2735 /* Don't expect IP packet out of this interfaces... */
2736 handle->linktype = DLT_LINUX_IRDA;
2737 /* We need to save packet direction for IrDA decoding,
2738 * so let's use "Linux-cooked" mode. Jean II */
2739 //handle->md.cooked = 1;
2742 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2743 * is needed, please report it to <daniele@orlandi.com> */
2745 #define ARPHRD_LAPD 8445
2748 /* Don't expect IP packet out of this interfaces... */
2749 handle->linktype = DLT_LINUX_LAPD;
2753 #define ARPHRD_NONE 0xFFFE
2757 * No link-layer header; packets are just IP
2758 * packets, so use DLT_RAW.
2760 handle->linktype = DLT_RAW;
2763 #ifndef ARPHRD_IEEE802154
2764 #define ARPHRD_IEEE802154 804
2766 case ARPHRD_IEEE802154:
2767 handle->linktype = DLT_IEEE802_15_4_NOFCS;
2771 handle->linktype = -1;
2776 /* ===== Functions to interface to the newer kernels ================== */
2779 * Try to open a packet socket using the new kernel PF_PACKET interface.
2780 * Returns 1 on success, 0 on an error that means the new interface isn't
2781 * present (so the old SOCK_PACKET interface should be tried), and a
2782 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2783 * work either (so it shouldn't be tried).
2786 activate_new(pcap_t *handle)
2788 #ifdef HAVE_PF_PACKET_SOCKETS
2789 const char *device = handle->opt.source;
2790 int is_any_device = (strcmp(device, "any") == 0);
2791 int sock_fd = -1, arptype;
2792 #ifdef HAVE_PACKET_AUXDATA
2796 struct packet_mreq mr;
2799 * Open a socket with protocol family packet. If the
2800 * "any" device was specified, we open a SOCK_DGRAM
2801 * socket for the cooked interface, otherwise we first
2802 * try a SOCK_RAW socket for the raw interface.
2804 sock_fd = is_any_device ?
2805 socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
2806 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
2808 if (sock_fd == -1) {
2809 if (errno == EINVAL || errno == EAFNOSUPPORT) {
2811 * We don't support PF_PACKET/SOCK_whatever
2812 * sockets; try the old mechanism.
2817 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
2818 pcap_strerror(errno) );
2819 if (errno == EPERM || errno == EACCES) {
2821 * You don't have permission to open the
2824 return PCAP_ERROR_PERM_DENIED;
2833 /* It seems the kernel supports the new interface. */
2834 handle->md.sock_packet = 0;
2837 * Get the interface index of the loopback device.
2838 * If the attempt fails, don't fail, just set the
2839 * "md.lo_ifindex" to -1.
2841 * XXX - can there be more than one device that loops
2842 * packets back, i.e. devices other than "lo"? If so,
2843 * we'd need to find them all, and have an array of
2844 * indices for them, and check all of them in
2845 * "pcap_read_packet()".
2847 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
2850 * Default value for offset to align link-layer payload
2851 * on a 4-byte boundary.
2856 * What kind of frames do we have to deal with? Fall back
2857 * to cooked mode if we have an unknown interface type
2858 * or a type we know doesn't work well in raw mode.
2860 if (!is_any_device) {
2861 /* Assume for now we don't need cooked mode. */
2862 handle->md.cooked = 0;
2864 if (handle->opt.rfmon) {
2866 * We were asked to turn on monitor mode.
2867 * Do so before we get the link-layer type,
2868 * because entering monitor mode could change
2869 * the link-layer type.
2871 err = enter_rfmon_mode(handle, sock_fd, device);
2879 * Nothing worked for turning monitor mode
2883 return PCAP_ERROR_RFMON_NOTSUP;
2887 * Either monitor mode has been turned on for
2888 * the device, or we've been given a different
2889 * device to open for monitor mode. If we've
2890 * been given a different device, use it.
2892 if (handle->md.mondevice != NULL)
2893 device = handle->md.mondevice;
2895 arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
2900 map_arphrd_to_dlt(handle, arptype, 1);
2901 if (handle->linktype == -1 ||
2902 handle->linktype == DLT_LINUX_SLL ||
2903 handle->linktype == DLT_LINUX_IRDA ||
2904 handle->linktype == DLT_LINUX_LAPD ||
2905 (handle->linktype == DLT_EN10MB &&
2906 (strncmp("isdn", device, 4) == 0 ||
2907 strncmp("isdY", device, 4) == 0))) {
2909 * Unknown interface type (-1), or a
2910 * device we explicitly chose to run
2911 * in cooked mode (e.g., PPP devices),
2912 * or an ISDN device (whose link-layer
2913 * type we can only determine by using
2914 * APIs that may be different on different
2915 * kernels) - reopen in cooked mode.
2917 if (close(sock_fd) == -1) {
2918 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2919 "close: %s", pcap_strerror(errno));
2922 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
2924 if (sock_fd == -1) {
2925 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2926 "socket: %s", pcap_strerror(errno));
2927 if (errno == EPERM || errno == EACCES) {
2929 * You don't have permission to
2932 return PCAP_ERROR_PERM_DENIED;
2940 handle->md.cooked = 1;
2943 * Get rid of any link-layer type list
2944 * we allocated - this only supports cooked
2947 if (handle->dlt_list != NULL) {
2948 free(handle->dlt_list);
2949 handle->dlt_list = NULL;
2950 handle->dlt_count = 0;
2953 if (handle->linktype == -1) {
2955 * Warn that we're falling back on
2956 * cooked mode; we may want to
2957 * update "map_arphrd_to_dlt()"
2958 * to handle the new type.
2960 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2962 "supported by libpcap - "
2963 "falling back to cooked "
2969 * IrDA capture is not a real "cooked" capture,
2970 * it's IrLAP frames, not IP packets. The
2971 * same applies to LAPD capture.
2973 if (handle->linktype != DLT_LINUX_IRDA &&
2974 handle->linktype != DLT_LINUX_LAPD)
2975 handle->linktype = DLT_LINUX_SLL;
2978 handle->md.ifindex = iface_get_id(sock_fd, device,
2980 if (handle->md.ifindex == -1) {
2985 if ((err = iface_bind(sock_fd, handle->md.ifindex,
2986 handle->errbuf)) != 1) {
2991 return 0; /* try old mechanism */
2997 if (handle->opt.rfmon) {
2999 * It doesn't support monitor mode.
3001 return PCAP_ERROR_RFMON_NOTSUP;
3005 * It uses cooked mode.
3007 handle->md.cooked = 1;
3008 handle->linktype = DLT_LINUX_SLL;
3011 * We're not bound to a device.
3012 * For now, we're using this as an indication
3013 * that we can't transmit; stop doing that only
3014 * if we figure out how to transmit in cooked
3017 handle->md.ifindex = -1;
3021 * Select promiscuous mode on if "promisc" is set.
3023 * Do not turn allmulti mode on if we don't select
3024 * promiscuous mode - on some devices (e.g., Orinoco
3025 * wireless interfaces), allmulti mode isn't supported
3026 * and the driver implements it by turning promiscuous
3027 * mode on, and that screws up the operation of the
3028 * card as a normal networking interface, and on no
3029 * other platform I know of does starting a non-
3030 * promiscuous capture affect which multicast packets
3031 * are received by the interface.
3035 * Hmm, how can we set promiscuous mode on all interfaces?
3036 * I am not sure if that is possible at all. For now, we
3037 * silently ignore attempts to turn promiscuous mode on
3038 * for the "any" device (so you don't have to explicitly
3039 * disable it in programs such as tcpdump).
3042 if (!is_any_device && handle->opt.promisc) {
3043 memset(&mr, 0, sizeof(mr));
3044 mr.mr_ifindex = handle->md.ifindex;
3045 mr.mr_type = PACKET_MR_PROMISC;
3046 if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
3047 &mr, sizeof(mr)) == -1) {
3048 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3049 "setsockopt: %s", pcap_strerror(errno));
3055 /* Enable auxillary data if supported and reserve room for
3056 * reconstructing VLAN headers. */
3057 #ifdef HAVE_PACKET_AUXDATA
3059 if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
3060 sizeof(val)) == -1 && errno != ENOPROTOOPT) {
3061 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3062 "setsockopt: %s", pcap_strerror(errno));
3066 handle->offset += VLAN_TAG_LEN;
3067 #endif /* HAVE_PACKET_AUXDATA */
3070 * This is a 2.2[.x] or later kernel (we know that
3071 * because we're not using a SOCK_PACKET socket -
3072 * PF_PACKET is supported only in 2.2 and later
3075 * We can safely pass "recvfrom()" a byte count
3076 * based on the snapshot length.
3078 * If we're in cooked mode, make the snapshot length
3079 * large enough to hold a "cooked mode" header plus
3080 * 1 byte of packet data (so we don't pass a byte
3081 * count of 0 to "recvfrom()").
3083 if (handle->md.cooked) {
3084 if (handle->snapshot < SLL_HDR_LEN + 1)
3085 handle->snapshot = SLL_HDR_LEN + 1;
3087 handle->bufsize = handle->snapshot;
3090 * Set the offset at which to insert VLAN tags.
3092 switch (handle->linktype) {
3095 handle->md.vlan_offset = 2 * ETH_ALEN;
3099 handle->md.vlan_offset = 14;
3103 handle->md.vlan_offset = -1; /* unknown */
3107 /* Save the socket FD in the pcap structure */
3108 handle->fd = sock_fd;
3113 "New packet capturing interface not supported by build "
3114 "environment", PCAP_ERRBUF_SIZE);
3119 #ifdef HAVE_PACKET_RING
3121 * Attempt to activate with memory-mapped access.
3123 * On success, returns 1, and sets *status to 0 if there are no warnings
3124 * or to a PCAP_WARNING_ code if there is a warning.
3126 * On failure due to lack of support for memory-mapped capture, returns
3129 * On error, returns -1, and sets *status to the appropriate error code;
3130 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3133 activate_mmap(pcap_t *handle, int *status)
3138 * Attempt to allocate a buffer to hold the contents of one
3139 * packet, for use by the oneshot callback.
3141 handle->md.oneshot_buffer = malloc(handle->snapshot);
3142 if (handle->md.oneshot_buffer == NULL) {
3143 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3144 "can't allocate oneshot buffer: %s",
3145 pcap_strerror(errno));
3146 *status = PCAP_ERROR;
3150 if (handle->opt.buffer_size == 0) {
3151 /* by default request 2M for the ring buffer */
3152 handle->opt.buffer_size = 2*1024*1024;
3154 ret = prepare_tpacket_socket(handle);
3156 free(handle->md.oneshot_buffer);
3157 *status = PCAP_ERROR;
3160 ret = create_ring(handle, status);
3163 * We don't support memory-mapped capture; our caller
3164 * will fall back on reading from the socket.
3166 free(handle->md.oneshot_buffer);
3171 * Error attempting to enable memory-mapped capture;
3172 * fail. create_ring() has set *status.
3174 free(handle->md.oneshot_buffer);
3179 * Success. *status has been set either to 0 if there are no
3180 * warnings or to a PCAP_WARNING_ value if there is a warning.
3182 * Override some defaults and inherit the other fields from
3184 * handle->offset is used to get the current position into the rx ring.
3185 * handle->cc is used to store the ring size.
3187 handle->read_op = pcap_read_linux_mmap;
3188 handle->cleanup_op = pcap_cleanup_linux_mmap;
3189 handle->setfilter_op = pcap_setfilter_linux_mmap;
3190 handle->setnonblock_op = pcap_setnonblock_mmap;
3191 handle->getnonblock_op = pcap_getnonblock_mmap;
3192 handle->oneshot_callback = pcap_oneshot_mmap;
3193 handle->selectable_fd = handle->fd;
3196 #else /* HAVE_PACKET_RING */
3198 activate_mmap(pcap_t *handle _U_, int *status _U_)
3202 #endif /* HAVE_PACKET_RING */
3204 #ifdef HAVE_PACKET_RING
3206 * Attempt to set the socket to version 2 of the memory-mapped header.
3207 * Return 1 if we succeed or if we fail because version 2 isn't
3208 * supported; return -1 on any other error, and set handle->errbuf.
3211 prepare_tpacket_socket(pcap_t *handle)
3213 #ifdef HAVE_TPACKET2
3218 handle->md.tp_version = TPACKET_V1;
3219 handle->md.tp_hdrlen = sizeof(struct tpacket_hdr);
3221 #ifdef HAVE_TPACKET2
3222 /* Probe whether kernel supports TPACKET_V2 */
3225 if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
3226 if (errno == ENOPROTOOPT)
3227 return 1; /* no - just drive on */
3229 /* Yes - treat as a failure. */
3230 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3231 "can't get TPACKET_V2 header len on packet socket: %s",
3232 pcap_strerror(errno));
3235 handle->md.tp_hdrlen = val;
3238 if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
3240 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3241 "can't activate TPACKET_V2 on packet socket: %s",
3242 pcap_strerror(errno));
3245 handle->md.tp_version = TPACKET_V2;
3247 /* Reserve space for VLAN tag reconstruction */
3249 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
3251 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3252 "can't set up reserve on packet socket: %s",
3253 pcap_strerror(errno));
3257 #endif /* HAVE_TPACKET2 */
3262 * Attempt to set up memory-mapped access.
3264 * On success, returns 1, and sets *status to 0 if there are no warnings
3265 * or to a PCAP_WARNING_ code if there is a warning.
3267 * On failure due to lack of support for memory-mapped capture, returns
3270 * On error, returns -1, and sets *status to the appropriate error code;
3271 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3274 create_ring(pcap_t *handle, int *status)
3276 unsigned i, j, frames_per_block;
3277 struct tpacket_req req;
3279 unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
3280 unsigned int frame_size;
3283 * Start out assuming no warnings or errors.
3287 /* Note that with large snapshot length (say 64K, which is the default
3288 * for recent versions of tcpdump, the value that "-s 0" has given
3289 * for a long time with tcpdump, and the default in Wireshark/TShark),
3290 * if we use the snapshot length to calculate the frame length,
3291 * only a few frames will be available in the ring even with pretty
3292 * large ring size (and a lot of memory will be unused).
3294 * Ideally, we should choose a frame length based on the
3295 * minimum of the specified snapshot length and the maximum
3296 * packet size. That's not as easy as it sounds; consider, for
3297 * example, an 802.11 interface in monitor mode, where the
3298 * frame would include a radiotap header, where the maximum
3299 * radiotap header length is device-dependent.
3301 * So, for now, we just do this for Ethernet devices, where
3302 * there's no metadata header, and the link-layer header is
3303 * fixed length. We can get the maximum packet size by
3304 * adding 18, the Ethernet header length plus the CRC length
3305 * (just in case we happen to get the CRC in the packet), to
3306 * the MTU of the interface; we fetch the MTU in the hopes
3307 * that it reflects support for jumbo frames. (Even if the
3308 * interface is just being used for passive snooping, the driver
3309 * might set the size of buffers in the receive ring based on
3310 * the MTU, so that the MTU limits the maximum size of packets
3311 * that we can receive.)
3313 * We don't do that if segmentation/fragmentation or receive
3314 * offload are enabled, so we don't get rudely surprised by
3315 * "packets" bigger than the MTU. */
3316 frame_size = handle->snapshot;
3317 if (handle->linktype == DLT_EN10MB) {
3321 offload = iface_get_offload(handle);
3322 if (offload == -1) {
3323 *status = PCAP_ERROR;
3327 mtu = iface_get_mtu(handle->fd, handle->opt.source,
3330 *status = PCAP_ERROR;
3333 if (frame_size > mtu + 18)
3334 frame_size = mtu + 18;
3338 /* NOTE: calculus matching those in tpacket_rcv()
3339 * in linux-2.6/net/packet/af_packet.c
3341 len = sizeof(sk_type);
3342 if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type, &len) < 0) {
3343 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3344 *status = PCAP_ERROR;
3347 #ifdef PACKET_RESERVE
3348 len = sizeof(tp_reserve);
3349 if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &tp_reserve, &len) < 0) {
3350 if (errno != ENOPROTOOPT) {
3352 * ENOPROTOOPT means "kernel doesn't support
3353 * PACKET_RESERVE", in which case we fall back
3356 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3357 *status = PCAP_ERROR;
3360 tp_reserve = 0; /* older kernel, reserve not supported */
3363 tp_reserve = 0; /* older kernel, reserve not supported */
3365 maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
3366 /* XXX: in the kernel maclen is calculated from
3367 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3368 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3369 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3370 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3371 * but I see no way to get those sizes in userspace,
3372 * like for instance with an ifreq ioctl();
3373 * the best thing I've found so far is MAX_HEADER in the kernel
3374 * part of linux-2.6/include/linux/netdevice.h
3375 * which goes up to 128+48=176; since pcap-linux.c defines
3376 * a MAX_LINKHEADER_SIZE of 256 which is greater than that,
3377 * let's use it.. maybe is it even large enough to directly
3380 tp_hdrlen = TPACKET_ALIGN(handle->md.tp_hdrlen) + sizeof(struct sockaddr_ll) ;
3381 netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
3382 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN of
3383 * netoff, which contradicts
3384 * linux-2.6/Documentation/networking/packet_mmap.txt
3386 * "- Gap, chosen so that packet data (Start+tp_net)
3387 * aligns to TPACKET_ALIGNMENT=16"
3389 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3390 * "CPUs often take a performance hit
3391 * when accessing unaligned memory locations"
3393 macoff = netoff - maclen;
3394 req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
3395 req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
3397 /* compute the minumum block size that will handle this frame.
3398 * The block has to be page size aligned.
3399 * The max block size allowed by the kernel is arch-dependent and
3400 * it's not explicitly checked here. */
3401 req.tp_block_size = getpagesize();
3402 while (req.tp_block_size < req.tp_frame_size)
3403 req.tp_block_size <<= 1;
3405 frames_per_block = req.tp_block_size/req.tp_frame_size;
3408 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3409 * so we check for PACKET_TIMESTAMP. We check for
3410 * linux/net_tstamp.h just in case a system somehow has
3411 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3414 * SIOCSHWTSTAMP was introduced in the patch that introduced
3415 * linux/net_tstamp.h, so we don't bother checking whether
3416 * SIOCSHWTSTAMP is defined (if your Linux system has
3417 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3418 * Linux system is badly broken).
3420 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3422 * If we were told to do so, ask the kernel and the driver
3423 * to use hardware timestamps.
3425 * Hardware timestamps are only supported with mmapped
3428 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
3429 handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
3430 struct hwtstamp_config hwconfig;
3435 * Ask for hardware time stamps on all packets,
3436 * including transmitted packets.
3438 memset(&hwconfig, 0, sizeof(hwconfig));
3439 hwconfig.tx_type = HWTSTAMP_TX_ON;
3440 hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
3442 memset(&ifr, 0, sizeof(ifr));
3443 strcpy(ifr.ifr_name, handle->opt.source);
3444 ifr.ifr_data = (void *)&hwconfig;
3446 if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
3451 * Treat this as an error, as the
3452 * user should try to run this
3453 * with the appropriate privileges -
3454 * and, if they can't, shouldn't
3455 * try requesting hardware time stamps.
3457 *status = PCAP_ERROR_PERM_DENIED;
3462 * Treat this as a warning, as the
3463 * only way to fix the warning is to
3464 * get an adapter that supports hardware
3465 * time stamps. We'll just fall back
3466 * on the standard host time stamps.
3468 *status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
3472 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3473 "SIOCSHWTSTAMP failed: %s",
3474 pcap_strerror(errno));
3475 *status = PCAP_ERROR;
3480 * Well, that worked. Now specify the type of
3481 * hardware time stamp we want for this
3484 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
3486 * Hardware timestamp, synchronized
3487 * with the system clock.
3489 timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
3492 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3493 * timestamp, not synchronized with the
3496 timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
3498 if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
3499 (void *)×ource, sizeof(timesource))) {
3500 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3501 "can't set PACKET_TIMESTAMP: %s",
3502 pcap_strerror(errno));
3503 *status = PCAP_ERROR;
3508 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3510 /* ask the kernel to create the ring */
3512 req.tp_block_nr = req.tp_frame_nr / frames_per_block;
3514 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3515 req.tp_frame_nr = req.tp_block_nr * frames_per_block;
3517 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3518 (void *) &req, sizeof(req))) {
3519 if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
3521 * Memory failure; try to reduce the requested ring
3524 * We used to reduce this by half -- do 5% instead.
3525 * That may result in more iterations and a longer
3526 * startup, but the user will be much happier with
3527 * the resulting buffer size.
3529 if (req.tp_frame_nr < 20)
3530 req.tp_frame_nr -= 1;
3532 req.tp_frame_nr -= req.tp_frame_nr/20;
3535 if (errno == ENOPROTOOPT) {
3537 * We don't have ring buffer support in this kernel.
3541 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3542 "can't create rx ring on packet socket: %s",
3543 pcap_strerror(errno));
3544 *status = PCAP_ERROR;
3548 /* memory map the rx ring */
3549 handle->md.mmapbuflen = req.tp_block_nr * req.tp_block_size;
3550 handle->md.mmapbuf = mmap(0, handle->md.mmapbuflen,
3551 PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
3552 if (handle->md.mmapbuf == MAP_FAILED) {
3553 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3554 "can't mmap rx ring: %s", pcap_strerror(errno));
3556 /* clear the allocated ring on error*/
3557 destroy_ring(handle);
3558 *status = PCAP_ERROR;
3562 /* allocate a ring for each frame header pointer*/
3563 handle->cc = req.tp_frame_nr;
3564 handle->buffer = malloc(handle->cc * sizeof(union thdr *));
3565 if (!handle->buffer) {
3566 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3567 "can't allocate ring of frame headers: %s",
3568 pcap_strerror(errno));
3570 destroy_ring(handle);
3571 *status = PCAP_ERROR;
3575 /* fill the header ring with proper frame ptr*/
3577 for (i=0; i<req.tp_block_nr; ++i) {
3578 void *base = &handle->md.mmapbuf[i*req.tp_block_size];
3579 for (j=0; j<frames_per_block; ++j, ++handle->offset) {
3580 RING_GET_FRAME(handle) = base;
3581 base += req.tp_frame_size;
3585 handle->bufsize = req.tp_frame_size;
3590 /* free all ring related resources*/
3592 destroy_ring(pcap_t *handle)
3594 /* tell the kernel to destroy the ring*/
3595 struct tpacket_req req;
3596 memset(&req, 0, sizeof(req));
3597 setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3598 (void *) &req, sizeof(req));
3600 /* if ring is mapped, unmap it*/
3601 if (handle->md.mmapbuf) {
3602 /* do not test for mmap failure, as we can't recover from any error */
3603 munmap(handle->md.mmapbuf, handle->md.mmapbuflen);
3604 handle->md.mmapbuf = NULL;
3609 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3610 * for Linux mmapped capture.
3612 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3613 * data handed to the callback to be valid after the callback returns,
3614 * but pcap_read_linux_mmap() has to release that packet as soon as
3615 * the callback returns (otherwise, the kernel thinks there's still
3616 * at least one unprocessed packet available in the ring, so a select()
3617 * will immediately return indicating that there's data to process), so,
3618 * in the callback, we have to make a copy of the packet.
3620 * Yes, this means that, if the capture is using the ring buffer, using
3621 * pcap_next() or pcap_next_ex() requires more copies than using
3622 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3623 * pcap_next() or pcap_next_ex().
3626 pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
3627 const u_char *bytes)
3629 struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
3632 memcpy(sp->pd->md.oneshot_buffer, bytes, h->caplen);
3633 *sp->pkt = sp->pd->md.oneshot_buffer;
3637 pcap_cleanup_linux_mmap( pcap_t *handle )
3639 destroy_ring(handle);
3640 if (handle->md.oneshot_buffer != NULL) {
3641 free(handle->md.oneshot_buffer);
3642 handle->md.oneshot_buffer = NULL;
3644 pcap_cleanup_linux(handle);
3649 pcap_getnonblock_mmap(pcap_t *p, char *errbuf)
3651 /* use negative value of timeout to indicate non blocking ops */
3652 return (p->md.timeout<0);
3656 pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
3659 * Map each value to their corresponding negation to
3660 * preserve the timeout value provided with pcap_set_timeout.
3663 if (p->md.timeout >= 0) {
3665 * Indicate that we're switching to
3666 * non-blocking mode.
3668 p->md.timeout = ~p->md.timeout;
3671 if (p->md.timeout < 0) {
3672 p->md.timeout = ~p->md.timeout;
3678 static inline union thdr *
3679 pcap_get_ring_frame(pcap_t *handle, int status)
3683 h.raw = RING_GET_FRAME(handle);
3684 switch (handle->md.tp_version) {
3686 if (status != (h.h1->tp_status ? TP_STATUS_USER :
3690 #ifdef HAVE_TPACKET2
3692 if (status != (h.h2->tp_status ? TP_STATUS_USER :
3706 pcap_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback,
3713 /* wait for frames availability.*/
3714 if (!pcap_get_ring_frame(handle, TP_STATUS_USER)) {
3715 struct pollfd pollinfo;
3718 pollinfo.fd = handle->fd;
3719 pollinfo.events = POLLIN;
3721 if (handle->md.timeout == 0)
3722 timeout = -1; /* block forever */
3723 else if (handle->md.timeout > 0)
3724 timeout = handle->md.timeout; /* block for that amount of time */
3726 timeout = 0; /* non-blocking mode - poll to pick up errors */
3728 ret = poll(&pollinfo, 1, timeout);
3729 if (ret < 0 && errno != EINTR) {
3730 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3731 "can't poll on packet socket: %s",
3732 pcap_strerror(errno));
3734 } else if (ret > 0 &&
3735 (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
3737 * There's some indication other than
3738 * "you can read on this descriptor" on
3741 if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
3742 snprintf(handle->errbuf,
3744 "Hangup on packet socket");
3747 if (pollinfo.revents & POLLERR) {
3749 * A recv() will give us the
3750 * actual error code.
3752 * XXX - make the socket non-blocking?
3754 if (recv(handle->fd, &c, sizeof c,
3756 continue; /* what, no error? */
3757 if (errno == ENETDOWN) {
3759 * The device on which we're
3760 * capturing went away.
3762 * XXX - we should really return
3763 * PCAP_ERROR_IFACE_NOT_UP,
3764 * but pcap_dispatch() etc.
3765 * aren't defined to return
3768 snprintf(handle->errbuf,
3770 "The interface went down");
3772 snprintf(handle->errbuf,
3774 "Error condition on packet socket: %s",
3779 if (pollinfo.revents & POLLNVAL) {
3780 snprintf(handle->errbuf,
3782 "Invalid polling request on packet socket");
3786 /* check for break loop condition on interrupted syscall*/
3787 if (handle->break_loop) {
3788 handle->break_loop = 0;
3789 return PCAP_ERROR_BREAK;
3794 /* non-positive values of max_packets are used to require all
3795 * packets currently available in the ring */
3796 while ((pkts < max_packets) || (max_packets <= 0)) {
3798 struct sockaddr_ll *sll;
3799 struct pcap_pkthdr pcaphdr;
3802 unsigned int tp_len;
3803 unsigned int tp_mac;
3804 unsigned int tp_snaplen;
3805 unsigned int tp_sec;
3806 unsigned int tp_usec;
3808 h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
3812 switch (handle->md.tp_version) {
3814 tp_len = h.h1->tp_len;
3815 tp_mac = h.h1->tp_mac;
3816 tp_snaplen = h.h1->tp_snaplen;
3817 tp_sec = h.h1->tp_sec;
3818 tp_usec = h.h1->tp_usec;
3820 #ifdef HAVE_TPACKET2
3822 tp_len = h.h2->tp_len;
3823 tp_mac = h.h2->tp_mac;
3824 tp_snaplen = h.h2->tp_snaplen;
3825 tp_sec = h.h2->tp_sec;
3826 tp_usec = h.h2->tp_nsec / 1000;
3830 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3831 "unsupported tpacket version %d",
3832 handle->md.tp_version);
3835 /* perform sanity check on internal offset. */
3836 if (tp_mac + tp_snaplen > handle->bufsize) {
3837 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3838 "corrupted frame on kernel ring mac "
3839 "offset %d + caplen %d > frame len %d",
3840 tp_mac, tp_snaplen, handle->bufsize);
3844 /* run filter on received packet
3845 * If the kernel filtering is enabled we need to run the
3846 * filter until all the frames present into the ring
3847 * at filter creation time are processed.
3848 * In such case md.use_bpf is used as a counter for the
3849 * packet we need to filter.
3850 * Note: alternatively it could be possible to stop applying
3851 * the filter when the ring became empty, but it can possibly
3852 * happen a lot later... */
3853 bp = (unsigned char*)h.raw + tp_mac;
3854 run_bpf = (!handle->md.use_bpf) ||
3855 ((handle->md.use_bpf>1) && handle->md.use_bpf--);
3856 if (run_bpf && handle->fcode.bf_insns &&
3857 (bpf_filter(handle->fcode.bf_insns, bp,
3858 tp_len, tp_snaplen) == 0))
3862 * Do checks based on packet direction.
3864 sll = (void *)h.raw + TPACKET_ALIGN(handle->md.tp_hdrlen);
3865 if (sll->sll_pkttype == PACKET_OUTGOING) {
3868 * If this is from the loopback device, reject it;
3869 * we'll see the packet as an incoming packet as well,
3870 * and we don't want to see it twice.
3872 if (sll->sll_ifindex == handle->md.lo_ifindex)
3876 * If the user only wants incoming packets, reject it.
3878 if (handle->direction == PCAP_D_IN)
3883 * If the user only wants outgoing packets, reject it.
3885 if (handle->direction == PCAP_D_OUT)
3889 /* get required packet info from ring header */
3890 pcaphdr.ts.tv_sec = tp_sec;
3891 pcaphdr.ts.tv_usec = tp_usec;
3892 pcaphdr.caplen = tp_snaplen;
3893 pcaphdr.len = tp_len;
3895 /* if required build in place the sll header*/
3896 if (handle->md.cooked) {
3897 struct sll_header *hdrp;
3900 * The kernel should have left us with enough
3901 * space for an sll header; back up the packet
3902 * data pointer into that space, as that'll be
3903 * the beginning of the packet we pass to the
3909 * Let's make sure that's past the end of
3910 * the tpacket header, i.e. >=
3911 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3912 * don't step on the header when we construct
3915 if (bp < (u_char *)h.raw +
3916 TPACKET_ALIGN(handle->md.tp_hdrlen) +
3917 sizeof(struct sockaddr_ll)) {
3918 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3919 "cooked-mode frame doesn't have room for sll header");
3924 * OK, that worked; construct the sll header.
3926 hdrp = (struct sll_header *)bp;
3927 hdrp->sll_pkttype = map_packet_type_to_sll_type(
3929 hdrp->sll_hatype = htons(sll->sll_hatype);
3930 hdrp->sll_halen = htons(sll->sll_halen);
3931 memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
3932 hdrp->sll_protocol = sll->sll_protocol;
3934 /* update packet len */
3935 pcaphdr.caplen += SLL_HDR_LEN;
3936 pcaphdr.len += SLL_HDR_LEN;
3939 #ifdef HAVE_TPACKET2
3940 if ((handle->md.tp_version == TPACKET_V2) &&
3941 #if defined(TP_STATUS_VLAN_VALID)
3942 (h.h2->tp_vlan_tci || (h.h2->tp_status & TP_STATUS_VLAN_VALID)) &&
3944 h.h2->tp_vlan_tci &&
3946 handle->md.vlan_offset != -1 &&
3947 tp_snaplen >= (unsigned int) handle->md.vlan_offset) {
3948 struct vlan_tag *tag;
3951 memmove(bp, bp + VLAN_TAG_LEN, handle->md.vlan_offset);
3953 tag = (struct vlan_tag *)(bp + handle->md.vlan_offset);
3954 tag->vlan_tpid = htons(ETH_P_8021Q);
3955 tag->vlan_tci = htons(h.h2->tp_vlan_tci);
3957 pcaphdr.caplen += VLAN_TAG_LEN;
3958 pcaphdr.len += VLAN_TAG_LEN;
3963 * The only way to tell the kernel to cut off the
3964 * packet at a snapshot length is with a filter program;
3965 * if there's no filter program, the kernel won't cut
3968 * Trim the snapshot length to be no longer than the
3969 * specified snapshot length.
3971 if (pcaphdr.caplen > handle->snapshot)
3972 pcaphdr.caplen = handle->snapshot;
3974 /* pass the packet to the user */
3976 callback(user, &pcaphdr, bp);
3977 handle->md.packets_read++;
3981 switch (handle->md.tp_version) {
3983 h.h1->tp_status = TP_STATUS_KERNEL;
3985 #ifdef HAVE_TPACKET2
3987 h.h2->tp_status = TP_STATUS_KERNEL;
3991 if (++handle->offset >= handle->cc)
3994 /* check for break loop condition*/
3995 if (handle->break_loop) {
3996 handle->break_loop = 0;
3997 return PCAP_ERROR_BREAK;
4004 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
4010 * Don't rewrite "ret" instructions; we don't need to, as
4011 * we're not reading packets with recvmsg(), and we don't
4012 * want to, as, by not rewriting them, the kernel can avoid
4013 * copying extra data.
4015 ret = pcap_setfilter_linux_common(handle, filter, 1);
4019 /* if the kernel filter is enabled, we need to apply the filter on
4020 * all packets present into the ring. Get an upper bound of their number
4022 if (!handle->md.use_bpf)
4025 /* walk the ring backward and count the free slot */
4026 offset = handle->offset;
4027 if (--handle->offset < 0)
4028 handle->offset = handle->cc - 1;
4029 for (n=0; n < handle->cc; ++n) {
4030 if (--handle->offset < 0)
4031 handle->offset = handle->cc - 1;
4032 if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
4036 /* be careful to not change current ring position */
4037 handle->offset = offset;
4039 /* store the number of packets currently present in the ring */
4040 handle->md.use_bpf = 1 + (handle->cc - n);
4044 #endif /* HAVE_PACKET_RING */
4047 #ifdef HAVE_PF_PACKET_SOCKETS
4049 * Return the index of the given device name. Fill ebuf and return
4053 iface_get_id(int fd, const char *device, char *ebuf)
4057 memset(&ifr, 0, sizeof(ifr));
4058 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4060 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
4061 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4062 "SIOCGIFINDEX: %s", pcap_strerror(errno));
4066 return ifr.ifr_ifindex;
4070 * Bind the socket associated with FD to the given device.
4071 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4072 * or a PCAP_ERROR_ value on a hard error.
4075 iface_bind(int fd, int ifindex, char *ebuf)
4077 struct sockaddr_ll sll;
4079 socklen_t errlen = sizeof(err);
4081 memset(&sll, 0, sizeof(sll));
4082 sll.sll_family = AF_PACKET;
4083 sll.sll_ifindex = ifindex;
4084 sll.sll_protocol = htons(ETH_P_ALL);
4086 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
4087 if (errno == ENETDOWN) {
4089 * Return a "network down" indication, so that
4090 * the application can report that rather than
4091 * saying we had a mysterious failure and
4092 * suggest that they report a problem to the
4093 * libpcap developers.
4095 return PCAP_ERROR_IFACE_NOT_UP;
4097 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4098 "bind: %s", pcap_strerror(errno));
4103 /* Any pending errors, e.g., network is down? */
4105 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
4106 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4107 "getsockopt: %s", pcap_strerror(errno));
4111 if (err == ENETDOWN) {
4113 * Return a "network down" indication, so that
4114 * the application can report that rather than
4115 * saying we had a mysterious failure and
4116 * suggest that they report a problem to the
4117 * libpcap developers.
4119 return PCAP_ERROR_IFACE_NOT_UP;
4120 } else if (err > 0) {
4121 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4122 "bind: %s", pcap_strerror(err));
4129 #ifdef IW_MODE_MONITOR
4131 * Check whether the device supports the Wireless Extensions.
4132 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4133 * if the device doesn't even exist.
4136 has_wext(int sock_fd, const char *device, char *ebuf)
4140 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4141 sizeof ireq.ifr_ifrn.ifrn_name);
4142 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4143 if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
4145 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4146 "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
4147 if (errno == ENODEV)
4148 return PCAP_ERROR_NO_SUCH_DEVICE;
4153 * Per me si va ne la citta dolente,
4154 * Per me si va ne l'etterno dolore,
4156 * Lasciate ogne speranza, voi ch'intrate.
4158 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4174 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4175 * on if it's not already on.
4177 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4178 * on this device, or a PCAP_ERROR_ value if we do support them but
4179 * we weren't able to turn monitor mode on.
4182 enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
4185 * XXX - at least some adapters require non-Wireless Extensions
4186 * mechanisms to turn monitor mode on.
4188 * Atheros cards might require that a separate "monitor virtual access
4189 * point" be created, with later versions of the madwifi driver.
4190 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4191 * monitor -bssid", which apparently spits out a line "athN"
4192 * where "athN" is the monitor mode device. To leave monitor
4193 * mode, it destroys the monitor mode device.
4195 * Some Intel Centrino adapters might require private ioctls to get
4196 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4197 * configure a separate "rtapN" interface to capture in monitor
4198 * mode without preventing the adapter from operating normally.
4199 * (airmon-ng doesn't appear to use that, though.)
4201 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4202 * up, and if all drivers were converted to mac80211 drivers.
4204 * If interface {if} is a mac80211 driver, the file
4205 * /sys/class/net/{if}/phy80211 is a symlink to
4206 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4208 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4209 * least, has a "wmaster0" device and a "wlan0" device; the
4210 * latter is the one with the IP address. Both show up in
4211 * "tcpdump -D" output. Capturing on the wmaster0 device
4212 * captures with 802.11 headers.
4214 * airmon-ng searches through /sys/class/net for devices named
4215 * monN, starting with mon0; as soon as one *doesn't* exist,
4216 * it chooses that as the monitor device name. If the "iw"
4217 * command exists, it does "iw dev {if} interface add {monif}
4218 * type monitor", where {monif} is the monitor device. It
4219 * then (sigh) sleeps .1 second, and then configures the
4220 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4221 * is a file, it writes {mondev}, without a newline, to that file,
4222 * and again (sigh) sleeps .1 second, and then iwconfig's that
4223 * device into monitor mode and configures it up. Otherwise,
4224 * you can't do monitor mode.
4226 * All these devices are "glued" together by having the
4227 * /sys/class/net/{device}/phy80211 links pointing to the same
4228 * place, so, given a wmaster, wlan, or mon device, you can
4229 * find the other devices by looking for devices with
4230 * the same phy80211 link.
4232 * To turn monitor mode off, delete the monitor interface,
4233 * either with "iw dev {monif} interface del" or by sending
4234 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4236 * Note: if you try to create a monitor device named "monN", and
4237 * there's already a "monN" device, it fails, as least with
4238 * the netlink interface (which is what iw uses), with a return
4239 * value of -ENFILE. (Return values are negative errnos.) We
4240 * could probably use that to find an unused device.
4244 struct iw_priv_args *priv;
4245 monitor_type montype;
4254 * Does this device *support* the Wireless Extensions?
4256 err = has_wext(sock_fd, device, handle->errbuf);
4258 return err; /* either it doesn't or the device doesn't even exist */
4260 * Start out assuming we have no private extensions to control
4263 montype = MONITOR_WEXT;
4267 * Try to get all the Wireless Extensions private ioctls
4268 * supported by this device.
4270 * First, get the size of the buffer we need, by supplying no
4271 * buffer and a length of 0. If the device supports private
4272 * ioctls, it should return E2BIG, with ireq.u.data.length set
4273 * to the length we need. If it doesn't support them, it should
4274 * return EOPNOTSUPP.
4276 memset(&ireq, 0, sizeof ireq);
4277 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4278 sizeof ireq.ifr_ifrn.ifrn_name);
4279 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4280 ireq.u.data.pointer = (void *)args;
4281 ireq.u.data.length = 0;
4282 ireq.u.data.flags = 0;
4283 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
4284 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4285 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4289 if (errno != EOPNOTSUPP) {
4291 * OK, it's not as if there are no private ioctls.
4293 if (errno != E2BIG) {
4297 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4298 "%s: SIOCGIWPRIV: %s", device,
4299 pcap_strerror(errno));
4304 * OK, try to get the list of private ioctls.
4306 priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
4308 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4309 "malloc: %s", pcap_strerror(errno));
4312 ireq.u.data.pointer = (void *)priv;
4313 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
4314 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4315 "%s: SIOCGIWPRIV: %s", device,
4316 pcap_strerror(errno));
4322 * Look for private ioctls to turn monitor mode on or, if
4323 * monitor mode is on, to set the header type.
4325 for (i = 0; i < ireq.u.data.length; i++) {
4326 if (strcmp(priv[i].name, "monitor_type") == 0) {
4328 * Hostap driver, use this one.
4329 * Set monitor mode first.
4330 * You can set it to 0 to get DLT_IEEE80211,
4331 * 1 to get DLT_PRISM, 2 to get
4332 * DLT_IEEE80211_RADIO_AVS, and, with more
4333 * recent versions of the driver, 3 to get
4334 * DLT_IEEE80211_RADIO.
4336 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4338 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4340 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4342 montype = MONITOR_HOSTAP;
4346 if (strcmp(priv[i].name, "set_prismhdr") == 0) {
4348 * Prism54 driver, use this one.
4349 * Set monitor mode first.
4350 * You can set it to 2 to get DLT_IEEE80211
4351 * or 3 or get DLT_PRISM.
4353 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4355 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4357 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4359 montype = MONITOR_PRISM54;
4363 if (strcmp(priv[i].name, "forceprismheader") == 0) {
4365 * RT2570 driver, use this one.
4366 * Do this after turning monitor mode on.
4367 * You can set it to 1 to get DLT_PRISM or 2
4368 * to get DLT_IEEE80211.
4370 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4372 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4374 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4376 montype = MONITOR_RT2570;
4380 if (strcmp(priv[i].name, "forceprism") == 0) {
4382 * RT73 driver, use this one.
4383 * Do this after turning monitor mode on.
4384 * Its argument is a *string*; you can
4385 * set it to "1" to get DLT_PRISM or "2"
4386 * to get DLT_IEEE80211.
4388 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
4390 if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
4392 montype = MONITOR_RT73;
4396 if (strcmp(priv[i].name, "prismhdr") == 0) {
4398 * One of the RTL8xxx drivers, use this one.
4399 * It can only be done after monitor mode
4400 * has been turned on. You can set it to 1
4401 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4403 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4405 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4407 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4409 montype = MONITOR_RTL8XXX;
4413 if (strcmp(priv[i].name, "rfmontx") == 0) {
4415 * RT2500 or RT61 driver, use this one.
4416 * It has one one-byte parameter; set
4417 * u.data.length to 1 and u.data.pointer to
4418 * point to the parameter.
4419 * It doesn't itself turn monitor mode on.
4420 * You can set it to 1 to allow transmitting
4421 * in monitor mode(?) and get DLT_IEEE80211,
4422 * or set it to 0 to disallow transmitting in
4423 * monitor mode(?) and get DLT_PRISM.
4425 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4427 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
4429 montype = MONITOR_RT2500;
4433 if (strcmp(priv[i].name, "monitor") == 0) {
4435 * Either ACX100 or hostap, use this one.
4436 * It turns monitor mode on.
4437 * If it takes two arguments, it's ACX100;
4438 * the first argument is 1 for DLT_PRISM
4439 * or 2 for DLT_IEEE80211, and the second
4440 * argument is the channel on which to
4441 * run. If it takes one argument, it's
4442 * HostAP, and the argument is 2 for
4443 * DLT_IEEE80211 and 3 for DLT_PRISM.
4445 * If we see this, we don't quit, as this
4446 * might be a version of the hostap driver
4447 * that also supports "monitor_type".
4449 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4451 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4453 switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
4456 montype = MONITOR_PRISM;
4461 montype = MONITOR_ACX100;
4474 * XXX - ipw3945? islism?
4480 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4481 sizeof ireq.ifr_ifrn.ifrn_name);
4482 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4483 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
4485 * We probably won't be able to set the mode, either.
4487 return PCAP_ERROR_RFMON_NOTSUP;
4491 * Is it currently in monitor mode?
4493 if (ireq.u.mode == IW_MODE_MONITOR) {
4495 * Yes. Just leave things as they are.
4496 * We don't offer multiple link-layer types, as
4497 * changing the link-layer type out from under
4498 * somebody else capturing in monitor mode would
4499 * be considered rude.
4504 * No. We have to put the adapter into rfmon mode.
4508 * If we haven't already done so, arrange to have
4509 * "pcap_close_all()" called when we exit.
4511 if (!pcap_do_addexit(handle)) {
4513 * "atexit()" failed; don't put the interface
4514 * in rfmon mode, just give up.
4516 return PCAP_ERROR_RFMON_NOTSUP;
4520 * Save the old mode.
4522 handle->md.oldmode = ireq.u.mode;
4525 * Put the adapter in rfmon mode. How we do this depends
4526 * on whether we have a special private ioctl or not.
4528 if (montype == MONITOR_PRISM) {
4530 * We have the "monitor" private ioctl, but none of
4531 * the other private ioctls. Use this, and select
4534 * If it fails, just fall back on SIOCSIWMODE.
4536 memset(&ireq, 0, sizeof ireq);
4537 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4538 sizeof ireq.ifr_ifrn.ifrn_name);
4539 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4540 ireq.u.data.length = 1; /* 1 argument */
4541 args[0] = 3; /* request Prism header */
4542 memcpy(ireq.u.name, args, IFNAMSIZ);
4543 if (ioctl(sock_fd, cmd, &ireq) != -1) {
4546 * Note that we have to put the old mode back
4547 * when we close the device.
4549 handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4552 * Add this to the list of pcaps to close
4555 pcap_add_to_pcaps_to_close(handle);
4561 * Failure. Fall back on SIOCSIWMODE.
4566 * First, take the interface down if it's up; otherwise, we
4569 memset(&ifr, 0, sizeof(ifr));
4570 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4571 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
4572 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4573 "%s: Can't get flags: %s", device, strerror(errno));
4577 if (ifr.ifr_flags & IFF_UP) {
4578 oldflags = ifr.ifr_flags;
4579 ifr.ifr_flags &= ~IFF_UP;
4580 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4581 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4582 "%s: Can't set flags: %s", device, strerror(errno));
4588 * Then turn monitor mode on.
4590 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4591 sizeof ireq.ifr_ifrn.ifrn_name);
4592 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4593 ireq.u.mode = IW_MODE_MONITOR;
4594 if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
4596 * Scientist, you've failed.
4597 * Bring the interface back up if we shut it down.
4599 ifr.ifr_flags = oldflags;
4600 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4601 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4602 "%s: Can't set flags: %s", device, strerror(errno));
4605 return PCAP_ERROR_RFMON_NOTSUP;
4609 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4610 * monitor mode and setting the channel, and then does
4615 * Now select the appropriate radio header.
4621 * We don't have any private ioctl to set the header.
4625 case MONITOR_HOSTAP:
4627 * Try to select the radiotap header.
4629 memset(&ireq, 0, sizeof ireq);
4630 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4631 sizeof ireq.ifr_ifrn.ifrn_name);
4632 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4633 args[0] = 3; /* request radiotap header */
4634 memcpy(ireq.u.name, args, sizeof (int));
4635 if (ioctl(sock_fd, cmd, &ireq) != -1)
4636 break; /* success */
4639 * That failed. Try to select the AVS header.
4641 memset(&ireq, 0, sizeof ireq);
4642 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4643 sizeof ireq.ifr_ifrn.ifrn_name);
4644 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4645 args[0] = 2; /* request AVS header */
4646 memcpy(ireq.u.name, args, sizeof (int));
4647 if (ioctl(sock_fd, cmd, &ireq) != -1)
4648 break; /* success */
4651 * That failed. Try to select the Prism header.
4653 memset(&ireq, 0, sizeof ireq);
4654 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4655 sizeof ireq.ifr_ifrn.ifrn_name);
4656 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4657 args[0] = 1; /* request Prism header */
4658 memcpy(ireq.u.name, args, sizeof (int));
4659 ioctl(sock_fd, cmd, &ireq);
4664 * The private ioctl failed.
4668 case MONITOR_PRISM54:
4670 * Select the Prism header.
4672 memset(&ireq, 0, sizeof ireq);
4673 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4674 sizeof ireq.ifr_ifrn.ifrn_name);
4675 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4676 args[0] = 3; /* request Prism header */
4677 memcpy(ireq.u.name, args, sizeof (int));
4678 ioctl(sock_fd, cmd, &ireq);
4681 case MONITOR_ACX100:
4683 * Get the current channel.
4685 memset(&ireq, 0, sizeof ireq);
4686 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4687 sizeof ireq.ifr_ifrn.ifrn_name);
4688 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4689 if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
4690 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4691 "%s: SIOCGIWFREQ: %s", device,
4692 pcap_strerror(errno));
4695 channel = ireq.u.freq.m;
4698 * Select the Prism header, and set the channel to the
4701 memset(&ireq, 0, sizeof ireq);
4702 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4703 sizeof ireq.ifr_ifrn.ifrn_name);
4704 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4705 args[0] = 1; /* request Prism header */
4706 args[1] = channel; /* set channel */
4707 memcpy(ireq.u.name, args, 2*sizeof (int));
4708 ioctl(sock_fd, cmd, &ireq);
4711 case MONITOR_RT2500:
4713 * Disallow transmission - that turns on the
4716 memset(&ireq, 0, sizeof ireq);
4717 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4718 sizeof ireq.ifr_ifrn.ifrn_name);
4719 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4720 args[0] = 0; /* disallow transmitting */
4721 memcpy(ireq.u.name, args, sizeof (int));
4722 ioctl(sock_fd, cmd, &ireq);
4725 case MONITOR_RT2570:
4727 * Force the Prism header.
4729 memset(&ireq, 0, sizeof ireq);
4730 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4731 sizeof ireq.ifr_ifrn.ifrn_name);
4732 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4733 args[0] = 1; /* request Prism header */
4734 memcpy(ireq.u.name, args, sizeof (int));
4735 ioctl(sock_fd, cmd, &ireq);
4740 * Force the Prism header.
4742 memset(&ireq, 0, sizeof ireq);
4743 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4744 sizeof ireq.ifr_ifrn.ifrn_name);
4745 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4746 ireq.u.data.length = 1; /* 1 argument */
4747 ireq.u.data.pointer = "1";
4748 ireq.u.data.flags = 0;
4749 ioctl(sock_fd, cmd, &ireq);
4752 case MONITOR_RTL8XXX:
4754 * Force the Prism header.
4756 memset(&ireq, 0, sizeof ireq);
4757 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4758 sizeof ireq.ifr_ifrn.ifrn_name);
4759 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4760 args[0] = 1; /* request Prism header */
4761 memcpy(ireq.u.name, args, sizeof (int));
4762 ioctl(sock_fd, cmd, &ireq);
4767 * Now bring the interface back up if we brought it down.
4769 if (oldflags != 0) {
4770 ifr.ifr_flags = oldflags;
4771 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4772 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4773 "%s: Can't set flags: %s", device, strerror(errno));
4776 * At least try to restore the old mode on the
4779 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
4781 * Scientist, you've failed.
4784 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
4785 "Please adjust manually.\n",
4793 * Note that we have to put the old mode back when we
4796 handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4799 * Add this to the list of pcaps to close when we exit.
4801 pcap_add_to_pcaps_to_close(handle);
4805 #endif /* IW_MODE_MONITOR */
4808 * Try various mechanisms to enter monitor mode.
4811 enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
4813 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4818 ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
4820 return ret; /* error attempting to do so */
4822 return 1; /* success */
4823 #endif /* HAVE_LIBNL */
4825 #ifdef IW_MODE_MONITOR
4826 ret = enter_rfmon_mode_wext(handle, sock_fd, device);
4828 return ret; /* error attempting to do so */
4830 return 1; /* success */
4831 #endif /* IW_MODE_MONITOR */
4834 * Either none of the mechanisms we know about work or none
4835 * of those mechanisms are available, so we can't do monitor
4842 * Find out if we have any form of fragmentation/reassembly offloading.
4844 * We do so using SIOCETHTOOL checking for various types of offloading;
4845 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4846 * of the types of offloading, there's nothing we can do to check, so
4847 * we just say "no, we don't".
4849 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
4851 iface_ethtool_ioctl(pcap_t *handle, int cmd, const char *cmdname)
4854 struct ethtool_value eval;
4856 memset(&ifr, 0, sizeof(ifr));
4857 strncpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
4859 ifr.ifr_data = (caddr_t)&eval;
4860 if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
4861 if (errno == EOPNOTSUPP || errno == EINVAL) {
4863 * OK, let's just return 0, which, in our
4864 * case, either means "no, what we're asking
4865 * about is not enabled" or "all the flags
4866 * are clear (i.e., nothing is enabled)".
4870 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4871 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle->opt.source,
4872 cmdname, strerror(errno));
4879 iface_get_offload(pcap_t *handle)
4884 ret = iface_ethtool_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO");
4888 return 1; /* TCP segmentation offloading on */
4892 ret = iface_ethtool_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO");
4896 return 1; /* UDP fragmentation offloading on */
4901 * XXX - will this cause large unsegmented packets to be
4902 * handed to PF_PACKET sockets on transmission? If not,
4903 * this need not be checked.
4905 ret = iface_ethtool_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO");
4909 return 1; /* generic segmentation offloading on */
4912 #ifdef ETHTOOL_GFLAGS
4913 ret = iface_ethtool_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS");
4916 if (ret & ETH_FLAG_LRO)
4917 return 1; /* large receive offloading on */
4922 * XXX - will this cause large reassembled packets to be
4923 * handed to PF_PACKET sockets on receipt? If not,
4924 * this need not be checked.
4926 ret = iface_ethtool_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO");
4930 return 1; /* generic (large) receive offloading on */
4935 #else /* SIOCETHTOOL */
4937 iface_get_offload(pcap_t *handle _U_)
4940 * XXX - do we need to get this information if we don't
4941 * have the ethtool ioctls? If so, how do we do that?
4945 #endif /* SIOCETHTOOL */
4947 #endif /* HAVE_PF_PACKET_SOCKETS */
4949 /* ===== Functions to interface to the older kernels ================== */
4952 * Try to open a packet socket using the old kernel interface.
4953 * Returns 1 on success and a PCAP_ERROR_ value on an error.
4956 activate_old(pcap_t *handle)
4960 const char *device = handle->opt.source;
4961 struct utsname utsname;
4964 /* Open the socket */
4966 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
4967 if (handle->fd == -1) {
4968 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4969 "socket: %s", pcap_strerror(errno));
4970 if (errno == EPERM || errno == EACCES) {
4972 * You don't have permission to open the
4975 return PCAP_ERROR_PERM_DENIED;
4984 /* It worked - we are using the old interface */
4985 handle->md.sock_packet = 1;
4987 /* ...which means we get the link-layer header. */
4988 handle->md.cooked = 0;
4990 /* Bind to the given device */
4992 if (strcmp(device, "any") == 0) {
4993 strncpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4997 if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
5001 * Try to get the link-layer type.
5003 arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
5008 * Try to find the DLT_ type corresponding to that
5011 map_arphrd_to_dlt(handle, arptype, 0);
5012 if (handle->linktype == -1) {
5013 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5014 "unknown arptype %d", arptype);
5018 /* Go to promisc mode if requested */
5020 if (handle->opt.promisc) {
5021 memset(&ifr, 0, sizeof(ifr));
5022 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5023 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
5024 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5025 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
5028 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
5030 * Promiscuous mode isn't currently on,
5031 * so turn it on, and remember that
5032 * we should turn it off when the
5037 * If we haven't already done so, arrange
5038 * to have "pcap_close_all()" called when
5041 if (!pcap_do_addexit(handle)) {
5043 * "atexit()" failed; don't put
5044 * the interface in promiscuous
5045 * mode, just give up.
5050 ifr.ifr_flags |= IFF_PROMISC;
5051 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
5052 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5054 pcap_strerror(errno));
5057 handle->md.must_do_on_close |= MUST_CLEAR_PROMISC;
5060 * Add this to the list of pcaps
5061 * to close when we exit.
5063 pcap_add_to_pcaps_to_close(handle);
5068 * Compute the buffer size.
5070 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5071 * kernel, and might require special handling - check.
5073 if (uname(&utsname) < 0 ||
5074 strncmp(utsname.release, "2.0", 3) == 0) {
5076 * Either we couldn't find out what kernel release
5077 * this is, or it's a 2.0[.x] kernel.
5079 * In the 2.0[.x] kernel, a "recvfrom()" on
5080 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5081 * return the number of bytes read, so if we pass
5082 * a length based on the snapshot length, it'll
5083 * return the number of bytes from the packet
5084 * copied to userland, not the actual length
5087 * This means that, for example, the IP dissector
5088 * in tcpdump will get handed a packet length less
5089 * than the length in the IP header, and will
5090 * complain about "truncated-ip".
5092 * So we don't bother trying to copy from the
5093 * kernel only the bytes in which we're interested,
5094 * but instead copy them all, just as the older
5095 * versions of libpcap for Linux did.
5097 * The buffer therefore needs to be big enough to
5098 * hold the largest packet we can get from this
5099 * device. Unfortunately, we can't get the MRU
5100 * of the network; we can only get the MTU. The
5101 * MTU may be too small, in which case a packet larger
5102 * than the buffer size will be truncated *and* we
5103 * won't get the actual packet size.
5105 * However, if the snapshot length is larger than
5106 * the buffer size based on the MTU, we use the
5107 * snapshot length as the buffer size, instead;
5108 * this means that with a sufficiently large snapshot
5109 * length we won't artificially truncate packets
5110 * to the MTU-based size.
5112 * This mess just one of many problems with packet
5113 * capture on 2.0[.x] kernels; you really want a
5114 * 2.2[.x] or later kernel if you want packet capture
5117 mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
5120 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
5121 if (handle->bufsize < handle->snapshot)
5122 handle->bufsize = handle->snapshot;
5125 * This is a 2.2[.x] or later kernel.
5127 * We can safely pass "recvfrom()" a byte count
5128 * based on the snapshot length.
5130 handle->bufsize = handle->snapshot;
5134 * Default value for offset to align link-layer payload
5135 * on a 4-byte boundary.
5140 * SOCK_PACKET sockets don't supply information from
5141 * stripped VLAN tags.
5143 handle->md.vlan_offset = -1; /* unknown */
5149 * Bind the socket associated with FD to the given device using the
5150 * interface of the old kernels.
5153 iface_bind_old(int fd, const char *device, char *ebuf)
5155 struct sockaddr saddr;
5157 socklen_t errlen = sizeof(err);
5159 memset(&saddr, 0, sizeof(saddr));
5160 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
5161 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
5162 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5163 "bind: %s", pcap_strerror(errno));
5167 /* Any pending errors, e.g., network is down? */
5169 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
5170 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5171 "getsockopt: %s", pcap_strerror(errno));
5176 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5177 "bind: %s", pcap_strerror(err));
5185 /* ===== System calls available on all supported kernels ============== */
5188 * Query the kernel for the MTU of the given interface.
5191 iface_get_mtu(int fd, const char *device, char *ebuf)
5196 return BIGGER_THAN_ALL_MTUS;
5198 memset(&ifr, 0, sizeof(ifr));
5199 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5201 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
5202 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5203 "SIOCGIFMTU: %s", pcap_strerror(errno));
5211 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5214 iface_get_arptype(int fd, const char *device, char *ebuf)
5218 memset(&ifr, 0, sizeof(ifr));
5219 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5221 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
5222 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5223 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
5224 if (errno == ENODEV) {
5228 return PCAP_ERROR_NO_SUCH_DEVICE;
5233 return ifr.ifr_hwaddr.sa_family;
5236 #ifdef SO_ATTACH_FILTER
5238 fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
5242 register struct bpf_insn *p;
5247 * Make a copy of the filter, and modify that copy if
5250 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
5251 len = handle->fcode.bf_len;
5252 f = (struct bpf_insn *)malloc(prog_size);
5254 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5255 "malloc: %s", pcap_strerror(errno));
5258 memcpy(f, handle->fcode.bf_insns, prog_size);
5260 fcode->filter = (struct sock_filter *) f;
5262 for (i = 0; i < len; ++i) {
5265 * What type of instruction is this?
5267 switch (BPF_CLASS(p->code)) {
5271 * It's a return instruction; are we capturing
5272 * in memory-mapped mode?
5276 * No; is the snapshot length a constant,
5277 * rather than the contents of the
5280 if (BPF_MODE(p->code) == BPF_K) {
5282 * Yes - if the value to be returned,
5283 * i.e. the snapshot length, is
5284 * anything other than 0, make it
5285 * 65535, so that the packet is
5286 * truncated by "recvfrom()",
5287 * not by the filter.
5289 * XXX - there's nothing we can
5290 * easily do if it's getting the
5291 * value from the accumulator; we'd
5292 * have to insert code to force
5293 * non-zero values to be 65535.
5304 * It's a load instruction; is it loading
5307 switch (BPF_MODE(p->code)) {
5313 * Yes; are we in cooked mode?
5315 if (handle->md.cooked) {
5317 * Yes, so we need to fix this
5320 if (fix_offset(p) < 0) {
5322 * We failed to do so.
5323 * Return 0, so our caller
5324 * knows to punt to userland.
5334 return 1; /* we succeeded */
5338 fix_offset(struct bpf_insn *p)
5341 * What's the offset?
5343 if (p->k >= SLL_HDR_LEN) {
5345 * It's within the link-layer payload; that starts at an
5346 * offset of 0, as far as the kernel packet filter is
5347 * concerned, so subtract the length of the link-layer
5350 p->k -= SLL_HDR_LEN;
5351 } else if (p->k == 0) {
5353 * It's the packet type field; map it to the special magic
5354 * kernel offset for that field.
5356 p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
5357 } else if (p->k == 14) {
5359 * It's the protocol field; map it to the special magic
5360 * kernel offset for that field.
5362 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
5363 } else if ((bpf_int32)(p->k) > 0) {
5365 * It's within the header, but it's not one of those
5366 * fields; we can't do that in the kernel, so punt
5375 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
5377 int total_filter_on = 0;
5383 * The socket filter code doesn't discard all packets queued
5384 * up on the socket when the filter is changed; this means
5385 * that packets that don't match the new filter may show up
5386 * after the new filter is put onto the socket, if those
5387 * packets haven't yet been read.
5389 * This means, for example, that if you do a tcpdump capture
5390 * with a filter, the first few packets in the capture might
5391 * be packets that wouldn't have passed the filter.
5393 * We therefore discard all packets queued up on the socket
5394 * when setting a kernel filter. (This isn't an issue for
5395 * userland filters, as the userland filtering is done after
5396 * packets are queued up.)
5398 * To flush those packets, we put the socket in read-only mode,
5399 * and read packets from the socket until there are no more to
5402 * In order to keep that from being an infinite loop - i.e.,
5403 * to keep more packets from arriving while we're draining
5404 * the queue - we put the "total filter", which is a filter
5405 * that rejects all packets, onto the socket before draining
5408 * This code deliberately ignores any errors, so that you may
5409 * get bogus packets if an error occurs, rather than having
5410 * the filtering done in userland even if it could have been
5411 * done in the kernel.
5413 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
5414 &total_fcode, sizeof(total_fcode)) == 0) {
5418 * Note that we've put the total filter onto the socket.
5420 total_filter_on = 1;
5423 * Save the socket's current mode, and put it in
5424 * non-blocking mode; we drain it by reading packets
5425 * until we get an error (which is normally a
5426 * "nothing more to be read" error).
5428 save_mode = fcntl(handle->fd, F_GETFL, 0);
5429 if (save_mode != -1 &&
5430 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
5431 while (recv(handle->fd, &drain, sizeof drain,
5435 fcntl(handle->fd, F_SETFL, save_mode);
5436 if (save_errno != EAGAIN) {
5438 reset_kernel_filter(handle);
5439 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5440 "recv: %s", pcap_strerror(save_errno));
5447 * Now attach the new filter.
5449 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
5450 fcode, sizeof(*fcode));
5451 if (ret == -1 && total_filter_on) {
5453 * Well, we couldn't set that filter on the socket,
5454 * but we could set the total filter on the socket.
5456 * This could, for example, mean that the filter was
5457 * too big to put into the kernel, so we'll have to
5458 * filter in userland; in any case, we'll be doing
5459 * filtering in userland, so we need to remove the
5460 * total filter so we see packets.
5465 * XXX - if this fails, we're really screwed;
5466 * we have the total filter on the socket,
5467 * and it won't come off. What do we do then?
5469 reset_kernel_filter(handle);
5477 reset_kernel_filter(pcap_t *handle)
5480 * setsockopt() barfs unless it get a dummy parameter.
5481 * valgrind whines unless the value is initialized,
5482 * as it has no idea that setsockopt() ignores its
5487 return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
5488 &dummy, sizeof(dummy));