pcap-linux.c revision 214518
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>
13075107Sfenner#include <sys/socket.h>
13175107Sfenner#include <sys/ioctl.h>
13275107Sfenner#include <sys/utsname.h>
133190225Srpaulo#include <sys/mman.h>
134214518Srpaulo#include <linux/if.h>
13575107Sfenner#include <netinet/in.h>
13675107Sfenner#include <linux/if_ether.h>
13775107Sfenner#include <net/if_arp.h>
138190225Srpaulo#include <poll.h>
139214518Srpaulo#include <dirent.h>
14026175Sfenner
14198530Sfenner/*
142190225Srpaulo * Got Wireless Extensions?
143190225Srpaulo */
144190225Srpaulo#ifdef HAVE_LINUX_WIRELESS_H
145190225Srpaulo#include <linux/wireless.h>
146214518Srpaulo#endif /* HAVE_LINUX_WIRELESS_H */
147190225Srpaulo
148214518Srpaulo/*
149214518Srpaulo * Got libnl?
150214518Srpaulo */
151214518Srpaulo#ifdef HAVE_LIBNL
152214518Srpaulo#include <linux/nl80211.h>
153214518Srpaulo
154214518Srpaulo#include <netlink/genl/genl.h>
155214518Srpaulo#include <netlink/genl/family.h>
156214518Srpaulo#include <netlink/genl/ctrl.h>
157214518Srpaulo#include <netlink/msg.h>
158214518Srpaulo#include <netlink/attr.h>
159214518Srpaulo#endif /* HAVE_LIBNL */
160214518Srpaulo
161190225Srpaulo#include "pcap-int.h"
162190225Srpaulo#include "pcap/sll.h"
163190225Srpaulo#include "pcap/vlan.h"
164190225Srpaulo
165190225Srpaulo#ifdef HAVE_DAG_API
166190225Srpaulo#include "pcap-dag.h"
167190225Srpaulo#endif /* HAVE_DAG_API */
168190225Srpaulo
169190225Srpaulo#ifdef HAVE_SEPTEL_API
170190225Srpaulo#include "pcap-septel.h"
171190225Srpaulo#endif /* HAVE_SEPTEL_API */
172190225Srpaulo
173214518Srpaulo#ifdef HAVE_SNF_API
174214518Srpaulo#include "pcap-snf.h"
175214518Srpaulo#endif /* HAVE_SNF_API */
176214518Srpaulo
177190225Srpaulo#ifdef PCAP_SUPPORT_USB
178190225Srpaulo#include "pcap-usb-linux.h"
179190225Srpaulo#endif
180190225Srpaulo
181190225Srpaulo#ifdef PCAP_SUPPORT_BT
182190225Srpaulo#include "pcap-bt-linux.h"
183190225Srpaulo#endif
184190225Srpaulo
185214518Srpaulo#ifdef PCAP_SUPPORT_CAN
186214518Srpaulo#include "pcap-can-linux.h"
187214518Srpaulo#endif
188214518Srpaulo
189190225Srpaulo/*
19098530Sfenner * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
19198530Sfenner * sockets rather than SOCK_PACKET sockets.
19298530Sfenner *
19398530Sfenner * To use them, we include <linux/if_packet.h> rather than
19498530Sfenner * <netpacket/packet.h>; we do so because
19598530Sfenner *
19698530Sfenner *	some Linux distributions (e.g., Slackware 4.0) have 2.2 or
19798530Sfenner *	later kernels and libc5, and don't provide a <netpacket/packet.h>
19898530Sfenner *	file;
19998530Sfenner *
20098530Sfenner *	not all versions of glibc2 have a <netpacket/packet.h> file
20198530Sfenner *	that defines stuff needed for some of the 2.4-or-later-kernel
20298530Sfenner *	features, so if the system has a 2.4 or later kernel, we
20398530Sfenner *	still can't use those features.
20498530Sfenner *
20598530Sfenner * We're already including a number of other <linux/XXX.h> headers, and
20698530Sfenner * this code is Linux-specific (no other OS has PF_PACKET sockets as
20798530Sfenner * a raw packet capture mechanism), so it's not as if you gain any
20898530Sfenner * useful portability by using <netpacket/packet.h>
20998530Sfenner *
21098530Sfenner * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
21198530Sfenner * isn't defined?  It only defines one data structure in 2.0.x, so
21298530Sfenner * it shouldn't cause any problems.
21398530Sfenner */
214127664Sbms#ifdef PF_PACKET
21598530Sfenner# include <linux/if_packet.h>
21626175Sfenner
21775107Sfenner /*
21898530Sfenner  * On at least some Linux distributions (for example, Red Hat 5.2),
21998530Sfenner  * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
22098530Sfenner  * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
22175107Sfenner  * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
22275107Sfenner  * the PACKET_xxx stuff.
22375107Sfenner  *
22475107Sfenner  * So we check whether PACKET_HOST is defined, and assume that we have
22575107Sfenner  * PF_PACKET sockets only if it is defined.
22675107Sfenner  */
22775107Sfenner# ifdef PACKET_HOST
22875107Sfenner#  define HAVE_PF_PACKET_SOCKETS
229190225Srpaulo#  ifdef PACKET_AUXDATA
230190225Srpaulo#   define HAVE_PACKET_AUXDATA
231190225Srpaulo#  endif /* PACKET_AUXDATA */
23275107Sfenner# endif /* PACKET_HOST */
233190225Srpaulo
234190225Srpaulo
235190225Srpaulo /* check for memory mapped access avaibility. We assume every needed
236190225Srpaulo  * struct is defined if the macro TPACKET_HDRLEN is defined, because it
237190225Srpaulo  * uses many ring related structs and macros */
238190225Srpaulo# ifdef TPACKET_HDRLEN
239190225Srpaulo#  define HAVE_PACKET_RING
240190225Srpaulo#  ifdef TPACKET2_HDRLEN
241190225Srpaulo#   define HAVE_TPACKET2
242190225Srpaulo#  else
243190225Srpaulo#   define TPACKET_V1	0
244190225Srpaulo#  endif /* TPACKET2_HDRLEN */
245190225Srpaulo# endif /* TPACKET_HDRLEN */
24698530Sfenner#endif /* PF_PACKET */
24775107Sfenner
24875107Sfenner#ifdef SO_ATTACH_FILTER
24975107Sfenner#include <linux/types.h>
25075107Sfenner#include <linux/filter.h>
25126175Sfenner#endif
25226175Sfenner
253190225Srpaulo#ifndef HAVE_SOCKLEN_T
25475107Sfennertypedef int		socklen_t;
25575107Sfenner#endif
25626175Sfenner
25775107Sfenner#ifndef MSG_TRUNC
25898530Sfenner/*
25998530Sfenner * This is being compiled on a system that lacks MSG_TRUNC; define it
26098530Sfenner * with the value it has in the 2.2 and later kernels, so that, on
26198530Sfenner * those kernels, when we pass it in the flags argument to "recvfrom()"
26298530Sfenner * we're passing the right value and thus get the MSG_TRUNC behavior
26398530Sfenner * we want.  (We don't get that behavior on 2.0[.x] kernels, because
26498530Sfenner * they didn't support MSG_TRUNC.)
26598530Sfenner */
26698530Sfenner#define MSG_TRUNC	0x20
26775107Sfenner#endif
26875107Sfenner
269127664Sbms#ifndef SOL_PACKET
270127664Sbms/*
271127664Sbms * This is being compiled on a system that lacks SOL_PACKET; define it
272127664Sbms * with the value it has in the 2.2 and later kernels, so that we can
273127664Sbms * set promiscuous mode in the good modern way rather than the old
274127664Sbms * 2.0-kernel crappy way.
275127664Sbms */
276127664Sbms#define SOL_PACKET	263
277127664Sbms#endif
278127664Sbms
27975107Sfenner#define MAX_LINKHEADER_SIZE	256
28075107Sfenner
281127664Sbms/*
282127664Sbms * When capturing on all interfaces we use this as the buffer size.
28375107Sfenner * Should be bigger then all MTUs that occur in real life.
28475107Sfenner * 64kB should be enough for now.
28575107Sfenner */
28675107Sfenner#define BIGGER_THAN_ALL_MTUS	(64*1024)
28775107Sfenner
28875107Sfenner/*
289190225Srpaulo * Prototypes for internal functions and methods.
29075107Sfenner */
291127664Sbmsstatic void map_arphrd_to_dlt(pcap_t *, int, int);
292190225Srpaulo#ifdef HAVE_PF_PACKET_SOCKETS
293190225Srpaulostatic short int map_packet_type_to_sll_type(short int);
294190225Srpaulo#endif
295190225Srpaulostatic int pcap_activate_linux(pcap_t *);
296190225Srpaulostatic int activate_old(pcap_t *);
297190225Srpaulostatic int activate_new(pcap_t *);
298190225Srpaulostatic int activate_mmap(pcap_t *);
299190225Srpaulostatic int pcap_can_set_rfmon_linux(pcap_t *);
300127664Sbmsstatic int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
30175107Sfennerstatic int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
302146768Ssamstatic int pcap_inject_linux(pcap_t *, const void *, size_t);
303127664Sbmsstatic int pcap_stats_linux(pcap_t *, struct pcap_stat *);
304127664Sbmsstatic int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
305162012Ssamstatic int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
306190225Srpaulostatic void pcap_cleanup_linux(pcap_t *);
30775107Sfenner
308190225Srpaulounion thdr {
309190225Srpaulo	struct tpacket_hdr	*h1;
310190225Srpaulo	struct tpacket2_hdr	*h2;
311190225Srpaulo	void			*raw;
312190225Srpaulo};
313190225Srpaulo
314190225Srpaulo#ifdef HAVE_PACKET_RING
315190225Srpaulo#define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
316190225Srpaulo
317190225Srpaulostatic void destroy_ring(pcap_t *handle);
318190225Srpaulostatic int create_ring(pcap_t *handle);
319190225Srpaulostatic int prepare_tpacket_socket(pcap_t *handle);
320190225Srpaulostatic void pcap_cleanup_linux_mmap(pcap_t *);
321190225Srpaulostatic int pcap_read_linux_mmap(pcap_t *, int, pcap_handler , u_char *);
322190225Srpaulostatic int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
323190225Srpaulostatic int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
324190225Srpaulostatic int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
325214518Srpaulostatic void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
326214518Srpaulo    const u_char *bytes);
327190225Srpaulo#endif
328190225Srpaulo
32975107Sfenner/*
33075107Sfenner * Wrap some ioctl calls
33175107Sfenner */
33275107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
33375107Sfennerstatic int	iface_get_id(int fd, const char *device, char *ebuf);
33475107Sfenner#endif
33575107Sfennerstatic int	iface_get_mtu(int fd, const char *device, char *ebuf);
33675107Sfennerstatic int 	iface_get_arptype(int fd, const char *device, char *ebuf);
33775107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
33875107Sfennerstatic int 	iface_bind(int fd, int ifindex, char *ebuf);
339214518Srpaulo#ifdef IW_MODE_MONITOR
340190225Srpaulostatic int	has_wext(int sock_fd, const char *device, char *ebuf);
341214518Srpaulo#endif /* IW_MODE_MONITOR */
342214518Srpaulostatic int	enter_rfmon_mode(pcap_t *handle, int sock_fd,
343190225Srpaulo    const char *device);
344214518Srpaulo#endif /* HAVE_PF_PACKET_SOCKETS */
34575107Sfennerstatic int 	iface_bind_old(int fd, const char *device, char *ebuf);
34675107Sfenner
34775107Sfenner#ifdef SO_ATTACH_FILTER
348214518Srpaulostatic int	fix_program(pcap_t *handle, struct sock_fprog *fcode,
349214518Srpaulo    int is_mapped);
35075107Sfennerstatic int	fix_offset(struct bpf_insn *p);
35198530Sfennerstatic int	set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
35298530Sfennerstatic int	reset_kernel_filter(pcap_t *handle);
35398530Sfenner
35498530Sfennerstatic struct sock_filter	total_insn
35598530Sfenner	= BPF_STMT(BPF_RET | BPF_K, 0);
35698530Sfennerstatic struct sock_fprog	total_fcode
35798530Sfenner	= { 1, &total_insn };
35875107Sfenner#endif
35975107Sfenner
36075107Sfennerpcap_t *
361190225Srpaulopcap_create(const char *device, char *ebuf)
36226175Sfenner{
363190225Srpaulo	pcap_t *handle;
36498530Sfenner
365214518Srpaulo	/*
366214518Srpaulo	 * A null device name is equivalent to the "any" device.
367214518Srpaulo	 */
368214518Srpaulo	if (device == NULL)
369214518Srpaulo		device = "any";
370214518Srpaulo
371127664Sbms#ifdef HAVE_DAG_API
372127664Sbms	if (strstr(device, "dag")) {
373190225Srpaulo		return dag_create(device, ebuf);
374127664Sbms	}
375127664Sbms#endif /* HAVE_DAG_API */
376127664Sbms
377147894Ssam#ifdef HAVE_SEPTEL_API
378147894Ssam	if (strstr(device, "septel")) {
379190225Srpaulo		return septel_create(device, ebuf);
380147894Ssam	}
381147894Ssam#endif /* HAVE_SEPTEL_API */
38226175Sfenner
383214518Srpaulo#ifdef HAVE_SNF_API
384214518Srpaulo        handle = snf_create(device, ebuf);
385214518Srpaulo        if (strstr(device, "snf") || handle != NULL)
386214518Srpaulo		return handle;
387214518Srpaulo
388214518Srpaulo#endif /* HAVE_SNF_API */
389214518Srpaulo
390190225Srpaulo#ifdef PCAP_SUPPORT_BT
391190225Srpaulo	if (strstr(device, "bluetooth")) {
392190225Srpaulo		return bt_create(device, ebuf);
393190225Srpaulo	}
394190225Srpaulo#endif
395147894Ssam
396214518Srpaulo#ifdef PCAP_SUPPORT_CAN
397214518Srpaulo	if (strstr(device, "can") || strstr(device, "vcan")) {
398214518Srpaulo		return can_create(device, ebuf);
399214518Srpaulo	}
400214518Srpaulo#endif
401214518Srpaulo
402190225Srpaulo#ifdef PCAP_SUPPORT_USB
403214518Srpaulo	if (strstr(device, "usbmon")) {
404190225Srpaulo		return usb_create(device, ebuf);
405190225Srpaulo	}
406190225Srpaulo#endif
407190225Srpaulo
408190225Srpaulo	handle = pcap_create_common(device, ebuf);
409190225Srpaulo	if (handle == NULL)
41075107Sfenner		return NULL;
411190225Srpaulo
412190225Srpaulo	handle->activate_op = pcap_activate_linux;
413190225Srpaulo	handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
414190225Srpaulo	return handle;
415190225Srpaulo}
416190225Srpaulo
417214518Srpaulo#ifdef HAVE_LIBNL
418214518Srpaulo/*
419214518Srpaulo	 *
420214518Srpaulo	 * If interface {if} is a mac80211 driver, the file
421214518Srpaulo	 * /sys/class/net/{if}/phy80211 is a symlink to
422214518Srpaulo	 * /sys/class/ieee80211/{phydev}, for some {phydev}.
423214518Srpaulo	 *
424214518Srpaulo	 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
425214518Srpaulo	 * least, has a "wmaster0" device and a "wlan0" device; the
426214518Srpaulo	 * latter is the one with the IP address.  Both show up in
427214518Srpaulo	 * "tcpdump -D" output.  Capturing on the wmaster0 device
428214518Srpaulo	 * captures with 802.11 headers.
429214518Srpaulo	 *
430214518Srpaulo	 * airmon-ng searches through /sys/class/net for devices named
431214518Srpaulo	 * monN, starting with mon0; as soon as one *doesn't* exist,
432214518Srpaulo	 * it chooses that as the monitor device name.  If the "iw"
433214518Srpaulo	 * command exists, it does "iw dev {if} interface add {monif}
434214518Srpaulo	 * type monitor", where {monif} is the monitor device.  It
435214518Srpaulo	 * then (sigh) sleeps .1 second, and then configures the
436214518Srpaulo	 * device up.  Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
437214518Srpaulo	 * is a file, it writes {mondev}, without a newline, to that file,
438214518Srpaulo	 * and again (sigh) sleeps .1 second, and then iwconfig's that
439214518Srpaulo	 * device into monitor mode and configures it up.  Otherwise,
440214518Srpaulo	 * you can't do monitor mode.
441214518Srpaulo	 *
442214518Srpaulo	 * All these devices are "glued" together by having the
443214518Srpaulo	 * /sys/class/net/{device}/phy80211 links pointing to the same
444214518Srpaulo	 * place, so, given a wmaster, wlan, or mon device, you can
445214518Srpaulo	 * find the other devices by looking for devices with
446214518Srpaulo	 * the same phy80211 link.
447214518Srpaulo	 *
448214518Srpaulo	 * To turn monitor mode off, delete the monitor interface,
449214518Srpaulo	 * either with "iw dev {monif} interface del" or by sending
450214518Srpaulo	 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
451214518Srpaulo	 *
452214518Srpaulo	 * Note: if you try to create a monitor device named "monN", and
453214518Srpaulo	 * there's already a "monN" device, it fails, as least with
454214518Srpaulo	 * the netlink interface (which is what iw uses), with a return
455214518Srpaulo	 * value of -ENFILE.  (Return values are negative errnos.)  We
456214518Srpaulo	 * could probably use that to find an unused device.
457214518Srpaulo	 *
458214518Srpaulo	 * Yes, you can have multiple monitor devices for a given
459214518Srpaulo	 * physical device.
460214518Srpaulo*/
461214518Srpaulo
462214518Srpaulo/*
463214518Srpaulo * Is this a mac80211 device?  If so, fill in the physical device path and
464214518Srpaulo * return 1; if not, return 0.  On an error, fill in handle->errbuf and
465214518Srpaulo * return PCAP_ERROR.
466214518Srpaulo */
467190225Srpaulostatic int
468214518Srpauloget_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
469214518Srpaulo    size_t phydev_max_pathlen)
470190225Srpaulo{
471214518Srpaulo	char *pathstr;
472214518Srpaulo	ssize_t bytes_read;
473214518Srpaulo
474214518Srpaulo	/*
475214518Srpaulo	 * Generate the path string for the symlink to the physical device.
476214518Srpaulo	 */
477214518Srpaulo	if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
478214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
479214518Srpaulo		    "%s: Can't generate path name string for /sys/class/net device",
480214518Srpaulo		    device);
481214518Srpaulo		return PCAP_ERROR;
482214518Srpaulo	}
483214518Srpaulo	bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
484214518Srpaulo	if (bytes_read == -1) {
485214518Srpaulo		if (errno == ENOENT || errno == EINVAL) {
486214518Srpaulo			/*
487214518Srpaulo			 * Doesn't exist, or not a symlink; assume that
488214518Srpaulo			 * means it's not a mac80211 device.
489214518Srpaulo			 */
490214518Srpaulo			free(pathstr);
491214518Srpaulo			return 0;
492214518Srpaulo		}
493214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
494214518Srpaulo		    "%s: Can't readlink %s: %s", device, pathstr,
495214518Srpaulo		    strerror(errno));
496214518Srpaulo		free(pathstr);
497214518Srpaulo		return PCAP_ERROR;
498214518Srpaulo	}
499214518Srpaulo	free(pathstr);
500214518Srpaulo	phydev_path[bytes_read] = '\0';
501214518Srpaulo	return 1;
502214518Srpaulo}
503214518Srpaulo
504214518Srpaulostruct nl80211_state {
505214518Srpaulo	struct nl_handle *nl_handle;
506214518Srpaulo	struct nl_cache *nl_cache;
507214518Srpaulo	struct genl_family *nl80211;
508214518Srpaulo};
509214518Srpaulo
510214518Srpaulostatic int
511214518Srpaulonl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
512214518Srpaulo{
513214518Srpaulo	state->nl_handle = nl_handle_alloc();
514214518Srpaulo	if (!state->nl_handle) {
515214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
516214518Srpaulo		    "%s: failed to allocate netlink handle", device);
517214518Srpaulo		return PCAP_ERROR;
518214518Srpaulo	}
519214518Srpaulo
520214518Srpaulo	if (genl_connect(state->nl_handle)) {
521214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
522214518Srpaulo		    "%s: failed to connect to generic netlink", device);
523214518Srpaulo		goto out_handle_destroy;
524214518Srpaulo	}
525214518Srpaulo
526214518Srpaulo	state->nl_cache = genl_ctrl_alloc_cache(state->nl_handle);
527214518Srpaulo	if (!state->nl_cache) {
528214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
529214518Srpaulo		    "%s: failed to allocate generic netlink cache", device);
530214518Srpaulo		goto out_handle_destroy;
531214518Srpaulo	}
532214518Srpaulo
533214518Srpaulo	state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
534214518Srpaulo	if (!state->nl80211) {
535214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
536214518Srpaulo		    "%s: nl80211 not found", device);
537214518Srpaulo		goto out_cache_free;
538214518Srpaulo	}
539214518Srpaulo
540214518Srpaulo	return 0;
541214518Srpaulo
542214518Srpauloout_cache_free:
543214518Srpaulo	nl_cache_free(state->nl_cache);
544214518Srpauloout_handle_destroy:
545214518Srpaulo	nl_handle_destroy(state->nl_handle);
546214518Srpaulo	return PCAP_ERROR;
547214518Srpaulo}
548214518Srpaulo
549214518Srpaulostatic void
550214518Srpaulonl80211_cleanup(struct nl80211_state *state)
551214518Srpaulo{
552214518Srpaulo	genl_family_put(state->nl80211);
553214518Srpaulo	nl_cache_free(state->nl_cache);
554214518Srpaulo	nl_handle_destroy(state->nl_handle);
555214518Srpaulo}
556214518Srpaulo
557214518Srpaulostatic int
558214518Srpauloadd_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
559214518Srpaulo    const char *device, const char *mondevice)
560214518Srpaulo{
561214518Srpaulo	int ifindex;
562214518Srpaulo	struct nl_msg *msg;
563214518Srpaulo	int err;
564214518Srpaulo
565214518Srpaulo	ifindex = iface_get_id(sock_fd, device, handle->errbuf);
566214518Srpaulo	if (ifindex == -1)
567214518Srpaulo		return PCAP_ERROR;
568214518Srpaulo
569214518Srpaulo	msg = nlmsg_alloc();
570214518Srpaulo	if (!msg) {
571214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
572214518Srpaulo		    "%s: failed to allocate netlink msg", device);
573214518Srpaulo		return PCAP_ERROR;
574214518Srpaulo	}
575214518Srpaulo
576214518Srpaulo	genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
577214518Srpaulo		    0, NL80211_CMD_NEW_INTERFACE, 0);
578214518Srpaulo	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
579214518Srpaulo	NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
580214518Srpaulo	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
581214518Srpaulo
582214518Srpaulo	err = nl_send_auto_complete(state->nl_handle, msg);
583214518Srpaulo	if (err < 0) {
584214518Srpaulo		if (err == -ENFILE) {
585214518Srpaulo			/*
586214518Srpaulo			 * Device not available; our caller should just
587214518Srpaulo			 * keep trying.
588214518Srpaulo			 */
589214518Srpaulo			nlmsg_free(msg);
590214518Srpaulo			return 0;
591214518Srpaulo		} else {
592214518Srpaulo			/*
593214518Srpaulo			 * Real failure, not just "that device is not
594214518Srpaulo			 * available.
595214518Srpaulo			 */
596214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
597214518Srpaulo			    "%s: nl_send_auto_complete failed adding %s interface: %s",
598214518Srpaulo			    device, mondevice, strerror(-err));
599214518Srpaulo			nlmsg_free(msg);
600214518Srpaulo			return PCAP_ERROR;
601214518Srpaulo		}
602214518Srpaulo	}
603214518Srpaulo	err = nl_wait_for_ack(state->nl_handle);
604214518Srpaulo	if (err < 0) {
605214518Srpaulo		if (err == -ENFILE) {
606214518Srpaulo			/*
607214518Srpaulo			 * Device not available; our caller should just
608214518Srpaulo			 * keep trying.
609214518Srpaulo			 */
610214518Srpaulo			nlmsg_free(msg);
611214518Srpaulo			return 0;
612214518Srpaulo		} else {
613214518Srpaulo			/*
614214518Srpaulo			 * Real failure, not just "that device is not
615214518Srpaulo			 * available.
616214518Srpaulo			 */
617214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
618214518Srpaulo			    "%s: nl_wait_for_ack failed adding %s interface: %s",
619214518Srpaulo			    device, mondevice, strerror(-err));
620214518Srpaulo			nlmsg_free(msg);
621214518Srpaulo			return PCAP_ERROR;
622214518Srpaulo		}
623214518Srpaulo	}
624214518Srpaulo
625214518Srpaulo	/*
626214518Srpaulo	 * Success.
627214518Srpaulo	 */
628214518Srpaulo	nlmsg_free(msg);
629214518Srpaulo	return 1;
630214518Srpaulo
631214518Srpaulonla_put_failure:
632214518Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
633214518Srpaulo	    "%s: nl_put failed adding %s interface",
634214518Srpaulo	    device, mondevice);
635214518Srpaulo	nlmsg_free(msg);
636214518Srpaulo	return PCAP_ERROR;
637214518Srpaulo}
638214518Srpaulo
639214518Srpaulostatic int
640214518Srpaulodel_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
641214518Srpaulo    const char *device, const char *mondevice)
642214518Srpaulo{
643214518Srpaulo	int ifindex;
644214518Srpaulo	struct nl_msg *msg;
645214518Srpaulo	int err;
646214518Srpaulo
647214518Srpaulo	ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
648214518Srpaulo	if (ifindex == -1)
649214518Srpaulo		return PCAP_ERROR;
650214518Srpaulo
651214518Srpaulo	msg = nlmsg_alloc();
652214518Srpaulo	if (!msg) {
653214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
654214518Srpaulo		    "%s: failed to allocate netlink msg", device);
655214518Srpaulo		return PCAP_ERROR;
656214518Srpaulo	}
657214518Srpaulo
658214518Srpaulo	genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
659214518Srpaulo		    0, NL80211_CMD_DEL_INTERFACE, 0);
660214518Srpaulo	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
661214518Srpaulo
662214518Srpaulo	err = nl_send_auto_complete(state->nl_handle, msg);
663214518Srpaulo	if (err < 0) {
664214518Srpaulo		if (err == -ENFILE) {
665214518Srpaulo			/*
666214518Srpaulo			 * Device not available; our caller should just
667214518Srpaulo			 * keep trying.
668214518Srpaulo			 */
669214518Srpaulo			nlmsg_free(msg);
670214518Srpaulo			return 0;
671214518Srpaulo		} else {
672214518Srpaulo			/*
673214518Srpaulo			 * Real failure, not just "that device is not
674214518Srpaulo			 * available.
675214518Srpaulo			 */
676214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
677214518Srpaulo			    "%s: nl_send_auto_complete failed deleting %s interface: %s",
678214518Srpaulo			    device, mondevice, strerror(-err));
679214518Srpaulo			nlmsg_free(msg);
680214518Srpaulo			return PCAP_ERROR;
681214518Srpaulo		}
682214518Srpaulo	}
683214518Srpaulo	err = nl_wait_for_ack(state->nl_handle);
684214518Srpaulo	if (err < 0) {
685214518Srpaulo		if (err == -ENFILE) {
686214518Srpaulo			/*
687214518Srpaulo			 * Device not available; our caller should just
688214518Srpaulo			 * keep trying.
689214518Srpaulo			 */
690214518Srpaulo			nlmsg_free(msg);
691214518Srpaulo			return 0;
692214518Srpaulo		} else {
693214518Srpaulo			/*
694214518Srpaulo			 * Real failure, not just "that device is not
695214518Srpaulo			 * available.
696214518Srpaulo			 */
697214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
698214518Srpaulo			    "%s: nl_wait_for_ack failed adding %s interface: %s",
699214518Srpaulo			    device, mondevice, strerror(-err));
700214518Srpaulo			nlmsg_free(msg);
701214518Srpaulo			return PCAP_ERROR;
702214518Srpaulo		}
703214518Srpaulo	}
704214518Srpaulo
705214518Srpaulo	/*
706214518Srpaulo	 * Success.
707214518Srpaulo	 */
708214518Srpaulo	nlmsg_free(msg);
709214518Srpaulo	return 1;
710214518Srpaulo
711214518Srpaulonla_put_failure:
712214518Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
713214518Srpaulo	    "%s: nl_put failed deleting %s interface",
714214518Srpaulo	    device, mondevice);
715214518Srpaulo	nlmsg_free(msg);
716214518Srpaulo	return PCAP_ERROR;
717214518Srpaulo}
718214518Srpaulo
719214518Srpaulostatic int
720214518Srpauloenter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
721214518Srpaulo{
722214518Srpaulo	int ret;
723214518Srpaulo	char phydev_path[PATH_MAX+1];
724214518Srpaulo	struct nl80211_state nlstate;
725214518Srpaulo	struct ifreq ifr;
726214518Srpaulo	u_int n;
727214518Srpaulo
728214518Srpaulo	/*
729214518Srpaulo	 * Is this a mac80211 device?
730214518Srpaulo	 */
731214518Srpaulo	ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
732214518Srpaulo	if (ret < 0)
733214518Srpaulo		return ret;	/* error */
734214518Srpaulo	if (ret == 0)
735214518Srpaulo		return 0;	/* no error, but not mac80211 device */
736214518Srpaulo
737214518Srpaulo	/*
738214518Srpaulo	 * XXX - is this already a monN device?
739214518Srpaulo	 * If so, we're done.
740214518Srpaulo	 * Is that determined by old Wireless Extensions ioctls?
741214518Srpaulo	 */
742214518Srpaulo
743214518Srpaulo	/*
744214518Srpaulo	 * OK, it's apparently a mac80211 device.
745214518Srpaulo	 * Try to find an unused monN device for it.
746214518Srpaulo	 */
747214518Srpaulo	ret = nl80211_init(handle, &nlstate, device);
748214518Srpaulo	if (ret != 0)
749214518Srpaulo		return ret;
750214518Srpaulo	for (n = 0; n < UINT_MAX; n++) {
751214518Srpaulo		/*
752214518Srpaulo		 * Try mon{n}.
753214518Srpaulo		 */
754214518Srpaulo		char mondevice[3+10+1];	/* mon{UINT_MAX}\0 */
755214518Srpaulo
756214518Srpaulo		snprintf(mondevice, sizeof mondevice, "mon%u", n);
757214518Srpaulo		ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
758214518Srpaulo		if (ret == 1) {
759214518Srpaulo			handle->md.mondevice = strdup(mondevice);
760214518Srpaulo			goto added;
761214518Srpaulo		}
762214518Srpaulo		if (ret < 0) {
763214518Srpaulo			/*
764214518Srpaulo			 * Hard failure.  Just return ret; handle->errbuf
765214518Srpaulo			 * has already been set.
766214518Srpaulo			 */
767214518Srpaulo			nl80211_cleanup(&nlstate);
768214518Srpaulo			return ret;
769214518Srpaulo		}
770214518Srpaulo	}
771214518Srpaulo
772214518Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
773214518Srpaulo	    "%s: No free monN interfaces", device);
774214518Srpaulo	nl80211_cleanup(&nlstate);
775214518Srpaulo	return PCAP_ERROR;
776214518Srpaulo
777214518Srpauloadded:
778214518Srpaulo
779214518Srpaulo#if 0
780214518Srpaulo	/*
781214518Srpaulo	 * Sleep for .1 seconds.
782214518Srpaulo	 */
783214518Srpaulo	delay.tv_sec = 0;
784214518Srpaulo	delay.tv_nsec = 500000000;
785214518Srpaulo	nanosleep(&delay, NULL);
786214518Srpaulo#endif
787214518Srpaulo
788214518Srpaulo	/*
789214518Srpaulo	 * Now configure the monitor interface up.
790214518Srpaulo	 */
791214518Srpaulo	memset(&ifr, 0, sizeof(ifr));
792214518Srpaulo	strncpy(ifr.ifr_name, handle->md.mondevice, sizeof(ifr.ifr_name));
793214518Srpaulo	if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
794214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
795214518Srpaulo		    "%s: Can't get flags for %s: %s", device,
796214518Srpaulo		    handle->md.mondevice, strerror(errno));
797214518Srpaulo		del_mon_if(handle, sock_fd, &nlstate, device,
798214518Srpaulo		    handle->md.mondevice);
799214518Srpaulo		nl80211_cleanup(&nlstate);
800214518Srpaulo		return PCAP_ERROR;
801214518Srpaulo	}
802214518Srpaulo	ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
803214518Srpaulo	if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
804214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
805214518Srpaulo		    "%s: Can't set flags for %s: %s", device,
806214518Srpaulo		    handle->md.mondevice, strerror(errno));
807214518Srpaulo		del_mon_if(handle, sock_fd, &nlstate, device,
808214518Srpaulo		    handle->md.mondevice);
809214518Srpaulo		nl80211_cleanup(&nlstate);
810214518Srpaulo		return PCAP_ERROR;
811214518Srpaulo	}
812214518Srpaulo
813214518Srpaulo	/*
814214518Srpaulo	 * Success.  Clean up the libnl state.
815214518Srpaulo	 */
816214518Srpaulo	nl80211_cleanup(&nlstate);
817214518Srpaulo
818214518Srpaulo	/*
819214518Srpaulo	 * Note that we have to delete the monitor device when we close
820214518Srpaulo	 * the handle.
821214518Srpaulo	 */
822214518Srpaulo	handle->md.must_do_on_close |= MUST_DELETE_MONIF;
823214518Srpaulo
824214518Srpaulo	/*
825214518Srpaulo	 * Add this to the list of pcaps to close when we exit.
826214518Srpaulo	 */
827214518Srpaulo	pcap_add_to_pcaps_to_close(handle);
828214518Srpaulo
829214518Srpaulo	return 1;
830214518Srpaulo}
831214518Srpaulo#endif /* HAVE_LIBNL */
832214518Srpaulo
833214518Srpaulostatic int
834214518Srpaulopcap_can_set_rfmon_linux(pcap_t *handle)
835214518Srpaulo{
836214518Srpaulo#ifdef HAVE_LIBNL
837214518Srpaulo	char phydev_path[PATH_MAX+1];
838214518Srpaulo	int ret;
839214518Srpaulo#endif
840190225Srpaulo#ifdef IW_MODE_MONITOR
841190225Srpaulo	int sock_fd;
842190225Srpaulo	struct iwreq ireq;
843190225Srpaulo#endif
844190225Srpaulo
845214518Srpaulo	if (strcmp(handle->opt.source, "any") == 0) {
846190225Srpaulo		/*
847214518Srpaulo		 * Monitor mode makes no sense on the "any" device.
848190225Srpaulo		 */
849190225Srpaulo		return 0;
85075107Sfenner	}
85175107Sfenner
852214518Srpaulo#ifdef HAVE_LIBNL
853214518Srpaulo	/*
854214518Srpaulo	 * Bleah.  There doesn't seem to be a way to ask a mac80211
855214518Srpaulo	 * device, through libnl, whether it supports monitor mode;
856214518Srpaulo	 * we'll just check whether the device appears to be a
857214518Srpaulo	 * mac80211 device and, if so, assume the device supports
858214518Srpaulo	 * monitor mode.
859214518Srpaulo	 *
860214518Srpaulo	 * wmaster devices don't appear to support the Wireless
861214518Srpaulo	 * Extensions, but we can create a mon device for a
862214518Srpaulo	 * wmaster device, so we don't bother checking whether
863214518Srpaulo	 * a mac80211 device supports the Wireless Extensions.
864214518Srpaulo	 */
865214518Srpaulo	ret = get_mac80211_phydev(handle, handle->opt.source, phydev_path,
866214518Srpaulo	    PATH_MAX);
867214518Srpaulo	if (ret < 0)
868214518Srpaulo		return ret;	/* error */
869214518Srpaulo	if (ret == 1)
870214518Srpaulo		return 1;	/* mac80211 device */
871214518Srpaulo#endif
872214518Srpaulo
873190225Srpaulo#ifdef IW_MODE_MONITOR
874190225Srpaulo	/*
875190225Srpaulo	 * Bleah.  There doesn't appear to be an ioctl to use to ask
876190225Srpaulo	 * whether a device supports monitor mode; we'll just do
877190225Srpaulo	 * SIOCGIWMODE and, if it succeeds, assume the device supports
878190225Srpaulo	 * monitor mode.
879190225Srpaulo	 *
880190225Srpaulo	 * Open a socket on which to attempt to get the mode.
881190225Srpaulo	 * (We assume that if we have Wireless Extensions support
882190225Srpaulo	 * we also have PF_PACKET support.)
883190225Srpaulo	 */
884190225Srpaulo	sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
885190225Srpaulo	if (sock_fd == -1) {
886214518Srpaulo		(void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
887190225Srpaulo		    "socket: %s", pcap_strerror(errno));
888190225Srpaulo		return PCAP_ERROR;
889190225Srpaulo	}
89075107Sfenner
891190225Srpaulo	/*
892190225Srpaulo	 * Attempt to get the current mode.
893190225Srpaulo	 */
894214518Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, handle->opt.source,
895190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
896190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
897190225Srpaulo	if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
898190225Srpaulo		/*
899190225Srpaulo		 * Well, we got the mode; assume we can set it.
900190225Srpaulo		 */
901190225Srpaulo		close(sock_fd);
902190225Srpaulo		return 1;
903190225Srpaulo	}
904190225Srpaulo	if (errno == ENODEV) {
905190225Srpaulo		/* The device doesn't even exist. */
906214518Srpaulo		(void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
907214518Srpaulo		    "SIOCGIWMODE failed: %s", pcap_strerror(errno));
908190225Srpaulo		close(sock_fd);
909190225Srpaulo		return PCAP_ERROR_NO_SUCH_DEVICE;
910190225Srpaulo	}
911190225Srpaulo	close(sock_fd);
912190225Srpaulo#endif
913190225Srpaulo	return 0;
914190225Srpaulo}
91575107Sfenner
916190225Srpaulo/*
917214518Srpaulo * Grabs the number of dropped packets by the interface from /proc/net/dev.
918214518Srpaulo *
919214518Srpaulo * XXX - what about /sys/class/net/{interface name}/rx_*?  There are
920214518Srpaulo * individual devices giving, in ASCII, various rx_ and tx_ statistics.
921214518Srpaulo *
922214518Srpaulo * Or can we get them in binary form from netlink?
923214518Srpaulo */
924214518Srpaulostatic long int
925214518Srpaulolinux_if_drops(const char * if_name)
926214518Srpaulo{
927214518Srpaulo	char buffer[512];
928214518Srpaulo	char * bufptr;
929214518Srpaulo	FILE * file;
930214518Srpaulo	int field_to_convert = 3, if_name_sz = strlen(if_name);
931214518Srpaulo	long int dropped_pkts = 0;
932214518Srpaulo
933214518Srpaulo	file = fopen("/proc/net/dev", "r");
934214518Srpaulo	if (!file)
935214518Srpaulo		return 0;
936214518Srpaulo
937214518Srpaulo	while (!dropped_pkts && fgets( buffer, sizeof(buffer), file ))
938214518Srpaulo	{
939214518Srpaulo		/* 	search for 'bytes' -- if its in there, then
940214518Srpaulo			that means we need to grab the fourth field. otherwise
941214518Srpaulo			grab the third field. */
942214518Srpaulo		if (field_to_convert != 4 && strstr(buffer, "bytes"))
943214518Srpaulo		{
944214518Srpaulo			field_to_convert = 4;
945214518Srpaulo			continue;
946214518Srpaulo		}
947214518Srpaulo
948214518Srpaulo		/* find iface and make sure it actually matches -- space before the name and : after it */
949214518Srpaulo		if ((bufptr = strstr(buffer, if_name)) &&
950214518Srpaulo			(bufptr == buffer || *(bufptr-1) == ' ') &&
951214518Srpaulo			*(bufptr + if_name_sz) == ':')
952214518Srpaulo		{
953214518Srpaulo			bufptr = bufptr + if_name_sz + 1;
954214518Srpaulo
955214518Srpaulo			/* grab the nth field from it */
956214518Srpaulo			while( --field_to_convert && *bufptr != '\0')
957214518Srpaulo			{
958214518Srpaulo				while (*bufptr != '\0' && *(bufptr++) == ' ');
959214518Srpaulo				while (*bufptr != '\0' && *(bufptr++) != ' ');
960214518Srpaulo			}
961214518Srpaulo
962214518Srpaulo			/* get rid of any final spaces */
963214518Srpaulo			while (*bufptr != '\0' && *bufptr == ' ') bufptr++;
964214518Srpaulo
965214518Srpaulo			if (*bufptr != '\0')
966214518Srpaulo				dropped_pkts = strtol(bufptr, NULL, 10);
967214518Srpaulo
968214518Srpaulo			break;
969214518Srpaulo		}
970214518Srpaulo	}
971214518Srpaulo
972214518Srpaulo	fclose(file);
973214518Srpaulo	return dropped_pkts;
974214518Srpaulo}
975214518Srpaulo
976214518Srpaulo
977214518Srpaulo/*
978190225Srpaulo * With older kernels promiscuous mode is kind of interesting because we
979190225Srpaulo * have to reset the interface before exiting. The problem can't really
980190225Srpaulo * be solved without some daemon taking care of managing usage counts.
981190225Srpaulo * If we put the interface into promiscuous mode, we set a flag indicating
982190225Srpaulo * that we must take it out of that mode when the interface is closed,
983190225Srpaulo * and, when closing the interface, if that flag is set we take it out
984190225Srpaulo * of promiscuous mode.
985190225Srpaulo *
986190225Srpaulo * Even with newer kernels, we have the same issue with rfmon mode.
987190225Srpaulo */
988190225Srpaulo
989190225Srpaulostatic void	pcap_cleanup_linux( pcap_t *handle )
990190225Srpaulo{
991190225Srpaulo	struct ifreq	ifr;
992214518Srpaulo#ifdef HAVE_LIBNL
993214518Srpaulo	struct nl80211_state nlstate;
994214518Srpaulo	int ret;
995214518Srpaulo#endif /* HAVE_LIBNL */
996190225Srpaulo#ifdef IW_MODE_MONITOR
997190225Srpaulo	struct iwreq ireq;
998214518Srpaulo#endif /* IW_MODE_MONITOR */
999190225Srpaulo
1000214518Srpaulo	if (handle->md.must_do_on_close != 0) {
1001190225Srpaulo		/*
1002190225Srpaulo		 * There's something we have to do when closing this
1003190225Srpaulo		 * pcap_t.
1004190225Srpaulo		 */
1005214518Srpaulo		if (handle->md.must_do_on_close & MUST_CLEAR_PROMISC) {
1006190225Srpaulo			/*
1007190225Srpaulo			 * We put the interface into promiscuous mode;
1008190225Srpaulo			 * take it out of promiscuous mode.
1009190225Srpaulo			 *
1010190225Srpaulo			 * XXX - if somebody else wants it in promiscuous
1011190225Srpaulo			 * mode, this code cannot know that, so it'll take
1012190225Srpaulo			 * it out of promiscuous mode.  That's not fixable
1013190225Srpaulo			 * in 2.0[.x] kernels.
1014190225Srpaulo			 */
1015190225Srpaulo			memset(&ifr, 0, sizeof(ifr));
1016190225Srpaulo			strncpy(ifr.ifr_name, handle->md.device,
1017190225Srpaulo			    sizeof(ifr.ifr_name));
1018190225Srpaulo			if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1019190225Srpaulo				fprintf(stderr,
1020190225Srpaulo				    "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1021190225Srpaulo				    "Please adjust manually.\n"
1022190225Srpaulo				    "Hint: This can't happen with Linux >= 2.2.0.\n",
1023190225Srpaulo				    strerror(errno));
1024190225Srpaulo			} else {
1025190225Srpaulo				if (ifr.ifr_flags & IFF_PROMISC) {
1026190225Srpaulo					/*
1027190225Srpaulo					 * Promiscuous mode is currently on;
1028190225Srpaulo					 * turn it off.
1029190225Srpaulo					 */
1030190225Srpaulo					ifr.ifr_flags &= ~IFF_PROMISC;
1031190225Srpaulo					if (ioctl(handle->fd, SIOCSIFFLAGS,
1032190225Srpaulo					    &ifr) == -1) {
1033190225Srpaulo						fprintf(stderr,
1034190225Srpaulo						    "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1035190225Srpaulo						    "Please adjust manually.\n"
1036190225Srpaulo						    "Hint: This can't happen with Linux >= 2.2.0.\n",
1037190225Srpaulo						    strerror(errno));
1038190225Srpaulo					}
1039190225Srpaulo				}
1040190225Srpaulo			}
1041190225Srpaulo		}
1042190225Srpaulo
1043214518Srpaulo#ifdef HAVE_LIBNL
1044214518Srpaulo		if (handle->md.must_do_on_close & MUST_DELETE_MONIF) {
1045214518Srpaulo			ret = nl80211_init(handle, &nlstate, handle->md.device);
1046214518Srpaulo			if (ret >= 0) {
1047214518Srpaulo				ret = del_mon_if(handle, handle->fd, &nlstate,
1048214518Srpaulo				    handle->md.device, handle->md.mondevice);
1049214518Srpaulo				nl80211_cleanup(&nlstate);
1050214518Srpaulo			}
1051214518Srpaulo			if (ret < 0) {
1052214518Srpaulo				fprintf(stderr,
1053214518Srpaulo				    "Can't delete monitor interface %s (%s).\n"
1054214518Srpaulo				    "Please delete manually.\n",
1055214518Srpaulo				    handle->md.mondevice, handle->errbuf);
1056214518Srpaulo			}
1057214518Srpaulo		}
1058214518Srpaulo#endif /* HAVE_LIBNL */
1059214518Srpaulo
1060190225Srpaulo#ifdef IW_MODE_MONITOR
1061214518Srpaulo		if (handle->md.must_do_on_close & MUST_CLEAR_RFMON) {
1062190225Srpaulo			/*
1063190225Srpaulo			 * We put the interface into rfmon mode;
1064190225Srpaulo			 * take it out of rfmon mode.
1065190225Srpaulo			 *
1066190225Srpaulo			 * XXX - if somebody else wants it in rfmon
1067190225Srpaulo			 * mode, this code cannot know that, so it'll take
1068190225Srpaulo			 * it out of rfmon mode.
1069190225Srpaulo			 */
1070190225Srpaulo			strncpy(ireq.ifr_ifrn.ifrn_name, handle->md.device,
1071190225Srpaulo			    sizeof ireq.ifr_ifrn.ifrn_name);
1072190225Srpaulo			ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1]
1073190225Srpaulo			    = 0;
1074190225Srpaulo			ireq.u.mode = handle->md.oldmode;
1075190225Srpaulo			if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
1076190225Srpaulo				/*
1077190225Srpaulo				 * Scientist, you've failed.
1078190225Srpaulo				 */
1079190225Srpaulo				fprintf(stderr,
1080190225Srpaulo				    "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
1081190225Srpaulo				    "Please adjust manually.\n",
1082190225Srpaulo				    strerror(errno));
1083190225Srpaulo			}
1084190225Srpaulo		}
1085214518Srpaulo#endif /* IW_MODE_MONITOR */
1086190225Srpaulo
1087190225Srpaulo		/*
1088190225Srpaulo		 * Take this pcap out of the list of pcaps for which we
1089190225Srpaulo		 * have to take the interface out of some mode.
1090190225Srpaulo		 */
1091190225Srpaulo		pcap_remove_from_pcaps_to_close(handle);
1092190225Srpaulo	}
1093190225Srpaulo
1094214518Srpaulo	if (handle->md.mondevice != NULL) {
1095214518Srpaulo		free(handle->md.mondevice);
1096214518Srpaulo		handle->md.mondevice = NULL;
1097214518Srpaulo	}
1098190225Srpaulo	if (handle->md.device != NULL) {
1099190225Srpaulo		free(handle->md.device);
1100190225Srpaulo		handle->md.device = NULL;
1101190225Srpaulo	}
1102190225Srpaulo	pcap_cleanup_live_common(handle);
1103190225Srpaulo}
1104190225Srpaulo
1105190225Srpaulo/*
1106190225Srpaulo *  Get a handle for a live capture from the given device. You can
1107190225Srpaulo *  pass NULL as device to get all packages (without link level
1108190225Srpaulo *  information of course). If you pass 1 as promisc the interface
1109190225Srpaulo *  will be set to promiscous mode (XXX: I think this usage should
1110190225Srpaulo *  be deprecated and functions be added to select that later allow
1111190225Srpaulo *  modification of that values -- Torsten).
1112190225Srpaulo */
1113190225Srpaulostatic int
1114190225Srpaulopcap_activate_linux(pcap_t *handle)
1115190225Srpaulo{
1116190225Srpaulo	const char	*device;
1117190225Srpaulo	int		status = 0;
1118190225Srpaulo
1119190225Srpaulo	device = handle->opt.source;
1120190225Srpaulo
1121190225Srpaulo	handle->inject_op = pcap_inject_linux;
1122190225Srpaulo	handle->setfilter_op = pcap_setfilter_linux;
1123190225Srpaulo	handle->setdirection_op = pcap_setdirection_linux;
1124190225Srpaulo	handle->set_datalink_op = NULL;	/* can't change data link type */
1125190225Srpaulo	handle->getnonblock_op = pcap_getnonblock_fd;
1126190225Srpaulo	handle->setnonblock_op = pcap_setnonblock_fd;
1127190225Srpaulo	handle->cleanup_op = pcap_cleanup_linux;
1128190225Srpaulo	handle->read_op = pcap_read_linux;
1129190225Srpaulo	handle->stats_op = pcap_stats_linux;
1130190225Srpaulo
113175107Sfenner	/*
1132214518Srpaulo	 * The "any" device is a special device which causes us not
1133214518Srpaulo	 * to bind to a particular device and thus to look at all
1134214518Srpaulo	 * devices.
113575107Sfenner	 */
1136214518Srpaulo	if (strcmp(device, "any") == 0) {
1137190225Srpaulo		if (handle->opt.promisc) {
1138190225Srpaulo			handle->opt.promisc = 0;
113998530Sfenner			/* Just a warning. */
1140190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
114198530Sfenner			    "Promiscuous mode not supported on the \"any\" device");
1142190225Srpaulo			status = PCAP_WARNING_PROMISC_NOTSUP;
114398530Sfenner		}
1144214518Srpaulo	}
1145127664Sbms
1146214518Srpaulo	handle->md.device	= strdup(device);
114775107Sfenner	if (handle->md.device == NULL) {
1148190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
114975107Sfenner			 pcap_strerror(errno) );
1150190225Srpaulo		return PCAP_ERROR;
115175107Sfenner	}
1152214518Srpaulo
1153214518Srpaulo	/*
1154214518Srpaulo	 * If we're in promiscuous mode, then we probably want
1155214518Srpaulo	 * to see when the interface drops packets too, so get an
1156214518Srpaulo	 * initial count from /proc/net/dev
1157214518Srpaulo	 */
1158214518Srpaulo	if (handle->opt.promisc)
1159214518Srpaulo		handle->md.proc_dropped = linux_if_drops(handle->md.device);
116075107Sfenner
1161127664Sbms	/*
1162127664Sbms	 * Current Linux kernels use the protocol family PF_PACKET to
1163127664Sbms	 * allow direct access to all packets on the network while
1164127664Sbms	 * older kernels had a special socket type SOCK_PACKET to
116575107Sfenner	 * implement this feature.
116675107Sfenner	 * While this old implementation is kind of obsolete we need
1167127664Sbms	 * to be compatible with older kernels for a while so we are
116875107Sfenner	 * trying both methods with the newer method preferred.
116975107Sfenner	 */
117075107Sfenner
1171190225Srpaulo	if ((status = activate_new(handle)) == 1) {
1172190225Srpaulo		/*
1173214518Srpaulo		 * Success.
1174190225Srpaulo		 * Try to use memory-mapped access.
1175190225Srpaulo		 */
1176214518Srpaulo		switch (activate_mmap(handle)) {
1177214518Srpaulo
1178214518Srpaulo		case 1:
1179214518Srpaulo			/* we succeeded; nothing more to do */
1180214518Srpaulo			return 0;
1181214518Srpaulo
1182214518Srpaulo		case 0:
1183214518Srpaulo			/*
1184214518Srpaulo			 * Kernel doesn't support it - just continue
1185214518Srpaulo			 * with non-memory-mapped access.
1186214518Srpaulo			 */
1187214518Srpaulo			status = 0;
1188214518Srpaulo			break;
1189214518Srpaulo
1190214518Srpaulo		case -1:
1191214518Srpaulo			/*
1192214518Srpaulo			 * We failed to set up to use it, or kernel
1193214518Srpaulo			 * supports it, but we failed to enable it;
1194214518Srpaulo			 * return an error.  handle->errbuf contains
1195214518Srpaulo			 * an error message.
1196214518Srpaulo			 */
1197214518Srpaulo			status = PCAP_ERROR;
1198214518Srpaulo			goto fail;
1199214518Srpaulo		}
1200190225Srpaulo	}
1201190225Srpaulo	else if (status == 0) {
1202127664Sbms		/* Non-fatal error; try old way */
1203214518Srpaulo		if ((status = activate_old(handle)) != 1) {
1204214518Srpaulo			/*
1205214518Srpaulo			 * Both methods to open the packet socket failed.
1206214518Srpaulo			 * Tidy up and report our failure (handle->errbuf
1207214518Srpaulo			 * is expected to be set by the functions above).
1208214518Srpaulo			 */
1209214518Srpaulo			goto fail;
1210214518Srpaulo		}
1211214518Srpaulo	} else {
1212127664Sbms		/*
1213214518Srpaulo		 * Fatal error with the new way; just fail.
1214214518Srpaulo		 * status has the error return; if it's PCAP_ERROR,
1215214518Srpaulo		 * handle->errbuf has been set appropriately.
121675107Sfenner		 */
1217190225Srpaulo		goto fail;
121875107Sfenner	}
121975107Sfenner
1220214518Srpaulo	/*
1221214518Srpaulo	 * We set up the socket, but not with memory-mapped access.
1222214518Srpaulo	 */
1223190225Srpaulo	if (handle->opt.buffer_size != 0) {
122498530Sfenner		/*
1225190225Srpaulo		 * Set the socket buffer size to the specified value.
122698530Sfenner		 */
1227190225Srpaulo		if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
1228190225Srpaulo		    &handle->opt.buffer_size,
1229190225Srpaulo		    sizeof(handle->opt.buffer_size)) == -1) {
1230190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1231190225Srpaulo				 "SO_RCVBUF: %s", pcap_strerror(errno));
1232190225Srpaulo			status = PCAP_ERROR;
1233190225Srpaulo			goto fail;
123498530Sfenner		}
123598530Sfenner	}
123698530Sfenner
123798530Sfenner	/* Allocate the buffer */
123898530Sfenner
123998530Sfenner	handle->buffer	 = malloc(handle->bufsize + handle->offset);
124098530Sfenner	if (!handle->buffer) {
1241190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
124298530Sfenner			 "malloc: %s", pcap_strerror(errno));
1243190225Srpaulo		status = PCAP_ERROR;
1244190225Srpaulo		goto fail;
124598530Sfenner	}
124698530Sfenner
1247127664Sbms	/*
1248127664Sbms	 * "handle->fd" is a socket, so "select()" and "poll()"
1249127664Sbms	 * should work on it.
1250127664Sbms	 */
1251127664Sbms	handle->selectable_fd = handle->fd;
1252127664Sbms
1253190225Srpaulo	return status;
1254127664Sbms
1255190225Srpaulofail:
1256190225Srpaulo	pcap_cleanup_linux(handle);
1257190225Srpaulo	return status;
125826175Sfenner}
125926175Sfenner
126075107Sfenner/*
126175107Sfenner *  Read at most max_packets from the capture stream and call the callback
126275107Sfenner *  for each of them. Returns the number of packets handled or -1 if an
1263127664Sbms *  error occured.
126475107Sfenner */
1265127664Sbmsstatic int
1266127664Sbmspcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
126726175Sfenner{
126875107Sfenner	/*
126975107Sfenner	 * Currently, on Linux only one packet is delivered per read,
127075107Sfenner	 * so we don't loop.
127175107Sfenner	 */
127275107Sfenner	return pcap_read_packet(handle, callback, user);
127375107Sfenner}
127426175Sfenner
127575107Sfenner/*
1276127664Sbms *  Read a packet from the socket calling the handler provided by
127775107Sfenner *  the user. Returns the number of packets received or -1 if an
127875107Sfenner *  error occured.
127975107Sfenner */
128075107Sfennerstatic int
128175107Sfennerpcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
128275107Sfenner{
128398530Sfenner	u_char			*bp;
128475107Sfenner	int			offset;
128575107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
128675107Sfenner	struct sockaddr_ll	from;
128775107Sfenner	struct sll_header	*hdrp;
128875107Sfenner#else
128975107Sfenner	struct sockaddr		from;
129075107Sfenner#endif
1291190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1292190225Srpaulo	struct iovec		iov;
1293190225Srpaulo	struct msghdr		msg;
1294190225Srpaulo	struct cmsghdr		*cmsg;
1295190225Srpaulo	union {
1296190225Srpaulo		struct cmsghdr	cmsg;
1297190225Srpaulo		char		buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
1298190225Srpaulo	} cmsg_buf;
1299190225Srpaulo#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
130075107Sfenner	socklen_t		fromlen;
1301190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
130275107Sfenner	int			packet_len, caplen;
130375107Sfenner	struct pcap_pkthdr	pcap_header;
130426175Sfenner
130575107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
130675107Sfenner	/*
130775107Sfenner	 * If this is a cooked device, leave extra room for a
130875107Sfenner	 * fake packet header.
130975107Sfenner	 */
131075107Sfenner	if (handle->md.cooked)
131175107Sfenner		offset = SLL_HDR_LEN;
131275107Sfenner	else
131375107Sfenner		offset = 0;
131475107Sfenner#else
131575107Sfenner	/*
131675107Sfenner	 * This system doesn't have PF_PACKET sockets, so it doesn't
131775107Sfenner	 * support cooked devices.
131875107Sfenner	 */
131975107Sfenner	offset = 0;
132075107Sfenner#endif
132175107Sfenner
1322190225Srpaulo	/*
1323190225Srpaulo	 * Receive a single packet from the kernel.
1324190225Srpaulo	 * We ignore EINTR, as that might just be due to a signal
1325190225Srpaulo	 * being delivered - if the signal should interrupt the
1326190225Srpaulo	 * loop, the signal handler should call pcap_breakloop()
1327190225Srpaulo	 * to set handle->break_loop (we ignore it on other
1328190225Srpaulo	 * platforms as well).
1329190225Srpaulo	 * We also ignore ENETDOWN, so that we can continue to
1330190225Srpaulo	 * capture traffic if the interface goes down and comes
1331190225Srpaulo	 * back up again; comments in the kernel indicate that
1332190225Srpaulo	 * we'll just block waiting for packets if we try to
1333190225Srpaulo	 * receive from a socket that delivered ENETDOWN, and,
1334190225Srpaulo	 * if we're using a memory-mapped buffer, we won't even
1335190225Srpaulo	 * get notified of "network down" events.
1336190225Srpaulo	 */
1337190225Srpaulo	bp = handle->buffer + handle->offset;
133875107Sfenner
1339190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1340190225Srpaulo	msg.msg_name		= &from;
1341190225Srpaulo	msg.msg_namelen		= sizeof(from);
1342190225Srpaulo	msg.msg_iov		= &iov;
1343190225Srpaulo	msg.msg_iovlen		= 1;
1344190225Srpaulo	msg.msg_control		= &cmsg_buf;
1345190225Srpaulo	msg.msg_controllen	= sizeof(cmsg_buf);
1346190225Srpaulo	msg.msg_flags		= 0;
1347190225Srpaulo
1348190225Srpaulo	iov.iov_len		= handle->bufsize - offset;
1349190225Srpaulo	iov.iov_base		= bp + offset;
1350190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1351190225Srpaulo
135226175Sfenner	do {
1353127664Sbms		/*
1354127664Sbms		 * Has "pcap_breakloop()" been called?
1355127664Sbms		 */
1356127664Sbms		if (handle->break_loop) {
1357127664Sbms			/*
1358214518Srpaulo			 * Yes - clear the flag that indicates that it has,
1359214518Srpaulo			 * and return PCAP_ERROR_BREAK as an indication that
1360214518Srpaulo			 * we were told to break out of the loop.
1361127664Sbms			 */
1362127664Sbms			handle->break_loop = 0;
1363214518Srpaulo			return PCAP_ERROR_BREAK;
1364127664Sbms		}
1365190225Srpaulo
1366190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1367190225Srpaulo		packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
1368190225Srpaulo#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
136926175Sfenner		fromlen = sizeof(from);
1370127664Sbms		packet_len = recvfrom(
137198530Sfenner			handle->fd, bp + offset,
1372127664Sbms			handle->bufsize - offset, MSG_TRUNC,
137375107Sfenner			(struct sockaddr *) &from, &fromlen);
1374190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1375214518Srpaulo	} while (packet_len == -1 && errno == EINTR);
137626175Sfenner
137775107Sfenner	/* Check if an error occured */
137826175Sfenner
137975107Sfenner	if (packet_len == -1) {
1380214518Srpaulo		switch (errno) {
1381214518Srpaulo
1382214518Srpaulo		case EAGAIN:
138375107Sfenner			return 0;	/* no packet there */
1384214518Srpaulo
1385214518Srpaulo		case ENETDOWN:
1386214518Srpaulo			/*
1387214518Srpaulo			 * The device on which we're capturing went away.
1388214518Srpaulo			 *
1389214518Srpaulo			 * XXX - we should really return
1390214518Srpaulo			 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1391214518Srpaulo			 * etc. aren't defined to return that.
1392214518Srpaulo			 */
1393190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1394214518Srpaulo				"The interface went down");
1395214518Srpaulo			return PCAP_ERROR;
1396214518Srpaulo
1397214518Srpaulo		default:
1398214518Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
139975107Sfenner				 "recvfrom: %s", pcap_strerror(errno));
1400214518Srpaulo			return PCAP_ERROR;
140126175Sfenner		}
140275107Sfenner	}
140326175Sfenner
140475107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
1405147894Ssam	if (!handle->md.sock_packet) {
1406147894Ssam		/*
1407172677Smlaier		 * Unfortunately, there is a window between socket() and
1408172677Smlaier		 * bind() where the kernel may queue packets from any
1409172677Smlaier		 * interface.  If we're bound to a particular interface,
1410172677Smlaier		 * discard packets not from that interface.
1411172677Smlaier		 *
1412172677Smlaier		 * (If socket filters are supported, we could do the
1413172677Smlaier		 * same thing we do when changing the filter; however,
1414172677Smlaier		 * that won't handle packet sockets without socket
1415172677Smlaier		 * filter support, and it's a bit more complicated.
1416172677Smlaier		 * It would save some instructions per packet, however.)
1417172677Smlaier		 */
1418172677Smlaier		if (handle->md.ifindex != -1 &&
1419172677Smlaier		    from.sll_ifindex != handle->md.ifindex)
1420172677Smlaier			return 0;
1421172677Smlaier
1422172677Smlaier		/*
1423147894Ssam		 * Do checks based on packet direction.
1424147894Ssam		 * We can only do this if we're using PF_PACKET; the
1425147894Ssam		 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1426147894Ssam		 * which lacks the relevant packet type information.
1427147894Ssam		 */
1428147894Ssam		if (from.sll_pkttype == PACKET_OUTGOING) {
1429147894Ssam			/*
1430147894Ssam			 * Outgoing packet.
1431147894Ssam			 * If this is from the loopback device, reject it;
1432147894Ssam			 * we'll see the packet as an incoming packet as well,
1433147894Ssam			 * and we don't want to see it twice.
1434147894Ssam			 */
1435147894Ssam			if (from.sll_ifindex == handle->md.lo_ifindex)
1436147894Ssam				return 0;
1437147894Ssam
1438147894Ssam			/*
1439147894Ssam			 * If the user only wants incoming packets, reject it.
1440147894Ssam			 */
1441162012Ssam			if (handle->direction == PCAP_D_IN)
1442147894Ssam				return 0;
1443147894Ssam		} else {
1444147894Ssam			/*
1445147894Ssam			 * Incoming packet.
1446147894Ssam			 * If the user only wants outgoing packets, reject it.
1447147894Ssam			 */
1448162012Ssam			if (handle->direction == PCAP_D_OUT)
1449147894Ssam				return 0;
1450147894Ssam		}
1451147894Ssam	}
145275107Sfenner#endif
145326175Sfenner
145475107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
145575107Sfenner	/*
145675107Sfenner	 * If this is a cooked device, fill in the fake packet header.
145775107Sfenner	 */
145875107Sfenner	if (handle->md.cooked) {
145975107Sfenner		/*
146075107Sfenner		 * Add the length of the fake header to the length
146175107Sfenner		 * of packet data we read.
146275107Sfenner		 */
146375107Sfenner		packet_len += SLL_HDR_LEN;
146426175Sfenner
146598530Sfenner		hdrp = (struct sll_header *)bp;
1466190225Srpaulo		hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
1467190225Srpaulo		hdrp->sll_hatype = htons(from.sll_hatype);
1468190225Srpaulo		hdrp->sll_halen = htons(from.sll_halen);
1469190225Srpaulo		memcpy(hdrp->sll_addr, from.sll_addr,
1470190225Srpaulo		    (from.sll_halen > SLL_ADDRLEN) ?
1471190225Srpaulo		      SLL_ADDRLEN :
1472190225Srpaulo		      from.sll_halen);
1473190225Srpaulo		hdrp->sll_protocol = from.sll_protocol;
1474190225Srpaulo	}
147526175Sfenner
1476190225Srpaulo#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1477190225Srpaulo	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1478190225Srpaulo		struct tpacket_auxdata *aux;
1479190225Srpaulo		unsigned int len;
1480190225Srpaulo		struct vlan_tag *tag;
148126175Sfenner
1482190225Srpaulo		if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
1483190225Srpaulo		    cmsg->cmsg_level != SOL_PACKET ||
1484190225Srpaulo		    cmsg->cmsg_type != PACKET_AUXDATA)
1485190225Srpaulo			continue;
148626175Sfenner
1487190225Srpaulo		aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
1488190225Srpaulo		if (aux->tp_vlan_tci == 0)
1489190225Srpaulo			continue;
149075107Sfenner
1491190225Srpaulo		len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
1492190225Srpaulo		if (len < 2 * ETH_ALEN)
149375107Sfenner			break;
149475107Sfenner
1495190225Srpaulo		bp -= VLAN_TAG_LEN;
1496190225Srpaulo		memmove(bp, bp + VLAN_TAG_LEN, 2 * ETH_ALEN);
149775107Sfenner
1498190225Srpaulo		tag = (struct vlan_tag *)(bp + 2 * ETH_ALEN);
1499190225Srpaulo		tag->vlan_tpid = htons(ETH_P_8021Q);
1500190225Srpaulo		tag->vlan_tci = htons(aux->tp_vlan_tci);
150175107Sfenner
1502190225Srpaulo		packet_len += VLAN_TAG_LEN;
150326175Sfenner	}
1504190225Srpaulo#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1505190225Srpaulo#endif /* HAVE_PF_PACKET_SOCKETS */
150675107Sfenner
150775107Sfenner	/*
1508127664Sbms	 * XXX: According to the kernel source we should get the real
1509127664Sbms	 * packet len if calling recvfrom with MSG_TRUNC set. It does
151075107Sfenner	 * not seem to work here :(, but it is supported by this code
1511127664Sbms	 * anyway.
151275107Sfenner	 * To be honest the code RELIES on that feature so this is really
151375107Sfenner	 * broken with 2.2.x kernels.
151475107Sfenner	 * I spend a day to figure out what's going on and I found out
1515127664Sbms	 * that the following is happening:
151675107Sfenner	 *
1517127664Sbms	 * The packet comes from a random interface and the packet_rcv
151875107Sfenner	 * hook is called with a clone of the packet. That code inserts
151975107Sfenner	 * the packet into the receive queue of the packet socket.
152075107Sfenner	 * If a filter is attached to that socket that filter is run
152175107Sfenner	 * first - and there lies the problem. The default filter always
152275107Sfenner	 * cuts the packet at the snaplen:
152375107Sfenner	 *
152475107Sfenner	 * # tcpdump -d
152575107Sfenner	 * (000) ret      #68
152675107Sfenner	 *
1527127664Sbms	 * So the packet filter cuts down the packet. The recvfrom call
152875107Sfenner	 * says "hey, it's only 68 bytes, it fits into the buffer" with
1529127664Sbms	 * the result that we don't get the real packet length. This
1530127664Sbms	 * is valid at least until kernel 2.2.17pre6.
153175107Sfenner	 *
153275107Sfenner	 * We currently handle this by making a copy of the filter
153375107Sfenner	 * program, fixing all "ret" instructions with non-zero
153475107Sfenner	 * operands to have an operand of 65535 so that the filter
153575107Sfenner	 * doesn't truncate the packet, and supplying that modified
153675107Sfenner	 * filter to the kernel.
153775107Sfenner	 */
153875107Sfenner
153975107Sfenner	caplen = packet_len;
154075107Sfenner	if (caplen > handle->snapshot)
154175107Sfenner		caplen = handle->snapshot;
154275107Sfenner
154375107Sfenner	/* Run the packet filter if not using kernel filter */
154475107Sfenner	if (!handle->md.use_bpf && handle->fcode.bf_insns) {
154598530Sfenner		if (bpf_filter(handle->fcode.bf_insns, bp,
154675107Sfenner		                packet_len, caplen) == 0)
154775107Sfenner		{
154875107Sfenner			/* rejected by filter */
154975107Sfenner			return 0;
155075107Sfenner		}
155175107Sfenner	}
155275107Sfenner
155375107Sfenner	/* Fill in our own header data */
155475107Sfenner
155575107Sfenner	if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
1556190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1557172677Smlaier			 "SIOCGSTAMP: %s", pcap_strerror(errno));
1558214518Srpaulo		return PCAP_ERROR;
155975107Sfenner	}
156075107Sfenner	pcap_header.caplen	= caplen;
156175107Sfenner	pcap_header.len		= packet_len;
156275107Sfenner
156398530Sfenner	/*
156498530Sfenner	 * Count the packet.
156598530Sfenner	 *
156698530Sfenner	 * Arguably, we should count them before we check the filter,
156798530Sfenner	 * as on many other platforms "ps_recv" counts packets
156898530Sfenner	 * handed to the filter rather than packets that passed
156998530Sfenner	 * the filter, but if filtering is done in the kernel, we
157098530Sfenner	 * can't get a count of packets that passed the filter,
157198530Sfenner	 * and that would mean the meaning of "ps_recv" wouldn't
157298530Sfenner	 * be the same on all Linux systems.
157398530Sfenner	 *
157498530Sfenner	 * XXX - it's not the same on all systems in any case;
157598530Sfenner	 * ideally, we should have a "get the statistics" call
157698530Sfenner	 * that supplies more counts and indicates which of them
157798530Sfenner	 * it supplies, so that we supply a count of packets
157898530Sfenner	 * handed to the filter only on platforms where that
157998530Sfenner	 * information is available.
158098530Sfenner	 *
158198530Sfenner	 * We count them here even if we can get the packet count
158298530Sfenner	 * from the kernel, as we can only determine at run time
158398530Sfenner	 * whether we'll be able to get it from the kernel (if
158498530Sfenner	 * HAVE_TPACKET_STATS isn't defined, we can't get it from
158598530Sfenner	 * the kernel, but if it is defined, the library might
158698530Sfenner	 * have been built with a 2.4 or later kernel, but we
158798530Sfenner	 * might be running on a 2.2[.x] kernel without Alexey
158898530Sfenner	 * Kuznetzov's turbopacket patches, and thus the kernel
158998530Sfenner	 * might not be able to supply those statistics).  We
159098530Sfenner	 * could, I guess, try, when opening the socket, to get
159198530Sfenner	 * the statistics, and if we can not increment the count
159298530Sfenner	 * here, but it's not clear that always incrementing
159398530Sfenner	 * the count is more expensive than always testing a flag
159498530Sfenner	 * in memory.
1595172677Smlaier	 *
1596172677Smlaier	 * We keep the count in "md.packets_read", and use that for
1597172677Smlaier	 * "ps_recv" if we can't get the statistics from the kernel.
1598172677Smlaier	 * We do that because, if we *can* get the statistics from
1599172677Smlaier	 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
1600172677Smlaier	 * as running counts, as reading the statistics from the
1601172677Smlaier	 * kernel resets the kernel statistics, and if we directly
1602172677Smlaier	 * increment "md.stat.ps_recv" here, that means it will
1603172677Smlaier	 * count packets *twice* on systems where we can get kernel
1604172677Smlaier	 * statistics - once here, and once in pcap_stats_linux().
160598530Sfenner	 */
1606172677Smlaier	handle->md.packets_read++;
160775107Sfenner
160898530Sfenner	/* Call the user supplied callback function */
160998530Sfenner	callback(userdata, &pcap_header, bp);
161098530Sfenner
161175107Sfenner	return 1;
161226175Sfenner}
161326175Sfenner
1614146768Ssamstatic int
1615146768Ssampcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
1616146768Ssam{
1617146768Ssam	int ret;
1618146768Ssam
1619146768Ssam#ifdef HAVE_PF_PACKET_SOCKETS
1620146768Ssam	if (!handle->md.sock_packet) {
1621146768Ssam		/* PF_PACKET socket */
1622146768Ssam		if (handle->md.ifindex == -1) {
1623146768Ssam			/*
1624146768Ssam			 * We don't support sending on the "any" device.
1625146768Ssam			 */
1626146768Ssam			strlcpy(handle->errbuf,
1627146768Ssam			    "Sending packets isn't supported on the \"any\" device",
1628146768Ssam			    PCAP_ERRBUF_SIZE);
1629146768Ssam			return (-1);
1630146768Ssam		}
1631146768Ssam
1632146768Ssam		if (handle->md.cooked) {
1633146768Ssam			/*
1634146768Ssam			 * We don't support sending on the "any" device.
1635146768Ssam			 *
1636146768Ssam			 * XXX - how do you send on a bound cooked-mode
1637146768Ssam			 * socket?
1638146768Ssam			 * Is a "sendto()" required there?
1639146768Ssam			 */
1640146768Ssam			strlcpy(handle->errbuf,
1641146768Ssam			    "Sending packets isn't supported in cooked mode",
1642146768Ssam			    PCAP_ERRBUF_SIZE);
1643146768Ssam			return (-1);
1644146768Ssam		}
1645146768Ssam	}
1646146768Ssam#endif
1647146768Ssam
1648146768Ssam	ret = send(handle->fd, buf, size, 0);
1649146768Ssam	if (ret == -1) {
1650146768Ssam		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1651146768Ssam		    pcap_strerror(errno));
1652146768Ssam		return (-1);
1653146768Ssam	}
1654146768Ssam	return (ret);
1655146768Ssam}
1656146768Ssam
165775107Sfenner/*
165875107Sfenner *  Get the statistics for the given packet capture handle.
165998530Sfenner *  Reports the number of dropped packets iff the kernel supports
166098530Sfenner *  the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
166198530Sfenner *  kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
166298530Sfenner *  patches); otherwise, that information isn't available, and we lie
166398530Sfenner *  and report 0 as the count of dropped packets.
166475107Sfenner */
1665127664Sbmsstatic int
1666127664Sbmspcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
166726175Sfenner{
166898530Sfenner#ifdef HAVE_TPACKET_STATS
166998530Sfenner	struct tpacket_stats kstats;
167098530Sfenner	socklen_t len = sizeof (struct tpacket_stats);
1671127664Sbms#endif
167298530Sfenner
1673214518Srpaulo	long if_dropped = 0;
1674214518Srpaulo
1675214518Srpaulo	/*
1676214518Srpaulo	 *	To fill in ps_ifdrop, we parse /proc/net/dev for the number
1677214518Srpaulo	 */
1678214518Srpaulo	if (handle->opt.promisc)
1679214518Srpaulo	{
1680214518Srpaulo		if_dropped = handle->md.proc_dropped;
1681214518Srpaulo		handle->md.proc_dropped = linux_if_drops(handle->md.device);
1682214518Srpaulo		handle->md.stat.ps_ifdrop += (handle->md.proc_dropped - if_dropped);
1683214518Srpaulo	}
1684214518Srpaulo
1685127664Sbms#ifdef HAVE_TPACKET_STATS
168698530Sfenner	/*
168798530Sfenner	 * Try to get the packet counts from the kernel.
168898530Sfenner	 */
168998530Sfenner	if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
169098530Sfenner			&kstats, &len) > -1) {
169198530Sfenner		/*
1692172677Smlaier		 * On systems where the PACKET_STATISTICS "getsockopt()"
1693172677Smlaier		 * argument is supported on PF_PACKET sockets:
1694172677Smlaier		 *
1695172677Smlaier		 *	"ps_recv" counts only packets that *passed* the
1696172677Smlaier		 *	filter, not packets that didn't pass the filter.
1697172677Smlaier		 *	This includes packets later dropped because we
1698172677Smlaier		 *	ran out of buffer space.
1699172677Smlaier		 *
1700172677Smlaier		 *	"ps_drop" counts packets dropped because we ran
1701172677Smlaier		 *	out of buffer space.  It doesn't count packets
1702172677Smlaier		 *	dropped by the interface driver.  It counts only
1703172677Smlaier		 *	packets that passed the filter.
1704172677Smlaier		 *
1705214518Srpaulo		 *	See above for ps_ifdrop.
1706214518Srpaulo		 *
1707172677Smlaier		 *	Both statistics include packets not yet read from
1708172677Smlaier		 *	the kernel by libpcap, and thus not yet seen by
1709172677Smlaier		 *	the application.
1710172677Smlaier		 *
171198530Sfenner		 * In "linux/net/packet/af_packet.c", at least in the
171298530Sfenner		 * 2.4.9 kernel, "tp_packets" is incremented for every
171398530Sfenner		 * packet that passes the packet filter *and* is
171498530Sfenner		 * successfully queued on the socket; "tp_drops" is
171598530Sfenner		 * incremented for every packet dropped because there's
171698530Sfenner		 * not enough free space in the socket buffer.
171798530Sfenner		 *
171898530Sfenner		 * When the statistics are returned for a PACKET_STATISTICS
171998530Sfenner		 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
172098530Sfenner		 * so that "tp_packets" counts all packets handed to
172198530Sfenner		 * the PF_PACKET socket, including packets dropped because
172298530Sfenner		 * there wasn't room on the socket buffer - but not
172398530Sfenner		 * including packets that didn't pass the filter.
172498530Sfenner		 *
172598530Sfenner		 * In the BSD BPF, the count of received packets is
172698530Sfenner		 * incremented for every packet handed to BPF, regardless
172798530Sfenner		 * of whether it passed the filter.
172898530Sfenner		 *
172998530Sfenner		 * We can't make "pcap_stats()" work the same on both
173098530Sfenner		 * platforms, but the best approximation is to return
173198530Sfenner		 * "tp_packets" as the count of packets and "tp_drops"
173298530Sfenner		 * as the count of drops.
1733146768Ssam		 *
1734146768Ssam		 * Keep a running total because each call to
1735146768Ssam		 *    getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1736146768Ssam		 * resets the counters to zero.
173798530Sfenner		 */
1738146768Ssam		handle->md.stat.ps_recv += kstats.tp_packets;
1739146768Ssam		handle->md.stat.ps_drop += kstats.tp_drops;
1740172677Smlaier		*stats = handle->md.stat;
1741172677Smlaier		return 0;
174298530Sfenner	}
174398530Sfenner	else
174498530Sfenner	{
174598530Sfenner		/*
174698530Sfenner		 * If the error was EOPNOTSUPP, fall through, so that
174798530Sfenner		 * if you build the library on a system with
174898530Sfenner		 * "struct tpacket_stats" and run it on a system
174998530Sfenner		 * that doesn't, it works as it does if the library
175098530Sfenner		 * is built on a system without "struct tpacket_stats".
175198530Sfenner		 */
175298530Sfenner		if (errno != EOPNOTSUPP) {
175398530Sfenner			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
175498530Sfenner			    "pcap_stats: %s", pcap_strerror(errno));
175598530Sfenner			return -1;
175698530Sfenner		}
175798530Sfenner	}
175898530Sfenner#endif
175998530Sfenner	/*
176098530Sfenner	 * On systems where the PACKET_STATISTICS "getsockopt()" argument
176198530Sfenner	 * is not supported on PF_PACKET sockets:
176298530Sfenner	 *
176398530Sfenner	 *	"ps_recv" counts only packets that *passed* the filter,
176498530Sfenner	 *	not packets that didn't pass the filter.  It does not
176598530Sfenner	 *	count packets dropped because we ran out of buffer
176698530Sfenner	 *	space.
176798530Sfenner	 *
176898530Sfenner	 *	"ps_drop" is not supported.
176998530Sfenner	 *
1770214518Srpaulo	 *	"ps_ifdrop" is supported. It will return the number
1771214518Srpaulo	 *	of drops the interface reports in /proc/net/dev,
1772214518Srpaulo	 *	if that is available.
1773214518Srpaulo	 *
177498530Sfenner	 *	"ps_recv" doesn't include packets not yet read from
177598530Sfenner	 *	the kernel by libpcap.
1776172677Smlaier	 *
1777172677Smlaier	 * We maintain the count of packets processed by libpcap in
1778172677Smlaier	 * "md.packets_read", for reasons described in the comment
1779172677Smlaier	 * at the end of pcap_read_packet().  We have no idea how many
1780214518Srpaulo	 * packets were dropped by the kernel buffers -- but we know
1781214518Srpaulo	 * how many the interface dropped, so we can return that.
178298530Sfenner	 */
1783214518Srpaulo
1784172677Smlaier	stats->ps_recv = handle->md.packets_read;
1785172677Smlaier	stats->ps_drop = 0;
1786214518Srpaulo	stats->ps_ifdrop = handle->md.stat.ps_ifdrop;
178775107Sfenner	return 0;
178875107Sfenner}
178926175Sfenner
179075107Sfenner/*
1791214518Srpaulo * Get from "/sys/class/net" all interfaces listed there; if they're
1792214518Srpaulo * already in the list of interfaces we have, that won't add another
1793214518Srpaulo * instance, but if they're not, that'll add them.
1794214518Srpaulo *
1795214518Srpaulo * We don't bother getting any addresses for them; it appears you can't
1796214518Srpaulo * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
1797214518Srpaulo * although some other types of addresses can be fetched with SIOCGIFADDR,
1798214518Srpaulo * we don't bother with them for now.
1799214518Srpaulo *
1800214518Srpaulo * We also don't fail if we couldn't open "/sys/class/net"; we just leave
1801214518Srpaulo * the list of interfaces as is, and return 0, so that we can try
1802214518Srpaulo * scanning /proc/net/dev.
1803214518Srpaulo */
1804214518Srpaulostatic int
1805214518Srpauloscan_sys_class_net(pcap_if_t **devlistp, char *errbuf)
1806214518Srpaulo{
1807214518Srpaulo	DIR *sys_class_net_d;
1808214518Srpaulo	int fd;
1809214518Srpaulo	struct dirent *ent;
1810214518Srpaulo	char *p;
1811214518Srpaulo	char name[512];	/* XXX - pick a size */
1812214518Srpaulo	char *q, *saveq;
1813214518Srpaulo	struct ifreq ifrflags;
1814214518Srpaulo	int ret = 1;
1815214518Srpaulo
1816214518Srpaulo	sys_class_net_d = opendir("/sys/class/net");
1817214518Srpaulo	if (sys_class_net_d == NULL && errno == ENOENT)
1818214518Srpaulo		return (0);
1819214518Srpaulo
1820214518Srpaulo	/*
1821214518Srpaulo	 * Create a socket from which to fetch interface information.
1822214518Srpaulo	 */
1823214518Srpaulo	fd = socket(AF_INET, SOCK_DGRAM, 0);
1824214518Srpaulo	if (fd < 0) {
1825214518Srpaulo		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1826214518Srpaulo		    "socket: %s", pcap_strerror(errno));
1827214518Srpaulo		return (-1);
1828214518Srpaulo	}
1829214518Srpaulo
1830214518Srpaulo	for (;;) {
1831214518Srpaulo		errno = 0;
1832214518Srpaulo		ent = readdir(sys_class_net_d);
1833214518Srpaulo		if (ent == NULL) {
1834214518Srpaulo			/*
1835214518Srpaulo			 * Error or EOF; if errno != 0, it's an error.
1836214518Srpaulo			 */
1837214518Srpaulo			break;
1838214518Srpaulo		}
1839214518Srpaulo
1840214518Srpaulo		/*
1841214518Srpaulo		 * Ignore directories (".", "..", and any subdirectories).
1842214518Srpaulo		 */
1843214518Srpaulo		if (ent->d_type == DT_DIR)
1844214518Srpaulo			continue;
1845214518Srpaulo
1846214518Srpaulo		/*
1847214518Srpaulo		 * Get the interface name.
1848214518Srpaulo		 */
1849214518Srpaulo		p = &ent->d_name[0];
1850214518Srpaulo		q = &name[0];
1851214518Srpaulo		while (*p != '\0' && isascii(*p) && !isspace(*p)) {
1852214518Srpaulo			if (*p == ':') {
1853214518Srpaulo				/*
1854214518Srpaulo				 * This could be the separator between a
1855214518Srpaulo				 * name and an alias number, or it could be
1856214518Srpaulo				 * the separator between a name with no
1857214518Srpaulo				 * alias number and the next field.
1858214518Srpaulo				 *
1859214518Srpaulo				 * If there's a colon after digits, it
1860214518Srpaulo				 * separates the name and the alias number,
1861214518Srpaulo				 * otherwise it separates the name and the
1862214518Srpaulo				 * next field.
1863214518Srpaulo				 */
1864214518Srpaulo				saveq = q;
1865214518Srpaulo				while (isascii(*p) && isdigit(*p))
1866214518Srpaulo					*q++ = *p++;
1867214518Srpaulo				if (*p != ':') {
1868214518Srpaulo					/*
1869214518Srpaulo					 * That was the next field,
1870214518Srpaulo					 * not the alias number.
1871214518Srpaulo					 */
1872214518Srpaulo					q = saveq;
1873214518Srpaulo				}
1874214518Srpaulo				break;
1875214518Srpaulo			} else
1876214518Srpaulo				*q++ = *p++;
1877214518Srpaulo		}
1878214518Srpaulo		*q = '\0';
1879214518Srpaulo
1880214518Srpaulo		/*
1881214518Srpaulo		 * Get the flags for this interface, and skip it if
1882214518Srpaulo		 * it's not up.
1883214518Srpaulo		 */
1884214518Srpaulo		strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
1885214518Srpaulo		if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
1886214518Srpaulo			if (errno == ENXIO)
1887214518Srpaulo				continue;
1888214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1889214518Srpaulo			    "SIOCGIFFLAGS: %.*s: %s",
1890214518Srpaulo			    (int)sizeof(ifrflags.ifr_name),
1891214518Srpaulo			    ifrflags.ifr_name,
1892214518Srpaulo			    pcap_strerror(errno));
1893214518Srpaulo			ret = -1;
1894214518Srpaulo			break;
1895214518Srpaulo		}
1896214518Srpaulo		if (!(ifrflags.ifr_flags & IFF_UP))
1897214518Srpaulo			continue;
1898214518Srpaulo
1899214518Srpaulo		/*
1900214518Srpaulo		 * Add an entry for this interface, with no addresses.
1901214518Srpaulo		 */
1902214518Srpaulo		if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
1903214518Srpaulo		    errbuf) == -1) {
1904214518Srpaulo			/*
1905214518Srpaulo			 * Failure.
1906214518Srpaulo			 */
1907214518Srpaulo			ret = -1;
1908214518Srpaulo			break;
1909214518Srpaulo		}
1910214518Srpaulo	}
1911214518Srpaulo	if (ret != -1) {
1912214518Srpaulo		/*
1913214518Srpaulo		 * Well, we didn't fail for any other reason; did we
1914214518Srpaulo		 * fail due to an error reading the directory?
1915214518Srpaulo		 */
1916214518Srpaulo		if (errno != 0) {
1917214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1918214518Srpaulo			    "Error reading /sys/class/net: %s",
1919214518Srpaulo			    pcap_strerror(errno));
1920214518Srpaulo			ret = -1;
1921214518Srpaulo		}
1922214518Srpaulo	}
1923214518Srpaulo
1924214518Srpaulo	(void)close(fd);
1925214518Srpaulo	(void)closedir(sys_class_net_d);
1926214518Srpaulo	return (ret);
1927214518Srpaulo}
1928214518Srpaulo
1929214518Srpaulo/*
1930214518Srpaulo * Get from "/proc/net/dev" all interfaces listed there; if they're
1931214518Srpaulo * already in the list of interfaces we have, that won't add another
1932214518Srpaulo * instance, but if they're not, that'll add them.
1933214518Srpaulo *
1934214518Srpaulo * See comments from scan_sys_class_net().
1935214518Srpaulo */
1936214518Srpaulostatic int
1937214518Srpauloscan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
1938214518Srpaulo{
1939214518Srpaulo	FILE *proc_net_f;
1940214518Srpaulo	int fd;
1941214518Srpaulo	char linebuf[512];
1942214518Srpaulo	int linenum;
1943214518Srpaulo	char *p;
1944214518Srpaulo	char name[512];	/* XXX - pick a size */
1945214518Srpaulo	char *q, *saveq;
1946214518Srpaulo	struct ifreq ifrflags;
1947214518Srpaulo	int ret = 0;
1948214518Srpaulo
1949214518Srpaulo	proc_net_f = fopen("/proc/net/dev", "r");
1950214518Srpaulo	if (proc_net_f == NULL && errno == ENOENT)
1951214518Srpaulo		return (0);
1952214518Srpaulo
1953214518Srpaulo	/*
1954214518Srpaulo	 * Create a socket from which to fetch interface information.
1955214518Srpaulo	 */
1956214518Srpaulo	fd = socket(AF_INET, SOCK_DGRAM, 0);
1957214518Srpaulo	if (fd < 0) {
1958214518Srpaulo		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1959214518Srpaulo		    "socket: %s", pcap_strerror(errno));
1960214518Srpaulo		return (-1);
1961214518Srpaulo	}
1962214518Srpaulo
1963214518Srpaulo	for (linenum = 1;
1964214518Srpaulo	    fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
1965214518Srpaulo		/*
1966214518Srpaulo		 * Skip the first two lines - they're headers.
1967214518Srpaulo		 */
1968214518Srpaulo		if (linenum <= 2)
1969214518Srpaulo			continue;
1970214518Srpaulo
1971214518Srpaulo		p = &linebuf[0];
1972214518Srpaulo
1973214518Srpaulo		/*
1974214518Srpaulo		 * Skip leading white space.
1975214518Srpaulo		 */
1976214518Srpaulo		while (*p != '\0' && isascii(*p) && isspace(*p))
1977214518Srpaulo			p++;
1978214518Srpaulo		if (*p == '\0' || *p == '\n')
1979214518Srpaulo			continue;	/* blank line */
1980214518Srpaulo
1981214518Srpaulo		/*
1982214518Srpaulo		 * Get the interface name.
1983214518Srpaulo		 */
1984214518Srpaulo		q = &name[0];
1985214518Srpaulo		while (*p != '\0' && isascii(*p) && !isspace(*p)) {
1986214518Srpaulo			if (*p == ':') {
1987214518Srpaulo				/*
1988214518Srpaulo				 * This could be the separator between a
1989214518Srpaulo				 * name and an alias number, or it could be
1990214518Srpaulo				 * the separator between a name with no
1991214518Srpaulo				 * alias number and the next field.
1992214518Srpaulo				 *
1993214518Srpaulo				 * If there's a colon after digits, it
1994214518Srpaulo				 * separates the name and the alias number,
1995214518Srpaulo				 * otherwise it separates the name and the
1996214518Srpaulo				 * next field.
1997214518Srpaulo				 */
1998214518Srpaulo				saveq = q;
1999214518Srpaulo				while (isascii(*p) && isdigit(*p))
2000214518Srpaulo					*q++ = *p++;
2001214518Srpaulo				if (*p != ':') {
2002214518Srpaulo					/*
2003214518Srpaulo					 * That was the next field,
2004214518Srpaulo					 * not the alias number.
2005214518Srpaulo					 */
2006214518Srpaulo					q = saveq;
2007214518Srpaulo				}
2008214518Srpaulo				break;
2009214518Srpaulo			} else
2010214518Srpaulo				*q++ = *p++;
2011214518Srpaulo		}
2012214518Srpaulo		*q = '\0';
2013214518Srpaulo
2014214518Srpaulo		/*
2015214518Srpaulo		 * Get the flags for this interface, and skip it if
2016214518Srpaulo		 * it's not up.
2017214518Srpaulo		 */
2018214518Srpaulo		strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2019214518Srpaulo		if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2020214518Srpaulo			if (errno == ENXIO)
2021214518Srpaulo				continue;
2022214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2023214518Srpaulo			    "SIOCGIFFLAGS: %.*s: %s",
2024214518Srpaulo			    (int)sizeof(ifrflags.ifr_name),
2025214518Srpaulo			    ifrflags.ifr_name,
2026214518Srpaulo			    pcap_strerror(errno));
2027214518Srpaulo			ret = -1;
2028214518Srpaulo			break;
2029214518Srpaulo		}
2030214518Srpaulo		if (!(ifrflags.ifr_flags & IFF_UP))
2031214518Srpaulo			continue;
2032214518Srpaulo
2033214518Srpaulo		/*
2034214518Srpaulo		 * Add an entry for this interface, with no addresses.
2035214518Srpaulo		 */
2036214518Srpaulo		if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2037214518Srpaulo		    errbuf) == -1) {
2038214518Srpaulo			/*
2039214518Srpaulo			 * Failure.
2040214518Srpaulo			 */
2041214518Srpaulo			ret = -1;
2042214518Srpaulo			break;
2043214518Srpaulo		}
2044214518Srpaulo	}
2045214518Srpaulo	if (ret != -1) {
2046214518Srpaulo		/*
2047214518Srpaulo		 * Well, we didn't fail for any other reason; did we
2048214518Srpaulo		 * fail due to an error reading the file?
2049214518Srpaulo		 */
2050214518Srpaulo		if (ferror(proc_net_f)) {
2051214518Srpaulo			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2052214518Srpaulo			    "Error reading /proc/net/dev: %s",
2053214518Srpaulo			    pcap_strerror(errno));
2054214518Srpaulo			ret = -1;
2055214518Srpaulo		}
2056214518Srpaulo	}
2057214518Srpaulo
2058214518Srpaulo	(void)close(fd);
2059214518Srpaulo	(void)fclose(proc_net_f);
2060214518Srpaulo	return (ret);
2061214518Srpaulo}
2062214518Srpaulo
2063214518Srpaulo/*
2064127664Sbms * Description string for the "any" device.
206575107Sfenner */
2066127664Sbmsstatic const char any_descr[] = "Pseudo-device that captures on all interfaces";
2067127664Sbms
206875107Sfennerint
2069127664Sbmspcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
207075107Sfenner{
2071214518Srpaulo	int ret;
2072214518Srpaulo
2073214518Srpaulo	/*
2074214518Srpaulo	 * Read "/sys/class/net", and add to the list of interfaces all
2075214518Srpaulo	 * interfaces listed there that we don't already have, because,
2076214518Srpaulo	 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2077214518Srpaulo	 * and even getifaddrs() won't return information about
2078214518Srpaulo	 * interfaces with no addresses, so you need to read "/sys/class/net"
2079214518Srpaulo	 * to get the names of the rest of the interfaces.
2080214518Srpaulo	 */
2081214518Srpaulo	ret = scan_sys_class_net(alldevsp, errbuf);
2082214518Srpaulo	if (ret == -1)
2083214518Srpaulo		return (-1);	/* failed */
2084214518Srpaulo	if (ret == 0) {
2085214518Srpaulo		/*
2086214518Srpaulo		 * No /sys/class/net; try reading /proc/net/dev instead.
2087214518Srpaulo		 */
2088214518Srpaulo		if (scan_proc_net_dev(alldevsp, errbuf) == -1)
2089214518Srpaulo			return (-1);
2090214518Srpaulo	}
2091214518Srpaulo
2092214518Srpaulo	/*
2093214518Srpaulo	 * Add the "any" device.
2094214518Srpaulo	 */
2095127664Sbms	if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
2096127664Sbms		return (-1);
2097127664Sbms
2098127664Sbms#ifdef HAVE_DAG_API
2099214518Srpaulo	/*
2100214518Srpaulo	 * Add DAG devices.
2101214518Srpaulo	 */
2102127664Sbms	if (dag_platform_finddevs(alldevsp, errbuf) < 0)
2103127664Sbms		return (-1);
2104127664Sbms#endif /* HAVE_DAG_API */
2105127664Sbms
2106147894Ssam#ifdef HAVE_SEPTEL_API
2107214518Srpaulo	/*
2108214518Srpaulo	 * Add Septel devices.
2109214518Srpaulo	 */
2110147894Ssam	if (septel_platform_finddevs(alldevsp, errbuf) < 0)
2111147894Ssam		return (-1);
2112147894Ssam#endif /* HAVE_SEPTEL_API */
2113147894Ssam
2114214518Srpaulo#ifdef HAVE_SNF_API
2115214518Srpaulo	if (snf_platform_finddevs(alldevsp, errbuf) < 0)
2116214518Srpaulo		return (-1);
2117214518Srpaulo#endif /* HAVE_SNF_API */
2118214518Srpaulo
2119190225Srpaulo#ifdef PCAP_SUPPORT_BT
2120214518Srpaulo	/*
2121214518Srpaulo	 * Add Bluetooth devices.
2122214518Srpaulo	 */
2123190225Srpaulo	if (bt_platform_finddevs(alldevsp, errbuf) < 0)
2124190225Srpaulo		return (-1);
2125190225Srpaulo#endif
2126190225Srpaulo
2127190225Srpaulo#ifdef PCAP_SUPPORT_USB
2128214518Srpaulo	/*
2129214518Srpaulo	 * Add USB devices.
2130214518Srpaulo	 */
2131190225Srpaulo	if (usb_platform_finddevs(alldevsp, errbuf) < 0)
2132190225Srpaulo		return (-1);
2133190225Srpaulo#endif
2134190225Srpaulo
2135127664Sbms	return (0);
2136127664Sbms}
2137127664Sbms
2138127664Sbms/*
2139127664Sbms *  Attach the given BPF code to the packet capture device.
2140127664Sbms */
2141127664Sbmsstatic int
2142214518Srpaulopcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
2143214518Srpaulo    int is_mmapped)
2144127664Sbms{
214575107Sfenner#ifdef SO_ATTACH_FILTER
214675107Sfenner	struct sock_fprog	fcode;
214775107Sfenner	int			can_filter_in_kernel;
2148127664Sbms	int			err = 0;
214975107Sfenner#endif
215075107Sfenner
215175107Sfenner	if (!handle)
215275107Sfenner		return -1;
215375107Sfenner	if (!filter) {
215475107Sfenner	        strncpy(handle->errbuf, "setfilter: No filter specified",
2155190225Srpaulo			PCAP_ERRBUF_SIZE);
215675107Sfenner		return -1;
215726175Sfenner	}
215826175Sfenner
215975107Sfenner	/* Make our private copy of the filter */
216075107Sfenner
2161127664Sbms	if (install_bpf_program(handle, filter) < 0)
2162127664Sbms		/* install_bpf_program() filled in errbuf */
216375107Sfenner		return -1;
216439291Sfenner
2165127664Sbms	/*
2166127664Sbms	 * Run user level packet filter by default. Will be overriden if
2167127664Sbms	 * installing a kernel filter succeeds.
216875107Sfenner	 */
216975107Sfenner	handle->md.use_bpf = 0;
217075107Sfenner
217175107Sfenner	/* Install kernel level filter if possible */
217275107Sfenner
217375107Sfenner#ifdef SO_ATTACH_FILTER
217475107Sfenner#ifdef USHRT_MAX
217575107Sfenner	if (handle->fcode.bf_len > USHRT_MAX) {
217675107Sfenner		/*
2177127664Sbms		 * fcode.len is an unsigned short for current kernel.
217875107Sfenner		 * I have yet to see BPF-Code with that much
217975107Sfenner		 * instructions but still it is possible. So for the
218075107Sfenner		 * sake of correctness I added this check.
218175107Sfenner		 */
218275107Sfenner		fprintf(stderr, "Warning: Filter too complex for kernel\n");
2183172677Smlaier		fcode.len = 0;
218475107Sfenner		fcode.filter = NULL;
218575107Sfenner		can_filter_in_kernel = 0;
218675107Sfenner	} else
218775107Sfenner#endif /* USHRT_MAX */
218875107Sfenner	{
218975107Sfenner		/*
219075107Sfenner		 * Oh joy, the Linux kernel uses struct sock_fprog instead
219175107Sfenner		 * of struct bpf_program and of course the length field is
219275107Sfenner		 * of different size. Pointed out by Sebastian
219375107Sfenner		 *
219475107Sfenner		 * Oh, and we also need to fix it up so that all "ret"
219575107Sfenner		 * instructions with non-zero operands have 65535 as the
2196214518Srpaulo		 * operand if we're not capturing in memory-mapped modee,
2197214518Srpaulo		 * and so that, if we're in cooked mode, all memory-reference
2198214518Srpaulo		 * instructions use special magic offsets in references to
2199214518Srpaulo		 * the link-layer header and assume that the link-layer
2200214518Srpaulo		 * payload begins at 0; "fix_program()" will do that.
220175107Sfenner		 */
2202214518Srpaulo		switch (fix_program(handle, &fcode, is_mmapped)) {
220375107Sfenner
220475107Sfenner		case -1:
220575107Sfenner		default:
220675107Sfenner			/*
220775107Sfenner			 * Fatal error; just quit.
220875107Sfenner			 * (The "default" case shouldn't happen; we
220975107Sfenner			 * return -1 for that reason.)
221075107Sfenner			 */
221175107Sfenner			return -1;
221275107Sfenner
221375107Sfenner		case 0:
221475107Sfenner			/*
221575107Sfenner			 * The program performed checks that we can't make
221675107Sfenner			 * work in the kernel.
221775107Sfenner			 */
221875107Sfenner			can_filter_in_kernel = 0;
221975107Sfenner			break;
222075107Sfenner
222175107Sfenner		case 1:
222275107Sfenner			/*
222375107Sfenner			 * We have a filter that'll work in the kernel.
222475107Sfenner			 */
222575107Sfenner			can_filter_in_kernel = 1;
222675107Sfenner			break;
222775107Sfenner		}
222839291Sfenner	}
222939291Sfenner
223075107Sfenner	if (can_filter_in_kernel) {
2231127664Sbms		if ((err = set_kernel_filter(handle, &fcode)) == 0)
223275107Sfenner		{
223375107Sfenner			/* Installation succeded - using kernel filter. */
223475107Sfenner			handle->md.use_bpf = 1;
223575107Sfenner		}
2236127664Sbms		else if (err == -1)	/* Non-fatal error */
223775107Sfenner		{
2238127664Sbms			/*
223975107Sfenner			 * Print a warning if we weren't able to install
224075107Sfenner			 * the filter for a reason other than "this kernel
224175107Sfenner			 * isn't configured to support socket filters.
224275107Sfenner			 */
224375107Sfenner			if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
224475107Sfenner				fprintf(stderr,
2245127664Sbms				    "Warning: Kernel filter failed: %s\n",
224675107Sfenner					pcap_strerror(errno));
224775107Sfenner			}
224875107Sfenner		}
224939291Sfenner	}
225039291Sfenner
225175107Sfenner	/*
225298530Sfenner	 * If we're not using the kernel filter, get rid of any kernel
225398530Sfenner	 * filter that might've been there before, e.g. because the
225498530Sfenner	 * previous filter could work in the kernel, or because some other
225598530Sfenner	 * code attached a filter to the socket by some means other than
225698530Sfenner	 * calling "pcap_setfilter()".  Otherwise, the kernel filter may
225798530Sfenner	 * filter out packets that would pass the new userland filter.
225898530Sfenner	 */
225998530Sfenner	if (!handle->md.use_bpf)
226098530Sfenner		reset_kernel_filter(handle);
226198530Sfenner
226298530Sfenner	/*
226375107Sfenner	 * Free up the copy of the filter that was made by "fix_program()".
226475107Sfenner	 */
226575107Sfenner	if (fcode.filter != NULL)
226675107Sfenner		free(fcode.filter);
2267127664Sbms
2268127664Sbms	if (err == -2)
2269127664Sbms		/* Fatal error */
2270127664Sbms		return -1;
227175107Sfenner#endif /* SO_ATTACH_FILTER */
227275107Sfenner
227375107Sfenner	return 0;
227475107Sfenner}
227575107Sfenner
2276214518Srpaulostatic int
2277214518Srpaulopcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
2278214518Srpaulo{
2279214518Srpaulo	return pcap_setfilter_linux_common(handle, filter, 0);
2280214518Srpaulo}
2281214518Srpaulo
2282214518Srpaulo
228375107Sfenner/*
2284147894Ssam * Set direction flag: Which packets do we accept on a forwarding
2285147894Ssam * single device? IN, OUT or both?
2286147894Ssam */
2287147894Ssamstatic int
2288162012Ssampcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
2289147894Ssam{
2290147894Ssam#ifdef HAVE_PF_PACKET_SOCKETS
2291147894Ssam	if (!handle->md.sock_packet) {
2292147894Ssam		handle->direction = d;
2293147894Ssam		return 0;
2294147894Ssam	}
2295147894Ssam#endif
2296147894Ssam	/*
2297147894Ssam	 * We're not using PF_PACKET sockets, so we can't determine
2298147894Ssam	 * the direction of the packet.
2299147894Ssam	 */
2300190225Srpaulo	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2301147894Ssam	    "Setting direction is not supported on SOCK_PACKET sockets");
2302147894Ssam	return -1;
2303147894Ssam}
2304147894Ssam
2305190225Srpaulo
2306190225Srpaulo#ifdef HAVE_PF_PACKET_SOCKETS
2307147894Ssam/*
2308190225Srpaulo * Map the PACKET_ value to a LINUX_SLL_ value; we
2309190225Srpaulo * want the same numerical value to be used in
2310190225Srpaulo * the link-layer header even if the numerical values
2311190225Srpaulo * for the PACKET_ #defines change, so that programs
2312190225Srpaulo * that look at the packet type field will always be
2313190225Srpaulo * able to handle DLT_LINUX_SLL captures.
2314190225Srpaulo */
2315190225Srpaulostatic short int
2316190225Srpaulomap_packet_type_to_sll_type(short int sll_pkttype)
2317190225Srpaulo{
2318190225Srpaulo	switch (sll_pkttype) {
2319190225Srpaulo
2320190225Srpaulo	case PACKET_HOST:
2321190225Srpaulo		return htons(LINUX_SLL_HOST);
2322190225Srpaulo
2323190225Srpaulo	case PACKET_BROADCAST:
2324190225Srpaulo		return htons(LINUX_SLL_BROADCAST);
2325190225Srpaulo
2326190225Srpaulo	case PACKET_MULTICAST:
2327190225Srpaulo		return  htons(LINUX_SLL_MULTICAST);
2328190225Srpaulo
2329190225Srpaulo	case PACKET_OTHERHOST:
2330190225Srpaulo		return htons(LINUX_SLL_OTHERHOST);
2331190225Srpaulo
2332190225Srpaulo	case PACKET_OUTGOING:
2333190225Srpaulo		return htons(LINUX_SLL_OUTGOING);
2334190225Srpaulo
2335190225Srpaulo	default:
2336190225Srpaulo		return -1;
2337190225Srpaulo	}
2338190225Srpaulo}
2339190225Srpaulo#endif
2340190225Srpaulo
2341190225Srpaulo/*
2342127664Sbms *  Linux uses the ARP hardware type to identify the type of an
2343127664Sbms *  interface. pcap uses the DLT_xxx constants for this. This
234498530Sfenner *  function takes a pointer to a "pcap_t", and an ARPHRD_xxx
234598530Sfenner *  constant, as arguments, and sets "handle->linktype" to the
234698530Sfenner *  appropriate DLT_XXX constant and sets "handle->offset" to
234798530Sfenner *  the appropriate value (to make "handle->offset" plus link-layer
234898530Sfenner *  header length be a multiple of 4, so that the link-layer payload
234998530Sfenner *  will be aligned on a 4-byte boundary when capturing packets).
235098530Sfenner *  (If the offset isn't set here, it'll be 0; add code as appropriate
235198530Sfenner *  for cases where it shouldn't be 0.)
2352127664Sbms *
2353127664Sbms *  If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2354127664Sbms *  in cooked mode; otherwise, we can't use cooked mode, so we have
2355127664Sbms *  to pick some type that works in raw mode, or fail.
2356127664Sbms *
235798530Sfenner *  Sets the link type to -1 if unable to map the type.
235875107Sfenner */
2359127664Sbmsstatic void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
236075107Sfenner{
236175107Sfenner	switch (arptype) {
236298530Sfenner
236339291Sfenner	case ARPHRD_ETHER:
2364146768Ssam		/*
2365146768Ssam		 * This is (presumably) a real Ethernet capture; give it a
2366146768Ssam		 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2367146768Ssam		 * that an application can let you choose it, in case you're
2368146768Ssam		 * capturing DOCSIS traffic that a Cisco Cable Modem
2369146768Ssam		 * Termination System is putting out onto an Ethernet (it
2370146768Ssam		 * doesn't put an Ethernet header onto the wire, it puts raw
2371146768Ssam		 * DOCSIS frames out on the wire inside the low-level
2372146768Ssam		 * Ethernet framing).
2373146768Ssam		 *
2374146768Ssam		 * XXX - are there any sorts of "fake Ethernet" that have
2375146768Ssam		 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2376146768Ssam		 * a Cisco CMTS won't put traffic onto it or get traffic
2377190225Srpaulo		 * bridged onto it?  ISDN is handled in "activate_new()",
2378146768Ssam		 * as we fall back on cooked mode there; are there any
2379146768Ssam		 * others?
2380146768Ssam		 */
2381146768Ssam		handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2382146768Ssam		/*
2383146768Ssam		 * If that fails, just leave the list empty.
2384146768Ssam		 */
2385146768Ssam		if (handle->dlt_list != NULL) {
2386146768Ssam			handle->dlt_list[0] = DLT_EN10MB;
2387146768Ssam			handle->dlt_list[1] = DLT_DOCSIS;
2388146768Ssam			handle->dlt_count = 2;
2389146768Ssam		}
2390146768Ssam		/* FALLTHROUGH */
2391146768Ssam
239239291Sfenner	case ARPHRD_METRICOM:
239398530Sfenner	case ARPHRD_LOOPBACK:
239498530Sfenner		handle->linktype = DLT_EN10MB;
239598530Sfenner		handle->offset = 2;
239698530Sfenner		break;
239798530Sfenner
239898530Sfenner	case ARPHRD_EETHER:
239998530Sfenner		handle->linktype = DLT_EN3MB;
240098530Sfenner		break;
240198530Sfenner
240298530Sfenner	case ARPHRD_AX25:
2403190225Srpaulo		handle->linktype = DLT_AX25_KISS;
240498530Sfenner		break;
240598530Sfenner
240698530Sfenner	case ARPHRD_PRONET:
240798530Sfenner		handle->linktype = DLT_PRONET;
240898530Sfenner		break;
240998530Sfenner
241098530Sfenner	case ARPHRD_CHAOS:
241198530Sfenner		handle->linktype = DLT_CHAOS;
241298530Sfenner		break;
2413214518Srpaulo#ifndef ARPHRD_CAN
2414214518Srpaulo#define ARPHRD_CAN 280
2415214518Srpaulo#endif
2416214518Srpaulo	case ARPHRD_CAN:
2417214518Srpaulo		handle->linktype = DLT_CAN_SOCKETCAN;
2418214518Srpaulo		break;
241998530Sfenner
242075107Sfenner#ifndef ARPHRD_IEEE802_TR
242175107Sfenner#define ARPHRD_IEEE802_TR 800	/* From Linux 2.4 */
242275107Sfenner#endif
242375107Sfenner	case ARPHRD_IEEE802_TR:
242498530Sfenner	case ARPHRD_IEEE802:
242598530Sfenner		handle->linktype = DLT_IEEE802;
242698530Sfenner		handle->offset = 2;
242798530Sfenner		break;
242839291Sfenner
242998530Sfenner	case ARPHRD_ARCNET:
2430127664Sbms		handle->linktype = DLT_ARCNET_LINUX;
243198530Sfenner		break;
243298530Sfenner
2433127664Sbms#ifndef ARPHRD_FDDI	/* From Linux 2.2.13 */
2434127664Sbms#define ARPHRD_FDDI	774
2435127664Sbms#endif
243698530Sfenner	case ARPHRD_FDDI:
243798530Sfenner		handle->linktype = DLT_FDDI;
243898530Sfenner		handle->offset = 3;
243998530Sfenner		break;
244098530Sfenner
244175107Sfenner#ifndef ARPHRD_ATM  /* FIXME: How to #include this? */
244275107Sfenner#define ARPHRD_ATM 19
244375107Sfenner#endif
244498530Sfenner	case ARPHRD_ATM:
244598530Sfenner		/*
244698530Sfenner		 * The Classical IP implementation in ATM for Linux
244798530Sfenner		 * supports both what RFC 1483 calls "LLC Encapsulation",
244898530Sfenner		 * in which each packet has an LLC header, possibly
244998530Sfenner		 * with a SNAP header as well, prepended to it, and
245098530Sfenner		 * what RFC 1483 calls "VC Based Multiplexing", in which
245198530Sfenner		 * different virtual circuits carry different network
245298530Sfenner		 * layer protocols, and no header is prepended to packets.
245398530Sfenner		 *
245498530Sfenner		 * They both have an ARPHRD_ type of ARPHRD_ATM, so
245598530Sfenner		 * you can't use the ARPHRD_ type to find out whether
245698530Sfenner		 * captured packets will have an LLC header, and,
245798530Sfenner		 * while there's a socket ioctl to *set* the encapsulation
245898530Sfenner		 * type, there's no ioctl to *get* the encapsulation type.
245998530Sfenner		 *
246098530Sfenner		 * This means that
246198530Sfenner		 *
246298530Sfenner		 *	programs that dissect Linux Classical IP frames
246398530Sfenner		 *	would have to check for an LLC header and,
246498530Sfenner		 *	depending on whether they see one or not, dissect
246598530Sfenner		 *	the frame as LLC-encapsulated or as raw IP (I
246698530Sfenner		 *	don't know whether there's any traffic other than
246798530Sfenner		 *	IP that would show up on the socket, or whether
246898530Sfenner		 *	there's any support for IPv6 in the Linux
246998530Sfenner		 *	Classical IP code);
247098530Sfenner		 *
247198530Sfenner		 *	filter expressions would have to compile into
247298530Sfenner		 *	code that checks for an LLC header and does
247398530Sfenner		 *	the right thing.
247498530Sfenner		 *
247598530Sfenner		 * Both of those are a nuisance - and, at least on systems
247698530Sfenner		 * that support PF_PACKET sockets, we don't have to put
247798530Sfenner		 * up with those nuisances; instead, we can just capture
2478127664Sbms		 * in cooked mode.  That's what we'll do, if we can.
2479127664Sbms		 * Otherwise, we'll just fail.
248098530Sfenner		 */
2481127664Sbms		if (cooked_ok)
2482127664Sbms			handle->linktype = DLT_LINUX_SLL;
2483127664Sbms		else
2484127664Sbms			handle->linktype = -1;
248598530Sfenner		break;
248639291Sfenner
248798530Sfenner#ifndef ARPHRD_IEEE80211  /* From Linux 2.4.6 */
248898530Sfenner#define ARPHRD_IEEE80211 801
248998530Sfenner#endif
249098530Sfenner	case ARPHRD_IEEE80211:
249198530Sfenner		handle->linktype = DLT_IEEE802_11;
249298530Sfenner		break;
249398530Sfenner
2494127664Sbms#ifndef ARPHRD_IEEE80211_PRISM  /* From Linux 2.4.18 */
2495127664Sbms#define ARPHRD_IEEE80211_PRISM 802
2496127664Sbms#endif
2497127664Sbms	case ARPHRD_IEEE80211_PRISM:
2498127664Sbms		handle->linktype = DLT_PRISM_HEADER;
2499127664Sbms		break;
2500127664Sbms
2501162012Ssam#ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2502162012Ssam#define ARPHRD_IEEE80211_RADIOTAP 803
2503162012Ssam#endif
2504162012Ssam	case ARPHRD_IEEE80211_RADIOTAP:
2505162012Ssam		handle->linktype = DLT_IEEE802_11_RADIO;
2506162012Ssam		break;
2507162012Ssam
250875107Sfenner	case ARPHRD_PPP:
250998530Sfenner		/*
251098530Sfenner		 * Some PPP code in the kernel supplies no link-layer
251198530Sfenner		 * header whatsoever to PF_PACKET sockets; other PPP
251298530Sfenner		 * code supplies PPP link-layer headers ("syncppp.c");
251398530Sfenner		 * some PPP code might supply random link-layer
251498530Sfenner		 * headers (PPP over ISDN - there's code in Ethereal,
251598530Sfenner		 * for example, to cope with PPP-over-ISDN captures
251698530Sfenner		 * with which the Ethereal developers have had to cope,
251798530Sfenner		 * heuristically trying to determine which of the
251898530Sfenner		 * oddball link-layer headers particular packets have).
251998530Sfenner		 *
252098530Sfenner		 * As such, we just punt, and run all PPP interfaces
2521127664Sbms		 * in cooked mode, if we can; otherwise, we just treat
2522127664Sbms		 * it as DLT_RAW, for now - if somebody needs to capture,
2523127664Sbms		 * on a 2.0[.x] kernel, on PPP devices that supply a
2524127664Sbms		 * link-layer header, they'll have to add code here to
2525127664Sbms		 * map to the appropriate DLT_ type (possibly adding a
2526127664Sbms		 * new DLT_ type, if necessary).
252798530Sfenner		 */
2528127664Sbms		if (cooked_ok)
2529127664Sbms			handle->linktype = DLT_LINUX_SLL;
2530127664Sbms		else {
2531127664Sbms			/*
2532127664Sbms			 * XXX - handle ISDN types here?  We can't fall
2533127664Sbms			 * back on cooked sockets, so we'd have to
2534127664Sbms			 * figure out from the device name what type of
2535127664Sbms			 * link-layer encapsulation it's using, and map
2536127664Sbms			 * that to an appropriate DLT_ value, meaning
2537127664Sbms			 * we'd map "isdnN" devices to DLT_RAW (they
2538127664Sbms			 * supply raw IP packets with no link-layer
2539127664Sbms			 * header) and "isdY" devices to a new DLT_I4L_IP
2540127664Sbms			 * type that has only an Ethernet packet type as
2541127664Sbms			 * a link-layer header.
2542127664Sbms			 *
2543127664Sbms			 * But sometimes we seem to get random crap
2544127664Sbms			 * in the link-layer header when capturing on
2545127664Sbms			 * ISDN devices....
2546127664Sbms			 */
2547127664Sbms			handle->linktype = DLT_RAW;
2548127664Sbms		}
254998530Sfenner		break;
255098530Sfenner
2551127664Sbms#ifndef ARPHRD_CISCO
2552127664Sbms#define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2553127664Sbms#endif
2554127664Sbms	case ARPHRD_CISCO:
255598530Sfenner		handle->linktype = DLT_C_HDLC;
255698530Sfenner		break;
255798530Sfenner
255875107Sfenner	/* Not sure if this is correct for all tunnels, but it
255975107Sfenner	 * works for CIPE */
256075107Sfenner	case ARPHRD_TUNNEL:
256175107Sfenner#ifndef ARPHRD_SIT
2562127664Sbms#define ARPHRD_SIT 776	/* From Linux 2.2.13 */
256375107Sfenner#endif
256475107Sfenner	case ARPHRD_SIT:
256575107Sfenner	case ARPHRD_CSLIP:
256675107Sfenner	case ARPHRD_SLIP6:
256775107Sfenner	case ARPHRD_CSLIP6:
256898530Sfenner	case ARPHRD_ADAPT:
256998530Sfenner	case ARPHRD_SLIP:
2570127664Sbms#ifndef ARPHRD_RAWHDLC
2571127664Sbms#define ARPHRD_RAWHDLC 518
2572127664Sbms#endif
2573127664Sbms	case ARPHRD_RAWHDLC:
2574127664Sbms#ifndef ARPHRD_DLCI
2575127664Sbms#define ARPHRD_DLCI 15
2576127664Sbms#endif
2577127664Sbms	case ARPHRD_DLCI:
257898530Sfenner		/*
257998530Sfenner		 * XXX - should some of those be mapped to DLT_LINUX_SLL
258098530Sfenner		 * instead?  Should we just map all of them to DLT_LINUX_SLL?
258198530Sfenner		 */
258298530Sfenner		handle->linktype = DLT_RAW;
258398530Sfenner		break;
258498530Sfenner
2585127664Sbms#ifndef ARPHRD_FRAD
2586127664Sbms#define ARPHRD_FRAD 770
2587127664Sbms#endif
2588127664Sbms	case ARPHRD_FRAD:
2589127664Sbms		handle->linktype = DLT_FRELAY;
2590127664Sbms		break;
2591127664Sbms
259298530Sfenner	case ARPHRD_LOCALTLK:
259398530Sfenner		handle->linktype = DLT_LTALK;
259498530Sfenner		break;
259598530Sfenner
2596127664Sbms#ifndef ARPHRD_FCPP
2597127664Sbms#define ARPHRD_FCPP	784
2598127664Sbms#endif
2599127664Sbms	case ARPHRD_FCPP:
2600127664Sbms#ifndef ARPHRD_FCAL
2601127664Sbms#define ARPHRD_FCAL	785
2602127664Sbms#endif
2603127664Sbms	case ARPHRD_FCAL:
2604127664Sbms#ifndef ARPHRD_FCPL
2605127664Sbms#define ARPHRD_FCPL	786
2606127664Sbms#endif
2607127664Sbms	case ARPHRD_FCPL:
2608127664Sbms#ifndef ARPHRD_FCFABRIC
2609127664Sbms#define ARPHRD_FCFABRIC	787
2610127664Sbms#endif
2611127664Sbms	case ARPHRD_FCFABRIC:
2612127664Sbms		/*
2613127664Sbms		 * We assume that those all mean RFC 2625 IP-over-
2614127664Sbms		 * Fibre Channel, with the RFC 2625 header at
2615127664Sbms		 * the beginning of the packet.
2616127664Sbms		 */
2617127664Sbms		handle->linktype = DLT_IP_OVER_FC;
2618127664Sbms		break;
2619127664Sbms
2620146768Ssam#ifndef ARPHRD_IRDA
2621146768Ssam#define ARPHRD_IRDA	783
2622146768Ssam#endif
2623127664Sbms	case ARPHRD_IRDA:
2624127664Sbms		/* Don't expect IP packet out of this interfaces... */
2625127664Sbms		handle->linktype = DLT_LINUX_IRDA;
2626127664Sbms		/* We need to save packet direction for IrDA decoding,
2627127664Sbms		 * so let's use "Linux-cooked" mode. Jean II */
2628127664Sbms		//handle->md.cooked = 1;
2629127664Sbms		break;
2630127664Sbms
2631172677Smlaier	/* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2632172677Smlaier	 * is needed, please report it to <daniele@orlandi.com> */
2633172677Smlaier#ifndef ARPHRD_LAPD
2634172677Smlaier#define ARPHRD_LAPD	8445
2635172677Smlaier#endif
2636172677Smlaier	case ARPHRD_LAPD:
2637172677Smlaier		/* Don't expect IP packet out of this interfaces... */
2638172677Smlaier		handle->linktype = DLT_LINUX_LAPD;
2639172677Smlaier		break;
2640172677Smlaier
2641190225Srpaulo#ifndef ARPHRD_NONE
2642190225Srpaulo#define ARPHRD_NONE	0xFFFE
2643190225Srpaulo#endif
2644190225Srpaulo	case ARPHRD_NONE:
2645190225Srpaulo		/*
2646190225Srpaulo		 * No link-layer header; packets are just IP
2647190225Srpaulo		 * packets, so use DLT_RAW.
2648190225Srpaulo		 */
2649190225Srpaulo		handle->linktype = DLT_RAW;
2650190225Srpaulo		break;
2651190225Srpaulo
265298530Sfenner	default:
265398530Sfenner		handle->linktype = -1;
265498530Sfenner		break;
265575107Sfenner	}
265675107Sfenner}
265739291Sfenner
265875107Sfenner/* ===== Functions to interface to the newer kernels ================== */
265939291Sfenner
266075107Sfenner/*
2661190225Srpaulo * Try to open a packet socket using the new kernel PF_PACKET interface.
2662190225Srpaulo * Returns 1 on success, 0 on an error that means the new interface isn't
2663190225Srpaulo * present (so the old SOCK_PACKET interface should be tried), and a
2664190225Srpaulo * PCAP_ERROR_ value on an error that means that the old mechanism won't
2665190225Srpaulo * work either (so it shouldn't be tried).
266675107Sfenner */
266775107Sfennerstatic int
2668190225Srpauloactivate_new(pcap_t *handle)
266975107Sfenner{
267075107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
2671214518Srpaulo	const char		*device = handle->opt.source;
2672214518Srpaulo	int			is_any_device = (strcmp(device, "any") == 0);
2673214518Srpaulo	int			sock_fd = -1, arptype;
2674214518Srpaulo#ifdef HAVE_PACKET_AUXDATA
2675214518Srpaulo	int			val;
2676214518Srpaulo#endif
2677190225Srpaulo	int			err = 0;
267875107Sfenner	struct packet_mreq	mr;
267939291Sfenner
2680190225Srpaulo	/*
2681214518Srpaulo	 * Open a socket with protocol family packet. If the
2682214518Srpaulo	 * "any" device was specified, we open a SOCK_DGRAM
2683214518Srpaulo	 * socket for the cooked interface, otherwise we first
2684214518Srpaulo	 * try a SOCK_RAW socket for the raw interface.
2685190225Srpaulo	 */
2686214518Srpaulo	sock_fd = is_any_device ?
2687214518Srpaulo		socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
2688214518Srpaulo		socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
268939291Sfenner
2690190225Srpaulo	if (sock_fd == -1) {
2691190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
2692190225Srpaulo			 pcap_strerror(errno) );
2693190225Srpaulo		return 0;	/* try old mechanism */
2694190225Srpaulo	}
269539291Sfenner
2696190225Srpaulo	/* It seems the kernel supports the new interface. */
2697190225Srpaulo	handle->md.sock_packet = 0;
269839291Sfenner
2699190225Srpaulo	/*
2700190225Srpaulo	 * Get the interface index of the loopback device.
2701190225Srpaulo	 * If the attempt fails, don't fail, just set the
2702190225Srpaulo	 * "md.lo_ifindex" to -1.
2703190225Srpaulo	 *
2704190225Srpaulo	 * XXX - can there be more than one device that loops
2705190225Srpaulo	 * packets back, i.e. devices other than "lo"?  If so,
2706190225Srpaulo	 * we'd need to find them all, and have an array of
2707190225Srpaulo	 * indices for them, and check all of them in
2708190225Srpaulo	 * "pcap_read_packet()".
2709190225Srpaulo	 */
2710190225Srpaulo	handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
271175107Sfenner
2712190225Srpaulo	/*
2713190225Srpaulo	 * Default value for offset to align link-layer payload
2714190225Srpaulo	 * on a 4-byte boundary.
2715190225Srpaulo	 */
2716190225Srpaulo	handle->offset	 = 0;
271775107Sfenner
2718190225Srpaulo	/*
2719190225Srpaulo	 * What kind of frames do we have to deal with? Fall back
2720190225Srpaulo	 * to cooked mode if we have an unknown interface type
2721190225Srpaulo	 * or a type we know doesn't work well in raw mode.
2722190225Srpaulo	 */
2723214518Srpaulo	if (!is_any_device) {
2724190225Srpaulo		/* Assume for now we don't need cooked mode. */
2725190225Srpaulo		handle->md.cooked = 0;
272698530Sfenner
2727190225Srpaulo		if (handle->opt.rfmon) {
2728190225Srpaulo			/*
2729190225Srpaulo			 * We were asked to turn on monitor mode.
2730190225Srpaulo			 * Do so before we get the link-layer type,
2731190225Srpaulo			 * because entering monitor mode could change
2732190225Srpaulo			 * the link-layer type.
2733190225Srpaulo			 */
2734214518Srpaulo			err = enter_rfmon_mode(handle, sock_fd, device);
2735190225Srpaulo			if (err < 0) {
2736190225Srpaulo				/* Hard failure */
2737190225Srpaulo				close(sock_fd);
2738190225Srpaulo				return err;
2739127664Sbms			}
2740190225Srpaulo			if (err == 0) {
274175107Sfenner				/*
2742190225Srpaulo				 * Nothing worked for turning monitor mode
2743190225Srpaulo				 * on.
274475107Sfenner				 */
2745190225Srpaulo				close(sock_fd);
2746190225Srpaulo				return PCAP_ERROR_RFMON_NOTSUP;
2747190225Srpaulo			}
2748214518Srpaulo
2749214518Srpaulo			/*
2750214518Srpaulo			 * Either monitor mode has been turned on for
2751214518Srpaulo			 * the device, or we've been given a different
2752214518Srpaulo			 * device to open for monitor mode.  If we've
2753214518Srpaulo			 * been given a different device, use it.
2754214518Srpaulo			 */
2755214518Srpaulo			if (handle->md.mondevice != NULL)
2756214518Srpaulo				device = handle->md.mondevice;
2757190225Srpaulo		}
2758190225Srpaulo		arptype	= iface_get_arptype(sock_fd, device, handle->errbuf);
2759190225Srpaulo		if (arptype < 0) {
2760190225Srpaulo			close(sock_fd);
2761190225Srpaulo			return arptype;
2762190225Srpaulo		}
2763190225Srpaulo		map_arphrd_to_dlt(handle, arptype, 1);
2764190225Srpaulo		if (handle->linktype == -1 ||
2765190225Srpaulo		    handle->linktype == DLT_LINUX_SLL ||
2766190225Srpaulo		    handle->linktype == DLT_LINUX_IRDA ||
2767190225Srpaulo		    handle->linktype == DLT_LINUX_LAPD ||
2768190225Srpaulo		    (handle->linktype == DLT_EN10MB &&
2769190225Srpaulo		     (strncmp("isdn", device, 4) == 0 ||
2770190225Srpaulo		      strncmp("isdY", device, 4) == 0))) {
2771190225Srpaulo			/*
2772190225Srpaulo			 * Unknown interface type (-1), or a
2773190225Srpaulo			 * device we explicitly chose to run
2774190225Srpaulo			 * in cooked mode (e.g., PPP devices),
2775190225Srpaulo			 * or an ISDN device (whose link-layer
2776190225Srpaulo			 * type we can only determine by using
2777190225Srpaulo			 * APIs that may be different on different
2778190225Srpaulo			 * kernels) - reopen in cooked mode.
2779190225Srpaulo			 */
2780190225Srpaulo			if (close(sock_fd) == -1) {
2781190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2782190225Srpaulo					 "close: %s", pcap_strerror(errno));
2783190225Srpaulo				return PCAP_ERROR;
2784190225Srpaulo			}
2785190225Srpaulo			sock_fd = socket(PF_PACKET, SOCK_DGRAM,
2786190225Srpaulo			    htons(ETH_P_ALL));
2787190225Srpaulo			if (sock_fd == -1) {
2788190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2789190225Srpaulo				    "socket: %s", pcap_strerror(errno));
2790190225Srpaulo				return PCAP_ERROR;
2791190225Srpaulo			}
2792190225Srpaulo			handle->md.cooked = 1;
279375107Sfenner
2794190225Srpaulo			/*
2795190225Srpaulo			 * Get rid of any link-layer type list
2796190225Srpaulo			 * we allocated - this only supports cooked
2797190225Srpaulo			 * capture.
2798190225Srpaulo			 */
2799190225Srpaulo			if (handle->dlt_list != NULL) {
2800190225Srpaulo				free(handle->dlt_list);
2801190225Srpaulo				handle->dlt_list = NULL;
2802190225Srpaulo				handle->dlt_count = 0;
2803190225Srpaulo			}
2804190225Srpaulo
2805190225Srpaulo			if (handle->linktype == -1) {
2806146768Ssam				/*
2807190225Srpaulo				 * Warn that we're falling back on
2808190225Srpaulo				 * cooked mode; we may want to
2809190225Srpaulo				 * update "map_arphrd_to_dlt()"
2810190225Srpaulo				 * to handle the new type.
2811146768Ssam				 */
2812190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2813190225Srpaulo					"arptype %d not "
2814190225Srpaulo					"supported by libpcap - "
2815190225Srpaulo					"falling back to cooked "
2816190225Srpaulo					"socket",
2817190225Srpaulo					arptype);
281875107Sfenner			}
281975107Sfenner
282075107Sfenner			/*
2821190225Srpaulo			 * IrDA capture is not a real "cooked" capture,
2822190225Srpaulo			 * it's IrLAP frames, not IP packets.  The
2823190225Srpaulo			 * same applies to LAPD capture.
282475107Sfenner			 */
2825190225Srpaulo			if (handle->linktype != DLT_LINUX_IRDA &&
2826190225Srpaulo			    handle->linktype != DLT_LINUX_LAPD)
2827190225Srpaulo				handle->linktype = DLT_LINUX_SLL;
2828190225Srpaulo		}
282975107Sfenner
2830190225Srpaulo		handle->md.ifindex = iface_get_id(sock_fd, device,
2831190225Srpaulo		    handle->errbuf);
2832190225Srpaulo		if (handle->md.ifindex == -1) {
2833190225Srpaulo			close(sock_fd);
2834190225Srpaulo			return PCAP_ERROR;
283575107Sfenner		}
283675107Sfenner
2837190225Srpaulo		if ((err = iface_bind(sock_fd, handle->md.ifindex,
2838190225Srpaulo		    handle->errbuf)) != 1) {
2839190225Srpaulo		    	close(sock_fd);
2840190225Srpaulo			if (err < 0)
2841190225Srpaulo				return err;
2842190225Srpaulo			else
2843190225Srpaulo				return 0;	/* try old mechanism */
2844190225Srpaulo		}
2845190225Srpaulo	} else {
2846127664Sbms		/*
2847214518Srpaulo		 * The "any" device.
2848127664Sbms		 */
2849214518Srpaulo		if (handle->opt.rfmon) {
2850214518Srpaulo			/*
2851214518Srpaulo			 * It doesn't support monitor mode.
2852214518Srpaulo			 */
2853214518Srpaulo			return PCAP_ERROR_RFMON_NOTSUP;
2854214518Srpaulo		}
2855214518Srpaulo
2856214518Srpaulo		/*
2857214518Srpaulo		 * It uses cooked mode.
2858214518Srpaulo		 */
2859190225Srpaulo		handle->md.cooked = 1;
2860190225Srpaulo		handle->linktype = DLT_LINUX_SLL;
286175107Sfenner
2862127664Sbms		/*
2863190225Srpaulo		 * We're not bound to a device.
2864190225Srpaulo		 * For now, we're using this as an indication
2865190225Srpaulo		 * that we can't transmit; stop doing that only
2866190225Srpaulo		 * if we figure out how to transmit in cooked
2867190225Srpaulo		 * mode.
286875107Sfenner		 */
2869190225Srpaulo		handle->md.ifindex = -1;
2870190225Srpaulo	}
287175107Sfenner
2872190225Srpaulo	/*
2873190225Srpaulo	 * Select promiscuous mode on if "promisc" is set.
2874190225Srpaulo	 *
2875190225Srpaulo	 * Do not turn allmulti mode on if we don't select
2876190225Srpaulo	 * promiscuous mode - on some devices (e.g., Orinoco
2877190225Srpaulo	 * wireless interfaces), allmulti mode isn't supported
2878190225Srpaulo	 * and the driver implements it by turning promiscuous
2879190225Srpaulo	 * mode on, and that screws up the operation of the
2880190225Srpaulo	 * card as a normal networking interface, and on no
2881190225Srpaulo	 * other platform I know of does starting a non-
2882190225Srpaulo	 * promiscuous capture affect which multicast packets
2883190225Srpaulo	 * are received by the interface.
2884190225Srpaulo	 */
288539291Sfenner
2886190225Srpaulo	/*
2887190225Srpaulo	 * Hmm, how can we set promiscuous mode on all interfaces?
2888214518Srpaulo	 * I am not sure if that is possible at all.  For now, we
2889214518Srpaulo	 * silently ignore attempts to turn promiscuous mode on
2890214518Srpaulo	 * for the "any" device (so you don't have to explicitly
2891214518Srpaulo	 * disable it in programs such as tcpdump).
2892190225Srpaulo	 */
289375107Sfenner
2894214518Srpaulo	if (!is_any_device && handle->opt.promisc) {
2895190225Srpaulo		memset(&mr, 0, sizeof(mr));
2896190225Srpaulo		mr.mr_ifindex = handle->md.ifindex;
2897190225Srpaulo		mr.mr_type    = PACKET_MR_PROMISC;
2898190225Srpaulo		if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
2899190225Srpaulo		    &mr, sizeof(mr)) == -1) {
2900190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2901190225Srpaulo				"setsockopt: %s", pcap_strerror(errno));
2902190225Srpaulo			close(sock_fd);
2903190225Srpaulo			return PCAP_ERROR;
2904190225Srpaulo		}
2905190225Srpaulo	}
290675107Sfenner
2907190225Srpaulo	/* Enable auxillary data if supported and reserve room for
2908190225Srpaulo	 * reconstructing VLAN headers. */
2909190225Srpaulo#ifdef HAVE_PACKET_AUXDATA
2910190225Srpaulo	val = 1;
2911190225Srpaulo	if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
2912190225Srpaulo		       sizeof(val)) == -1 && errno != ENOPROTOOPT) {
2913190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2914190225Srpaulo			 "setsockopt: %s", pcap_strerror(errno));
2915190225Srpaulo		close(sock_fd);
2916190225Srpaulo		return PCAP_ERROR;
2917190225Srpaulo	}
2918190225Srpaulo	handle->offset += VLAN_TAG_LEN;
2919190225Srpaulo#endif /* HAVE_PACKET_AUXDATA */
292075107Sfenner
2921190225Srpaulo	/*
2922190225Srpaulo	 * This is a 2.2[.x] or later kernel (we know that
2923190225Srpaulo	 * because we're not using a SOCK_PACKET socket -
2924190225Srpaulo	 * PF_PACKET is supported only in 2.2 and later
2925190225Srpaulo	 * kernels).
2926190225Srpaulo	 *
2927190225Srpaulo	 * We can safely pass "recvfrom()" a byte count
2928190225Srpaulo	 * based on the snapshot length.
2929190225Srpaulo	 *
2930190225Srpaulo	 * If we're in cooked mode, make the snapshot length
2931190225Srpaulo	 * large enough to hold a "cooked mode" header plus
2932190225Srpaulo	 * 1 byte of packet data (so we don't pass a byte
2933190225Srpaulo	 * count of 0 to "recvfrom()").
2934190225Srpaulo	 */
2935190225Srpaulo	if (handle->md.cooked) {
2936190225Srpaulo		if (handle->snapshot < SLL_HDR_LEN + 1)
2937190225Srpaulo			handle->snapshot = SLL_HDR_LEN + 1;
2938190225Srpaulo	}
2939190225Srpaulo	handle->bufsize = handle->snapshot;
294075107Sfenner
2941190225Srpaulo	/* Save the socket FD in the pcap structure */
2942190225Srpaulo	handle->fd = sock_fd;
2943127664Sbms
2944190225Srpaulo	return 1;
294575107Sfenner#else
2946127664Sbms	strncpy(ebuf,
2947127664Sbms		"New packet capturing interface not supported by build "
294875107Sfenner		"environment", PCAP_ERRBUF_SIZE);
294975107Sfenner	return 0;
295039291Sfenner#endif
295175107Sfenner}
295239291Sfenner
2953190225Srpaulostatic int
2954190225Srpauloactivate_mmap(pcap_t *handle)
2955190225Srpaulo{
2956190225Srpaulo#ifdef HAVE_PACKET_RING
2957190225Srpaulo	int ret;
2958190225Srpaulo
2959214518Srpaulo	/*
2960214518Srpaulo	 * Attempt to allocate a buffer to hold the contents of one
2961214518Srpaulo	 * packet, for use by the oneshot callback.
2962214518Srpaulo	 */
2963214518Srpaulo	handle->md.oneshot_buffer = malloc(handle->snapshot);
2964214518Srpaulo	if (handle->md.oneshot_buffer == NULL) {
2965214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2966214518Srpaulo			 "can't allocate oneshot buffer: %s",
2967214518Srpaulo			 pcap_strerror(errno));
2968214518Srpaulo		return PCAP_ERROR;
2969214518Srpaulo	}
2970214518Srpaulo
2971190225Srpaulo	if (handle->opt.buffer_size == 0) {
2972190225Srpaulo		/* by default request 2M for the ring buffer */
2973190225Srpaulo		handle->opt.buffer_size = 2*1024*1024;
2974190225Srpaulo	}
2975190225Srpaulo	ret = prepare_tpacket_socket(handle);
2976214518Srpaulo	if (ret != 1) {
2977214518Srpaulo		free(handle->md.oneshot_buffer);
2978190225Srpaulo		return ret;
2979214518Srpaulo	}
2980190225Srpaulo	ret = create_ring(handle);
2981214518Srpaulo	if (ret != 1) {
2982214518Srpaulo		free(handle->md.oneshot_buffer);
2983190225Srpaulo		return ret;
2984214518Srpaulo	}
2985190225Srpaulo
2986190225Srpaulo	/* override some defaults and inherit the other fields from
2987190225Srpaulo	 * activate_new
2988190225Srpaulo	 * handle->offset is used to get the current position into the rx ring
2989190225Srpaulo	 * handle->cc is used to store the ring size */
2990190225Srpaulo	handle->read_op = pcap_read_linux_mmap;
2991190225Srpaulo	handle->cleanup_op = pcap_cleanup_linux_mmap;
2992190225Srpaulo	handle->setfilter_op = pcap_setfilter_linux_mmap;
2993190225Srpaulo	handle->setnonblock_op = pcap_setnonblock_mmap;
2994190225Srpaulo	handle->getnonblock_op = pcap_getnonblock_mmap;
2995214518Srpaulo	handle->oneshot_callback = pcap_oneshot_mmap;
2996190225Srpaulo	handle->selectable_fd = handle->fd;
2997190225Srpaulo	return 1;
2998190225Srpaulo#else /* HAVE_PACKET_RING */
2999190225Srpaulo	return 0;
3000190225Srpaulo#endif /* HAVE_PACKET_RING */
3001190225Srpaulo}
3002190225Srpaulo
3003190225Srpaulo#ifdef HAVE_PACKET_RING
3004190225Srpaulostatic int
3005190225Srpauloprepare_tpacket_socket(pcap_t *handle)
3006190225Srpaulo{
3007190225Srpaulo#ifdef HAVE_TPACKET2
3008190225Srpaulo	socklen_t len;
3009190225Srpaulo	int val;
3010190225Srpaulo#endif
3011190225Srpaulo
3012190225Srpaulo	handle->md.tp_version = TPACKET_V1;
3013190225Srpaulo	handle->md.tp_hdrlen = sizeof(struct tpacket_hdr);
3014190225Srpaulo
3015190225Srpaulo#ifdef HAVE_TPACKET2
3016190225Srpaulo	/* Probe whether kernel supports TPACKET_V2 */
3017190225Srpaulo	val = TPACKET_V2;
3018190225Srpaulo	len = sizeof(val);
3019190225Srpaulo	if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
3020190225Srpaulo		if (errno == ENOPROTOOPT)
3021214518Srpaulo			return 1;	/* no - just drive on */
3022214518Srpaulo
3023214518Srpaulo		/* Yes - treat as a failure. */
3024190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3025214518Srpaulo		    "can't get TPACKET_V2 header len on packet socket: %s",
3026214518Srpaulo		    pcap_strerror(errno));
3027214518Srpaulo		return -1;
3028190225Srpaulo	}
3029190225Srpaulo	handle->md.tp_hdrlen = val;
3030190225Srpaulo
3031190225Srpaulo	val = TPACKET_V2;
3032190225Srpaulo	if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
3033190225Srpaulo		       sizeof(val)) < 0) {
3034190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3035214518Srpaulo		    "can't activate TPACKET_V2 on packet socket: %s",
3036214518Srpaulo		    pcap_strerror(errno));
3037214518Srpaulo		return -1;
3038190225Srpaulo	}
3039190225Srpaulo	handle->md.tp_version = TPACKET_V2;
3040190225Srpaulo
3041190225Srpaulo	/* Reserve space for VLAN tag reconstruction */
3042190225Srpaulo	val = VLAN_TAG_LEN;
3043190225Srpaulo	if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
3044190225Srpaulo		       sizeof(val)) < 0) {
3045190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3046214518Srpaulo		    "can't set up reserve on packet socket: %s",
3047214518Srpaulo		    pcap_strerror(errno));
3048214518Srpaulo		return -1;
3049190225Srpaulo	}
3050190225Srpaulo
3051190225Srpaulo#endif /* HAVE_TPACKET2 */
3052190225Srpaulo	return 1;
3053190225Srpaulo}
3054190225Srpaulo
3055190225Srpaulostatic int
3056190225Srpaulocreate_ring(pcap_t *handle)
3057190225Srpaulo{
3058214518Srpaulo	unsigned i, j, frames_per_block;
3059190225Srpaulo	struct tpacket_req req;
3060190225Srpaulo
3061190225Srpaulo	/* Note that with large snapshot (say 64K) only a few frames
3062190225Srpaulo	 * will be available in the ring even with pretty large ring size
3063190225Srpaulo	 * (and a lot of memory will be unused).
3064190225Srpaulo	 * The snap len should be carefully chosen to achive best
3065190225Srpaulo	 * performance */
3066190225Srpaulo	req.tp_frame_size = TPACKET_ALIGN(handle->snapshot +
3067190225Srpaulo					  TPACKET_ALIGN(handle->md.tp_hdrlen) +
3068190225Srpaulo					  sizeof(struct sockaddr_ll));
3069190225Srpaulo	req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
3070214518Srpaulo
3071214518Srpaulo	/* compute the minumum block size that will handle this frame.
3072214518Srpaulo	 * The block has to be page size aligned.
3073214518Srpaulo	 * The max block size allowed by the kernel is arch-dependent and
3074214518Srpaulo	 * it's not explicitly checked here. */
3075214518Srpaulo	req.tp_block_size = getpagesize();
3076214518Srpaulo	while (req.tp_block_size < req.tp_frame_size)
3077214518Srpaulo		req.tp_block_size <<= 1;
3078214518Srpaulo
3079214518Srpaulo	frames_per_block = req.tp_block_size/req.tp_frame_size;
3080214518Srpaulo
3081214518Srpaulo	/* ask the kernel to create the ring */
3082214518Srpauloretry:
3083190225Srpaulo	req.tp_block_nr = req.tp_frame_nr / frames_per_block;
3084190225Srpaulo
3085190225Srpaulo	/* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3086190225Srpaulo	req.tp_frame_nr = req.tp_block_nr * frames_per_block;
3087214518Srpaulo
3088190225Srpaulo	if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3089190225Srpaulo					(void *) &req, sizeof(req))) {
3090190225Srpaulo		if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
3091214518Srpaulo			/*
3092214518Srpaulo			 * Memory failure; try to reduce the requested ring
3093214518Srpaulo			 * size.
3094214518Srpaulo			 *
3095214518Srpaulo			 * We used to reduce this by half -- do 5% instead.
3096214518Srpaulo			 * That may result in more iterations and a longer
3097214518Srpaulo			 * startup, but the user will be much happier with
3098214518Srpaulo			 * the resulting buffer size.
3099214518Srpaulo			 */
3100214518Srpaulo			if (req.tp_frame_nr < 20)
3101214518Srpaulo				req.tp_frame_nr -= 1;
3102214518Srpaulo			else
3103214518Srpaulo				req.tp_frame_nr -= req.tp_frame_nr/20;
3104190225Srpaulo			goto retry;
3105190225Srpaulo		}
3106214518Srpaulo		if (errno == ENOPROTOOPT) {
3107214518Srpaulo			/*
3108214518Srpaulo			 * We don't have ring buffer support in this kernel.
3109214518Srpaulo			 */
3110214518Srpaulo			return 0;
3111214518Srpaulo		}
3112214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3113214518Srpaulo		    "can't create rx ring on packet socket: %s",
3114214518Srpaulo		    pcap_strerror(errno));
3115214518Srpaulo		return -1;
3116190225Srpaulo	}
3117190225Srpaulo
3118190225Srpaulo	/* memory map the rx ring */
3119214518Srpaulo	handle->md.mmapbuflen = req.tp_block_nr * req.tp_block_size;
3120214518Srpaulo	handle->md.mmapbuf = mmap(0, handle->md.mmapbuflen,
3121214518Srpaulo	    PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
3122214518Srpaulo	if (handle->md.mmapbuf == MAP_FAILED) {
3123214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3124214518Srpaulo		    "can't mmap rx ring: %s", pcap_strerror(errno));
3125190225Srpaulo
3126190225Srpaulo		/* clear the allocated ring on error*/
3127190225Srpaulo		destroy_ring(handle);
3128214518Srpaulo		return -1;
3129190225Srpaulo	}
3130190225Srpaulo
3131190225Srpaulo	/* allocate a ring for each frame header pointer*/
3132190225Srpaulo	handle->cc = req.tp_frame_nr;
3133190225Srpaulo	handle->buffer = malloc(handle->cc * sizeof(union thdr *));
3134190225Srpaulo	if (!handle->buffer) {
3135214518Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3136214518Srpaulo		    "can't allocate ring of frame headers: %s",
3137214518Srpaulo		    pcap_strerror(errno));
3138214518Srpaulo
3139190225Srpaulo		destroy_ring(handle);
3140214518Srpaulo		return -1;
3141190225Srpaulo	}
3142190225Srpaulo
3143190225Srpaulo	/* fill the header ring with proper frame ptr*/
3144190225Srpaulo	handle->offset = 0;
3145190225Srpaulo	for (i=0; i<req.tp_block_nr; ++i) {
3146214518Srpaulo		void *base = &handle->md.mmapbuf[i*req.tp_block_size];
3147190225Srpaulo		for (j=0; j<frames_per_block; ++j, ++handle->offset) {
3148190225Srpaulo			RING_GET_FRAME(handle) = base;
3149190225Srpaulo			base += req.tp_frame_size;
3150190225Srpaulo		}
3151190225Srpaulo	}
3152190225Srpaulo
3153190225Srpaulo	handle->bufsize = req.tp_frame_size;
3154190225Srpaulo	handle->offset = 0;
3155190225Srpaulo	return 1;
3156190225Srpaulo}
3157190225Srpaulo
3158190225Srpaulo/* free all ring related resources*/
3159190225Srpaulostatic void
3160190225Srpaulodestroy_ring(pcap_t *handle)
3161190225Srpaulo{
3162190225Srpaulo	/* tell the kernel to destroy the ring*/
3163190225Srpaulo	struct tpacket_req req;
3164190225Srpaulo	memset(&req, 0, sizeof(req));
3165190225Srpaulo	setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3166190225Srpaulo				(void *) &req, sizeof(req));
3167190225Srpaulo
3168190225Srpaulo	/* if ring is mapped, unmap it*/
3169214518Srpaulo	if (handle->md.mmapbuf) {
3170214518Srpaulo		/* do not test for mmap failure, as we can't recover from any error */
3171214518Srpaulo		munmap(handle->md.mmapbuf, handle->md.mmapbuflen);
3172214518Srpaulo		handle->md.mmapbuf = NULL;
3173190225Srpaulo	}
3174190225Srpaulo}
3175190225Srpaulo
3176214518Srpaulo/*
3177214518Srpaulo * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3178214518Srpaulo * for Linux mmapped capture.
3179214518Srpaulo *
3180214518Srpaulo * The problem is that pcap_next() and pcap_next_ex() expect the packet
3181214518Srpaulo * data handed to the callback to be valid after the callback returns,
3182214518Srpaulo * but pcap_read_linux_mmap() has to release that packet as soon as
3183214518Srpaulo * the callback returns (otherwise, the kernel thinks there's still
3184214518Srpaulo * at least one unprocessed packet available in the ring, so a select()
3185214518Srpaulo * will immediately return indicating that there's data to process), so,
3186214518Srpaulo * in the callback, we have to make a copy of the packet.
3187214518Srpaulo *
3188214518Srpaulo * Yes, this means that, if the capture is using the ring buffer, using
3189214518Srpaulo * pcap_next() or pcap_next_ex() requires more copies than using
3190214518Srpaulo * pcap_loop() or pcap_dispatch().  If that bothers you, don't use
3191214518Srpaulo * pcap_next() or pcap_next_ex().
3192214518Srpaulo */
3193190225Srpaulostatic void
3194214518Srpaulopcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
3195214518Srpaulo    const u_char *bytes)
3196214518Srpaulo{
3197214518Srpaulo	struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
3198214518Srpaulo
3199214518Srpaulo	*sp->hdr = *h;
3200214518Srpaulo	memcpy(sp->pd->md.oneshot_buffer, bytes, h->caplen);
3201214518Srpaulo	*sp->pkt = sp->pd->md.oneshot_buffer;
3202214518Srpaulo}
3203214518Srpaulo
3204214518Srpaulostatic void
3205190225Srpaulopcap_cleanup_linux_mmap( pcap_t *handle )
3206190225Srpaulo{
3207190225Srpaulo	destroy_ring(handle);
3208214518Srpaulo	if (handle->md.oneshot_buffer != NULL) {
3209214518Srpaulo		free(handle->md.oneshot_buffer);
3210214518Srpaulo		handle->md.oneshot_buffer = NULL;
3211214518Srpaulo	}
3212190225Srpaulo	pcap_cleanup_linux(handle);
3213190225Srpaulo}
3214190225Srpaulo
3215190225Srpaulo
3216190225Srpaulostatic int
3217190225Srpaulopcap_getnonblock_mmap(pcap_t *p, char *errbuf)
3218190225Srpaulo{
3219190225Srpaulo	/* use negative value of timeout to indicate non blocking ops */
3220190225Srpaulo	return (p->md.timeout<0);
3221190225Srpaulo}
3222190225Srpaulo
3223190225Srpaulostatic int
3224190225Srpaulopcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
3225190225Srpaulo{
3226190225Srpaulo	/* map each value to the corresponding 2's complement, to
3227190225Srpaulo	 * preserve the timeout value provided with pcap_set_timeout */
3228190225Srpaulo	if (nonblock) {
3229214518Srpaulo		if (p->md.timeout >= 0) {
3230214518Srpaulo			/*
3231214518Srpaulo			 * Timeout is non-negative, so we're not already
3232214518Srpaulo			 * in non-blocking mode; set it to the 2's
3233214518Srpaulo			 * complement, to make it negative, as an
3234214518Srpaulo			 * indication that we're in non-blocking mode.
3235214518Srpaulo			 */
3236190225Srpaulo			p->md.timeout = p->md.timeout*-1 - 1;
3237214518Srpaulo		}
3238214518Srpaulo	} else {
3239214518Srpaulo		if (p->md.timeout < 0) {
3240214518Srpaulo			/*
3241214518Srpaulo			 * Timeout is negative, so we're not already
3242214518Srpaulo			 * in blocking mode; reverse the previous
3243214518Srpaulo			 * operation, to make the timeout non-negative
3244214518Srpaulo			 * again.
3245214518Srpaulo			 */
3246190225Srpaulo			p->md.timeout = (p->md.timeout+1)*-1;
3247214518Srpaulo		}
3248214518Srpaulo	}
3249190225Srpaulo	return 0;
3250190225Srpaulo}
3251190225Srpaulo
3252190225Srpaulostatic inline union thdr *
3253190225Srpaulopcap_get_ring_frame(pcap_t *handle, int status)
3254190225Srpaulo{
3255190225Srpaulo	union thdr h;
3256190225Srpaulo
3257190225Srpaulo	h.raw = RING_GET_FRAME(handle);
3258190225Srpaulo	switch (handle->md.tp_version) {
3259190225Srpaulo	case TPACKET_V1:
3260190225Srpaulo		if (status != (h.h1->tp_status ? TP_STATUS_USER :
3261190225Srpaulo						TP_STATUS_KERNEL))
3262190225Srpaulo			return NULL;
3263190225Srpaulo		break;
3264190225Srpaulo#ifdef HAVE_TPACKET2
3265190225Srpaulo	case TPACKET_V2:
3266190225Srpaulo		if (status != (h.h2->tp_status ? TP_STATUS_USER :
3267190225Srpaulo						TP_STATUS_KERNEL))
3268190225Srpaulo			return NULL;
3269190225Srpaulo		break;
3270190225Srpaulo#endif
3271190225Srpaulo	}
3272190225Srpaulo	return h.raw;
3273190225Srpaulo}
3274190225Srpaulo
3275214518Srpaulo#ifndef POLLRDHUP
3276214518Srpaulo#define POLLRDHUP 0
3277214518Srpaulo#endif
3278214518Srpaulo
3279190225Srpaulostatic int
3280190225Srpaulopcap_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback,
3281190225Srpaulo		u_char *user)
3282190225Srpaulo{
3283214518Srpaulo	int timeout;
3284190225Srpaulo	int pkts = 0;
3285214518Srpaulo	char c;
3286190225Srpaulo
3287190225Srpaulo	/* wait for frames availability.*/
3288214518Srpaulo	if (!pcap_get_ring_frame(handle, TP_STATUS_USER)) {
3289190225Srpaulo		struct pollfd pollinfo;
3290190225Srpaulo		int ret;
3291190225Srpaulo
3292190225Srpaulo		pollinfo.fd = handle->fd;
3293190225Srpaulo		pollinfo.events = POLLIN;
3294190225Srpaulo
3295214518Srpaulo		if (handle->md.timeout == 0)
3296214518Srpaulo			timeout = -1;	/* block forever */
3297214518Srpaulo		else if (handle->md.timeout > 0)
3298214518Srpaulo			timeout = handle->md.timeout;	/* block for that amount of time */
3299214518Srpaulo		else
3300214518Srpaulo			timeout = 0;	/* non-blocking mode - poll to pick up errors */
3301190225Srpaulo		do {
3302214518Srpaulo			ret = poll(&pollinfo, 1, timeout);
3303214518Srpaulo			if (ret < 0 && errno != EINTR) {
3304190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3305214518Srpaulo					"can't poll on packet socket: %s",
3306214518Srpaulo					pcap_strerror(errno));
3307214518Srpaulo				return PCAP_ERROR;
3308214518Srpaulo			} else if (ret > 0 &&
3309214518Srpaulo			    (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
3310214518Srpaulo				/*
3311214518Srpaulo				 * There's some indication other than
3312214518Srpaulo				 * "you can read on this descriptor" on
3313214518Srpaulo				 * the descriptor.
3314214518Srpaulo				 */
3315214518Srpaulo				if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
3316214518Srpaulo					snprintf(handle->errbuf,
3317214518Srpaulo						PCAP_ERRBUF_SIZE,
3318214518Srpaulo						"Hangup on packet socket");
3319214518Srpaulo					return PCAP_ERROR;
3320214518Srpaulo				}
3321214518Srpaulo				if (pollinfo.revents & POLLERR) {
3322214518Srpaulo					/*
3323214518Srpaulo					 * A recv() will give us the
3324214518Srpaulo					 * actual error code.
3325214518Srpaulo					 *
3326214518Srpaulo					 * XXX - make the socket non-blocking?
3327214518Srpaulo					 */
3328214518Srpaulo					if (recv(handle->fd, &c, sizeof c,
3329214518Srpaulo					    MSG_PEEK) != -1)
3330214518Srpaulo						continue;	/* what, no error? */
3331214518Srpaulo					if (errno == ENETDOWN) {
3332214518Srpaulo						/*
3333214518Srpaulo						 * The device on which we're
3334214518Srpaulo						 * capturing went away.
3335214518Srpaulo						 *
3336214518Srpaulo						 * XXX - we should really return
3337214518Srpaulo						 * PCAP_ERROR_IFACE_NOT_UP,
3338214518Srpaulo						 * but pcap_dispatch() etc.
3339214518Srpaulo						 * aren't defined to return
3340214518Srpaulo						 * that.
3341214518Srpaulo						 */
3342214518Srpaulo						snprintf(handle->errbuf,
3343214518Srpaulo							PCAP_ERRBUF_SIZE,
3344214518Srpaulo							"The interface went down");
3345214518Srpaulo					} else {
3346214518Srpaulo						snprintf(handle->errbuf,
3347214518Srpaulo							PCAP_ERRBUF_SIZE,
3348214518Srpaulo							"Error condition on packet socket: %s",
3349214518Srpaulo							strerror(errno));
3350214518Srpaulo					}
3351214518Srpaulo					return PCAP_ERROR;
3352214518Srpaulo				}
3353214518Srpaulo				if (pollinfo.revents & POLLNVAL) {
3354214518Srpaulo					snprintf(handle->errbuf,
3355214518Srpaulo						PCAP_ERRBUF_SIZE,
3356214518Srpaulo						"Invalid polling request on packet socket");
3357214518Srpaulo					return PCAP_ERROR;
3358214518Srpaulo				}
3359214518Srpaulo  			}
3360190225Srpaulo			/* check for break loop condition on interrupted syscall*/
3361190225Srpaulo			if (handle->break_loop) {
3362190225Srpaulo				handle->break_loop = 0;
3363214518Srpaulo				return PCAP_ERROR_BREAK;
3364190225Srpaulo			}
3365190225Srpaulo		} while (ret < 0);
3366190225Srpaulo	}
3367190225Srpaulo
3368190225Srpaulo	/* non-positive values of max_packets are used to require all
3369190225Srpaulo	 * packets currently available in the ring */
3370190225Srpaulo	while ((pkts < max_packets) || (max_packets <= 0)) {
3371190225Srpaulo		int run_bpf;
3372190225Srpaulo		struct sockaddr_ll *sll;
3373190225Srpaulo		struct pcap_pkthdr pcaphdr;
3374190225Srpaulo		unsigned char *bp;
3375190225Srpaulo		union thdr h;
3376190225Srpaulo		unsigned int tp_len;
3377190225Srpaulo		unsigned int tp_mac;
3378190225Srpaulo		unsigned int tp_snaplen;
3379190225Srpaulo		unsigned int tp_sec;
3380190225Srpaulo		unsigned int tp_usec;
3381190225Srpaulo
3382190225Srpaulo		h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
3383190225Srpaulo		if (!h.raw)
3384190225Srpaulo			break;
3385190225Srpaulo
3386190225Srpaulo		switch (handle->md.tp_version) {
3387190225Srpaulo		case TPACKET_V1:
3388190225Srpaulo			tp_len	   = h.h1->tp_len;
3389190225Srpaulo			tp_mac	   = h.h1->tp_mac;
3390190225Srpaulo			tp_snaplen = h.h1->tp_snaplen;
3391190225Srpaulo			tp_sec	   = h.h1->tp_sec;
3392190225Srpaulo			tp_usec	   = h.h1->tp_usec;
3393190225Srpaulo			break;
3394190225Srpaulo#ifdef HAVE_TPACKET2
3395190225Srpaulo		case TPACKET_V2:
3396190225Srpaulo			tp_len	   = h.h2->tp_len;
3397190225Srpaulo			tp_mac	   = h.h2->tp_mac;
3398190225Srpaulo			tp_snaplen = h.h2->tp_snaplen;
3399190225Srpaulo			tp_sec	   = h.h2->tp_sec;
3400190225Srpaulo			tp_usec	   = h.h2->tp_nsec / 1000;
3401190225Srpaulo			break;
3402190225Srpaulo#endif
3403190225Srpaulo		default:
3404190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3405190225Srpaulo				"unsupported tpacket version %d",
3406190225Srpaulo				handle->md.tp_version);
3407190225Srpaulo			return -1;
3408190225Srpaulo		}
3409190225Srpaulo		/* perform sanity check on internal offset. */
3410190225Srpaulo		if (tp_mac + tp_snaplen > handle->bufsize) {
3411190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3412190225Srpaulo				"corrupted frame on kernel ring mac "
3413190225Srpaulo				"offset %d + caplen %d > frame len %d",
3414190225Srpaulo				tp_mac, tp_snaplen, handle->bufsize);
3415190225Srpaulo			return -1;
3416190225Srpaulo		}
3417190225Srpaulo
3418190225Srpaulo		/* run filter on received packet
3419190225Srpaulo		 * If the kernel filtering is enabled we need to run the
3420190225Srpaulo		 * filter until all the frames present into the ring
3421190225Srpaulo		 * at filter creation time are processed.
3422190225Srpaulo		 * In such case md.use_bpf is used as a counter for the
3423190225Srpaulo		 * packet we need to filter.
3424190225Srpaulo		 * Note: alternatively it could be possible to stop applying
3425190225Srpaulo		 * the filter when the ring became empty, but it can possibly
3426190225Srpaulo		 * happen a lot later... */
3427190225Srpaulo		bp = (unsigned char*)h.raw + tp_mac;
3428190225Srpaulo		run_bpf = (!handle->md.use_bpf) ||
3429190225Srpaulo			((handle->md.use_bpf>1) && handle->md.use_bpf--);
3430190225Srpaulo		if (run_bpf && handle->fcode.bf_insns &&
3431190225Srpaulo				(bpf_filter(handle->fcode.bf_insns, bp,
3432190225Srpaulo					tp_len, tp_snaplen) == 0))
3433190225Srpaulo			goto skip;
3434190225Srpaulo
3435214518Srpaulo		/*
3436214518Srpaulo		 * Do checks based on packet direction.
3437214518Srpaulo		 */
3438190225Srpaulo		sll = (void *)h.raw + TPACKET_ALIGN(handle->md.tp_hdrlen);
3439214518Srpaulo		if (sll->sll_pkttype == PACKET_OUTGOING) {
3440214518Srpaulo			/*
3441214518Srpaulo			 * Outgoing packet.
3442214518Srpaulo			 * If this is from the loopback device, reject it;
3443214518Srpaulo			 * we'll see the packet as an incoming packet as well,
3444214518Srpaulo			 * and we don't want to see it twice.
3445214518Srpaulo			 */
3446214518Srpaulo			if (sll->sll_ifindex == handle->md.lo_ifindex)
3447214518Srpaulo				goto skip;
3448190225Srpaulo
3449214518Srpaulo			/*
3450214518Srpaulo			 * If the user only wants incoming packets, reject it.
3451214518Srpaulo			 */
3452214518Srpaulo			if (handle->direction == PCAP_D_IN)
3453214518Srpaulo				goto skip;
3454214518Srpaulo		} else {
3455214518Srpaulo			/*
3456214518Srpaulo			 * Incoming packet.
3457214518Srpaulo			 * If the user only wants outgoing packets, reject it.
3458214518Srpaulo			 */
3459214518Srpaulo			if (handle->direction == PCAP_D_OUT)
3460214518Srpaulo				goto skip;
3461214518Srpaulo		}
3462214518Srpaulo
3463190225Srpaulo		/* get required packet info from ring header */
3464190225Srpaulo		pcaphdr.ts.tv_sec = tp_sec;
3465190225Srpaulo		pcaphdr.ts.tv_usec = tp_usec;
3466190225Srpaulo		pcaphdr.caplen = tp_snaplen;
3467190225Srpaulo		pcaphdr.len = tp_len;
3468190225Srpaulo
3469190225Srpaulo		/* if required build in place the sll header*/
3470190225Srpaulo		if (handle->md.cooked) {
3471190225Srpaulo			struct sll_header *hdrp;
3472190225Srpaulo
3473190225Srpaulo			/*
3474190225Srpaulo			 * The kernel should have left us with enough
3475190225Srpaulo			 * space for an sll header; back up the packet
3476190225Srpaulo			 * data pointer into that space, as that'll be
3477190225Srpaulo			 * the beginning of the packet we pass to the
3478190225Srpaulo			 * callback.
3479190225Srpaulo			 */
3480190225Srpaulo			bp -= SLL_HDR_LEN;
3481190225Srpaulo
3482190225Srpaulo			/*
3483190225Srpaulo			 * Let's make sure that's past the end of
3484190225Srpaulo			 * the tpacket header, i.e. >=
3485190225Srpaulo			 * ((u_char *)thdr + TPACKET_HDRLEN), so we
3486190225Srpaulo			 * don't step on the header when we construct
3487190225Srpaulo			 * the sll header.
3488190225Srpaulo			 */
3489190225Srpaulo			if (bp < (u_char *)h.raw +
3490190225Srpaulo					   TPACKET_ALIGN(handle->md.tp_hdrlen) +
3491190225Srpaulo					   sizeof(struct sockaddr_ll)) {
3492190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3493190225Srpaulo					"cooked-mode frame doesn't have room for sll header");
3494190225Srpaulo				return -1;
3495190225Srpaulo			}
3496190225Srpaulo
3497190225Srpaulo			/*
3498190225Srpaulo			 * OK, that worked; construct the sll header.
3499190225Srpaulo			 */
3500190225Srpaulo			hdrp = (struct sll_header *)bp;
3501190225Srpaulo			hdrp->sll_pkttype = map_packet_type_to_sll_type(
3502190225Srpaulo							sll->sll_pkttype);
3503190225Srpaulo			hdrp->sll_hatype = htons(sll->sll_hatype);
3504190225Srpaulo			hdrp->sll_halen = htons(sll->sll_halen);
3505190225Srpaulo			memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
3506190225Srpaulo			hdrp->sll_protocol = sll->sll_protocol;
3507190225Srpaulo
3508190225Srpaulo			/* update packet len */
3509190225Srpaulo			pcaphdr.caplen += SLL_HDR_LEN;
3510190225Srpaulo			pcaphdr.len += SLL_HDR_LEN;
3511190225Srpaulo		}
3512190225Srpaulo
3513190225Srpaulo#ifdef HAVE_TPACKET2
3514190225Srpaulo		if (handle->md.tp_version == TPACKET_V2 && h.h2->tp_vlan_tci &&
3515190225Srpaulo		    tp_snaplen >= 2 * ETH_ALEN) {
3516190225Srpaulo			struct vlan_tag *tag;
3517190225Srpaulo
3518190225Srpaulo			bp -= VLAN_TAG_LEN;
3519190225Srpaulo			memmove(bp, bp + VLAN_TAG_LEN, 2 * ETH_ALEN);
3520190225Srpaulo
3521190225Srpaulo			tag = (struct vlan_tag *)(bp + 2 * ETH_ALEN);
3522190225Srpaulo			tag->vlan_tpid = htons(ETH_P_8021Q);
3523190225Srpaulo			tag->vlan_tci = htons(h.h2->tp_vlan_tci);
3524190225Srpaulo
3525190225Srpaulo			pcaphdr.caplen += VLAN_TAG_LEN;
3526190225Srpaulo			pcaphdr.len += VLAN_TAG_LEN;
3527190225Srpaulo		}
3528190225Srpaulo#endif
3529190225Srpaulo
3530214518Srpaulo		/*
3531214518Srpaulo		 * The only way to tell the kernel to cut off the
3532214518Srpaulo		 * packet at a snapshot length is with a filter program;
3533214518Srpaulo		 * if there's no filter program, the kernel won't cut
3534214518Srpaulo		 * the packet off.
3535214518Srpaulo		 *
3536214518Srpaulo		 * Trim the snapshot length to be no longer than the
3537214518Srpaulo		 * specified snapshot length.
3538214518Srpaulo		 */
3539214518Srpaulo		if (pcaphdr.caplen > handle->snapshot)
3540214518Srpaulo			pcaphdr.caplen = handle->snapshot;
3541214518Srpaulo
3542190225Srpaulo		/* pass the packet to the user */
3543190225Srpaulo		pkts++;
3544190225Srpaulo		callback(user, &pcaphdr, bp);
3545190225Srpaulo		handle->md.packets_read++;
3546190225Srpaulo
3547190225Srpauloskip:
3548190225Srpaulo		/* next packet */
3549190225Srpaulo		switch (handle->md.tp_version) {
3550190225Srpaulo		case TPACKET_V1:
3551190225Srpaulo			h.h1->tp_status = TP_STATUS_KERNEL;
3552190225Srpaulo			break;
3553190225Srpaulo#ifdef HAVE_TPACKET2
3554190225Srpaulo		case TPACKET_V2:
3555190225Srpaulo			h.h2->tp_status = TP_STATUS_KERNEL;
3556190225Srpaulo			break;
3557190225Srpaulo#endif
3558190225Srpaulo		}
3559190225Srpaulo		if (++handle->offset >= handle->cc)
3560190225Srpaulo			handle->offset = 0;
3561190225Srpaulo
3562190225Srpaulo		/* check for break loop condition*/
3563190225Srpaulo		if (handle->break_loop) {
3564190225Srpaulo			handle->break_loop = 0;
3565214518Srpaulo			return PCAP_ERROR_BREAK;
3566190225Srpaulo		}
3567190225Srpaulo	}
3568190225Srpaulo	return pkts;
3569190225Srpaulo}
3570190225Srpaulo
3571190225Srpaulostatic int
3572190225Srpaulopcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
3573190225Srpaulo{
3574190225Srpaulo	int n, offset;
3575214518Srpaulo	int ret;
3576214518Srpaulo
3577214518Srpaulo	/*
3578214518Srpaulo	 * Don't rewrite "ret" instructions; we don't need to, as
3579214518Srpaulo	 * we're not reading packets with recvmsg(), and we don't
3580214518Srpaulo	 * want to, as, by not rewriting them, the kernel can avoid
3581214518Srpaulo	 * copying extra data.
3582214518Srpaulo	 */
3583214518Srpaulo	ret = pcap_setfilter_linux_common(handle, filter, 1);
3584190225Srpaulo	if (ret < 0)
3585190225Srpaulo		return ret;
3586190225Srpaulo
3587190225Srpaulo	/* if the kernel filter is enabled, we need to apply the filter on
3588190225Srpaulo	 * all packets present into the ring. Get an upper bound of their number
3589190225Srpaulo	 */
3590190225Srpaulo	if (!handle->md.use_bpf)
3591190225Srpaulo		return ret;
3592190225Srpaulo
3593190225Srpaulo	/* walk the ring backward and count the free slot */
3594190225Srpaulo	offset = handle->offset;
3595190225Srpaulo	if (--handle->offset < 0)
3596190225Srpaulo		handle->offset = handle->cc - 1;
3597190225Srpaulo	for (n=0; n < handle->cc; ++n) {
3598190225Srpaulo		if (--handle->offset < 0)
3599190225Srpaulo			handle->offset = handle->cc - 1;
3600190225Srpaulo		if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
3601190225Srpaulo			break;
3602190225Srpaulo	}
3603190225Srpaulo
3604190225Srpaulo	/* be careful to not change current ring position */
3605190225Srpaulo	handle->offset = offset;
3606190225Srpaulo
3607190225Srpaulo	/* store the number of packets currently present in the ring */
3608190225Srpaulo	handle->md.use_bpf = 1 + (handle->cc - n);
3609190225Srpaulo	return ret;
3610190225Srpaulo}
3611190225Srpaulo
3612190225Srpaulo#endif /* HAVE_PACKET_RING */
3613190225Srpaulo
3614190225Srpaulo
361575107Sfenner#ifdef HAVE_PF_PACKET_SOCKETS
361675107Sfenner/*
3617127664Sbms *  Return the index of the given device name. Fill ebuf and return
361875107Sfenner *  -1 on failure.
361975107Sfenner */
362075107Sfennerstatic int
362175107Sfenneriface_get_id(int fd, const char *device, char *ebuf)
362275107Sfenner{
362375107Sfenner	struct ifreq	ifr;
362426175Sfenner
362539291Sfenner	memset(&ifr, 0, sizeof(ifr));
362639291Sfenner	strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
362775107Sfenner
362875107Sfenner	if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
362975107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
3630172677Smlaier			 "SIOCGIFINDEX: %s", pcap_strerror(errno));
363175107Sfenner		return -1;
363226175Sfenner	}
363326175Sfenner
363475107Sfenner	return ifr.ifr_ifindex;
363575107Sfenner}
363626175Sfenner
363775107Sfenner/*
3638127664Sbms *  Bind the socket associated with FD to the given device.
3639190225Srpaulo *  Return 1 on success, 0 if we should try a SOCK_PACKET socket,
3640190225Srpaulo *  or a PCAP_ERROR_ value on a hard error.
364175107Sfenner */
364275107Sfennerstatic int
364375107Sfenneriface_bind(int fd, int ifindex, char *ebuf)
364475107Sfenner{
364575107Sfenner	struct sockaddr_ll	sll;
3646127664Sbms	int			err;
3647127664Sbms	socklen_t		errlen = sizeof(err);
364875107Sfenner
364975107Sfenner	memset(&sll, 0, sizeof(sll));
365075107Sfenner	sll.sll_family		= AF_PACKET;
365175107Sfenner	sll.sll_ifindex		= ifindex;
365275107Sfenner	sll.sll_protocol	= htons(ETH_P_ALL);
365375107Sfenner
365475107Sfenner	if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
3655190225Srpaulo		if (errno == ENETDOWN) {
3656190225Srpaulo			/*
3657190225Srpaulo			 * Return a "network down" indication, so that
3658190225Srpaulo			 * the application can report that rather than
3659190225Srpaulo			 * saying we had a mysterious failure and
3660190225Srpaulo			 * suggest that they report a problem to the
3661190225Srpaulo			 * libpcap developers.
3662190225Srpaulo			 */
3663190225Srpaulo			return PCAP_ERROR_IFACE_NOT_UP;
3664190225Srpaulo		} else {
3665190225Srpaulo			snprintf(ebuf, PCAP_ERRBUF_SIZE,
3666190225Srpaulo				 "bind: %s", pcap_strerror(errno));
3667190225Srpaulo			return PCAP_ERROR;
3668190225Srpaulo		}
366926175Sfenner	}
367026175Sfenner
3671127664Sbms	/* Any pending errors, e.g., network is down? */
3672127664Sbms
3673127664Sbms	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
3674127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
3675127664Sbms			"getsockopt: %s", pcap_strerror(errno));
3676190225Srpaulo		return 0;
3677127664Sbms	}
3678127664Sbms
3679190225Srpaulo	if (err == ENETDOWN) {
3680190225Srpaulo		/*
3681190225Srpaulo		 * Return a "network down" indication, so that
3682190225Srpaulo		 * the application can report that rather than
3683190225Srpaulo		 * saying we had a mysterious failure and
3684190225Srpaulo		 * suggest that they report a problem to the
3685190225Srpaulo		 * libpcap developers.
3686190225Srpaulo		 */
3687190225Srpaulo		return PCAP_ERROR_IFACE_NOT_UP;
3688190225Srpaulo	} else if (err > 0) {
3689127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
3690127664Sbms			"bind: %s", pcap_strerror(err));
3691190225Srpaulo		return 0;
3692127664Sbms	}
3693127664Sbms
3694190225Srpaulo	return 1;
369575107Sfenner}
369675107Sfenner
3697214518Srpaulo#ifdef IW_MODE_MONITOR
369875107Sfenner/*
3699190225Srpaulo * Check whether the device supports the Wireless Extensions.
3700190225Srpaulo * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
3701190225Srpaulo * if the device doesn't even exist.
370275107Sfenner */
3703190225Srpaulostatic int
3704190225Srpaulohas_wext(int sock_fd, const char *device, char *ebuf)
3705190225Srpaulo{
3706190225Srpaulo	struct iwreq ireq;
370775107Sfenner
3708190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
3709190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
3710190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3711190225Srpaulo	if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
3712190225Srpaulo		return 1;	/* yes */
3713190225Srpaulo	snprintf(ebuf, PCAP_ERRBUF_SIZE,
3714190225Srpaulo	    "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
3715190225Srpaulo	if (errno == ENODEV)
3716190225Srpaulo		return PCAP_ERROR_NO_SUCH_DEVICE;
3717190225Srpaulo	return 0;
3718190225Srpaulo}
3719190225Srpaulo
372075107Sfenner/*
3721190225Srpaulo * Per me si va ne la citta dolente,
3722190225Srpaulo * Per me si va ne l'etterno dolore,
3723190225Srpaulo *	...
3724190225Srpaulo * Lasciate ogne speranza, voi ch'intrate.
3725190225Srpaulo *
3726190225Srpaulo * XXX - airmon-ng does special stuff with the Orinoco driver and the
3727190225Srpaulo * wlan-ng driver.
372875107Sfenner */
3729190225Srpaulotypedef enum {
3730190225Srpaulo	MONITOR_WEXT,
3731190225Srpaulo	MONITOR_HOSTAP,
3732190225Srpaulo	MONITOR_PRISM,
3733190225Srpaulo	MONITOR_PRISM54,
3734190225Srpaulo	MONITOR_ACX100,
3735190225Srpaulo	MONITOR_RT2500,
3736190225Srpaulo	MONITOR_RT2570,
3737190225Srpaulo	MONITOR_RT73,
3738190225Srpaulo	MONITOR_RTL8XXX
3739190225Srpaulo} monitor_type;
374075107Sfenner
374175107Sfenner/*
3742190225Srpaulo * Use the Wireless Extensions, if we have them, to try to turn monitor mode
3743190225Srpaulo * on if it's not already on.
3744190225Srpaulo *
3745190225Srpaulo * Returns 1 on success, 0 if we don't support the Wireless Extensions
3746190225Srpaulo * on this device, or a PCAP_ERROR_ value if we do support them but
3747190225Srpaulo * we weren't able to turn monitor mode on.
374875107Sfenner */
3749190225Srpaulostatic int
3750190225Srpauloenter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
375175107Sfenner{
3752190225Srpaulo	/*
3753190225Srpaulo	 * XXX - at least some adapters require non-Wireless Extensions
3754190225Srpaulo	 * mechanisms to turn monitor mode on.
3755190225Srpaulo	 *
3756190225Srpaulo	 * Atheros cards might require that a separate "monitor virtual access
3757190225Srpaulo	 * point" be created, with later versions of the madwifi driver.
3758190225Srpaulo	 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
3759190225Srpaulo	 * monitor -bssid", which apparently spits out a line "athN"
3760190225Srpaulo	 * where "athN" is the monitor mode device.  To leave monitor
3761190225Srpaulo	 * mode, it destroys the monitor mode device.
3762190225Srpaulo	 *
3763190225Srpaulo	 * Some Intel Centrino adapters might require private ioctls to get
3764190225Srpaulo	 * radio headers; the ipw2200 and ipw3945 drivers allow you to
3765190225Srpaulo	 * configure a separate "rtapN" interface to capture in monitor
3766190225Srpaulo	 * mode without preventing the adapter from operating normally.
3767190225Srpaulo	 * (airmon-ng doesn't appear to use that, though.)
3768190225Srpaulo	 *
3769190225Srpaulo	 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
3770190225Srpaulo	 * up, and if all drivers were converted to mac80211 drivers.
3771190225Srpaulo	 *
3772190225Srpaulo	 * If interface {if} is a mac80211 driver, the file
3773190225Srpaulo	 * /sys/class/net/{if}/phy80211 is a symlink to
3774190225Srpaulo	 * /sys/class/ieee80211/{phydev}, for some {phydev}.
3775190225Srpaulo	 *
3776190225Srpaulo	 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
3777190225Srpaulo	 * least, has a "wmaster0" device and a "wlan0" device; the
3778190225Srpaulo	 * latter is the one with the IP address.  Both show up in
3779190225Srpaulo	 * "tcpdump -D" output.  Capturing on the wmaster0 device
3780190225Srpaulo	 * captures with 802.11 headers.
3781190225Srpaulo	 *
3782190225Srpaulo	 * airmon-ng searches through /sys/class/net for devices named
3783190225Srpaulo	 * monN, starting with mon0; as soon as one *doesn't* exist,
3784190225Srpaulo	 * it chooses that as the monitor device name.  If the "iw"
3785190225Srpaulo	 * command exists, it does "iw dev {if} interface add {monif}
3786190225Srpaulo	 * type monitor", where {monif} is the monitor device.  It
3787190225Srpaulo	 * then (sigh) sleeps .1 second, and then configures the
3788190225Srpaulo	 * device up.  Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
3789190225Srpaulo	 * is a file, it writes {mondev}, without a newline, to that file,
3790190225Srpaulo	 * and again (sigh) sleeps .1 second, and then iwconfig's that
3791190225Srpaulo	 * device into monitor mode and configures it up.  Otherwise,
3792190225Srpaulo	 * you can't do monitor mode.
3793190225Srpaulo	 *
3794190225Srpaulo	 * All these devices are "glued" together by having the
3795190225Srpaulo	 * /sys/class/net/{device}/phy80211 links pointing to the same
3796190225Srpaulo	 * place, so, given a wmaster, wlan, or mon device, you can
3797190225Srpaulo	 * find the other devices by looking for devices with
3798190225Srpaulo	 * the same phy80211 link.
3799190225Srpaulo	 *
3800190225Srpaulo	 * To turn monitor mode off, delete the monitor interface,
3801190225Srpaulo	 * either with "iw dev {monif} interface del" or by sending
3802190225Srpaulo	 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
3803190225Srpaulo	 *
3804190225Srpaulo	 * Note: if you try to create a monitor device named "monN", and
3805190225Srpaulo	 * there's already a "monN" device, it fails, as least with
3806190225Srpaulo	 * the netlink interface (which is what iw uses), with a return
3807190225Srpaulo	 * value of -ENFILE.  (Return values are negative errnos.)  We
3808190225Srpaulo	 * could probably use that to find an unused device.
3809190225Srpaulo	 */
3810190225Srpaulo	int err;
3811190225Srpaulo	struct iwreq ireq;
3812190225Srpaulo	struct iw_priv_args *priv;
3813190225Srpaulo	monitor_type montype;
3814190225Srpaulo	int i;
3815190225Srpaulo	__u32 cmd;
3816190225Srpaulo	int args[2];
3817190225Srpaulo	int channel;
381875107Sfenner
3819190225Srpaulo	/*
3820190225Srpaulo	 * Does this device *support* the Wireless Extensions?
3821190225Srpaulo	 */
3822190225Srpaulo	err = has_wext(sock_fd, device, handle->errbuf);
3823190225Srpaulo	if (err <= 0)
3824190225Srpaulo		return err;	/* either it doesn't or the device doesn't even exist */
3825190225Srpaulo	/*
3826190225Srpaulo	 * Try to get all the Wireless Extensions private ioctls
3827190225Srpaulo	 * supported by this device.
3828190225Srpaulo	 *
3829190225Srpaulo	 * First, get the size of the buffer we need, by supplying no
3830190225Srpaulo	 * buffer and a length of 0.  If the device supports private
3831190225Srpaulo	 * ioctls, it should return E2BIG, with ireq.u.data.length set
3832190225Srpaulo	 * to the length we need.  If it doesn't support them, it should
3833190225Srpaulo	 * return EOPNOTSUPP.
3834190225Srpaulo	 */
3835190225Srpaulo	memset(&ireq, 0, sizeof ireq);
3836190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
3837190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
3838190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3839214518Srpaulo	ireq.u.data.pointer = (void *)args;
3840190225Srpaulo	ireq.u.data.length = 0;
3841190225Srpaulo	ireq.u.data.flags = 0;
3842190225Srpaulo	if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
3843190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3844190225Srpaulo		    "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
3845190225Srpaulo		    device);
3846190225Srpaulo		return PCAP_ERROR;
3847190225Srpaulo	}
3848190225Srpaulo	if (errno == EOPNOTSUPP) {
3849190225Srpaulo		/*
3850190225Srpaulo		 * No private ioctls, so we assume that there's only one
3851190225Srpaulo		 * DLT_ for monitor mode.
3852190225Srpaulo		 */
3853190225Srpaulo		return 0;
3854190225Srpaulo	}
3855190225Srpaulo	if (errno != E2BIG) {
3856190225Srpaulo		/*
3857190225Srpaulo		 * Failed.
3858190225Srpaulo		 */
3859190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3860190225Srpaulo		    "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
3861190225Srpaulo		return PCAP_ERROR;
3862190225Srpaulo	}
3863190225Srpaulo	priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
3864190225Srpaulo	if (priv == NULL) {
3865190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3866190225Srpaulo			 "malloc: %s", pcap_strerror(errno));
3867190225Srpaulo		return PCAP_ERROR;
3868190225Srpaulo	}
3869214518Srpaulo	ireq.u.data.pointer = (void *)priv;
3870190225Srpaulo	if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
3871190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3872190225Srpaulo		    "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
3873190225Srpaulo		free(priv);
3874190225Srpaulo		return PCAP_ERROR;
3875190225Srpaulo	}
387675107Sfenner
3877190225Srpaulo	/*
3878190225Srpaulo	 * Look for private ioctls to turn monitor mode on or, if
3879190225Srpaulo	 * monitor mode is on, to set the header type.
3880190225Srpaulo	 */
3881190225Srpaulo	montype = MONITOR_WEXT;
3882190225Srpaulo	cmd = 0;
3883190225Srpaulo	for (i = 0; i < ireq.u.data.length; i++) {
3884190225Srpaulo		if (strcmp(priv[i].name, "monitor_type") == 0) {
3885190225Srpaulo			/*
3886190225Srpaulo			 * Hostap driver, use this one.
3887190225Srpaulo			 * Set monitor mode first.
3888190225Srpaulo			 * You can set it to 0 to get DLT_IEEE80211,
3889214518Srpaulo			 * 1 to get DLT_PRISM, 2 to get
3890214518Srpaulo			 * DLT_IEEE80211_RADIO_AVS, and, with more
3891214518Srpaulo			 * recent versions of the driver, 3 to get
3892214518Srpaulo			 * DLT_IEEE80211_RADIO.
3893190225Srpaulo			 */
3894190225Srpaulo			if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
3895190225Srpaulo				break;
3896190225Srpaulo			if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
3897190225Srpaulo				break;
3898190225Srpaulo			if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
3899190225Srpaulo				break;
3900190225Srpaulo			montype = MONITOR_HOSTAP;
3901190225Srpaulo			cmd = priv[i].cmd;
3902190225Srpaulo			break;
3903190225Srpaulo		}
3904190225Srpaulo		if (strcmp(priv[i].name, "set_prismhdr") == 0) {
3905190225Srpaulo			/*
3906190225Srpaulo			 * Prism54 driver, use this one.
3907190225Srpaulo			 * Set monitor mode first.
3908190225Srpaulo			 * You can set it to 2 to get DLT_IEEE80211
3909190225Srpaulo			 * or 3 or get DLT_PRISM.
3910190225Srpaulo			 */
3911190225Srpaulo			if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
3912190225Srpaulo				break;
3913190225Srpaulo			if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
3914190225Srpaulo				break;
3915190225Srpaulo			if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
3916190225Srpaulo				break;
3917190225Srpaulo			montype = MONITOR_PRISM54;
3918190225Srpaulo			cmd = priv[i].cmd;
3919190225Srpaulo			break;
3920190225Srpaulo		}
3921190225Srpaulo		if (strcmp(priv[i].name, "forceprismheader") == 0) {
3922190225Srpaulo			/*
3923190225Srpaulo			 * RT2570 driver, use this one.
3924190225Srpaulo			 * Do this after turning monitor mode on.
3925190225Srpaulo			 * You can set it to 1 to get DLT_PRISM or 2
3926190225Srpaulo			 * to get DLT_IEEE80211.
3927190225Srpaulo			 */
3928190225Srpaulo			if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
3929190225Srpaulo				break;
3930190225Srpaulo			if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
3931190225Srpaulo				break;
3932190225Srpaulo			if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
3933190225Srpaulo				break;
3934190225Srpaulo			montype = MONITOR_RT2570;
3935190225Srpaulo			cmd = priv[i].cmd;
3936190225Srpaulo			break;
3937190225Srpaulo		}
3938190225Srpaulo		if (strcmp(priv[i].name, "forceprism") == 0) {
3939190225Srpaulo			/*
3940190225Srpaulo			 * RT73 driver, use this one.
3941190225Srpaulo			 * Do this after turning monitor mode on.
3942190225Srpaulo			 * Its argument is a *string*; you can
3943190225Srpaulo			 * set it to "1" to get DLT_PRISM or "2"
3944190225Srpaulo			 * to get DLT_IEEE80211.
3945190225Srpaulo			 */
3946190225Srpaulo			if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
3947190225Srpaulo				break;
3948190225Srpaulo			if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
3949190225Srpaulo				break;
3950190225Srpaulo			montype = MONITOR_RT73;
3951190225Srpaulo			cmd = priv[i].cmd;
3952190225Srpaulo			break;
3953190225Srpaulo		}
3954190225Srpaulo		if (strcmp(priv[i].name, "prismhdr") == 0) {
3955190225Srpaulo			/*
3956190225Srpaulo			 * One of the RTL8xxx drivers, use this one.
3957190225Srpaulo			 * It can only be done after monitor mode
3958190225Srpaulo			 * has been turned on.  You can set it to 1
3959190225Srpaulo			 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
3960190225Srpaulo			 */
3961190225Srpaulo			if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
3962190225Srpaulo				break;
3963190225Srpaulo			if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
3964190225Srpaulo				break;
3965190225Srpaulo			if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
3966190225Srpaulo				break;
3967190225Srpaulo			montype = MONITOR_RTL8XXX;
3968190225Srpaulo			cmd = priv[i].cmd;
3969190225Srpaulo			break;
3970190225Srpaulo		}
3971190225Srpaulo		if (strcmp(priv[i].name, "rfmontx") == 0) {
3972190225Srpaulo			/*
3973190225Srpaulo			 * RT2500 or RT61 driver, use this one.
3974190225Srpaulo			 * It has one one-byte parameter; set
3975190225Srpaulo			 * u.data.length to 1 and u.data.pointer to
3976190225Srpaulo			 * point to the parameter.
3977190225Srpaulo			 * It doesn't itself turn monitor mode on.
3978190225Srpaulo			 * You can set it to 1 to allow transmitting
3979190225Srpaulo			 * in monitor mode(?) and get DLT_IEEE80211,
3980190225Srpaulo			 * or set it to 0 to disallow transmitting in
3981190225Srpaulo			 * monitor mode(?) and get DLT_PRISM.
3982190225Srpaulo			 */
3983190225Srpaulo			if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
3984190225Srpaulo				break;
3985190225Srpaulo			if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
3986190225Srpaulo				break;
3987190225Srpaulo			montype = MONITOR_RT2500;
3988190225Srpaulo			cmd = priv[i].cmd;
3989190225Srpaulo			break;
3990190225Srpaulo		}
3991190225Srpaulo		if (strcmp(priv[i].name, "monitor") == 0) {
3992190225Srpaulo			/*
3993190225Srpaulo			 * Either ACX100 or hostap, use this one.
3994190225Srpaulo			 * It turns monitor mode on.
3995190225Srpaulo			 * If it takes two arguments, it's ACX100;
3996190225Srpaulo			 * the first argument is 1 for DLT_PRISM
3997190225Srpaulo			 * or 2 for DLT_IEEE80211, and the second
3998190225Srpaulo			 * argument is the channel on which to
3999190225Srpaulo			 * run.  If it takes one argument, it's
4000190225Srpaulo			 * HostAP, and the argument is 2 for
4001190225Srpaulo			 * DLT_IEEE80211 and 3 for DLT_PRISM.
4002190225Srpaulo			 *
4003190225Srpaulo			 * If we see this, we don't quit, as this
4004190225Srpaulo			 * might be a version of the hostap driver
4005190225Srpaulo			 * that also supports "monitor_type".
4006190225Srpaulo			 */
4007190225Srpaulo			if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4008190225Srpaulo				break;
4009190225Srpaulo			if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4010190225Srpaulo				break;
4011190225Srpaulo			switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
401275107Sfenner
4013190225Srpaulo			case 1:
4014190225Srpaulo				montype = MONITOR_PRISM;
4015190225Srpaulo				cmd = priv[i].cmd;
4016190225Srpaulo				break;
4017190225Srpaulo
4018190225Srpaulo			case 2:
4019190225Srpaulo				montype = MONITOR_ACX100;
4020190225Srpaulo				cmd = priv[i].cmd;
4021190225Srpaulo				break;
4022190225Srpaulo
4023190225Srpaulo			default:
4024190225Srpaulo				break;
4025190225Srpaulo			}
4026190225Srpaulo		}
4027190225Srpaulo	}
4028190225Srpaulo	free(priv);
4029190225Srpaulo
4030190225Srpaulo	/*
4031190225Srpaulo	 * XXX - ipw3945?  islism?
4032190225Srpaulo	 */
4033190225Srpaulo
4034190225Srpaulo	/*
4035190225Srpaulo	 * Get the old mode.
4036190225Srpaulo	 */
4037190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
4038190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
4039190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4040190225Srpaulo	if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
404175107Sfenner		/*
4042190225Srpaulo		 * We probably won't be able to set the mode, either.
4043190225Srpaulo		 */
4044190225Srpaulo		return PCAP_ERROR_RFMON_NOTSUP;
4045190225Srpaulo	}
4046190225Srpaulo
4047190225Srpaulo	/*
4048190225Srpaulo	 * Is it currently in monitor mode?
4049190225Srpaulo	 */
4050190225Srpaulo	if (ireq.u.mode == IW_MODE_MONITOR) {
4051190225Srpaulo		/*
4052190225Srpaulo		 * Yes.  Just leave things as they are.
4053190225Srpaulo		 * We don't offer multiple link-layer types, as
4054190225Srpaulo		 * changing the link-layer type out from under
4055190225Srpaulo		 * somebody else capturing in monitor mode would
4056190225Srpaulo		 * be considered rude.
4057190225Srpaulo		 */
4058190225Srpaulo		return 1;
4059190225Srpaulo	}
4060190225Srpaulo	/*
4061190225Srpaulo	 * No.  We have to put the adapter into rfmon mode.
4062190225Srpaulo	 */
4063190225Srpaulo
4064190225Srpaulo	/*
4065190225Srpaulo	 * If we haven't already done so, arrange to have
4066190225Srpaulo	 * "pcap_close_all()" called when we exit.
4067190225Srpaulo	 */
4068190225Srpaulo	if (!pcap_do_addexit(handle)) {
4069190225Srpaulo		/*
4070190225Srpaulo		 * "atexit()" failed; don't put the interface
4071190225Srpaulo		 * in rfmon mode, just give up.
4072190225Srpaulo		 */
4073190225Srpaulo		return PCAP_ERROR_RFMON_NOTSUP;
4074190225Srpaulo	}
4075190225Srpaulo
4076190225Srpaulo	/*
4077190225Srpaulo	 * Save the old mode.
4078190225Srpaulo	 */
4079190225Srpaulo	handle->md.oldmode = ireq.u.mode;
4080190225Srpaulo
4081190225Srpaulo	/*
4082190225Srpaulo	 * Put the adapter in rfmon mode.  How we do this depends
4083190225Srpaulo	 * on whether we have a special private ioctl or not.
4084190225Srpaulo	 */
4085190225Srpaulo	if (montype == MONITOR_PRISM) {
4086190225Srpaulo		/*
4087190225Srpaulo		 * We have the "monitor" private ioctl, but none of
4088190225Srpaulo		 * the other private ioctls.  Use this, and select
4089190225Srpaulo		 * the Prism header.
409075107Sfenner		 *
4091190225Srpaulo		 * If it fails, just fall back on SIOCSIWMODE.
409275107Sfenner		 */
4093190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4094190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4095190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4096190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4097190225Srpaulo		ireq.u.data.length = 1;	/* 1 argument */
4098190225Srpaulo		args[0] = 3;	/* request Prism header */
4099190225Srpaulo		memcpy(ireq.u.name, args, IFNAMSIZ);
4100190225Srpaulo		if (ioctl(sock_fd, cmd, &ireq) != -1) {
4101190225Srpaulo			/*
4102190225Srpaulo			 * Success.
4103190225Srpaulo			 * Note that we have to put the old mode back
4104190225Srpaulo			 * when we close the device.
4105190225Srpaulo			 */
4106214518Srpaulo			handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4107190225Srpaulo
4108190225Srpaulo			/*
4109190225Srpaulo			 * Add this to the list of pcaps to close
4110190225Srpaulo			 * when we exit.
4111190225Srpaulo			 */
4112190225Srpaulo			pcap_add_to_pcaps_to_close(handle);
4113190225Srpaulo
4114190225Srpaulo			return 1;
411526175Sfenner		}
411675107Sfenner
411775107Sfenner		/*
4118190225Srpaulo		 * Failure.  Fall back on SIOCSIWMODE.
411975107Sfenner		 */
4120190225Srpaulo	}
4121190225Srpaulo
4122190225Srpaulo	/*
4123190225Srpaulo	 * First, turn monitor mode on.
4124190225Srpaulo	 */
4125190225Srpaulo	strncpy(ireq.ifr_ifrn.ifrn_name, device,
4126190225Srpaulo	    sizeof ireq.ifr_ifrn.ifrn_name);
4127190225Srpaulo	ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4128190225Srpaulo	ireq.u.mode = IW_MODE_MONITOR;
4129190225Srpaulo	if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
4130190225Srpaulo		/*
4131190225Srpaulo		 * Scientist, you've failed.
4132190225Srpaulo		 */
4133190225Srpaulo		return PCAP_ERROR_RFMON_NOTSUP;
4134190225Srpaulo	}
4135190225Srpaulo
4136190225Srpaulo	/*
4137190225Srpaulo	 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4138190225Srpaulo	 * monitor mode and setting the channel, and then does
4139190225Srpaulo	 * "iwconfig up".
4140190225Srpaulo	 */
4141190225Srpaulo
4142190225Srpaulo	/*
4143190225Srpaulo	 * Now select the appropriate radio header.
4144190225Srpaulo	 */
4145190225Srpaulo	switch (montype) {
4146190225Srpaulo
4147190225Srpaulo	case MONITOR_WEXT:
4148190225Srpaulo		/*
4149190225Srpaulo		 * We don't have any private ioctl to set the header.
4150190225Srpaulo		 */
4151190225Srpaulo		break;
4152190225Srpaulo
4153190225Srpaulo	case MONITOR_HOSTAP:
4154190225Srpaulo		/*
4155214518Srpaulo		 * Try to select the radiotap header.
4156190225Srpaulo		 */
4157190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4158190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4159190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4160190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4161214518Srpaulo		args[0] = 3;	/* request radiotap header */
4162214518Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4163214518Srpaulo		if (ioctl(sock_fd, cmd, &ireq) != -1)
4164214518Srpaulo			break;	/* success */
4165214518Srpaulo
4166214518Srpaulo		/*
4167214518Srpaulo		 * That failed.  Try to select the AVS header.
4168214518Srpaulo		 */
4169214518Srpaulo		memset(&ireq, 0, sizeof ireq);
4170214518Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4171214518Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4172214518Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4173190225Srpaulo		args[0] = 2;	/* request AVS header */
4174190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4175214518Srpaulo		if (ioctl(sock_fd, cmd, &ireq) != -1)
4176214518Srpaulo			break;	/* success */
4177214518Srpaulo
4178214518Srpaulo		/*
4179214518Srpaulo		 * That failed.  Try to select the Prism header.
4180214518Srpaulo		 */
4181214518Srpaulo		memset(&ireq, 0, sizeof ireq);
4182214518Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4183214518Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4184214518Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4185214518Srpaulo		args[0] = 1;	/* request Prism header */
4186214518Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4187214518Srpaulo		ioctl(sock_fd, cmd, &ireq);
4188190225Srpaulo		break;
4189190225Srpaulo
4190190225Srpaulo	case MONITOR_PRISM:
4191190225Srpaulo		/*
4192190225Srpaulo		 * The private ioctl failed.
4193190225Srpaulo		 */
4194190225Srpaulo		break;
4195190225Srpaulo
4196190225Srpaulo	case MONITOR_PRISM54:
4197190225Srpaulo		/*
4198190225Srpaulo		 * Select the Prism header.
4199190225Srpaulo		 */
4200190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4201190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4202190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4203190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4204190225Srpaulo		args[0] = 3;	/* request Prism header */
4205190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4206190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4207190225Srpaulo		break;
4208190225Srpaulo
4209190225Srpaulo	case MONITOR_ACX100:
4210190225Srpaulo		/*
4211190225Srpaulo		 * Get the current channel.
4212190225Srpaulo		 */
4213190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4214190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4215190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4216190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4217190225Srpaulo		if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
4218190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4219190225Srpaulo			    "%s: SIOCGIWFREQ: %s", device,
4220190225Srpaulo			    pcap_strerror(errno));
4221190225Srpaulo			return PCAP_ERROR;
4222190225Srpaulo		}
4223190225Srpaulo		channel = ireq.u.freq.m;
4224190225Srpaulo
4225190225Srpaulo		/*
4226190225Srpaulo		 * Select the Prism header, and set the channel to the
4227190225Srpaulo		 * current value.
4228190225Srpaulo		 */
4229190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4230190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4231190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4232190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4233190225Srpaulo		args[0] = 1;		/* request Prism header */
4234190225Srpaulo		args[1] = channel;	/* set channel */
4235190225Srpaulo		memcpy(ireq.u.name, args, 2*sizeof (int));
4236190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4237190225Srpaulo		break;
4238190225Srpaulo
4239190225Srpaulo	case MONITOR_RT2500:
4240190225Srpaulo		/*
4241190225Srpaulo		 * Disallow transmission - that turns on the
4242190225Srpaulo		 * Prism header.
4243190225Srpaulo		 */
4244190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4245190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4246190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4247190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4248190225Srpaulo		args[0] = 0;	/* disallow transmitting */
4249190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4250190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4251190225Srpaulo		break;
4252190225Srpaulo
4253190225Srpaulo	case MONITOR_RT2570:
4254190225Srpaulo		/*
4255190225Srpaulo		 * Force the Prism header.
4256190225Srpaulo		 */
4257190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4258190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4259190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4260190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4261190225Srpaulo		args[0] = 1;	/* request Prism header */
4262190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4263190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4264190225Srpaulo		break;
4265190225Srpaulo
4266190225Srpaulo	case MONITOR_RT73:
4267190225Srpaulo		/*
4268190225Srpaulo		 * Force the Prism header.
4269190225Srpaulo		 */
4270190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4271190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4272190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4273190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4274190225Srpaulo		ireq.u.data.length = 1;	/* 1 argument */
4275190225Srpaulo		ireq.u.data.pointer = "1";
4276190225Srpaulo		ireq.u.data.flags = 0;
4277190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4278190225Srpaulo		break;
4279190225Srpaulo
4280190225Srpaulo	case MONITOR_RTL8XXX:
4281190225Srpaulo		/*
4282190225Srpaulo		 * Force the Prism header.
4283190225Srpaulo		 */
4284190225Srpaulo		memset(&ireq, 0, sizeof ireq);
4285190225Srpaulo		strncpy(ireq.ifr_ifrn.ifrn_name, device,
4286190225Srpaulo		    sizeof ireq.ifr_ifrn.ifrn_name);
4287190225Srpaulo		ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4288190225Srpaulo		args[0] = 1;	/* request Prism header */
4289190225Srpaulo		memcpy(ireq.u.name, args, sizeof (int));
4290190225Srpaulo		ioctl(sock_fd, cmd, &ireq);
4291190225Srpaulo		break;
429226175Sfenner	}
4293127664Sbms
4294190225Srpaulo	/*
4295190225Srpaulo	 * Note that we have to put the old mode back when we
4296190225Srpaulo	 * close the device.
4297190225Srpaulo	 */
4298214518Srpaulo	handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4299190225Srpaulo
4300190225Srpaulo	/*
4301190225Srpaulo	 * Add this to the list of pcaps to close when we exit.
4302190225Srpaulo	 */
4303190225Srpaulo	pcap_add_to_pcaps_to_close(handle);
4304190225Srpaulo
4305190225Srpaulo	return 1;
4306214518Srpaulo}
4307214518Srpaulo#endif /* IW_MODE_MONITOR */
4308214518Srpaulo
4309214518Srpaulo/*
4310214518Srpaulo * Try various mechanisms to enter monitor mode.
4311214518Srpaulo */
4312214518Srpaulostatic int
4313214518Srpauloenter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
4314214518Srpaulo{
4315214518Srpaulo#if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4316214518Srpaulo	int ret;
4317214518Srpaulo#endif
4318214518Srpaulo
4319214518Srpaulo#ifdef HAVE_LIBNL
4320214518Srpaulo	ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
4321214518Srpaulo	if (ret < 0)
4322214518Srpaulo		return ret;	/* error attempting to do so */
4323214518Srpaulo	if (ret == 1)
4324214518Srpaulo		return 1;	/* success */
4325214518Srpaulo#endif /* HAVE_LIBNL */
4326214518Srpaulo
4327214518Srpaulo#ifdef IW_MODE_MONITOR
4328214518Srpaulo	ret = enter_rfmon_mode_wext(handle, sock_fd, device);
4329214518Srpaulo	if (ret < 0)
4330214518Srpaulo		return ret;	/* error attempting to do so */
4331214518Srpaulo	if (ret == 1)
4332214518Srpaulo		return 1;	/* success */
4333214518Srpaulo#endif /* IW_MODE_MONITOR */
4334214518Srpaulo
4335190225Srpaulo	/*
4336214518Srpaulo	 * Either none of the mechanisms we know about work or none
4337214518Srpaulo	 * of those mechanisms are available, so we can't do monitor
4338214518Srpaulo	 * mode.
4339190225Srpaulo	 */
4340190225Srpaulo	return 0;
434175107Sfenner}
434226175Sfenner
4343190225Srpaulo#endif /* HAVE_PF_PACKET_SOCKETS */
4344190225Srpaulo
4345190225Srpaulo/* ===== Functions to interface to the older kernels ================== */
4346190225Srpaulo
434775107Sfenner/*
4348190225Srpaulo * Try to open a packet socket using the old kernel interface.
4349190225Srpaulo * Returns 1 on success and a PCAP_ERROR_ value on an error.
435075107Sfenner */
435175107Sfennerstatic int
4352190225Srpauloactivate_old(pcap_t *handle)
435375107Sfenner{
4354127664Sbms	int		arptype;
435575107Sfenner	struct ifreq	ifr;
4356190225Srpaulo	const char	*device = handle->opt.source;
4357190225Srpaulo	struct utsname	utsname;
4358190225Srpaulo	int		mtu;
435975107Sfenner
4360190225Srpaulo	/* Open the socket */
436175107Sfenner
4362190225Srpaulo	handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
4363190225Srpaulo	if (handle->fd == -1) {
4364190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4365190225Srpaulo			 "socket: %s", pcap_strerror(errno));
4366190225Srpaulo		return PCAP_ERROR_PERM_DENIED;
4367190225Srpaulo	}
436875107Sfenner
4369190225Srpaulo	/* It worked - we are using the old interface */
4370190225Srpaulo	handle->md.sock_packet = 1;
437175107Sfenner
4372190225Srpaulo	/* ...which means we get the link-layer header. */
4373190225Srpaulo	handle->md.cooked = 0;
437475107Sfenner
4375190225Srpaulo	/* Bind to the given device */
437675107Sfenner
4377214518Srpaulo	if (strcmp(device, "any") == 0) {
4378190225Srpaulo		strncpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
4379190225Srpaulo			PCAP_ERRBUF_SIZE);
4380190225Srpaulo		return PCAP_ERROR;
4381190225Srpaulo	}
4382190225Srpaulo	if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
4383190225Srpaulo		return PCAP_ERROR;
438475107Sfenner
4385190225Srpaulo	/*
4386190225Srpaulo	 * Try to get the link-layer type.
4387190225Srpaulo	 */
4388190225Srpaulo	arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
4389190225Srpaulo	if (arptype < 0)
4390190225Srpaulo		return PCAP_ERROR;
4391127664Sbms
4392190225Srpaulo	/*
4393190225Srpaulo	 * Try to find the DLT_ type corresponding to that
4394190225Srpaulo	 * link-layer type.
4395190225Srpaulo	 */
4396190225Srpaulo	map_arphrd_to_dlt(handle, arptype, 0);
4397190225Srpaulo	if (handle->linktype == -1) {
4398190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4399190225Srpaulo			 "unknown arptype %d", arptype);
4400190225Srpaulo		return PCAP_ERROR;
4401190225Srpaulo	}
4402127664Sbms
4403190225Srpaulo	/* Go to promisc mode if requested */
4404127664Sbms
4405190225Srpaulo	if (handle->opt.promisc) {
4406190225Srpaulo		memset(&ifr, 0, sizeof(ifr));
4407190225Srpaulo		strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4408190225Srpaulo		if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
4409190225Srpaulo			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4410190225Srpaulo				 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
4411190225Srpaulo			return PCAP_ERROR;
4412190225Srpaulo		}
4413190225Srpaulo		if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
4414190225Srpaulo			/*
4415190225Srpaulo			 * Promiscuous mode isn't currently on,
4416190225Srpaulo			 * so turn it on, and remember that
4417190225Srpaulo			 * we should turn it off when the
4418190225Srpaulo			 * pcap_t is closed.
4419190225Srpaulo			 */
442075107Sfenner
4421190225Srpaulo			/*
4422190225Srpaulo			 * If we haven't already done so, arrange
4423190225Srpaulo			 * to have "pcap_close_all()" called when
4424190225Srpaulo			 * we exit.
4425190225Srpaulo			 */
4426190225Srpaulo			if (!pcap_do_addexit(handle)) {
442775107Sfenner				/*
4428190225Srpaulo				 * "atexit()" failed; don't put
4429190225Srpaulo				 * the interface in promiscuous
4430190225Srpaulo				 * mode, just give up.
443175107Sfenner				 */
4432190225Srpaulo				return PCAP_ERROR;
4433190225Srpaulo			}
443475107Sfenner
4435190225Srpaulo			ifr.ifr_flags |= IFF_PROMISC;
4436190225Srpaulo			if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
4437190225Srpaulo			        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4438190225Srpaulo					 "SIOCSIFFLAGS: %s",
4439190225Srpaulo					 pcap_strerror(errno));
4440190225Srpaulo				return PCAP_ERROR;
4441190225Srpaulo			}
4442214518Srpaulo			handle->md.must_do_on_close |= MUST_CLEAR_PROMISC;
444375107Sfenner
4444190225Srpaulo			/*
4445190225Srpaulo			 * Add this to the list of pcaps
4446190225Srpaulo			 * to close when we exit.
4447190225Srpaulo			 */
4448190225Srpaulo			pcap_add_to_pcaps_to_close(handle);
444975107Sfenner		}
4450190225Srpaulo	}
445175107Sfenner
4452190225Srpaulo	/*
4453190225Srpaulo	 * Compute the buffer size.
4454190225Srpaulo	 *
4455190225Srpaulo	 * We're using SOCK_PACKET, so this might be a 2.0[.x]
4456190225Srpaulo	 * kernel, and might require special handling - check.
4457190225Srpaulo	 */
4458190225Srpaulo	if (uname(&utsname) < 0 ||
4459190225Srpaulo	    strncmp(utsname.release, "2.0", 3) == 0) {
446098530Sfenner		/*
4461190225Srpaulo		 * Either we couldn't find out what kernel release
4462190225Srpaulo		 * this is, or it's a 2.0[.x] kernel.
4463190225Srpaulo		 *
4464190225Srpaulo		 * In the 2.0[.x] kernel, a "recvfrom()" on
4465190225Srpaulo		 * a SOCK_PACKET socket, with MSG_TRUNC set, will
4466190225Srpaulo		 * return the number of bytes read, so if we pass
4467190225Srpaulo		 * a length based on the snapshot length, it'll
4468190225Srpaulo		 * return the number of bytes from the packet
4469190225Srpaulo		 * copied to userland, not the actual length
4470190225Srpaulo		 * of the packet.
4471190225Srpaulo		 *
4472190225Srpaulo		 * This means that, for example, the IP dissector
4473190225Srpaulo		 * in tcpdump will get handed a packet length less
4474190225Srpaulo		 * than the length in the IP header, and will
4475190225Srpaulo		 * complain about "truncated-ip".
4476190225Srpaulo		 *
4477190225Srpaulo		 * So we don't bother trying to copy from the
4478190225Srpaulo		 * kernel only the bytes in which we're interested,
4479190225Srpaulo		 * but instead copy them all, just as the older
4480190225Srpaulo		 * versions of libpcap for Linux did.
4481190225Srpaulo		 *
4482190225Srpaulo		 * The buffer therefore needs to be big enough to
4483190225Srpaulo		 * hold the largest packet we can get from this
4484190225Srpaulo		 * device.  Unfortunately, we can't get the MRU
4485190225Srpaulo		 * of the network; we can only get the MTU.  The
4486190225Srpaulo		 * MTU may be too small, in which case a packet larger
4487190225Srpaulo		 * than the buffer size will be truncated *and* we
4488190225Srpaulo		 * won't get the actual packet size.
4489190225Srpaulo		 *
4490190225Srpaulo		 * However, if the snapshot length is larger than
4491190225Srpaulo		 * the buffer size based on the MTU, we use the
4492190225Srpaulo		 * snapshot length as the buffer size, instead;
4493190225Srpaulo		 * this means that with a sufficiently large snapshot
4494190225Srpaulo		 * length we won't artificially truncate packets
4495190225Srpaulo		 * to the MTU-based size.
4496190225Srpaulo		 *
4497190225Srpaulo		 * This mess just one of many problems with packet
4498190225Srpaulo		 * capture on 2.0[.x] kernels; you really want a
4499190225Srpaulo		 * 2.2[.x] or later kernel if you want packet capture
4500190225Srpaulo		 * to work well.
450198530Sfenner		 */
4502190225Srpaulo		mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
4503190225Srpaulo		if (mtu == -1)
4504190225Srpaulo			return PCAP_ERROR;
4505190225Srpaulo		handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
4506190225Srpaulo		if (handle->bufsize < handle->snapshot)
4507190225Srpaulo			handle->bufsize = handle->snapshot;
4508190225Srpaulo	} else {
4509190225Srpaulo		/*
4510190225Srpaulo		 * This is a 2.2[.x] or later kernel.
4511190225Srpaulo		 *
4512190225Srpaulo		 * We can safely pass "recvfrom()" a byte count
4513190225Srpaulo		 * based on the snapshot length.
4514190225Srpaulo		 */
4515190225Srpaulo		handle->bufsize = handle->snapshot;
4516190225Srpaulo	}
451798530Sfenner
4518190225Srpaulo	/*
4519190225Srpaulo	 * Default value for offset to align link-layer payload
4520190225Srpaulo	 * on a 4-byte boundary.
4521190225Srpaulo	 */
4522190225Srpaulo	handle->offset	 = 0;
452375107Sfenner
4524190225Srpaulo	return 1;
452575107Sfenner}
452675107Sfenner
452775107Sfenner/*
4528127664Sbms *  Bind the socket associated with FD to the given device using the
452975107Sfenner *  interface of the old kernels.
453075107Sfenner */
453175107Sfennerstatic int
453275107Sfenneriface_bind_old(int fd, const char *device, char *ebuf)
453375107Sfenner{
453475107Sfenner	struct sockaddr	saddr;
4535127664Sbms	int		err;
4536127664Sbms	socklen_t	errlen = sizeof(err);
453775107Sfenner
453875107Sfenner	memset(&saddr, 0, sizeof(saddr));
453975107Sfenner	strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
454075107Sfenner	if (bind(fd, &saddr, sizeof(saddr)) == -1) {
454175107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
454275107Sfenner			 "bind: %s", pcap_strerror(errno));
454375107Sfenner		return -1;
454426175Sfenner	}
454526175Sfenner
4546127664Sbms	/* Any pending errors, e.g., network is down? */
4547127664Sbms
4548127664Sbms	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
4549127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4550127664Sbms			"getsockopt: %s", pcap_strerror(errno));
4551127664Sbms		return -1;
4552127664Sbms	}
4553127664Sbms
4554127664Sbms	if (err > 0) {
4555127664Sbms		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4556127664Sbms			"bind: %s", pcap_strerror(err));
4557127664Sbms		return -1;
4558127664Sbms	}
4559127664Sbms
456075107Sfenner	return 0;
456126175Sfenner}
456226175Sfenner
456375107Sfenner
456475107Sfenner/* ===== System calls available on all supported kernels ============== */
456575107Sfenner
456675107Sfenner/*
4567127664Sbms *  Query the kernel for the MTU of the given interface.
456875107Sfenner */
456975107Sfennerstatic int
457075107Sfenneriface_get_mtu(int fd, const char *device, char *ebuf)
457126175Sfenner{
457275107Sfenner	struct ifreq	ifr;
457326175Sfenner
457475107Sfenner	if (!device)
457575107Sfenner		return BIGGER_THAN_ALL_MTUS;
457675107Sfenner
457775107Sfenner	memset(&ifr, 0, sizeof(ifr));
457875107Sfenner	strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
457975107Sfenner
458075107Sfenner	if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
458175107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4582172677Smlaier			 "SIOCGIFMTU: %s", pcap_strerror(errno));
458375107Sfenner		return -1;
458475107Sfenner	}
458575107Sfenner
458675107Sfenner	return ifr.ifr_mtu;
458726175Sfenner}
458826175Sfenner
458975107Sfenner/*
459075107Sfenner *  Get the hardware type of the given interface as ARPHRD_xxx constant.
459175107Sfenner */
459275107Sfennerstatic int
459375107Sfenneriface_get_arptype(int fd, const char *device, char *ebuf)
459426175Sfenner{
459575107Sfenner	struct ifreq	ifr;
459626175Sfenner
459775107Sfenner	memset(&ifr, 0, sizeof(ifr));
459875107Sfenner	strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
459975107Sfenner
460075107Sfenner	if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
460175107Sfenner		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4602172677Smlaier			 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
4603190225Srpaulo		if (errno == ENODEV) {
4604190225Srpaulo			/*
4605190225Srpaulo			 * No such device.
4606190225Srpaulo			 */
4607190225Srpaulo			return PCAP_ERROR_NO_SUCH_DEVICE;
4608190225Srpaulo		}
4609190225Srpaulo		return PCAP_ERROR;
461075107Sfenner	}
461175107Sfenner
461275107Sfenner	return ifr.ifr_hwaddr.sa_family;
461326175Sfenner}
461475107Sfenner
461598530Sfenner#ifdef SO_ATTACH_FILTER
461675107Sfennerstatic int
4617214518Srpaulofix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
461875107Sfenner{
461975107Sfenner	size_t prog_size;
462075107Sfenner	register int i;
462175107Sfenner	register struct bpf_insn *p;
462275107Sfenner	struct bpf_insn *f;
462375107Sfenner	int len;
462475107Sfenner
462575107Sfenner	/*
462675107Sfenner	 * Make a copy of the filter, and modify that copy if
462775107Sfenner	 * necessary.
462875107Sfenner	 */
462975107Sfenner	prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
463075107Sfenner	len = handle->fcode.bf_len;
463175107Sfenner	f = (struct bpf_insn *)malloc(prog_size);
463275107Sfenner	if (f == NULL) {
4633190225Srpaulo		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
463475107Sfenner			 "malloc: %s", pcap_strerror(errno));
463575107Sfenner		return -1;
463675107Sfenner	}
463775107Sfenner	memcpy(f, handle->fcode.bf_insns, prog_size);
463875107Sfenner	fcode->len = len;
463975107Sfenner	fcode->filter = (struct sock_filter *) f;
464075107Sfenner
464175107Sfenner	for (i = 0; i < len; ++i) {
464275107Sfenner		p = &f[i];
464375107Sfenner		/*
464475107Sfenner		 * What type of instruction is this?
464575107Sfenner		 */
464675107Sfenner		switch (BPF_CLASS(p->code)) {
464775107Sfenner
464875107Sfenner		case BPF_RET:
464975107Sfenner			/*
4650214518Srpaulo			 * It's a return instruction; are we capturing
4651214518Srpaulo			 * in memory-mapped mode?
465275107Sfenner			 */
4653214518Srpaulo			if (!is_mmapped) {
465475107Sfenner				/*
4655214518Srpaulo				 * No; is the snapshot length a constant,
4656214518Srpaulo				 * rather than the contents of the
4657214518Srpaulo				 * accumulator?
465875107Sfenner				 */
4659214518Srpaulo				if (BPF_MODE(p->code) == BPF_K) {
4660214518Srpaulo					/*
4661214518Srpaulo					 * Yes - if the value to be returned,
4662214518Srpaulo					 * i.e. the snapshot length, is
4663214518Srpaulo					 * anything other than 0, make it
4664214518Srpaulo					 * 65535, so that the packet is
4665214518Srpaulo					 * truncated by "recvfrom()",
4666214518Srpaulo					 * not by the filter.
4667214518Srpaulo					 *
4668214518Srpaulo					 * XXX - there's nothing we can
4669214518Srpaulo					 * easily do if it's getting the
4670214518Srpaulo					 * value from the accumulator; we'd
4671214518Srpaulo					 * have to insert code to force
4672214518Srpaulo					 * non-zero values to be 65535.
4673214518Srpaulo					 */
4674214518Srpaulo					if (p->k != 0)
4675214518Srpaulo						p->k = 65535;
4676214518Srpaulo				}
467775107Sfenner			}
467875107Sfenner			break;
467975107Sfenner
468075107Sfenner		case BPF_LD:
468175107Sfenner		case BPF_LDX:
468275107Sfenner			/*
468375107Sfenner			 * It's a load instruction; is it loading
468475107Sfenner			 * from the packet?
468575107Sfenner			 */
468675107Sfenner			switch (BPF_MODE(p->code)) {
468775107Sfenner
468875107Sfenner			case BPF_ABS:
468975107Sfenner			case BPF_IND:
469075107Sfenner			case BPF_MSH:
469175107Sfenner				/*
469275107Sfenner				 * Yes; are we in cooked mode?
469375107Sfenner				 */
469475107Sfenner				if (handle->md.cooked) {
469575107Sfenner					/*
469675107Sfenner					 * Yes, so we need to fix this
469775107Sfenner					 * instruction.
469875107Sfenner					 */
469975107Sfenner					if (fix_offset(p) < 0) {
470075107Sfenner						/*
470175107Sfenner						 * We failed to do so.
470275107Sfenner						 * Return 0, so our caller
470375107Sfenner						 * knows to punt to userland.
470475107Sfenner						 */
470575107Sfenner						return 0;
470675107Sfenner					}
470775107Sfenner				}
470875107Sfenner				break;
470975107Sfenner			}
471075107Sfenner			break;
471175107Sfenner		}
471275107Sfenner	}
471375107Sfenner	return 1;	/* we succeeded */
471475107Sfenner}
471575107Sfenner
471675107Sfennerstatic int
471775107Sfennerfix_offset(struct bpf_insn *p)
471875107Sfenner{
471975107Sfenner	/*
472075107Sfenner	 * What's the offset?
472175107Sfenner	 */
472275107Sfenner	if (p->k >= SLL_HDR_LEN) {
472375107Sfenner		/*
472475107Sfenner		 * It's within the link-layer payload; that starts at an
472575107Sfenner		 * offset of 0, as far as the kernel packet filter is
472675107Sfenner		 * concerned, so subtract the length of the link-layer
472775107Sfenner		 * header.
472875107Sfenner		 */
472975107Sfenner		p->k -= SLL_HDR_LEN;
473075107Sfenner	} else if (p->k == 14) {
473175107Sfenner		/*
473275107Sfenner		 * It's the protocol field; map it to the special magic
473375107Sfenner		 * kernel offset for that field.
473475107Sfenner		 */
473575107Sfenner		p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
473675107Sfenner	} else {
473775107Sfenner		/*
473875107Sfenner		 * It's within the header, but it's not one of those
473975107Sfenner		 * fields; we can't do that in the kernel, so punt
474075107Sfenner		 * to userland.
474175107Sfenner		 */
474275107Sfenner		return -1;
474375107Sfenner	}
474475107Sfenner	return 0;
474575107Sfenner}
474698530Sfenner
474798530Sfennerstatic int
474898530Sfennerset_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
474998530Sfenner{
475098530Sfenner	int total_filter_on = 0;
475198530Sfenner	int save_mode;
475298530Sfenner	int ret;
475398530Sfenner	int save_errno;
475498530Sfenner
475598530Sfenner	/*
475698530Sfenner	 * The socket filter code doesn't discard all packets queued
475798530Sfenner	 * up on the socket when the filter is changed; this means
475898530Sfenner	 * that packets that don't match the new filter may show up
475998530Sfenner	 * after the new filter is put onto the socket, if those
476098530Sfenner	 * packets haven't yet been read.
476198530Sfenner	 *
476298530Sfenner	 * This means, for example, that if you do a tcpdump capture
476398530Sfenner	 * with a filter, the first few packets in the capture might
476498530Sfenner	 * be packets that wouldn't have passed the filter.
476598530Sfenner	 *
476698530Sfenner	 * We therefore discard all packets queued up on the socket
476798530Sfenner	 * when setting a kernel filter.  (This isn't an issue for
476898530Sfenner	 * userland filters, as the userland filtering is done after
476998530Sfenner	 * packets are queued up.)
477098530Sfenner	 *
477198530Sfenner	 * To flush those packets, we put the socket in read-only mode,
477298530Sfenner	 * and read packets from the socket until there are no more to
477398530Sfenner	 * read.
477498530Sfenner	 *
477598530Sfenner	 * In order to keep that from being an infinite loop - i.e.,
477698530Sfenner	 * to keep more packets from arriving while we're draining
477798530Sfenner	 * the queue - we put the "total filter", which is a filter
477898530Sfenner	 * that rejects all packets, onto the socket before draining
477998530Sfenner	 * the queue.
478098530Sfenner	 *
478198530Sfenner	 * This code deliberately ignores any errors, so that you may
478298530Sfenner	 * get bogus packets if an error occurs, rather than having
478398530Sfenner	 * the filtering done in userland even if it could have been
478498530Sfenner	 * done in the kernel.
478598530Sfenner	 */
4786127664Sbms	if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
478798530Sfenner		       &total_fcode, sizeof(total_fcode)) == 0) {
478898530Sfenner		char drain[1];
478998530Sfenner
479098530Sfenner		/*
479198530Sfenner		 * Note that we've put the total filter onto the socket.
479298530Sfenner		 */
479398530Sfenner		total_filter_on = 1;
479498530Sfenner
479598530Sfenner		/*
479698530Sfenner		 * Save the socket's current mode, and put it in
479798530Sfenner		 * non-blocking mode; we drain it by reading packets
4798127664Sbms		 * until we get an error (which is normally a
479998530Sfenner		 * "nothing more to be read" error).
480098530Sfenner		 */
480198530Sfenner		save_mode = fcntl(handle->fd, F_GETFL, 0);
480298530Sfenner		if (save_mode != -1 &&
480398530Sfenner		    fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
480498530Sfenner			while (recv(handle->fd, &drain, sizeof drain,
480598530Sfenner			       MSG_TRUNC) >= 0)
480698530Sfenner				;
4807127664Sbms			save_errno = errno;
480898530Sfenner			fcntl(handle->fd, F_SETFL, save_mode);
4809127664Sbms			if (save_errno != EAGAIN) {
4810127664Sbms				/* Fatal error */
4811127664Sbms				reset_kernel_filter(handle);
4812190225Srpaulo				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4813127664Sbms				 "recv: %s", pcap_strerror(save_errno));
4814127664Sbms				return -2;
4815127664Sbms			}
481698530Sfenner		}
481798530Sfenner	}
481898530Sfenner
481998530Sfenner	/*
482098530Sfenner	 * Now attach the new filter.
482198530Sfenner	 */
4822127664Sbms	ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
482398530Sfenner			 fcode, sizeof(*fcode));
482498530Sfenner	if (ret == -1 && total_filter_on) {
482598530Sfenner		/*
482698530Sfenner		 * Well, we couldn't set that filter on the socket,
482798530Sfenner		 * but we could set the total filter on the socket.
482898530Sfenner		 *
482998530Sfenner		 * This could, for example, mean that the filter was
483098530Sfenner		 * too big to put into the kernel, so we'll have to
483198530Sfenner		 * filter in userland; in any case, we'll be doing
483298530Sfenner		 * filtering in userland, so we need to remove the
483398530Sfenner		 * total filter so we see packets.
483498530Sfenner		 */
483598530Sfenner		save_errno = errno;
483698530Sfenner
483798530Sfenner		/*
483898530Sfenner		 * XXX - if this fails, we're really screwed;
483998530Sfenner		 * we have the total filter on the socket,
484098530Sfenner		 * and it won't come off.  What do we do then?
484198530Sfenner		 */
484298530Sfenner		reset_kernel_filter(handle);
484398530Sfenner
484498530Sfenner		errno = save_errno;
484598530Sfenner	}
4846127664Sbms	return ret;
484798530Sfenner}
484898530Sfenner
484998530Sfennerstatic int
485098530Sfennerreset_kernel_filter(pcap_t *handle)
485198530Sfenner{
4852172677Smlaier	/*
4853172677Smlaier	 * setsockopt() barfs unless it get a dummy parameter.
4854172677Smlaier	 * valgrind whines unless the value is initialized,
4855172677Smlaier	 * as it has no idea that setsockopt() ignores its
4856172677Smlaier	 * parameter.
4857172677Smlaier	 */
4858172677Smlaier	int dummy = 0;
485998530Sfenner
486098530Sfenner	return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
486198530Sfenner				   &dummy, sizeof(dummy));
486298530Sfenner}
486375107Sfenner#endif
4864