126175Sfenner/*
275107Sfenner *  pcap-linux.c: Packet capture interface to the Linux kernel
326175Sfenner *
475107Sfenner *  Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
575107Sfenner *  		       Sebastian Krahmer  <krahmer@cs.uni-potsdam.de>
6127664Sbms *
775107Sfenner *  License: BSD
8127664Sbms *
975107Sfenner *  Redistribution and use in source and binary forms, with or without
1075107Sfenner *  modification, are permitted provided that the following conditions
1175107Sfenner *  are met:
12127664Sbms *
1375107Sfenner *  1. Redistributions of source code must retain the above copyright
1475107Sfenner *     notice, this list of conditions and the following disclaimer.
1575107Sfenner *  2. Redistributions in binary form must reproduce the above copyright
1675107Sfenner *     notice, this list of conditions and the following disclaimer in
1775107Sfenner *     the documentation and/or other materials provided with the
1875107Sfenner *     distribution.
1975107Sfenner *  3. The names of the authors may not be used to endorse or promote
2075107Sfenner *     products derived from this software without specific prior
2175107Sfenner *     written permission.
22127664Sbms *
2375107Sfenner *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
2475107Sfenner *  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
2575107Sfenner *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26190225Srpaulo *
27190225Srpaulo *  Modifications:     Added PACKET_MMAP support
28190225Srpaulo *                     Paolo Abeni <paolo.abeni@email.it>
29190225Srpaulo *
30190225Srpaulo *                     based on previous works of:
31190225Srpaulo *                     Simon Patarin <patarin@cs.unibo.it>
32190225Srpaulo *                     Phil Wood <cpw@lanl.gov>
33214518Srpaulo *
34214518Srpaulo * Monitor-mode support for mac80211 includes code taken from the iw
35214518Srpaulo * command; the copyright notice for that code is
36214518Srpaulo *
37214518Srpaulo * Copyright (c) 2007, 2008	Johannes Berg
38214518Srpaulo * Copyright (c) 2007		Andy Lutomirski
39214518Srpaulo * Copyright (c) 2007		Mike Kershaw
40214518Srpaulo * Copyright (c) 2008		G��bor Stefanik
41214518Srpaulo *
42214518Srpaulo * All rights reserved.
43214518Srpaulo *
44214518Srpaulo * Redistribution and use in source and binary forms, with or without
45214518Srpaulo * modification, are permitted provided that the following conditions
46214518Srpaulo * are met:
47214518Srpaulo * 1. Redistributions of source code must retain the above copyright
48214518Srpaulo *    notice, this list of conditions and the following disclaimer.
49214518Srpaulo * 2. Redistributions in binary form must reproduce the above copyright
50214518Srpaulo *    notice, this list of conditions and the following disclaimer in the
51214518Srpaulo *    documentation and/or other materials provided with the distribution.
52214518Srpaulo * 3. The name of the author may not be used to endorse or promote products
53214518Srpaulo *    derived from this software without specific prior written permission.
54214518Srpaulo *
55214518Srpaulo * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
56214518Srpaulo * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
57214518Srpaulo * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
58214518Srpaulo * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
59214518Srpaulo * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
60214518Srpaulo * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
61214518Srpaulo * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
62214518Srpaulo * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
63214518Srpaulo * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64214518Srpaulo * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65214518Srpaulo * SUCH DAMAGE.
6626175Sfenner */
67127664Sbms
6826175Sfenner#ifndef lint
69127664Sbmsstatic const char rcsid[] _U_ =
70214518Srpaulo    "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.164 2008-12-14 22:00:57 guy Exp $ (LBL)";
7126175Sfenner#endif
7226175Sfenner
7375107Sfenner/*
7475107Sfenner * Known problems with 2.0[.x] kernels:
7575107Sfenner *
7675107Sfenner *   - The loopback device gives every packet twice; on 2.2[.x] kernels,
7775107Sfenner *     if we use PF_PACKET, we can filter out the transmitted version
7875107Sfenner *     of the packet by using data in the "sockaddr_ll" returned by
7975107Sfenner *     "recvfrom()", but, on 2.0[.x] kernels, we have to use
8075107Sfenner *     PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
8175107Sfenner *     "sockaddr_pkt" which doesn't give us enough information to let
8275107Sfenner *     us do that.
8375107Sfenner *
8475107Sfenner *   - We have to set the interface's IFF_PROMISC flag ourselves, if
8575107Sfenner *     we're to run in promiscuous mode, which means we have to turn
8675107Sfenner *     it off ourselves when we're done; the kernel doesn't keep track
8775107Sfenner *     of how many sockets are listening promiscuously, which means
8875107Sfenner *     it won't get turned off automatically when no sockets are
8975107Sfenner *     listening promiscuously.  We catch "pcap_close()" and, for
9075107Sfenner *     interfaces we put into promiscuous mode, take them out of
9175107Sfenner *     promiscuous mode - which isn't necessarily the right thing to
9275107Sfenner *     do, if another socket also requested promiscuous mode between
9375107Sfenner *     the time when we opened the socket and the time when we close
9475107Sfenner *     the socket.
9598530Sfenner *
9698530Sfenner *   - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
9798530Sfenner *     return the amount of data that you could have read, rather than
9898530Sfenner *     the amount that was returned, so we can't just allocate a buffer
9998530Sfenner *     whose size is the snapshot length and pass the snapshot length
10098530Sfenner *     as the byte count, and also pass MSG_TRUNC, so that the return
10198530Sfenner *     value tells us how long the packet was on the wire.
10298530Sfenner *
10398530Sfenner *     This means that, if we want to get the actual size of the packet,
10498530Sfenner *     so we can return it in the "len" field of the packet header,
10598530Sfenner *     we have to read the entire packet, not just the part that fits
10698530Sfenner *     within the snapshot length, and thus waste CPU time copying data
10798530Sfenner *     from the kernel that our caller won't see.
10898530Sfenner *
10998530Sfenner *     We have to get the actual size, and supply it in "len", because
11098530Sfenner *     otherwise, the IP dissector in tcpdump, for example, will complain
11198530Sfenner *     about "truncated-ip", as the packet will appear to have been
11298530Sfenner *     shorter, on the wire, than the IP header said it should have been.
11375107Sfenner */
11426175Sfenner
11575107Sfenner
116214518Srpaulo#define _GNU_SOURCE
117214518Srpaulo
11875107Sfenner#ifdef HAVE_CONFIG_H
11975107Sfenner#include "config.h"
12039291Sfenner#endif
12126175Sfenner
12226175Sfenner#include <errno.h>
123214518Srpaulo#include <stdio.h>
12426175Sfenner#include <stdlib.h>
125214518Srpaulo#include <ctype.h>
12675107Sfenner#include <unistd.h>
12775107Sfenner#include <fcntl.h>
12826175Sfenner#include <string.h>
129214518Srpaulo#include <limits.h>
130252281Sdelphij#include <sys/stat.h>
13175107Sfenner#include <sys/socket.h>
13275107Sfenner#include <sys/ioctl.h>
13375107Sfenner#include <sys/utsname.h>
134190225Srpaulo#include <sys/mman.h>
135214518Srpaulo#include <linux/if.h>
136252281Sdelphij#include <linux/if_packet.h>
13775107Sfenner#include <netinet/in.h>
13875107Sfenner#include <linux/if_ether.h>
13975107Sfenner#include <net/if_arp.h>
140190225Srpaulo#include <poll.h>
141214518Srpaulo#include <dirent.h>
14226175Sfenner
143190225Srpaulo#include "pcap-int.h"
144190225Srpaulo#include "pcap/sll.h"
145190225Srpaulo#include "pcap/vlan.h"
146190225Srpaulo
147190225Srpaulo/*
14898530Sfenner * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
14998530Sfenner * sockets rather than SOCK_PACKET sockets.
15098530Sfenner *
15198530Sfenner * To use them, we include <linux/if_packet.h> rather than
15298530Sfenner * <netpacket/packet.h>; we do so because
15398530Sfenner *
15498530Sfenner *	some Linux distributions (e.g., Slackware 4.0) have 2.2 or
15598530Sfenner *	later kernels and libc5, and don't provide a <netpacket/packet.h>
15698530Sfenner *	file;
15798530Sfenner *
15898530Sfenner *	not all versions of glibc2 have a <netpacket/packet.h> file
15998530Sfenner *	that defines stuff needed for some of the 2.4-or-later-kernel
16098530Sfenner *	features, so if the system has a 2.4 or later kernel, we
16198530Sfenner *	still can't use those features.
16298530Sfenner *
16398530Sfenner * We're already including a number of other <linux/XXX.h> headers, and
16498530Sfenner * this code is Linux-specific (no other OS has PF_PACKET sockets as
16598530Sfenner * a raw packet capture mechanism), so it's not as if you gain any
16698530Sfenner * useful portability by using <netpacket/packet.h>
16798530Sfenner *
16898530Sfenner * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
16998530Sfenner * isn't defined?  It only defines one data structure in 2.0.x, so
17098530Sfenner * it shouldn't cause any problems.
17198530Sfenner */
172127664Sbms#ifdef PF_PACKET
17398530Sfenner# include <linux/if_packet.h>
17426175Sfenner
17575107Sfenner /*
17698530Sfenner  * On at least some Linux distributions (for example, Red Hat 5.2),
17798530Sfenner  * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
17898530Sfenner  * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
17975107Sfenner  * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
18075107Sfenner  * the PACKET_xxx stuff.
18175107Sfenner  *
18275107Sfenner  * So we check whether PACKET_HOST is defined, and assume that we have
18375107Sfenner  * PF_PACKET sockets only if it is defined.
18475107Sfenner  */
18575107Sfenner# ifdef PACKET_HOST
18675107Sfenner#  define HAVE_PF_PACKET_SOCKETS
187190225Srpaulo#  ifdef PACKET_AUXDATA
188190225Srpaulo#   define HAVE_PACKET_AUXDATA
189190225Srpaulo#  endif /* PACKET_AUXDATA */
19075107Sfenner# endif /* PACKET_HOST */
191190225Srpaulo
192190225Srpaulo
193190225Srpaulo /* check for memory mapped access avaibility. We assume every needed
194190225Srpaulo  * struct is defined if the macro TPACKET_HDRLEN is defined, because it
195190225Srpaulo  * uses many ring related structs and macros */
196190225Srpaulo# ifdef TPACKET_HDRLEN
197190225Srpaulo#  define HAVE_PACKET_RING
198190225Srpaulo#  ifdef TPACKET2_HDRLEN
199190225Srpaulo#   define HAVE_TPACKET2
200190225Srpaulo#  else
201190225Srpaulo#   define TPACKET_V1	0
202190225Srpaulo#  endif /* TPACKET2_HDRLEN */
203190225Srpaulo# endif /* TPACKET_HDRLEN */
20498530Sfenner#endif /* PF_PACKET */
20575107Sfenner
20675107Sfenner#ifdef SO_ATTACH_FILTER
20775107Sfenner#include <linux/types.h>
20875107Sfenner#include <linux/filter.h>
20926175Sfenner#endif
21026175Sfenner
211236167Sdelphij/*
212236167Sdelphij * We need linux/sockios.h if we have linux/net_tstamp.h (for time stamp
213236167Sdelphij * specification) or linux/ethtool.h (for ethtool ioctls to get offloading
214236167Sdelphij * information).
215236167Sdelphij */
216236167Sdelphij#if defined(HAVE_LINUX_NET_TSTAMP_H) || defined(HAVE_LINUX_ETHTOOL_H)
217236167Sdelphij#include <linux/sockios.h>
218236167Sdelphij#endif
219236167Sdelphij
220236167Sdelphij#ifdef HAVE_LINUX_NET_TSTAMP_H
221236167Sdelphij#include <linux/net_tstamp.h>
222236167Sdelphij#endif
223236167Sdelphij
224236167Sdelphij/*
225236167Sdelphij * Got Wireless Extensions?
226236167Sdelphij */
227236167Sdelphij#ifdef HAVE_LINUX_WIRELESS_H
228236167Sdelphij#include <linux/wireless.h>
229236167Sdelphij#endif /* HAVE_LINUX_WIRELESS_H */
230236167Sdelphij
231236167Sdelphij/*
232236167Sdelphij * Got libnl?
233236167Sdelphij */
234236167Sdelphij#ifdef HAVE_LIBNL
235236167Sdelphij#include <linux/nl80211.h>
236236167Sdelphij
237236167Sdelphij#include <netlink/genl/genl.h>
238236167Sdelphij#include <netlink/genl/family.h>
239236167Sdelphij#include <netlink/genl/ctrl.h>
240236167Sdelphij#include <netlink/msg.h>
241236167Sdelphij#include <netlink/attr.h>
242236167Sdelphij#endif /* HAVE_LIBNL */
243236167Sdelphij
244236167Sdelphij/*
245236167Sdelphij * Got ethtool support?
246236167Sdelphij */
247236167Sdelphij#ifdef HAVE_LINUX_ETHTOOL_H
248236167Sdelphij#include <linux/ethtool.h>
249236167Sdelphij#endif
250236167Sdelphij
251190225Srpaulo#ifndef HAVE_SOCKLEN_T
25275107Sfennertypedef int		socklen_t;
25375107Sfenner#endif
25426175Sfenner
25575107Sfenner#ifndef MSG_TRUNC
25698530Sfenner/*
25798530Sfenner * This is being compiled on a system that lacks MSG_TRUNC; define it
25898530Sfenner * with the value it has in the 2.2 and later kernels, so that, on
25998530Sfenner * those kernels, when we pass it in the flags argument to "recvfrom()"
26098530Sfenner * we're passing the right value and thus get the MSG_TRUNC behavior
26198530Sfenner * we want.  (We don't get that behavior on 2.0[.x] kernels, because
26298530Sfenner * they didn't support MSG_TRUNC.)
26398530Sfenner */
26498530Sfenner#define MSG_TRUNC	0x20
26575107Sfenner#endif
26675107Sfenner
267127664Sbms#ifndef SOL_PACKET
268127664Sbms/*
269127664Sbms * This is being compiled on a system that lacks SOL_PACKET; define it
270127664Sbms * with the value it has in the 2.2 and later kernels, so that we can
271127664Sbms * set promiscuous mode in the good modern way rather than the old
272127664Sbms * 2.0-kernel crappy way.
273127664Sbms */
274127664Sbms#define SOL_PACKET	263
275127664Sbms#endif
276127664Sbms
27775107Sfenner#define MAX_LINKHEADER_SIZE	256
27875107Sfenner
279127664Sbms/*
280127664Sbms * When capturing on all interfaces we use this as the buffer size.
28175107Sfenner * Should be bigger then all MTUs that occur in real life.
28275107Sfenner * 64kB should be enough for now.
28375107Sfenner */
28475107Sfenner#define BIGGER_THAN_ALL_MTUS	(64*1024)
28575107Sfenner
28675107Sfenner/*
287190225Srpaulo * Prototypes for internal functions and methods.
28875107Sfenner */
289127664Sbmsstatic void map_arphrd_to_dlt(pcap_t *, int, int);
290190225Srpaulo#ifdef HAVE_PF_PACKET_SOCKETS
291190225Srpaulostatic short int map_packet_type_to_sll_type(short int);
292190225Srpaulo#endif
293190225Srpaulostatic int pcap_activate_linux(pcap_t *);
294190225Srpaulostatic int activate_old(pcap_t *);
295190225Srpaulostatic int activate_new(pcap_t *);
296236167Sdelphijstatic int activate_mmap(pcap_t *, int *);
297190225Srpaulostatic int pcap_can_set_rfmon_linux(pcap_t *);
298127664Sbmsstatic int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
29975107Sfennerstatic int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
300146768Ssamstatic int pcap_inject_linux(pcap_t *, const void *, size_t);
301127664Sbmsstatic int pcap_stats_linux(pcap_t *, struct pcap_stat *);
302127664Sbmsstatic int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
303162012Ssamstatic int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
304190225Srpaulostatic void pcap_cleanup_linux(pcap_t *);
30575107Sfenner
306190225Srpaulounion thdr {
307190225Srpaulo	struct tpacket_hdr	*h1;
308190225Srpaulo	struct tpacket2_hdr	*h2;
309190225Srpaulo	void			*raw;
310190225Srpaulo};
311190225Srpaulo
312190225Srpaulo#ifdef HAVE_PACKET_RING
313190225Srpaulo#define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
314190225Srpaulo
315190225Srpaulostatic void destroy_ring(pcap_t *handle);
316236167Sdelphijstatic int create_ring(pcap_t *handle, int *status);
317190225Srpaulostatic int prepare_tpacket_socket(pcap_t *handle);
318190225Srpaulostatic void pcap_cleanup_linux_mmap(pcap_t *);
319190225Srpaulostatic int pcap_read_linux_mmap(pcap_t *, int, pcap_handler , u_char *);
320190225Srpaulostatic int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
321190225Srpaulostatic int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
322190225Srpaulostatic int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
323214518Srpaulostatic void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
324214518Srpaulo    const u_char *bytes);
325190225Srpaulo#endif
326190225Srpaulo
32775107Sfenner/*
32875107Sfenner * Wrap some ioctl calls
32975107Sfenner */
33075107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
33175107Sfennerstatic int	iface_get_id(int fd, const char *device, char *ebuf);
332236167Sdelphij#endif /* HAVE_PF_PACKET_SOCKETS */
33375107Sfennerstatic int	iface_get_mtu(int fd, const char *device, char *ebuf);
33475107Sfennerstatic int 	iface_get_arptype(int fd, const char *device, char *ebuf);
33575107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
33675107Sfennerstatic int 	iface_bind(int fd, int ifindex, char *ebuf);
337214518Srpaulo#ifdef IW_MODE_MONITOR
338190225Srpaulostatic int	has_wext(int sock_fd, const char *device, char *ebuf);
339214518Srpaulo#endif /* IW_MODE_MONITOR */
340214518Srpaulostatic int	enter_rfmon_mode(pcap_t *handle, int sock_fd,
341190225Srpaulo    const char *device);
342214518Srpaulo#endif /* HAVE_PF_PACKET_SOCKETS */
343236167Sdelphijstatic int	iface_get_offload(pcap_t *handle);
34475107Sfennerstatic int 	iface_bind_old(int fd, const char *device, char *ebuf);
34575107Sfenner
34675107Sfenner#ifdef SO_ATTACH_FILTER
347214518Srpaulostatic int	fix_program(pcap_t *handle, struct sock_fprog *fcode,
348214518Srpaulo    int is_mapped);
34975107Sfennerstatic int	fix_offset(struct bpf_insn *p);
35098530Sfennerstatic int	set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
35198530Sfennerstatic int	reset_kernel_filter(pcap_t *handle);
35298530Sfenner
35398530Sfennerstatic struct sock_filter	total_insn
35498530Sfenner	= BPF_STMT(BPF_RET | BPF_K, 0);
35598530Sfennerstatic struct sock_fprog	total_fcode
35698530Sfenner	= { 1, &total_insn };
357236167Sdelphij#endif /* SO_ATTACH_FILTER */
35875107Sfenner
35975107Sfennerpcap_t *
360252281Sdelphijpcap_create_interface(const char *device, char *ebuf)
36126175Sfenner{
362190225Srpaulo	pcap_t *handle;
36398530Sfenner
364190225Srpaulo	handle = pcap_create_common(device, ebuf);
365190225Srpaulo	if (handle == NULL)
36675107Sfenner		return NULL;
367190225Srpaulo
368190225Srpaulo	handle->activate_op = pcap_activate_linux;
369190225Srpaulo	handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
370236167Sdelphij#if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
371236167Sdelphij	/*
372236167Sdelphij	 * We claim that we support:
373236167Sdelphij	 *
374236167Sdelphij	 *	software time stamps, with no details about their precision;
375236167Sdelphij	 *	hardware time stamps, synced to the host time;
376236167Sdelphij	 *	hardware time stamps, not synced to the host time.
377236167Sdelphij	 *
378236167Sdelphij	 * XXX - we can't ask a device whether it supports
379236167Sdelphij	 * hardware time stamps, so we just claim all devices do.
380236167Sdelphij	 */
381236167Sdelphij	handle->tstamp_type_count = 3;
382236167Sdelphij	handle->tstamp_type_list = malloc(3 * sizeof(u_int));
383236167Sdelphij	if (handle->tstamp_type_list == NULL) {
384236167Sdelphij		free(handle);
385236167Sdelphij		return NULL;
386236167Sdelphij	}
387236167Sdelphij	handle->tstamp_type_list[0] = PCAP_TSTAMP_HOST;
388236167Sdelphij	handle->tstamp_type_list[1] = PCAP_TSTAMP_ADAPTER;
389236167Sdelphij	handle->tstamp_type_list[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED;
390236167Sdelphij#endif
391236167Sdelphij
392190225Srpaulo	return handle;
393190225Srpaulo}
394190225Srpaulo
395214518Srpaulo#ifdef HAVE_LIBNL
396214518Srpaulo/*
397236167Sdelphij * If interface {if} is a mac80211 driver, the file
398236167Sdelphij * /sys/class/net/{if}/phy80211 is a symlink to
399236167Sdelphij * /sys/class/ieee80211/{phydev}, for some {phydev}.
400236167Sdelphij *
401236167Sdelphij * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
402236167Sdelphij * least, has a "wmaster0" device and a "wlan0" device; the
403236167Sdelphij * latter is the one with the IP address.  Both show up in
404236167Sdelphij * "tcpdump -D" output.  Capturing on the wmaster0 device
405236167Sdelphij * captures with 802.11 headers.
406236167Sdelphij *
407236167Sdelphij * airmon-ng searches through /sys/class/net for devices named
408236167Sdelphij * monN, starting with mon0; as soon as one *doesn't* exist,
409236167Sdelphij * it chooses that as the monitor device name.  If the "iw"
410236167Sdelphij * command exists, it does "iw dev {if} interface add {monif}
411236167Sdelphij * type monitor", where {monif} is the monitor device.  It
412236167Sdelphij * then (sigh) sleeps .1 second, and then configures the
413236167Sdelphij * device up.  Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
414236167Sdelphij * is a file, it writes {mondev}, without a newline, to that file,
415236167Sdelphij * and again (sigh) sleeps .1 second, and then iwconfig's that
416236167Sdelphij * device into monitor mode and configures it up.  Otherwise,
417236167Sdelphij * you can't do monitor mode.
418236167Sdelphij *
419236167Sdelphij * All these devices are "glued" together by having the
420236167Sdelphij * /sys/class/net/{device}/phy80211 links pointing to the same
421236167Sdelphij * place, so, given a wmaster, wlan, or mon device, you can
422236167Sdelphij * find the other devices by looking for devices with
423236167Sdelphij * the same phy80211 link.
424236167Sdelphij *
425236167Sdelphij * To turn monitor mode off, delete the monitor interface,
426236167Sdelphij * either with "iw dev {monif} interface del" or by sending
427236167Sdelphij * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
428236167Sdelphij *
429236167Sdelphij * Note: if you try to create a monitor device named "monN", and
430236167Sdelphij * there's already a "monN" device, it fails, as least with
431236167Sdelphij * the netlink interface (which is what iw uses), with a return
432236167Sdelphij * value of -ENFILE.  (Return values are negative errnos.)  We
433236167Sdelphij * could probably use that to find an unused device.
434236167Sdelphij *
435236167Sdelphij * Yes, you can have multiple monitor devices for a given
436236167Sdelphij * physical device.
437214518Srpaulo*/
438214518Srpaulo
439214518Srpaulo/*
440214518Srpaulo * Is this a mac80211 device?  If so, fill in the physical device path and
441214518Srpaulo * return 1; if not, return 0.  On an error, fill in handle->errbuf and
442214518Srpaulo * return PCAP_ERROR.
443214518Srpaulo */
444190225Srpaulostatic int
445214518Srpauloget_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
446214518Srpaulo    size_t phydev_max_pathlen)
447190225Srpaulo{
448214518Srpaulo	char *pathstr;
449214518Srpaulo	ssize_t bytes_read;
450214518Srpaulo
451214518Srpaulo	/*
452214518Srpaulo	 * Generate the path string for the symlink to the physical device.
453214518Srpaulo	 */
454214518Srpaulo	if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
455214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
456214518Srpaulo		    "%s: Can't generate path name string for /sys/class/net device",
457214518Srpaulo		    device);
458214518Srpaulo		return PCAP_ERROR;
459214518Srpaulo	}
460214518Srpaulo	bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
461214518Srpaulo	if (bytes_read == -1) {
462214518Srpaulo		if (errno == ENOENT || errno == EINVAL) {
463214518Srpaulo			/*
464214518Srpaulo			 * Doesn't exist, or not a symlink; assume that
465214518Srpaulo			 * means it's not a mac80211 device.
466214518Srpaulo			 */
467214518Srpaulo			free(pathstr);
468214518Srpaulo			return 0;
469214518Srpaulo		}
470214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
471214518Srpaulo		    "%s: Can't readlink %s: %s", device, pathstr,
472214518Srpaulo		    strerror(errno));
473214518Srpaulo		free(pathstr);
474214518Srpaulo		return PCAP_ERROR;
475214518Srpaulo	}
476214518Srpaulo	free(pathstr);
477214518Srpaulo	phydev_path[bytes_read] = '\0';
478214518Srpaulo	return 1;
479214518Srpaulo}
480214518Srpaulo
481252281Sdelphij#ifdef HAVE_LIBNL_SOCKETS
482236167Sdelphij#define get_nl_errmsg	nl_geterror
483236167Sdelphij#else
484236167Sdelphij/* libnl 2.x compatibility code */
485236167Sdelphij
486236167Sdelphij#define nl_sock nl_handle
487236167Sdelphij
488236167Sdelphijstatic inline struct nl_handle *
489236167Sdelphijnl_socket_alloc(void)
490236167Sdelphij{
491236167Sdelphij	return nl_handle_alloc();
492236167Sdelphij}
493236167Sdelphij
494236167Sdelphijstatic inline void
495236167Sdelphijnl_socket_free(struct nl_handle *h)
496236167Sdelphij{
497236167Sdelphij	nl_handle_destroy(h);
498236167Sdelphij}
499236167Sdelphij
500236167Sdelphij#define get_nl_errmsg	strerror
501236167Sdelphij
502236167Sdelphijstatic inline int
503236167Sdelphij__genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
504236167Sdelphij{
505236167Sdelphij	struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
506236167Sdelphij	if (!tmp)
507236167Sdelphij		return -ENOMEM;
508236167Sdelphij	*cache = tmp;
509236167Sdelphij	return 0;
510236167Sdelphij}
511236167Sdelphij#define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
512252281Sdelphij#endif /* !HAVE_LIBNL_SOCKETS */
513236167Sdelphij
514214518Srpaulostruct nl80211_state {
515236167Sdelphij	struct nl_sock *nl_sock;
516214518Srpaulo	struct nl_cache *nl_cache;
517214518Srpaulo	struct genl_family *nl80211;
518214518Srpaulo};
519214518Srpaulo
520214518Srpaulostatic int
521214518Srpaulonl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
522214518Srpaulo{
523236167Sdelphij	int err;
524236167Sdelphij
525236167Sdelphij	state->nl_sock = nl_socket_alloc();
526236167Sdelphij	if (!state->nl_sock) {
527214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
528214518Srpaulo		    "%s: failed to allocate netlink handle", device);
529214518Srpaulo		return PCAP_ERROR;
530214518Srpaulo	}
531214518Srpaulo
532236167Sdelphij	if (genl_connect(state->nl_sock)) {
533214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
534214518Srpaulo		    "%s: failed to connect to generic netlink", device);
535214518Srpaulo		goto out_handle_destroy;
536214518Srpaulo	}
537214518Srpaulo
538236167Sdelphij	err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
539236167Sdelphij	if (err < 0) {
540214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
541236167Sdelphij		    "%s: failed to allocate generic netlink cache: %s",
542236167Sdelphij		    device, get_nl_errmsg(-err));
543214518Srpaulo		goto out_handle_destroy;
544214518Srpaulo	}
545214518Srpaulo
546214518Srpaulo	state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
547214518Srpaulo	if (!state->nl80211) {
548214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
549214518Srpaulo		    "%s: nl80211 not found", device);
550214518Srpaulo		goto out_cache_free;
551214518Srpaulo	}
552214518Srpaulo
553214518Srpaulo	return 0;
554214518Srpaulo
555214518Srpauloout_cache_free:
556214518Srpaulo	nl_cache_free(state->nl_cache);
557214518Srpauloout_handle_destroy:
558236167Sdelphij	nl_socket_free(state->nl_sock);
559214518Srpaulo	return PCAP_ERROR;
560214518Srpaulo}
561214518Srpaulo
562214518Srpaulostatic void
563214518Srpaulonl80211_cleanup(struct nl80211_state *state)
564214518Srpaulo{
565214518Srpaulo	genl_family_put(state->nl80211);
566214518Srpaulo	nl_cache_free(state->nl_cache);
567236167Sdelphij	nl_socket_free(state->nl_sock);
568214518Srpaulo}
569214518Srpaulo
570214518Srpaulostatic int
571214518Srpauloadd_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
572214518Srpaulo    const char *device, const char *mondevice)
573214518Srpaulo{
574214518Srpaulo	int ifindex;
575214518Srpaulo	struct nl_msg *msg;
576214518Srpaulo	int err;
577214518Srpaulo
578214518Srpaulo	ifindex = iface_get_id(sock_fd, device, handle->errbuf);
579214518Srpaulo	if (ifindex == -1)
580214518Srpaulo		return PCAP_ERROR;
581214518Srpaulo
582214518Srpaulo	msg = nlmsg_alloc();
583214518Srpaulo	if (!msg) {
584214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
585214518Srpaulo		    "%s: failed to allocate netlink msg", device);
586214518Srpaulo		return PCAP_ERROR;
587214518Srpaulo	}
588214518Srpaulo
589214518Srpaulo	genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
590214518Srpaulo		    0, NL80211_CMD_NEW_INTERFACE, 0);
591214518Srpaulo	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
592214518Srpaulo	NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
593214518Srpaulo	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
594214518Srpaulo
595236167Sdelphij	err = nl_send_auto_complete(state->nl_sock, msg);
596214518Srpaulo	if (err < 0) {
597252281Sdelphij#if defined HAVE_LIBNL_NLE
598236167Sdelphij		if (err == -NLE_FAILURE) {
599236167Sdelphij#else
600214518Srpaulo		if (err == -ENFILE) {
601236167Sdelphij#endif
602214518Srpaulo			/*
603214518Srpaulo			 * Device not available; our caller should just
604236167Sdelphij			 * keep trying.  (libnl 2.x maps ENFILE to
605236167Sdelphij			 * NLE_FAILURE; it can also map other errors
606236167Sdelphij			 * to that, but there's not much we can do
607236167Sdelphij			 * about that.)
608214518Srpaulo			 */
609214518Srpaulo			nlmsg_free(msg);
610214518Srpaulo			return 0;
611214518Srpaulo		} else {
612214518Srpaulo			/*
613214518Srpaulo			 * Real failure, not just "that device is not
614214518Srpaulo			 * available.
615214518Srpaulo			 */
616214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
617214518Srpaulo			    "%s: nl_send_auto_complete failed adding %s interface: %s",
618236167Sdelphij			    device, mondevice, get_nl_errmsg(-err));
619214518Srpaulo			nlmsg_free(msg);
620214518Srpaulo			return PCAP_ERROR;
621214518Srpaulo		}
622214518Srpaulo	}
623236167Sdelphij	err = nl_wait_for_ack(state->nl_sock);
624214518Srpaulo	if (err < 0) {
625252281Sdelphij#if defined HAVE_LIBNL_NLE
626236167Sdelphij		if (err == -NLE_FAILURE) {
627236167Sdelphij#else
628214518Srpaulo		if (err == -ENFILE) {
629236167Sdelphij#endif
630214518Srpaulo			/*
631214518Srpaulo			 * Device not available; our caller should just
632236167Sdelphij			 * keep trying.  (libnl 2.x maps ENFILE to
633236167Sdelphij			 * NLE_FAILURE; it can also map other errors
634236167Sdelphij			 * to that, but there's not much we can do
635236167Sdelphij			 * about that.)
636214518Srpaulo			 */
637214518Srpaulo			nlmsg_free(msg);
638214518Srpaulo			return 0;
639214518Srpaulo		} else {
640214518Srpaulo			/*
641214518Srpaulo			 * Real failure, not just "that device is not
642214518Srpaulo			 * available.
643214518Srpaulo			 */
644214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
645214518Srpaulo			    "%s: nl_wait_for_ack failed adding %s interface: %s",
646236167Sdelphij			    device, mondevice, get_nl_errmsg(-err));
647214518Srpaulo			nlmsg_free(msg);
648214518Srpaulo			return PCAP_ERROR;
649214518Srpaulo		}
650214518Srpaulo	}
651214518Srpaulo
652214518Srpaulo	/*
653214518Srpaulo	 * Success.
654214518Srpaulo	 */
655214518Srpaulo	nlmsg_free(msg);
656214518Srpaulo	return 1;
657214518Srpaulo
658214518Srpaulonla_put_failure:
659214518Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
660214518Srpaulo	    "%s: nl_put failed adding %s interface",
661214518Srpaulo	    device, mondevice);
662214518Srpaulo	nlmsg_free(msg);
663214518Srpaulo	return PCAP_ERROR;
664214518Srpaulo}
665214518Srpaulo
666214518Srpaulostatic int
667214518Srpaulodel_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
668214518Srpaulo    const char *device, const char *mondevice)
669214518Srpaulo{
670214518Srpaulo	int ifindex;
671214518Srpaulo	struct nl_msg *msg;
672214518Srpaulo	int err;
673214518Srpaulo
674214518Srpaulo	ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
675214518Srpaulo	if (ifindex == -1)
676214518Srpaulo		return PCAP_ERROR;
677214518Srpaulo
678214518Srpaulo	msg = nlmsg_alloc();
679214518Srpaulo	if (!msg) {
680214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
681214518Srpaulo		    "%s: failed to allocate netlink msg", device);
682214518Srpaulo		return PCAP_ERROR;
683214518Srpaulo	}
684214518Srpaulo
685214518Srpaulo	genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
686214518Srpaulo		    0, NL80211_CMD_DEL_INTERFACE, 0);
687214518Srpaulo	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
688214518Srpaulo
689236167Sdelphij	err = nl_send_auto_complete(state->nl_sock, msg);
690214518Srpaulo	if (err < 0) {
691236167Sdelphij		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
692236167Sdelphij		    "%s: nl_send_auto_complete failed deleting %s interface: %s",
693236167Sdelphij		    device, mondevice, get_nl_errmsg(-err));
694236167Sdelphij		nlmsg_free(msg);
695236167Sdelphij		return PCAP_ERROR;
696214518Srpaulo	}
697236167Sdelphij	err = nl_wait_for_ack(state->nl_sock);
698214518Srpaulo	if (err < 0) {
699236167Sdelphij		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
700236167Sdelphij		    "%s: nl_wait_for_ack failed adding %s interface: %s",
701236167Sdelphij		    device, mondevice, get_nl_errmsg(-err));
702236167Sdelphij		nlmsg_free(msg);
703236167Sdelphij		return PCAP_ERROR;
704214518Srpaulo	}
705214518Srpaulo
706214518Srpaulo	/*
707214518Srpaulo	 * Success.
708214518Srpaulo	 */
709214518Srpaulo	nlmsg_free(msg);
710214518Srpaulo	return 1;
711214518Srpaulo
712214518Srpaulonla_put_failure:
713214518Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
714214518Srpaulo	    "%s: nl_put failed deleting %s interface",
715214518Srpaulo	    device, mondevice);
716214518Srpaulo	nlmsg_free(msg);
717214518Srpaulo	return PCAP_ERROR;
718214518Srpaulo}
719214518Srpaulo
720214518Srpaulostatic int
721214518Srpauloenter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
722214518Srpaulo{
723214518Srpaulo	int ret;
724214518Srpaulo	char phydev_path[PATH_MAX+1];
725214518Srpaulo	struct nl80211_state nlstate;
726214518Srpaulo	struct ifreq ifr;
727214518Srpaulo	u_int n;
728214518Srpaulo
729214518Srpaulo	/*
730214518Srpaulo	 * Is this a mac80211 device?
731214518Srpaulo	 */
732214518Srpaulo	ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
733214518Srpaulo	if (ret < 0)
734214518Srpaulo		return ret;	/* error */
735214518Srpaulo	if (ret == 0)
736214518Srpaulo		return 0;	/* no error, but not mac80211 device */
737214518Srpaulo
738214518Srpaulo	/*
739214518Srpaulo	 * XXX - is this already a monN device?
740214518Srpaulo	 * If so, we're done.
741214518Srpaulo	 * Is that determined by old Wireless Extensions ioctls?
742214518Srpaulo	 */
743214518Srpaulo
744214518Srpaulo	/*
745214518Srpaulo	 * OK, it's apparently a mac80211 device.
746214518Srpaulo	 * Try to find an unused monN device for it.
747214518Srpaulo	 */
748214518Srpaulo	ret = nl80211_init(handle, &nlstate, device);
749214518Srpaulo	if (ret != 0)
750214518Srpaulo		return ret;
751214518Srpaulo	for (n = 0; n < UINT_MAX; n++) {
752214518Srpaulo		/*
753214518Srpaulo		 * Try mon{n}.
754214518Srpaulo		 */
755214518Srpaulo		char mondevice[3+10+1];	/* mon{UINT_MAX}\0 */
756214518Srpaulo
757214518Srpaulo		snprintf(mondevice, sizeof mondevice, "mon%u", n);
758214518Srpaulo		ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
759214518Srpaulo		if (ret == 1) {
760214518Srpaulo			handle->md.mondevice = strdup(mondevice);
761214518Srpaulo			goto added;
762214518Srpaulo		}
763214518Srpaulo		if (ret < 0) {
764214518Srpaulo			/*
765214518Srpaulo			 * Hard failure.  Just return ret; handle->errbuf
766214518Srpaulo			 * has already been set.
767214518Srpaulo			 */
768214518Srpaulo			nl80211_cleanup(&nlstate);
769214518Srpaulo			return ret;
770214518Srpaulo		}
771214518Srpaulo	}
772214518Srpaulo
773214518Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
774214518Srpaulo	    "%s: No free monN interfaces", device);
775214518Srpaulo	nl80211_cleanup(&nlstate);
776214518Srpaulo	return PCAP_ERROR;
777214518Srpaulo
778214518Srpauloadded:
779214518Srpaulo
780214518Srpaulo#if 0
781214518Srpaulo	/*
782214518Srpaulo	 * Sleep for .1 seconds.
783214518Srpaulo	 */
784214518Srpaulo	delay.tv_sec = 0;
785214518Srpaulo	delay.tv_nsec = 500000000;
786214518Srpaulo	nanosleep(&delay, NULL);
787214518Srpaulo#endif
788214518Srpaulo
789214518Srpaulo	/*
790236167Sdelphij	 * If we haven't already done so, arrange to have
791236167Sdelphij	 * "pcap_close_all()" called when we exit.
792236167Sdelphij	 */
793236167Sdelphij	if (!pcap_do_addexit(handle)) {
794236167Sdelphij		/*
795236167Sdelphij		 * "atexit()" failed; don't put the interface
796236167Sdelphij		 * in rfmon mode, just give up.
797236167Sdelphij		 */
798236167Sdelphij		return PCAP_ERROR_RFMON_NOTSUP;
799236167Sdelphij	}
800236167Sdelphij
801236167Sdelphij	/*
802214518Srpaulo	 * Now configure the monitor interface up.
803214518Srpaulo	 */
804214518Srpaulo	memset(&ifr, 0, sizeof(ifr));
805214518Srpaulo	strncpy(ifr.ifr_name, handle->md.mondevice, sizeof(ifr.ifr_name));
806214518Srpaulo	if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
807214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
808214518Srpaulo		    "%s: Can't get flags for %s: %s", device,
809214518Srpaulo		    handle->md.mondevice, strerror(errno));
810214518Srpaulo		del_mon_if(handle, sock_fd, &nlstate, device,
811214518Srpaulo		    handle->md.mondevice);
812214518Srpaulo		nl80211_cleanup(&nlstate);
813214518Srpaulo		return PCAP_ERROR;
814214518Srpaulo	}
815214518Srpaulo	ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
816214518Srpaulo	if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
817214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
818214518Srpaulo		    "%s: Can't set flags for %s: %s", device,
819214518Srpaulo		    handle->md.mondevice, strerror(errno));
820214518Srpaulo		del_mon_if(handle, sock_fd, &nlstate, device,
821214518Srpaulo		    handle->md.mondevice);
822214518Srpaulo		nl80211_cleanup(&nlstate);
823214518Srpaulo		return PCAP_ERROR;
824214518Srpaulo	}
825214518Srpaulo
826214518Srpaulo	/*
827214518Srpaulo	 * Success.  Clean up the libnl state.
828214518Srpaulo	 */
829214518Srpaulo	nl80211_cleanup(&nlstate);
830214518Srpaulo
831214518Srpaulo	/*
832214518Srpaulo	 * Note that we have to delete the monitor device when we close
833214518Srpaulo	 * the handle.
834214518Srpaulo	 */
835214518Srpaulo	handle->md.must_do_on_close |= MUST_DELETE_MONIF;
836214518Srpaulo
837214518Srpaulo	/*
838214518Srpaulo	 * Add this to the list of pcaps to close when we exit.
839214518Srpaulo	 */
840214518Srpaulo	pcap_add_to_pcaps_to_close(handle);
841214518Srpaulo
842214518Srpaulo	return 1;
843214518Srpaulo}
844214518Srpaulo#endif /* HAVE_LIBNL */
845214518Srpaulo
846214518Srpaulostatic int
847214518Srpaulopcap_can_set_rfmon_linux(pcap_t *handle)
848214518Srpaulo{
849214518Srpaulo#ifdef HAVE_LIBNL
850214518Srpaulo	char phydev_path[PATH_MAX+1];
851214518Srpaulo	int ret;
852214518Srpaulo#endif
853190225Srpaulo#ifdef IW_MODE_MONITOR
854190225Srpaulo	int sock_fd;
855190225Srpaulo	struct iwreq ireq;
856190225Srpaulo#endif
857190225Srpaulo
858214518Srpaulo	if (strcmp(handle->opt.source, "any") == 0) {
859190225Srpaulo		/*
860214518Srpaulo		 * Monitor mode makes no sense on the "any" device.
861190225Srpaulo		 */
862190225Srpaulo		return 0;
86375107Sfenner	}
86475107Sfenner
865214518Srpaulo#ifdef HAVE_LIBNL
866214518Srpaulo	/*
867214518Srpaulo	 * Bleah.  There doesn't seem to be a way to ask a mac80211
868214518Srpaulo	 * device, through libnl, whether it supports monitor mode;
869214518Srpaulo	 * we'll just check whether the device appears to be a
870214518Srpaulo	 * mac80211 device and, if so, assume the device supports
871214518Srpaulo	 * monitor mode.
872214518Srpaulo	 *
873214518Srpaulo	 * wmaster devices don't appear to support the Wireless
874214518Srpaulo	 * Extensions, but we can create a mon device for a
875214518Srpaulo	 * wmaster device, so we don't bother checking whether
876214518Srpaulo	 * a mac80211 device supports the Wireless Extensions.
877214518Srpaulo	 */
878214518Srpaulo	ret = get_mac80211_phydev(handle, handle->opt.source, phydev_path,
879214518Srpaulo	    PATH_MAX);
880214518Srpaulo	if (ret < 0)
881214518Srpaulo		return ret;	/* error */
882214518Srpaulo	if (ret == 1)
883214518Srpaulo		return 1;	/* mac80211 device */
884214518Srpaulo#endif
885214518Srpaulo
886190225Srpaulo#ifdef IW_MODE_MONITOR
887190225Srpaulo	/*
888190225Srpaulo	 * Bleah.  There doesn't appear to be an ioctl to use to ask
889190225Srpaulo	 * whether a device supports monitor mode; we'll just do
890190225Srpaulo	 * SIOCGIWMODE and, if it succeeds, assume the device supports
891190225Srpaulo	 * monitor mode.
892190225Srpaulo	 *
893190225Srpaulo	 * Open a socket on which to attempt to get the mode.
894190225Srpaulo	 * (We assume that if we have Wireless Extensions support
895190225Srpaulo	 * we also have PF_PACKET support.)
896190225Srpaulo	 */
897190225Srpaulo	sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
898190225Srpaulo	if (sock_fd == -1) {
899214518Srpaulo		(void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
900190225Srpaulo		    "socket: %s", pcap_strerror(errno));
901190225Srpaulo		return PCAP_ERROR;
902190225Srpaulo	}
90375107Sfenner
904190225Srpaulo	/*
905190225Srpaulo	 * Attempt to get the current mode.
906190225Srpaulo	 */
907214518Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, handle->opt.source,
908190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
909190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
910190225Srpaulo	if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
911190225Srpaulo		/*
912190225Srpaulo		 * Well, we got the mode; assume we can set it.
913190225Srpaulo		 */
914190225Srpaulo		close(sock_fd);
915190225Srpaulo		return 1;
916190225Srpaulo	}
917190225Srpaulo	if (errno == ENODEV) {
918190225Srpaulo		/* The device doesn't even exist. */
919214518Srpaulo		(void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
920214518Srpaulo		    "SIOCGIWMODE failed: %s", pcap_strerror(errno));
921190225Srpaulo		close(sock_fd);
922190225Srpaulo		return PCAP_ERROR_NO_SUCH_DEVICE;
923190225Srpaulo	}
924190225Srpaulo	close(sock_fd);
925190225Srpaulo#endif
926190225Srpaulo	return 0;
927190225Srpaulo}
92875107Sfenner
929190225Srpaulo/*
930214518Srpaulo * Grabs the number of dropped packets by the interface from /proc/net/dev.
931214518Srpaulo *
932214518Srpaulo * XXX - what about /sys/class/net/{interface name}/rx_*?  There are
933214518Srpaulo * individual devices giving, in ASCII, various rx_ and tx_ statistics.
934214518Srpaulo *
935214518Srpaulo * Or can we get them in binary form from netlink?
936214518Srpaulo */
937214518Srpaulostatic long int
938214518Srpaulolinux_if_drops(const char * if_name)
939214518Srpaulo{
940214518Srpaulo	char buffer[512];
941214518Srpaulo	char * bufptr;
942214518Srpaulo	FILE * file;
943214518Srpaulo	int field_to_convert = 3, if_name_sz = strlen(if_name);
944214518Srpaulo	long int dropped_pkts = 0;
945214518Srpaulo
946214518Srpaulo	file = fopen("/proc/net/dev", "r");
947214518Srpaulo	if (!file)
948214518Srpaulo		return 0;
949214518Srpaulo
950214518Srpaulo	while (!dropped_pkts && fgets( buffer, sizeof(buffer), file ))
951214518Srpaulo	{
952214518Srpaulo		/* 	search for 'bytes' -- if its in there, then
953214518Srpaulo			that means we need to grab the fourth field. otherwise
954214518Srpaulo			grab the third field. */
955214518Srpaulo		if (field_to_convert != 4 && strstr(buffer, "bytes"))
956214518Srpaulo		{
957214518Srpaulo			field_to_convert = 4;
958214518Srpaulo			continue;
959214518Srpaulo		}
960214518Srpaulo
961214518Srpaulo		/* find iface and make sure it actually matches -- space before the name and : after it */
962214518Srpaulo		if ((bufptr = strstr(buffer, if_name)) &&
963214518Srpaulo			(bufptr == buffer || *(bufptr-1) == ' ') &&
964214518Srpaulo			*(bufptr + if_name_sz) == ':')
965214518Srpaulo		{
966214518Srpaulo			bufptr = bufptr + if_name_sz + 1;
967214518Srpaulo
968214518Srpaulo			/* grab the nth field from it */
969214518Srpaulo			while( --field_to_convert && *bufptr != '\0')
970214518Srpaulo			{
971214518Srpaulo				while (*bufptr != '\0' && *(bufptr++) == ' ');
972214518Srpaulo				while (*bufptr != '\0' && *(bufptr++) != ' ');
973214518Srpaulo			}
974214518Srpaulo
975214518Srpaulo			/* get rid of any final spaces */
976214518Srpaulo			while (*bufptr != '\0' && *bufptr == ' ') bufptr++;
977214518Srpaulo
978214518Srpaulo			if (*bufptr != '\0')
979214518Srpaulo				dropped_pkts = strtol(bufptr, NULL, 10);
980214518Srpaulo
981214518Srpaulo			break;
982214518Srpaulo		}
983214518Srpaulo	}
984214518Srpaulo
985214518Srpaulo	fclose(file);
986214518Srpaulo	return dropped_pkts;
987214518Srpaulo}
988214518Srpaulo
989214518Srpaulo
990214518Srpaulo/*
991190225Srpaulo * With older kernels promiscuous mode is kind of interesting because we
992190225Srpaulo * have to reset the interface before exiting. The problem can't really
993190225Srpaulo * be solved without some daemon taking care of managing usage counts.
994190225Srpaulo * If we put the interface into promiscuous mode, we set a flag indicating
995190225Srpaulo * that we must take it out of that mode when the interface is closed,
996190225Srpaulo * and, when closing the interface, if that flag is set we take it out
997190225Srpaulo * of promiscuous mode.
998190225Srpaulo *
999190225Srpaulo * Even with newer kernels, we have the same issue with rfmon mode.
1000190225Srpaulo */
1001190225Srpaulo
1002190225Srpaulostatic void	pcap_cleanup_linux( pcap_t *handle )
1003190225Srpaulo{
1004190225Srpaulo	struct ifreq	ifr;
1005214518Srpaulo#ifdef HAVE_LIBNL
1006214518Srpaulo	struct nl80211_state nlstate;
1007214518Srpaulo	int ret;
1008214518Srpaulo#endif /* HAVE_LIBNL */
1009190225Srpaulo#ifdef IW_MODE_MONITOR
1010236167Sdelphij	int oldflags;
1011190225Srpaulo	struct iwreq ireq;
1012214518Srpaulo#endif /* IW_MODE_MONITOR */
1013190225Srpaulo
1014214518Srpaulo	if (handle->md.must_do_on_close != 0) {
1015190225Srpaulo		/*
1016190225Srpaulo		 * There's something we have to do when closing this
1017190225Srpaulo		 * pcap_t.
1018190225Srpaulo		 */
1019214518Srpaulo		if (handle->md.must_do_on_close & MUST_CLEAR_PROMISC) {
1020190225Srpaulo			/*
1021190225Srpaulo			 * We put the interface into promiscuous mode;
1022190225Srpaulo			 * take it out of promiscuous mode.
1023190225Srpaulo			 *
1024190225Srpaulo			 * XXX - if somebody else wants it in promiscuous
1025190225Srpaulo			 * mode, this code cannot know that, so it'll take
1026190225Srpaulo			 * it out of promiscuous mode.  That's not fixable
1027190225Srpaulo			 * in 2.0[.x] kernels.
1028190225Srpaulo			 */
1029190225Srpaulo			memset(&ifr, 0, sizeof(ifr));
1030190225Srpaulo			strncpy(ifr.ifr_name, handle->md.device,
1031190225Srpaulo			    sizeof(ifr.ifr_name));
1032190225Srpaulo			if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1033190225Srpaulo				fprintf(stderr,
1034236167Sdelphij				    "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1035190225Srpaulo				    "Please adjust manually.\n"
1036190225Srpaulo				    "Hint: This can't happen with Linux >= 2.2.0.\n",
1037236167Sdelphij				    handle->md.device, strerror(errno));
1038190225Srpaulo			} else {
1039190225Srpaulo				if (ifr.ifr_flags & IFF_PROMISC) {
1040190225Srpaulo					/*
1041190225Srpaulo					 * Promiscuous mode is currently on;
1042190225Srpaulo					 * turn it off.
1043190225Srpaulo					 */
1044190225Srpaulo					ifr.ifr_flags &= ~IFF_PROMISC;
1045190225Srpaulo					if (ioctl(handle->fd, SIOCSIFFLAGS,
1046190225Srpaulo					    &ifr) == -1) {
1047190225Srpaulo						fprintf(stderr,
1048236167Sdelphij						    "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1049190225Srpaulo						    "Please adjust manually.\n"
1050190225Srpaulo						    "Hint: This can't happen with Linux >= 2.2.0.\n",
1051236167Sdelphij						    handle->md.device,
1052190225Srpaulo						    strerror(errno));
1053190225Srpaulo					}
1054190225Srpaulo				}
1055190225Srpaulo			}
1056190225Srpaulo		}
1057190225Srpaulo
1058214518Srpaulo#ifdef HAVE_LIBNL
1059214518Srpaulo		if (handle->md.must_do_on_close & MUST_DELETE_MONIF) {
1060214518Srpaulo			ret = nl80211_init(handle, &nlstate, handle->md.device);
1061214518Srpaulo			if (ret >= 0) {
1062214518Srpaulo				ret = del_mon_if(handle, handle->fd, &nlstate,
1063214518Srpaulo				    handle->md.device, handle->md.mondevice);
1064214518Srpaulo				nl80211_cleanup(&nlstate);
1065214518Srpaulo			}
1066214518Srpaulo			if (ret < 0) {
1067214518Srpaulo				fprintf(stderr,
1068214518Srpaulo				    "Can't delete monitor interface %s (%s).\n"
1069214518Srpaulo				    "Please delete manually.\n",
1070214518Srpaulo				    handle->md.mondevice, handle->errbuf);
1071214518Srpaulo			}
1072214518Srpaulo		}
1073214518Srpaulo#endif /* HAVE_LIBNL */
1074214518Srpaulo
1075190225Srpaulo#ifdef IW_MODE_MONITOR
1076214518Srpaulo		if (handle->md.must_do_on_close & MUST_CLEAR_RFMON) {
1077190225Srpaulo			/*
1078190225Srpaulo			 * We put the interface into rfmon mode;
1079190225Srpaulo			 * take it out of rfmon mode.
1080190225Srpaulo			 *
1081190225Srpaulo			 * XXX - if somebody else wants it in rfmon
1082190225Srpaulo			 * mode, this code cannot know that, so it'll take
1083190225Srpaulo			 * it out of rfmon mode.
1084190225Srpaulo			 */
1085236167Sdelphij
1086236167Sdelphij			/*
1087236167Sdelphij			 * First, take the interface down if it's up;
1088236167Sdelphij			 * otherwise, we might get EBUSY.
1089236167Sdelphij			 * If we get errors, just drive on and print
1090236167Sdelphij			 * a warning if we can't restore the mode.
1091236167Sdelphij			 */
1092236167Sdelphij			oldflags = 0;
1093236167Sdelphij			memset(&ifr, 0, sizeof(ifr));
1094236167Sdelphij			strncpy(ifr.ifr_name, handle->md.device,
1095236167Sdelphij			    sizeof(ifr.ifr_name));
1096236167Sdelphij			if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
1097236167Sdelphij				if (ifr.ifr_flags & IFF_UP) {
1098236167Sdelphij					oldflags = ifr.ifr_flags;
1099236167Sdelphij					ifr.ifr_flags &= ~IFF_UP;
1100236167Sdelphij					if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
1101236167Sdelphij						oldflags = 0;	/* didn't set, don't restore */
1102236167Sdelphij				}
1103236167Sdelphij			}
1104236167Sdelphij
1105236167Sdelphij			/*
1106236167Sdelphij			 * Now restore the mode.
1107236167Sdelphij			 */
1108190225Srpaulo			strncpy(ireq.ifr_ifrn.ifrn_name, handle->md.device,
1109190225Srpaulo			    sizeof ireq.ifr_ifrn.ifrn_name);
1110190225Srpaulo			ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1]
1111190225Srpaulo			    = 0;
1112190225Srpaulo			ireq.u.mode = handle->md.oldmode;
1113190225Srpaulo			if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
1114190225Srpaulo				/*
1115190225Srpaulo				 * Scientist, you've failed.
1116190225Srpaulo				 */
1117190225Srpaulo				fprintf(stderr,
1118236167Sdelphij				    "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1119190225Srpaulo				    "Please adjust manually.\n",
1120236167Sdelphij				    handle->md.device, strerror(errno));
1121190225Srpaulo			}
1122236167Sdelphij
1123236167Sdelphij			/*
1124236167Sdelphij			 * Now bring the interface back up if we brought
1125236167Sdelphij			 * it down.
1126236167Sdelphij			 */
1127236167Sdelphij			if (oldflags != 0) {
1128236167Sdelphij				ifr.ifr_flags = oldflags;
1129236167Sdelphij				if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1130236167Sdelphij					fprintf(stderr,
1131236167Sdelphij					    "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1132236167Sdelphij					    "Please adjust manually.\n",
1133236167Sdelphij					    handle->md.device, strerror(errno));
1134236167Sdelphij				}
1135236167Sdelphij			}
1136190225Srpaulo		}
1137214518Srpaulo#endif /* IW_MODE_MONITOR */
1138190225Srpaulo
1139190225Srpaulo		/*
1140190225Srpaulo		 * Take this pcap out of the list of pcaps for which we
1141190225Srpaulo		 * have to take the interface out of some mode.
1142190225Srpaulo		 */
1143190225Srpaulo		pcap_remove_from_pcaps_to_close(handle);
1144190225Srpaulo	}
1145190225Srpaulo
1146214518Srpaulo	if (handle->md.mondevice != NULL) {
1147214518Srpaulo		free(handle->md.mondevice);
1148214518Srpaulo		handle->md.mondevice = NULL;
1149214518Srpaulo	}
1150190225Srpaulo	if (handle->md.device != NULL) {
1151190225Srpaulo		free(handle->md.device);
1152190225Srpaulo		handle->md.device = NULL;
1153190225Srpaulo	}
1154190225Srpaulo	pcap_cleanup_live_common(handle);
1155190225Srpaulo}
1156190225Srpaulo
1157190225Srpaulo/*
1158190225Srpaulo *  Get a handle for a live capture from the given device. You can
1159190225Srpaulo *  pass NULL as device to get all packages (without link level
1160190225Srpaulo *  information of course). If you pass 1 as promisc the interface
1161190225Srpaulo *  will be set to promiscous mode (XXX: I think this usage should
1162190225Srpaulo *  be deprecated and functions be added to select that later allow
1163190225Srpaulo *  modification of that values -- Torsten).
1164190225Srpaulo */
1165190225Srpaulostatic int
1166190225Srpaulopcap_activate_linux(pcap_t *handle)
1167190225Srpaulo{
1168190225Srpaulo	const char	*device;
1169190225Srpaulo	int		status = 0;
1170190225Srpaulo
1171190225Srpaulo	device = handle->opt.source;
1172190225Srpaulo
1173190225Srpaulo	handle->inject_op = pcap_inject_linux;
1174190225Srpaulo	handle->setfilter_op = pcap_setfilter_linux;
1175190225Srpaulo	handle->setdirection_op = pcap_setdirection_linux;
1176190225Srpaulo	handle->set_datalink_op = NULL;	/* can't change data link type */
1177190225Srpaulo	handle->getnonblock_op = pcap_getnonblock_fd;
1178190225Srpaulo	handle->setnonblock_op = pcap_setnonblock_fd;
1179190225Srpaulo	handle->cleanup_op = pcap_cleanup_linux;
1180190225Srpaulo	handle->read_op = pcap_read_linux;
1181190225Srpaulo	handle->stats_op = pcap_stats_linux;
1182190225Srpaulo
118375107Sfenner	/*
1184214518Srpaulo	 * The "any" device is a special device which causes us not
1185214518Srpaulo	 * to bind to a particular device and thus to look at all
1186214518Srpaulo	 * devices.
118775107Sfenner	 */
1188214518Srpaulo	if (strcmp(device, "any") == 0) {
1189190225Srpaulo		if (handle->opt.promisc) {
1190190225Srpaulo			handle->opt.promisc = 0;
119198530Sfenner			/* Just a warning. */
1192190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
119398530Sfenner			    "Promiscuous mode not supported on the \"any\" device");
1194190225Srpaulo			status = PCAP_WARNING_PROMISC_NOTSUP;
119598530Sfenner		}
1196214518Srpaulo	}
1197127664Sbms
1198214518Srpaulo	handle->md.device	= strdup(device);
119975107Sfenner	if (handle->md.device == NULL) {
1200190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
120175107Sfenner			 pcap_strerror(errno) );
1202190225Srpaulo		return PCAP_ERROR;
120375107Sfenner	}
1204214518Srpaulo
1205214518Srpaulo	/*
1206214518Srpaulo	 * If we're in promiscuous mode, then we probably want
1207214518Srpaulo	 * to see when the interface drops packets too, so get an
1208214518Srpaulo	 * initial count from /proc/net/dev
1209214518Srpaulo	 */
1210214518Srpaulo	if (handle->opt.promisc)
1211214518Srpaulo		handle->md.proc_dropped = linux_if_drops(handle->md.device);
121275107Sfenner
1213127664Sbms	/*
1214127664Sbms	 * Current Linux kernels use the protocol family PF_PACKET to
1215127664Sbms	 * allow direct access to all packets on the network while
1216127664Sbms	 * older kernels had a special socket type SOCK_PACKET to
121775107Sfenner	 * implement this feature.
121875107Sfenner	 * While this old implementation is kind of obsolete we need
1219127664Sbms	 * to be compatible with older kernels for a while so we are
122075107Sfenner	 * trying both methods with the newer method preferred.
122175107Sfenner	 */
1222236167Sdelphij	status = activate_new(handle);
1223236167Sdelphij	if (status < 0) {
1224190225Srpaulo		/*
1225236167Sdelphij		 * Fatal error with the new way; just fail.
1226236167Sdelphij		 * status has the error return; if it's PCAP_ERROR,
1227236167Sdelphij		 * handle->errbuf has been set appropriately.
1228236167Sdelphij		 */
1229236167Sdelphij		goto fail;
1230236167Sdelphij	}
1231236167Sdelphij	if (status == 1) {
1232236167Sdelphij		/*
1233214518Srpaulo		 * Success.
1234190225Srpaulo		 * Try to use memory-mapped access.
1235190225Srpaulo		 */
1236236167Sdelphij		switch (activate_mmap(handle, &status)) {
1237214518Srpaulo
1238214518Srpaulo		case 1:
1239236167Sdelphij			/*
1240236167Sdelphij			 * We succeeded.  status has been
1241236167Sdelphij			 * set to the status to return,
1242236167Sdelphij			 * which might be 0, or might be
1243236167Sdelphij			 * a PCAP_WARNING_ value.
1244236167Sdelphij			 */
1245236167Sdelphij			return status;
1246214518Srpaulo
1247214518Srpaulo		case 0:
1248214518Srpaulo			/*
1249214518Srpaulo			 * Kernel doesn't support it - just continue
1250214518Srpaulo			 * with non-memory-mapped access.
1251214518Srpaulo			 */
1252214518Srpaulo			break;
1253214518Srpaulo
1254214518Srpaulo		case -1:
1255214518Srpaulo			/*
1256236167Sdelphij			 * We failed to set up to use it, or the kernel
1257236167Sdelphij			 * supports it, but we failed to enable it.
1258236167Sdelphij			 * status has been set to the error status to
1259236167Sdelphij			 * return and, if it's PCAP_ERROR, handle->errbuf
1260236167Sdelphij			 * contains the error message.
1261214518Srpaulo			 */
1262214518Srpaulo			goto fail;
1263214518Srpaulo		}
1264190225Srpaulo	}
1265190225Srpaulo	else if (status == 0) {
1266127664Sbms		/* Non-fatal error; try old way */
1267214518Srpaulo		if ((status = activate_old(handle)) != 1) {
1268214518Srpaulo			/*
1269214518Srpaulo			 * Both methods to open the packet socket failed.
1270214518Srpaulo			 * Tidy up and report our failure (handle->errbuf
1271214518Srpaulo			 * is expected to be set by the functions above).
1272214518Srpaulo			 */
1273214518Srpaulo			goto fail;
1274214518Srpaulo		}
127575107Sfenner	}
127675107Sfenner
1277214518Srpaulo	/*
1278214518Srpaulo	 * We set up the socket, but not with memory-mapped access.
1279214518Srpaulo	 */
1280236167Sdelphij	status = 0;
1281190225Srpaulo	if (handle->opt.buffer_size != 0) {
128298530Sfenner		/*
1283190225Srpaulo		 * Set the socket buffer size to the specified value.
128498530Sfenner		 */
1285190225Srpaulo		if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
1286190225Srpaulo		    &handle->opt.buffer_size,
1287190225Srpaulo		    sizeof(handle->opt.buffer_size)) == -1) {
1288190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1289190225Srpaulo				 "SO_RCVBUF: %s", pcap_strerror(errno));
1290190225Srpaulo			status = PCAP_ERROR;
1291190225Srpaulo			goto fail;
129298530Sfenner		}
129398530Sfenner	}
129498530Sfenner
129598530Sfenner	/* Allocate the buffer */
129698530Sfenner
129798530Sfenner	handle->buffer	 = malloc(handle->bufsize + handle->offset);
129898530Sfenner	if (!handle->buffer) {
1299190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
130098530Sfenner			 "malloc: %s", pcap_strerror(errno));
1301190225Srpaulo		status = PCAP_ERROR;
1302190225Srpaulo		goto fail;
130398530Sfenner	}
130498530Sfenner
1305127664Sbms	/*
1306127664Sbms	 * "handle->fd" is a socket, so "select()" and "poll()"
1307127664Sbms	 * should work on it.
1308127664Sbms	 */
1309127664Sbms	handle->selectable_fd = handle->fd;
1310127664Sbms
1311190225Srpaulo	return status;
1312127664Sbms
1313190225Srpaulofail:
1314190225Srpaulo	pcap_cleanup_linux(handle);
1315190225Srpaulo	return status;
131626175Sfenner}
131726175Sfenner
131875107Sfenner/*
131975107Sfenner *  Read at most max_packets from the capture stream and call the callback
132075107Sfenner *  for each of them. Returns the number of packets handled or -1 if an
1321127664Sbms *  error occured.
132275107Sfenner */
1323127664Sbmsstatic int
1324127664Sbmspcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
132526175Sfenner{
132675107Sfenner	/*
132775107Sfenner	 * Currently, on Linux only one packet is delivered per read,
132875107Sfenner	 * so we don't loop.
132975107Sfenner	 */
133075107Sfenner	return pcap_read_packet(handle, callback, user);
133175107Sfenner}
133226175Sfenner
133375107Sfenner/*
1334127664Sbms *  Read a packet from the socket calling the handler provided by
133575107Sfenner *  the user. Returns the number of packets received or -1 if an
133675107Sfenner *  error occured.
133775107Sfenner */
133875107Sfennerstatic int
133975107Sfennerpcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
134075107Sfenner{
134198530Sfenner	u_char			*bp;
134275107Sfenner	int			offset;
134375107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
134475107Sfenner	struct sockaddr_ll	from;
134575107Sfenner	struct sll_header	*hdrp;
134675107Sfenner#else
134775107Sfenner	struct sockaddr		from;
134875107Sfenner#endif
1349190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1350190225Srpaulo	struct iovec		iov;
1351190225Srpaulo	struct msghdr		msg;
1352190225Srpaulo	struct cmsghdr		*cmsg;
1353190225Srpaulo	union {
1354190225Srpaulo		struct cmsghdr	cmsg;
1355190225Srpaulo		char		buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
1356190225Srpaulo	} cmsg_buf;
1357190225Srpaulo#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
135875107Sfenner	socklen_t		fromlen;
1359190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
136075107Sfenner	int			packet_len, caplen;
136175107Sfenner	struct pcap_pkthdr	pcap_header;
136226175Sfenner
136375107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
136475107Sfenner	/*
136575107Sfenner	 * If this is a cooked device, leave extra room for a
136675107Sfenner	 * fake packet header.
136775107Sfenner	 */
136875107Sfenner	if (handle->md.cooked)
136975107Sfenner		offset = SLL_HDR_LEN;
137075107Sfenner	else
137175107Sfenner		offset = 0;
137275107Sfenner#else
137375107Sfenner	/*
137475107Sfenner	 * This system doesn't have PF_PACKET sockets, so it doesn't
137575107Sfenner	 * support cooked devices.
137675107Sfenner	 */
137775107Sfenner	offset = 0;
137875107Sfenner#endif
137975107Sfenner
1380190225Srpaulo	/*
1381190225Srpaulo	 * Receive a single packet from the kernel.
1382190225Srpaulo	 * We ignore EINTR, as that might just be due to a signal
1383190225Srpaulo	 * being delivered - if the signal should interrupt the
1384190225Srpaulo	 * loop, the signal handler should call pcap_breakloop()
1385190225Srpaulo	 * to set handle->break_loop (we ignore it on other
1386190225Srpaulo	 * platforms as well).
1387190225Srpaulo	 * We also ignore ENETDOWN, so that we can continue to
1388190225Srpaulo	 * capture traffic if the interface goes down and comes
1389190225Srpaulo	 * back up again; comments in the kernel indicate that
1390190225Srpaulo	 * we'll just block waiting for packets if we try to
1391190225Srpaulo	 * receive from a socket that delivered ENETDOWN, and,
1392190225Srpaulo	 * if we're using a memory-mapped buffer, we won't even
1393190225Srpaulo	 * get notified of "network down" events.
1394190225Srpaulo	 */
1395190225Srpaulo	bp = handle->buffer + handle->offset;
139675107Sfenner
1397190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1398190225Srpaulo	msg.msg_name		= &from;
1399190225Srpaulo	msg.msg_namelen		= sizeof(from);
1400190225Srpaulo	msg.msg_iov		= &iov;
1401190225Srpaulo	msg.msg_iovlen		= 1;
1402190225Srpaulo	msg.msg_control		= &cmsg_buf;
1403190225Srpaulo	msg.msg_controllen	= sizeof(cmsg_buf);
1404190225Srpaulo	msg.msg_flags		= 0;
1405190225Srpaulo
1406190225Srpaulo	iov.iov_len		= handle->bufsize - offset;
1407190225Srpaulo	iov.iov_base		= bp + offset;
1408190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1409190225Srpaulo
141026175Sfenner	do {
1411127664Sbms		/*
1412127664Sbms		 * Has "pcap_breakloop()" been called?
1413127664Sbms		 */
1414127664Sbms		if (handle->break_loop) {
1415127664Sbms			/*
1416214518Srpaulo			 * Yes - clear the flag that indicates that it has,
1417214518Srpaulo			 * and return PCAP_ERROR_BREAK as an indication that
1418214518Srpaulo			 * we were told to break out of the loop.
1419127664Sbms			 */
1420127664Sbms			handle->break_loop = 0;
1421214518Srpaulo			return PCAP_ERROR_BREAK;
1422127664Sbms		}
1423190225Srpaulo
1424190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1425190225Srpaulo		packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
1426190225Srpaulo#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
142726175Sfenner		fromlen = sizeof(from);
1428127664Sbms		packet_len = recvfrom(
142998530Sfenner			handle->fd, bp + offset,
1430127664Sbms			handle->bufsize - offset, MSG_TRUNC,
143175107Sfenner			(struct sockaddr *) &from, &fromlen);
1432190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1433214518Srpaulo	} while (packet_len == -1 && errno == EINTR);
143426175Sfenner
143575107Sfenner	/* Check if an error occured */
143626175Sfenner
143775107Sfenner	if (packet_len == -1) {
1438214518Srpaulo		switch (errno) {
1439214518Srpaulo
1440214518Srpaulo		case EAGAIN:
144175107Sfenner			return 0;	/* no packet there */
1442214518Srpaulo
1443214518Srpaulo		case ENETDOWN:
1444214518Srpaulo			/*
1445214518Srpaulo			 * The device on which we're capturing went away.
1446214518Srpaulo			 *
1447214518Srpaulo			 * XXX - we should really return
1448214518Srpaulo			 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1449214518Srpaulo			 * etc. aren't defined to return that.
1450214518Srpaulo			 */
1451190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1452214518Srpaulo				"The interface went down");
1453214518Srpaulo			return PCAP_ERROR;
1454214518Srpaulo
1455214518Srpaulo		default:
1456214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
145775107Sfenner				 "recvfrom: %s", pcap_strerror(errno));
1458214518Srpaulo			return PCAP_ERROR;
145926175Sfenner		}
146075107Sfenner	}
146126175Sfenner
146275107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
1463147894Ssam	if (!handle->md.sock_packet) {
1464147894Ssam		/*
1465172677Smlaier		 * Unfortunately, there is a window between socket() and
1466172677Smlaier		 * bind() where the kernel may queue packets from any
1467172677Smlaier		 * interface.  If we're bound to a particular interface,
1468172677Smlaier		 * discard packets not from that interface.
1469172677Smlaier		 *
1470172677Smlaier		 * (If socket filters are supported, we could do the
1471172677Smlaier		 * same thing we do when changing the filter; however,
1472172677Smlaier		 * that won't handle packet sockets without socket
1473172677Smlaier		 * filter support, and it's a bit more complicated.
1474172677Smlaier		 * It would save some instructions per packet, however.)
1475172677Smlaier		 */
1476172677Smlaier		if (handle->md.ifindex != -1 &&
1477172677Smlaier		    from.sll_ifindex != handle->md.ifindex)
1478172677Smlaier			return 0;
1479172677Smlaier
1480172677Smlaier		/*
1481147894Ssam		 * Do checks based on packet direction.
1482147894Ssam		 * We can only do this if we're using PF_PACKET; the
1483147894Ssam		 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1484147894Ssam		 * which lacks the relevant packet type information.
1485147894Ssam		 */
1486147894Ssam		if (from.sll_pkttype == PACKET_OUTGOING) {
1487147894Ssam			/*
1488147894Ssam			 * Outgoing packet.
1489147894Ssam			 * If this is from the loopback device, reject it;
1490147894Ssam			 * we'll see the packet as an incoming packet as well,
1491147894Ssam			 * and we don't want to see it twice.
1492147894Ssam			 */
1493147894Ssam			if (from.sll_ifindex == handle->md.lo_ifindex)
1494147894Ssam				return 0;
1495147894Ssam
1496147894Ssam			/*
1497147894Ssam			 * If the user only wants incoming packets, reject it.
1498147894Ssam			 */
1499162012Ssam			if (handle->direction == PCAP_D_IN)
1500147894Ssam				return 0;
1501147894Ssam		} else {
1502147894Ssam			/*
1503147894Ssam			 * Incoming packet.
1504147894Ssam			 * If the user only wants outgoing packets, reject it.
1505147894Ssam			 */
1506162012Ssam			if (handle->direction == PCAP_D_OUT)
1507147894Ssam				return 0;
1508147894Ssam		}
1509147894Ssam	}
151075107Sfenner#endif
151126175Sfenner
151275107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
151375107Sfenner	/*
151475107Sfenner	 * If this is a cooked device, fill in the fake packet header.
151575107Sfenner	 */
151675107Sfenner	if (handle->md.cooked) {
151775107Sfenner		/*
151875107Sfenner		 * Add the length of the fake header to the length
151975107Sfenner		 * of packet data we read.
152075107Sfenner		 */
152175107Sfenner		packet_len += SLL_HDR_LEN;
152226175Sfenner
152398530Sfenner		hdrp = (struct sll_header *)bp;
1524190225Srpaulo		hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
1525190225Srpaulo		hdrp->sll_hatype = htons(from.sll_hatype);
1526190225Srpaulo		hdrp->sll_halen = htons(from.sll_halen);
1527190225Srpaulo		memcpy(hdrp->sll_addr, from.sll_addr,
1528190225Srpaulo		    (from.sll_halen > SLL_ADDRLEN) ?
1529190225Srpaulo		      SLL_ADDRLEN :
1530190225Srpaulo		      from.sll_halen);
1531190225Srpaulo		hdrp->sll_protocol = from.sll_protocol;
1532190225Srpaulo	}
153326175Sfenner
1534190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1535252281Sdelphij	if (handle->md.vlan_offset != -1) {
1536252281Sdelphij		for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1537252281Sdelphij			struct tpacket_auxdata *aux;
1538252281Sdelphij			unsigned int len;
1539252281Sdelphij			struct vlan_tag *tag;
154026175Sfenner
1541252281Sdelphij			if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
1542252281Sdelphij			    cmsg->cmsg_level != SOL_PACKET ||
1543252281Sdelphij			    cmsg->cmsg_type != PACKET_AUXDATA)
1544252281Sdelphij				continue;
154526175Sfenner
1546252281Sdelphij			aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
1547252281Sdelphij#if defined(TP_STATUS_VLAN_VALID)
1548252281Sdelphij			if ((aux->tp_vlan_tci == 0) && !(aux->tp_status & TP_STATUS_VLAN_VALID))
1549252281Sdelphij#else
1550252281Sdelphij			if (aux->tp_vlan_tci == 0) /* this is ambigious but without the
1551252281Sdelphij						TP_STATUS_VLAN_VALID flag, there is
1552252281Sdelphij						nothing that we can do */
1553252281Sdelphij#endif
1554252281Sdelphij				continue;
155575107Sfenner
1556252281Sdelphij			len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
1557252281Sdelphij			if (len < (unsigned int) handle->md.vlan_offset)
1558252281Sdelphij				break;
155975107Sfenner
1560252281Sdelphij			bp -= VLAN_TAG_LEN;
1561252281Sdelphij			memmove(bp, bp + VLAN_TAG_LEN, handle->md.vlan_offset);
156275107Sfenner
1563252281Sdelphij			tag = (struct vlan_tag *)(bp + handle->md.vlan_offset);
1564252281Sdelphij			tag->vlan_tpid = htons(ETH_P_8021Q);
1565252281Sdelphij			tag->vlan_tci = htons(aux->tp_vlan_tci);
156675107Sfenner
1567252281Sdelphij			packet_len += VLAN_TAG_LEN;
1568252281Sdelphij		}
156926175Sfenner	}
1570190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1571190225Srpaulo#endif /* HAVE_PF_PACKET_SOCKETS */
157275107Sfenner
157375107Sfenner	/*
1574127664Sbms	 * XXX: According to the kernel source we should get the real
1575127664Sbms	 * packet len if calling recvfrom with MSG_TRUNC set. It does
157675107Sfenner	 * not seem to work here :(, but it is supported by this code
1577127664Sbms	 * anyway.
157875107Sfenner	 * To be honest the code RELIES on that feature so this is really
157975107Sfenner	 * broken with 2.2.x kernels.
158075107Sfenner	 * I spend a day to figure out what's going on and I found out
1581127664Sbms	 * that the following is happening:
158275107Sfenner	 *
1583127664Sbms	 * The packet comes from a random interface and the packet_rcv
158475107Sfenner	 * hook is called with a clone of the packet. That code inserts
158575107Sfenner	 * the packet into the receive queue of the packet socket.
158675107Sfenner	 * If a filter is attached to that socket that filter is run
158775107Sfenner	 * first - and there lies the problem. The default filter always
158875107Sfenner	 * cuts the packet at the snaplen:
158975107Sfenner	 *
159075107Sfenner	 * # tcpdump -d
159175107Sfenner	 * (000) ret      #68
159275107Sfenner	 *
1593127664Sbms	 * So the packet filter cuts down the packet. The recvfrom call
159475107Sfenner	 * says "hey, it's only 68 bytes, it fits into the buffer" with
1595127664Sbms	 * the result that we don't get the real packet length. This
1596127664Sbms	 * is valid at least until kernel 2.2.17pre6.
159775107Sfenner	 *
159875107Sfenner	 * We currently handle this by making a copy of the filter
159975107Sfenner	 * program, fixing all "ret" instructions with non-zero
160075107Sfenner	 * operands to have an operand of 65535 so that the filter
160175107Sfenner	 * doesn't truncate the packet, and supplying that modified
160275107Sfenner	 * filter to the kernel.
160375107Sfenner	 */
160475107Sfenner
160575107Sfenner	caplen = packet_len;
160675107Sfenner	if (caplen > handle->snapshot)
160775107Sfenner		caplen = handle->snapshot;
160875107Sfenner
160975107Sfenner	/* Run the packet filter if not using kernel filter */
161075107Sfenner	if (!handle->md.use_bpf && handle->fcode.bf_insns) {
161198530Sfenner		if (bpf_filter(handle->fcode.bf_insns, bp,
161275107Sfenner		                packet_len, caplen) == 0)
161375107Sfenner		{
161475107Sfenner			/* rejected by filter */
161575107Sfenner			return 0;
161675107Sfenner		}
161775107Sfenner	}
161875107Sfenner
161975107Sfenner	/* Fill in our own header data */
162075107Sfenner
162175107Sfenner	if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
1622190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1623172677Smlaier			 "SIOCGSTAMP: %s", pcap_strerror(errno));
1624214518Srpaulo		return PCAP_ERROR;
162575107Sfenner	}
162675107Sfenner	pcap_header.caplen	= caplen;
162775107Sfenner	pcap_header.len		= packet_len;
162875107Sfenner
162998530Sfenner	/*
163098530Sfenner	 * Count the packet.
163198530Sfenner	 *
163298530Sfenner	 * Arguably, we should count them before we check the filter,
163398530Sfenner	 * as on many other platforms "ps_recv" counts packets
163498530Sfenner	 * handed to the filter rather than packets that passed
163598530Sfenner	 * the filter, but if filtering is done in the kernel, we
163698530Sfenner	 * can't get a count of packets that passed the filter,
163798530Sfenner	 * and that would mean the meaning of "ps_recv" wouldn't
163898530Sfenner	 * be the same on all Linux systems.
163998530Sfenner	 *
164098530Sfenner	 * XXX - it's not the same on all systems in any case;
164198530Sfenner	 * ideally, we should have a "get the statistics" call
164298530Sfenner	 * that supplies more counts and indicates which of them
164398530Sfenner	 * it supplies, so that we supply a count of packets
164498530Sfenner	 * handed to the filter only on platforms where that
164598530Sfenner	 * information is available.
164698530Sfenner	 *
164798530Sfenner	 * We count them here even if we can get the packet count
164898530Sfenner	 * from the kernel, as we can only determine at run time
164998530Sfenner	 * whether we'll be able to get it from the kernel (if
165098530Sfenner	 * HAVE_TPACKET_STATS isn't defined, we can't get it from
165198530Sfenner	 * the kernel, but if it is defined, the library might
165298530Sfenner	 * have been built with a 2.4 or later kernel, but we
165398530Sfenner	 * might be running on a 2.2[.x] kernel without Alexey
165498530Sfenner	 * Kuznetzov's turbopacket patches, and thus the kernel
165598530Sfenner	 * might not be able to supply those statistics).  We
165698530Sfenner	 * could, I guess, try, when opening the socket, to get
165798530Sfenner	 * the statistics, and if we can not increment the count
165898530Sfenner	 * here, but it's not clear that always incrementing
165998530Sfenner	 * the count is more expensive than always testing a flag
166098530Sfenner	 * in memory.
1661172677Smlaier	 *
1662172677Smlaier	 * We keep the count in "md.packets_read", and use that for
1663172677Smlaier	 * "ps_recv" if we can't get the statistics from the kernel.
1664172677Smlaier	 * We do that because, if we *can* get the statistics from
1665172677Smlaier	 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1666172677Smlaier	 * as running counts, as reading the statistics from the
1667172677Smlaier	 * kernel resets the kernel statistics, and if we directly
1668172677Smlaier	 * increment "md.stat.ps_recv" here, that means it will
1669172677Smlaier	 * count packets *twice* on systems where we can get kernel
1670172677Smlaier	 * statistics - once here, and once in pcap_stats_linux().
167198530Sfenner	 */
1672172677Smlaier	handle->md.packets_read++;
167375107Sfenner
167498530Sfenner	/* Call the user supplied callback function */
167598530Sfenner	callback(userdata, &pcap_header, bp);
167698530Sfenner
167775107Sfenner	return 1;
167826175Sfenner}
167926175Sfenner
1680146768Ssamstatic int
1681146768Ssampcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
1682146768Ssam{
1683146768Ssam	int ret;
1684146768Ssam
1685146768Ssam#ifdef HAVE_PF_PACKET_SOCKETS
1686146768Ssam	if (!handle->md.sock_packet) {
1687146768Ssam		/* PF_PACKET socket */
1688146768Ssam		if (handle->md.ifindex == -1) {
1689146768Ssam			/*
1690146768Ssam			 * We don't support sending on the "any" device.
1691146768Ssam			 */
1692146768Ssam			strlcpy(handle->errbuf,
1693146768Ssam			    "Sending packets isn't supported on the \"any\" device",
1694146768Ssam			    PCAP_ERRBUF_SIZE);
1695146768Ssam			return (-1);
1696146768Ssam		}
1697146768Ssam
1698146768Ssam		if (handle->md.cooked) {
1699146768Ssam			/*
1700146768Ssam			 * We don't support sending on the "any" device.
1701146768Ssam			 *
1702146768Ssam			 * XXX - how do you send on a bound cooked-mode
1703146768Ssam			 * socket?
1704146768Ssam			 * Is a "sendto()" required there?
1705146768Ssam			 */
1706146768Ssam			strlcpy(handle->errbuf,
1707146768Ssam			    "Sending packets isn't supported in cooked mode",
1708146768Ssam			    PCAP_ERRBUF_SIZE);
1709146768Ssam			return (-1);
1710146768Ssam		}
1711146768Ssam	}
1712146768Ssam#endif
1713146768Ssam
1714146768Ssam	ret = send(handle->fd, buf, size, 0);
1715146768Ssam	if (ret == -1) {
1716146768Ssam		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1717146768Ssam		    pcap_strerror(errno));
1718146768Ssam		return (-1);
1719146768Ssam	}
1720146768Ssam	return (ret);
1721146768Ssam}
1722146768Ssam
172375107Sfenner/*
172475107Sfenner *  Get the statistics for the given packet capture handle.
172598530Sfenner *  Reports the number of dropped packets iff the kernel supports
172698530Sfenner *  the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
172798530Sfenner *  kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
172898530Sfenner *  patches); otherwise, that information isn't available, and we lie
172998530Sfenner *  and report 0 as the count of dropped packets.
173075107Sfenner */
1731127664Sbmsstatic int
1732127664Sbmspcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
173326175Sfenner{
173498530Sfenner#ifdef HAVE_TPACKET_STATS
173598530Sfenner	struct tpacket_stats kstats;
173698530Sfenner	socklen_t len = sizeof (struct tpacket_stats);
1737127664Sbms#endif
173898530Sfenner
1739214518Srpaulo	long if_dropped = 0;
1740214518Srpaulo
1741214518Srpaulo	/*
1742214518Srpaulo	 *	To fill in ps_ifdrop, we parse /proc/net/dev for the number
1743214518Srpaulo	 */
1744214518Srpaulo	if (handle->opt.promisc)
1745214518Srpaulo	{
1746214518Srpaulo		if_dropped = handle->md.proc_dropped;
1747214518Srpaulo		handle->md.proc_dropped = linux_if_drops(handle->md.device);
1748214518Srpaulo		handle->md.stat.ps_ifdrop += (handle->md.proc_dropped - if_dropped);
1749214518Srpaulo	}
1750214518Srpaulo
1751127664Sbms#ifdef HAVE_TPACKET_STATS
175298530Sfenner	/*
175398530Sfenner	 * Try to get the packet counts from the kernel.
175498530Sfenner	 */
175598530Sfenner	if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
175698530Sfenner			&kstats, &len) > -1) {
175798530Sfenner		/*
1758172677Smlaier		 * On systems where the PACKET_STATISTICS "getsockopt()"
1759172677Smlaier		 * argument is supported on PF_PACKET sockets:
1760172677Smlaier		 *
1761172677Smlaier		 *	"ps_recv" counts only packets that *passed* the
1762172677Smlaier		 *	filter, not packets that didn't pass the filter.
1763172677Smlaier		 *	This includes packets later dropped because we
1764172677Smlaier		 *	ran out of buffer space.
1765172677Smlaier		 *
1766172677Smlaier		 *	"ps_drop" counts packets dropped because we ran
1767172677Smlaier		 *	out of buffer space.  It doesn't count packets
1768172677Smlaier		 *	dropped by the interface driver.  It counts only
1769172677Smlaier		 *	packets that passed the filter.
1770172677Smlaier		 *
1771214518Srpaulo		 *	See above for ps_ifdrop.
1772214518Srpaulo		 *
1773172677Smlaier		 *	Both statistics include packets not yet read from
1774172677Smlaier		 *	the kernel by libpcap, and thus not yet seen by
1775172677Smlaier		 *	the application.
1776172677Smlaier		 *
177798530Sfenner		 * In "linux/net/packet/af_packet.c", at least in the
177898530Sfenner		 * 2.4.9 kernel, "tp_packets" is incremented for every
177998530Sfenner		 * packet that passes the packet filter *and* is
178098530Sfenner		 * successfully queued on the socket; "tp_drops" is
178198530Sfenner		 * incremented for every packet dropped because there's
178298530Sfenner		 * not enough free space in the socket buffer.
178398530Sfenner		 *
178498530Sfenner		 * When the statistics are returned for a PACKET_STATISTICS
178598530Sfenner		 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
178698530Sfenner		 * so that "tp_packets" counts all packets handed to
178798530Sfenner		 * the PF_PACKET socket, including packets dropped because
178898530Sfenner		 * there wasn't room on the socket buffer - but not
178998530Sfenner		 * including packets that didn't pass the filter.
179098530Sfenner		 *
179198530Sfenner		 * In the BSD BPF, the count of received packets is
179298530Sfenner		 * incremented for every packet handed to BPF, regardless
179398530Sfenner		 * of whether it passed the filter.
179498530Sfenner		 *
179598530Sfenner		 * We can't make "pcap_stats()" work the same on both
179698530Sfenner		 * platforms, but the best approximation is to return
179798530Sfenner		 * "tp_packets" as the count of packets and "tp_drops"
179898530Sfenner		 * as the count of drops.
1799146768Ssam		 *
1800146768Ssam		 * Keep a running total because each call to
1801146768Ssam		 *    getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1802146768Ssam		 * resets the counters to zero.
180398530Sfenner		 */
1804146768Ssam		handle->md.stat.ps_recv += kstats.tp_packets;
1805146768Ssam		handle->md.stat.ps_drop += kstats.tp_drops;
1806172677Smlaier		*stats = handle->md.stat;
1807172677Smlaier		return 0;
180898530Sfenner	}
180998530Sfenner	else
181098530Sfenner	{
181198530Sfenner		/*
181298530Sfenner		 * If the error was EOPNOTSUPP, fall through, so that
181398530Sfenner		 * if you build the library on a system with
181498530Sfenner		 * "struct tpacket_stats" and run it on a system
181598530Sfenner		 * that doesn't, it works as it does if the library
181698530Sfenner		 * is built on a system without "struct tpacket_stats".
181798530Sfenner		 */
181898530Sfenner		if (errno != EOPNOTSUPP) {
181998530Sfenner			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
182098530Sfenner			    "pcap_stats: %s", pcap_strerror(errno));
182198530Sfenner			return -1;
182298530Sfenner		}
182398530Sfenner	}
182498530Sfenner#endif
182598530Sfenner	/*
182698530Sfenner	 * On systems where the PACKET_STATISTICS "getsockopt()" argument
182798530Sfenner	 * is not supported on PF_PACKET sockets:
182898530Sfenner	 *
182998530Sfenner	 *	"ps_recv" counts only packets that *passed* the filter,
183098530Sfenner	 *	not packets that didn't pass the filter.  It does not
183198530Sfenner	 *	count packets dropped because we ran out of buffer
183298530Sfenner	 *	space.
183398530Sfenner	 *
183498530Sfenner	 *	"ps_drop" is not supported.
183598530Sfenner	 *
1836214518Srpaulo	 *	"ps_ifdrop" is supported. It will return the number
1837214518Srpaulo	 *	of drops the interface reports in /proc/net/dev,
1838214518Srpaulo	 *	if that is available.
1839214518Srpaulo	 *
184098530Sfenner	 *	"ps_recv" doesn't include packets not yet read from
184198530Sfenner	 *	the kernel by libpcap.
1842172677Smlaier	 *
1843172677Smlaier	 * We maintain the count of packets processed by libpcap in
1844172677Smlaier	 * "md.packets_read", for reasons described in the comment
1845172677Smlaier	 * at the end of pcap_read_packet().  We have no idea how many
1846214518Srpaulo	 * packets were dropped by the kernel buffers -- but we know
1847214518Srpaulo	 * how many the interface dropped, so we can return that.
184898530Sfenner	 */
1849214518Srpaulo
1850172677Smlaier	stats->ps_recv = handle->md.packets_read;
1851172677Smlaier	stats->ps_drop = 0;
1852214518Srpaulo	stats->ps_ifdrop = handle->md.stat.ps_ifdrop;
185375107Sfenner	return 0;
185475107Sfenner}
185526175Sfenner
185675107Sfenner/*
1857214518Srpaulo * Get from "/sys/class/net" all interfaces listed there; if they're
1858214518Srpaulo * already in the list of interfaces we have, that won't add another
1859214518Srpaulo * instance, but if they're not, that'll add them.
1860214518Srpaulo *
1861214518Srpaulo * We don't bother getting any addresses for them; it appears you can't
1862214518Srpaulo * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1863214518Srpaulo * although some other types of addresses can be fetched with SIOCGIFADDR,
1864214518Srpaulo * we don't bother with them for now.
1865214518Srpaulo *
1866214518Srpaulo * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1867214518Srpaulo * the list of interfaces as is, and return 0, so that we can try
1868214518Srpaulo * scanning /proc/net/dev.
1869214518Srpaulo */
1870214518Srpaulostatic int
1871214518Srpauloscan_sys_class_net(pcap_if_t **devlistp, char *errbuf)
1872214518Srpaulo{
1873214518Srpaulo	DIR *sys_class_net_d;
1874214518Srpaulo	int fd;
1875214518Srpaulo	struct dirent *ent;
1876252281Sdelphij	char subsystem_path[PATH_MAX+1];
1877252281Sdelphij	struct stat statb;
1878214518Srpaulo	char *p;
1879214518Srpaulo	char name[512];	/* XXX - pick a size */
1880214518Srpaulo	char *q, *saveq;
1881214518Srpaulo	struct ifreq ifrflags;
1882214518Srpaulo	int ret = 1;
1883214518Srpaulo
1884214518Srpaulo	sys_class_net_d = opendir("/sys/class/net");
1885236167Sdelphij	if (sys_class_net_d == NULL) {
1886236167Sdelphij		/*
1887236167Sdelphij		 * Don't fail if it doesn't exist at all.
1888236167Sdelphij		 */
1889236167Sdelphij		if (errno == ENOENT)
1890236167Sdelphij			return (0);
1891214518Srpaulo
1892236167Sdelphij		/*
1893236167Sdelphij		 * Fail if we got some other error.
1894236167Sdelphij		 */
1895236167Sdelphij		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1896236167Sdelphij		    "Can't open /sys/class/net: %s", pcap_strerror(errno));
1897236167Sdelphij		return (-1);
1898236167Sdelphij	}
1899236167Sdelphij
1900214518Srpaulo	/*
1901214518Srpaulo	 * Create a socket from which to fetch interface information.
1902214518Srpaulo	 */
1903214518Srpaulo	fd = socket(AF_INET, SOCK_DGRAM, 0);
1904214518Srpaulo	if (fd < 0) {
1905214518Srpaulo		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1906214518Srpaulo		    "socket: %s", pcap_strerror(errno));
1907236167Sdelphij		(void)closedir(sys_class_net_d);
1908214518Srpaulo		return (-1);
1909214518Srpaulo	}
1910214518Srpaulo
1911214518Srpaulo	for (;;) {
1912214518Srpaulo		errno = 0;
1913214518Srpaulo		ent = readdir(sys_class_net_d);
1914214518Srpaulo		if (ent == NULL) {
1915214518Srpaulo			/*
1916214518Srpaulo			 * Error or EOF; if errno != 0, it's an error.
1917214518Srpaulo			 */
1918214518Srpaulo			break;
1919214518Srpaulo		}
1920214518Srpaulo
1921214518Srpaulo		/*
1922252281Sdelphij		 * Ignore "." and "..".
1923214518Srpaulo		 */
1924252281Sdelphij		if (strcmp(ent->d_name, ".") == 0 ||
1925252281Sdelphij		    strcmp(ent->d_name, "..") == 0)
1926214518Srpaulo			continue;
1927214518Srpaulo
1928214518Srpaulo		/*
1929252281Sdelphij		 * Ignore plain files; they do not have subdirectories
1930252281Sdelphij		 * and thus have no attributes.
1931252281Sdelphij		 */
1932252281Sdelphij		if (ent->d_type == DT_REG)
1933252281Sdelphij			continue;
1934252281Sdelphij
1935252281Sdelphij		/*
1936252281Sdelphij		 * Is there an "ifindex" file under that name?
1937252281Sdelphij		 * (We don't care whether it's a directory or
1938252281Sdelphij		 * a symlink; older kernels have directories
1939252281Sdelphij		 * for devices, newer kernels have symlinks to
1940252281Sdelphij		 * directories.)
1941252281Sdelphij		 */
1942252281Sdelphij		snprintf(subsystem_path, sizeof subsystem_path,
1943252281Sdelphij		    "/sys/class/net/%s/ifindex", ent->d_name);
1944252281Sdelphij		if (lstat(subsystem_path, &statb) != 0) {
1945252281Sdelphij			/*
1946252281Sdelphij			 * Stat failed.  Either there was an error
1947252281Sdelphij			 * other than ENOENT, and we don't know if
1948252281Sdelphij			 * this is an interface, or it's ENOENT,
1949252281Sdelphij			 * and either some part of "/sys/class/net/{if}"
1950252281Sdelphij			 * disappeared, in which case it probably means
1951252281Sdelphij			 * the interface disappeared, or there's no
1952252281Sdelphij			 * "ifindex" file, which means it's not a
1953252281Sdelphij			 * network interface.
1954252281Sdelphij			 */
1955252281Sdelphij			continue;
1956252281Sdelphij		}
1957252281Sdelphij
1958252281Sdelphij		/*
1959214518Srpaulo		 * Get the interface name.
1960214518Srpaulo		 */
1961214518Srpaulo		p = &ent->d_name[0];
1962214518Srpaulo		q = &name[0];
1963214518Srpaulo		while (*p != '\0' && isascii(*p) && !isspace(*p)) {
1964214518Srpaulo			if (*p == ':') {
1965214518Srpaulo				/*
1966214518Srpaulo				 * This could be the separator between a
1967214518Srpaulo				 * name and an alias number, or it could be
1968214518Srpaulo				 * the separator between a name with no
1969214518Srpaulo				 * alias number and the next field.
1970214518Srpaulo				 *
1971214518Srpaulo				 * If there's a colon after digits, it
1972214518Srpaulo				 * separates the name and the alias number,
1973214518Srpaulo				 * otherwise it separates the name and the
1974214518Srpaulo				 * next field.
1975214518Srpaulo				 */
1976214518Srpaulo				saveq = q;
1977214518Srpaulo				while (isascii(*p) && isdigit(*p))
1978214518Srpaulo					*q++ = *p++;
1979214518Srpaulo				if (*p != ':') {
1980214518Srpaulo					/*
1981214518Srpaulo					 * That was the next field,
1982214518Srpaulo					 * not the alias number.
1983214518Srpaulo					 */
1984214518Srpaulo					q = saveq;
1985214518Srpaulo				}
1986214518Srpaulo				break;
1987214518Srpaulo			} else
1988214518Srpaulo				*q++ = *p++;
1989214518Srpaulo		}
1990214518Srpaulo		*q = '\0';
1991214518Srpaulo
1992214518Srpaulo		/*
1993214518Srpaulo		 * Get the flags for this interface, and skip it if
1994214518Srpaulo		 * it's not up.
1995214518Srpaulo		 */
1996214518Srpaulo		strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
1997214518Srpaulo		if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
1998236167Sdelphij			if (errno == ENXIO || errno == ENODEV)
1999214518Srpaulo				continue;
2000214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2001214518Srpaulo			    "SIOCGIFFLAGS: %.*s: %s",
2002214518Srpaulo			    (int)sizeof(ifrflags.ifr_name),
2003214518Srpaulo			    ifrflags.ifr_name,
2004214518Srpaulo			    pcap_strerror(errno));
2005214518Srpaulo			ret = -1;
2006214518Srpaulo			break;
2007214518Srpaulo		}
2008214518Srpaulo		if (!(ifrflags.ifr_flags & IFF_UP))
2009214518Srpaulo			continue;
2010214518Srpaulo
2011214518Srpaulo		/*
2012214518Srpaulo		 * Add an entry for this interface, with no addresses.
2013214518Srpaulo		 */
2014214518Srpaulo		if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2015214518Srpaulo		    errbuf) == -1) {
2016214518Srpaulo			/*
2017214518Srpaulo			 * Failure.
2018214518Srpaulo			 */
2019214518Srpaulo			ret = -1;
2020214518Srpaulo			break;
2021214518Srpaulo		}
2022214518Srpaulo	}
2023214518Srpaulo	if (ret != -1) {
2024214518Srpaulo		/*
2025214518Srpaulo		 * Well, we didn't fail for any other reason; did we
2026214518Srpaulo		 * fail due to an error reading the directory?
2027214518Srpaulo		 */
2028214518Srpaulo		if (errno != 0) {
2029214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2030214518Srpaulo			    "Error reading /sys/class/net: %s",
2031214518Srpaulo			    pcap_strerror(errno));
2032214518Srpaulo			ret = -1;
2033214518Srpaulo		}
2034214518Srpaulo	}
2035214518Srpaulo
2036214518Srpaulo	(void)close(fd);
2037214518Srpaulo	(void)closedir(sys_class_net_d);
2038214518Srpaulo	return (ret);
2039214518Srpaulo}
2040214518Srpaulo
2041214518Srpaulo/*
2042214518Srpaulo * Get from "/proc/net/dev" all interfaces listed there; if they're
2043214518Srpaulo * already in the list of interfaces we have, that won't add another
2044214518Srpaulo * instance, but if they're not, that'll add them.
2045214518Srpaulo *
2046214518Srpaulo * See comments from scan_sys_class_net().
2047214518Srpaulo */
2048214518Srpaulostatic int
2049214518Srpauloscan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
2050214518Srpaulo{
2051214518Srpaulo	FILE *proc_net_f;
2052214518Srpaulo	int fd;
2053214518Srpaulo	char linebuf[512];
2054214518Srpaulo	int linenum;
2055214518Srpaulo	char *p;
2056214518Srpaulo	char name[512];	/* XXX - pick a size */
2057214518Srpaulo	char *q, *saveq;
2058214518Srpaulo	struct ifreq ifrflags;
2059214518Srpaulo	int ret = 0;
2060214518Srpaulo
2061214518Srpaulo	proc_net_f = fopen("/proc/net/dev", "r");
2062236167Sdelphij	if (proc_net_f == NULL) {
2063236167Sdelphij		/*
2064236167Sdelphij		 * Don't fail if it doesn't exist at all.
2065236167Sdelphij		 */
2066236167Sdelphij		if (errno == ENOENT)
2067236167Sdelphij			return (0);
2068214518Srpaulo
2069236167Sdelphij		/*
2070236167Sdelphij		 * Fail if we got some other error.
2071236167Sdelphij		 */
2072236167Sdelphij		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2073236167Sdelphij		    "Can't open /proc/net/dev: %s", pcap_strerror(errno));
2074236167Sdelphij		return (-1);
2075236167Sdelphij	}
2076236167Sdelphij
2077214518Srpaulo	/*
2078214518Srpaulo	 * Create a socket from which to fetch interface information.
2079214518Srpaulo	 */
2080214518Srpaulo	fd = socket(AF_INET, SOCK_DGRAM, 0);
2081214518Srpaulo	if (fd < 0) {
2082214518Srpaulo		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2083214518Srpaulo		    "socket: %s", pcap_strerror(errno));
2084236167Sdelphij		(void)fclose(proc_net_f);
2085214518Srpaulo		return (-1);
2086214518Srpaulo	}
2087214518Srpaulo
2088214518Srpaulo	for (linenum = 1;
2089214518Srpaulo	    fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
2090214518Srpaulo		/*
2091214518Srpaulo		 * Skip the first two lines - they're headers.
2092214518Srpaulo		 */
2093214518Srpaulo		if (linenum <= 2)
2094214518Srpaulo			continue;
2095214518Srpaulo
2096214518Srpaulo		p = &linebuf[0];
2097214518Srpaulo
2098214518Srpaulo		/*
2099214518Srpaulo		 * Skip leading white space.
2100214518Srpaulo		 */
2101214518Srpaulo		while (*p != '\0' && isascii(*p) && isspace(*p))
2102214518Srpaulo			p++;
2103214518Srpaulo		if (*p == '\0' || *p == '\n')
2104214518Srpaulo			continue;	/* blank line */
2105214518Srpaulo
2106214518Srpaulo		/*
2107214518Srpaulo		 * Get the interface name.
2108214518Srpaulo		 */
2109214518Srpaulo		q = &name[0];
2110214518Srpaulo		while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2111214518Srpaulo			if (*p == ':') {
2112214518Srpaulo				/*
2113214518Srpaulo				 * This could be the separator between a
2114214518Srpaulo				 * name and an alias number, or it could be
2115214518Srpaulo				 * the separator between a name with no
2116214518Srpaulo				 * alias number and the next field.
2117214518Srpaulo				 *
2118214518Srpaulo				 * If there's a colon after digits, it
2119214518Srpaulo				 * separates the name and the alias number,
2120214518Srpaulo				 * otherwise it separates the name and the
2121214518Srpaulo				 * next field.
2122214518Srpaulo				 */
2123214518Srpaulo				saveq = q;
2124214518Srpaulo				while (isascii(*p) && isdigit(*p))
2125214518Srpaulo					*q++ = *p++;
2126214518Srpaulo				if (*p != ':') {
2127214518Srpaulo					/*
2128214518Srpaulo					 * That was the next field,
2129214518Srpaulo					 * not the alias number.
2130214518Srpaulo					 */
2131214518Srpaulo					q = saveq;
2132214518Srpaulo				}
2133214518Srpaulo				break;
2134214518Srpaulo			} else
2135214518Srpaulo				*q++ = *p++;
2136214518Srpaulo		}
2137214518Srpaulo		*q = '\0';
2138214518Srpaulo
2139214518Srpaulo		/*
2140214518Srpaulo		 * Get the flags for this interface, and skip it if
2141214518Srpaulo		 * it's not up.
2142214518Srpaulo		 */
2143214518Srpaulo		strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2144214518Srpaulo		if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2145214518Srpaulo			if (errno == ENXIO)
2146214518Srpaulo				continue;
2147214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2148214518Srpaulo			    "SIOCGIFFLAGS: %.*s: %s",
2149214518Srpaulo			    (int)sizeof(ifrflags.ifr_name),
2150214518Srpaulo			    ifrflags.ifr_name,
2151214518Srpaulo			    pcap_strerror(errno));
2152214518Srpaulo			ret = -1;
2153214518Srpaulo			break;
2154214518Srpaulo		}
2155214518Srpaulo		if (!(ifrflags.ifr_flags & IFF_UP))
2156214518Srpaulo			continue;
2157214518Srpaulo
2158214518Srpaulo		/*
2159214518Srpaulo		 * Add an entry for this interface, with no addresses.
2160214518Srpaulo		 */
2161214518Srpaulo		if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2162214518Srpaulo		    errbuf) == -1) {
2163214518Srpaulo			/*
2164214518Srpaulo			 * Failure.
2165214518Srpaulo			 */
2166214518Srpaulo			ret = -1;
2167214518Srpaulo			break;
2168214518Srpaulo		}
2169214518Srpaulo	}
2170214518Srpaulo	if (ret != -1) {
2171214518Srpaulo		/*
2172214518Srpaulo		 * Well, we didn't fail for any other reason; did we
2173214518Srpaulo		 * fail due to an error reading the file?
2174214518Srpaulo		 */
2175214518Srpaulo		if (ferror(proc_net_f)) {
2176214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2177214518Srpaulo			    "Error reading /proc/net/dev: %s",
2178214518Srpaulo			    pcap_strerror(errno));
2179214518Srpaulo			ret = -1;
2180214518Srpaulo		}
2181214518Srpaulo	}
2182214518Srpaulo
2183214518Srpaulo	(void)close(fd);
2184214518Srpaulo	(void)fclose(proc_net_f);
2185214518Srpaulo	return (ret);
2186214518Srpaulo}
2187214518Srpaulo
2188214518Srpaulo/*
2189127664Sbms * Description string for the "any" device.
219075107Sfenner */
2191127664Sbmsstatic const char any_descr[] = "Pseudo-device that captures on all interfaces";
2192127664Sbms
219375107Sfennerint
2194127664Sbmspcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
219575107Sfenner{
2196214518Srpaulo	int ret;
2197214518Srpaulo
2198214518Srpaulo	/*
2199214518Srpaulo	 * Read "/sys/class/net", and add to the list of interfaces all
2200214518Srpaulo	 * interfaces listed there that we don't already have, because,
2201214518Srpaulo	 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2202214518Srpaulo	 * and even getifaddrs() won't return information about
2203214518Srpaulo	 * interfaces with no addresses, so you need to read "/sys/class/net"
2204214518Srpaulo	 * to get the names of the rest of the interfaces.
2205214518Srpaulo	 */
2206214518Srpaulo	ret = scan_sys_class_net(alldevsp, errbuf);
2207214518Srpaulo	if (ret == -1)
2208214518Srpaulo		return (-1);	/* failed */
2209214518Srpaulo	if (ret == 0) {
2210214518Srpaulo		/*
2211214518Srpaulo		 * No /sys/class/net; try reading /proc/net/dev instead.
2212214518Srpaulo		 */
2213214518Srpaulo		if (scan_proc_net_dev(alldevsp, errbuf) == -1)
2214214518Srpaulo			return (-1);
2215214518Srpaulo	}
2216214518Srpaulo
2217214518Srpaulo	/*
2218214518Srpaulo	 * Add the "any" device.
2219214518Srpaulo	 */
2220127664Sbms	if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
2221127664Sbms		return (-1);
2222127664Sbms
2223127664Sbms	return (0);
2224127664Sbms}
2225127664Sbms
2226127664Sbms/*
2227127664Sbms *  Attach the given BPF code to the packet capture device.
2228127664Sbms */
2229127664Sbmsstatic int
2230214518Srpaulopcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
2231214518Srpaulo    int is_mmapped)
2232127664Sbms{
223375107Sfenner#ifdef SO_ATTACH_FILTER
223475107Sfenner	struct sock_fprog	fcode;
223575107Sfenner	int			can_filter_in_kernel;
2236127664Sbms	int			err = 0;
223775107Sfenner#endif
223875107Sfenner
223975107Sfenner	if (!handle)
224075107Sfenner		return -1;
224175107Sfenner	if (!filter) {
224275107Sfenner	        strncpy(handle->errbuf, "setfilter: No filter specified",
2243190225Srpaulo			PCAP_ERRBUF_SIZE);
224475107Sfenner		return -1;
224526175Sfenner	}
224626175Sfenner
224775107Sfenner	/* Make our private copy of the filter */
224875107Sfenner
2249127664Sbms	if (install_bpf_program(handle, filter) < 0)
2250127664Sbms		/* install_bpf_program() filled in errbuf */
225175107Sfenner		return -1;
225239291Sfenner
2253127664Sbms	/*
2254127664Sbms	 * Run user level packet filter by default. Will be overriden if
2255127664Sbms	 * installing a kernel filter succeeds.
225675107Sfenner	 */
225775107Sfenner	handle->md.use_bpf = 0;
225875107Sfenner
225975107Sfenner	/* Install kernel level filter if possible */
226075107Sfenner
226175107Sfenner#ifdef SO_ATTACH_FILTER
226275107Sfenner#ifdef USHRT_MAX
226375107Sfenner	if (handle->fcode.bf_len > USHRT_MAX) {
226475107Sfenner		/*
2265127664Sbms		 * fcode.len is an unsigned short for current kernel.
226675107Sfenner		 * I have yet to see BPF-Code with that much
226775107Sfenner		 * instructions but still it is possible. So for the
226875107Sfenner		 * sake of correctness I added this check.
226975107Sfenner		 */
227075107Sfenner		fprintf(stderr, "Warning: Filter too complex for kernel\n");
2271172677Smlaier		fcode.len = 0;
227275107Sfenner		fcode.filter = NULL;
227375107Sfenner		can_filter_in_kernel = 0;
227475107Sfenner	} else
227575107Sfenner#endif /* USHRT_MAX */
227675107Sfenner	{
227775107Sfenner		/*
227875107Sfenner		 * Oh joy, the Linux kernel uses struct sock_fprog instead
227975107Sfenner		 * of struct bpf_program and of course the length field is
228075107Sfenner		 * of different size. Pointed out by Sebastian
228175107Sfenner		 *
228275107Sfenner		 * Oh, and we also need to fix it up so that all "ret"
228375107Sfenner		 * instructions with non-zero operands have 65535 as the
2284214518Srpaulo		 * operand if we're not capturing in memory-mapped modee,
2285214518Srpaulo		 * and so that, if we're in cooked mode, all memory-reference
2286214518Srpaulo		 * instructions use special magic offsets in references to
2287214518Srpaulo		 * the link-layer header and assume that the link-layer
2288214518Srpaulo		 * payload begins at 0; "fix_program()" will do that.
228975107Sfenner		 */
2290214518Srpaulo		switch (fix_program(handle, &fcode, is_mmapped)) {
229175107Sfenner
229275107Sfenner		case -1:
229375107Sfenner		default:
229475107Sfenner			/*
229575107Sfenner			 * Fatal error; just quit.
229675107Sfenner			 * (The "default" case shouldn't happen; we
229775107Sfenner			 * return -1 for that reason.)
229875107Sfenner			 */
229975107Sfenner			return -1;
230075107Sfenner
230175107Sfenner		case 0:
230275107Sfenner			/*
230375107Sfenner			 * The program performed checks that we can't make
230475107Sfenner			 * work in the kernel.
230575107Sfenner			 */
230675107Sfenner			can_filter_in_kernel = 0;
230775107Sfenner			break;
230875107Sfenner
230975107Sfenner		case 1:
231075107Sfenner			/*
231175107Sfenner			 * We have a filter that'll work in the kernel.
231275107Sfenner			 */
231375107Sfenner			can_filter_in_kernel = 1;
231475107Sfenner			break;
231575107Sfenner		}
231639291Sfenner	}
231739291Sfenner
2318236167Sdelphij	/*
2319236167Sdelphij	 * NOTE: at this point, we've set both the "len" and "filter"
2320236167Sdelphij	 * fields of "fcode".  As of the 2.6.32.4 kernel, at least,
2321236167Sdelphij	 * those are the only members of the "sock_fprog" structure,
2322236167Sdelphij	 * so we initialize every member of that structure.
2323236167Sdelphij	 *
2324236167Sdelphij	 * If there is anything in "fcode" that is not initialized,
2325236167Sdelphij	 * it is either a field added in a later kernel, or it's
2326236167Sdelphij	 * padding.
2327236167Sdelphij	 *
2328236167Sdelphij	 * If a new field is added, this code needs to be updated
2329236167Sdelphij	 * to set it correctly.
2330236167Sdelphij	 *
2331236167Sdelphij	 * If there are no other fields, then:
2332236167Sdelphij	 *
2333236167Sdelphij	 *	if the Linux kernel looks at the padding, it's
2334236167Sdelphij	 *	buggy;
2335236167Sdelphij	 *
2336236167Sdelphij	 *	if the Linux kernel doesn't look at the padding,
2337236167Sdelphij	 *	then if some tool complains that we're passing
2338236167Sdelphij	 *	uninitialized data to the kernel, then the tool
2339236167Sdelphij	 *	is buggy and needs to understand that it's just
2340236167Sdelphij	 *	padding.
2341236167Sdelphij	 */
234275107Sfenner	if (can_filter_in_kernel) {
2343127664Sbms		if ((err = set_kernel_filter(handle, &fcode)) == 0)
234475107Sfenner		{
234575107Sfenner			/* Installation succeded - using kernel filter. */
234675107Sfenner			handle->md.use_bpf = 1;
234775107Sfenner		}
2348127664Sbms		else if (err == -1)	/* Non-fatal error */
234975107Sfenner		{
2350127664Sbms			/*
235175107Sfenner			 * Print a warning if we weren't able to install
235275107Sfenner			 * the filter for a reason other than "this kernel
235375107Sfenner			 * isn't configured to support socket filters.
235475107Sfenner			 */
235575107Sfenner			if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
235675107Sfenner				fprintf(stderr,
2357127664Sbms				    "Warning: Kernel filter failed: %s\n",
235875107Sfenner					pcap_strerror(errno));
235975107Sfenner			}
236075107Sfenner		}
236139291Sfenner	}
236239291Sfenner
236375107Sfenner	/*
236498530Sfenner	 * If we're not using the kernel filter, get rid of any kernel
236598530Sfenner	 * filter that might've been there before, e.g. because the
236698530Sfenner	 * previous filter could work in the kernel, or because some other
236798530Sfenner	 * code attached a filter to the socket by some means other than
236898530Sfenner	 * calling "pcap_setfilter()".  Otherwise, the kernel filter may
236998530Sfenner	 * filter out packets that would pass the new userland filter.
237098530Sfenner	 */
237198530Sfenner	if (!handle->md.use_bpf)
237298530Sfenner		reset_kernel_filter(handle);
237398530Sfenner
237498530Sfenner	/*
237575107Sfenner	 * Free up the copy of the filter that was made by "fix_program()".
237675107Sfenner	 */
237775107Sfenner	if (fcode.filter != NULL)
237875107Sfenner		free(fcode.filter);
2379127664Sbms
2380127664Sbms	if (err == -2)
2381127664Sbms		/* Fatal error */
2382127664Sbms		return -1;
238375107Sfenner#endif /* SO_ATTACH_FILTER */
238475107Sfenner
238575107Sfenner	return 0;
238675107Sfenner}
238775107Sfenner
2388214518Srpaulostatic int
2389214518Srpaulopcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
2390214518Srpaulo{
2391214518Srpaulo	return pcap_setfilter_linux_common(handle, filter, 0);
2392214518Srpaulo}
2393214518Srpaulo
2394214518Srpaulo
239575107Sfenner/*
2396147894Ssam * Set direction flag: Which packets do we accept on a forwarding
2397147894Ssam * single device? IN, OUT or both?
2398147894Ssam */
2399147894Ssamstatic int
2400162012Ssampcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
2401147894Ssam{
2402147894Ssam#ifdef HAVE_PF_PACKET_SOCKETS
2403147894Ssam	if (!handle->md.sock_packet) {
2404147894Ssam		handle->direction = d;
2405147894Ssam		return 0;
2406147894Ssam	}
2407147894Ssam#endif
2408147894Ssam	/*
2409147894Ssam	 * We're not using PF_PACKET sockets, so we can't determine
2410147894Ssam	 * the direction of the packet.
2411147894Ssam	 */
2412190225Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2413147894Ssam	    "Setting direction is not supported on SOCK_PACKET sockets");
2414147894Ssam	return -1;
2415147894Ssam}
2416147894Ssam
2417190225Srpaulo#ifdef HAVE_PF_PACKET_SOCKETS
2418147894Ssam/*
2419190225Srpaulo * Map the PACKET_ value to a LINUX_SLL_ value; we
2420190225Srpaulo * want the same numerical value to be used in
2421190225Srpaulo * the link-layer header even if the numerical values
2422190225Srpaulo * for the PACKET_ #defines change, so that programs
2423190225Srpaulo * that look at the packet type field will always be
2424190225Srpaulo * able to handle DLT_LINUX_SLL captures.
2425190225Srpaulo */
2426190225Srpaulostatic short int
2427190225Srpaulomap_packet_type_to_sll_type(short int sll_pkttype)
2428190225Srpaulo{
2429190225Srpaulo	switch (sll_pkttype) {
2430190225Srpaulo
2431190225Srpaulo	case PACKET_HOST:
2432190225Srpaulo		return htons(LINUX_SLL_HOST);
2433190225Srpaulo
2434190225Srpaulo	case PACKET_BROADCAST:
2435190225Srpaulo		return htons(LINUX_SLL_BROADCAST);
2436190225Srpaulo
2437190225Srpaulo	case PACKET_MULTICAST:
2438190225Srpaulo		return  htons(LINUX_SLL_MULTICAST);
2439190225Srpaulo
2440190225Srpaulo	case PACKET_OTHERHOST:
2441190225Srpaulo		return htons(LINUX_SLL_OTHERHOST);
2442190225Srpaulo
2443190225Srpaulo	case PACKET_OUTGOING:
2444190225Srpaulo		return htons(LINUX_SLL_OUTGOING);
2445190225Srpaulo
2446190225Srpaulo	default:
2447190225Srpaulo		return -1;
2448190225Srpaulo	}
2449190225Srpaulo}
2450190225Srpaulo#endif
2451190225Srpaulo
2452190225Srpaulo/*
2453127664Sbms *  Linux uses the ARP hardware type to identify the type of an
2454127664Sbms *  interface. pcap uses the DLT_xxx constants for this. This
245598530Sfenner *  function takes a pointer to a "pcap_t", and an ARPHRD_xxx
245698530Sfenner *  constant, as arguments, and sets "handle->linktype" to the
245798530Sfenner *  appropriate DLT_XXX constant and sets "handle->offset" to
245898530Sfenner *  the appropriate value (to make "handle->offset" plus link-layer
245998530Sfenner *  header length be a multiple of 4, so that the link-layer payload
246098530Sfenner *  will be aligned on a 4-byte boundary when capturing packets).
246198530Sfenner *  (If the offset isn't set here, it'll be 0; add code as appropriate
246298530Sfenner *  for cases where it shouldn't be 0.)
2463127664Sbms *
2464127664Sbms *  If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2465127664Sbms *  in cooked mode; otherwise, we can't use cooked mode, so we have
2466127664Sbms *  to pick some type that works in raw mode, or fail.
2467127664Sbms *
246898530Sfenner *  Sets the link type to -1 if unable to map the type.
246975107Sfenner */
2470127664Sbmsstatic void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
247175107Sfenner{
247275107Sfenner	switch (arptype) {
247398530Sfenner
247439291Sfenner	case ARPHRD_ETHER:
2475146768Ssam		/*
2476146768Ssam		 * This is (presumably) a real Ethernet capture; give it a
2477146768Ssam		 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2478146768Ssam		 * that an application can let you choose it, in case you're
2479146768Ssam		 * capturing DOCSIS traffic that a Cisco Cable Modem
2480146768Ssam		 * Termination System is putting out onto an Ethernet (it
2481146768Ssam		 * doesn't put an Ethernet header onto the wire, it puts raw
2482146768Ssam		 * DOCSIS frames out on the wire inside the low-level
2483146768Ssam		 * Ethernet framing).
2484146768Ssam		 *
2485146768Ssam		 * XXX - are there any sorts of "fake Ethernet" that have
2486146768Ssam		 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2487146768Ssam		 * a Cisco CMTS won't put traffic onto it or get traffic
2488190225Srpaulo		 * bridged onto it?  ISDN is handled in "activate_new()",
2489146768Ssam		 * as we fall back on cooked mode there; are there any
2490146768Ssam		 * others?
2491146768Ssam		 */
2492146768Ssam		handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2493146768Ssam		/*
2494146768Ssam		 * If that fails, just leave the list empty.
2495146768Ssam		 */
2496146768Ssam		if (handle->dlt_list != NULL) {
2497146768Ssam			handle->dlt_list[0] = DLT_EN10MB;
2498146768Ssam			handle->dlt_list[1] = DLT_DOCSIS;
2499146768Ssam			handle->dlt_count = 2;
2500146768Ssam		}
2501146768Ssam		/* FALLTHROUGH */
2502146768Ssam
250339291Sfenner	case ARPHRD_METRICOM:
250498530Sfenner	case ARPHRD_LOOPBACK:
250598530Sfenner		handle->linktype = DLT_EN10MB;
250698530Sfenner		handle->offset = 2;
250798530Sfenner		break;
250898530Sfenner
250998530Sfenner	case ARPHRD_EETHER:
251098530Sfenner		handle->linktype = DLT_EN3MB;
251198530Sfenner		break;
251298530Sfenner
251398530Sfenner	case ARPHRD_AX25:
2514190225Srpaulo		handle->linktype = DLT_AX25_KISS;
251598530Sfenner		break;
251698530Sfenner
251798530Sfenner	case ARPHRD_PRONET:
251898530Sfenner		handle->linktype = DLT_PRONET;
251998530Sfenner		break;
252098530Sfenner
252198530Sfenner	case ARPHRD_CHAOS:
252298530Sfenner		handle->linktype = DLT_CHAOS;
252398530Sfenner		break;
2524214518Srpaulo#ifndef ARPHRD_CAN
2525214518Srpaulo#define ARPHRD_CAN 280
2526214518Srpaulo#endif
2527214518Srpaulo	case ARPHRD_CAN:
2528214518Srpaulo		handle->linktype = DLT_CAN_SOCKETCAN;
2529214518Srpaulo		break;
253098530Sfenner
253175107Sfenner#ifndef ARPHRD_IEEE802_TR
253275107Sfenner#define ARPHRD_IEEE802_TR 800	/* From Linux 2.4 */
253375107Sfenner#endif
253475107Sfenner	case ARPHRD_IEEE802_TR:
253598530Sfenner	case ARPHRD_IEEE802:
253698530Sfenner		handle->linktype = DLT_IEEE802;
253798530Sfenner		handle->offset = 2;
253898530Sfenner		break;
253939291Sfenner
254098530Sfenner	case ARPHRD_ARCNET:
2541127664Sbms		handle->linktype = DLT_ARCNET_LINUX;
254298530Sfenner		break;
254398530Sfenner
2544127664Sbms#ifndef ARPHRD_FDDI	/* From Linux 2.2.13 */
2545127664Sbms#define ARPHRD_FDDI	774
2546127664Sbms#endif
254798530Sfenner	case ARPHRD_FDDI:
254898530Sfenner		handle->linktype = DLT_FDDI;
254998530Sfenner		handle->offset = 3;
255098530Sfenner		break;
255198530Sfenner
255275107Sfenner#ifndef ARPHRD_ATM  /* FIXME: How to #include this? */
255375107Sfenner#define ARPHRD_ATM 19
255475107Sfenner#endif
255598530Sfenner	case ARPHRD_ATM:
255698530Sfenner		/*
255798530Sfenner		 * The Classical IP implementation in ATM for Linux
255898530Sfenner		 * supports both what RFC 1483 calls "LLC Encapsulation",
255998530Sfenner		 * in which each packet has an LLC header, possibly
256098530Sfenner		 * with a SNAP header as well, prepended to it, and
256198530Sfenner		 * what RFC 1483 calls "VC Based Multiplexing", in which
256298530Sfenner		 * different virtual circuits carry different network
256398530Sfenner		 * layer protocols, and no header is prepended to packets.
256498530Sfenner		 *
256598530Sfenner		 * They both have an ARPHRD_ type of ARPHRD_ATM, so
256698530Sfenner		 * you can't use the ARPHRD_ type to find out whether
256798530Sfenner		 * captured packets will have an LLC header, and,
256898530Sfenner		 * while there's a socket ioctl to *set* the encapsulation
256998530Sfenner		 * type, there's no ioctl to *get* the encapsulation type.
257098530Sfenner		 *
257198530Sfenner		 * This means that
257298530Sfenner		 *
257398530Sfenner		 *	programs that dissect Linux Classical IP frames
257498530Sfenner		 *	would have to check for an LLC header and,
257598530Sfenner		 *	depending on whether they see one or not, dissect
257698530Sfenner		 *	the frame as LLC-encapsulated or as raw IP (I
257798530Sfenner		 *	don't know whether there's any traffic other than
257898530Sfenner		 *	IP that would show up on the socket, or whether
257998530Sfenner		 *	there's any support for IPv6 in the Linux
258098530Sfenner		 *	Classical IP code);
258198530Sfenner		 *
258298530Sfenner		 *	filter expressions would have to compile into
258398530Sfenner		 *	code that checks for an LLC header and does
258498530Sfenner		 *	the right thing.
258598530Sfenner		 *
258698530Sfenner		 * Both of those are a nuisance - and, at least on systems
258798530Sfenner		 * that support PF_PACKET sockets, we don't have to put
258898530Sfenner		 * up with those nuisances; instead, we can just capture
2589127664Sbms		 * in cooked mode.  That's what we'll do, if we can.
2590127664Sbms		 * Otherwise, we'll just fail.
259198530Sfenner		 */
2592127664Sbms		if (cooked_ok)
2593127664Sbms			handle->linktype = DLT_LINUX_SLL;
2594127664Sbms		else
2595127664Sbms			handle->linktype = -1;
259698530Sfenner		break;
259739291Sfenner
259898530Sfenner#ifndef ARPHRD_IEEE80211  /* From Linux 2.4.6 */
259998530Sfenner#define ARPHRD_IEEE80211 801
260098530Sfenner#endif
260198530Sfenner	case ARPHRD_IEEE80211:
260298530Sfenner		handle->linktype = DLT_IEEE802_11;
260398530Sfenner		break;
260498530Sfenner
2605127664Sbms#ifndef ARPHRD_IEEE80211_PRISM  /* From Linux 2.4.18 */
2606127664Sbms#define ARPHRD_IEEE80211_PRISM 802
2607127664Sbms#endif
2608127664Sbms	case ARPHRD_IEEE80211_PRISM:
2609127664Sbms		handle->linktype = DLT_PRISM_HEADER;
2610127664Sbms		break;
2611127664Sbms
2612162012Ssam#ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2613162012Ssam#define ARPHRD_IEEE80211_RADIOTAP 803
2614162012Ssam#endif
2615162012Ssam	case ARPHRD_IEEE80211_RADIOTAP:
2616162012Ssam		handle->linktype = DLT_IEEE802_11_RADIO;
2617162012Ssam		break;
2618162012Ssam
261975107Sfenner	case ARPHRD_PPP:
262098530Sfenner		/*
262198530Sfenner		 * Some PPP code in the kernel supplies no link-layer
262298530Sfenner		 * header whatsoever to PF_PACKET sockets; other PPP
262398530Sfenner		 * code supplies PPP link-layer headers ("syncppp.c");
262498530Sfenner		 * some PPP code might supply random link-layer
262598530Sfenner		 * headers (PPP over ISDN - there's code in Ethereal,
262698530Sfenner		 * for example, to cope with PPP-over-ISDN captures
262798530Sfenner		 * with which the Ethereal developers have had to cope,
262898530Sfenner		 * heuristically trying to determine which of the
262998530Sfenner		 * oddball link-layer headers particular packets have).
263098530Sfenner		 *
263198530Sfenner		 * As such, we just punt, and run all PPP interfaces
2632127664Sbms		 * in cooked mode, if we can; otherwise, we just treat
2633127664Sbms		 * it as DLT_RAW, for now - if somebody needs to capture,
2634127664Sbms		 * on a 2.0[.x] kernel, on PPP devices that supply a
2635127664Sbms		 * link-layer header, they'll have to add code here to
2636127664Sbms		 * map to the appropriate DLT_ type (possibly adding a
2637127664Sbms		 * new DLT_ type, if necessary).
263898530Sfenner		 */
2639127664Sbms		if (cooked_ok)
2640127664Sbms			handle->linktype = DLT_LINUX_SLL;
2641127664Sbms		else {
2642127664Sbms			/*
2643127664Sbms			 * XXX - handle ISDN types here?  We can't fall
2644127664Sbms			 * back on cooked sockets, so we'd have to
2645127664Sbms			 * figure out from the device name what type of
2646127664Sbms			 * link-layer encapsulation it's using, and map
2647127664Sbms			 * that to an appropriate DLT_ value, meaning
2648127664Sbms			 * we'd map "isdnN" devices to DLT_RAW (they
2649127664Sbms			 * supply raw IP packets with no link-layer
2650127664Sbms			 * header) and "isdY" devices to a new DLT_I4L_IP
2651127664Sbms			 * type that has only an Ethernet packet type as
2652127664Sbms			 * a link-layer header.
2653127664Sbms			 *
2654127664Sbms			 * But sometimes we seem to get random crap
2655127664Sbms			 * in the link-layer header when capturing on
2656127664Sbms			 * ISDN devices....
2657127664Sbms			 */
2658127664Sbms			handle->linktype = DLT_RAW;
2659127664Sbms		}
266098530Sfenner		break;
266198530Sfenner
2662127664Sbms#ifndef ARPHRD_CISCO
2663127664Sbms#define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2664127664Sbms#endif
2665127664Sbms	case ARPHRD_CISCO:
266698530Sfenner		handle->linktype = DLT_C_HDLC;
266798530Sfenner		break;
266898530Sfenner
266975107Sfenner	/* Not sure if this is correct for all tunnels, but it
267075107Sfenner	 * works for CIPE */
267175107Sfenner	case ARPHRD_TUNNEL:
267275107Sfenner#ifndef ARPHRD_SIT
2673127664Sbms#define ARPHRD_SIT 776	/* From Linux 2.2.13 */
267475107Sfenner#endif
267575107Sfenner	case ARPHRD_SIT:
267675107Sfenner	case ARPHRD_CSLIP:
267775107Sfenner	case ARPHRD_SLIP6:
267875107Sfenner	case ARPHRD_CSLIP6:
267998530Sfenner	case ARPHRD_ADAPT:
268098530Sfenner	case ARPHRD_SLIP:
2681127664Sbms#ifndef ARPHRD_RAWHDLC
2682127664Sbms#define ARPHRD_RAWHDLC 518
2683127664Sbms#endif
2684127664Sbms	case ARPHRD_RAWHDLC:
2685127664Sbms#ifndef ARPHRD_DLCI
2686127664Sbms#define ARPHRD_DLCI 15
2687127664Sbms#endif
2688127664Sbms	case ARPHRD_DLCI:
268998530Sfenner		/*
269098530Sfenner		 * XXX - should some of those be mapped to DLT_LINUX_SLL
269198530Sfenner		 * instead?  Should we just map all of them to DLT_LINUX_SLL?
269298530Sfenner		 */
269398530Sfenner		handle->linktype = DLT_RAW;
269498530Sfenner		break;
269598530Sfenner
2696127664Sbms#ifndef ARPHRD_FRAD
2697127664Sbms#define ARPHRD_FRAD 770
2698127664Sbms#endif
2699127664Sbms	case ARPHRD_FRAD:
2700127664Sbms		handle->linktype = DLT_FRELAY;
2701127664Sbms		break;
2702127664Sbms
270398530Sfenner	case ARPHRD_LOCALTLK:
270498530Sfenner		handle->linktype = DLT_LTALK;
270598530Sfenner		break;
270698530Sfenner
2707127664Sbms#ifndef ARPHRD_FCPP
2708127664Sbms#define ARPHRD_FCPP	784
2709127664Sbms#endif
2710127664Sbms	case ARPHRD_FCPP:
2711127664Sbms#ifndef ARPHRD_FCAL
2712127664Sbms#define ARPHRD_FCAL	785
2713127664Sbms#endif
2714127664Sbms	case ARPHRD_FCAL:
2715127664Sbms#ifndef ARPHRD_FCPL
2716127664Sbms#define ARPHRD_FCPL	786
2717127664Sbms#endif
2718127664Sbms	case ARPHRD_FCPL:
2719127664Sbms#ifndef ARPHRD_FCFABRIC
2720127664Sbms#define ARPHRD_FCFABRIC	787
2721127664Sbms#endif
2722127664Sbms	case ARPHRD_FCFABRIC:
2723127664Sbms		/*
2724127664Sbms		 * We assume that those all mean RFC 2625 IP-over-
2725127664Sbms		 * Fibre Channel, with the RFC 2625 header at
2726127664Sbms		 * the beginning of the packet.
2727127664Sbms		 */
2728127664Sbms		handle->linktype = DLT_IP_OVER_FC;
2729127664Sbms		break;
2730127664Sbms
2731146768Ssam#ifndef ARPHRD_IRDA
2732146768Ssam#define ARPHRD_IRDA	783
2733146768Ssam#endif
2734127664Sbms	case ARPHRD_IRDA:
2735127664Sbms		/* Don't expect IP packet out of this interfaces... */
2736127664Sbms		handle->linktype = DLT_LINUX_IRDA;
2737127664Sbms		/* We need to save packet direction for IrDA decoding,
2738127664Sbms		 * so let's use "Linux-cooked" mode. Jean II */
2739127664Sbms		//handle->md.cooked = 1;
2740127664Sbms		break;
2741127664Sbms
2742172677Smlaier	/* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2743172677Smlaier	 * is needed, please report it to <daniele@orlandi.com> */
2744172677Smlaier#ifndef ARPHRD_LAPD
2745172677Smlaier#define ARPHRD_LAPD	8445
2746172677Smlaier#endif
2747172677Smlaier	case ARPHRD_LAPD:
2748172677Smlaier		/* Don't expect IP packet out of this interfaces... */
2749172677Smlaier		handle->linktype = DLT_LINUX_LAPD;
2750172677Smlaier		break;
2751172677Smlaier
2752190225Srpaulo#ifndef ARPHRD_NONE
2753190225Srpaulo#define ARPHRD_NONE	0xFFFE
2754190225Srpaulo#endif
2755190225Srpaulo	case ARPHRD_NONE:
2756190225Srpaulo		/*
2757190225Srpaulo		 * No link-layer header; packets are just IP
2758190225Srpaulo		 * packets, so use DLT_RAW.
2759190225Srpaulo		 */
2760190225Srpaulo		handle->linktype = DLT_RAW;
2761190225Srpaulo		break;
2762190225Srpaulo
2763236167Sdelphij#ifndef ARPHRD_IEEE802154
2764236167Sdelphij#define ARPHRD_IEEE802154      804
2765236167Sdelphij#endif
2766236167Sdelphij       case ARPHRD_IEEE802154:
2767236167Sdelphij               handle->linktype =  DLT_IEEE802_15_4_NOFCS;
2768236167Sdelphij               break;
2769236167Sdelphij
277098530Sfenner	default:
277198530Sfenner		handle->linktype = -1;
277298530Sfenner		break;
277375107Sfenner	}
277475107Sfenner}
277539291Sfenner
277675107Sfenner/* ===== Functions to interface to the newer kernels ================== */
277739291Sfenner
277875107Sfenner/*
2779190225Srpaulo * Try to open a packet socket using the new kernel PF_PACKET interface.
2780190225Srpaulo * Returns 1 on success, 0 on an error that means the new interface isn't
2781190225Srpaulo * present (so the old SOCK_PACKET interface should be tried), and a
2782190225Srpaulo * PCAP_ERROR_ value on an error that means that the old mechanism won't
2783190225Srpaulo * work either (so it shouldn't be tried).
278475107Sfenner */
278575107Sfennerstatic int
2786190225Srpauloactivate_new(pcap_t *handle)
278775107Sfenner{
278875107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
2789214518Srpaulo	const char		*device = handle->opt.source;
2790214518Srpaulo	int			is_any_device = (strcmp(device, "any") == 0);
2791214518Srpaulo	int			sock_fd = -1, arptype;
2792214518Srpaulo#ifdef HAVE_PACKET_AUXDATA
2793214518Srpaulo	int			val;
2794214518Srpaulo#endif
2795190225Srpaulo	int			err = 0;
279675107Sfenner	struct packet_mreq	mr;
279739291Sfenner
2798190225Srpaulo	/*
2799214518Srpaulo	 * Open a socket with protocol family packet. If the
2800214518Srpaulo	 * "any" device was specified, we open a SOCK_DGRAM
2801214518Srpaulo	 * socket for the cooked interface, otherwise we first
2802214518Srpaulo	 * try a SOCK_RAW socket for the raw interface.
2803190225Srpaulo	 */
2804214518Srpaulo	sock_fd = is_any_device ?
2805214518Srpaulo		socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
2806214518Srpaulo		socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
280739291Sfenner
2808190225Srpaulo	if (sock_fd == -1) {
2809236167Sdelphij		if (errno == EINVAL || errno == EAFNOSUPPORT) {
2810236167Sdelphij			/*
2811236167Sdelphij			 * We don't support PF_PACKET/SOCK_whatever
2812236167Sdelphij			 * sockets; try the old mechanism.
2813236167Sdelphij			 */
2814236167Sdelphij			return 0;
2815236167Sdelphij		}
2816236167Sdelphij
2817190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
2818190225Srpaulo			 pcap_strerror(errno) );
2819236167Sdelphij		if (errno == EPERM || errno == EACCES) {
2820236167Sdelphij			/*
2821236167Sdelphij			 * You don't have permission to open the
2822236167Sdelphij			 * socket.
2823236167Sdelphij			 */
2824236167Sdelphij			return PCAP_ERROR_PERM_DENIED;
2825236167Sdelphij		} else {
2826236167Sdelphij			/*
2827236167Sdelphij			 * Other error.
2828236167Sdelphij			 */
2829236167Sdelphij			return PCAP_ERROR;
2830236167Sdelphij		}
2831190225Srpaulo	}
283239291Sfenner
2833190225Srpaulo	/* It seems the kernel supports the new interface. */
2834190225Srpaulo	handle->md.sock_packet = 0;
283539291Sfenner
2836190225Srpaulo	/*
2837190225Srpaulo	 * Get the interface index of the loopback device.
2838190225Srpaulo	 * If the attempt fails, don't fail, just set the
2839190225Srpaulo	 * "md.lo_ifindex" to -1.
2840190225Srpaulo	 *
2841190225Srpaulo	 * XXX - can there be more than one device that loops
2842190225Srpaulo	 * packets back, i.e. devices other than "lo"?  If so,
2843190225Srpaulo	 * we'd need to find them all, and have an array of
2844190225Srpaulo	 * indices for them, and check all of them in
2845190225Srpaulo	 * "pcap_read_packet()".
2846190225Srpaulo	 */
2847190225Srpaulo	handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
284875107Sfenner
2849190225Srpaulo	/*
2850190225Srpaulo	 * Default value for offset to align link-layer payload
2851190225Srpaulo	 * on a 4-byte boundary.
2852190225Srpaulo	 */
2853190225Srpaulo	handle->offset	 = 0;
285475107Sfenner
2855190225Srpaulo	/*
2856190225Srpaulo	 * What kind of frames do we have to deal with? Fall back
2857190225Srpaulo	 * to cooked mode if we have an unknown interface type
2858190225Srpaulo	 * or a type we know doesn't work well in raw mode.
2859190225Srpaulo	 */
2860214518Srpaulo	if (!is_any_device) {
2861190225Srpaulo		/* Assume for now we don't need cooked mode. */
2862190225Srpaulo		handle->md.cooked = 0;
286398530Sfenner
2864190225Srpaulo		if (handle->opt.rfmon) {
2865190225Srpaulo			/*
2866190225Srpaulo			 * We were asked to turn on monitor mode.
2867190225Srpaulo			 * Do so before we get the link-layer type,
2868190225Srpaulo			 * because entering monitor mode could change
2869190225Srpaulo			 * the link-layer type.
2870190225Srpaulo			 */
2871214518Srpaulo			err = enter_rfmon_mode(handle, sock_fd, device);
2872190225Srpaulo			if (err < 0) {
2873190225Srpaulo				/* Hard failure */
2874190225Srpaulo				close(sock_fd);
2875190225Srpaulo				return err;
2876127664Sbms			}
2877190225Srpaulo			if (err == 0) {
287875107Sfenner				/*
2879190225Srpaulo				 * Nothing worked for turning monitor mode
2880190225Srpaulo				 * on.
288175107Sfenner				 */
2882190225Srpaulo				close(sock_fd);
2883190225Srpaulo				return PCAP_ERROR_RFMON_NOTSUP;
2884190225Srpaulo			}
2885214518Srpaulo
2886214518Srpaulo			/*
2887214518Srpaulo			 * Either monitor mode has been turned on for
2888214518Srpaulo			 * the device, or we've been given a different
2889214518Srpaulo			 * device to open for monitor mode.  If we've
2890214518Srpaulo			 * been given a different device, use it.
2891214518Srpaulo			 */
2892214518Srpaulo			if (handle->md.mondevice != NULL)
2893214518Srpaulo				device = handle->md.mondevice;
2894190225Srpaulo		}
2895190225Srpaulo		arptype	= iface_get_arptype(sock_fd, device, handle->errbuf);
2896190225Srpaulo		if (arptype < 0) {
2897190225Srpaulo			close(sock_fd);
2898190225Srpaulo			return arptype;
2899190225Srpaulo		}
2900190225Srpaulo		map_arphrd_to_dlt(handle, arptype, 1);
2901190225Srpaulo		if (handle->linktype == -1 ||
2902190225Srpaulo		    handle->linktype == DLT_LINUX_SLL ||
2903190225Srpaulo		    handle->linktype == DLT_LINUX_IRDA ||
2904190225Srpaulo		    handle->linktype == DLT_LINUX_LAPD ||
2905190225Srpaulo		    (handle->linktype == DLT_EN10MB &&
2906190225Srpaulo		     (strncmp("isdn", device, 4) == 0 ||
2907190225Srpaulo		      strncmp("isdY", device, 4) == 0))) {
2908190225Srpaulo			/*
2909190225Srpaulo			 * Unknown interface type (-1), or a
2910190225Srpaulo			 * device we explicitly chose to run
2911190225Srpaulo			 * in cooked mode (e.g., PPP devices),
2912190225Srpaulo			 * or an ISDN device (whose link-layer
2913190225Srpaulo			 * type we can only determine by using
2914190225Srpaulo			 * APIs that may be different on different
2915190225Srpaulo			 * kernels) - reopen in cooked mode.
2916190225Srpaulo			 */
2917190225Srpaulo			if (close(sock_fd) == -1) {
2918190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2919190225Srpaulo					 "close: %s", pcap_strerror(errno));
2920190225Srpaulo				return PCAP_ERROR;
2921190225Srpaulo			}
2922190225Srpaulo			sock_fd = socket(PF_PACKET, SOCK_DGRAM,
2923190225Srpaulo			    htons(ETH_P_ALL));
2924190225Srpaulo			if (sock_fd == -1) {
2925190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2926190225Srpaulo				    "socket: %s", pcap_strerror(errno));
2927236167Sdelphij				if (errno == EPERM || errno == EACCES) {
2928236167Sdelphij					/*
2929236167Sdelphij					 * You don't have permission to
2930236167Sdelphij					 * open the socket.
2931236167Sdelphij					 */
2932236167Sdelphij					return PCAP_ERROR_PERM_DENIED;
2933236167Sdelphij				} else {
2934236167Sdelphij					/*
2935236167Sdelphij					 * Other error.
2936236167Sdelphij					 */
2937236167Sdelphij					return PCAP_ERROR;
2938236167Sdelphij				}
2939190225Srpaulo			}
2940190225Srpaulo			handle->md.cooked = 1;
294175107Sfenner
2942190225Srpaulo			/*
2943190225Srpaulo			 * Get rid of any link-layer type list
2944190225Srpaulo			 * we allocated - this only supports cooked
2945190225Srpaulo			 * capture.
2946190225Srpaulo			 */
2947190225Srpaulo			if (handle->dlt_list != NULL) {
2948190225Srpaulo				free(handle->dlt_list);
2949190225Srpaulo				handle->dlt_list = NULL;
2950190225Srpaulo				handle->dlt_count = 0;
2951190225Srpaulo			}
2952190225Srpaulo
2953190225Srpaulo			if (handle->linktype == -1) {
2954146768Ssam				/*
2955190225Srpaulo				 * Warn that we're falling back on
2956190225Srpaulo				 * cooked mode; we may want to
2957190225Srpaulo				 * update "map_arphrd_to_dlt()"
2958190225Srpaulo				 * to handle the new type.
2959146768Ssam				 */
2960190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2961190225Srpaulo					"arptype %d not "
2962190225Srpaulo					"supported by libpcap - "
2963190225Srpaulo					"falling back to cooked "
2964190225Srpaulo					"socket",
2965190225Srpaulo					arptype);
296675107Sfenner			}
296775107Sfenner
296875107Sfenner			/*
2969190225Srpaulo			 * IrDA capture is not a real "cooked" capture,
2970190225Srpaulo			 * it's IrLAP frames, not IP packets.  The
2971190225Srpaulo			 * same applies to LAPD capture.
297275107Sfenner			 */
2973190225Srpaulo			if (handle->linktype != DLT_LINUX_IRDA &&
2974190225Srpaulo			    handle->linktype != DLT_LINUX_LAPD)
2975190225Srpaulo				handle->linktype = DLT_LINUX_SLL;
2976190225Srpaulo		}
297775107Sfenner
2978190225Srpaulo		handle->md.ifindex = iface_get_id(sock_fd, device,
2979190225Srpaulo		    handle->errbuf);
2980190225Srpaulo		if (handle->md.ifindex == -1) {
2981190225Srpaulo			close(sock_fd);
2982190225Srpaulo			return PCAP_ERROR;
298375107Sfenner		}
298475107Sfenner
2985190225Srpaulo		if ((err = iface_bind(sock_fd, handle->md.ifindex,
2986190225Srpaulo		    handle->errbuf)) != 1) {
2987190225Srpaulo		    	close(sock_fd);
2988190225Srpaulo			if (err < 0)
2989190225Srpaulo				return err;
2990190225Srpaulo			else
2991190225Srpaulo				return 0;	/* try old mechanism */
2992190225Srpaulo		}
2993190225Srpaulo	} else {
2994127664Sbms		/*
2995214518Srpaulo		 * The "any" device.
2996127664Sbms		 */
2997214518Srpaulo		if (handle->opt.rfmon) {
2998214518Srpaulo			/*
2999214518Srpaulo			 * It doesn't support monitor mode.
3000214518Srpaulo			 */
3001214518Srpaulo			return PCAP_ERROR_RFMON_NOTSUP;
3002214518Srpaulo		}
3003214518Srpaulo
3004214518Srpaulo		/*
3005214518Srpaulo		 * It uses cooked mode.
3006214518Srpaulo		 */
3007190225Srpaulo		handle->md.cooked = 1;
3008190225Srpaulo		handle->linktype = DLT_LINUX_SLL;
300975107Sfenner
3010127664Sbms		/*
3011190225Srpaulo		 * We're not bound to a device.
3012190225Srpaulo		 * For now, we're using this as an indication
3013190225Srpaulo		 * that we can't transmit; stop doing that only
3014190225Srpaulo		 * if we figure out how to transmit in cooked
3015190225Srpaulo		 * mode.
301675107Sfenner		 */
3017190225Srpaulo		handle->md.ifindex = -1;
3018190225Srpaulo	}
301975107Sfenner
3020190225Srpaulo	/*
3021190225Srpaulo	 * Select promiscuous mode on if "promisc" is set.
3022190225Srpaulo	 *
3023190225Srpaulo	 * Do not turn allmulti mode on if we don't select
3024190225Srpaulo	 * promiscuous mode - on some devices (e.g., Orinoco
3025190225Srpaulo	 * wireless interfaces), allmulti mode isn't supported
3026190225Srpaulo	 * and the driver implements it by turning promiscuous
3027190225Srpaulo	 * mode on, and that screws up the operation of the
3028190225Srpaulo	 * card as a normal networking interface, and on no
3029190225Srpaulo	 * other platform I know of does starting a non-
3030190225Srpaulo	 * promiscuous capture affect which multicast packets
3031190225Srpaulo	 * are received by the interface.
3032190225Srpaulo	 */
303339291Sfenner
3034190225Srpaulo	/*
3035190225Srpaulo	 * Hmm, how can we set promiscuous mode on all interfaces?
3036214518Srpaulo	 * I am not sure if that is possible at all.  For now, we
3037214518Srpaulo	 * silently ignore attempts to turn promiscuous mode on
3038214518Srpaulo	 * for the "any" device (so you don't have to explicitly
3039214518Srpaulo	 * disable it in programs such as tcpdump).
3040190225Srpaulo	 */
304175107Sfenner
3042214518Srpaulo	if (!is_any_device && handle->opt.promisc) {
3043190225Srpaulo		memset(&mr, 0, sizeof(mr));
3044190225Srpaulo		mr.mr_ifindex = handle->md.ifindex;
3045190225Srpaulo		mr.mr_type    = PACKET_MR_PROMISC;
3046190225Srpaulo		if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
3047190225Srpaulo		    &mr, sizeof(mr)) == -1) {
3048190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3049190225Srpaulo				"setsockopt: %s", pcap_strerror(errno));
3050190225Srpaulo			close(sock_fd);
3051190225Srpaulo			return PCAP_ERROR;
3052190225Srpaulo		}
3053190225Srpaulo	}
305475107Sfenner
3055190225Srpaulo	/* Enable auxillary data if supported and reserve room for
3056190225Srpaulo	 * reconstructing VLAN headers. */
3057190225Srpaulo#ifdef HAVE_PACKET_AUXDATA
3058190225Srpaulo	val = 1;
3059190225Srpaulo	if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
3060190225Srpaulo		       sizeof(val)) == -1 && errno != ENOPROTOOPT) {
3061190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3062190225Srpaulo			 "setsockopt: %s", pcap_strerror(errno));
3063190225Srpaulo		close(sock_fd);
3064190225Srpaulo		return PCAP_ERROR;
3065190225Srpaulo	}
3066190225Srpaulo	handle->offset += VLAN_TAG_LEN;
3067190225Srpaulo#endif /* HAVE_PACKET_AUXDATA */
306875107Sfenner
3069190225Srpaulo	/*
3070190225Srpaulo	 * This is a 2.2[.x] or later kernel (we know that
3071190225Srpaulo	 * because we're not using a SOCK_PACKET socket -
3072190225Srpaulo	 * PF_PACKET is supported only in 2.2 and later
3073190225Srpaulo	 * kernels).
3074190225Srpaulo	 *
3075190225Srpaulo	 * We can safely pass "recvfrom()" a byte count
3076190225Srpaulo	 * based on the snapshot length.
3077190225Srpaulo	 *
3078190225Srpaulo	 * If we're in cooked mode, make the snapshot length
3079190225Srpaulo	 * large enough to hold a "cooked mode" header plus
3080190225Srpaulo	 * 1 byte of packet data (so we don't pass a byte
3081190225Srpaulo	 * count of 0 to "recvfrom()").
3082190225Srpaulo	 */
3083190225Srpaulo	if (handle->md.cooked) {
3084190225Srpaulo		if (handle->snapshot < SLL_HDR_LEN + 1)
3085190225Srpaulo			handle->snapshot = SLL_HDR_LEN + 1;
3086190225Srpaulo	}
3087190225Srpaulo	handle->bufsize = handle->snapshot;
308875107Sfenner
3089252281Sdelphij	/*
3090252281Sdelphij	 * Set the offset at which to insert VLAN tags.
3091252281Sdelphij	 */
3092252281Sdelphij	switch (handle->linktype) {
3093252281Sdelphij
3094252281Sdelphij	case DLT_EN10MB:
3095252281Sdelphij		handle->md.vlan_offset = 2 * ETH_ALEN;
3096252281Sdelphij		break;
3097252281Sdelphij
3098252281Sdelphij	case DLT_LINUX_SLL:
3099252281Sdelphij		handle->md.vlan_offset = 14;
3100252281Sdelphij		break;
3101252281Sdelphij
3102252281Sdelphij	default:
3103252281Sdelphij		handle->md.vlan_offset = -1; /* unknown */
3104252281Sdelphij		break;
3105252281Sdelphij	}
3106252281Sdelphij
3107190225Srpaulo	/* Save the socket FD in the pcap structure */
3108190225Srpaulo	handle->fd = sock_fd;
3109127664Sbms
3110190225Srpaulo	return 1;
311175107Sfenner#else
3112127664Sbms	strncpy(ebuf,
3113127664Sbms		"New packet capturing interface not supported by build "
311475107Sfenner		"environment", PCAP_ERRBUF_SIZE);
311575107Sfenner	return 0;
311639291Sfenner#endif
311775107Sfenner}
311839291Sfenner
3119236167Sdelphij#ifdef HAVE_PACKET_RING
3120236167Sdelphij/*
3121236167Sdelphij * Attempt to activate with memory-mapped access.
3122236167Sdelphij *
3123236167Sdelphij * On success, returns 1, and sets *status to 0 if there are no warnings
3124236167Sdelphij * or to a PCAP_WARNING_ code if there is a warning.
3125236167Sdelphij *
3126236167Sdelphij * On failure due to lack of support for memory-mapped capture, returns
3127236167Sdelphij * 0.
3128236167Sdelphij *
3129236167Sdelphij * On error, returns -1, and sets *status to the appropriate error code;
3130236167Sdelphij * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3131236167Sdelphij */
3132190225Srpaulostatic int
3133236167Sdelphijactivate_mmap(pcap_t *handle, int *status)
3134190225Srpaulo{
3135190225Srpaulo	int ret;
3136190225Srpaulo
3137214518Srpaulo	/*
3138214518Srpaulo	 * Attempt to allocate a buffer to hold the contents of one
3139214518Srpaulo	 * packet, for use by the oneshot callback.
3140214518Srpaulo	 */
3141214518Srpaulo	handle->md.oneshot_buffer = malloc(handle->snapshot);
3142214518Srpaulo	if (handle->md.oneshot_buffer == NULL) {
3143214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3144214518Srpaulo			 "can't allocate oneshot buffer: %s",
3145214518Srpaulo			 pcap_strerror(errno));
3146236167Sdelphij		*status = PCAP_ERROR;
3147236167Sdelphij		return -1;
3148214518Srpaulo	}
3149214518Srpaulo
3150190225Srpaulo	if (handle->opt.buffer_size == 0) {
3151190225Srpaulo		/* by default request 2M for the ring buffer */
3152190225Srpaulo		handle->opt.buffer_size = 2*1024*1024;
3153190225Srpaulo	}
3154190225Srpaulo	ret = prepare_tpacket_socket(handle);
3155236167Sdelphij	if (ret == -1) {
3156214518Srpaulo		free(handle->md.oneshot_buffer);
3157236167Sdelphij		*status = PCAP_ERROR;
3158190225Srpaulo		return ret;
3159214518Srpaulo	}
3160236167Sdelphij	ret = create_ring(handle, status);
3161236167Sdelphij	if (ret == 0) {
3162236167Sdelphij		/*
3163236167Sdelphij		 * We don't support memory-mapped capture; our caller
3164236167Sdelphij		 * will fall back on reading from the socket.
3165236167Sdelphij		 */
3166214518Srpaulo		free(handle->md.oneshot_buffer);
3167236167Sdelphij		return 0;
3168214518Srpaulo	}
3169236167Sdelphij	if (ret == -1) {
3170236167Sdelphij		/*
3171236167Sdelphij		 * Error attempting to enable memory-mapped capture;
3172236167Sdelphij		 * fail.  create_ring() has set *status.
3173236167Sdelphij		 */
3174236167Sdelphij		free(handle->md.oneshot_buffer);
3175236167Sdelphij		return -1;
3176236167Sdelphij	}
3177190225Srpaulo
3178236167Sdelphij	/*
3179236167Sdelphij	 * Success.  *status has been set either to 0 if there are no
3180236167Sdelphij	 * warnings or to a PCAP_WARNING_ value if there is a warning.
3181236167Sdelphij	 *
3182236167Sdelphij	 * Override some defaults and inherit the other fields from
3183236167Sdelphij	 * activate_new.
3184236167Sdelphij	 * handle->offset is used to get the current position into the rx ring.
3185236167Sdelphij	 * handle->cc is used to store the ring size.
3186236167Sdelphij	 */
3187190225Srpaulo	handle->read_op = pcap_read_linux_mmap;
3188190225Srpaulo	handle->cleanup_op = pcap_cleanup_linux_mmap;
3189190225Srpaulo	handle->setfilter_op = pcap_setfilter_linux_mmap;
3190190225Srpaulo	handle->setnonblock_op = pcap_setnonblock_mmap;
3191190225Srpaulo	handle->getnonblock_op = pcap_getnonblock_mmap;
3192214518Srpaulo	handle->oneshot_callback = pcap_oneshot_mmap;
3193190225Srpaulo	handle->selectable_fd = handle->fd;
3194190225Srpaulo	return 1;
3195236167Sdelphij}
3196190225Srpaulo#else /* HAVE_PACKET_RING */
3197236167Sdelphijstatic int
3198236167Sdelphijactivate_mmap(pcap_t *handle _U_, int *status _U_)
3199236167Sdelphij{
3200190225Srpaulo	return 0;
3201236167Sdelphij}
3202190225Srpaulo#endif /* HAVE_PACKET_RING */
3203190225Srpaulo
3204190225Srpaulo#ifdef HAVE_PACKET_RING
3205236167Sdelphij/*
3206236167Sdelphij * Attempt to set the socket to version 2 of the memory-mapped header.
3207236167Sdelphij * Return 1 if we succeed or if we fail because version 2 isn't
3208236167Sdelphij * supported; return -1 on any other error, and set handle->errbuf.
3209236167Sdelphij */
3210190225Srpaulostatic int
3211190225Srpauloprepare_tpacket_socket(pcap_t *handle)
3212190225Srpaulo{
3213190225Srpaulo#ifdef HAVE_TPACKET2
3214190225Srpaulo	socklen_t len;
3215190225Srpaulo	int val;
3216190225Srpaulo#endif
3217190225Srpaulo
3218190225Srpaulo	handle->md.tp_version = TPACKET_V1;
3219190225Srpaulo	handle->md.tp_hdrlen = sizeof(struct tpacket_hdr);
3220190225Srpaulo
3221190225Srpaulo#ifdef HAVE_TPACKET2
3222190225Srpaulo	/* Probe whether kernel supports TPACKET_V2 */
3223190225Srpaulo	val = TPACKET_V2;
3224190225Srpaulo	len = sizeof(val);
3225190225Srpaulo	if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
3226190225Srpaulo		if (errno == ENOPROTOOPT)
3227214518Srpaulo			return 1;	/* no - just drive on */
3228214518Srpaulo
3229214518Srpaulo		/* Yes - treat as a failure. */
3230190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3231214518Srpaulo		    "can't get TPACKET_V2 header len on packet socket: %s",
3232214518Srpaulo		    pcap_strerror(errno));
3233214518Srpaulo		return -1;
3234190225Srpaulo	}
3235190225Srpaulo	handle->md.tp_hdrlen = val;
3236190225Srpaulo
3237190225Srpaulo	val = TPACKET_V2;
3238190225Srpaulo	if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
3239190225Srpaulo		       sizeof(val)) < 0) {
3240190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3241214518Srpaulo		    "can't activate TPACKET_V2 on packet socket: %s",
3242214518Srpaulo		    pcap_strerror(errno));
3243214518Srpaulo		return -1;
3244190225Srpaulo	}
3245190225Srpaulo	handle->md.tp_version = TPACKET_V2;
3246190225Srpaulo
3247190225Srpaulo	/* Reserve space for VLAN tag reconstruction */
3248190225Srpaulo	val = VLAN_TAG_LEN;
3249190225Srpaulo	if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
3250190225Srpaulo		       sizeof(val)) < 0) {
3251190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3252214518Srpaulo		    "can't set up reserve on packet socket: %s",
3253214518Srpaulo		    pcap_strerror(errno));
3254214518Srpaulo		return -1;
3255190225Srpaulo	}
3256190225Srpaulo
3257190225Srpaulo#endif /* HAVE_TPACKET2 */
3258190225Srpaulo	return 1;
3259190225Srpaulo}
3260190225Srpaulo
3261236167Sdelphij/*
3262236167Sdelphij * Attempt to set up memory-mapped access.
3263236167Sdelphij *
3264236167Sdelphij * On success, returns 1, and sets *status to 0 if there are no warnings
3265236167Sdelphij * or to a PCAP_WARNING_ code if there is a warning.
3266236167Sdelphij *
3267236167Sdelphij * On failure due to lack of support for memory-mapped capture, returns
3268236167Sdelphij * 0.
3269236167Sdelphij *
3270236167Sdelphij * On error, returns -1, and sets *status to the appropriate error code;
3271236167Sdelphij * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3272236167Sdelphij */
3273190225Srpaulostatic int
3274236167Sdelphijcreate_ring(pcap_t *handle, int *status)
3275190225Srpaulo{
3276214518Srpaulo	unsigned i, j, frames_per_block;
3277190225Srpaulo	struct tpacket_req req;
3278236167Sdelphij	socklen_t len;
3279236167Sdelphij	unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
3280236167Sdelphij	unsigned int frame_size;
3281190225Srpaulo
3282236167Sdelphij	/*
3283236167Sdelphij	 * Start out assuming no warnings or errors.
3284236167Sdelphij	 */
3285236167Sdelphij	*status = 0;
3286236167Sdelphij
3287236167Sdelphij	/* Note that with large snapshot length (say 64K, which is the default
3288236167Sdelphij	 * for recent versions of tcpdump, the value that "-s 0" has given
3289236167Sdelphij	 * for a long time with tcpdump, and the default in Wireshark/TShark),
3290236167Sdelphij	 * if we use the snapshot length to calculate the frame length,
3291236167Sdelphij	 * only a few frames will be available in the ring even with pretty
3292236167Sdelphij	 * large ring size (and a lot of memory will be unused).
3293236167Sdelphij	 *
3294236167Sdelphij	 * Ideally, we should choose a frame length based on the
3295236167Sdelphij	 * minimum of the specified snapshot length and the maximum
3296236167Sdelphij	 * packet size.  That's not as easy as it sounds; consider, for
3297236167Sdelphij	 * example, an 802.11 interface in monitor mode, where the
3298236167Sdelphij	 * frame would include a radiotap header, where the maximum
3299236167Sdelphij	 * radiotap header length is device-dependent.
3300236167Sdelphij	 *
3301236167Sdelphij	 * So, for now, we just do this for Ethernet devices, where
3302236167Sdelphij	 * there's no metadata header, and the link-layer header is
3303236167Sdelphij	 * fixed length.  We can get the maximum packet size by
3304236167Sdelphij	 * adding 18, the Ethernet header length plus the CRC length
3305236167Sdelphij	 * (just in case we happen to get the CRC in the packet), to
3306236167Sdelphij	 * the MTU of the interface; we fetch the MTU in the hopes
3307236167Sdelphij	 * that it reflects support for jumbo frames.  (Even if the
3308236167Sdelphij	 * interface is just being used for passive snooping, the driver
3309236167Sdelphij	 * might set the size of buffers in the receive ring based on
3310236167Sdelphij	 * the MTU, so that the MTU limits the maximum size of packets
3311236167Sdelphij	 * that we can receive.)
3312236167Sdelphij	 *
3313236167Sdelphij	 * We don't do that if segmentation/fragmentation or receive
3314236167Sdelphij	 * offload are enabled, so we don't get rudely surprised by
3315236167Sdelphij	 * "packets" bigger than the MTU. */
3316236167Sdelphij	frame_size = handle->snapshot;
3317236167Sdelphij	if (handle->linktype == DLT_EN10MB) {
3318236167Sdelphij		int mtu;
3319236167Sdelphij		int offload;
3320236167Sdelphij
3321236167Sdelphij		offload = iface_get_offload(handle);
3322236167Sdelphij		if (offload == -1) {
3323236167Sdelphij			*status = PCAP_ERROR;
3324236167Sdelphij			return -1;
3325236167Sdelphij		}
3326236167Sdelphij		if (!offload) {
3327236167Sdelphij			mtu = iface_get_mtu(handle->fd, handle->opt.source,
3328236167Sdelphij			    handle->errbuf);
3329236167Sdelphij			if (mtu == -1) {
3330236167Sdelphij				*status = PCAP_ERROR;
3331236167Sdelphij				return -1;
3332236167Sdelphij			}
3333236167Sdelphij			if (frame_size > mtu + 18)
3334236167Sdelphij				frame_size = mtu + 18;
3335236167Sdelphij		}
3336236167Sdelphij	}
3337236167Sdelphij
3338236167Sdelphij	/* NOTE: calculus matching those in tpacket_rcv()
3339236167Sdelphij	 * in linux-2.6/net/packet/af_packet.c
3340236167Sdelphij	 */
3341236167Sdelphij	len = sizeof(sk_type);
3342236167Sdelphij	if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type, &len) < 0) {
3343236167Sdelphij		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3344236167Sdelphij		*status = PCAP_ERROR;
3345236167Sdelphij		return -1;
3346236167Sdelphij	}
3347236167Sdelphij#ifdef PACKET_RESERVE
3348236167Sdelphij	len = sizeof(tp_reserve);
3349236167Sdelphij	if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &tp_reserve, &len) < 0) {
3350236167Sdelphij		if (errno != ENOPROTOOPT) {
3351236167Sdelphij			/*
3352236167Sdelphij			 * ENOPROTOOPT means "kernel doesn't support
3353236167Sdelphij			 * PACKET_RESERVE", in which case we fall back
3354236167Sdelphij			 * as best we can.
3355236167Sdelphij			 */
3356236167Sdelphij			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3357236167Sdelphij			*status = PCAP_ERROR;
3358236167Sdelphij			return -1;
3359236167Sdelphij		}
3360236167Sdelphij		tp_reserve = 0;	/* older kernel, reserve not supported */
3361236167Sdelphij	}
3362236167Sdelphij#else
3363236167Sdelphij	tp_reserve = 0;	/* older kernel, reserve not supported */
3364236167Sdelphij#endif
3365236167Sdelphij	maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
3366236167Sdelphij		/* XXX: in the kernel maclen is calculated from
3367236167Sdelphij		 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3368236167Sdelphij		 * in:  packet_snd()           in linux-2.6/net/packet/af_packet.c
3369236167Sdelphij		 * then packet_alloc_skb()     in linux-2.6/net/packet/af_packet.c
3370236167Sdelphij		 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3371236167Sdelphij		 * but I see no way to get those sizes in userspace,
3372236167Sdelphij		 * like for instance with an ifreq ioctl();
3373236167Sdelphij		 * the best thing I've found so far is MAX_HEADER in the kernel
3374236167Sdelphij		 * part of linux-2.6/include/linux/netdevice.h
3375236167Sdelphij		 * which goes up to 128+48=176; since pcap-linux.c defines
3376236167Sdelphij		 * a MAX_LINKHEADER_SIZE of 256 which is greater than that,
3377236167Sdelphij		 * let's use it.. maybe is it even large enough to directly
3378236167Sdelphij		 * replace macoff..
3379236167Sdelphij		 */
3380236167Sdelphij	tp_hdrlen = TPACKET_ALIGN(handle->md.tp_hdrlen) + sizeof(struct sockaddr_ll) ;
3381236167Sdelphij	netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
3382236167Sdelphij		/* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN of
3383236167Sdelphij		 * netoff, which contradicts
3384236167Sdelphij		 * linux-2.6/Documentation/networking/packet_mmap.txt
3385236167Sdelphij		 * documenting that:
3386236167Sdelphij		 * "- Gap, chosen so that packet data (Start+tp_net)
3387236167Sdelphij		 * aligns to TPACKET_ALIGNMENT=16"
3388236167Sdelphij		 */
3389236167Sdelphij		/* NOTE: in linux-2.6/include/linux/skbuff.h:
3390236167Sdelphij		 * "CPUs often take a performance hit
3391236167Sdelphij		 *  when accessing unaligned memory locations"
3392236167Sdelphij		 */
3393236167Sdelphij	macoff = netoff - maclen;
3394236167Sdelphij	req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
3395190225Srpaulo	req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
3396214518Srpaulo
3397214518Srpaulo	/* compute the minumum block size that will handle this frame.
3398214518Srpaulo	 * The block has to be page size aligned.
3399214518Srpaulo	 * The max block size allowed by the kernel is arch-dependent and
3400214518Srpaulo	 * it's not explicitly checked here. */
3401214518Srpaulo	req.tp_block_size = getpagesize();
3402214518Srpaulo	while (req.tp_block_size < req.tp_frame_size)
3403214518Srpaulo		req.tp_block_size <<= 1;
3404214518Srpaulo
3405214518Srpaulo	frames_per_block = req.tp_block_size/req.tp_frame_size;
3406214518Srpaulo
3407236167Sdelphij	/*
3408236167Sdelphij	 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3409236167Sdelphij	 * so we check for PACKET_TIMESTAMP.  We check for
3410236167Sdelphij	 * linux/net_tstamp.h just in case a system somehow has
3411236167Sdelphij	 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3412236167Sdelphij	 * be unnecessary.
3413236167Sdelphij	 *
3414236167Sdelphij	 * SIOCSHWTSTAMP was introduced in the patch that introduced
3415236167Sdelphij	 * linux/net_tstamp.h, so we don't bother checking whether
3416236167Sdelphij	 * SIOCSHWTSTAMP is defined (if your Linux system has
3417236167Sdelphij	 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3418236167Sdelphij	 * Linux system is badly broken).
3419236167Sdelphij	 */
3420236167Sdelphij#if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3421236167Sdelphij	/*
3422236167Sdelphij	 * If we were told to do so, ask the kernel and the driver
3423236167Sdelphij	 * to use hardware timestamps.
3424236167Sdelphij	 *
3425236167Sdelphij	 * Hardware timestamps are only supported with mmapped
3426236167Sdelphij	 * captures.
3427236167Sdelphij	 */
3428236167Sdelphij	if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
3429236167Sdelphij	    handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
3430236167Sdelphij		struct hwtstamp_config hwconfig;
3431236167Sdelphij		struct ifreq ifr;
3432236167Sdelphij		int timesource;
3433236167Sdelphij
3434236167Sdelphij		/*
3435236167Sdelphij		 * Ask for hardware time stamps on all packets,
3436236167Sdelphij		 * including transmitted packets.
3437236167Sdelphij		 */
3438236167Sdelphij		memset(&hwconfig, 0, sizeof(hwconfig));
3439236167Sdelphij		hwconfig.tx_type = HWTSTAMP_TX_ON;
3440236167Sdelphij		hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
3441236167Sdelphij
3442236167Sdelphij		memset(&ifr, 0, sizeof(ifr));
3443236167Sdelphij		strcpy(ifr.ifr_name, handle->opt.source);
3444236167Sdelphij		ifr.ifr_data = (void *)&hwconfig;
3445236167Sdelphij
3446236167Sdelphij		if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
3447236167Sdelphij			switch (errno) {
3448236167Sdelphij
3449236167Sdelphij			case EPERM:
3450236167Sdelphij				/*
3451236167Sdelphij				 * Treat this as an error, as the
3452236167Sdelphij				 * user should try to run this
3453236167Sdelphij				 * with the appropriate privileges -
3454236167Sdelphij				 * and, if they can't, shouldn't
3455236167Sdelphij				 * try requesting hardware time stamps.
3456236167Sdelphij				 */
3457236167Sdelphij				*status = PCAP_ERROR_PERM_DENIED;
3458236167Sdelphij				return -1;
3459236167Sdelphij
3460236167Sdelphij			case EOPNOTSUPP:
3461236167Sdelphij				/*
3462236167Sdelphij				 * Treat this as a warning, as the
3463236167Sdelphij				 * only way to fix the warning is to
3464236167Sdelphij				 * get an adapter that supports hardware
3465236167Sdelphij				 * time stamps.  We'll just fall back
3466236167Sdelphij				 * on the standard host time stamps.
3467236167Sdelphij				 */
3468236167Sdelphij				*status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
3469236167Sdelphij				break;
3470236167Sdelphij
3471236167Sdelphij			default:
3472236167Sdelphij				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3473236167Sdelphij					"SIOCSHWTSTAMP failed: %s",
3474236167Sdelphij					pcap_strerror(errno));
3475236167Sdelphij				*status = PCAP_ERROR;
3476236167Sdelphij				return -1;
3477236167Sdelphij			}
3478236167Sdelphij		} else {
3479236167Sdelphij			/*
3480236167Sdelphij			 * Well, that worked.  Now specify the type of
3481236167Sdelphij			 * hardware time stamp we want for this
3482236167Sdelphij			 * socket.
3483236167Sdelphij			 */
3484236167Sdelphij			if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
3485236167Sdelphij				/*
3486236167Sdelphij				 * Hardware timestamp, synchronized
3487236167Sdelphij				 * with the system clock.
3488236167Sdelphij				 */
3489236167Sdelphij				timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
3490236167Sdelphij			} else {
3491236167Sdelphij				/*
3492236167Sdelphij				 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3493236167Sdelphij				 * timestamp, not synchronized with the
3494236167Sdelphij				 * system clock.
3495236167Sdelphij				 */
3496236167Sdelphij				timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
3497236167Sdelphij			}
3498236167Sdelphij			if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
3499236167Sdelphij				(void *)&timesource, sizeof(timesource))) {
3500236167Sdelphij				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3501236167Sdelphij					"can't set PACKET_TIMESTAMP: %s",
3502236167Sdelphij					pcap_strerror(errno));
3503236167Sdelphij				*status = PCAP_ERROR;
3504236167Sdelphij				return -1;
3505236167Sdelphij			}
3506236167Sdelphij		}
3507236167Sdelphij	}
3508236167Sdelphij#endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3509236167Sdelphij
3510214518Srpaulo	/* ask the kernel to create the ring */
3511214518Srpauloretry:
3512190225Srpaulo	req.tp_block_nr = req.tp_frame_nr / frames_per_block;
3513190225Srpaulo
3514190225Srpaulo	/* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3515190225Srpaulo	req.tp_frame_nr = req.tp_block_nr * frames_per_block;
3516214518Srpaulo
3517190225Srpaulo	if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3518190225Srpaulo					(void *) &req, sizeof(req))) {
3519190225Srpaulo		if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
3520214518Srpaulo			/*
3521214518Srpaulo			 * Memory failure; try to reduce the requested ring
3522214518Srpaulo			 * size.
3523214518Srpaulo			 *
3524214518Srpaulo			 * We used to reduce this by half -- do 5% instead.
3525214518Srpaulo			 * That may result in more iterations and a longer
3526214518Srpaulo			 * startup, but the user will be much happier with
3527214518Srpaulo			 * the resulting buffer size.
3528214518Srpaulo			 */
3529214518Srpaulo			if (req.tp_frame_nr < 20)
3530214518Srpaulo				req.tp_frame_nr -= 1;
3531214518Srpaulo			else
3532214518Srpaulo				req.tp_frame_nr -= req.tp_frame_nr/20;
3533190225Srpaulo			goto retry;
3534190225Srpaulo		}
3535214518Srpaulo		if (errno == ENOPROTOOPT) {
3536214518Srpaulo			/*
3537214518Srpaulo			 * We don't have ring buffer support in this kernel.
3538214518Srpaulo			 */
3539214518Srpaulo			return 0;
3540214518Srpaulo		}
3541214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3542214518Srpaulo		    "can't create rx ring on packet socket: %s",
3543214518Srpaulo		    pcap_strerror(errno));
3544236167Sdelphij		*status = PCAP_ERROR;
3545214518Srpaulo		return -1;
3546190225Srpaulo	}
3547190225Srpaulo
3548190225Srpaulo	/* memory map the rx ring */
3549214518Srpaulo	handle->md.mmapbuflen = req.tp_block_nr * req.tp_block_size;
3550214518Srpaulo	handle->md.mmapbuf = mmap(0, handle->md.mmapbuflen,
3551214518Srpaulo	    PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
3552214518Srpaulo	if (handle->md.mmapbuf == MAP_FAILED) {
3553214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3554214518Srpaulo		    "can't mmap rx ring: %s", pcap_strerror(errno));
3555190225Srpaulo
3556190225Srpaulo		/* clear the allocated ring on error*/
3557190225Srpaulo		destroy_ring(handle);
3558236167Sdelphij		*status = PCAP_ERROR;
3559214518Srpaulo		return -1;
3560190225Srpaulo	}
3561190225Srpaulo
3562190225Srpaulo	/* allocate a ring for each frame header pointer*/
3563190225Srpaulo	handle->cc = req.tp_frame_nr;
3564190225Srpaulo	handle->buffer = malloc(handle->cc * sizeof(union thdr *));
3565190225Srpaulo	if (!handle->buffer) {
3566214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3567214518Srpaulo		    "can't allocate ring of frame headers: %s",
3568214518Srpaulo		    pcap_strerror(errno));
3569214518Srpaulo
3570190225Srpaulo		destroy_ring(handle);
3571236167Sdelphij		*status = PCAP_ERROR;
3572214518Srpaulo		return -1;
3573190225Srpaulo	}
3574190225Srpaulo
3575190225Srpaulo	/* fill the header ring with proper frame ptr*/
3576190225Srpaulo	handle->offset = 0;
3577190225Srpaulo	for (i=0; i<req.tp_block_nr; ++i) {
3578214518Srpaulo		void *base = &handle->md.mmapbuf[i*req.tp_block_size];
3579190225Srpaulo		for (j=0; j<frames_per_block; ++j, ++handle->offset) {
3580190225Srpaulo			RING_GET_FRAME(handle) = base;
3581190225Srpaulo			base += req.tp_frame_size;
3582190225Srpaulo		}
3583190225Srpaulo	}
3584190225Srpaulo
3585190225Srpaulo	handle->bufsize = req.tp_frame_size;
3586190225Srpaulo	handle->offset = 0;
3587190225Srpaulo	return 1;
3588190225Srpaulo}
3589190225Srpaulo
3590190225Srpaulo/* free all ring related resources*/
3591190225Srpaulostatic void
3592190225Srpaulodestroy_ring(pcap_t *handle)
3593190225Srpaulo{
3594190225Srpaulo	/* tell the kernel to destroy the ring*/
3595190225Srpaulo	struct tpacket_req req;
3596190225Srpaulo	memset(&req, 0, sizeof(req));
3597190225Srpaulo	setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3598190225Srpaulo				(void *) &req, sizeof(req));
3599190225Srpaulo
3600190225Srpaulo	/* if ring is mapped, unmap it*/
3601214518Srpaulo	if (handle->md.mmapbuf) {
3602214518Srpaulo		/* do not test for mmap failure, as we can't recover from any error */
3603214518Srpaulo		munmap(handle->md.mmapbuf, handle->md.mmapbuflen);
3604214518Srpaulo		handle->md.mmapbuf = NULL;
3605190225Srpaulo	}
3606190225Srpaulo}
3607190225Srpaulo
3608214518Srpaulo/*
3609214518Srpaulo * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3610214518Srpaulo * for Linux mmapped capture.
3611214518Srpaulo *
3612214518Srpaulo * The problem is that pcap_next() and pcap_next_ex() expect the packet
3613214518Srpaulo * data handed to the callback to be valid after the callback returns,
3614214518Srpaulo * but pcap_read_linux_mmap() has to release that packet as soon as
3615214518Srpaulo * the callback returns (otherwise, the kernel thinks there's still
3616214518Srpaulo * at least one unprocessed packet available in the ring, so a select()
3617214518Srpaulo * will immediately return indicating that there's data to process), so,
3618214518Srpaulo * in the callback, we have to make a copy of the packet.
3619214518Srpaulo *
3620214518Srpaulo * Yes, this means that, if the capture is using the ring buffer, using
3621214518Srpaulo * pcap_next() or pcap_next_ex() requires more copies than using
3622214518Srpaulo * pcap_loop() or pcap_dispatch().  If that bothers you, don't use
3623214518Srpaulo * pcap_next() or pcap_next_ex().
3624214518Srpaulo */
3625190225Srpaulostatic void
3626214518Srpaulopcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
3627214518Srpaulo    const u_char *bytes)
3628214518Srpaulo{
3629214518Srpaulo	struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
3630214518Srpaulo
3631214518Srpaulo	*sp->hdr = *h;
3632214518Srpaulo	memcpy(sp->pd->md.oneshot_buffer, bytes, h->caplen);
3633214518Srpaulo	*sp->pkt = sp->pd->md.oneshot_buffer;
3634214518Srpaulo}
3635214518Srpaulo
3636214518Srpaulostatic void
3637190225Srpaulopcap_cleanup_linux_mmap( pcap_t *handle )
3638190225Srpaulo{
3639190225Srpaulo	destroy_ring(handle);
3640214518Srpaulo	if (handle->md.oneshot_buffer != NULL) {
3641214518Srpaulo		free(handle->md.oneshot_buffer);
3642214518Srpaulo		handle->md.oneshot_buffer = NULL;
3643214518Srpaulo	}
3644190225Srpaulo	pcap_cleanup_linux(handle);
3645190225Srpaulo}
3646190225Srpaulo
3647190225Srpaulo
3648190225Srpaulostatic int
3649190225Srpaulopcap_getnonblock_mmap(pcap_t *p, char *errbuf)
3650190225Srpaulo{
3651190225Srpaulo	/* use negative value of timeout to indicate non blocking ops */
3652190225Srpaulo	return (p->md.timeout<0);
3653190225Srpaulo}
3654190225Srpaulo
3655190225Srpaulostatic int
3656190225Srpaulopcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
3657190225Srpaulo{
3658252281Sdelphij	/*
3659252281Sdelphij	 * Map each value to their corresponding negation to
3660252281Sdelphij	 * preserve the timeout value provided with pcap_set_timeout.
3661252281Sdelphij	 */
3662190225Srpaulo	if (nonblock) {
3663214518Srpaulo		if (p->md.timeout >= 0) {
3664214518Srpaulo			/*
3665252281Sdelphij			 * Indicate that we're switching to
3666252281Sdelphij			 * non-blocking mode.
3667214518Srpaulo			 */
3668252281Sdelphij			p->md.timeout = ~p->md.timeout;
3669214518Srpaulo		}
3670214518Srpaulo	} else {
3671214518Srpaulo		if (p->md.timeout < 0) {
3672252281Sdelphij			p->md.timeout = ~p->md.timeout;
3673214518Srpaulo		}
3674214518Srpaulo	}
3675190225Srpaulo	return 0;
3676190225Srpaulo}
3677190225Srpaulo
3678190225Srpaulostatic inline union thdr *
3679190225Srpaulopcap_get_ring_frame(pcap_t *handle, int status)
3680190225Srpaulo{
3681190225Srpaulo	union thdr h;
3682190225Srpaulo
3683190225Srpaulo	h.raw = RING_GET_FRAME(handle);
3684190225Srpaulo	switch (handle->md.tp_version) {
3685190225Srpaulo	case TPACKET_V1:
3686190225Srpaulo		if (status != (h.h1->tp_status ? TP_STATUS_USER :
3687190225Srpaulo						TP_STATUS_KERNEL))
3688190225Srpaulo			return NULL;
3689190225Srpaulo		break;
3690190225Srpaulo#ifdef HAVE_TPACKET2
3691190225Srpaulo	case TPACKET_V2:
3692190225Srpaulo		if (status != (h.h2->tp_status ? TP_STATUS_USER :
3693190225Srpaulo						TP_STATUS_KERNEL))
3694190225Srpaulo			return NULL;
3695190225Srpaulo		break;
3696190225Srpaulo#endif
3697190225Srpaulo	}
3698190225Srpaulo	return h.raw;
3699190225Srpaulo}
3700190225Srpaulo
3701214518Srpaulo#ifndef POLLRDHUP
3702214518Srpaulo#define POLLRDHUP 0
3703214518Srpaulo#endif
3704214518Srpaulo
3705190225Srpaulostatic int
3706190225Srpaulopcap_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback,
3707190225Srpaulo		u_char *user)
3708190225Srpaulo{
3709214518Srpaulo	int timeout;
3710190225Srpaulo	int pkts = 0;
3711214518Srpaulo	char c;
3712190225Srpaulo
3713190225Srpaulo	/* wait for frames availability.*/
3714214518Srpaulo	if (!pcap_get_ring_frame(handle, TP_STATUS_USER)) {
3715190225Srpaulo		struct pollfd pollinfo;
3716190225Srpaulo		int ret;
3717190225Srpaulo
3718190225Srpaulo		pollinfo.fd = handle->fd;
3719190225Srpaulo		pollinfo.events = POLLIN;
3720190225Srpaulo
3721214518Srpaulo		if (handle->md.timeout == 0)
3722214518Srpaulo			timeout = -1;	/* block forever */
3723214518Srpaulo		else if (handle->md.timeout > 0)
3724214518Srpaulo			timeout = handle->md.timeout;	/* block for that amount of time */
3725214518Srpaulo		else
3726214518Srpaulo			timeout = 0;	/* non-blocking mode - poll to pick up errors */
3727190225Srpaulo		do {
3728214518Srpaulo			ret = poll(&pollinfo, 1, timeout);
3729214518Srpaulo			if (ret < 0 && errno != EINTR) {
3730190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3731214518Srpaulo					"can't poll on packet socket: %s",
3732214518Srpaulo					pcap_strerror(errno));
3733214518Srpaulo				return PCAP_ERROR;
3734214518Srpaulo			} else if (ret > 0 &&
3735214518Srpaulo			    (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
3736214518Srpaulo				/*
3737214518Srpaulo				 * There's some indication other than
3738214518Srpaulo				 * "you can read on this descriptor" on
3739214518Srpaulo				 * the descriptor.
3740214518Srpaulo				 */
3741214518Srpaulo				if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
3742214518Srpaulo					snprintf(handle->errbuf,
3743214518Srpaulo						PCAP_ERRBUF_SIZE,
3744214518Srpaulo						"Hangup on packet socket");
3745214518Srpaulo					return PCAP_ERROR;
3746214518Srpaulo				}
3747214518Srpaulo				if (pollinfo.revents & POLLERR) {
3748214518Srpaulo					/*
3749214518Srpaulo					 * A recv() will give us the
3750214518Srpaulo					 * actual error code.
3751214518Srpaulo					 *
3752214518Srpaulo					 * XXX - make the socket non-blocking?
3753214518Srpaulo					 */
3754214518Srpaulo					if (recv(handle->fd, &c, sizeof c,
3755214518Srpaulo					    MSG_PEEK) != -1)
3756214518Srpaulo						continue;	/* what, no error? */
3757214518Srpaulo					if (errno == ENETDOWN) {
3758214518Srpaulo						/*
3759214518Srpaulo						 * The device on which we're
3760214518Srpaulo						 * capturing went away.
3761214518Srpaulo						 *
3762214518Srpaulo						 * XXX - we should really return
3763214518Srpaulo						 * PCAP_ERROR_IFACE_NOT_UP,
3764214518Srpaulo						 * but pcap_dispatch() etc.
3765214518Srpaulo						 * aren't defined to return
3766214518Srpaulo						 * that.
3767214518Srpaulo						 */
3768214518Srpaulo						snprintf(handle->errbuf,
3769214518Srpaulo							PCAP_ERRBUF_SIZE,
3770214518Srpaulo							"The interface went down");
3771214518Srpaulo					} else {
3772214518Srpaulo						snprintf(handle->errbuf,
3773214518Srpaulo							PCAP_ERRBUF_SIZE,
3774214518Srpaulo							"Error condition on packet socket: %s",
3775214518Srpaulo							strerror(errno));
3776214518Srpaulo					}
3777214518Srpaulo					return PCAP_ERROR;
3778214518Srpaulo				}
3779214518Srpaulo				if (pollinfo.revents & POLLNVAL) {
3780214518Srpaulo					snprintf(handle->errbuf,
3781214518Srpaulo						PCAP_ERRBUF_SIZE,
3782214518Srpaulo						"Invalid polling request on packet socket");
3783214518Srpaulo					return PCAP_ERROR;
3784214518Srpaulo				}
3785214518Srpaulo  			}
3786190225Srpaulo			/* check for break loop condition on interrupted syscall*/
3787190225Srpaulo			if (handle->break_loop) {
3788190225Srpaulo				handle->break_loop = 0;
3789214518Srpaulo				return PCAP_ERROR_BREAK;
3790190225Srpaulo			}
3791190225Srpaulo		} while (ret < 0);
3792190225Srpaulo	}
3793190225Srpaulo
3794190225Srpaulo	/* non-positive values of max_packets are used to require all
3795190225Srpaulo	 * packets currently available in the ring */
3796190225Srpaulo	while ((pkts < max_packets) || (max_packets <= 0)) {
3797190225Srpaulo		int run_bpf;
3798190225Srpaulo		struct sockaddr_ll *sll;
3799190225Srpaulo		struct pcap_pkthdr pcaphdr;
3800190225Srpaulo		unsigned char *bp;
3801190225Srpaulo		union thdr h;
3802190225Srpaulo		unsigned int tp_len;
3803190225Srpaulo		unsigned int tp_mac;
3804190225Srpaulo		unsigned int tp_snaplen;
3805190225Srpaulo		unsigned int tp_sec;
3806190225Srpaulo		unsigned int tp_usec;
3807190225Srpaulo
3808190225Srpaulo		h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
3809190225Srpaulo		if (!h.raw)
3810190225Srpaulo			break;
3811190225Srpaulo
3812190225Srpaulo		switch (handle->md.tp_version) {
3813190225Srpaulo		case TPACKET_V1:
3814190225Srpaulo			tp_len	   = h.h1->tp_len;
3815190225Srpaulo			tp_mac	   = h.h1->tp_mac;
3816190225Srpaulo			tp_snaplen = h.h1->tp_snaplen;
3817190225Srpaulo			tp_sec	   = h.h1->tp_sec;
3818190225Srpaulo			tp_usec	   = h.h1->tp_usec;
3819190225Srpaulo			break;
3820190225Srpaulo#ifdef HAVE_TPACKET2
3821190225Srpaulo		case TPACKET_V2:
3822190225Srpaulo			tp_len	   = h.h2->tp_len;
3823190225Srpaulo			tp_mac	   = h.h2->tp_mac;
3824190225Srpaulo			tp_snaplen = h.h2->tp_snaplen;
3825190225Srpaulo			tp_sec	   = h.h2->tp_sec;
3826190225Srpaulo			tp_usec	   = h.h2->tp_nsec / 1000;
3827190225Srpaulo			break;
3828190225Srpaulo#endif
3829190225Srpaulo		default:
3830190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3831190225Srpaulo				"unsupported tpacket version %d",
3832190225Srpaulo				handle->md.tp_version);
3833190225Srpaulo			return -1;
3834190225Srpaulo		}
3835190225Srpaulo		/* perform sanity check on internal offset. */
3836190225Srpaulo		if (tp_mac + tp_snaplen > handle->bufsize) {
3837190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3838190225Srpaulo				"corrupted frame on kernel ring mac "
3839190225Srpaulo				"offset %d + caplen %d > frame len %d",
3840190225Srpaulo				tp_mac, tp_snaplen, handle->bufsize);
3841190225Srpaulo			return -1;
3842190225Srpaulo		}
3843190225Srpaulo
3844190225Srpaulo		/* run filter on received packet
3845190225Srpaulo		 * If the kernel filtering is enabled we need to run the
3846190225Srpaulo		 * filter until all the frames present into the ring
3847190225Srpaulo		 * at filter creation time are processed.
3848190225Srpaulo		 * In such case md.use_bpf is used as a counter for the
3849190225Srpaulo		 * packet we need to filter.
3850190225Srpaulo		 * Note: alternatively it could be possible to stop applying
3851190225Srpaulo		 * the filter when the ring became empty, but it can possibly
3852190225Srpaulo		 * happen a lot later... */
3853190225Srpaulo		bp = (unsigned char*)h.raw + tp_mac;
3854190225Srpaulo		run_bpf = (!handle->md.use_bpf) ||
3855190225Srpaulo			((handle->md.use_bpf>1) && handle->md.use_bpf--);
3856190225Srpaulo		if (run_bpf && handle->fcode.bf_insns &&
3857190225Srpaulo				(bpf_filter(handle->fcode.bf_insns, bp,
3858190225Srpaulo					tp_len, tp_snaplen) == 0))
3859190225Srpaulo			goto skip;
3860190225Srpaulo
3861214518Srpaulo		/*
3862214518Srpaulo		 * Do checks based on packet direction.
3863214518Srpaulo		 */
3864190225Srpaulo		sll = (void *)h.raw + TPACKET_ALIGN(handle->md.tp_hdrlen);
3865214518Srpaulo		if (sll->sll_pkttype == PACKET_OUTGOING) {
3866214518Srpaulo			/*
3867214518Srpaulo			 * Outgoing packet.
3868214518Srpaulo			 * If this is from the loopback device, reject it;
3869214518Srpaulo			 * we'll see the packet as an incoming packet as well,
3870214518Srpaulo			 * and we don't want to see it twice.
3871214518Srpaulo			 */
3872214518Srpaulo			if (sll->sll_ifindex == handle->md.lo_ifindex)
3873214518Srpaulo				goto skip;
3874190225Srpaulo
3875214518Srpaulo			/*
3876214518Srpaulo			 * If the user only wants incoming packets, reject it.
3877214518Srpaulo			 */
3878214518Srpaulo			if (handle->direction == PCAP_D_IN)
3879214518Srpaulo				goto skip;
3880214518Srpaulo		} else {
3881214518Srpaulo			/*
3882214518Srpaulo			 * Incoming packet.
3883214518Srpaulo			 * If the user only wants outgoing packets, reject it.
3884214518Srpaulo			 */
3885214518Srpaulo			if (handle->direction == PCAP_D_OUT)
3886214518Srpaulo				goto skip;
3887214518Srpaulo		}
3888214518Srpaulo
3889190225Srpaulo		/* get required packet info from ring header */
3890190225Srpaulo		pcaphdr.ts.tv_sec = tp_sec;
3891190225Srpaulo		pcaphdr.ts.tv_usec = tp_usec;
3892190225Srpaulo		pcaphdr.caplen = tp_snaplen;
3893190225Srpaulo		pcaphdr.len = tp_len;
3894190225Srpaulo
3895190225Srpaulo		/* if required build in place the sll header*/
3896190225Srpaulo		if (handle->md.cooked) {
3897190225Srpaulo			struct sll_header *hdrp;
3898190225Srpaulo
3899190225Srpaulo			/*
3900190225Srpaulo			 * The kernel should have left us with enough
3901190225Srpaulo			 * space for an sll header; back up the packet
3902190225Srpaulo			 * data pointer into that space, as that'll be
3903190225Srpaulo			 * the beginning of the packet we pass to the
3904190225Srpaulo			 * callback.
3905190225Srpaulo			 */
3906190225Srpaulo			bp -= SLL_HDR_LEN;
3907190225Srpaulo
3908190225Srpaulo			/*
3909190225Srpaulo			 * Let's make sure that's past the end of
3910190225Srpaulo			 * the tpacket header, i.e. >=
3911190225Srpaulo			 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3912190225Srpaulo			 * don't step on the header when we construct
3913190225Srpaulo			 * the sll header.
3914190225Srpaulo			 */
3915190225Srpaulo			if (bp < (u_char *)h.raw +
3916190225Srpaulo					   TPACKET_ALIGN(handle->md.tp_hdrlen) +
3917190225Srpaulo					   sizeof(struct sockaddr_ll)) {
3918190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3919190225Srpaulo					"cooked-mode frame doesn't have room for sll header");
3920190225Srpaulo				return -1;
3921190225Srpaulo			}
3922190225Srpaulo
3923190225Srpaulo			/*
3924190225Srpaulo			 * OK, that worked; construct the sll header.
3925190225Srpaulo			 */
3926190225Srpaulo			hdrp = (struct sll_header *)bp;
3927190225Srpaulo			hdrp->sll_pkttype = map_packet_type_to_sll_type(
3928190225Srpaulo							sll->sll_pkttype);
3929190225Srpaulo			hdrp->sll_hatype = htons(sll->sll_hatype);
3930190225Srpaulo			hdrp->sll_halen = htons(sll->sll_halen);
3931190225Srpaulo			memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
3932190225Srpaulo			hdrp->sll_protocol = sll->sll_protocol;
3933190225Srpaulo
3934190225Srpaulo			/* update packet len */
3935190225Srpaulo			pcaphdr.caplen += SLL_HDR_LEN;
3936190225Srpaulo			pcaphdr.len += SLL_HDR_LEN;
3937190225Srpaulo		}
3938190225Srpaulo
3939190225Srpaulo#ifdef HAVE_TPACKET2
3940252281Sdelphij		if ((handle->md.tp_version == TPACKET_V2) &&
3941252281Sdelphij#if defined(TP_STATUS_VLAN_VALID)
3942252281Sdelphij		(h.h2->tp_vlan_tci || (h.h2->tp_status & TP_STATUS_VLAN_VALID)) &&
3943252281Sdelphij#else
3944252281Sdelphij		h.h2->tp_vlan_tci &&
3945252281Sdelphij#endif
3946252281Sdelphij		    handle->md.vlan_offset != -1 &&
3947252281Sdelphij		    tp_snaplen >= (unsigned int) handle->md.vlan_offset) {
3948190225Srpaulo			struct vlan_tag *tag;
3949190225Srpaulo
3950190225Srpaulo			bp -= VLAN_TAG_LEN;
3951252281Sdelphij			memmove(bp, bp + VLAN_TAG_LEN, handle->md.vlan_offset);
3952190225Srpaulo
3953252281Sdelphij			tag = (struct vlan_tag *)(bp + handle->md.vlan_offset);
3954190225Srpaulo			tag->vlan_tpid = htons(ETH_P_8021Q);
3955190225Srpaulo			tag->vlan_tci = htons(h.h2->tp_vlan_tci);
3956190225Srpaulo
3957190225Srpaulo			pcaphdr.caplen += VLAN_TAG_LEN;
3958190225Srpaulo			pcaphdr.len += VLAN_TAG_LEN;
3959190225Srpaulo		}
3960190225Srpaulo#endif
3961190225Srpaulo
3962214518Srpaulo		/*
3963214518Srpaulo		 * The only way to tell the kernel to cut off the
3964214518Srpaulo		 * packet at a snapshot length is with a filter program;
3965214518Srpaulo		 * if there's no filter program, the kernel won't cut
3966214518Srpaulo		 * the packet off.
3967214518Srpaulo		 *
3968214518Srpaulo		 * Trim the snapshot length to be no longer than the
3969214518Srpaulo		 * specified snapshot length.
3970214518Srpaulo		 */
3971214518Srpaulo		if (pcaphdr.caplen > handle->snapshot)
3972214518Srpaulo			pcaphdr.caplen = handle->snapshot;
3973214518Srpaulo
3974190225Srpaulo		/* pass the packet to the user */
3975190225Srpaulo		pkts++;
3976190225Srpaulo		callback(user, &pcaphdr, bp);
3977190225Srpaulo		handle->md.packets_read++;
3978190225Srpaulo
3979190225Srpauloskip:
3980190225Srpaulo		/* next packet */
3981190225Srpaulo		switch (handle->md.tp_version) {
3982190225Srpaulo		case TPACKET_V1:
3983190225Srpaulo			h.h1->tp_status = TP_STATUS_KERNEL;
3984190225Srpaulo			break;
3985190225Srpaulo#ifdef HAVE_TPACKET2
3986190225Srpaulo		case TPACKET_V2:
3987190225Srpaulo			h.h2->tp_status = TP_STATUS_KERNEL;
3988190225Srpaulo			break;
3989190225Srpaulo#endif
3990190225Srpaulo		}
3991190225Srpaulo		if (++handle->offset >= handle->cc)
3992190225Srpaulo			handle->offset = 0;
3993190225Srpaulo
3994190225Srpaulo		/* check for break loop condition*/
3995190225Srpaulo		if (handle->break_loop) {
3996190225Srpaulo			handle->break_loop = 0;
3997214518Srpaulo			return PCAP_ERROR_BREAK;
3998190225Srpaulo		}
3999190225Srpaulo	}
4000190225Srpaulo	return pkts;
4001190225Srpaulo}
4002190225Srpaulo
4003190225Srpaulostatic int
4004190225Srpaulopcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
4005190225Srpaulo{
4006190225Srpaulo	int n, offset;
4007214518Srpaulo	int ret;
4008214518Srpaulo
4009214518Srpaulo	/*
4010214518Srpaulo	 * Don't rewrite "ret" instructions; we don't need to, as
4011214518Srpaulo	 * we're not reading packets with recvmsg(), and we don't
4012214518Srpaulo	 * want to, as, by not rewriting them, the kernel can avoid
4013214518Srpaulo	 * copying extra data.
4014214518Srpaulo	 */
4015214518Srpaulo	ret = pcap_setfilter_linux_common(handle, filter, 1);
4016190225Srpaulo	if (ret < 0)
4017190225Srpaulo		return ret;
4018190225Srpaulo
4019190225Srpaulo	/* if the kernel filter is enabled, we need to apply the filter on
4020190225Srpaulo	 * all packets present into the ring. Get an upper bound of their number
4021190225Srpaulo	 */
4022190225Srpaulo	if (!handle->md.use_bpf)
4023190225Srpaulo		return ret;
4024190225Srpaulo
4025190225Srpaulo	/* walk the ring backward and count the free slot */
4026190225Srpaulo	offset = handle->offset;
4027190225Srpaulo	if (--handle->offset < 0)
4028190225Srpaulo		handle->offset = handle->cc - 1;
4029190225Srpaulo	for (n=0; n < handle->cc; ++n) {
4030190225Srpaulo		if (--handle->offset < 0)
4031190225Srpaulo			handle->offset = handle->cc - 1;
4032190225Srpaulo		if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
4033190225Srpaulo			break;
4034190225Srpaulo	}
4035190225Srpaulo
4036190225Srpaulo	/* be careful to not change current ring position */
4037190225Srpaulo	handle->offset = offset;
4038190225Srpaulo
4039190225Srpaulo	/* store the number of packets currently present in the ring */
4040190225Srpaulo	handle->md.use_bpf = 1 + (handle->cc - n);
4041190225Srpaulo	return ret;
4042190225Srpaulo}
4043190225Srpaulo
4044190225Srpaulo#endif /* HAVE_PACKET_RING */
4045190225Srpaulo
4046190225Srpaulo
404775107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
404875107Sfenner/*
4049127664Sbms *  Return the index of the given device name. Fill ebuf and return
405075107Sfenner *  -1 on failure.
405175107Sfenner */
405275107Sfennerstatic int
405375107Sfenneriface_get_id(int fd, const char *device, char *ebuf)
405475107Sfenner{
405575107Sfenner	struct ifreq	ifr;
405626175Sfenner
405739291Sfenner	memset(&ifr, 0, sizeof(ifr));
405839291Sfenner	strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
405975107Sfenner
406075107Sfenner	if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
406175107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4062172677Smlaier			 "SIOCGIFINDEX: %s", pcap_strerror(errno));
406375107Sfenner		return -1;
406426175Sfenner	}
406526175Sfenner
406675107Sfenner	return ifr.ifr_ifindex;
406775107Sfenner}
406826175Sfenner
406975107Sfenner/*
4070127664Sbms *  Bind the socket associated with FD to the given device.
4071190225Srpaulo *  Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4072190225Srpaulo *  or a PCAP_ERROR_ value on a hard error.
407375107Sfenner */
407475107Sfennerstatic int
407575107Sfenneriface_bind(int fd, int ifindex, char *ebuf)
407675107Sfenner{
407775107Sfenner	struct sockaddr_ll	sll;
4078127664Sbms	int			err;
4079127664Sbms	socklen_t		errlen = sizeof(err);
408075107Sfenner
408175107Sfenner	memset(&sll, 0, sizeof(sll));
408275107Sfenner	sll.sll_family		= AF_PACKET;
408375107Sfenner	sll.sll_ifindex		= ifindex;
408475107Sfenner	sll.sll_protocol	= htons(ETH_P_ALL);
408575107Sfenner
408675107Sfenner	if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
4087190225Srpaulo		if (errno == ENETDOWN) {
4088190225Srpaulo			/*
4089190225Srpaulo			 * Return a "network down" indication, so that
4090190225Srpaulo			 * the application can report that rather than
4091190225Srpaulo			 * saying we had a mysterious failure and
4092190225Srpaulo			 * suggest that they report a problem to the
4093190225Srpaulo			 * libpcap developers.
4094190225Srpaulo			 */
4095190225Srpaulo			return PCAP_ERROR_IFACE_NOT_UP;
4096190225Srpaulo		} else {
4097190225Srpaulo			snprintf(ebuf, PCAP_ERRBUF_SIZE,
4098190225Srpaulo				 "bind: %s", pcap_strerror(errno));
4099190225Srpaulo			return PCAP_ERROR;
4100190225Srpaulo		}
410126175Sfenner	}
410226175Sfenner
4103127664Sbms	/* Any pending errors, e.g., network is down? */
4104127664Sbms
4105127664Sbms	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
4106127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4107127664Sbms			"getsockopt: %s", pcap_strerror(errno));
4108190225Srpaulo		return 0;
4109127664Sbms	}
4110127664Sbms
4111190225Srpaulo	if (err == ENETDOWN) {
4112190225Srpaulo		/*
4113190225Srpaulo		 * Return a "network down" indication, so that
4114190225Srpaulo		 * the application can report that rather than
4115190225Srpaulo		 * saying we had a mysterious failure and
4116190225Srpaulo		 * suggest that they report a problem to the
4117190225Srpaulo		 * libpcap developers.
4118190225Srpaulo		 */
4119190225Srpaulo		return PCAP_ERROR_IFACE_NOT_UP;
4120190225Srpaulo	} else if (err > 0) {
4121127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4122127664Sbms			"bind: %s", pcap_strerror(err));
4123190225Srpaulo		return 0;
4124127664Sbms	}
4125127664Sbms
4126190225Srpaulo	return 1;
412775107Sfenner}
412875107Sfenner
4129214518Srpaulo#ifdef IW_MODE_MONITOR
413075107Sfenner/*
4131190225Srpaulo * Check whether the device supports the Wireless Extensions.
4132190225Srpaulo * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4133190225Srpaulo * if the device doesn't even exist.
413475107Sfenner */
4135190225Srpaulostatic int
4136190225Srpaulohas_wext(int sock_fd, const char *device, char *ebuf)
4137190225Srpaulo{
4138190225Srpaulo	struct iwreq ireq;
413975107Sfenner
4140190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
4141190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
4142190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4143190225Srpaulo	if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
4144190225Srpaulo		return 1;	/* yes */
4145190225Srpaulo	snprintf(ebuf, PCAP_ERRBUF_SIZE,
4146190225Srpaulo	    "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
4147190225Srpaulo	if (errno == ENODEV)
4148190225Srpaulo		return PCAP_ERROR_NO_SUCH_DEVICE;
4149190225Srpaulo	return 0;
4150190225Srpaulo}
4151190225Srpaulo
415275107Sfenner/*
4153190225Srpaulo * Per me si va ne la citta dolente,
4154190225Srpaulo * Per me si va ne l'etterno dolore,
4155190225Srpaulo *	...
4156190225Srpaulo * Lasciate ogne speranza, voi ch'intrate.
4157190225Srpaulo *
4158190225Srpaulo * XXX - airmon-ng does special stuff with the Orinoco driver and the
4159190225Srpaulo * wlan-ng driver.
416075107Sfenner */
4161190225Srpaulotypedef enum {
4162190225Srpaulo	MONITOR_WEXT,
4163190225Srpaulo	MONITOR_HOSTAP,
4164190225Srpaulo	MONITOR_PRISM,
4165190225Srpaulo	MONITOR_PRISM54,
4166190225Srpaulo	MONITOR_ACX100,
4167190225Srpaulo	MONITOR_RT2500,
4168190225Srpaulo	MONITOR_RT2570,
4169190225Srpaulo	MONITOR_RT73,
4170190225Srpaulo	MONITOR_RTL8XXX
4171190225Srpaulo} monitor_type;
417275107Sfenner
417375107Sfenner/*
4174190225Srpaulo * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4175190225Srpaulo * on if it's not already on.
4176190225Srpaulo *
4177190225Srpaulo * Returns 1 on success, 0 if we don't support the Wireless Extensions
4178190225Srpaulo * on this device, or a PCAP_ERROR_ value if we do support them but
4179190225Srpaulo * we weren't able to turn monitor mode on.
418075107Sfenner */
4181190225Srpaulostatic int
4182190225Srpauloenter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
418375107Sfenner{
4184190225Srpaulo	/*
4185190225Srpaulo	 * XXX - at least some adapters require non-Wireless Extensions
4186190225Srpaulo	 * mechanisms to turn monitor mode on.
4187190225Srpaulo	 *
4188190225Srpaulo	 * Atheros cards might require that a separate "monitor virtual access
4189190225Srpaulo	 * point" be created, with later versions of the madwifi driver.
4190190225Srpaulo	 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4191190225Srpaulo	 * monitor -bssid", which apparently spits out a line "athN"
4192190225Srpaulo	 * where "athN" is the monitor mode device.  To leave monitor
4193190225Srpaulo	 * mode, it destroys the monitor mode device.
4194190225Srpaulo	 *
4195190225Srpaulo	 * Some Intel Centrino adapters might require private ioctls to get
4196190225Srpaulo	 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4197190225Srpaulo	 * configure a separate "rtapN" interface to capture in monitor
4198190225Srpaulo	 * mode without preventing the adapter from operating normally.
4199190225Srpaulo	 * (airmon-ng doesn't appear to use that, though.)
4200190225Srpaulo	 *
4201190225Srpaulo	 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4202190225Srpaulo	 * up, and if all drivers were converted to mac80211 drivers.
4203190225Srpaulo	 *
4204190225Srpaulo	 * If interface {if} is a mac80211 driver, the file
4205190225Srpaulo	 * /sys/class/net/{if}/phy80211 is a symlink to
4206190225Srpaulo	 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4207190225Srpaulo	 *
4208190225Srpaulo	 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4209190225Srpaulo	 * least, has a "wmaster0" device and a "wlan0" device; the
4210190225Srpaulo	 * latter is the one with the IP address.  Both show up in
4211190225Srpaulo	 * "tcpdump -D" output.  Capturing on the wmaster0 device
4212190225Srpaulo	 * captures with 802.11 headers.
4213190225Srpaulo	 *
4214190225Srpaulo	 * airmon-ng searches through /sys/class/net for devices named
4215190225Srpaulo	 * monN, starting with mon0; as soon as one *doesn't* exist,
4216190225Srpaulo	 * it chooses that as the monitor device name.  If the "iw"
4217190225Srpaulo	 * command exists, it does "iw dev {if} interface add {monif}
4218190225Srpaulo	 * type monitor", where {monif} is the monitor device.  It
4219190225Srpaulo	 * then (sigh) sleeps .1 second, and then configures the
4220190225Srpaulo	 * device up.  Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4221190225Srpaulo	 * is a file, it writes {mondev}, without a newline, to that file,
4222190225Srpaulo	 * and again (sigh) sleeps .1 second, and then iwconfig's that
4223190225Srpaulo	 * device into monitor mode and configures it up.  Otherwise,
4224190225Srpaulo	 * you can't do monitor mode.
4225190225Srpaulo	 *
4226190225Srpaulo	 * All these devices are "glued" together by having the
4227190225Srpaulo	 * /sys/class/net/{device}/phy80211 links pointing to the same
4228190225Srpaulo	 * place, so, given a wmaster, wlan, or mon device, you can
4229190225Srpaulo	 * find the other devices by looking for devices with
4230190225Srpaulo	 * the same phy80211 link.
4231190225Srpaulo	 *
4232190225Srpaulo	 * To turn monitor mode off, delete the monitor interface,
4233190225Srpaulo	 * either with "iw dev {monif} interface del" or by sending
4234190225Srpaulo	 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4235190225Srpaulo	 *
4236190225Srpaulo	 * Note: if you try to create a monitor device named "monN", and
4237190225Srpaulo	 * there's already a "monN" device, it fails, as least with
4238190225Srpaulo	 * the netlink interface (which is what iw uses), with a return
4239190225Srpaulo	 * value of -ENFILE.  (Return values are negative errnos.)  We
4240190225Srpaulo	 * could probably use that to find an unused device.
4241190225Srpaulo	 */
4242190225Srpaulo	int err;
4243190225Srpaulo	struct iwreq ireq;
4244190225Srpaulo	struct iw_priv_args *priv;
4245190225Srpaulo	monitor_type montype;
4246190225Srpaulo	int i;
4247190225Srpaulo	__u32 cmd;
4248236167Sdelphij	struct ifreq ifr;
4249236167Sdelphij	int oldflags;
4250190225Srpaulo	int args[2];
4251190225Srpaulo	int channel;
425275107Sfenner
4253190225Srpaulo	/*
4254190225Srpaulo	 * Does this device *support* the Wireless Extensions?
4255190225Srpaulo	 */
4256190225Srpaulo	err = has_wext(sock_fd, device, handle->errbuf);
4257190225Srpaulo	if (err <= 0)
4258190225Srpaulo		return err;	/* either it doesn't or the device doesn't even exist */
4259190225Srpaulo	/*
4260236167Sdelphij	 * Start out assuming we have no private extensions to control
4261236167Sdelphij	 * radio metadata.
4262236167Sdelphij	 */
4263236167Sdelphij	montype = MONITOR_WEXT;
4264236167Sdelphij	cmd = 0;
4265236167Sdelphij
4266236167Sdelphij	/*
4267190225Srpaulo	 * Try to get all the Wireless Extensions private ioctls
4268190225Srpaulo	 * supported by this device.
4269190225Srpaulo	 *
4270190225Srpaulo	 * First, get the size of the buffer we need, by supplying no
4271190225Srpaulo	 * buffer and a length of 0.  If the device supports private
4272190225Srpaulo	 * ioctls, it should return E2BIG, with ireq.u.data.length set
4273190225Srpaulo	 * to the length we need.  If it doesn't support them, it should
4274190225Srpaulo	 * return EOPNOTSUPP.
4275190225Srpaulo	 */
4276190225Srpaulo	memset(&ireq, 0, sizeof ireq);
4277190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
4278190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
4279190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4280214518Srpaulo	ireq.u.data.pointer = (void *)args;
4281190225Srpaulo	ireq.u.data.length = 0;
4282190225Srpaulo	ireq.u.data.flags = 0;
4283190225Srpaulo	if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
4284190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4285190225Srpaulo		    "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4286190225Srpaulo		    device);
4287190225Srpaulo		return PCAP_ERROR;
4288190225Srpaulo	}
4289236167Sdelphij	if (errno != EOPNOTSUPP) {
4290190225Srpaulo		/*
4291236167Sdelphij		 * OK, it's not as if there are no private ioctls.
4292190225Srpaulo		 */
4293236167Sdelphij		if (errno != E2BIG) {
4294190225Srpaulo			/*
4295236167Sdelphij			 * Failed.
4296190225Srpaulo			 */
4297236167Sdelphij			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4298236167Sdelphij			    "%s: SIOCGIWPRIV: %s", device,
4299236167Sdelphij			    pcap_strerror(errno));
4300236167Sdelphij			return PCAP_ERROR;
4301190225Srpaulo		}
4302236167Sdelphij
4303236167Sdelphij		/*
4304236167Sdelphij		 * OK, try to get the list of private ioctls.
4305236167Sdelphij		 */
4306236167Sdelphij		priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
4307236167Sdelphij		if (priv == NULL) {
4308236167Sdelphij			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4309236167Sdelphij			    "malloc: %s", pcap_strerror(errno));
4310236167Sdelphij			return PCAP_ERROR;
4311190225Srpaulo		}
4312236167Sdelphij		ireq.u.data.pointer = (void *)priv;
4313236167Sdelphij		if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
4314236167Sdelphij			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4315236167Sdelphij			    "%s: SIOCGIWPRIV: %s", device,
4316236167Sdelphij			    pcap_strerror(errno));
4317236167Sdelphij			free(priv);
4318236167Sdelphij			return PCAP_ERROR;
4319190225Srpaulo		}
4320236167Sdelphij
4321236167Sdelphij		/*
4322236167Sdelphij		 * Look for private ioctls to turn monitor mode on or, if
4323236167Sdelphij		 * monitor mode is on, to set the header type.
4324236167Sdelphij		 */
4325236167Sdelphij		for (i = 0; i < ireq.u.data.length; i++) {
4326236167Sdelphij			if (strcmp(priv[i].name, "monitor_type") == 0) {
4327236167Sdelphij				/*
4328236167Sdelphij				 * Hostap driver, use this one.
4329236167Sdelphij				 * Set monitor mode first.
4330236167Sdelphij				 * You can set it to 0 to get DLT_IEEE80211,
4331236167Sdelphij				 * 1 to get DLT_PRISM, 2 to get
4332236167Sdelphij				 * DLT_IEEE80211_RADIO_AVS, and, with more
4333236167Sdelphij				 * recent versions of the driver, 3 to get
4334236167Sdelphij				 * DLT_IEEE80211_RADIO.
4335236167Sdelphij				 */
4336236167Sdelphij				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4337236167Sdelphij					break;
4338236167Sdelphij				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4339236167Sdelphij					break;
4340236167Sdelphij				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4341236167Sdelphij					break;
4342236167Sdelphij				montype = MONITOR_HOSTAP;
4343236167Sdelphij				cmd = priv[i].cmd;
4344190225Srpaulo				break;
4345236167Sdelphij			}
4346236167Sdelphij			if (strcmp(priv[i].name, "set_prismhdr") == 0) {
4347236167Sdelphij				/*
4348236167Sdelphij				 * Prism54 driver, use this one.
4349236167Sdelphij				 * Set monitor mode first.
4350236167Sdelphij				 * You can set it to 2 to get DLT_IEEE80211
4351236167Sdelphij				 * or 3 or get DLT_PRISM.
4352236167Sdelphij				 */
4353236167Sdelphij				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4354236167Sdelphij					break;
4355236167Sdelphij				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4356236167Sdelphij					break;
4357236167Sdelphij				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4358236167Sdelphij					break;
4359236167Sdelphij				montype = MONITOR_PRISM54;
4360236167Sdelphij				cmd = priv[i].cmd;
4361190225Srpaulo				break;
4362236167Sdelphij			}
4363236167Sdelphij			if (strcmp(priv[i].name, "forceprismheader") == 0) {
4364236167Sdelphij				/*
4365236167Sdelphij				 * RT2570 driver, use this one.
4366236167Sdelphij				 * Do this after turning monitor mode on.
4367236167Sdelphij				 * You can set it to 1 to get DLT_PRISM or 2
4368236167Sdelphij				 * to get DLT_IEEE80211.
4369236167Sdelphij				 */
4370236167Sdelphij				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4371236167Sdelphij					break;
4372236167Sdelphij				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4373236167Sdelphij					break;
4374236167Sdelphij				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4375236167Sdelphij					break;
4376236167Sdelphij				montype = MONITOR_RT2570;
4377236167Sdelphij				cmd = priv[i].cmd;
4378190225Srpaulo				break;
4379236167Sdelphij			}
4380236167Sdelphij			if (strcmp(priv[i].name, "forceprism") == 0) {
4381236167Sdelphij				/*
4382236167Sdelphij				 * RT73 driver, use this one.
4383236167Sdelphij				 * Do this after turning monitor mode on.
4384236167Sdelphij				 * Its argument is a *string*; you can
4385236167Sdelphij				 * set it to "1" to get DLT_PRISM or "2"
4386236167Sdelphij				 * to get DLT_IEEE80211.
4387236167Sdelphij				 */
4388236167Sdelphij				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
4389236167Sdelphij					break;
4390236167Sdelphij				if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
4391236167Sdelphij					break;
4392236167Sdelphij				montype = MONITOR_RT73;
4393236167Sdelphij				cmd = priv[i].cmd;
4394190225Srpaulo				break;
4395236167Sdelphij			}
4396236167Sdelphij			if (strcmp(priv[i].name, "prismhdr") == 0) {
4397236167Sdelphij				/*
4398236167Sdelphij				 * One of the RTL8xxx drivers, use this one.
4399236167Sdelphij				 * It can only be done after monitor mode
4400236167Sdelphij				 * has been turned on.  You can set it to 1
4401236167Sdelphij				 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4402236167Sdelphij				 */
4403236167Sdelphij				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4404236167Sdelphij					break;
4405236167Sdelphij				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4406236167Sdelphij					break;
4407236167Sdelphij				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4408236167Sdelphij					break;
4409236167Sdelphij				montype = MONITOR_RTL8XXX;
4410190225Srpaulo				cmd = priv[i].cmd;
4411190225Srpaulo				break;
4412236167Sdelphij			}
4413236167Sdelphij			if (strcmp(priv[i].name, "rfmontx") == 0) {
4414236167Sdelphij				/*
4415236167Sdelphij				 * RT2500 or RT61 driver, use this one.
4416236167Sdelphij				 * It has one one-byte parameter; set
4417236167Sdelphij				 * u.data.length to 1 and u.data.pointer to
4418236167Sdelphij				 * point to the parameter.
4419236167Sdelphij				 * It doesn't itself turn monitor mode on.
4420236167Sdelphij				 * You can set it to 1 to allow transmitting
4421236167Sdelphij				 * in monitor mode(?) and get DLT_IEEE80211,
4422236167Sdelphij				 * or set it to 0 to disallow transmitting in
4423236167Sdelphij				 * monitor mode(?) and get DLT_PRISM.
4424236167Sdelphij				 */
4425236167Sdelphij				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4426236167Sdelphij					break;
4427236167Sdelphij				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
4428236167Sdelphij					break;
4429236167Sdelphij				montype = MONITOR_RT2500;
4430190225Srpaulo				cmd = priv[i].cmd;
4431190225Srpaulo				break;
4432236167Sdelphij			}
4433236167Sdelphij			if (strcmp(priv[i].name, "monitor") == 0) {
4434236167Sdelphij				/*
4435236167Sdelphij				 * Either ACX100 or hostap, use this one.
4436236167Sdelphij				 * It turns monitor mode on.
4437236167Sdelphij				 * If it takes two arguments, it's ACX100;
4438236167Sdelphij				 * the first argument is 1 for DLT_PRISM
4439236167Sdelphij				 * or 2 for DLT_IEEE80211, and the second
4440236167Sdelphij				 * argument is the channel on which to
4441236167Sdelphij				 * run.  If it takes one argument, it's
4442236167Sdelphij				 * HostAP, and the argument is 2 for
4443236167Sdelphij				 * DLT_IEEE80211 and 3 for DLT_PRISM.
4444236167Sdelphij				 *
4445236167Sdelphij				 * If we see this, we don't quit, as this
4446236167Sdelphij				 * might be a version of the hostap driver
4447236167Sdelphij				 * that also supports "monitor_type".
4448236167Sdelphij				 */
4449236167Sdelphij				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4450236167Sdelphij					break;
4451236167Sdelphij				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4452236167Sdelphij					break;
4453236167Sdelphij				switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
4454190225Srpaulo
4455236167Sdelphij				case 1:
4456236167Sdelphij					montype = MONITOR_PRISM;
4457236167Sdelphij					cmd = priv[i].cmd;
4458236167Sdelphij					break;
4459236167Sdelphij
4460236167Sdelphij				case 2:
4461236167Sdelphij					montype = MONITOR_ACX100;
4462236167Sdelphij					cmd = priv[i].cmd;
4463236167Sdelphij					break;
4464236167Sdelphij
4465236167Sdelphij				default:
4466236167Sdelphij					break;
4467236167Sdelphij				}
4468190225Srpaulo			}
4469190225Srpaulo		}
4470236167Sdelphij		free(priv);
4471190225Srpaulo	}
4472190225Srpaulo
4473190225Srpaulo	/*
4474190225Srpaulo	 * XXX - ipw3945?  islism?
4475190225Srpaulo	 */
4476190225Srpaulo
4477190225Srpaulo	/*
4478190225Srpaulo	 * Get the old mode.
4479190225Srpaulo	 */
4480190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
4481190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
4482190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4483190225Srpaulo	if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
448475107Sfenner		/*
4485190225Srpaulo		 * We probably won't be able to set the mode, either.
4486190225Srpaulo		 */
4487190225Srpaulo		return PCAP_ERROR_RFMON_NOTSUP;
4488190225Srpaulo	}
4489190225Srpaulo
4490190225Srpaulo	/*
4491190225Srpaulo	 * Is it currently in monitor mode?
4492190225Srpaulo	 */
4493190225Srpaulo	if (ireq.u.mode == IW_MODE_MONITOR) {
4494190225Srpaulo		/*
4495190225Srpaulo		 * Yes.  Just leave things as they are.
4496190225Srpaulo		 * We don't offer multiple link-layer types, as
4497190225Srpaulo		 * changing the link-layer type out from under
4498190225Srpaulo		 * somebody else capturing in monitor mode would
4499190225Srpaulo		 * be considered rude.
4500190225Srpaulo		 */
4501190225Srpaulo		return 1;
4502190225Srpaulo	}
4503190225Srpaulo	/*
4504190225Srpaulo	 * No.  We have to put the adapter into rfmon mode.
4505190225Srpaulo	 */
4506190225Srpaulo
4507190225Srpaulo	/*
4508190225Srpaulo	 * If we haven't already done so, arrange to have
4509190225Srpaulo	 * "pcap_close_all()" called when we exit.
4510190225Srpaulo	 */
4511190225Srpaulo	if (!pcap_do_addexit(handle)) {
4512190225Srpaulo		/*
4513190225Srpaulo		 * "atexit()" failed; don't put the interface
4514190225Srpaulo		 * in rfmon mode, just give up.
4515190225Srpaulo		 */
4516190225Srpaulo		return PCAP_ERROR_RFMON_NOTSUP;
4517190225Srpaulo	}
4518190225Srpaulo
4519190225Srpaulo	/*
4520190225Srpaulo	 * Save the old mode.
4521190225Srpaulo	 */
4522190225Srpaulo	handle->md.oldmode = ireq.u.mode;
4523190225Srpaulo
4524190225Srpaulo	/*
4525190225Srpaulo	 * Put the adapter in rfmon mode.  How we do this depends
4526190225Srpaulo	 * on whether we have a special private ioctl or not.
4527190225Srpaulo	 */
4528190225Srpaulo	if (montype == MONITOR_PRISM) {
4529190225Srpaulo		/*
4530190225Srpaulo		 * We have the "monitor" private ioctl, but none of
4531190225Srpaulo		 * the other private ioctls.  Use this, and select
4532190225Srpaulo		 * the Prism header.
453375107Sfenner		 *
4534190225Srpaulo		 * If it fails, just fall back on SIOCSIWMODE.
453575107Sfenner		 */
4536190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4537190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4538190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4539190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4540190225Srpaulo		ireq.u.data.length = 1;	/* 1 argument */
4541190225Srpaulo		args[0] = 3;	/* request Prism header */
4542190225Srpaulo		memcpy(ireq.u.name, args, IFNAMSIZ);
4543190225Srpaulo		if (ioctl(sock_fd, cmd, &ireq) != -1) {
4544190225Srpaulo			/*
4545190225Srpaulo			 * Success.
4546190225Srpaulo			 * Note that we have to put the old mode back
4547190225Srpaulo			 * when we close the device.
4548190225Srpaulo			 */
4549214518Srpaulo			handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4550190225Srpaulo
4551190225Srpaulo			/*
4552190225Srpaulo			 * Add this to the list of pcaps to close
4553190225Srpaulo			 * when we exit.
4554190225Srpaulo			 */
4555190225Srpaulo			pcap_add_to_pcaps_to_close(handle);
4556190225Srpaulo
4557190225Srpaulo			return 1;
455826175Sfenner		}
455975107Sfenner
456075107Sfenner		/*
4561190225Srpaulo		 * Failure.  Fall back on SIOCSIWMODE.
456275107Sfenner		 */
4563190225Srpaulo	}
4564190225Srpaulo
4565190225Srpaulo	/*
4566236167Sdelphij	 * First, take the interface down if it's up; otherwise, we
4567236167Sdelphij	 * might get EBUSY.
4568190225Srpaulo	 */
4569236167Sdelphij	memset(&ifr, 0, sizeof(ifr));
4570236167Sdelphij	strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4571236167Sdelphij	if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
4572236167Sdelphij		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4573236167Sdelphij		    "%s: Can't get flags: %s", device, strerror(errno));
4574236167Sdelphij		return PCAP_ERROR;
4575236167Sdelphij	}
4576236167Sdelphij	oldflags = 0;
4577236167Sdelphij	if (ifr.ifr_flags & IFF_UP) {
4578236167Sdelphij		oldflags = ifr.ifr_flags;
4579236167Sdelphij		ifr.ifr_flags &= ~IFF_UP;
4580236167Sdelphij		if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4581236167Sdelphij			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4582236167Sdelphij			    "%s: Can't set flags: %s", device, strerror(errno));
4583236167Sdelphij			return PCAP_ERROR;
4584236167Sdelphij		}
4585236167Sdelphij	}
4586236167Sdelphij
4587236167Sdelphij	/*
4588236167Sdelphij	 * Then turn monitor mode on.
4589236167Sdelphij	 */
4590190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
4591190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
4592190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4593190225Srpaulo	ireq.u.mode = IW_MODE_MONITOR;
4594190225Srpaulo	if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
4595190225Srpaulo		/*
4596190225Srpaulo		 * Scientist, you've failed.
4597236167Sdelphij		 * Bring the interface back up if we shut it down.
4598190225Srpaulo		 */
4599236167Sdelphij		ifr.ifr_flags = oldflags;
4600236167Sdelphij		if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4601236167Sdelphij			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4602236167Sdelphij			    "%s: Can't set flags: %s", device, strerror(errno));
4603236167Sdelphij			return PCAP_ERROR;
4604236167Sdelphij		}
4605190225Srpaulo		return PCAP_ERROR_RFMON_NOTSUP;
4606190225Srpaulo	}
4607190225Srpaulo
4608190225Srpaulo	/*
4609190225Srpaulo	 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4610190225Srpaulo	 * monitor mode and setting the channel, and then does
4611190225Srpaulo	 * "iwconfig up".
4612190225Srpaulo	 */
4613190225Srpaulo
4614190225Srpaulo	/*
4615190225Srpaulo	 * Now select the appropriate radio header.
4616190225Srpaulo	 */
4617190225Srpaulo	switch (montype) {
4618190225Srpaulo
4619190225Srpaulo	case MONITOR_WEXT:
4620190225Srpaulo		/*
4621190225Srpaulo		 * We don't have any private ioctl to set the header.
4622190225Srpaulo		 */
4623190225Srpaulo		break;
4624190225Srpaulo
4625190225Srpaulo	case MONITOR_HOSTAP:
4626190225Srpaulo		/*
4627214518Srpaulo		 * Try to select the radiotap header.
4628190225Srpaulo		 */
4629190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4630190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4631190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4632190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4633214518Srpaulo		args[0] = 3;	/* request radiotap header */
4634214518Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4635214518Srpaulo		if (ioctl(sock_fd, cmd, &ireq) != -1)
4636214518Srpaulo			break;	/* success */
4637214518Srpaulo
4638214518Srpaulo		/*
4639214518Srpaulo		 * That failed.  Try to select the AVS header.
4640214518Srpaulo		 */
4641214518Srpaulo		memset(&ireq, 0, sizeof ireq);
4642214518Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4643214518Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4644214518Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4645190225Srpaulo		args[0] = 2;	/* request AVS header */
4646190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4647214518Srpaulo		if (ioctl(sock_fd, cmd, &ireq) != -1)
4648214518Srpaulo			break;	/* success */
4649214518Srpaulo
4650214518Srpaulo		/*
4651214518Srpaulo		 * That failed.  Try to select the Prism header.
4652214518Srpaulo		 */
4653214518Srpaulo		memset(&ireq, 0, sizeof ireq);
4654214518Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4655214518Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4656214518Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4657214518Srpaulo		args[0] = 1;	/* request Prism header */
4658214518Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4659214518Srpaulo		ioctl(sock_fd, cmd, &ireq);
4660190225Srpaulo		break;
4661190225Srpaulo
4662190225Srpaulo	case MONITOR_PRISM:
4663190225Srpaulo		/*
4664190225Srpaulo		 * The private ioctl failed.
4665190225Srpaulo		 */
4666190225Srpaulo		break;
4667190225Srpaulo
4668190225Srpaulo	case MONITOR_PRISM54:
4669190225Srpaulo		/*
4670190225Srpaulo		 * Select the Prism header.
4671190225Srpaulo		 */
4672190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4673190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4674190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4675190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4676190225Srpaulo		args[0] = 3;	/* request Prism header */
4677190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4678190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4679190225Srpaulo		break;
4680190225Srpaulo
4681190225Srpaulo	case MONITOR_ACX100:
4682190225Srpaulo		/*
4683190225Srpaulo		 * Get the current channel.
4684190225Srpaulo		 */
4685190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4686190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4687190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4688190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4689190225Srpaulo		if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
4690190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4691190225Srpaulo			    "%s: SIOCGIWFREQ: %s", device,
4692190225Srpaulo			    pcap_strerror(errno));
4693190225Srpaulo			return PCAP_ERROR;
4694190225Srpaulo		}
4695190225Srpaulo		channel = ireq.u.freq.m;
4696190225Srpaulo
4697190225Srpaulo		/*
4698190225Srpaulo		 * Select the Prism header, and set the channel to the
4699190225Srpaulo		 * current value.
4700190225Srpaulo		 */
4701190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4702190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4703190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4704190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4705190225Srpaulo		args[0] = 1;		/* request Prism header */
4706190225Srpaulo		args[1] = channel;	/* set channel */
4707190225Srpaulo		memcpy(ireq.u.name, args, 2*sizeof (int));
4708190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4709190225Srpaulo		break;
4710190225Srpaulo
4711190225Srpaulo	case MONITOR_RT2500:
4712190225Srpaulo		/*
4713190225Srpaulo		 * Disallow transmission - that turns on the
4714190225Srpaulo		 * Prism header.
4715190225Srpaulo		 */
4716190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4717190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4718190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4719190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4720190225Srpaulo		args[0] = 0;	/* disallow transmitting */
4721190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4722190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4723190225Srpaulo		break;
4724190225Srpaulo
4725190225Srpaulo	case MONITOR_RT2570:
4726190225Srpaulo		/*
4727190225Srpaulo		 * Force the Prism header.
4728190225Srpaulo		 */
4729190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4730190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4731190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4732190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4733190225Srpaulo		args[0] = 1;	/* request Prism header */
4734190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4735190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4736190225Srpaulo		break;
4737190225Srpaulo
4738190225Srpaulo	case MONITOR_RT73:
4739190225Srpaulo		/*
4740190225Srpaulo		 * Force the Prism header.
4741190225Srpaulo		 */
4742190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4743190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4744190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4745190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4746190225Srpaulo		ireq.u.data.length = 1;	/* 1 argument */
4747190225Srpaulo		ireq.u.data.pointer = "1";
4748190225Srpaulo		ireq.u.data.flags = 0;
4749190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4750190225Srpaulo		break;
4751190225Srpaulo
4752190225Srpaulo	case MONITOR_RTL8XXX:
4753190225Srpaulo		/*
4754190225Srpaulo		 * Force the Prism header.
4755190225Srpaulo		 */
4756190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4757190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4758190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4759190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4760190225Srpaulo		args[0] = 1;	/* request Prism header */
4761190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4762190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4763190225Srpaulo		break;
476426175Sfenner	}
4765127664Sbms
4766190225Srpaulo	/*
4767236167Sdelphij	 * Now bring the interface back up if we brought it down.
4768236167Sdelphij	 */
4769236167Sdelphij	if (oldflags != 0) {
4770236167Sdelphij		ifr.ifr_flags = oldflags;
4771236167Sdelphij		if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4772236167Sdelphij			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4773236167Sdelphij			    "%s: Can't set flags: %s", device, strerror(errno));
4774236167Sdelphij
4775236167Sdelphij			/*
4776236167Sdelphij			 * At least try to restore the old mode on the
4777236167Sdelphij			 * interface.
4778236167Sdelphij			 */
4779236167Sdelphij			if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
4780236167Sdelphij				/*
4781236167Sdelphij				 * Scientist, you've failed.
4782236167Sdelphij				 */
4783236167Sdelphij				fprintf(stderr,
4784236167Sdelphij				    "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
4785236167Sdelphij				    "Please adjust manually.\n",
4786236167Sdelphij				    strerror(errno));
4787236167Sdelphij			}
4788236167Sdelphij			return PCAP_ERROR;
4789236167Sdelphij		}
4790236167Sdelphij	}
4791236167Sdelphij
4792236167Sdelphij	/*
4793190225Srpaulo	 * Note that we have to put the old mode back when we
4794190225Srpaulo	 * close the device.
4795190225Srpaulo	 */
4796214518Srpaulo	handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4797190225Srpaulo
4798190225Srpaulo	/*
4799190225Srpaulo	 * Add this to the list of pcaps to close when we exit.
4800190225Srpaulo	 */
4801190225Srpaulo	pcap_add_to_pcaps_to_close(handle);
4802190225Srpaulo
4803190225Srpaulo	return 1;
4804214518Srpaulo}
4805214518Srpaulo#endif /* IW_MODE_MONITOR */
4806214518Srpaulo
4807214518Srpaulo/*
4808214518Srpaulo * Try various mechanisms to enter monitor mode.
4809214518Srpaulo */
4810214518Srpaulostatic int
4811214518Srpauloenter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
4812214518Srpaulo{
4813214518Srpaulo#if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4814214518Srpaulo	int ret;
4815214518Srpaulo#endif
4816214518Srpaulo
4817214518Srpaulo#ifdef HAVE_LIBNL
4818214518Srpaulo	ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
4819214518Srpaulo	if (ret < 0)
4820214518Srpaulo		return ret;	/* error attempting to do so */
4821214518Srpaulo	if (ret == 1)
4822214518Srpaulo		return 1;	/* success */
4823214518Srpaulo#endif /* HAVE_LIBNL */
4824214518Srpaulo
4825214518Srpaulo#ifdef IW_MODE_MONITOR
4826214518Srpaulo	ret = enter_rfmon_mode_wext(handle, sock_fd, device);
4827214518Srpaulo	if (ret < 0)
4828214518Srpaulo		return ret;	/* error attempting to do so */
4829214518Srpaulo	if (ret == 1)
4830214518Srpaulo		return 1;	/* success */
4831214518Srpaulo#endif /* IW_MODE_MONITOR */
4832214518Srpaulo
4833190225Srpaulo	/*
4834214518Srpaulo	 * Either none of the mechanisms we know about work or none
4835214518Srpaulo	 * of those mechanisms are available, so we can't do monitor
4836214518Srpaulo	 * mode.
4837190225Srpaulo	 */
4838190225Srpaulo	return 0;
483975107Sfenner}
484026175Sfenner
4841236167Sdelphij/*
4842236167Sdelphij * Find out if we have any form of fragmentation/reassembly offloading.
4843236167Sdelphij *
4844236167Sdelphij * We do so using SIOCETHTOOL checking for various types of offloading;
4845236167Sdelphij * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4846236167Sdelphij * of the types of offloading, there's nothing we can do to check, so
4847236167Sdelphij * we just say "no, we don't".
4848236167Sdelphij */
4849236167Sdelphij#if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
4850236167Sdelphijstatic int
4851236167Sdelphijiface_ethtool_ioctl(pcap_t *handle, int cmd, const char *cmdname)
4852236167Sdelphij{
4853236167Sdelphij	struct ifreq	ifr;
4854236167Sdelphij	struct ethtool_value eval;
4855236167Sdelphij
4856236167Sdelphij	memset(&ifr, 0, sizeof(ifr));
4857236167Sdelphij	strncpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
4858236167Sdelphij	eval.cmd = cmd;
4859236167Sdelphij	ifr.ifr_data = (caddr_t)&eval;
4860236167Sdelphij	if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
4861252281Sdelphij		if (errno == EOPNOTSUPP || errno == EINVAL) {
4862236167Sdelphij			/*
4863236167Sdelphij			 * OK, let's just return 0, which, in our
4864236167Sdelphij			 * case, either means "no, what we're asking
4865236167Sdelphij			 * about is not enabled" or "all the flags
4866236167Sdelphij			 * are clear (i.e., nothing is enabled)".
4867236167Sdelphij			 */
4868236167Sdelphij			return 0;
4869236167Sdelphij		}
4870236167Sdelphij		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4871236167Sdelphij		    "%s: SIOETHTOOL(%s) ioctl failed: %s", handle->opt.source,
4872236167Sdelphij		    cmdname, strerror(errno));
4873236167Sdelphij		return -1;
4874236167Sdelphij	}
4875236167Sdelphij	return eval.data;
4876236167Sdelphij}
4877236167Sdelphij
4878236167Sdelphijstatic int
4879236167Sdelphijiface_get_offload(pcap_t *handle)
4880236167Sdelphij{
4881236167Sdelphij	int ret;
4882236167Sdelphij
4883236167Sdelphij#ifdef ETHTOOL_GTSO
4884236167Sdelphij	ret = iface_ethtool_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO");
4885236167Sdelphij	if (ret == -1)
4886236167Sdelphij		return -1;
4887236167Sdelphij	if (ret)
4888236167Sdelphij		return 1;	/* TCP segmentation offloading on */
4889236167Sdelphij#endif
4890236167Sdelphij
4891236167Sdelphij#ifdef ETHTOOL_GUFO
4892236167Sdelphij	ret = iface_ethtool_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO");
4893236167Sdelphij	if (ret == -1)
4894236167Sdelphij		return -1;
4895236167Sdelphij	if (ret)
4896236167Sdelphij		return 1;	/* UDP fragmentation offloading on */
4897236167Sdelphij#endif
4898236167Sdelphij
4899236167Sdelphij#ifdef ETHTOOL_GGSO
4900236167Sdelphij	/*
4901236167Sdelphij	 * XXX - will this cause large unsegmented packets to be
4902236167Sdelphij	 * handed to PF_PACKET sockets on transmission?  If not,
4903236167Sdelphij	 * this need not be checked.
4904236167Sdelphij	 */
4905236167Sdelphij	ret = iface_ethtool_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO");
4906236167Sdelphij	if (ret == -1)
4907236167Sdelphij		return -1;
4908236167Sdelphij	if (ret)
4909236167Sdelphij		return 1;	/* generic segmentation offloading on */
4910236167Sdelphij#endif
4911236167Sdelphij
4912236167Sdelphij#ifdef ETHTOOL_GFLAGS
4913236167Sdelphij	ret = iface_ethtool_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS");
4914236167Sdelphij	if (ret == -1)
4915236167Sdelphij		return -1;
4916236167Sdelphij	if (ret & ETH_FLAG_LRO)
4917236167Sdelphij		return 1;	/* large receive offloading on */
4918236167Sdelphij#endif
4919236167Sdelphij
4920236167Sdelphij#ifdef ETHTOOL_GGRO
4921236167Sdelphij	/*
4922236167Sdelphij	 * XXX - will this cause large reassembled packets to be
4923236167Sdelphij	 * handed to PF_PACKET sockets on receipt?  If not,
4924236167Sdelphij	 * this need not be checked.
4925236167Sdelphij	 */
4926236167Sdelphij	ret = iface_ethtool_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO");
4927236167Sdelphij	if (ret == -1)
4928236167Sdelphij		return -1;
4929236167Sdelphij	if (ret)
4930236167Sdelphij		return 1;	/* generic (large) receive offloading on */
4931236167Sdelphij#endif
4932236167Sdelphij
4933236167Sdelphij	return 0;
4934236167Sdelphij}
4935236167Sdelphij#else /* SIOCETHTOOL */
4936236167Sdelphijstatic int
4937236167Sdelphijiface_get_offload(pcap_t *handle _U_)
4938236167Sdelphij{
4939236167Sdelphij	/*
4940236167Sdelphij	 * XXX - do we need to get this information if we don't
4941236167Sdelphij	 * have the ethtool ioctls?  If so, how do we do that?
4942236167Sdelphij	 */
4943236167Sdelphij	return 0;
4944236167Sdelphij}
4945236167Sdelphij#endif /* SIOCETHTOOL */
4946236167Sdelphij
4947190225Srpaulo#endif /* HAVE_PF_PACKET_SOCKETS */
4948190225Srpaulo
4949190225Srpaulo/* ===== Functions to interface to the older kernels ================== */
4950190225Srpaulo
495175107Sfenner/*
4952190225Srpaulo * Try to open a packet socket using the old kernel interface.
4953190225Srpaulo * Returns 1 on success and a PCAP_ERROR_ value on an error.
495475107Sfenner */
495575107Sfennerstatic int
4956190225Srpauloactivate_old(pcap_t *handle)
495775107Sfenner{
4958127664Sbms	int		arptype;
495975107Sfenner	struct ifreq	ifr;
4960190225Srpaulo	const char	*device = handle->opt.source;
4961190225Srpaulo	struct utsname	utsname;
4962190225Srpaulo	int		mtu;
496375107Sfenner
4964190225Srpaulo	/* Open the socket */
496575107Sfenner
4966190225Srpaulo	handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
4967190225Srpaulo	if (handle->fd == -1) {
4968190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4969190225Srpaulo			 "socket: %s", pcap_strerror(errno));
4970236167Sdelphij		if (errno == EPERM || errno == EACCES) {
4971236167Sdelphij			/*
4972236167Sdelphij			 * You don't have permission to open the
4973236167Sdelphij			 * socket.
4974236167Sdelphij			 */
4975236167Sdelphij			return PCAP_ERROR_PERM_DENIED;
4976236167Sdelphij		} else {
4977236167Sdelphij			/*
4978236167Sdelphij			 * Other error.
4979236167Sdelphij			 */
4980236167Sdelphij			return PCAP_ERROR;
4981236167Sdelphij		}
4982190225Srpaulo	}
498375107Sfenner
4984190225Srpaulo	/* It worked - we are using the old interface */
4985190225Srpaulo	handle->md.sock_packet = 1;
498675107Sfenner
4987190225Srpaulo	/* ...which means we get the link-layer header. */
4988190225Srpaulo	handle->md.cooked = 0;
498975107Sfenner
4990190225Srpaulo	/* Bind to the given device */
499175107Sfenner
4992214518Srpaulo	if (strcmp(device, "any") == 0) {
4993190225Srpaulo		strncpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4994190225Srpaulo			PCAP_ERRBUF_SIZE);
4995190225Srpaulo		return PCAP_ERROR;
4996190225Srpaulo	}
4997190225Srpaulo	if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
4998190225Srpaulo		return PCAP_ERROR;
499975107Sfenner
5000190225Srpaulo	/*
5001190225Srpaulo	 * Try to get the link-layer type.
5002190225Srpaulo	 */
5003190225Srpaulo	arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
5004190225Srpaulo	if (arptype < 0)
5005190225Srpaulo		return PCAP_ERROR;
5006127664Sbms
5007190225Srpaulo	/*
5008190225Srpaulo	 * Try to find the DLT_ type corresponding to that
5009190225Srpaulo	 * link-layer type.
5010190225Srpaulo	 */
5011190225Srpaulo	map_arphrd_to_dlt(handle, arptype, 0);
5012190225Srpaulo	if (handle->linktype == -1) {
5013190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5014190225Srpaulo			 "unknown arptype %d", arptype);
5015190225Srpaulo		return PCAP_ERROR;
5016190225Srpaulo	}
5017127664Sbms
5018190225Srpaulo	/* Go to promisc mode if requested */
5019127664Sbms
5020190225Srpaulo	if (handle->opt.promisc) {
5021190225Srpaulo		memset(&ifr, 0, sizeof(ifr));
5022190225Srpaulo		strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5023190225Srpaulo		if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
5024190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5025190225Srpaulo				 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
5026190225Srpaulo			return PCAP_ERROR;
5027190225Srpaulo		}
5028190225Srpaulo		if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
5029190225Srpaulo			/*
5030190225Srpaulo			 * Promiscuous mode isn't currently on,
5031190225Srpaulo			 * so turn it on, and remember that
5032190225Srpaulo			 * we should turn it off when the
5033190225Srpaulo			 * pcap_t is closed.
5034190225Srpaulo			 */
503575107Sfenner
5036190225Srpaulo			/*
5037190225Srpaulo			 * If we haven't already done so, arrange
5038190225Srpaulo			 * to have "pcap_close_all()" called when
5039190225Srpaulo			 * we exit.
5040190225Srpaulo			 */
5041190225Srpaulo			if (!pcap_do_addexit(handle)) {
504275107Sfenner				/*
5043190225Srpaulo				 * "atexit()" failed; don't put
5044190225Srpaulo				 * the interface in promiscuous
5045190225Srpaulo				 * mode, just give up.
504675107Sfenner				 */
5047190225Srpaulo				return PCAP_ERROR;
5048190225Srpaulo			}
504975107Sfenner
5050190225Srpaulo			ifr.ifr_flags |= IFF_PROMISC;
5051190225Srpaulo			if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
5052190225Srpaulo			        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5053190225Srpaulo					 "SIOCSIFFLAGS: %s",
5054190225Srpaulo					 pcap_strerror(errno));
5055190225Srpaulo				return PCAP_ERROR;
5056190225Srpaulo			}
5057214518Srpaulo			handle->md.must_do_on_close |= MUST_CLEAR_PROMISC;
505875107Sfenner
5059190225Srpaulo			/*
5060190225Srpaulo			 * Add this to the list of pcaps
5061190225Srpaulo			 * to close when we exit.
5062190225Srpaulo			 */
5063190225Srpaulo			pcap_add_to_pcaps_to_close(handle);
506475107Sfenner		}
5065190225Srpaulo	}
506675107Sfenner
5067190225Srpaulo	/*
5068190225Srpaulo	 * Compute the buffer size.
5069190225Srpaulo	 *
5070190225Srpaulo	 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5071190225Srpaulo	 * kernel, and might require special handling - check.
5072190225Srpaulo	 */
5073190225Srpaulo	if (uname(&utsname) < 0 ||
5074190225Srpaulo	    strncmp(utsname.release, "2.0", 3) == 0) {
507598530Sfenner		/*
5076190225Srpaulo		 * Either we couldn't find out what kernel release
5077190225Srpaulo		 * this is, or it's a 2.0[.x] kernel.
5078190225Srpaulo		 *
5079190225Srpaulo		 * In the 2.0[.x] kernel, a "recvfrom()" on
5080190225Srpaulo		 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5081190225Srpaulo		 * return the number of bytes read, so if we pass
5082190225Srpaulo		 * a length based on the snapshot length, it'll
5083190225Srpaulo		 * return the number of bytes from the packet
5084190225Srpaulo		 * copied to userland, not the actual length
5085190225Srpaulo		 * of the packet.
5086190225Srpaulo		 *
5087190225Srpaulo		 * This means that, for example, the IP dissector
5088190225Srpaulo		 * in tcpdump will get handed a packet length less
5089190225Srpaulo		 * than the length in the IP header, and will
5090190225Srpaulo		 * complain about "truncated-ip".
5091190225Srpaulo		 *
5092190225Srpaulo		 * So we don't bother trying to copy from the
5093190225Srpaulo		 * kernel only the bytes in which we're interested,
5094190225Srpaulo		 * but instead copy them all, just as the older
5095190225Srpaulo		 * versions of libpcap for Linux did.
5096190225Srpaulo		 *
5097190225Srpaulo		 * The buffer therefore needs to be big enough to
5098190225Srpaulo		 * hold the largest packet we can get from this
5099190225Srpaulo		 * device.  Unfortunately, we can't get the MRU
5100190225Srpaulo		 * of the network; we can only get the MTU.  The
5101190225Srpaulo		 * MTU may be too small, in which case a packet larger
5102190225Srpaulo		 * than the buffer size will be truncated *and* we
5103190225Srpaulo		 * won't get the actual packet size.
5104190225Srpaulo		 *
5105190225Srpaulo		 * However, if the snapshot length is larger than
5106190225Srpaulo		 * the buffer size based on the MTU, we use the
5107190225Srpaulo		 * snapshot length as the buffer size, instead;
5108190225Srpaulo		 * this means that with a sufficiently large snapshot
5109190225Srpaulo		 * length we won't artificially truncate packets
5110190225Srpaulo		 * to the MTU-based size.
5111190225Srpaulo		 *
5112190225Srpaulo		 * This mess just one of many problems with packet
5113190225Srpaulo		 * capture on 2.0[.x] kernels; you really want a
5114190225Srpaulo		 * 2.2[.x] or later kernel if you want packet capture
5115190225Srpaulo		 * to work well.
511698530Sfenner		 */
5117190225Srpaulo		mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
5118190225Srpaulo		if (mtu == -1)
5119190225Srpaulo			return PCAP_ERROR;
5120190225Srpaulo		handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
5121190225Srpaulo		if (handle->bufsize < handle->snapshot)
5122190225Srpaulo			handle->bufsize = handle->snapshot;
5123190225Srpaulo	} else {
5124190225Srpaulo		/*
5125190225Srpaulo		 * This is a 2.2[.x] or later kernel.
5126190225Srpaulo		 *
5127190225Srpaulo		 * We can safely pass "recvfrom()" a byte count
5128190225Srpaulo		 * based on the snapshot length.
5129190225Srpaulo		 */
5130190225Srpaulo		handle->bufsize = handle->snapshot;
5131190225Srpaulo	}
513298530Sfenner
5133190225Srpaulo	/*
5134190225Srpaulo	 * Default value for offset to align link-layer payload
5135190225Srpaulo	 * on a 4-byte boundary.
5136190225Srpaulo	 */
5137190225Srpaulo	handle->offset	 = 0;
513875107Sfenner
5139252281Sdelphij	/*
5140252281Sdelphij	 * SOCK_PACKET sockets don't supply information from
5141252281Sdelphij	 * stripped VLAN tags.
5142252281Sdelphij	 */
5143252281Sdelphij	handle->md.vlan_offset = -1; /* unknown */
5144252281Sdelphij
5145190225Srpaulo	return 1;
514675107Sfenner}
514775107Sfenner
514875107Sfenner/*
5149127664Sbms *  Bind the socket associated with FD to the given device using the
515075107Sfenner *  interface of the old kernels.
515175107Sfenner */
515275107Sfennerstatic int
515375107Sfenneriface_bind_old(int fd, const char *device, char *ebuf)
515475107Sfenner{
515575107Sfenner	struct sockaddr	saddr;
5156127664Sbms	int		err;
5157127664Sbms	socklen_t	errlen = sizeof(err);
515875107Sfenner
515975107Sfenner	memset(&saddr, 0, sizeof(saddr));
516075107Sfenner	strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
516175107Sfenner	if (bind(fd, &saddr, sizeof(saddr)) == -1) {
516275107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
516375107Sfenner			 "bind: %s", pcap_strerror(errno));
516475107Sfenner		return -1;
516526175Sfenner	}
516626175Sfenner
5167127664Sbms	/* Any pending errors, e.g., network is down? */
5168127664Sbms
5169127664Sbms	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
5170127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
5171127664Sbms			"getsockopt: %s", pcap_strerror(errno));
5172127664Sbms		return -1;
5173127664Sbms	}
5174127664Sbms
5175127664Sbms	if (err > 0) {
5176127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
5177127664Sbms			"bind: %s", pcap_strerror(err));
5178127664Sbms		return -1;
5179127664Sbms	}
5180127664Sbms
518175107Sfenner	return 0;
518226175Sfenner}
518326175Sfenner
518475107Sfenner
518575107Sfenner/* ===== System calls available on all supported kernels ============== */
518675107Sfenner
518775107Sfenner/*
5188127664Sbms *  Query the kernel for the MTU of the given interface.
518975107Sfenner */
519075107Sfennerstatic int
519175107Sfenneriface_get_mtu(int fd, const char *device, char *ebuf)
519226175Sfenner{
519375107Sfenner	struct ifreq	ifr;
519426175Sfenner
519575107Sfenner	if (!device)
519675107Sfenner		return BIGGER_THAN_ALL_MTUS;
519775107Sfenner
519875107Sfenner	memset(&ifr, 0, sizeof(ifr));
519975107Sfenner	strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
520075107Sfenner
520175107Sfenner	if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
520275107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
5203172677Smlaier			 "SIOCGIFMTU: %s", pcap_strerror(errno));
520475107Sfenner		return -1;
520575107Sfenner	}
520675107Sfenner
520775107Sfenner	return ifr.ifr_mtu;
520826175Sfenner}
520926175Sfenner
521075107Sfenner/*
521175107Sfenner *  Get the hardware type of the given interface as ARPHRD_xxx constant.
521275107Sfenner */
521375107Sfennerstatic int
521475107Sfenneriface_get_arptype(int fd, const char *device, char *ebuf)
521526175Sfenner{
521675107Sfenner	struct ifreq	ifr;
521726175Sfenner
521875107Sfenner	memset(&ifr, 0, sizeof(ifr));
521975107Sfenner	strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
522075107Sfenner
522175107Sfenner	if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
522275107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
5223172677Smlaier			 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
5224190225Srpaulo		if (errno == ENODEV) {
5225190225Srpaulo			/*
5226190225Srpaulo			 * No such device.
5227190225Srpaulo			 */
5228190225Srpaulo			return PCAP_ERROR_NO_SUCH_DEVICE;
5229190225Srpaulo		}
5230190225Srpaulo		return PCAP_ERROR;
523175107Sfenner	}
523275107Sfenner
523375107Sfenner	return ifr.ifr_hwaddr.sa_family;
523426175Sfenner}
523575107Sfenner
523698530Sfenner#ifdef SO_ATTACH_FILTER
523775107Sfennerstatic int
5238214518Srpaulofix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
523975107Sfenner{
524075107Sfenner	size_t prog_size;
524175107Sfenner	register int i;
524275107Sfenner	register struct bpf_insn *p;
524375107Sfenner	struct bpf_insn *f;
524475107Sfenner	int len;
524575107Sfenner
524675107Sfenner	/*
524775107Sfenner	 * Make a copy of the filter, and modify that copy if
524875107Sfenner	 * necessary.
524975107Sfenner	 */
525075107Sfenner	prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
525175107Sfenner	len = handle->fcode.bf_len;
525275107Sfenner	f = (struct bpf_insn *)malloc(prog_size);
525375107Sfenner	if (f == NULL) {
5254190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
525575107Sfenner			 "malloc: %s", pcap_strerror(errno));
525675107Sfenner		return -1;
525775107Sfenner	}
525875107Sfenner	memcpy(f, handle->fcode.bf_insns, prog_size);
525975107Sfenner	fcode->len = len;
526075107Sfenner	fcode->filter = (struct sock_filter *) f;
526175107Sfenner
526275107Sfenner	for (i = 0; i < len; ++i) {
526375107Sfenner		p = &f[i];
526475107Sfenner		/*
526575107Sfenner		 * What type of instruction is this?
526675107Sfenner		 */
526775107Sfenner		switch (BPF_CLASS(p->code)) {
526875107Sfenner
526975107Sfenner		case BPF_RET:
527075107Sfenner			/*
5271214518Srpaulo			 * It's a return instruction; are we capturing
5272214518Srpaulo			 * in memory-mapped mode?
527375107Sfenner			 */
5274214518Srpaulo			if (!is_mmapped) {
527575107Sfenner				/*
5276214518Srpaulo				 * No; is the snapshot length a constant,
5277214518Srpaulo				 * rather than the contents of the
5278214518Srpaulo				 * accumulator?
527975107Sfenner				 */
5280214518Srpaulo				if (BPF_MODE(p->code) == BPF_K) {
5281214518Srpaulo					/*
5282214518Srpaulo					 * Yes - if the value to be returned,
5283214518Srpaulo					 * i.e. the snapshot length, is
5284214518Srpaulo					 * anything other than 0, make it
5285214518Srpaulo					 * 65535, so that the packet is
5286214518Srpaulo					 * truncated by "recvfrom()",
5287214518Srpaulo					 * not by the filter.
5288214518Srpaulo					 *
5289214518Srpaulo					 * XXX - there's nothing we can
5290214518Srpaulo					 * easily do if it's getting the
5291214518Srpaulo					 * value from the accumulator; we'd
5292214518Srpaulo					 * have to insert code to force
5293214518Srpaulo					 * non-zero values to be 65535.
5294214518Srpaulo					 */
5295214518Srpaulo					if (p->k != 0)
5296214518Srpaulo						p->k = 65535;
5297214518Srpaulo				}
529875107Sfenner			}
529975107Sfenner			break;
530075107Sfenner
530175107Sfenner		case BPF_LD:
530275107Sfenner		case BPF_LDX:
530375107Sfenner			/*
530475107Sfenner			 * It's a load instruction; is it loading
530575107Sfenner			 * from the packet?
530675107Sfenner			 */
530775107Sfenner			switch (BPF_MODE(p->code)) {
530875107Sfenner
530975107Sfenner			case BPF_ABS:
531075107Sfenner			case BPF_IND:
531175107Sfenner			case BPF_MSH:
531275107Sfenner				/*
531375107Sfenner				 * Yes; are we in cooked mode?
531475107Sfenner				 */
531575107Sfenner				if (handle->md.cooked) {
531675107Sfenner					/*
531775107Sfenner					 * Yes, so we need to fix this
531875107Sfenner					 * instruction.
531975107Sfenner					 */
532075107Sfenner					if (fix_offset(p) < 0) {
532175107Sfenner						/*
532275107Sfenner						 * We failed to do so.
532375107Sfenner						 * Return 0, so our caller
532475107Sfenner						 * knows to punt to userland.
532575107Sfenner						 */
532675107Sfenner						return 0;
532775107Sfenner					}
532875107Sfenner				}
532975107Sfenner				break;
533075107Sfenner			}
533175107Sfenner			break;
533275107Sfenner		}
533375107Sfenner	}
533475107Sfenner	return 1;	/* we succeeded */
533575107Sfenner}
533675107Sfenner
533775107Sfennerstatic int
533875107Sfennerfix_offset(struct bpf_insn *p)
533975107Sfenner{
534075107Sfenner	/*
534175107Sfenner	 * What's the offset?
534275107Sfenner	 */
534375107Sfenner	if (p->k >= SLL_HDR_LEN) {
534475107Sfenner		/*
534575107Sfenner		 * It's within the link-layer payload; that starts at an
534675107Sfenner		 * offset of 0, as far as the kernel packet filter is
534775107Sfenner		 * concerned, so subtract the length of the link-layer
534875107Sfenner		 * header.
534975107Sfenner		 */
535075107Sfenner		p->k -= SLL_HDR_LEN;
5351242484Sdelphij	} else if (p->k == 0) {
5352242484Sdelphij		/*
5353242484Sdelphij		 * It's the packet type field; map it to the special magic
5354242484Sdelphij		 * kernel offset for that field.
5355242484Sdelphij		 */
5356242484Sdelphij		p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
535775107Sfenner	} else if (p->k == 14) {
535875107Sfenner		/*
535975107Sfenner		 * It's the protocol field; map it to the special magic
536075107Sfenner		 * kernel offset for that field.
536175107Sfenner		 */
536275107Sfenner		p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
5363242484Sdelphij	} else if ((bpf_int32)(p->k) > 0) {
536475107Sfenner		/*
536575107Sfenner		 * It's within the header, but it's not one of those
536675107Sfenner		 * fields; we can't do that in the kernel, so punt
536775107Sfenner		 * to userland.
536875107Sfenner		 */
536975107Sfenner		return -1;
537075107Sfenner	}
537175107Sfenner	return 0;
537275107Sfenner}
537398530Sfenner
537498530Sfennerstatic int
537598530Sfennerset_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
537698530Sfenner{
537798530Sfenner	int total_filter_on = 0;
537898530Sfenner	int save_mode;
537998530Sfenner	int ret;
538098530Sfenner	int save_errno;
538198530Sfenner
538298530Sfenner	/*
538398530Sfenner	 * The socket filter code doesn't discard all packets queued
538498530Sfenner	 * up on the socket when the filter is changed; this means
538598530Sfenner	 * that packets that don't match the new filter may show up
538698530Sfenner	 * after the new filter is put onto the socket, if those
538798530Sfenner	 * packets haven't yet been read.
538898530Sfenner	 *
538998530Sfenner	 * This means, for example, that if you do a tcpdump capture
539098530Sfenner	 * with a filter, the first few packets in the capture might
539198530Sfenner	 * be packets that wouldn't have passed the filter.
539298530Sfenner	 *
539398530Sfenner	 * We therefore discard all packets queued up on the socket
539498530Sfenner	 * when setting a kernel filter.  (This isn't an issue for
539598530Sfenner	 * userland filters, as the userland filtering is done after
539698530Sfenner	 * packets are queued up.)
539798530Sfenner	 *
539898530Sfenner	 * To flush those packets, we put the socket in read-only mode,
539998530Sfenner	 * and read packets from the socket until there are no more to
540098530Sfenner	 * read.
540198530Sfenner	 *
540298530Sfenner	 * In order to keep that from being an infinite loop - i.e.,
540398530Sfenner	 * to keep more packets from arriving while we're draining
540498530Sfenner	 * the queue - we put the "total filter", which is a filter
540598530Sfenner	 * that rejects all packets, onto the socket before draining
540698530Sfenner	 * the queue.
540798530Sfenner	 *
540898530Sfenner	 * This code deliberately ignores any errors, so that you may
540998530Sfenner	 * get bogus packets if an error occurs, rather than having
541098530Sfenner	 * the filtering done in userland even if it could have been
541198530Sfenner	 * done in the kernel.
541298530Sfenner	 */
5413127664Sbms	if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
541498530Sfenner		       &total_fcode, sizeof(total_fcode)) == 0) {
541598530Sfenner		char drain[1];
541698530Sfenner
541798530Sfenner		/*
541898530Sfenner		 * Note that we've put the total filter onto the socket.
541998530Sfenner		 */
542098530Sfenner		total_filter_on = 1;
542198530Sfenner
542298530Sfenner		/*
542398530Sfenner		 * Save the socket's current mode, and put it in
542498530Sfenner		 * non-blocking mode; we drain it by reading packets
5425127664Sbms		 * until we get an error (which is normally a
542698530Sfenner		 * "nothing more to be read" error).
542798530Sfenner		 */
542898530Sfenner		save_mode = fcntl(handle->fd, F_GETFL, 0);
542998530Sfenner		if (save_mode != -1 &&
543098530Sfenner		    fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
543198530Sfenner			while (recv(handle->fd, &drain, sizeof drain,
543298530Sfenner			       MSG_TRUNC) >= 0)
543398530Sfenner				;
5434127664Sbms			save_errno = errno;
543598530Sfenner			fcntl(handle->fd, F_SETFL, save_mode);
5436127664Sbms			if (save_errno != EAGAIN) {
5437127664Sbms				/* Fatal error */
5438127664Sbms				reset_kernel_filter(handle);
5439190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5440127664Sbms				 "recv: %s", pcap_strerror(save_errno));
5441127664Sbms				return -2;
5442127664Sbms			}
544398530Sfenner		}
544498530Sfenner	}
544598530Sfenner
544698530Sfenner	/*
544798530Sfenner	 * Now attach the new filter.
544898530Sfenner	 */
5449127664Sbms	ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
545098530Sfenner			 fcode, sizeof(*fcode));
545198530Sfenner	if (ret == -1 && total_filter_on) {
545298530Sfenner		/*
545398530Sfenner		 * Well, we couldn't set that filter on the socket,
545498530Sfenner		 * but we could set the total filter on the socket.
545598530Sfenner		 *
545698530Sfenner		 * This could, for example, mean that the filter was
545798530Sfenner		 * too big to put into the kernel, so we'll have to
545898530Sfenner		 * filter in userland; in any case, we'll be doing
545998530Sfenner		 * filtering in userland, so we need to remove the
546098530Sfenner		 * total filter so we see packets.
546198530Sfenner		 */
546298530Sfenner		save_errno = errno;
546398530Sfenner
546498530Sfenner		/*
546598530Sfenner		 * XXX - if this fails, we're really screwed;
546698530Sfenner		 * we have the total filter on the socket,
546798530Sfenner		 * and it won't come off.  What do we do then?
546898530Sfenner		 */
546998530Sfenner		reset_kernel_filter(handle);
547098530Sfenner
547198530Sfenner		errno = save_errno;
547298530Sfenner	}
5473127664Sbms	return ret;
547498530Sfenner}
547598530Sfenner
547698530Sfennerstatic int
547798530Sfennerreset_kernel_filter(pcap_t *handle)
547898530Sfenner{
5479172677Smlaier	/*
5480172677Smlaier	 * setsockopt() barfs unless it get a dummy parameter.
5481172677Smlaier	 * valgrind whines unless the value is initialized,
5482172677Smlaier	 * as it has no idea that setsockopt() ignores its
5483172677Smlaier	 * parameter.
5484172677Smlaier	 */
5485172677Smlaier	int dummy = 0;
548698530Sfenner
548798530Sfenner	return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
548898530Sfenner				   &dummy, sizeof(dummy));
548998530Sfenner}
549075107Sfenner#endif
5491