Busybox: Upgrade to 1.21.1 (stable). lsof active.
[tomato.git] / release / src / router / libpcap / pcap-linux.c
blobf180912a9c4bb9fa9c25b0a823f1a90b1efe80b8
1 /*
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>
7 * License: BSD
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
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
18 * distribution.
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
21 * written permission.
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
46 * are met:
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
65 * SUCH DAMAGE.
68 #ifndef lint
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)";
71 #endif
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
82 * us do that.
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
94 * the socket.
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.
116 #define _GNU_SOURCE
118 #ifdef HAVE_CONFIG_H
119 #include "config.h"
120 #endif
122 #include <errno.h>
123 #include <stdio.h>
124 #include <stdlib.h>
125 #include <ctype.h>
126 #include <unistd.h>
127 #include <fcntl.h>
128 #include <string.h>
129 #include <limits.h>
130 #include <sys/socket.h>
131 #include <sys/ioctl.h>
132 #include <sys/utsname.h>
133 #include <sys/mman.h>
134 #include <linux/if.h>
135 #include <netinet/in.h>
136 #include <linux/if_ether.h>
137 #include <net/if_arp.h>
138 #include <poll.h>
139 #include <dirent.h>
141 #include "pcap-int.h"
142 #include "pcap/sll.h"
143 #include "pcap/vlan.h"
145 #ifdef HAVE_DAG_API
146 #include "pcap-dag.h"
147 #endif /* HAVE_DAG_API */
149 #ifdef HAVE_SEPTEL_API
150 #include "pcap-septel.h"
151 #endif /* HAVE_SEPTEL_API */
153 #ifdef HAVE_SNF_API
154 #include "pcap-snf.h"
155 #endif /* HAVE_SNF_API */
157 #ifdef PCAP_SUPPORT_USB
158 #include "pcap-usb-linux.h"
159 #endif
161 #ifdef PCAP_SUPPORT_BT
162 #include "pcap-bt-linux.h"
163 #endif
165 #ifdef PCAP_SUPPORT_CAN
166 #include "pcap-can-linux.h"
167 #endif
169 #if PCAP_SUPPORT_CANUSB
170 #include "pcap-canusb-linux.h"
171 #endif
173 #ifdef PCAP_SUPPORT_NETFILTER
174 #include "pcap-netfilter-linux.h"
175 #endif
177 #ifdef HAVE_REMOTE
178 #include <pcap-remote.h>
179 #endif
182 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
183 * sockets rather than SOCK_PACKET sockets.
185 * To use them, we include <linux/if_packet.h> rather than
186 * <netpacket/packet.h>; we do so because
188 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
189 * later kernels and libc5, and don't provide a <netpacket/packet.h>
190 * file;
192 * not all versions of glibc2 have a <netpacket/packet.h> file
193 * that defines stuff needed for some of the 2.4-or-later-kernel
194 * features, so if the system has a 2.4 or later kernel, we
195 * still can't use those features.
197 * We're already including a number of other <linux/XXX.h> headers, and
198 * this code is Linux-specific (no other OS has PF_PACKET sockets as
199 * a raw packet capture mechanism), so it's not as if you gain any
200 * useful portability by using <netpacket/packet.h>
202 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
203 * isn't defined? It only defines one data structure in 2.0.x, so
204 * it shouldn't cause any problems.
206 #ifdef PF_PACKET
207 # include <linux/if_packet.h>
210 * On at least some Linux distributions (for example, Red Hat 5.2),
211 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
212 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
213 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
214 * the PACKET_xxx stuff.
216 * So we check whether PACKET_HOST is defined, and assume that we have
217 * PF_PACKET sockets only if it is defined.
219 # ifdef PACKET_HOST
220 # define HAVE_PF_PACKET_SOCKETS
221 # ifdef PACKET_AUXDATA
222 # define HAVE_PACKET_AUXDATA
223 # endif /* PACKET_AUXDATA */
224 # endif /* PACKET_HOST */
227 /* check for memory mapped access avaibility. We assume every needed
228 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
229 * uses many ring related structs and macros */
230 # ifdef TPACKET_HDRLEN
231 # define HAVE_PACKET_RING
232 # ifdef TPACKET2_HDRLEN
233 # define HAVE_TPACKET2
234 # else
235 # define TPACKET_V1 0
236 # endif /* TPACKET2_HDRLEN */
237 # endif /* TPACKET_HDRLEN */
238 #endif /* PF_PACKET */
240 #ifdef SO_ATTACH_FILTER
241 #include <linux/types.h>
242 #include <linux/filter.h>
243 #endif
246 * We need linux/sockios.h if we have linux/net_tstamp.h (for time stamp
247 * specification) or linux/ethtool.h (for ethtool ioctls to get offloading
248 * information).
250 #if defined(HAVE_LINUX_NET_TSTAMP_H) || defined(HAVE_LINUX_ETHTOOL_H)
251 #include <linux/sockios.h>
252 #endif
254 #ifdef HAVE_LINUX_NET_TSTAMP_H
255 #include <linux/net_tstamp.h>
256 #endif
259 * Got Wireless Extensions?
261 #ifdef HAVE_LINUX_WIRELESS_H
262 #include <linux/wireless.h>
263 #endif /* HAVE_LINUX_WIRELESS_H */
266 * Got libnl?
268 #ifdef HAVE_LIBNL
269 #include <linux/nl80211.h>
271 #include <netlink/genl/genl.h>
272 #include <netlink/genl/family.h>
273 #include <netlink/genl/ctrl.h>
274 #include <netlink/msg.h>
275 #include <netlink/attr.h>
276 #endif /* HAVE_LIBNL */
279 * Got ethtool support?
281 #ifdef HAVE_LINUX_ETHTOOL_H
282 #include <linux/ethtool.h>
283 #endif
285 #ifndef HAVE_SOCKLEN_T
286 typedef int socklen_t;
287 #endif
289 #ifndef MSG_TRUNC
291 * This is being compiled on a system that lacks MSG_TRUNC; define it
292 * with the value it has in the 2.2 and later kernels, so that, on
293 * those kernels, when we pass it in the flags argument to "recvfrom()"
294 * we're passing the right value and thus get the MSG_TRUNC behavior
295 * we want. (We don't get that behavior on 2.0[.x] kernels, because
296 * they didn't support MSG_TRUNC.)
298 #define MSG_TRUNC 0x20
299 #endif
301 #ifndef SOL_PACKET
303 * This is being compiled on a system that lacks SOL_PACKET; define it
304 * with the value it has in the 2.2 and later kernels, so that we can
305 * set promiscuous mode in the good modern way rather than the old
306 * 2.0-kernel crappy way.
308 #define SOL_PACKET 263
309 #endif
311 #define MAX_LINKHEADER_SIZE 256
314 * When capturing on all interfaces we use this as the buffer size.
315 * Should be bigger then all MTUs that occur in real life.
316 * 64kB should be enough for now.
318 #define BIGGER_THAN_ALL_MTUS (64*1024)
321 * Prototypes for internal functions and methods.
323 static void map_arphrd_to_dlt(pcap_t *, int, int);
324 #ifdef HAVE_PF_PACKET_SOCKETS
325 static short int map_packet_type_to_sll_type(short int);
326 #endif
327 static int pcap_activate_linux(pcap_t *);
328 static int activate_old(pcap_t *);
329 static int activate_new(pcap_t *);
330 static int activate_mmap(pcap_t *, int *);
331 static int pcap_can_set_rfmon_linux(pcap_t *);
332 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
333 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
334 static int pcap_inject_linux(pcap_t *, const void *, size_t);
335 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
336 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
337 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
338 static void pcap_cleanup_linux(pcap_t *);
340 union thdr {
341 struct tpacket_hdr *h1;
342 struct tpacket2_hdr *h2;
343 void *raw;
346 #ifdef HAVE_PACKET_RING
347 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
349 static void destroy_ring(pcap_t *handle);
350 static int create_ring(pcap_t *handle, int *status);
351 static int prepare_tpacket_socket(pcap_t *handle);
352 static void pcap_cleanup_linux_mmap(pcap_t *);
353 static int pcap_read_linux_mmap(pcap_t *, int, pcap_handler , u_char *);
354 static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
355 static int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
356 static int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
357 static void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
358 const u_char *bytes);
359 #endif
362 * Wrap some ioctl calls
364 #ifdef HAVE_PF_PACKET_SOCKETS
365 static int iface_get_id(int fd, const char *device, char *ebuf);
366 #endif /* HAVE_PF_PACKET_SOCKETS */
367 static int iface_get_mtu(int fd, const char *device, char *ebuf);
368 static int iface_get_arptype(int fd, const char *device, char *ebuf);
369 #ifdef HAVE_PF_PACKET_SOCKETS
370 static int iface_bind(int fd, int ifindex, char *ebuf);
371 #ifdef IW_MODE_MONITOR
372 static int has_wext(int sock_fd, const char *device, char *ebuf);
373 #endif /* IW_MODE_MONITOR */
374 static int enter_rfmon_mode(pcap_t *handle, int sock_fd,
375 const char *device);
376 #endif /* HAVE_PF_PACKET_SOCKETS */
377 static int iface_get_offload(pcap_t *handle);
378 static int iface_bind_old(int fd, const char *device, char *ebuf);
380 #ifdef SO_ATTACH_FILTER
381 static int fix_program(pcap_t *handle, struct sock_fprog *fcode,
382 int is_mapped);
383 static int fix_offset(struct bpf_insn *p);
384 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
385 static int reset_kernel_filter(pcap_t *handle);
387 static struct sock_filter total_insn
388 = BPF_STMT(BPF_RET | BPF_K, 0);
389 static struct sock_fprog total_fcode
390 = { 1, &total_insn };
391 #endif /* SO_ATTACH_FILTER */
393 pcap_t *
394 pcap_create(const char *device, char *ebuf)
396 pcap_t *handle;
399 * A null device name is equivalent to the "any" device.
401 if (device == NULL)
402 device = "any";
404 #ifdef HAVE_DAG_API
405 if (strstr(device, "dag")) {
406 return dag_create(device, ebuf);
408 #endif /* HAVE_DAG_API */
410 #ifdef HAVE_SEPTEL_API
411 if (strstr(device, "septel")) {
412 return septel_create(device, ebuf);
414 #endif /* HAVE_SEPTEL_API */
416 #ifdef HAVE_SNF_API
417 handle = snf_create(device, ebuf);
418 if (strstr(device, "snf") || handle != NULL)
419 return handle;
421 #endif /* HAVE_SNF_API */
423 #ifdef PCAP_SUPPORT_BT
424 if (strstr(device, "bluetooth")) {
425 return bt_create(device, ebuf);
427 #endif
429 #if PCAP_SUPPORT_CANUSB
430 if (strstr(device, "canusb")) {
431 return canusb_create(device, ebuf);
433 #endif
435 #ifdef PCAP_SUPPORT_CAN
436 if ((strncmp(device, "can", 3) == 0 && isdigit(device[3])) ||
437 (strncmp(device, "vcan", 4) == 0 && isdigit(device[4]))) {
438 return can_create(device, ebuf);
440 #endif
442 #ifdef PCAP_SUPPORT_USB
443 if (strstr(device, "usbmon")) {
444 return usb_create(device, ebuf);
446 #endif
448 #ifdef PCAP_SUPPORT_NETFILTER
449 if (strncmp(device, "nflog", strlen("nflog")) == 0) {
450 return nflog_create(device, ebuf);
452 #endif
454 handle = pcap_create_common(device, ebuf);
455 if (handle == NULL)
456 return NULL;
458 handle->activate_op = pcap_activate_linux;
459 handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
460 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
462 * We claim that we support:
464 * software time stamps, with no details about their precision;
465 * hardware time stamps, synced to the host time;
466 * hardware time stamps, not synced to the host time.
468 * XXX - we can't ask a device whether it supports
469 * hardware time stamps, so we just claim all devices do.
471 handle->tstamp_type_count = 3;
472 handle->tstamp_type_list = malloc(3 * sizeof(u_int));
473 if (handle->tstamp_type_list == NULL) {
474 free(handle);
475 return NULL;
477 handle->tstamp_type_list[0] = PCAP_TSTAMP_HOST;
478 handle->tstamp_type_list[1] = PCAP_TSTAMP_ADAPTER;
479 handle->tstamp_type_list[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED;
480 #endif
482 return handle;
485 #ifdef HAVE_LIBNL
487 * If interface {if} is a mac80211 driver, the file
488 * /sys/class/net/{if}/phy80211 is a symlink to
489 * /sys/class/ieee80211/{phydev}, for some {phydev}.
491 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
492 * least, has a "wmaster0" device and a "wlan0" device; the
493 * latter is the one with the IP address. Both show up in
494 * "tcpdump -D" output. Capturing on the wmaster0 device
495 * captures with 802.11 headers.
497 * airmon-ng searches through /sys/class/net for devices named
498 * monN, starting with mon0; as soon as one *doesn't* exist,
499 * it chooses that as the monitor device name. If the "iw"
500 * command exists, it does "iw dev {if} interface add {monif}
501 * type monitor", where {monif} is the monitor device. It
502 * then (sigh) sleeps .1 second, and then configures the
503 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
504 * is a file, it writes {mondev}, without a newline, to that file,
505 * and again (sigh) sleeps .1 second, and then iwconfig's that
506 * device into monitor mode and configures it up. Otherwise,
507 * you can't do monitor mode.
509 * All these devices are "glued" together by having the
510 * /sys/class/net/{device}/phy80211 links pointing to the same
511 * place, so, given a wmaster, wlan, or mon device, you can
512 * find the other devices by looking for devices with
513 * the same phy80211 link.
515 * To turn monitor mode off, delete the monitor interface,
516 * either with "iw dev {monif} interface del" or by sending
517 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
519 * Note: if you try to create a monitor device named "monN", and
520 * there's already a "monN" device, it fails, as least with
521 * the netlink interface (which is what iw uses), with a return
522 * value of -ENFILE. (Return values are negative errnos.) We
523 * could probably use that to find an unused device.
525 * Yes, you can have multiple monitor devices for a given
526 * physical device.
530 * Is this a mac80211 device? If so, fill in the physical device path and
531 * return 1; if not, return 0. On an error, fill in handle->errbuf and
532 * return PCAP_ERROR.
534 static int
535 get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
536 size_t phydev_max_pathlen)
538 char *pathstr;
539 ssize_t bytes_read;
542 * Generate the path string for the symlink to the physical device.
544 if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
545 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
546 "%s: Can't generate path name string for /sys/class/net device",
547 device);
548 return PCAP_ERROR;
550 bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
551 if (bytes_read == -1) {
552 if (errno == ENOENT || errno == EINVAL) {
554 * Doesn't exist, or not a symlink; assume that
555 * means it's not a mac80211 device.
557 free(pathstr);
558 return 0;
560 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
561 "%s: Can't readlink %s: %s", device, pathstr,
562 strerror(errno));
563 free(pathstr);
564 return PCAP_ERROR;
566 free(pathstr);
567 phydev_path[bytes_read] = '\0';
568 return 1;
571 #ifdef HAVE_LIBNL_2_x
572 #define get_nl_errmsg nl_geterror
573 #else
574 /* libnl 2.x compatibility code */
576 #define nl_sock nl_handle
578 static inline struct nl_handle *
579 nl_socket_alloc(void)
581 return nl_handle_alloc();
584 static inline void
585 nl_socket_free(struct nl_handle *h)
587 nl_handle_destroy(h);
590 #define get_nl_errmsg strerror
592 static inline int
593 __genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
595 struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
596 if (!tmp)
597 return -ENOMEM;
598 *cache = tmp;
599 return 0;
601 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
602 #endif /* !HAVE_LIBNL_2_x */
604 struct nl80211_state {
605 struct nl_sock *nl_sock;
606 struct nl_cache *nl_cache;
607 struct genl_family *nl80211;
610 static int
611 nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
613 int err;
615 state->nl_sock = nl_socket_alloc();
616 if (!state->nl_sock) {
617 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
618 "%s: failed to allocate netlink handle", device);
619 return PCAP_ERROR;
622 if (genl_connect(state->nl_sock)) {
623 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
624 "%s: failed to connect to generic netlink", device);
625 goto out_handle_destroy;
628 err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
629 if (err < 0) {
630 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
631 "%s: failed to allocate generic netlink cache: %s",
632 device, get_nl_errmsg(-err));
633 goto out_handle_destroy;
636 state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
637 if (!state->nl80211) {
638 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
639 "%s: nl80211 not found", device);
640 goto out_cache_free;
643 return 0;
645 out_cache_free:
646 nl_cache_free(state->nl_cache);
647 out_handle_destroy:
648 nl_socket_free(state->nl_sock);
649 return PCAP_ERROR;
652 static void
653 nl80211_cleanup(struct nl80211_state *state)
655 genl_family_put(state->nl80211);
656 nl_cache_free(state->nl_cache);
657 nl_socket_free(state->nl_sock);
660 static int
661 add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
662 const char *device, const char *mondevice)
664 int ifindex;
665 struct nl_msg *msg;
666 int err;
668 ifindex = iface_get_id(sock_fd, device, handle->errbuf);
669 if (ifindex == -1)
670 return PCAP_ERROR;
672 msg = nlmsg_alloc();
673 if (!msg) {
674 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
675 "%s: failed to allocate netlink msg", device);
676 return PCAP_ERROR;
679 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
680 0, NL80211_CMD_NEW_INTERFACE, 0);
681 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
682 NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
683 NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
685 err = nl_send_auto_complete(state->nl_sock, msg);
686 if (err < 0) {
687 #ifdef HAVE_LIBNL_2_x
688 if (err == -NLE_FAILURE) {
689 #else
690 if (err == -ENFILE) {
691 #endif
693 * Device not available; our caller should just
694 * keep trying. (libnl 2.x maps ENFILE to
695 * NLE_FAILURE; it can also map other errors
696 * to that, but there's not much we can do
697 * about that.)
699 nlmsg_free(msg);
700 return 0;
701 } else {
703 * Real failure, not just "that device is not
704 * available.
706 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
707 "%s: nl_send_auto_complete failed adding %s interface: %s",
708 device, mondevice, get_nl_errmsg(-err));
709 nlmsg_free(msg);
710 return PCAP_ERROR;
713 err = nl_wait_for_ack(state->nl_sock);
714 if (err < 0) {
715 #ifdef HAVE_LIBNL_2_x
716 if (err == -NLE_FAILURE) {
717 #else
718 if (err == -ENFILE) {
719 #endif
721 * Device not available; our caller should just
722 * keep trying. (libnl 2.x maps ENFILE to
723 * NLE_FAILURE; it can also map other errors
724 * to that, but there's not much we can do
725 * about that.)
727 nlmsg_free(msg);
728 return 0;
729 } else {
731 * Real failure, not just "that device is not
732 * available.
734 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
735 "%s: nl_wait_for_ack failed adding %s interface: %s",
736 device, mondevice, get_nl_errmsg(-err));
737 nlmsg_free(msg);
738 return PCAP_ERROR;
743 * Success.
745 nlmsg_free(msg);
746 return 1;
748 nla_put_failure:
749 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
750 "%s: nl_put failed adding %s interface",
751 device, mondevice);
752 nlmsg_free(msg);
753 return PCAP_ERROR;
756 static int
757 del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
758 const char *device, const char *mondevice)
760 int ifindex;
761 struct nl_msg *msg;
762 int err;
764 ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
765 if (ifindex == -1)
766 return PCAP_ERROR;
768 msg = nlmsg_alloc();
769 if (!msg) {
770 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
771 "%s: failed to allocate netlink msg", device);
772 return PCAP_ERROR;
775 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
776 0, NL80211_CMD_DEL_INTERFACE, 0);
777 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
779 err = nl_send_auto_complete(state->nl_sock, msg);
780 if (err < 0) {
781 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
782 "%s: nl_send_auto_complete failed deleting %s interface: %s",
783 device, mondevice, get_nl_errmsg(-err));
784 nlmsg_free(msg);
785 return PCAP_ERROR;
787 err = nl_wait_for_ack(state->nl_sock);
788 if (err < 0) {
789 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
790 "%s: nl_wait_for_ack failed adding %s interface: %s",
791 device, mondevice, get_nl_errmsg(-err));
792 nlmsg_free(msg);
793 return PCAP_ERROR;
797 * Success.
799 nlmsg_free(msg);
800 return 1;
802 nla_put_failure:
803 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
804 "%s: nl_put failed deleting %s interface",
805 device, mondevice);
806 nlmsg_free(msg);
807 return PCAP_ERROR;
810 static int
811 enter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
813 int ret;
814 char phydev_path[PATH_MAX+1];
815 struct nl80211_state nlstate;
816 struct ifreq ifr;
817 u_int n;
820 * Is this a mac80211 device?
822 ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
823 if (ret < 0)
824 return ret; /* error */
825 if (ret == 0)
826 return 0; /* no error, but not mac80211 device */
829 * XXX - is this already a monN device?
830 * If so, we're done.
831 * Is that determined by old Wireless Extensions ioctls?
835 * OK, it's apparently a mac80211 device.
836 * Try to find an unused monN device for it.
838 ret = nl80211_init(handle, &nlstate, device);
839 if (ret != 0)
840 return ret;
841 for (n = 0; n < UINT_MAX; n++) {
843 * Try mon{n}.
845 char mondevice[3+10+1]; /* mon{UINT_MAX}\0 */
847 snprintf(mondevice, sizeof mondevice, "mon%u", n);
848 ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
849 if (ret == 1) {
850 handle->md.mondevice = strdup(mondevice);
851 goto added;
853 if (ret < 0) {
855 * Hard failure. Just return ret; handle->errbuf
856 * has already been set.
858 nl80211_cleanup(&nlstate);
859 return ret;
863 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
864 "%s: No free monN interfaces", device);
865 nl80211_cleanup(&nlstate);
866 return PCAP_ERROR;
868 added:
870 #if 0
872 * Sleep for .1 seconds.
874 delay.tv_sec = 0;
875 delay.tv_nsec = 500000000;
876 nanosleep(&delay, NULL);
877 #endif
880 * If we haven't already done so, arrange to have
881 * "pcap_close_all()" called when we exit.
883 if (!pcap_do_addexit(handle)) {
885 * "atexit()" failed; don't put the interface
886 * in rfmon mode, just give up.
888 return PCAP_ERROR_RFMON_NOTSUP;
892 * Now configure the monitor interface up.
894 memset(&ifr, 0, sizeof(ifr));
895 strncpy(ifr.ifr_name, handle->md.mondevice, sizeof(ifr.ifr_name));
896 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
897 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
898 "%s: Can't get flags for %s: %s", device,
899 handle->md.mondevice, strerror(errno));
900 del_mon_if(handle, sock_fd, &nlstate, device,
901 handle->md.mondevice);
902 nl80211_cleanup(&nlstate);
903 return PCAP_ERROR;
905 ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
906 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
907 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
908 "%s: Can't set flags for %s: %s", device,
909 handle->md.mondevice, strerror(errno));
910 del_mon_if(handle, sock_fd, &nlstate, device,
911 handle->md.mondevice);
912 nl80211_cleanup(&nlstate);
913 return PCAP_ERROR;
917 * Success. Clean up the libnl state.
919 nl80211_cleanup(&nlstate);
922 * Note that we have to delete the monitor device when we close
923 * the handle.
925 handle->md.must_do_on_close |= MUST_DELETE_MONIF;
928 * Add this to the list of pcaps to close when we exit.
930 pcap_add_to_pcaps_to_close(handle);
932 return 1;
934 #endif /* HAVE_LIBNL */
936 static int
937 pcap_can_set_rfmon_linux(pcap_t *handle)
939 #ifdef HAVE_LIBNL
940 char phydev_path[PATH_MAX+1];
941 int ret;
942 #endif
943 #ifdef IW_MODE_MONITOR
944 int sock_fd; struct iwreq ireq;
945 #endif
947 if (strcmp(handle->opt.source, "any") == 0) {
949 * Monitor mode makes no sense on the "any" device.
951 return 0;
954 #ifdef HAVE_LIBNL
956 * Bleah. There doesn't seem to be a way to ask a mac80211
957 * device, through libnl, whether it supports monitor mode;
958 * we'll just check whether the device appears to be a
959 * mac80211 device and, if so, assume the device supports
960 * monitor mode.
962 * wmaster devices don't appear to support the Wireless
963 * Extensions, but we can create a mon device for a
964 * wmaster device, so we don't bother checking whether
965 * a mac80211 device supports the Wireless Extensions.
967 ret = get_mac80211_phydev(handle, handle->opt.source, phydev_path,
968 PATH_MAX);
969 if (ret < 0)
970 return ret; /* error */
971 if (ret == 1)
972 return 1; /* mac80211 device */
973 #endif
975 #ifdef IW_MODE_MONITOR
977 * Bleah. There doesn't appear to be an ioctl to use to ask
978 * whether a device supports monitor mode; we'll just do
979 * SIOCGIWMODE and, if it succeeds, assume the device supports
980 * monitor mode.
982 * Open a socket on which to attempt to get the mode.
983 * (We assume that if we have Wireless Extensions support
984 * we also have PF_PACKET support.)
986 sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
987 if (sock_fd == -1) {
988 (void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
989 "socket: %s", pcap_strerror(errno));
990 return PCAP_ERROR;
994 * Attempt to get the current mode.
996 strncpy(ireq.ifr_ifrn.ifrn_name, handle->opt.source,
997 sizeof ireq.ifr_ifrn.ifrn_name);
998 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
999 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
1001 * Well, we got the mode; assume we can set it.
1003 close(sock_fd);
1004 return 1;
1006 if (errno == ENODEV) {
1007 /* The device doesn't even exist. */
1008 (void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1009 "SIOCGIWMODE failed: %s", pcap_strerror(errno));
1010 close(sock_fd);
1011 return PCAP_ERROR_NO_SUCH_DEVICE;
1013 close(sock_fd);
1014 #endif
1015 return 0;
1019 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1021 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1022 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1024 * Or can we get them in binary form from netlink?
1026 static long int
1027 linux_if_drops(const char * if_name)
1029 char buffer[512];
1030 char * bufptr;
1031 FILE * file;
1032 int field_to_convert = 3, if_name_sz = strlen(if_name);
1033 long int dropped_pkts = 0;
1035 file = fopen("/proc/net/dev", "r");
1036 if (!file)
1037 return 0;
1039 while (!dropped_pkts && fgets( buffer, sizeof(buffer), file ))
1041 /* search for 'bytes' -- if its in there, then
1042 that means we need to grab the fourth field. otherwise
1043 grab the third field. */
1044 if (field_to_convert != 4 && strstr(buffer, "bytes"))
1046 field_to_convert = 4;
1047 continue;
1050 /* find iface and make sure it actually matches -- space before the name and : after it */
1051 if ((bufptr = strstr(buffer, if_name)) &&
1052 (bufptr == buffer || *(bufptr-1) == ' ') &&
1053 *(bufptr + if_name_sz) == ':')
1055 bufptr = bufptr + if_name_sz + 1;
1057 /* grab the nth field from it */
1058 while( --field_to_convert && *bufptr != '\0')
1060 while (*bufptr != '\0' && *(bufptr++) == ' ');
1061 while (*bufptr != '\0' && *(bufptr++) != ' ');
1064 /* get rid of any final spaces */
1065 while (*bufptr != '\0' && *bufptr == ' ') bufptr++;
1067 if (*bufptr != '\0')
1068 dropped_pkts = strtol(bufptr, NULL, 10);
1070 break;
1074 fclose(file);
1075 return dropped_pkts;
1080 * With older kernels promiscuous mode is kind of interesting because we
1081 * have to reset the interface before exiting. The problem can't really
1082 * be solved without some daemon taking care of managing usage counts.
1083 * If we put the interface into promiscuous mode, we set a flag indicating
1084 * that we must take it out of that mode when the interface is closed,
1085 * and, when closing the interface, if that flag is set we take it out
1086 * of promiscuous mode.
1088 * Even with newer kernels, we have the same issue with rfmon mode.
1091 static void pcap_cleanup_linux( pcap_t *handle )
1093 struct ifreq ifr;
1094 #ifdef HAVE_LIBNL
1095 struct nl80211_state nlstate;
1096 int ret;
1097 #endif /* HAVE_LIBNL */
1098 #ifdef IW_MODE_MONITOR
1099 int oldflags;
1100 struct iwreq ireq;
1101 #endif /* IW_MODE_MONITOR */
1103 if (handle->md.must_do_on_close != 0) {
1105 * There's something we have to do when closing this
1106 * pcap_t.
1108 if (handle->md.must_do_on_close & MUST_CLEAR_PROMISC) {
1110 * We put the interface into promiscuous mode;
1111 * take it out of promiscuous mode.
1113 * XXX - if somebody else wants it in promiscuous
1114 * mode, this code cannot know that, so it'll take
1115 * it out of promiscuous mode. That's not fixable
1116 * in 2.0[.x] kernels.
1118 memset(&ifr, 0, sizeof(ifr));
1119 strncpy(ifr.ifr_name, handle->md.device,
1120 sizeof(ifr.ifr_name));
1121 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1122 fprintf(stderr,
1123 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1124 "Please adjust manually.\n"
1125 "Hint: This can't happen with Linux >= 2.2.0.\n",
1126 handle->md.device, strerror(errno));
1127 } else {
1128 if (ifr.ifr_flags & IFF_PROMISC) {
1130 * Promiscuous mode is currently on;
1131 * turn it off.
1133 ifr.ifr_flags &= ~IFF_PROMISC;
1134 if (ioctl(handle->fd, SIOCSIFFLAGS,
1135 &ifr) == -1) {
1136 fprintf(stderr,
1137 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1138 "Please adjust manually.\n"
1139 "Hint: This can't happen with Linux >= 2.2.0.\n",
1140 handle->md.device,
1141 strerror(errno));
1147 #ifdef HAVE_LIBNL
1148 if (handle->md.must_do_on_close & MUST_DELETE_MONIF) {
1149 ret = nl80211_init(handle, &nlstate, handle->md.device);
1150 if (ret >= 0) {
1151 ret = del_mon_if(handle, handle->fd, &nlstate,
1152 handle->md.device, handle->md.mondevice);
1153 nl80211_cleanup(&nlstate);
1155 if (ret < 0) {
1156 fprintf(stderr,
1157 "Can't delete monitor interface %s (%s).\n"
1158 "Please delete manually.\n",
1159 handle->md.mondevice, handle->errbuf);
1162 #endif /* HAVE_LIBNL */
1164 #ifdef IW_MODE_MONITOR
1165 if (handle->md.must_do_on_close & MUST_CLEAR_RFMON) {
1167 * We put the interface into rfmon mode;
1168 * take it out of rfmon mode.
1170 * XXX - if somebody else wants it in rfmon
1171 * mode, this code cannot know that, so it'll take
1172 * it out of rfmon mode.
1176 * First, take the interface down if it's up;
1177 * otherwise, we might get EBUSY.
1178 * If we get errors, just drive on and print
1179 * a warning if we can't restore the mode.
1181 oldflags = 0;
1182 memset(&ifr, 0, sizeof(ifr));
1183 strncpy(ifr.ifr_name, handle->md.device,
1184 sizeof(ifr.ifr_name));
1185 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
1186 if (ifr.ifr_flags & IFF_UP) {
1187 oldflags = ifr.ifr_flags;
1188 ifr.ifr_flags &= ~IFF_UP;
1189 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
1190 oldflags = 0; /* didn't set, don't restore */
1195 * Now restore the mode.
1197 strncpy(ireq.ifr_ifrn.ifrn_name, handle->md.device,
1198 sizeof ireq.ifr_ifrn.ifrn_name);
1199 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1]
1200 = 0;
1201 ireq.u.mode = handle->md.oldmode;
1202 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
1204 * Scientist, you've failed.
1206 fprintf(stderr,
1207 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1208 "Please adjust manually.\n",
1209 handle->md.device, strerror(errno));
1213 * Now bring the interface back up if we brought
1214 * it down.
1216 if (oldflags != 0) {
1217 ifr.ifr_flags = oldflags;
1218 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1219 fprintf(stderr,
1220 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1221 "Please adjust manually.\n",
1222 handle->md.device, strerror(errno));
1226 #endif /* IW_MODE_MONITOR */
1229 * Take this pcap out of the list of pcaps for which we
1230 * have to take the interface out of some mode.
1232 pcap_remove_from_pcaps_to_close(handle);
1235 if (handle->md.mondevice != NULL) {
1236 free(handle->md.mondevice);
1237 handle->md.mondevice = NULL;
1239 if (handle->md.device != NULL) {
1240 free(handle->md.device);
1241 handle->md.device = NULL;
1243 pcap_cleanup_live_common(handle);
1247 * Get a handle for a live capture from the given device. You can
1248 * pass NULL as device to get all packages (without link level
1249 * information of course). If you pass 1 as promisc the interface
1250 * will be set to promiscous mode (XXX: I think this usage should
1251 * be deprecated and functions be added to select that later allow
1252 * modification of that values -- Torsten).
1254 static int
1255 pcap_activate_linux(pcap_t *handle)
1257 const char *device;
1258 int status = 0;
1261 #ifdef HAVE_REMOTE
1262 char host[PCAP_BUF_SIZE + 1];
1263 char port[PCAP_BUF_SIZE + 1];
1264 char name[PCAP_BUF_SIZE + 1];
1265 int srctype;
1266 int opensource_remote_result;
1269 Retrofit; we have to make older applications compatible with the remote capture
1270 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
1271 Obviously, we cannot exploit all the new features; for instance, we cannot
1272 send authentication, we cannot use a UDP data connection, and so on.
1274 if (pcap_parsesrcstr(handle->opt.source, &srctype, host, port, name, handle->errbuf) )
1275 return PCAP_ERROR;
1277 if (srctype == PCAP_SRC_IFREMOTE)
1279 opensource_remote_result = pcap_opensource_remote(handle, NULL);
1281 if (opensource_remote_result != 0)
1282 return opensource_remote_result;
1284 handle->rmt_flags= (handle->opt.promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0;
1286 return 0;
1289 if (srctype == PCAP_SRC_IFLOCAL)
1292 * If it starts with rpcap://, cut down the string
1294 if (strncmp(handle->opt.source, PCAP_SRC_IF_STRING, strlen(PCAP_SRC_IF_STRING)) == 0)
1296 size_t len = strlen(handle->opt.source) - strlen(PCAP_SRC_IF_STRING) + 1;
1297 char *new_string;
1299 allocate a new string and free the old one
1301 if (len > 0)
1303 new_string = (char*)malloc(len);
1304 if (new_string != NULL)
1306 char *tmp;
1307 strcpy(new_string, handle->opt.source + strlen(PCAP_SRC_IF_STRING));
1308 tmp = handle->opt.source;
1309 handle->opt.source = new_string;
1310 free(tmp);
1316 #endif /* HAVE_REMOTE */
1318 device = handle->opt.source;
1320 handle->inject_op = pcap_inject_linux;
1321 handle->setfilter_op = pcap_setfilter_linux;
1322 handle->setdirection_op = pcap_setdirection_linux;
1323 handle->set_datalink_op = NULL; /* can't change data link type */
1324 handle->getnonblock_op = pcap_getnonblock_fd;
1325 handle->setnonblock_op = pcap_setnonblock_fd;
1326 handle->cleanup_op = pcap_cleanup_linux;
1327 handle->read_op = pcap_read_linux;
1328 handle->stats_op = pcap_stats_linux;
1331 * The "any" device is a special device which causes us not
1332 * to bind to a particular device and thus to look at all
1333 * devices.
1335 if (strcmp(device, "any") == 0) {
1336 if (handle->opt.promisc) {
1337 handle->opt.promisc = 0;
1338 /* Just a warning. */
1339 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1340 "Promiscuous mode not supported on the \"any\" device");
1341 status = PCAP_WARNING_PROMISC_NOTSUP;
1345 handle->md.device = strdup(device);
1346 if (handle->md.device == NULL) {
1347 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1348 pcap_strerror(errno) );
1349 return PCAP_ERROR;
1353 * If we're in promiscuous mode, then we probably want
1354 * to see when the interface drops packets too, so get an
1355 * initial count from /proc/net/dev
1357 if (handle->opt.promisc)
1358 handle->md.proc_dropped = linux_if_drops(handle->md.device);
1361 * Current Linux kernels use the protocol family PF_PACKET to
1362 * allow direct access to all packets on the network while
1363 * older kernels had a special socket type SOCK_PACKET to
1364 * implement this feature.
1365 * While this old implementation is kind of obsolete we need
1366 * to be compatible with older kernels for a while so we are
1367 * trying both methods with the newer method preferred.
1369 status = activate_new(handle);
1370 if (status < 0) {
1372 * Fatal error with the new way; just fail.
1373 * status has the error return; if it's PCAP_ERROR,
1374 * handle->errbuf has been set appropriately.
1376 goto fail;
1378 if (status == 1) {
1380 * Success.
1381 * Try to use memory-mapped access.
1383 switch (activate_mmap(handle, &status)) {
1385 case 1:
1387 * We succeeded. status has been
1388 * set to the status to return,
1389 * which might be 0, or might be
1390 * a PCAP_WARNING_ value.
1392 return status;
1394 case 0:
1396 * Kernel doesn't support it - just continue
1397 * with non-memory-mapped access.
1399 break;
1401 case -1:
1403 * We failed to set up to use it, or the kernel
1404 * supports it, but we failed to enable it.
1405 * status has been set to the error status to
1406 * return and, if it's PCAP_ERROR, handle->errbuf
1407 * contains the error message.
1409 goto fail;
1412 else if (status == 0) {
1413 /* Non-fatal error; try old way */
1414 if ((status = activate_old(handle)) != 1) {
1416 * Both methods to open the packet socket failed.
1417 * Tidy up and report our failure (handle->errbuf
1418 * is expected to be set by the functions above).
1420 goto fail;
1425 * We set up the socket, but not with memory-mapped access.
1427 status = 0;
1428 if (handle->opt.buffer_size != 0) {
1430 * Set the socket buffer size to the specified value.
1432 if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
1433 &handle->opt.buffer_size,
1434 sizeof(handle->opt.buffer_size)) == -1) {
1435 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1436 "SO_RCVBUF: %s", pcap_strerror(errno));
1437 status = PCAP_ERROR;
1438 goto fail;
1442 /* Allocate the buffer */
1444 handle->buffer = malloc(handle->bufsize + handle->offset);
1445 if (!handle->buffer) {
1446 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1447 "malloc: %s", pcap_strerror(errno));
1448 status = PCAP_ERROR;
1449 goto fail;
1453 * "handle->fd" is a socket, so "select()" and "poll()"
1454 * should work on it.
1456 handle->selectable_fd = handle->fd;
1458 return status;
1460 fail:
1461 pcap_cleanup_linux(handle);
1462 return status;
1466 * Read at most max_packets from the capture stream and call the callback
1467 * for each of them. Returns the number of packets handled or -1 if an
1468 * error occured.
1470 static int
1471 pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1474 * Currently, on Linux only one packet is delivered per read,
1475 * so we don't loop.
1477 return pcap_read_packet(handle, callback, user);
1481 * Read a packet from the socket calling the handler provided by
1482 * the user. Returns the number of packets received or -1 if an
1483 * error occured.
1485 static int
1486 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
1488 u_char *bp;
1489 int offset;
1490 #ifdef HAVE_PF_PACKET_SOCKETS
1491 struct sockaddr_ll from;
1492 struct sll_header *hdrp;
1493 #else
1494 struct sockaddr from;
1495 #endif
1496 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1497 struct iovec iov;
1498 struct msghdr msg;
1499 struct cmsghdr *cmsg;
1500 union {
1501 struct cmsghdr cmsg;
1502 char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
1503 } cmsg_buf;
1504 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1505 socklen_t fromlen;
1506 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1507 int packet_len, caplen;
1508 struct pcap_pkthdr pcap_header;
1510 #ifdef HAVE_PF_PACKET_SOCKETS
1512 * If this is a cooked device, leave extra room for a
1513 * fake packet header.
1515 if (handle->md.cooked)
1516 offset = SLL_HDR_LEN;
1517 else
1518 offset = 0;
1519 #else
1521 * This system doesn't have PF_PACKET sockets, so it doesn't
1522 * support cooked devices.
1524 offset = 0;
1525 #endif
1528 * Receive a single packet from the kernel.
1529 * We ignore EINTR, as that might just be due to a signal
1530 * being delivered - if the signal should interrupt the
1531 * loop, the signal handler should call pcap_breakloop()
1532 * to set handle->break_loop (we ignore it on other
1533 * platforms as well).
1534 * We also ignore ENETDOWN, so that we can continue to
1535 * capture traffic if the interface goes down and comes
1536 * back up again; comments in the kernel indicate that
1537 * we'll just block waiting for packets if we try to
1538 * receive from a socket that delivered ENETDOWN, and,
1539 * if we're using a memory-mapped buffer, we won't even
1540 * get notified of "network down" events.
1542 bp = handle->buffer + handle->offset;
1544 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1545 msg.msg_name = &from;
1546 msg.msg_namelen = sizeof(from);
1547 msg.msg_iov = &iov;
1548 msg.msg_iovlen = 1;
1549 msg.msg_control = &cmsg_buf;
1550 msg.msg_controllen = sizeof(cmsg_buf);
1551 msg.msg_flags = 0;
1553 iov.iov_len = handle->bufsize - offset;
1554 iov.iov_base = bp + offset;
1555 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1557 do {
1559 * Has "pcap_breakloop()" been called?
1561 if (handle->break_loop) {
1563 * Yes - clear the flag that indicates that it has,
1564 * and return PCAP_ERROR_BREAK as an indication that
1565 * we were told to break out of the loop.
1567 handle->break_loop = 0;
1568 return PCAP_ERROR_BREAK;
1571 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1572 packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
1573 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1574 fromlen = sizeof(from);
1575 packet_len = recvfrom(
1576 handle->fd, bp + offset,
1577 handle->bufsize - offset, MSG_TRUNC,
1578 (struct sockaddr *) &from, &fromlen);
1579 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1580 } while (packet_len == -1 && errno == EINTR);
1582 /* Check if an error occured */
1584 if (packet_len == -1) {
1585 switch (errno) {
1587 case EAGAIN:
1588 return 0; /* no packet there */
1590 case ENETDOWN:
1592 * The device on which we're capturing went away.
1594 * XXX - we should really return
1595 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1596 * etc. aren't defined to return that.
1598 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1599 "The interface went down");
1600 return PCAP_ERROR;
1602 default:
1603 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1604 "recvfrom: %s", pcap_strerror(errno));
1605 return PCAP_ERROR;
1609 #ifdef HAVE_PF_PACKET_SOCKETS
1610 if (!handle->md.sock_packet) {
1612 * Unfortunately, there is a window between socket() and
1613 * bind() where the kernel may queue packets from any
1614 * interface. If we're bound to a particular interface,
1615 * discard packets not from that interface.
1617 * (If socket filters are supported, we could do the
1618 * same thing we do when changing the filter; however,
1619 * that won't handle packet sockets without socket
1620 * filter support, and it's a bit more complicated.
1621 * It would save some instructions per packet, however.)
1623 if (handle->md.ifindex != -1 &&
1624 from.sll_ifindex != handle->md.ifindex)
1625 return 0;
1628 * Do checks based on packet direction.
1629 * We can only do this if we're using PF_PACKET; the
1630 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1631 * which lacks the relevant packet type information.
1633 if (from.sll_pkttype == PACKET_OUTGOING) {
1635 * Outgoing packet.
1636 * If this is from the loopback device, reject it;
1637 * we'll see the packet as an incoming packet as well,
1638 * and we don't want to see it twice.
1640 if (from.sll_ifindex == handle->md.lo_ifindex)
1641 return 0;
1644 * If the user only wants incoming packets, reject it.
1646 if (handle->direction == PCAP_D_IN)
1647 return 0;
1648 } else {
1650 * Incoming packet.
1651 * If the user only wants outgoing packets, reject it.
1653 if (handle->direction == PCAP_D_OUT)
1654 return 0;
1657 #endif
1659 #ifdef HAVE_PF_PACKET_SOCKETS
1661 * If this is a cooked device, fill in the fake packet header.
1663 if (handle->md.cooked) {
1665 * Add the length of the fake header to the length
1666 * of packet data we read.
1668 packet_len += SLL_HDR_LEN;
1670 hdrp = (struct sll_header *)bp;
1671 hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
1672 hdrp->sll_hatype = htons(from.sll_hatype);
1673 hdrp->sll_halen = htons(from.sll_halen);
1674 memcpy(hdrp->sll_addr, from.sll_addr,
1675 (from.sll_halen > SLL_ADDRLEN) ?
1676 SLL_ADDRLEN :
1677 from.sll_halen);
1678 hdrp->sll_protocol = from.sll_protocol;
1681 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1682 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1683 struct tpacket_auxdata *aux;
1684 unsigned int len;
1685 struct vlan_tag *tag;
1687 if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
1688 cmsg->cmsg_level != SOL_PACKET ||
1689 cmsg->cmsg_type != PACKET_AUXDATA)
1690 continue;
1692 aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
1693 if (aux->tp_vlan_tci == 0)
1694 continue;
1696 len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
1697 if (len < 2 * ETH_ALEN)
1698 break;
1700 bp -= VLAN_TAG_LEN;
1701 memmove(bp, bp + VLAN_TAG_LEN, 2 * ETH_ALEN);
1703 tag = (struct vlan_tag *)(bp + 2 * ETH_ALEN);
1704 tag->vlan_tpid = htons(ETH_P_8021Q);
1705 tag->vlan_tci = htons(aux->tp_vlan_tci);
1707 packet_len += VLAN_TAG_LEN;
1709 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1710 #endif /* HAVE_PF_PACKET_SOCKETS */
1713 * XXX: According to the kernel source we should get the real
1714 * packet len if calling recvfrom with MSG_TRUNC set. It does
1715 * not seem to work here :(, but it is supported by this code
1716 * anyway.
1717 * To be honest the code RELIES on that feature so this is really
1718 * broken with 2.2.x kernels.
1719 * I spend a day to figure out what's going on and I found out
1720 * that the following is happening:
1722 * The packet comes from a random interface and the packet_rcv
1723 * hook is called with a clone of the packet. That code inserts
1724 * the packet into the receive queue of the packet socket.
1725 * If a filter is attached to that socket that filter is run
1726 * first - and there lies the problem. The default filter always
1727 * cuts the packet at the snaplen:
1729 * # tcpdump -d
1730 * (000) ret #68
1732 * So the packet filter cuts down the packet. The recvfrom call
1733 * says "hey, it's only 68 bytes, it fits into the buffer" with
1734 * the result that we don't get the real packet length. This
1735 * is valid at least until kernel 2.2.17pre6.
1737 * We currently handle this by making a copy of the filter
1738 * program, fixing all "ret" instructions with non-zero
1739 * operands to have an operand of 65535 so that the filter
1740 * doesn't truncate the packet, and supplying that modified
1741 * filter to the kernel.
1744 caplen = packet_len;
1745 if (caplen > handle->snapshot)
1746 caplen = handle->snapshot;
1748 /* Run the packet filter if not using kernel filter */
1749 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
1750 if (bpf_filter(handle->fcode.bf_insns, bp,
1751 packet_len, caplen) == 0)
1753 /* rejected by filter */
1754 return 0;
1758 /* Fill in our own header data */
1760 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
1761 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1762 "SIOCGSTAMP: %s", pcap_strerror(errno));
1763 return PCAP_ERROR;
1765 pcap_header.caplen = caplen;
1766 pcap_header.len = packet_len;
1769 * Count the packet.
1771 * Arguably, we should count them before we check the filter,
1772 * as on many other platforms "ps_recv" counts packets
1773 * handed to the filter rather than packets that passed
1774 * the filter, but if filtering is done in the kernel, we
1775 * can't get a count of packets that passed the filter,
1776 * and that would mean the meaning of "ps_recv" wouldn't
1777 * be the same on all Linux systems.
1779 * XXX - it's not the same on all systems in any case;
1780 * ideally, we should have a "get the statistics" call
1781 * that supplies more counts and indicates which of them
1782 * it supplies, so that we supply a count of packets
1783 * handed to the filter only on platforms where that
1784 * information is available.
1786 * We count them here even if we can get the packet count
1787 * from the kernel, as we can only determine at run time
1788 * whether we'll be able to get it from the kernel (if
1789 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1790 * the kernel, but if it is defined, the library might
1791 * have been built with a 2.4 or later kernel, but we
1792 * might be running on a 2.2[.x] kernel without Alexey
1793 * Kuznetzov's turbopacket patches, and thus the kernel
1794 * might not be able to supply those statistics). We
1795 * could, I guess, try, when opening the socket, to get
1796 * the statistics, and if we can not increment the count
1797 * here, but it's not clear that always incrementing
1798 * the count is more expensive than always testing a flag
1799 * in memory.
1801 * We keep the count in "md.packets_read", and use that for
1802 * "ps_recv" if we can't get the statistics from the kernel.
1803 * We do that because, if we *can* get the statistics from
1804 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1805 * as running counts, as reading the statistics from the
1806 * kernel resets the kernel statistics, and if we directly
1807 * increment "md.stat.ps_recv" here, that means it will
1808 * count packets *twice* on systems where we can get kernel
1809 * statistics - once here, and once in pcap_stats_linux().
1811 handle->md.packets_read++;
1813 /* Call the user supplied callback function */
1814 callback(userdata, &pcap_header, bp);
1816 return 1;
1819 static int
1820 pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
1822 int ret;
1824 #ifdef HAVE_PF_PACKET_SOCKETS
1825 if (!handle->md.sock_packet) {
1826 /* PF_PACKET socket */
1827 if (handle->md.ifindex == -1) {
1829 * We don't support sending on the "any" device.
1831 strlcpy(handle->errbuf,
1832 "Sending packets isn't supported on the \"any\" device",
1833 PCAP_ERRBUF_SIZE);
1834 return (-1);
1837 if (handle->md.cooked) {
1839 * We don't support sending on the "any" device.
1841 * XXX - how do you send on a bound cooked-mode
1842 * socket?
1843 * Is a "sendto()" required there?
1845 strlcpy(handle->errbuf,
1846 "Sending packets isn't supported in cooked mode",
1847 PCAP_ERRBUF_SIZE);
1848 return (-1);
1851 #endif
1853 ret = send(handle->fd, buf, size, 0);
1854 if (ret == -1) {
1855 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1856 pcap_strerror(errno));
1857 return (-1);
1859 return (ret);
1863 * Get the statistics for the given packet capture handle.
1864 * Reports the number of dropped packets iff the kernel supports
1865 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1866 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1867 * patches); otherwise, that information isn't available, and we lie
1868 * and report 0 as the count of dropped packets.
1870 static int
1871 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
1873 #ifdef HAVE_TPACKET_STATS
1874 struct tpacket_stats kstats;
1875 socklen_t len = sizeof (struct tpacket_stats);
1876 #endif
1878 long if_dropped = 0;
1881 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
1883 if (handle->opt.promisc)
1885 if_dropped = handle->md.proc_dropped;
1886 handle->md.proc_dropped = linux_if_drops(handle->md.device);
1887 handle->md.stat.ps_ifdrop += (handle->md.proc_dropped - if_dropped);
1890 #ifdef HAVE_TPACKET_STATS
1892 * Try to get the packet counts from the kernel.
1894 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
1895 &kstats, &len) > -1) {
1897 * On systems where the PACKET_STATISTICS "getsockopt()"
1898 * argument is supported on PF_PACKET sockets:
1900 * "ps_recv" counts only packets that *passed* the
1901 * filter, not packets that didn't pass the filter.
1902 * This includes packets later dropped because we
1903 * ran out of buffer space.
1905 * "ps_drop" counts packets dropped because we ran
1906 * out of buffer space. It doesn't count packets
1907 * dropped by the interface driver. It counts only
1908 * packets that passed the filter.
1910 * See above for ps_ifdrop.
1912 * Both statistics include packets not yet read from
1913 * the kernel by libpcap, and thus not yet seen by
1914 * the application.
1916 * In "linux/net/packet/af_packet.c", at least in the
1917 * 2.4.9 kernel, "tp_packets" is incremented for every
1918 * packet that passes the packet filter *and* is
1919 * successfully queued on the socket; "tp_drops" is
1920 * incremented for every packet dropped because there's
1921 * not enough free space in the socket buffer.
1923 * When the statistics are returned for a PACKET_STATISTICS
1924 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1925 * so that "tp_packets" counts all packets handed to
1926 * the PF_PACKET socket, including packets dropped because
1927 * there wasn't room on the socket buffer - but not
1928 * including packets that didn't pass the filter.
1930 * In the BSD BPF, the count of received packets is
1931 * incremented for every packet handed to BPF, regardless
1932 * of whether it passed the filter.
1934 * We can't make "pcap_stats()" work the same on both
1935 * platforms, but the best approximation is to return
1936 * "tp_packets" as the count of packets and "tp_drops"
1937 * as the count of drops.
1939 * Keep a running total because each call to
1940 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1941 * resets the counters to zero.
1943 handle->md.stat.ps_recv += kstats.tp_packets;
1944 handle->md.stat.ps_drop += kstats.tp_drops;
1945 *stats = handle->md.stat;
1946 return 0;
1948 else
1951 * If the error was EOPNOTSUPP, fall through, so that
1952 * if you build the library on a system with
1953 * "struct tpacket_stats" and run it on a system
1954 * that doesn't, it works as it does if the library
1955 * is built on a system without "struct tpacket_stats".
1957 if (errno != EOPNOTSUPP) {
1958 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1959 "pcap_stats: %s", pcap_strerror(errno));
1960 return -1;
1963 #endif
1965 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1966 * is not supported on PF_PACKET sockets:
1968 * "ps_recv" counts only packets that *passed* the filter,
1969 * not packets that didn't pass the filter. It does not
1970 * count packets dropped because we ran out of buffer
1971 * space.
1973 * "ps_drop" is not supported.
1975 * "ps_ifdrop" is supported. It will return the number
1976 * of drops the interface reports in /proc/net/dev,
1977 * if that is available.
1979 * "ps_recv" doesn't include packets not yet read from
1980 * the kernel by libpcap.
1982 * We maintain the count of packets processed by libpcap in
1983 * "md.packets_read", for reasons described in the comment
1984 * at the end of pcap_read_packet(). We have no idea how many
1985 * packets were dropped by the kernel buffers -- but we know
1986 * how many the interface dropped, so we can return that.
1989 stats->ps_recv = handle->md.packets_read;
1990 stats->ps_drop = 0;
1991 stats->ps_ifdrop = handle->md.stat.ps_ifdrop;
1992 return 0;
1996 * Get from "/sys/class/net" all interfaces listed there; if they're
1997 * already in the list of interfaces we have, that won't add another
1998 * instance, but if they're not, that'll add them.
2000 * We don't bother getting any addresses for them; it appears you can't
2001 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2002 * although some other types of addresses can be fetched with SIOCGIFADDR,
2003 * we don't bother with them for now.
2005 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2006 * the list of interfaces as is, and return 0, so that we can try
2007 * scanning /proc/net/dev.
2009 static int
2010 scan_sys_class_net(pcap_if_t **devlistp, char *errbuf)
2012 DIR *sys_class_net_d;
2013 int fd;
2014 struct dirent *ent;
2015 char *p;
2016 char name[512]; /* XXX - pick a size */
2017 char *q, *saveq;
2018 struct ifreq ifrflags;
2019 int ret = 1;
2021 sys_class_net_d = opendir("/sys/class/net");
2022 if (sys_class_net_d == NULL) {
2024 * Don't fail if it doesn't exist at all.
2026 if (errno == ENOENT)
2027 return (0);
2030 * Fail if we got some other error.
2032 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2033 "Can't open /sys/class/net: %s", pcap_strerror(errno));
2034 return (-1);
2038 * Create a socket from which to fetch interface information.
2040 fd = socket(AF_INET, SOCK_DGRAM, 0);
2041 if (fd < 0) {
2042 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2043 "socket: %s", pcap_strerror(errno));
2044 (void)closedir(sys_class_net_d);
2045 return (-1);
2048 for (;;) {
2049 errno = 0;
2050 ent = readdir(sys_class_net_d);
2051 if (ent == NULL) {
2053 * Error or EOF; if errno != 0, it's an error.
2055 break;
2059 * Ignore directories (".", "..", and any subdirectories).
2061 if (ent->d_type == DT_DIR)
2062 continue;
2065 * Get the interface name.
2067 p = &ent->d_name[0];
2068 q = &name[0];
2069 while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2070 if (*p == ':') {
2072 * This could be the separator between a
2073 * name and an alias number, or it could be
2074 * the separator between a name with no
2075 * alias number and the next field.
2077 * If there's a colon after digits, it
2078 * separates the name and the alias number,
2079 * otherwise it separates the name and the
2080 * next field.
2082 saveq = q;
2083 while (isascii(*p) && isdigit(*p))
2084 *q++ = *p++;
2085 if (*p != ':') {
2087 * That was the next field,
2088 * not the alias number.
2090 q = saveq;
2092 break;
2093 } else
2094 *q++ = *p++;
2096 *q = '\0';
2099 * Get the flags for this interface, and skip it if
2100 * it's not up.
2102 strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2103 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2104 if (errno == ENXIO || errno == ENODEV)
2105 continue;
2106 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2107 "SIOCGIFFLAGS: %.*s: %s",
2108 (int)sizeof(ifrflags.ifr_name),
2109 ifrflags.ifr_name,
2110 pcap_strerror(errno));
2111 ret = -1;
2112 break;
2114 if (!(ifrflags.ifr_flags & IFF_UP))
2115 continue;
2118 * Add an entry for this interface, with no addresses.
2120 if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2121 errbuf) == -1) {
2123 * Failure.
2125 ret = -1;
2126 break;
2129 if (ret != -1) {
2131 * Well, we didn't fail for any other reason; did we
2132 * fail due to an error reading the directory?
2134 if (errno != 0) {
2135 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2136 "Error reading /sys/class/net: %s",
2137 pcap_strerror(errno));
2138 ret = -1;
2142 (void)close(fd);
2143 (void)closedir(sys_class_net_d);
2144 return (ret);
2148 * Get from "/proc/net/dev" all interfaces listed there; if they're
2149 * already in the list of interfaces we have, that won't add another
2150 * instance, but if they're not, that'll add them.
2152 * See comments from scan_sys_class_net().
2154 static int
2155 scan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
2157 FILE *proc_net_f;
2158 int fd;
2159 char linebuf[512];
2160 int linenum;
2161 char *p;
2162 char name[512]; /* XXX - pick a size */
2163 char *q, *saveq;
2164 struct ifreq ifrflags;
2165 int ret = 0;
2167 proc_net_f = fopen("/proc/net/dev", "r");
2168 if (proc_net_f == NULL) {
2170 * Don't fail if it doesn't exist at all.
2172 if (errno == ENOENT)
2173 return (0);
2176 * Fail if we got some other error.
2178 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2179 "Can't open /proc/net/dev: %s", pcap_strerror(errno));
2180 return (-1);
2184 * Create a socket from which to fetch interface information.
2186 fd = socket(AF_INET, SOCK_DGRAM, 0);
2187 if (fd < 0) {
2188 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2189 "socket: %s", pcap_strerror(errno));
2190 (void)fclose(proc_net_f);
2191 return (-1);
2194 for (linenum = 1;
2195 fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
2197 * Skip the first two lines - they're headers.
2199 if (linenum <= 2)
2200 continue;
2202 p = &linebuf[0];
2205 * Skip leading white space.
2207 while (*p != '\0' && isascii(*p) && isspace(*p))
2208 p++;
2209 if (*p == '\0' || *p == '\n')
2210 continue; /* blank line */
2213 * Get the interface name.
2215 q = &name[0];
2216 while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2217 if (*p == ':') {
2219 * This could be the separator between a
2220 * name and an alias number, or it could be
2221 * the separator between a name with no
2222 * alias number and the next field.
2224 * If there's a colon after digits, it
2225 * separates the name and the alias number,
2226 * otherwise it separates the name and the
2227 * next field.
2229 saveq = q;
2230 while (isascii(*p) && isdigit(*p))
2231 *q++ = *p++;
2232 if (*p != ':') {
2234 * That was the next field,
2235 * not the alias number.
2237 q = saveq;
2239 break;
2240 } else
2241 *q++ = *p++;
2243 *q = '\0';
2246 * Get the flags for this interface, and skip it if
2247 * it's not up.
2249 strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2250 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2251 if (errno == ENXIO)
2252 continue;
2253 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2254 "SIOCGIFFLAGS: %.*s: %s",
2255 (int)sizeof(ifrflags.ifr_name),
2256 ifrflags.ifr_name,
2257 pcap_strerror(errno));
2258 ret = -1;
2259 break;
2261 if (!(ifrflags.ifr_flags & IFF_UP))
2262 continue;
2265 * Add an entry for this interface, with no addresses.
2267 if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2268 errbuf) == -1) {
2270 * Failure.
2272 ret = -1;
2273 break;
2276 if (ret != -1) {
2278 * Well, we didn't fail for any other reason; did we
2279 * fail due to an error reading the file?
2281 if (ferror(proc_net_f)) {
2282 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2283 "Error reading /proc/net/dev: %s",
2284 pcap_strerror(errno));
2285 ret = -1;
2289 (void)close(fd);
2290 (void)fclose(proc_net_f);
2291 return (ret);
2295 * Description string for the "any" device.
2297 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
2300 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2302 int ret;
2305 * Read "/sys/class/net", and add to the list of interfaces all
2306 * interfaces listed there that we don't already have, because,
2307 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2308 * and even getifaddrs() won't return information about
2309 * interfaces with no addresses, so you need to read "/sys/class/net"
2310 * to get the names of the rest of the interfaces.
2312 ret = scan_sys_class_net(alldevsp, errbuf);
2313 if (ret == -1)
2314 return (-1); /* failed */
2315 if (ret == 0) {
2317 * No /sys/class/net; try reading /proc/net/dev instead.
2319 if (scan_proc_net_dev(alldevsp, errbuf) == -1)
2320 return (-1);
2324 * Add the "any" device.
2326 if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
2327 return (-1);
2329 #ifdef HAVE_DAG_API
2331 * Add DAG devices.
2333 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
2334 return (-1);
2335 #endif /* HAVE_DAG_API */
2337 #ifdef HAVE_SEPTEL_API
2339 * Add Septel devices.
2341 if (septel_platform_finddevs(alldevsp, errbuf) < 0)
2342 return (-1);
2343 #endif /* HAVE_SEPTEL_API */
2345 #ifdef HAVE_SNF_API
2346 if (snf_platform_finddevs(alldevsp, errbuf) < 0)
2347 return (-1);
2348 #endif /* HAVE_SNF_API */
2350 #ifdef PCAP_SUPPORT_BT
2352 * Add Bluetooth devices.
2354 if (bt_platform_finddevs(alldevsp, errbuf) < 0)
2355 return (-1);
2356 #endif
2358 #ifdef PCAP_SUPPORT_USB
2360 * Add USB devices.
2362 if (usb_platform_finddevs(alldevsp, errbuf) < 0)
2363 return (-1);
2364 #endif
2366 #ifdef PCAP_SUPPORT_NETFILTER
2368 * Add netfilter devices.
2370 if (netfilter_platform_finddevs(alldevsp, errbuf) < 0)
2371 return (-1);
2372 #endif
2374 #if PCAP_SUPPORT_CANUSB
2375 if (canusb_platform_finddevs(alldevsp, errbuf) < 0)
2376 return (-1);
2377 #endif
2379 return (0);
2383 * Attach the given BPF code to the packet capture device.
2385 static int
2386 pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
2387 int is_mmapped)
2389 #ifdef SO_ATTACH_FILTER
2390 struct sock_fprog fcode;
2391 int can_filter_in_kernel;
2392 int err = 0;
2393 #endif
2395 if (!handle)
2396 return -1;
2397 if (!filter) {
2398 strncpy(handle->errbuf, "setfilter: No filter specified",
2399 PCAP_ERRBUF_SIZE);
2400 return -1;
2403 /* Make our private copy of the filter */
2405 if (install_bpf_program(handle, filter) < 0)
2406 /* install_bpf_program() filled in errbuf */
2407 return -1;
2410 * Run user level packet filter by default. Will be overriden if
2411 * installing a kernel filter succeeds.
2413 handle->md.use_bpf = 0;
2415 /* Install kernel level filter if possible */
2417 #ifdef SO_ATTACH_FILTER
2418 #ifdef USHRT_MAX
2419 if (handle->fcode.bf_len > USHRT_MAX) {
2421 * fcode.len is an unsigned short for current kernel.
2422 * I have yet to see BPF-Code with that much
2423 * instructions but still it is possible. So for the
2424 * sake of correctness I added this check.
2426 fprintf(stderr, "Warning: Filter too complex for kernel\n");
2427 fcode.len = 0;
2428 fcode.filter = NULL;
2429 can_filter_in_kernel = 0;
2430 } else
2431 #endif /* USHRT_MAX */
2434 * Oh joy, the Linux kernel uses struct sock_fprog instead
2435 * of struct bpf_program and of course the length field is
2436 * of different size. Pointed out by Sebastian
2438 * Oh, and we also need to fix it up so that all "ret"
2439 * instructions with non-zero operands have 65535 as the
2440 * operand if we're not capturing in memory-mapped modee,
2441 * and so that, if we're in cooked mode, all memory-reference
2442 * instructions use special magic offsets in references to
2443 * the link-layer header and assume that the link-layer
2444 * payload begins at 0; "fix_program()" will do that.
2446 switch (fix_program(handle, &fcode, is_mmapped)) {
2448 case -1:
2449 default:
2451 * Fatal error; just quit.
2452 * (The "default" case shouldn't happen; we
2453 * return -1 for that reason.)
2455 return -1;
2457 case 0:
2459 * The program performed checks that we can't make
2460 * work in the kernel.
2462 can_filter_in_kernel = 0;
2463 break;
2465 case 1:
2467 * We have a filter that'll work in the kernel.
2469 can_filter_in_kernel = 1;
2470 break;
2475 * NOTE: at this point, we've set both the "len" and "filter"
2476 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2477 * those are the only members of the "sock_fprog" structure,
2478 * so we initialize every member of that structure.
2480 * If there is anything in "fcode" that is not initialized,
2481 * it is either a field added in a later kernel, or it's
2482 * padding.
2484 * If a new field is added, this code needs to be updated
2485 * to set it correctly.
2487 * If there are no other fields, then:
2489 * if the Linux kernel looks at the padding, it's
2490 * buggy;
2492 * if the Linux kernel doesn't look at the padding,
2493 * then if some tool complains that we're passing
2494 * uninitialized data to the kernel, then the tool
2495 * is buggy and needs to understand that it's just
2496 * padding.
2498 if (can_filter_in_kernel) {
2499 if ((err = set_kernel_filter(handle, &fcode)) == 0)
2501 /* Installation succeded - using kernel filter. */
2502 handle->md.use_bpf = 1;
2504 else if (err == -1) /* Non-fatal error */
2507 * Print a warning if we weren't able to install
2508 * the filter for a reason other than "this kernel
2509 * isn't configured to support socket filters.
2511 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
2512 fprintf(stderr,
2513 "Warning: Kernel filter failed: %s\n",
2514 pcap_strerror(errno));
2520 * If we're not using the kernel filter, get rid of any kernel
2521 * filter that might've been there before, e.g. because the
2522 * previous filter could work in the kernel, or because some other
2523 * code attached a filter to the socket by some means other than
2524 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2525 * filter out packets that would pass the new userland filter.
2527 if (!handle->md.use_bpf)
2528 reset_kernel_filter(handle);
2531 * Free up the copy of the filter that was made by "fix_program()".
2533 if (fcode.filter != NULL)
2534 free(fcode.filter);
2536 if (err == -2)
2537 /* Fatal error */
2538 return -1;
2539 #endif /* SO_ATTACH_FILTER */
2541 return 0;
2544 static int
2545 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
2547 return pcap_setfilter_linux_common(handle, filter, 0);
2552 * Set direction flag: Which packets do we accept on a forwarding
2553 * single device? IN, OUT or both?
2555 static int
2556 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
2558 #ifdef HAVE_PF_PACKET_SOCKETS
2559 if (!handle->md.sock_packet) {
2560 handle->direction = d;
2561 return 0;
2563 #endif
2565 * We're not using PF_PACKET sockets, so we can't determine
2566 * the direction of the packet.
2568 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2569 "Setting direction is not supported on SOCK_PACKET sockets");
2570 return -1;
2573 #ifdef HAVE_PF_PACKET_SOCKETS
2575 * Map the PACKET_ value to a LINUX_SLL_ value; we
2576 * want the same numerical value to be used in
2577 * the link-layer header even if the numerical values
2578 * for the PACKET_ #defines change, so that programs
2579 * that look at the packet type field will always be
2580 * able to handle DLT_LINUX_SLL captures.
2582 static short int
2583 map_packet_type_to_sll_type(short int sll_pkttype)
2585 switch (sll_pkttype) {
2587 case PACKET_HOST:
2588 return htons(LINUX_SLL_HOST);
2590 case PACKET_BROADCAST:
2591 return htons(LINUX_SLL_BROADCAST);
2593 case PACKET_MULTICAST:
2594 return htons(LINUX_SLL_MULTICAST);
2596 case PACKET_OTHERHOST:
2597 return htons(LINUX_SLL_OTHERHOST);
2599 case PACKET_OUTGOING:
2600 return htons(LINUX_SLL_OUTGOING);
2602 default:
2603 return -1;
2606 #endif
2609 * Linux uses the ARP hardware type to identify the type of an
2610 * interface. pcap uses the DLT_xxx constants for this. This
2611 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2612 * constant, as arguments, and sets "handle->linktype" to the
2613 * appropriate DLT_XXX constant and sets "handle->offset" to
2614 * the appropriate value (to make "handle->offset" plus link-layer
2615 * header length be a multiple of 4, so that the link-layer payload
2616 * will be aligned on a 4-byte boundary when capturing packets).
2617 * (If the offset isn't set here, it'll be 0; add code as appropriate
2618 * for cases where it shouldn't be 0.)
2620 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2621 * in cooked mode; otherwise, we can't use cooked mode, so we have
2622 * to pick some type that works in raw mode, or fail.
2624 * Sets the link type to -1 if unable to map the type.
2626 static void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
2628 switch (arptype) {
2630 case ARPHRD_ETHER:
2632 * This is (presumably) a real Ethernet capture; give it a
2633 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2634 * that an application can let you choose it, in case you're
2635 * capturing DOCSIS traffic that a Cisco Cable Modem
2636 * Termination System is putting out onto an Ethernet (it
2637 * doesn't put an Ethernet header onto the wire, it puts raw
2638 * DOCSIS frames out on the wire inside the low-level
2639 * Ethernet framing).
2641 * XXX - are there any sorts of "fake Ethernet" that have
2642 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2643 * a Cisco CMTS won't put traffic onto it or get traffic
2644 * bridged onto it? ISDN is handled in "activate_new()",
2645 * as we fall back on cooked mode there; are there any
2646 * others?
2648 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2650 * If that fails, just leave the list empty.
2652 if (handle->dlt_list != NULL) {
2653 handle->dlt_list[0] = DLT_EN10MB;
2654 handle->dlt_list[1] = DLT_DOCSIS;
2655 handle->dlt_count = 2;
2657 /* FALLTHROUGH */
2659 case ARPHRD_METRICOM:
2660 case ARPHRD_LOOPBACK:
2661 handle->linktype = DLT_EN10MB;
2662 handle->offset = 2;
2663 break;
2665 case ARPHRD_EETHER:
2666 handle->linktype = DLT_EN3MB;
2667 break;
2669 case ARPHRD_AX25:
2670 handle->linktype = DLT_AX25_KISS;
2671 break;
2673 case ARPHRD_PRONET:
2674 handle->linktype = DLT_PRONET;
2675 break;
2677 case ARPHRD_CHAOS:
2678 handle->linktype = DLT_CHAOS;
2679 break;
2680 #ifndef ARPHRD_CAN
2681 #define ARPHRD_CAN 280
2682 #endif
2683 case ARPHRD_CAN:
2684 handle->linktype = DLT_CAN_SOCKETCAN;
2685 break;
2687 #ifndef ARPHRD_IEEE802_TR
2688 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2689 #endif
2690 case ARPHRD_IEEE802_TR:
2691 case ARPHRD_IEEE802:
2692 handle->linktype = DLT_IEEE802;
2693 handle->offset = 2;
2694 break;
2696 case ARPHRD_ARCNET:
2697 handle->linktype = DLT_ARCNET_LINUX;
2698 break;
2700 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2701 #define ARPHRD_FDDI 774
2702 #endif
2703 case ARPHRD_FDDI:
2704 handle->linktype = DLT_FDDI;
2705 handle->offset = 3;
2706 break;
2708 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2709 #define ARPHRD_ATM 19
2710 #endif
2711 case ARPHRD_ATM:
2713 * The Classical IP implementation in ATM for Linux
2714 * supports both what RFC 1483 calls "LLC Encapsulation",
2715 * in which each packet has an LLC header, possibly
2716 * with a SNAP header as well, prepended to it, and
2717 * what RFC 1483 calls "VC Based Multiplexing", in which
2718 * different virtual circuits carry different network
2719 * layer protocols, and no header is prepended to packets.
2721 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2722 * you can't use the ARPHRD_ type to find out whether
2723 * captured packets will have an LLC header, and,
2724 * while there's a socket ioctl to *set* the encapsulation
2725 * type, there's no ioctl to *get* the encapsulation type.
2727 * This means that
2729 * programs that dissect Linux Classical IP frames
2730 * would have to check for an LLC header and,
2731 * depending on whether they see one or not, dissect
2732 * the frame as LLC-encapsulated or as raw IP (I
2733 * don't know whether there's any traffic other than
2734 * IP that would show up on the socket, or whether
2735 * there's any support for IPv6 in the Linux
2736 * Classical IP code);
2738 * filter expressions would have to compile into
2739 * code that checks for an LLC header and does
2740 * the right thing.
2742 * Both of those are a nuisance - and, at least on systems
2743 * that support PF_PACKET sockets, we don't have to put
2744 * up with those nuisances; instead, we can just capture
2745 * in cooked mode. That's what we'll do, if we can.
2746 * Otherwise, we'll just fail.
2748 if (cooked_ok)
2749 handle->linktype = DLT_LINUX_SLL;
2750 else
2751 handle->linktype = -1;
2752 break;
2754 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2755 #define ARPHRD_IEEE80211 801
2756 #endif
2757 case ARPHRD_IEEE80211:
2758 handle->linktype = DLT_IEEE802_11;
2759 break;
2761 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2762 #define ARPHRD_IEEE80211_PRISM 802
2763 #endif
2764 case ARPHRD_IEEE80211_PRISM:
2765 handle->linktype = DLT_PRISM_HEADER;
2766 break;
2768 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2769 #define ARPHRD_IEEE80211_RADIOTAP 803
2770 #endif
2771 case ARPHRD_IEEE80211_RADIOTAP:
2772 handle->linktype = DLT_IEEE802_11_RADIO;
2773 break;
2775 case ARPHRD_PPP:
2777 * Some PPP code in the kernel supplies no link-layer
2778 * header whatsoever to PF_PACKET sockets; other PPP
2779 * code supplies PPP link-layer headers ("syncppp.c");
2780 * some PPP code might supply random link-layer
2781 * headers (PPP over ISDN - there's code in Ethereal,
2782 * for example, to cope with PPP-over-ISDN captures
2783 * with which the Ethereal developers have had to cope,
2784 * heuristically trying to determine which of the
2785 * oddball link-layer headers particular packets have).
2787 * As such, we just punt, and run all PPP interfaces
2788 * in cooked mode, if we can; otherwise, we just treat
2789 * it as DLT_RAW, for now - if somebody needs to capture,
2790 * on a 2.0[.x] kernel, on PPP devices that supply a
2791 * link-layer header, they'll have to add code here to
2792 * map to the appropriate DLT_ type (possibly adding a
2793 * new DLT_ type, if necessary).
2795 if (cooked_ok)
2796 handle->linktype = DLT_LINUX_SLL;
2797 else {
2799 * XXX - handle ISDN types here? We can't fall
2800 * back on cooked sockets, so we'd have to
2801 * figure out from the device name what type of
2802 * link-layer encapsulation it's using, and map
2803 * that to an appropriate DLT_ value, meaning
2804 * we'd map "isdnN" devices to DLT_RAW (they
2805 * supply raw IP packets with no link-layer
2806 * header) and "isdY" devices to a new DLT_I4L_IP
2807 * type that has only an Ethernet packet type as
2808 * a link-layer header.
2810 * But sometimes we seem to get random crap
2811 * in the link-layer header when capturing on
2812 * ISDN devices....
2814 handle->linktype = DLT_RAW;
2816 break;
2818 #ifndef ARPHRD_CISCO
2819 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2820 #endif
2821 case ARPHRD_CISCO:
2822 handle->linktype = DLT_C_HDLC;
2823 break;
2825 /* Not sure if this is correct for all tunnels, but it
2826 * works for CIPE */
2827 case ARPHRD_TUNNEL:
2828 #ifndef ARPHRD_SIT
2829 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2830 #endif
2831 case ARPHRD_SIT:
2832 case ARPHRD_CSLIP:
2833 case ARPHRD_SLIP6:
2834 case ARPHRD_CSLIP6:
2835 case ARPHRD_ADAPT:
2836 case ARPHRD_SLIP:
2837 #ifndef ARPHRD_RAWHDLC
2838 #define ARPHRD_RAWHDLC 518
2839 #endif
2840 case ARPHRD_RAWHDLC:
2841 #ifndef ARPHRD_DLCI
2842 #define ARPHRD_DLCI 15
2843 #endif
2844 case ARPHRD_DLCI:
2846 * XXX - should some of those be mapped to DLT_LINUX_SLL
2847 * instead? Should we just map all of them to DLT_LINUX_SLL?
2849 handle->linktype = DLT_RAW;
2850 break;
2852 #ifndef ARPHRD_FRAD
2853 #define ARPHRD_FRAD 770
2854 #endif
2855 case ARPHRD_FRAD:
2856 handle->linktype = DLT_FRELAY;
2857 break;
2859 case ARPHRD_LOCALTLK:
2860 handle->linktype = DLT_LTALK;
2861 break;
2863 #ifndef ARPHRD_FCPP
2864 #define ARPHRD_FCPP 784
2865 #endif
2866 case ARPHRD_FCPP:
2867 #ifndef ARPHRD_FCAL
2868 #define ARPHRD_FCAL 785
2869 #endif
2870 case ARPHRD_FCAL:
2871 #ifndef ARPHRD_FCPL
2872 #define ARPHRD_FCPL 786
2873 #endif
2874 case ARPHRD_FCPL:
2875 #ifndef ARPHRD_FCFABRIC
2876 #define ARPHRD_FCFABRIC 787
2877 #endif
2878 case ARPHRD_FCFABRIC:
2880 * We assume that those all mean RFC 2625 IP-over-
2881 * Fibre Channel, with the RFC 2625 header at
2882 * the beginning of the packet.
2884 handle->linktype = DLT_IP_OVER_FC;
2885 break;
2887 #ifndef ARPHRD_IRDA
2888 #define ARPHRD_IRDA 783
2889 #endif
2890 case ARPHRD_IRDA:
2891 /* Don't expect IP packet out of this interfaces... */
2892 handle->linktype = DLT_LINUX_IRDA;
2893 /* We need to save packet direction for IrDA decoding,
2894 * so let's use "Linux-cooked" mode. Jean II */
2895 //handle->md.cooked = 1;
2896 break;
2898 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2899 * is needed, please report it to <daniele@orlandi.com> */
2900 #ifndef ARPHRD_LAPD
2901 #define ARPHRD_LAPD 8445
2902 #endif
2903 case ARPHRD_LAPD:
2904 /* Don't expect IP packet out of this interfaces... */
2905 handle->linktype = DLT_LINUX_LAPD;
2906 break;
2908 #ifndef ARPHRD_NONE
2909 #define ARPHRD_NONE 0xFFFE
2910 #endif
2911 case ARPHRD_NONE:
2913 * No link-layer header; packets are just IP
2914 * packets, so use DLT_RAW.
2916 handle->linktype = DLT_RAW;
2917 break;
2919 #ifndef ARPHRD_IEEE802154
2920 #define ARPHRD_IEEE802154 804
2921 #endif
2922 case ARPHRD_IEEE802154:
2923 handle->linktype = DLT_IEEE802_15_4_NOFCS;
2924 break;
2926 default:
2927 handle->linktype = -1;
2928 break;
2932 /* ===== Functions to interface to the newer kernels ================== */
2935 * Try to open a packet socket using the new kernel PF_PACKET interface.
2936 * Returns 1 on success, 0 on an error that means the new interface isn't
2937 * present (so the old SOCK_PACKET interface should be tried), and a
2938 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2939 * work either (so it shouldn't be tried).
2941 static int
2942 activate_new(pcap_t *handle)
2944 #ifdef HAVE_PF_PACKET_SOCKETS
2945 const char *device = handle->opt.source;
2946 int is_any_device = (strcmp(device, "any") == 0);
2947 int sock_fd = -1, arptype;
2948 #ifdef HAVE_PACKET_AUXDATA
2949 int val;
2950 #endif
2951 int err = 0;
2952 struct packet_mreq mr;
2955 * Open a socket with protocol family packet. If the
2956 * "any" device was specified, we open a SOCK_DGRAM
2957 * socket for the cooked interface, otherwise we first
2958 * try a SOCK_RAW socket for the raw interface.
2960 sock_fd = is_any_device ?
2961 socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
2962 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
2964 if (sock_fd == -1) {
2965 if (errno == EINVAL || errno == EAFNOSUPPORT) {
2967 * We don't support PF_PACKET/SOCK_whatever
2968 * sockets; try the old mechanism.
2970 return 0;
2973 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
2974 pcap_strerror(errno) );
2975 if (errno == EPERM || errno == EACCES) {
2977 * You don't have permission to open the
2978 * socket.
2980 return PCAP_ERROR_PERM_DENIED;
2981 } else {
2983 * Other error.
2985 return PCAP_ERROR;
2989 /* It seems the kernel supports the new interface. */
2990 handle->md.sock_packet = 0;
2993 * Get the interface index of the loopback device.
2994 * If the attempt fails, don't fail, just set the
2995 * "md.lo_ifindex" to -1.
2997 * XXX - can there be more than one device that loops
2998 * packets back, i.e. devices other than "lo"? If so,
2999 * we'd need to find them all, and have an array of
3000 * indices for them, and check all of them in
3001 * "pcap_read_packet()".
3003 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
3006 * Default value for offset to align link-layer payload
3007 * on a 4-byte boundary.
3009 handle->offset = 0;
3012 * What kind of frames do we have to deal with? Fall back
3013 * to cooked mode if we have an unknown interface type
3014 * or a type we know doesn't work well in raw mode.
3016 if (!is_any_device) {
3017 /* Assume for now we don't need cooked mode. */
3018 handle->md.cooked = 0;
3020 if (handle->opt.rfmon) {
3022 * We were asked to turn on monitor mode.
3023 * Do so before we get the link-layer type,
3024 * because entering monitor mode could change
3025 * the link-layer type.
3027 err = enter_rfmon_mode(handle, sock_fd, device);
3028 if (err < 0) {
3029 /* Hard failure */
3030 close(sock_fd);
3031 return err;
3033 if (err == 0) {
3035 * Nothing worked for turning monitor mode
3036 * on.
3038 close(sock_fd);
3039 return PCAP_ERROR_RFMON_NOTSUP;
3043 * Either monitor mode has been turned on for
3044 * the device, or we've been given a different
3045 * device to open for monitor mode. If we've
3046 * been given a different device, use it.
3048 if (handle->md.mondevice != NULL)
3049 device = handle->md.mondevice;
3051 arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
3052 if (arptype < 0) {
3053 close(sock_fd);
3054 return arptype;
3056 map_arphrd_to_dlt(handle, arptype, 1);
3057 if (handle->linktype == -1 ||
3058 handle->linktype == DLT_LINUX_SLL ||
3059 handle->linktype == DLT_LINUX_IRDA ||
3060 handle->linktype == DLT_LINUX_LAPD ||
3061 (handle->linktype == DLT_EN10MB &&
3062 (strncmp("isdn", device, 4) == 0 ||
3063 strncmp("isdY", device, 4) == 0))) {
3065 * Unknown interface type (-1), or a
3066 * device we explicitly chose to run
3067 * in cooked mode (e.g., PPP devices),
3068 * or an ISDN device (whose link-layer
3069 * type we can only determine by using
3070 * APIs that may be different on different
3071 * kernels) - reopen in cooked mode.
3073 if (close(sock_fd) == -1) {
3074 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3075 "close: %s", pcap_strerror(errno));
3076 return PCAP_ERROR;
3078 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
3079 htons(ETH_P_ALL));
3080 if (sock_fd == -1) {
3081 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3082 "socket: %s", pcap_strerror(errno));
3083 if (errno == EPERM || errno == EACCES) {
3085 * You don't have permission to
3086 * open the socket.
3088 return PCAP_ERROR_PERM_DENIED;
3089 } else {
3091 * Other error.
3093 return PCAP_ERROR;
3096 handle->md.cooked = 1;
3099 * Get rid of any link-layer type list
3100 * we allocated - this only supports cooked
3101 * capture.
3103 if (handle->dlt_list != NULL) {
3104 free(handle->dlt_list);
3105 handle->dlt_list = NULL;
3106 handle->dlt_count = 0;
3109 if (handle->linktype == -1) {
3111 * Warn that we're falling back on
3112 * cooked mode; we may want to
3113 * update "map_arphrd_to_dlt()"
3114 * to handle the new type.
3116 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3117 "arptype %d not "
3118 "supported by libpcap - "
3119 "falling back to cooked "
3120 "socket",
3121 arptype);
3125 * IrDA capture is not a real "cooked" capture,
3126 * it's IrLAP frames, not IP packets. The
3127 * same applies to LAPD capture.
3129 if (handle->linktype != DLT_LINUX_IRDA &&
3130 handle->linktype != DLT_LINUX_LAPD)
3131 handle->linktype = DLT_LINUX_SLL;
3134 handle->md.ifindex = iface_get_id(sock_fd, device,
3135 handle->errbuf);
3136 if (handle->md.ifindex == -1) {
3137 close(sock_fd);
3138 return PCAP_ERROR;
3141 if ((err = iface_bind(sock_fd, handle->md.ifindex,
3142 handle->errbuf)) != 1) {
3143 close(sock_fd);
3144 if (err < 0)
3145 return err;
3146 else
3147 return 0; /* try old mechanism */
3149 } else {
3151 * The "any" device.
3153 if (handle->opt.rfmon) {
3155 * It doesn't support monitor mode.
3157 return PCAP_ERROR_RFMON_NOTSUP;
3161 * It uses cooked mode.
3163 handle->md.cooked = 1;
3164 handle->linktype = DLT_LINUX_SLL;
3167 * We're not bound to a device.
3168 * For now, we're using this as an indication
3169 * that we can't transmit; stop doing that only
3170 * if we figure out how to transmit in cooked
3171 * mode.
3173 handle->md.ifindex = -1;
3177 * Select promiscuous mode on if "promisc" is set.
3179 * Do not turn allmulti mode on if we don't select
3180 * promiscuous mode - on some devices (e.g., Orinoco
3181 * wireless interfaces), allmulti mode isn't supported
3182 * and the driver implements it by turning promiscuous
3183 * mode on, and that screws up the operation of the
3184 * card as a normal networking interface, and on no
3185 * other platform I know of does starting a non-
3186 * promiscuous capture affect which multicast packets
3187 * are received by the interface.
3191 * Hmm, how can we set promiscuous mode on all interfaces?
3192 * I am not sure if that is possible at all. For now, we
3193 * silently ignore attempts to turn promiscuous mode on
3194 * for the "any" device (so you don't have to explicitly
3195 * disable it in programs such as tcpdump).
3198 if (!is_any_device && handle->opt.promisc) {
3199 memset(&mr, 0, sizeof(mr));
3200 mr.mr_ifindex = handle->md.ifindex;
3201 mr.mr_type = PACKET_MR_PROMISC;
3202 if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
3203 &mr, sizeof(mr)) == -1) {
3204 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3205 "setsockopt: %s", pcap_strerror(errno));
3206 close(sock_fd);
3207 return PCAP_ERROR;
3211 /* Enable auxillary data if supported and reserve room for
3212 * reconstructing VLAN headers. */
3213 #ifdef HAVE_PACKET_AUXDATA
3214 val = 1;
3215 if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
3216 sizeof(val)) == -1 && errno != ENOPROTOOPT) {
3217 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3218 "setsockopt: %s", pcap_strerror(errno));
3219 close(sock_fd);
3220 return PCAP_ERROR;
3222 handle->offset += VLAN_TAG_LEN;
3223 #endif /* HAVE_PACKET_AUXDATA */
3226 * This is a 2.2[.x] or later kernel (we know that
3227 * because we're not using a SOCK_PACKET socket -
3228 * PF_PACKET is supported only in 2.2 and later
3229 * kernels).
3231 * We can safely pass "recvfrom()" a byte count
3232 * based on the snapshot length.
3234 * If we're in cooked mode, make the snapshot length
3235 * large enough to hold a "cooked mode" header plus
3236 * 1 byte of packet data (so we don't pass a byte
3237 * count of 0 to "recvfrom()").
3239 if (handle->md.cooked) {
3240 if (handle->snapshot < SLL_HDR_LEN + 1)
3241 handle->snapshot = SLL_HDR_LEN + 1;
3243 handle->bufsize = handle->snapshot;
3245 /* Save the socket FD in the pcap structure */
3246 handle->fd = sock_fd;
3248 return 1;
3249 #else
3250 strncpy(ebuf,
3251 "New packet capturing interface not supported by build "
3252 "environment", PCAP_ERRBUF_SIZE);
3253 return 0;
3254 #endif
3257 #ifdef HAVE_PACKET_RING
3259 * Attempt to activate with memory-mapped access.
3261 * On success, returns 1, and sets *status to 0 if there are no warnings
3262 * or to a PCAP_WARNING_ code if there is a warning.
3264 * On failure due to lack of support for memory-mapped capture, returns
3265 * 0.
3267 * On error, returns -1, and sets *status to the appropriate error code;
3268 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3270 static int
3271 activate_mmap(pcap_t *handle, int *status)
3273 int ret;
3276 * Attempt to allocate a buffer to hold the contents of one
3277 * packet, for use by the oneshot callback.
3279 handle->md.oneshot_buffer = malloc(handle->snapshot);
3280 if (handle->md.oneshot_buffer == NULL) {
3281 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3282 "can't allocate oneshot buffer: %s",
3283 pcap_strerror(errno));
3284 *status = PCAP_ERROR;
3285 return -1;
3288 if (handle->opt.buffer_size == 0) {
3289 /* by default request 2M for the ring buffer */
3290 handle->opt.buffer_size = 2*1024*1024;
3292 ret = prepare_tpacket_socket(handle);
3293 if (ret == -1) {
3294 free(handle->md.oneshot_buffer);
3295 *status = PCAP_ERROR;
3296 return ret;
3298 ret = create_ring(handle, status);
3299 if (ret == 0) {
3301 * We don't support memory-mapped capture; our caller
3302 * will fall back on reading from the socket.
3304 free(handle->md.oneshot_buffer);
3305 return 0;
3307 if (ret == -1) {
3309 * Error attempting to enable memory-mapped capture;
3310 * fail. create_ring() has set *status.
3312 free(handle->md.oneshot_buffer);
3313 return -1;
3317 * Success. *status has been set either to 0 if there are no
3318 * warnings or to a PCAP_WARNING_ value if there is a warning.
3320 * Override some defaults and inherit the other fields from
3321 * activate_new.
3322 * handle->offset is used to get the current position into the rx ring.
3323 * handle->cc is used to store the ring size.
3325 handle->read_op = pcap_read_linux_mmap;
3326 handle->cleanup_op = pcap_cleanup_linux_mmap;
3327 handle->setfilter_op = pcap_setfilter_linux_mmap;
3328 handle->setnonblock_op = pcap_setnonblock_mmap;
3329 handle->getnonblock_op = pcap_getnonblock_mmap;
3330 handle->oneshot_callback = pcap_oneshot_mmap;
3331 handle->selectable_fd = handle->fd;
3332 return 1;
3334 #else /* HAVE_PACKET_RING */
3335 static int
3336 activate_mmap(pcap_t *handle _U_, int *status _U_)
3338 return 0;
3340 #endif /* HAVE_PACKET_RING */
3342 #ifdef HAVE_PACKET_RING
3344 * Attempt to set the socket to version 2 of the memory-mapped header.
3345 * Return 1 if we succeed or if we fail because version 2 isn't
3346 * supported; return -1 on any other error, and set handle->errbuf.
3348 static int
3349 prepare_tpacket_socket(pcap_t *handle)
3351 #ifdef HAVE_TPACKET2
3352 socklen_t len;
3353 int val;
3354 #endif
3356 handle->md.tp_version = TPACKET_V1;
3357 handle->md.tp_hdrlen = sizeof(struct tpacket_hdr);
3359 #ifdef HAVE_TPACKET2
3360 /* Probe whether kernel supports TPACKET_V2 */
3361 val = TPACKET_V2;
3362 len = sizeof(val);
3363 if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
3364 if (errno == ENOPROTOOPT)
3365 return 1; /* no - just drive on */
3367 /* Yes - treat as a failure. */
3368 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3369 "can't get TPACKET_V2 header len on packet socket: %s",
3370 pcap_strerror(errno));
3371 return -1;
3373 handle->md.tp_hdrlen = val;
3375 val = TPACKET_V2;
3376 if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
3377 sizeof(val)) < 0) {
3378 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3379 "can't activate TPACKET_V2 on packet socket: %s",
3380 pcap_strerror(errno));
3381 return -1;
3383 handle->md.tp_version = TPACKET_V2;
3385 /* Reserve space for VLAN tag reconstruction */
3386 val = VLAN_TAG_LEN;
3387 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
3388 sizeof(val)) < 0) {
3389 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3390 "can't set up reserve on packet socket: %s",
3391 pcap_strerror(errno));
3392 return -1;
3395 #endif /* HAVE_TPACKET2 */
3396 return 1;
3400 * Attempt to set up memory-mapped access.
3402 * On success, returns 1, and sets *status to 0 if there are no warnings
3403 * or to a PCAP_WARNING_ code if there is a warning.
3405 * On failure due to lack of support for memory-mapped capture, returns
3406 * 0.
3408 * On error, returns -1, and sets *status to the appropriate error code;
3409 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3411 static int
3412 create_ring(pcap_t *handle, int *status)
3414 unsigned i, j, frames_per_block;
3415 struct tpacket_req req;
3416 socklen_t len;
3417 unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
3418 unsigned int frame_size;
3421 * Start out assuming no warnings or errors.
3423 *status = 0;
3425 /* Note that with large snapshot length (say 64K, which is the default
3426 * for recent versions of tcpdump, the value that "-s 0" has given
3427 * for a long time with tcpdump, and the default in Wireshark/TShark),
3428 * if we use the snapshot length to calculate the frame length,
3429 * only a few frames will be available in the ring even with pretty
3430 * large ring size (and a lot of memory will be unused).
3432 * Ideally, we should choose a frame length based on the
3433 * minimum of the specified snapshot length and the maximum
3434 * packet size. That's not as easy as it sounds; consider, for
3435 * example, an 802.11 interface in monitor mode, where the
3436 * frame would include a radiotap header, where the maximum
3437 * radiotap header length is device-dependent.
3439 * So, for now, we just do this for Ethernet devices, where
3440 * there's no metadata header, and the link-layer header is
3441 * fixed length. We can get the maximum packet size by
3442 * adding 18, the Ethernet header length plus the CRC length
3443 * (just in case we happen to get the CRC in the packet), to
3444 * the MTU of the interface; we fetch the MTU in the hopes
3445 * that it reflects support for jumbo frames. (Even if the
3446 * interface is just being used for passive snooping, the driver
3447 * might set the size of buffers in the receive ring based on
3448 * the MTU, so that the MTU limits the maximum size of packets
3449 * that we can receive.)
3451 * We don't do that if segmentation/fragmentation or receive
3452 * offload are enabled, so we don't get rudely surprised by
3453 * "packets" bigger than the MTU. */
3454 frame_size = handle->snapshot;
3455 if (handle->linktype == DLT_EN10MB) {
3456 int mtu;
3457 int offload;
3459 offload = iface_get_offload(handle);
3460 if (offload == -1) {
3461 *status = PCAP_ERROR;
3462 return -1;
3464 if (!offload) {
3465 mtu = iface_get_mtu(handle->fd, handle->opt.source,
3466 handle->errbuf);
3467 if (mtu == -1) {
3468 *status = PCAP_ERROR;
3469 return -1;
3471 if (frame_size > mtu + 18)
3472 frame_size = mtu + 18;
3476 /* NOTE: calculus matching those in tpacket_rcv()
3477 * in linux-2.6/net/packet/af_packet.c
3479 len = sizeof(sk_type);
3480 if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type, &len) < 0) {
3481 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3482 *status = PCAP_ERROR;
3483 return -1;
3485 #ifdef PACKET_RESERVE
3486 len = sizeof(tp_reserve);
3487 if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &tp_reserve, &len) < 0) {
3488 if (errno != ENOPROTOOPT) {
3490 * ENOPROTOOPT means "kernel doesn't support
3491 * PACKET_RESERVE", in which case we fall back
3492 * as best we can.
3494 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3495 *status = PCAP_ERROR;
3496 return -1;
3498 tp_reserve = 0; /* older kernel, reserve not supported */
3500 #else
3501 tp_reserve = 0; /* older kernel, reserve not supported */
3502 #endif
3503 maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
3504 /* XXX: in the kernel maclen is calculated from
3505 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3506 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3507 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3508 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3509 * but I see no way to get those sizes in userspace,
3510 * like for instance with an ifreq ioctl();
3511 * the best thing I've found so far is MAX_HEADER in the kernel
3512 * part of linux-2.6/include/linux/netdevice.h
3513 * which goes up to 128+48=176; since pcap-linux.c defines
3514 * a MAX_LINKHEADER_SIZE of 256 which is greater than that,
3515 * let's use it.. maybe is it even large enough to directly
3516 * replace macoff..
3518 tp_hdrlen = TPACKET_ALIGN(handle->md.tp_hdrlen) + sizeof(struct sockaddr_ll) ;
3519 netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
3520 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN of
3521 * netoff, which contradicts
3522 * linux-2.6/Documentation/networking/packet_mmap.txt
3523 * documenting that:
3524 * "- Gap, chosen so that packet data (Start+tp_net)
3525 * aligns to TPACKET_ALIGNMENT=16"
3527 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3528 * "CPUs often take a performance hit
3529 * when accessing unaligned memory locations"
3531 macoff = netoff - maclen;
3532 req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
3533 req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
3535 /* compute the minumum block size that will handle this frame.
3536 * The block has to be page size aligned.
3537 * The max block size allowed by the kernel is arch-dependent and
3538 * it's not explicitly checked here. */
3539 req.tp_block_size = getpagesize();
3540 while (req.tp_block_size < req.tp_frame_size)
3541 req.tp_block_size <<= 1;
3543 frames_per_block = req.tp_block_size/req.tp_frame_size;
3546 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3547 * so we check for PACKET_TIMESTAMP. We check for
3548 * linux/net_tstamp.h just in case a system somehow has
3549 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3550 * be unnecessary.
3552 * SIOCSHWTSTAMP was introduced in the patch that introduced
3553 * linux/net_tstamp.h, so we don't bother checking whether
3554 * SIOCSHWTSTAMP is defined (if your Linux system has
3555 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3556 * Linux system is badly broken).
3558 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3560 * If we were told to do so, ask the kernel and the driver
3561 * to use hardware timestamps.
3563 * Hardware timestamps are only supported with mmapped
3564 * captures.
3566 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
3567 handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
3568 struct hwtstamp_config hwconfig;
3569 struct ifreq ifr;
3570 int timesource;
3573 * Ask for hardware time stamps on all packets,
3574 * including transmitted packets.
3576 memset(&hwconfig, 0, sizeof(hwconfig));
3577 hwconfig.tx_type = HWTSTAMP_TX_ON;
3578 hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
3580 memset(&ifr, 0, sizeof(ifr));
3581 strcpy(ifr.ifr_name, handle->opt.source);
3582 ifr.ifr_data = (void *)&hwconfig;
3584 if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
3585 switch (errno) {
3587 case EPERM:
3589 * Treat this as an error, as the
3590 * user should try to run this
3591 * with the appropriate privileges -
3592 * and, if they can't, shouldn't
3593 * try requesting hardware time stamps.
3595 *status = PCAP_ERROR_PERM_DENIED;
3596 return -1;
3598 case EOPNOTSUPP:
3600 * Treat this as a warning, as the
3601 * only way to fix the warning is to
3602 * get an adapter that supports hardware
3603 * time stamps. We'll just fall back
3604 * on the standard host time stamps.
3606 *status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
3607 break;
3609 default:
3610 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3611 "SIOCSHWTSTAMP failed: %s",
3612 pcap_strerror(errno));
3613 *status = PCAP_ERROR;
3614 return -1;
3616 } else {
3618 * Well, that worked. Now specify the type of
3619 * hardware time stamp we want for this
3620 * socket.
3622 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
3624 * Hardware timestamp, synchronized
3625 * with the system clock.
3627 timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
3628 } else {
3630 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3631 * timestamp, not synchronized with the
3632 * system clock.
3634 timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
3636 if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
3637 (void *)&timesource, sizeof(timesource))) {
3638 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3639 "can't set PACKET_TIMESTAMP: %s",
3640 pcap_strerror(errno));
3641 *status = PCAP_ERROR;
3642 return -1;
3646 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3648 /* ask the kernel to create the ring */
3649 retry:
3650 req.tp_block_nr = req.tp_frame_nr / frames_per_block;
3652 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3653 req.tp_frame_nr = req.tp_block_nr * frames_per_block;
3655 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3656 (void *) &req, sizeof(req))) {
3657 if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
3659 * Memory failure; try to reduce the requested ring
3660 * size.
3662 * We used to reduce this by half -- do 5% instead.
3663 * That may result in more iterations and a longer
3664 * startup, but the user will be much happier with
3665 * the resulting buffer size.
3667 if (req.tp_frame_nr < 20)
3668 req.tp_frame_nr -= 1;
3669 else
3670 req.tp_frame_nr -= req.tp_frame_nr/20;
3671 goto retry;
3673 if (errno == ENOPROTOOPT) {
3675 * We don't have ring buffer support in this kernel.
3677 return 0;
3679 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3680 "can't create rx ring on packet socket: %s",
3681 pcap_strerror(errno));
3682 *status = PCAP_ERROR;
3683 return -1;
3686 /* memory map the rx ring */
3687 handle->md.mmapbuflen = req.tp_block_nr * req.tp_block_size;
3688 handle->md.mmapbuf = mmap(0, handle->md.mmapbuflen,
3689 PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
3690 if (handle->md.mmapbuf == MAP_FAILED) {
3691 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3692 "can't mmap rx ring: %s", pcap_strerror(errno));
3694 /* clear the allocated ring on error*/
3695 destroy_ring(handle);
3696 *status = PCAP_ERROR;
3697 return -1;
3700 /* allocate a ring for each frame header pointer*/
3701 handle->cc = req.tp_frame_nr;
3702 handle->buffer = malloc(handle->cc * sizeof(union thdr *));
3703 if (!handle->buffer) {
3704 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3705 "can't allocate ring of frame headers: %s",
3706 pcap_strerror(errno));
3708 destroy_ring(handle);
3709 *status = PCAP_ERROR;
3710 return -1;
3713 /* fill the header ring with proper frame ptr*/
3714 handle->offset = 0;
3715 for (i=0; i<req.tp_block_nr; ++i) {
3716 void *base = &handle->md.mmapbuf[i*req.tp_block_size];
3717 for (j=0; j<frames_per_block; ++j, ++handle->offset) {
3718 RING_GET_FRAME(handle) = base;
3719 base += req.tp_frame_size;
3723 handle->bufsize = req.tp_frame_size;
3724 handle->offset = 0;
3725 return 1;
3728 /* free all ring related resources*/
3729 static void
3730 destroy_ring(pcap_t *handle)
3732 /* tell the kernel to destroy the ring*/
3733 struct tpacket_req req;
3734 memset(&req, 0, sizeof(req));
3735 setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3736 (void *) &req, sizeof(req));
3738 /* if ring is mapped, unmap it*/
3739 if (handle->md.mmapbuf) {
3740 /* do not test for mmap failure, as we can't recover from any error */
3741 munmap(handle->md.mmapbuf, handle->md.mmapbuflen);
3742 handle->md.mmapbuf = NULL;
3747 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3748 * for Linux mmapped capture.
3750 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3751 * data handed to the callback to be valid after the callback returns,
3752 * but pcap_read_linux_mmap() has to release that packet as soon as
3753 * the callback returns (otherwise, the kernel thinks there's still
3754 * at least one unprocessed packet available in the ring, so a select()
3755 * will immediately return indicating that there's data to process), so,
3756 * in the callback, we have to make a copy of the packet.
3758 * Yes, this means that, if the capture is using the ring buffer, using
3759 * pcap_next() or pcap_next_ex() requires more copies than using
3760 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3761 * pcap_next() or pcap_next_ex().
3763 static void
3764 pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
3765 const u_char *bytes)
3767 struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
3769 *sp->hdr = *h;
3770 memcpy(sp->pd->md.oneshot_buffer, bytes, h->caplen);
3771 *sp->pkt = sp->pd->md.oneshot_buffer;
3774 static void
3775 pcap_cleanup_linux_mmap( pcap_t *handle )
3777 destroy_ring(handle);
3778 if (handle->md.oneshot_buffer != NULL) {
3779 free(handle->md.oneshot_buffer);
3780 handle->md.oneshot_buffer = NULL;
3782 pcap_cleanup_linux(handle);
3786 static int
3787 pcap_getnonblock_mmap(pcap_t *p, char *errbuf)
3789 /* use negative value of timeout to indicate non blocking ops */
3790 return (p->md.timeout<0);
3793 static int
3794 pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
3796 /* map each value to the corresponding 2's complement, to
3797 * preserve the timeout value provided with pcap_set_timeout */
3798 if (nonblock) {
3799 if (p->md.timeout >= 0) {
3801 * Timeout is non-negative, so we're not already
3802 * in non-blocking mode; set it to the 2's
3803 * complement, to make it negative, as an
3804 * indication that we're in non-blocking mode.
3806 p->md.timeout = p->md.timeout*-1 - 1;
3808 } else {
3809 if (p->md.timeout < 0) {
3811 * Timeout is negative, so we're not already
3812 * in blocking mode; reverse the previous
3813 * operation, to make the timeout non-negative
3814 * again.
3816 p->md.timeout = (p->md.timeout+1)*-1;
3819 return 0;
3822 static inline union thdr *
3823 pcap_get_ring_frame(pcap_t *handle, int status)
3825 union thdr h;
3827 h.raw = RING_GET_FRAME(handle);
3828 switch (handle->md.tp_version) {
3829 case TPACKET_V1:
3830 if (status != (h.h1->tp_status ? TP_STATUS_USER :
3831 TP_STATUS_KERNEL))
3832 return NULL;
3833 break;
3834 #ifdef HAVE_TPACKET2
3835 case TPACKET_V2:
3836 if (status != (h.h2->tp_status ? TP_STATUS_USER :
3837 TP_STATUS_KERNEL))
3838 return NULL;
3839 break;
3840 #endif
3842 return h.raw;
3845 #ifndef POLLRDHUP
3846 #define POLLRDHUP 0
3847 #endif
3849 static int
3850 pcap_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback,
3851 u_char *user)
3853 int timeout;
3854 int pkts = 0;
3855 char c;
3857 /* wait for frames availability.*/
3858 if (!pcap_get_ring_frame(handle, TP_STATUS_USER)) {
3859 struct pollfd pollinfo;
3860 int ret;
3862 pollinfo.fd = handle->fd;
3863 pollinfo.events = POLLIN;
3865 if (handle->md.timeout == 0)
3866 timeout = -1; /* block forever */
3867 else if (handle->md.timeout > 0)
3868 timeout = handle->md.timeout; /* block for that amount of time */
3869 else
3870 timeout = 0; /* non-blocking mode - poll to pick up errors */
3871 do {
3872 ret = poll(&pollinfo, 1, timeout);
3873 if (ret < 0 && errno != EINTR) {
3874 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3875 "can't poll on packet socket: %s",
3876 pcap_strerror(errno));
3877 return PCAP_ERROR;
3878 } else if (ret > 0 &&
3879 (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
3881 * There's some indication other than
3882 * "you can read on this descriptor" on
3883 * the descriptor.
3885 if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
3886 snprintf(handle->errbuf,
3887 PCAP_ERRBUF_SIZE,
3888 "Hangup on packet socket");
3889 return PCAP_ERROR;
3891 if (pollinfo.revents & POLLERR) {
3893 * A recv() will give us the
3894 * actual error code.
3896 * XXX - make the socket non-blocking?
3898 if (recv(handle->fd, &c, sizeof c,
3899 MSG_PEEK) != -1)
3900 continue; /* what, no error? */
3901 if (errno == ENETDOWN) {
3903 * The device on which we're
3904 * capturing went away.
3906 * XXX - we should really return
3907 * PCAP_ERROR_IFACE_NOT_UP,
3908 * but pcap_dispatch() etc.
3909 * aren't defined to return
3910 * that.
3912 snprintf(handle->errbuf,
3913 PCAP_ERRBUF_SIZE,
3914 "The interface went down");
3915 } else {
3916 snprintf(handle->errbuf,
3917 PCAP_ERRBUF_SIZE,
3918 "Error condition on packet socket: %s",
3919 strerror(errno));
3921 return PCAP_ERROR;
3923 if (pollinfo.revents & POLLNVAL) {
3924 snprintf(handle->errbuf,
3925 PCAP_ERRBUF_SIZE,
3926 "Invalid polling request on packet socket");
3927 return PCAP_ERROR;
3930 /* check for break loop condition on interrupted syscall*/
3931 if (handle->break_loop) {
3932 handle->break_loop = 0;
3933 return PCAP_ERROR_BREAK;
3935 } while (ret < 0);
3938 /* non-positive values of max_packets are used to require all
3939 * packets currently available in the ring */
3940 while ((pkts < max_packets) || (max_packets <= 0)) {
3941 int run_bpf;
3942 struct sockaddr_ll *sll;
3943 struct pcap_pkthdr pcaphdr;
3944 unsigned char *bp;
3945 union thdr h;
3946 unsigned int tp_len;
3947 unsigned int tp_mac;
3948 unsigned int tp_snaplen;
3949 unsigned int tp_sec;
3950 unsigned int tp_usec;
3952 h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
3953 if (!h.raw)
3954 break;
3956 switch (handle->md.tp_version) {
3957 case TPACKET_V1:
3958 tp_len = h.h1->tp_len;
3959 tp_mac = h.h1->tp_mac;
3960 tp_snaplen = h.h1->tp_snaplen;
3961 tp_sec = h.h1->tp_sec;
3962 tp_usec = h.h1->tp_usec;
3963 break;
3964 #ifdef HAVE_TPACKET2
3965 case TPACKET_V2:
3966 tp_len = h.h2->tp_len;
3967 tp_mac = h.h2->tp_mac;
3968 tp_snaplen = h.h2->tp_snaplen;
3969 tp_sec = h.h2->tp_sec;
3970 tp_usec = h.h2->tp_nsec / 1000;
3971 break;
3972 #endif
3973 default:
3974 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3975 "unsupported tpacket version %d",
3976 handle->md.tp_version);
3977 return -1;
3979 /* perform sanity check on internal offset. */
3980 if (tp_mac + tp_snaplen > handle->bufsize) {
3981 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3982 "corrupted frame on kernel ring mac "
3983 "offset %d + caplen %d > frame len %d",
3984 tp_mac, tp_snaplen, handle->bufsize);
3985 return -1;
3988 /* run filter on received packet
3989 * If the kernel filtering is enabled we need to run the
3990 * filter until all the frames present into the ring
3991 * at filter creation time are processed.
3992 * In such case md.use_bpf is used as a counter for the
3993 * packet we need to filter.
3994 * Note: alternatively it could be possible to stop applying
3995 * the filter when the ring became empty, but it can possibly
3996 * happen a lot later... */
3997 bp = (unsigned char*)h.raw + tp_mac;
3998 run_bpf = (!handle->md.use_bpf) ||
3999 ((handle->md.use_bpf>1) && handle->md.use_bpf--);
4000 if (run_bpf && handle->fcode.bf_insns &&
4001 (bpf_filter(handle->fcode.bf_insns, bp,
4002 tp_len, tp_snaplen) == 0))
4003 goto skip;
4006 * Do checks based on packet direction.
4008 sll = (void *)h.raw + TPACKET_ALIGN(handle->md.tp_hdrlen);
4009 if (sll->sll_pkttype == PACKET_OUTGOING) {
4011 * Outgoing packet.
4012 * If this is from the loopback device, reject it;
4013 * we'll see the packet as an incoming packet as well,
4014 * and we don't want to see it twice.
4016 if (sll->sll_ifindex == handle->md.lo_ifindex)
4017 goto skip;
4020 * If the user only wants incoming packets, reject it.
4022 if (handle->direction == PCAP_D_IN)
4023 goto skip;
4024 } else {
4026 * Incoming packet.
4027 * If the user only wants outgoing packets, reject it.
4029 if (handle->direction == PCAP_D_OUT)
4030 goto skip;
4033 /* get required packet info from ring header */
4034 pcaphdr.ts.tv_sec = tp_sec;
4035 pcaphdr.ts.tv_usec = tp_usec;
4036 pcaphdr.caplen = tp_snaplen;
4037 pcaphdr.len = tp_len;
4039 /* if required build in place the sll header*/
4040 if (handle->md.cooked) {
4041 struct sll_header *hdrp;
4044 * The kernel should have left us with enough
4045 * space for an sll header; back up the packet
4046 * data pointer into that space, as that'll be
4047 * the beginning of the packet we pass to the
4048 * callback.
4050 bp -= SLL_HDR_LEN;
4053 * Let's make sure that's past the end of
4054 * the tpacket header, i.e. >=
4055 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4056 * don't step on the header when we construct
4057 * the sll header.
4059 if (bp < (u_char *)h.raw +
4060 TPACKET_ALIGN(handle->md.tp_hdrlen) +
4061 sizeof(struct sockaddr_ll)) {
4062 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4063 "cooked-mode frame doesn't have room for sll header");
4064 return -1;
4068 * OK, that worked; construct the sll header.
4070 hdrp = (struct sll_header *)bp;
4071 hdrp->sll_pkttype = map_packet_type_to_sll_type(
4072 sll->sll_pkttype);
4073 hdrp->sll_hatype = htons(sll->sll_hatype);
4074 hdrp->sll_halen = htons(sll->sll_halen);
4075 memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
4076 hdrp->sll_protocol = sll->sll_protocol;
4078 /* update packet len */
4079 pcaphdr.caplen += SLL_HDR_LEN;
4080 pcaphdr.len += SLL_HDR_LEN;
4083 #ifdef HAVE_TPACKET2
4084 if (handle->md.tp_version == TPACKET_V2 && h.h2->tp_vlan_tci &&
4085 tp_snaplen >= 2 * ETH_ALEN) {
4086 struct vlan_tag *tag;
4088 bp -= VLAN_TAG_LEN;
4089 memmove(bp, bp + VLAN_TAG_LEN, 2 * ETH_ALEN);
4091 tag = (struct vlan_tag *)(bp + 2 * ETH_ALEN);
4092 tag->vlan_tpid = htons(ETH_P_8021Q);
4093 tag->vlan_tci = htons(h.h2->tp_vlan_tci);
4095 pcaphdr.caplen += VLAN_TAG_LEN;
4096 pcaphdr.len += VLAN_TAG_LEN;
4098 #endif
4101 * The only way to tell the kernel to cut off the
4102 * packet at a snapshot length is with a filter program;
4103 * if there's no filter program, the kernel won't cut
4104 * the packet off.
4106 * Trim the snapshot length to be no longer than the
4107 * specified snapshot length.
4109 if (pcaphdr.caplen > handle->snapshot)
4110 pcaphdr.caplen = handle->snapshot;
4112 /* pass the packet to the user */
4113 pkts++;
4114 callback(user, &pcaphdr, bp);
4115 handle->md.packets_read++;
4117 skip:
4118 /* next packet */
4119 switch (handle->md.tp_version) {
4120 case TPACKET_V1:
4121 h.h1->tp_status = TP_STATUS_KERNEL;
4122 break;
4123 #ifdef HAVE_TPACKET2
4124 case TPACKET_V2:
4125 h.h2->tp_status = TP_STATUS_KERNEL;
4126 break;
4127 #endif
4129 if (++handle->offset >= handle->cc)
4130 handle->offset = 0;
4132 /* check for break loop condition*/
4133 if (handle->break_loop) {
4134 handle->break_loop = 0;
4135 return PCAP_ERROR_BREAK;
4138 return pkts;
4141 static int
4142 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
4144 int n, offset;
4145 int ret;
4148 * Don't rewrite "ret" instructions; we don't need to, as
4149 * we're not reading packets with recvmsg(), and we don't
4150 * want to, as, by not rewriting them, the kernel can avoid
4151 * copying extra data.
4153 ret = pcap_setfilter_linux_common(handle, filter, 1);
4154 if (ret < 0)
4155 return ret;
4157 /* if the kernel filter is enabled, we need to apply the filter on
4158 * all packets present into the ring. Get an upper bound of their number
4160 if (!handle->md.use_bpf)
4161 return ret;
4163 /* walk the ring backward and count the free slot */
4164 offset = handle->offset;
4165 if (--handle->offset < 0)
4166 handle->offset = handle->cc - 1;
4167 for (n=0; n < handle->cc; ++n) {
4168 if (--handle->offset < 0)
4169 handle->offset = handle->cc - 1;
4170 if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
4171 break;
4174 /* be careful to not change current ring position */
4175 handle->offset = offset;
4177 /* store the number of packets currently present in the ring */
4178 handle->md.use_bpf = 1 + (handle->cc - n);
4179 return ret;
4182 #endif /* HAVE_PACKET_RING */
4185 #ifdef HAVE_PF_PACKET_SOCKETS
4187 * Return the index of the given device name. Fill ebuf and return
4188 * -1 on failure.
4190 static int
4191 iface_get_id(int fd, const char *device, char *ebuf)
4193 struct ifreq ifr;
4195 memset(&ifr, 0, sizeof(ifr));
4196 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4198 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
4199 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4200 "SIOCGIFINDEX: %s", pcap_strerror(errno));
4201 return -1;
4204 return ifr.ifr_ifindex;
4208 * Bind the socket associated with FD to the given device.
4209 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4210 * or a PCAP_ERROR_ value on a hard error.
4212 static int
4213 iface_bind(int fd, int ifindex, char *ebuf)
4215 struct sockaddr_ll sll;
4216 int err;
4217 socklen_t errlen = sizeof(err);
4219 memset(&sll, 0, sizeof(sll));
4220 sll.sll_family = AF_PACKET;
4221 sll.sll_ifindex = ifindex;
4222 sll.sll_protocol = htons(ETH_P_ALL);
4224 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
4225 if (errno == ENETDOWN) {
4227 * Return a "network down" indication, so that
4228 * the application can report that rather than
4229 * saying we had a mysterious failure and
4230 * suggest that they report a problem to the
4231 * libpcap developers.
4233 return PCAP_ERROR_IFACE_NOT_UP;
4234 } else {
4235 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4236 "bind: %s", pcap_strerror(errno));
4237 return PCAP_ERROR;
4241 /* Any pending errors, e.g., network is down? */
4243 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
4244 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4245 "getsockopt: %s", pcap_strerror(errno));
4246 return 0;
4249 if (err == ENETDOWN) {
4251 * Return a "network down" indication, so that
4252 * the application can report that rather than
4253 * saying we had a mysterious failure and
4254 * suggest that they report a problem to the
4255 * libpcap developers.
4257 return PCAP_ERROR_IFACE_NOT_UP;
4258 } else if (err > 0) {
4259 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4260 "bind: %s", pcap_strerror(err));
4261 return 0;
4264 return 1;
4267 #ifdef IW_MODE_MONITOR
4269 * Check whether the device supports the Wireless Extensions.
4270 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4271 * if the device doesn't even exist.
4273 static int
4274 has_wext(int sock_fd, const char *device, char *ebuf)
4276 struct iwreq ireq;
4278 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4279 sizeof ireq.ifr_ifrn.ifrn_name);
4280 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4281 if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
4282 return 1; /* yes */
4283 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4284 "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
4285 if (errno == ENODEV)
4286 return PCAP_ERROR_NO_SUCH_DEVICE;
4287 return 0;
4291 * Per me si va ne la citta dolente,
4292 * Per me si va ne l'etterno dolore,
4293 * ...
4294 * Lasciate ogne speranza, voi ch'intrate.
4296 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4297 * wlan-ng driver.
4299 typedef enum {
4300 MONITOR_WEXT,
4301 MONITOR_HOSTAP,
4302 MONITOR_PRISM,
4303 MONITOR_PRISM54,
4304 MONITOR_ACX100,
4305 MONITOR_RT2500,
4306 MONITOR_RT2570,
4307 MONITOR_RT73,
4308 MONITOR_RTL8XXX
4309 } monitor_type;
4312 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4313 * on if it's not already on.
4315 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4316 * on this device, or a PCAP_ERROR_ value if we do support them but
4317 * we weren't able to turn monitor mode on.
4319 static int
4320 enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
4323 * XXX - at least some adapters require non-Wireless Extensions
4324 * mechanisms to turn monitor mode on.
4326 * Atheros cards might require that a separate "monitor virtual access
4327 * point" be created, with later versions of the madwifi driver.
4328 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4329 * monitor -bssid", which apparently spits out a line "athN"
4330 * where "athN" is the monitor mode device. To leave monitor
4331 * mode, it destroys the monitor mode device.
4333 * Some Intel Centrino adapters might require private ioctls to get
4334 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4335 * configure a separate "rtapN" interface to capture in monitor
4336 * mode without preventing the adapter from operating normally.
4337 * (airmon-ng doesn't appear to use that, though.)
4339 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4340 * up, and if all drivers were converted to mac80211 drivers.
4342 * If interface {if} is a mac80211 driver, the file
4343 * /sys/class/net/{if}/phy80211 is a symlink to
4344 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4346 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4347 * least, has a "wmaster0" device and a "wlan0" device; the
4348 * latter is the one with the IP address. Both show up in
4349 * "tcpdump -D" output. Capturing on the wmaster0 device
4350 * captures with 802.11 headers.
4352 * airmon-ng searches through /sys/class/net for devices named
4353 * monN, starting with mon0; as soon as one *doesn't* exist,
4354 * it chooses that as the monitor device name. If the "iw"
4355 * command exists, it does "iw dev {if} interface add {monif}
4356 * type monitor", where {monif} is the monitor device. It
4357 * then (sigh) sleeps .1 second, and then configures the
4358 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4359 * is a file, it writes {mondev}, without a newline, to that file,
4360 * and again (sigh) sleeps .1 second, and then iwconfig's that
4361 * device into monitor mode and configures it up. Otherwise,
4362 * you can't do monitor mode.
4364 * All these devices are "glued" together by having the
4365 * /sys/class/net/{device}/phy80211 links pointing to the same
4366 * place, so, given a wmaster, wlan, or mon device, you can
4367 * find the other devices by looking for devices with
4368 * the same phy80211 link.
4370 * To turn monitor mode off, delete the monitor interface,
4371 * either with "iw dev {monif} interface del" or by sending
4372 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4374 * Note: if you try to create a monitor device named "monN", and
4375 * there's already a "monN" device, it fails, as least with
4376 * the netlink interface (which is what iw uses), with a return
4377 * value of -ENFILE. (Return values are negative errnos.) We
4378 * could probably use that to find an unused device.
4380 int err;
4381 struct iwreq ireq;
4382 struct iw_priv_args *priv;
4383 monitor_type montype;
4384 int i;
4385 __u32 cmd;
4386 struct ifreq ifr;
4387 int oldflags;
4388 int args[2];
4389 int channel;
4392 * Does this device *support* the Wireless Extensions?
4394 err = has_wext(sock_fd, device, handle->errbuf);
4395 if (err <= 0)
4396 return err; /* either it doesn't or the device doesn't even exist */
4398 * Start out assuming we have no private extensions to control
4399 * radio metadata.
4401 montype = MONITOR_WEXT;
4402 cmd = 0;
4405 * Try to get all the Wireless Extensions private ioctls
4406 * supported by this device.
4408 * First, get the size of the buffer we need, by supplying no
4409 * buffer and a length of 0. If the device supports private
4410 * ioctls, it should return E2BIG, with ireq.u.data.length set
4411 * to the length we need. If it doesn't support them, it should
4412 * return EOPNOTSUPP.
4414 memset(&ireq, 0, sizeof ireq);
4415 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4416 sizeof ireq.ifr_ifrn.ifrn_name);
4417 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4418 ireq.u.data.pointer = (void *)args;
4419 ireq.u.data.length = 0;
4420 ireq.u.data.flags = 0;
4421 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
4422 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4423 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4424 device);
4425 return PCAP_ERROR;
4427 if (errno != EOPNOTSUPP) {
4429 * OK, it's not as if there are no private ioctls.
4431 if (errno != E2BIG) {
4433 * Failed.
4435 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4436 "%s: SIOCGIWPRIV: %s", device,
4437 pcap_strerror(errno));
4438 return PCAP_ERROR;
4442 * OK, try to get the list of private ioctls.
4444 priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
4445 if (priv == NULL) {
4446 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4447 "malloc: %s", pcap_strerror(errno));
4448 return PCAP_ERROR;
4450 ireq.u.data.pointer = (void *)priv;
4451 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
4452 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4453 "%s: SIOCGIWPRIV: %s", device,
4454 pcap_strerror(errno));
4455 free(priv);
4456 return PCAP_ERROR;
4460 * Look for private ioctls to turn monitor mode on or, if
4461 * monitor mode is on, to set the header type.
4463 for (i = 0; i < ireq.u.data.length; i++) {
4464 if (strcmp(priv[i].name, "monitor_type") == 0) {
4466 * Hostap driver, use this one.
4467 * Set monitor mode first.
4468 * You can set it to 0 to get DLT_IEEE80211,
4469 * 1 to get DLT_PRISM, 2 to get
4470 * DLT_IEEE80211_RADIO_AVS, and, with more
4471 * recent versions of the driver, 3 to get
4472 * DLT_IEEE80211_RADIO.
4474 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4475 break;
4476 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4477 break;
4478 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4479 break;
4480 montype = MONITOR_HOSTAP;
4481 cmd = priv[i].cmd;
4482 break;
4484 if (strcmp(priv[i].name, "set_prismhdr") == 0) {
4486 * Prism54 driver, use this one.
4487 * Set monitor mode first.
4488 * You can set it to 2 to get DLT_IEEE80211
4489 * or 3 or get DLT_PRISM.
4491 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4492 break;
4493 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4494 break;
4495 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4496 break;
4497 montype = MONITOR_PRISM54;
4498 cmd = priv[i].cmd;
4499 break;
4501 if (strcmp(priv[i].name, "forceprismheader") == 0) {
4503 * RT2570 driver, use this one.
4504 * Do this after turning monitor mode on.
4505 * You can set it to 1 to get DLT_PRISM or 2
4506 * to get DLT_IEEE80211.
4508 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4509 break;
4510 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4511 break;
4512 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4513 break;
4514 montype = MONITOR_RT2570;
4515 cmd = priv[i].cmd;
4516 break;
4518 if (strcmp(priv[i].name, "forceprism") == 0) {
4520 * RT73 driver, use this one.
4521 * Do this after turning monitor mode on.
4522 * Its argument is a *string*; you can
4523 * set it to "1" to get DLT_PRISM or "2"
4524 * to get DLT_IEEE80211.
4526 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
4527 break;
4528 if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
4529 break;
4530 montype = MONITOR_RT73;
4531 cmd = priv[i].cmd;
4532 break;
4534 if (strcmp(priv[i].name, "prismhdr") == 0) {
4536 * One of the RTL8xxx drivers, use this one.
4537 * It can only be done after monitor mode
4538 * has been turned on. You can set it to 1
4539 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4541 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4542 break;
4543 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4544 break;
4545 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4546 break;
4547 montype = MONITOR_RTL8XXX;
4548 cmd = priv[i].cmd;
4549 break;
4551 if (strcmp(priv[i].name, "rfmontx") == 0) {
4553 * RT2500 or RT61 driver, use this one.
4554 * It has one one-byte parameter; set
4555 * u.data.length to 1 and u.data.pointer to
4556 * point to the parameter.
4557 * It doesn't itself turn monitor mode on.
4558 * You can set it to 1 to allow transmitting
4559 * in monitor mode(?) and get DLT_IEEE80211,
4560 * or set it to 0 to disallow transmitting in
4561 * monitor mode(?) and get DLT_PRISM.
4563 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4564 break;
4565 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
4566 break;
4567 montype = MONITOR_RT2500;
4568 cmd = priv[i].cmd;
4569 break;
4571 if (strcmp(priv[i].name, "monitor") == 0) {
4573 * Either ACX100 or hostap, use this one.
4574 * It turns monitor mode on.
4575 * If it takes two arguments, it's ACX100;
4576 * the first argument is 1 for DLT_PRISM
4577 * or 2 for DLT_IEEE80211, and the second
4578 * argument is the channel on which to
4579 * run. If it takes one argument, it's
4580 * HostAP, and the argument is 2 for
4581 * DLT_IEEE80211 and 3 for DLT_PRISM.
4583 * If we see this, we don't quit, as this
4584 * might be a version of the hostap driver
4585 * that also supports "monitor_type".
4587 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4588 break;
4589 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4590 break;
4591 switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
4593 case 1:
4594 montype = MONITOR_PRISM;
4595 cmd = priv[i].cmd;
4596 break;
4598 case 2:
4599 montype = MONITOR_ACX100;
4600 cmd = priv[i].cmd;
4601 break;
4603 default:
4604 break;
4608 free(priv);
4612 * XXX - ipw3945? islism?
4616 * Get the old mode.
4618 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4619 sizeof ireq.ifr_ifrn.ifrn_name);
4620 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4621 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
4623 * We probably won't be able to set the mode, either.
4625 return PCAP_ERROR_RFMON_NOTSUP;
4629 * Is it currently in monitor mode?
4631 if (ireq.u.mode == IW_MODE_MONITOR) {
4633 * Yes. Just leave things as they are.
4634 * We don't offer multiple link-layer types, as
4635 * changing the link-layer type out from under
4636 * somebody else capturing in monitor mode would
4637 * be considered rude.
4639 return 1;
4642 * No. We have to put the adapter into rfmon mode.
4646 * If we haven't already done so, arrange to have
4647 * "pcap_close_all()" called when we exit.
4649 if (!pcap_do_addexit(handle)) {
4651 * "atexit()" failed; don't put the interface
4652 * in rfmon mode, just give up.
4654 return PCAP_ERROR_RFMON_NOTSUP;
4658 * Save the old mode.
4660 handle->md.oldmode = ireq.u.mode;
4663 * Put the adapter in rfmon mode. How we do this depends
4664 * on whether we have a special private ioctl or not.
4666 if (montype == MONITOR_PRISM) {
4668 * We have the "monitor" private ioctl, but none of
4669 * the other private ioctls. Use this, and select
4670 * the Prism header.
4672 * If it fails, just fall back on SIOCSIWMODE.
4674 memset(&ireq, 0, sizeof ireq);
4675 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4676 sizeof ireq.ifr_ifrn.ifrn_name);
4677 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4678 ireq.u.data.length = 1; /* 1 argument */
4679 args[0] = 3; /* request Prism header */
4680 memcpy(ireq.u.name, args, IFNAMSIZ);
4681 if (ioctl(sock_fd, cmd, &ireq) != -1) {
4683 * Success.
4684 * Note that we have to put the old mode back
4685 * when we close the device.
4687 handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4690 * Add this to the list of pcaps to close
4691 * when we exit.
4693 pcap_add_to_pcaps_to_close(handle);
4695 return 1;
4699 * Failure. Fall back on SIOCSIWMODE.
4704 * First, take the interface down if it's up; otherwise, we
4705 * might get EBUSY.
4707 memset(&ifr, 0, sizeof(ifr));
4708 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4709 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
4710 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4711 "%s: Can't get flags: %s", device, strerror(errno));
4712 return PCAP_ERROR;
4714 oldflags = 0;
4715 if (ifr.ifr_flags & IFF_UP) {
4716 oldflags = ifr.ifr_flags;
4717 ifr.ifr_flags &= ~IFF_UP;
4718 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4719 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4720 "%s: Can't set flags: %s", device, strerror(errno));
4721 return PCAP_ERROR;
4726 * Then turn monitor mode on.
4728 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4729 sizeof ireq.ifr_ifrn.ifrn_name);
4730 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4731 ireq.u.mode = IW_MODE_MONITOR;
4732 if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
4734 * Scientist, you've failed.
4735 * Bring the interface back up if we shut it down.
4737 ifr.ifr_flags = oldflags;
4738 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4739 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4740 "%s: Can't set flags: %s", device, strerror(errno));
4741 return PCAP_ERROR;
4743 return PCAP_ERROR_RFMON_NOTSUP;
4747 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4748 * monitor mode and setting the channel, and then does
4749 * "iwconfig up".
4753 * Now select the appropriate radio header.
4755 switch (montype) {
4757 case MONITOR_WEXT:
4759 * We don't have any private ioctl to set the header.
4761 break;
4763 case MONITOR_HOSTAP:
4765 * Try to select the radiotap header.
4767 memset(&ireq, 0, sizeof ireq);
4768 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4769 sizeof ireq.ifr_ifrn.ifrn_name);
4770 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4771 args[0] = 3; /* request radiotap header */
4772 memcpy(ireq.u.name, args, sizeof (int));
4773 if (ioctl(sock_fd, cmd, &ireq) != -1)
4774 break; /* success */
4777 * That failed. Try to select the AVS header.
4779 memset(&ireq, 0, sizeof ireq);
4780 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4781 sizeof ireq.ifr_ifrn.ifrn_name);
4782 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4783 args[0] = 2; /* request AVS header */
4784 memcpy(ireq.u.name, args, sizeof (int));
4785 if (ioctl(sock_fd, cmd, &ireq) != -1)
4786 break; /* success */
4789 * That failed. Try to select the Prism header.
4791 memset(&ireq, 0, sizeof ireq);
4792 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4793 sizeof ireq.ifr_ifrn.ifrn_name);
4794 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4795 args[0] = 1; /* request Prism header */
4796 memcpy(ireq.u.name, args, sizeof (int));
4797 ioctl(sock_fd, cmd, &ireq);
4798 break;
4800 case MONITOR_PRISM:
4802 * The private ioctl failed.
4804 break;
4806 case MONITOR_PRISM54:
4808 * Select the Prism header.
4810 memset(&ireq, 0, sizeof ireq);
4811 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4812 sizeof ireq.ifr_ifrn.ifrn_name);
4813 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4814 args[0] = 3; /* request Prism header */
4815 memcpy(ireq.u.name, args, sizeof (int));
4816 ioctl(sock_fd, cmd, &ireq);
4817 break;
4819 case MONITOR_ACX100:
4821 * Get the current channel.
4823 memset(&ireq, 0, sizeof ireq);
4824 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4825 sizeof ireq.ifr_ifrn.ifrn_name);
4826 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4827 if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
4828 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4829 "%s: SIOCGIWFREQ: %s", device,
4830 pcap_strerror(errno));
4831 return PCAP_ERROR;
4833 channel = ireq.u.freq.m;
4836 * Select the Prism header, and set the channel to the
4837 * current value.
4839 memset(&ireq, 0, sizeof ireq);
4840 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4841 sizeof ireq.ifr_ifrn.ifrn_name);
4842 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4843 args[0] = 1; /* request Prism header */
4844 args[1] = channel; /* set channel */
4845 memcpy(ireq.u.name, args, 2*sizeof (int));
4846 ioctl(sock_fd, cmd, &ireq);
4847 break;
4849 case MONITOR_RT2500:
4851 * Disallow transmission - that turns on the
4852 * Prism header.
4854 memset(&ireq, 0, sizeof ireq);
4855 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4856 sizeof ireq.ifr_ifrn.ifrn_name);
4857 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4858 args[0] = 0; /* disallow transmitting */
4859 memcpy(ireq.u.name, args, sizeof (int));
4860 ioctl(sock_fd, cmd, &ireq);
4861 break;
4863 case MONITOR_RT2570:
4865 * Force the Prism header.
4867 memset(&ireq, 0, sizeof ireq);
4868 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4869 sizeof ireq.ifr_ifrn.ifrn_name);
4870 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4871 args[0] = 1; /* request Prism header */
4872 memcpy(ireq.u.name, args, sizeof (int));
4873 ioctl(sock_fd, cmd, &ireq);
4874 break;
4876 case MONITOR_RT73:
4878 * Force the Prism header.
4880 memset(&ireq, 0, sizeof ireq);
4881 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4882 sizeof ireq.ifr_ifrn.ifrn_name);
4883 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4884 ireq.u.data.length = 1; /* 1 argument */
4885 ireq.u.data.pointer = "1";
4886 ireq.u.data.flags = 0;
4887 ioctl(sock_fd, cmd, &ireq);
4888 break;
4890 case MONITOR_RTL8XXX:
4892 * Force the Prism header.
4894 memset(&ireq, 0, sizeof ireq);
4895 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4896 sizeof ireq.ifr_ifrn.ifrn_name);
4897 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4898 args[0] = 1; /* request Prism header */
4899 memcpy(ireq.u.name, args, sizeof (int));
4900 ioctl(sock_fd, cmd, &ireq);
4901 break;
4905 * Now bring the interface back up if we brought it down.
4907 if (oldflags != 0) {
4908 ifr.ifr_flags = oldflags;
4909 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4910 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4911 "%s: Can't set flags: %s", device, strerror(errno));
4914 * At least try to restore the old mode on the
4915 * interface.
4917 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
4919 * Scientist, you've failed.
4921 fprintf(stderr,
4922 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
4923 "Please adjust manually.\n",
4924 strerror(errno));
4926 return PCAP_ERROR;
4931 * Note that we have to put the old mode back when we
4932 * close the device.
4934 handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4937 * Add this to the list of pcaps to close when we exit.
4939 pcap_add_to_pcaps_to_close(handle);
4941 return 1;
4943 #endif /* IW_MODE_MONITOR */
4946 * Try various mechanisms to enter monitor mode.
4948 static int
4949 enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
4951 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4952 int ret;
4953 #endif
4955 #ifdef HAVE_LIBNL
4956 ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
4957 if (ret < 0)
4958 return ret; /* error attempting to do so */
4959 if (ret == 1)
4960 return 1; /* success */
4961 #endif /* HAVE_LIBNL */
4963 #ifdef IW_MODE_MONITOR
4964 ret = enter_rfmon_mode_wext(handle, sock_fd, device);
4965 if (ret < 0)
4966 return ret; /* error attempting to do so */
4967 if (ret == 1)
4968 return 1; /* success */
4969 #endif /* IW_MODE_MONITOR */
4972 * Either none of the mechanisms we know about work or none
4973 * of those mechanisms are available, so we can't do monitor
4974 * mode.
4976 return 0;
4980 * Find out if we have any form of fragmentation/reassembly offloading.
4982 * We do so using SIOCETHTOOL checking for various types of offloading;
4983 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4984 * of the types of offloading, there's nothing we can do to check, so
4985 * we just say "no, we don't".
4987 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
4988 static int
4989 iface_ethtool_ioctl(pcap_t *handle, int cmd, const char *cmdname)
4991 struct ifreq ifr;
4992 struct ethtool_value eval;
4994 memset(&ifr, 0, sizeof(ifr));
4995 strncpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
4996 eval.cmd = cmd;
4997 ifr.ifr_data = (caddr_t)&eval;
4998 if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
4999 if (errno == EOPNOTSUPP) {
5001 * OK, let's just return 0, which, in our
5002 * case, either means "no, what we're asking
5003 * about is not enabled" or "all the flags
5004 * are clear (i.e., nothing is enabled)".
5006 return 0;
5008 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5009 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle->opt.source,
5010 cmdname, strerror(errno));
5011 return -1;
5013 return eval.data;
5016 static int
5017 iface_get_offload(pcap_t *handle)
5019 int ret;
5021 #ifdef ETHTOOL_GTSO
5022 ret = iface_ethtool_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO");
5023 if (ret == -1)
5024 return -1;
5025 if (ret)
5026 return 1; /* TCP segmentation offloading on */
5027 #endif
5029 #ifdef ETHTOOL_GUFO
5030 ret = iface_ethtool_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO");
5031 if (ret == -1)
5032 return -1;
5033 if (ret)
5034 return 1; /* UDP fragmentation offloading on */
5035 #endif
5037 #ifdef ETHTOOL_GGSO
5039 * XXX - will this cause large unsegmented packets to be
5040 * handed to PF_PACKET sockets on transmission? If not,
5041 * this need not be checked.
5043 ret = iface_ethtool_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO");
5044 if (ret == -1)
5045 return -1;
5046 if (ret)
5047 return 1; /* generic segmentation offloading on */
5048 #endif
5050 #ifdef ETHTOOL_GFLAGS
5051 ret = iface_ethtool_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS");
5052 if (ret == -1)
5053 return -1;
5054 if (ret & ETH_FLAG_LRO)
5055 return 1; /* large receive offloading on */
5056 #endif
5058 #ifdef ETHTOOL_GGRO
5060 * XXX - will this cause large reassembled packets to be
5061 * handed to PF_PACKET sockets on receipt? If not,
5062 * this need not be checked.
5064 ret = iface_ethtool_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO");
5065 if (ret == -1)
5066 return -1;
5067 if (ret)
5068 return 1; /* generic (large) receive offloading on */
5069 #endif
5071 return 0;
5073 #else /* SIOCETHTOOL */
5074 static int
5075 iface_get_offload(pcap_t *handle _U_)
5078 * XXX - do we need to get this information if we don't
5079 * have the ethtool ioctls? If so, how do we do that?
5081 return 0;
5083 #endif /* SIOCETHTOOL */
5085 #endif /* HAVE_PF_PACKET_SOCKETS */
5087 /* ===== Functions to interface to the older kernels ================== */
5090 * Try to open a packet socket using the old kernel interface.
5091 * Returns 1 on success and a PCAP_ERROR_ value on an error.
5093 static int
5094 activate_old(pcap_t *handle)
5096 int arptype;
5097 struct ifreq ifr;
5098 const char *device = handle->opt.source;
5099 struct utsname utsname;
5100 int mtu;
5102 /* Open the socket */
5104 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
5105 if (handle->fd == -1) {
5106 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5107 "socket: %s", pcap_strerror(errno));
5108 if (errno == EPERM || errno == EACCES) {
5110 * You don't have permission to open the
5111 * socket.
5113 return PCAP_ERROR_PERM_DENIED;
5114 } else {
5116 * Other error.
5118 return PCAP_ERROR;
5122 /* It worked - we are using the old interface */
5123 handle->md.sock_packet = 1;
5125 /* ...which means we get the link-layer header. */
5126 handle->md.cooked = 0;
5128 /* Bind to the given device */
5130 if (strcmp(device, "any") == 0) {
5131 strncpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
5132 PCAP_ERRBUF_SIZE);
5133 return PCAP_ERROR;
5135 if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
5136 return PCAP_ERROR;
5139 * Try to get the link-layer type.
5141 arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
5142 if (arptype < 0)
5143 return PCAP_ERROR;
5146 * Try to find the DLT_ type corresponding to that
5147 * link-layer type.
5149 map_arphrd_to_dlt(handle, arptype, 0);
5150 if (handle->linktype == -1) {
5151 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5152 "unknown arptype %d", arptype);
5153 return PCAP_ERROR;
5156 /* Go to promisc mode if requested */
5158 if (handle->opt.promisc) {
5159 memset(&ifr, 0, sizeof(ifr));
5160 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5161 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
5162 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5163 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
5164 return PCAP_ERROR;
5166 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
5168 * Promiscuous mode isn't currently on,
5169 * so turn it on, and remember that
5170 * we should turn it off when the
5171 * pcap_t is closed.
5175 * If we haven't already done so, arrange
5176 * to have "pcap_close_all()" called when
5177 * we exit.
5179 if (!pcap_do_addexit(handle)) {
5181 * "atexit()" failed; don't put
5182 * the interface in promiscuous
5183 * mode, just give up.
5185 return PCAP_ERROR;
5188 ifr.ifr_flags |= IFF_PROMISC;
5189 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
5190 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5191 "SIOCSIFFLAGS: %s",
5192 pcap_strerror(errno));
5193 return PCAP_ERROR;
5195 handle->md.must_do_on_close |= MUST_CLEAR_PROMISC;
5198 * Add this to the list of pcaps
5199 * to close when we exit.
5201 pcap_add_to_pcaps_to_close(handle);
5206 * Compute the buffer size.
5208 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5209 * kernel, and might require special handling - check.
5211 if (uname(&utsname) < 0 ||
5212 strncmp(utsname.release, "2.0", 3) == 0) {
5214 * Either we couldn't find out what kernel release
5215 * this is, or it's a 2.0[.x] kernel.
5217 * In the 2.0[.x] kernel, a "recvfrom()" on
5218 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5219 * return the number of bytes read, so if we pass
5220 * a length based on the snapshot length, it'll
5221 * return the number of bytes from the packet
5222 * copied to userland, not the actual length
5223 * of the packet.
5225 * This means that, for example, the IP dissector
5226 * in tcpdump will get handed a packet length less
5227 * than the length in the IP header, and will
5228 * complain about "truncated-ip".
5230 * So we don't bother trying to copy from the
5231 * kernel only the bytes in which we're interested,
5232 * but instead copy them all, just as the older
5233 * versions of libpcap for Linux did.
5235 * The buffer therefore needs to be big enough to
5236 * hold the largest packet we can get from this
5237 * device. Unfortunately, we can't get the MRU
5238 * of the network; we can only get the MTU. The
5239 * MTU may be too small, in which case a packet larger
5240 * than the buffer size will be truncated *and* we
5241 * won't get the actual packet size.
5243 * However, if the snapshot length is larger than
5244 * the buffer size based on the MTU, we use the
5245 * snapshot length as the buffer size, instead;
5246 * this means that with a sufficiently large snapshot
5247 * length we won't artificially truncate packets
5248 * to the MTU-based size.
5250 * This mess just one of many problems with packet
5251 * capture on 2.0[.x] kernels; you really want a
5252 * 2.2[.x] or later kernel if you want packet capture
5253 * to work well.
5255 mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
5256 if (mtu == -1)
5257 return PCAP_ERROR;
5258 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
5259 if (handle->bufsize < handle->snapshot)
5260 handle->bufsize = handle->snapshot;
5261 } else {
5263 * This is a 2.2[.x] or later kernel.
5265 * We can safely pass "recvfrom()" a byte count
5266 * based on the snapshot length.
5268 handle->bufsize = handle->snapshot;
5272 * Default value for offset to align link-layer payload
5273 * on a 4-byte boundary.
5275 handle->offset = 0;
5277 return 1;
5281 * Bind the socket associated with FD to the given device using the
5282 * interface of the old kernels.
5284 static int
5285 iface_bind_old(int fd, const char *device, char *ebuf)
5287 struct sockaddr saddr;
5288 int err;
5289 socklen_t errlen = sizeof(err);
5291 memset(&saddr, 0, sizeof(saddr));
5292 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
5293 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
5294 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5295 "bind: %s", pcap_strerror(errno));
5296 return -1;
5299 /* Any pending errors, e.g., network is down? */
5301 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
5302 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5303 "getsockopt: %s", pcap_strerror(errno));
5304 return -1;
5307 if (err > 0) {
5308 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5309 "bind: %s", pcap_strerror(err));
5310 return -1;
5313 return 0;
5317 /* ===== System calls available on all supported kernels ============== */
5320 * Query the kernel for the MTU of the given interface.
5322 static int
5323 iface_get_mtu(int fd, const char *device, char *ebuf)
5325 struct ifreq ifr;
5327 if (!device)
5328 return BIGGER_THAN_ALL_MTUS;
5330 memset(&ifr, 0, sizeof(ifr));
5331 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5333 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
5334 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5335 "SIOCGIFMTU: %s", pcap_strerror(errno));
5336 return -1;
5339 return ifr.ifr_mtu;
5343 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5345 static int
5346 iface_get_arptype(int fd, const char *device, char *ebuf)
5348 struct ifreq ifr;
5350 memset(&ifr, 0, sizeof(ifr));
5351 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5353 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
5354 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5355 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
5356 if (errno == ENODEV) {
5358 * No such device.
5360 return PCAP_ERROR_NO_SUCH_DEVICE;
5362 return PCAP_ERROR;
5365 return ifr.ifr_hwaddr.sa_family;
5368 #ifdef SO_ATTACH_FILTER
5369 static int
5370 fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
5372 size_t prog_size;
5373 register int i;
5374 register struct bpf_insn *p;
5375 struct bpf_insn *f;
5376 int len;
5379 * Make a copy of the filter, and modify that copy if
5380 * necessary.
5382 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
5383 len = handle->fcode.bf_len;
5384 f = (struct bpf_insn *)malloc(prog_size);
5385 if (f == NULL) {
5386 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5387 "malloc: %s", pcap_strerror(errno));
5388 return -1;
5390 memcpy(f, handle->fcode.bf_insns, prog_size);
5391 fcode->len = len;
5392 fcode->filter = (struct sock_filter *) f;
5394 for (i = 0; i < len; ++i) {
5395 p = &f[i];
5397 * What type of instruction is this?
5399 switch (BPF_CLASS(p->code)) {
5401 case BPF_RET:
5403 * It's a return instruction; are we capturing
5404 * in memory-mapped mode?
5406 if (!is_mmapped) {
5408 * No; is the snapshot length a constant,
5409 * rather than the contents of the
5410 * accumulator?
5412 if (BPF_MODE(p->code) == BPF_K) {
5414 * Yes - if the value to be returned,
5415 * i.e. the snapshot length, is
5416 * anything other than 0, make it
5417 * 65535, so that the packet is
5418 * truncated by "recvfrom()",
5419 * not by the filter.
5421 * XXX - there's nothing we can
5422 * easily do if it's getting the
5423 * value from the accumulator; we'd
5424 * have to insert code to force
5425 * non-zero values to be 65535.
5427 if (p->k != 0)
5428 p->k = 65535;
5431 break;
5433 case BPF_LD:
5434 case BPF_LDX:
5436 * It's a load instruction; is it loading
5437 * from the packet?
5439 switch (BPF_MODE(p->code)) {
5441 case BPF_ABS:
5442 case BPF_IND:
5443 case BPF_MSH:
5445 * Yes; are we in cooked mode?
5447 if (handle->md.cooked) {
5449 * Yes, so we need to fix this
5450 * instruction.
5452 if (fix_offset(p) < 0) {
5454 * We failed to do so.
5455 * Return 0, so our caller
5456 * knows to punt to userland.
5458 return 0;
5461 break;
5463 break;
5466 return 1; /* we succeeded */
5469 static int
5470 fix_offset(struct bpf_insn *p)
5473 * What's the offset?
5475 if (p->k >= SLL_HDR_LEN) {
5477 * It's within the link-layer payload; that starts at an
5478 * offset of 0, as far as the kernel packet filter is
5479 * concerned, so subtract the length of the link-layer
5480 * header.
5482 p->k -= SLL_HDR_LEN;
5483 } else if (p->k == 0) {
5485 * It's the packet type field; map it to the special magic
5486 * kernel offset for that field.
5488 p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
5489 } else if (p->k == 14) {
5491 * It's the protocol field; map it to the special magic
5492 * kernel offset for that field.
5494 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
5495 } else if ((bpf_int32)(p->k) > 0) {
5497 * It's within the header, but it's not one of those
5498 * fields; we can't do that in the kernel, so punt
5499 * to userland.
5501 return -1;
5503 return 0;
5506 static int
5507 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
5509 int total_filter_on = 0;
5510 int save_mode;
5511 int ret;
5512 int save_errno;
5515 * The socket filter code doesn't discard all packets queued
5516 * up on the socket when the filter is changed; this means
5517 * that packets that don't match the new filter may show up
5518 * after the new filter is put onto the socket, if those
5519 * packets haven't yet been read.
5521 * This means, for example, that if you do a tcpdump capture
5522 * with a filter, the first few packets in the capture might
5523 * be packets that wouldn't have passed the filter.
5525 * We therefore discard all packets queued up on the socket
5526 * when setting a kernel filter. (This isn't an issue for
5527 * userland filters, as the userland filtering is done after
5528 * packets are queued up.)
5530 * To flush those packets, we put the socket in read-only mode,
5531 * and read packets from the socket until there are no more to
5532 * read.
5534 * In order to keep that from being an infinite loop - i.e.,
5535 * to keep more packets from arriving while we're draining
5536 * the queue - we put the "total filter", which is a filter
5537 * that rejects all packets, onto the socket before draining
5538 * the queue.
5540 * This code deliberately ignores any errors, so that you may
5541 * get bogus packets if an error occurs, rather than having
5542 * the filtering done in userland even if it could have been
5543 * done in the kernel.
5545 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
5546 &total_fcode, sizeof(total_fcode)) == 0) {
5547 char drain[1];
5550 * Note that we've put the total filter onto the socket.
5552 total_filter_on = 1;
5555 * Save the socket's current mode, and put it in
5556 * non-blocking mode; we drain it by reading packets
5557 * until we get an error (which is normally a
5558 * "nothing more to be read" error).
5560 save_mode = fcntl(handle->fd, F_GETFL, 0);
5561 if (save_mode != -1 &&
5562 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
5563 while (recv(handle->fd, &drain, sizeof drain,
5564 MSG_TRUNC) >= 0)
5566 save_errno = errno;
5567 fcntl(handle->fd, F_SETFL, save_mode);
5568 if (save_errno != EAGAIN) {
5569 /* Fatal error */
5570 reset_kernel_filter(handle);
5571 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5572 "recv: %s", pcap_strerror(save_errno));
5573 return -2;
5579 * Now attach the new filter.
5581 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
5582 fcode, sizeof(*fcode));
5583 if (ret == -1 && total_filter_on) {
5585 * Well, we couldn't set that filter on the socket,
5586 * but we could set the total filter on the socket.
5588 * This could, for example, mean that the filter was
5589 * too big to put into the kernel, so we'll have to
5590 * filter in userland; in any case, we'll be doing
5591 * filtering in userland, so we need to remove the
5592 * total filter so we see packets.
5594 save_errno = errno;
5597 * XXX - if this fails, we're really screwed;
5598 * we have the total filter on the socket,
5599 * and it won't come off. What do we do then?
5601 reset_kernel_filter(handle);
5603 errno = save_errno;
5605 return ret;
5608 static int
5609 reset_kernel_filter(pcap_t *handle)
5612 * setsockopt() barfs unless it get a dummy parameter.
5613 * valgrind whines unless the value is initialized,
5614 * as it has no idea that setsockopt() ignores its
5615 * parameter.
5617 int dummy = 0;
5619 return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
5620 &dummy, sizeof(dummy));
5622 #endif