xref: /minix3/external/bsd/libpcap/dist/pcap-linux.c (revision d56f51ea7d8b9045e5c8e2028422523d3f9a5840)
1 /*	$NetBSD: pcap-linux.c,v 1.3 2015/03/31 21:39:42 christos Exp $	*/
2 
3 /*
4  *  pcap-linux.c: Packet capture interface to the Linux kernel
5  *
6  *  Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
7  *  		       Sebastian Krahmer  <krahmer@cs.uni-potsdam.de>
8  *
9  *  License: BSD
10  *
11  *  Redistribution and use in source and binary forms, with or without
12  *  modification, are permitted provided that the following conditions
13  *  are met:
14  *
15  *  1. Redistributions of source code must retain the above copyright
16  *     notice, this list of conditions and the following disclaimer.
17  *  2. Redistributions in binary form must reproduce the above copyright
18  *     notice, this list of conditions and the following disclaimer in
19  *     the documentation and/or other materials provided with the
20  *     distribution.
21  *  3. The names of the authors may not be used to endorse or promote
22  *     products derived from this software without specific prior
23  *     written permission.
24  *
25  *  THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
26  *  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
27  *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
28  *
29  *  Modifications:     Added PACKET_MMAP support
30  *                     Paolo Abeni <paolo.abeni@email.it>
31  *                     Added TPACKET_V3 support
32  *                     Gabor Tatarka <gabor.tatarka@ericsson.com>
33  *
34  *                     based on previous works of:
35  *                     Simon Patarin <patarin@cs.unibo.it>
36  *                     Phil Wood <cpw@lanl.gov>
37  *
38  * Monitor-mode support for mac80211 includes code taken from the iw
39  * command; the copyright notice for that code is
40  *
41  * Copyright (c) 2007, 2008	Johannes Berg
42  * Copyright (c) 2007		Andy Lutomirski
43  * Copyright (c) 2007		Mike Kershaw
44  * Copyright (c) 2008		Gábor Stefanik
45  *
46  * All rights reserved.
47  *
48  * Redistribution and use in source and binary forms, with or without
49  * modification, are permitted provided that the following conditions
50  * are met:
51  * 1. Redistributions of source code must retain the above copyright
52  *    notice, this list of conditions and the following disclaimer.
53  * 2. Redistributions in binary form must reproduce the above copyright
54  *    notice, this list of conditions and the following disclaimer in the
55  *    documentation and/or other materials provided with the distribution.
56  * 3. The name of the author may not be used to endorse or promote products
57  *    derived from this software without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
60  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
61  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
62  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
63  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
64  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
65  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
66  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
67  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  */
71 
72 /*
73  * Known problems with 2.0[.x] kernels:
74  *
75  *   - The loopback device gives every packet twice; on 2.2[.x] kernels,
76  *     if we use PF_PACKET, we can filter out the transmitted version
77  *     of the packet by using data in the "sockaddr_ll" returned by
78  *     "recvfrom()", but, on 2.0[.x] kernels, we have to use
79  *     PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
80  *     "sockaddr_pkt" which doesn't give us enough information to let
81  *     us do that.
82  *
83  *   - We have to set the interface's IFF_PROMISC flag ourselves, if
84  *     we're to run in promiscuous mode, which means we have to turn
85  *     it off ourselves when we're done; the kernel doesn't keep track
86  *     of how many sockets are listening promiscuously, which means
87  *     it won't get turned off automatically when no sockets are
88  *     listening promiscuously.  We catch "pcap_close()" and, for
89  *     interfaces we put into promiscuous mode, take them out of
90  *     promiscuous mode - which isn't necessarily the right thing to
91  *     do, if another socket also requested promiscuous mode between
92  *     the time when we opened the socket and the time when we close
93  *     the socket.
94  *
95  *   - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
96  *     return the amount of data that you could have read, rather than
97  *     the amount that was returned, so we can't just allocate a buffer
98  *     whose size is the snapshot length and pass the snapshot length
99  *     as the byte count, and also pass MSG_TRUNC, so that the return
100  *     value tells us how long the packet was on the wire.
101  *
102  *     This means that, if we want to get the actual size of the packet,
103  *     so we can return it in the "len" field of the packet header,
104  *     we have to read the entire packet, not just the part that fits
105  *     within the snapshot length, and thus waste CPU time copying data
106  *     from the kernel that our caller won't see.
107  *
108  *     We have to get the actual size, and supply it in "len", because
109  *     otherwise, the IP dissector in tcpdump, for example, will complain
110  *     about "truncated-ip", as the packet will appear to have been
111  *     shorter, on the wire, than the IP header said it should have been.
112  */
113 
114 
115 #define _GNU_SOURCE
116 
117 #include <sys/cdefs.h>
118 __RCSID("$NetBSD: pcap-linux.c,v 1.3 2015/03/31 21:39:42 christos Exp $");
119 
120 #ifdef HAVE_CONFIG_H
121 #include "config.h"
122 #endif
123 
124 #include <errno.h>
125 #include <stdio.h>
126 #include <stdlib.h>
127 #include <ctype.h>
128 #include <unistd.h>
129 #include <fcntl.h>
130 #include <string.h>
131 #include <limits.h>
132 #include <sys/stat.h>
133 #include <sys/socket.h>
134 #include <sys/ioctl.h>
135 #include <sys/utsname.h>
136 #include <sys/mman.h>
137 #include <linux/if.h>
138 #include <linux/if_packet.h>
139 #include <linux/sockios.h>
140 #include <netinet/in.h>
141 #include <linux/if_ether.h>
142 #include <net/if_arp.h>
143 #include <poll.h>
144 #include <dirent.h>
145 
146 #include "pcap-int.h"
147 #include "pcap/sll.h"
148 #include "pcap/vlan.h"
149 
150 /*
151  * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
152  * sockets rather than SOCK_PACKET sockets.
153  *
154  * To use them, we include <linux/if_packet.h> rather than
155  * <netpacket/packet.h>; we do so because
156  *
157  *	some Linux distributions (e.g., Slackware 4.0) have 2.2 or
158  *	later kernels and libc5, and don't provide a <netpacket/packet.h>
159  *	file;
160  *
161  *	not all versions of glibc2 have a <netpacket/packet.h> file
162  *	that defines stuff needed for some of the 2.4-or-later-kernel
163  *	features, so if the system has a 2.4 or later kernel, we
164  *	still can't use those features.
165  *
166  * We're already including a number of other <linux/XXX.h> headers, and
167  * this code is Linux-specific (no other OS has PF_PACKET sockets as
168  * a raw packet capture mechanism), so it's not as if you gain any
169  * useful portability by using <netpacket/packet.h>
170  *
171  * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
172  * isn't defined?  It only defines one data structure in 2.0.x, so
173  * it shouldn't cause any problems.
174  */
175 #ifdef PF_PACKET
176 # include <linux/if_packet.h>
177 
178  /*
179   * On at least some Linux distributions (for example, Red Hat 5.2),
180   * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
181   * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
182   * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
183   * the PACKET_xxx stuff.
184   *
185   * So we check whether PACKET_HOST is defined, and assume that we have
186   * PF_PACKET sockets only if it is defined.
187   */
188 # ifdef PACKET_HOST
189 #  define HAVE_PF_PACKET_SOCKETS
190 #  ifdef PACKET_AUXDATA
191 #   define HAVE_PACKET_AUXDATA
192 #  endif /* PACKET_AUXDATA */
193 # endif /* PACKET_HOST */
194 
195 
196  /* check for memory mapped access avaibility. We assume every needed
197   * struct is defined if the macro TPACKET_HDRLEN is defined, because it
198   * uses many ring related structs and macros */
199 # ifdef PCAP_SUPPORT_PACKET_RING
200 # ifdef TPACKET_HDRLEN
201 #  define HAVE_PACKET_RING
202 #  ifdef TPACKET3_HDRLEN
203 #   define HAVE_TPACKET3
204 #  endif /* TPACKET3_HDRLEN */
205 #  ifdef TPACKET2_HDRLEN
206 #   define HAVE_TPACKET2
207 #  else  /* TPACKET2_HDRLEN */
208 #   define TPACKET_V1	0    /* Old kernel with only V1, so no TPACKET_Vn defined */
209 #  endif /* TPACKET2_HDRLEN */
210 # endif /* TPACKET_HDRLEN */
211 # endif /* PCAP_SUPPORT_PACKET_RING */
212 #endif /* PF_PACKET */
213 
214 #ifdef SO_ATTACH_FILTER
215 #include <linux/types.h>
216 #include <linux/filter.h>
217 #endif
218 
219 #ifdef HAVE_LINUX_NET_TSTAMP_H
220 #include <linux/net_tstamp.h>
221 #endif
222 
223 /*
224  * Got Wireless Extensions?
225  */
226 #ifdef HAVE_LINUX_WIRELESS_H
227 #include <linux/wireless.h>
228 #endif /* HAVE_LINUX_WIRELESS_H */
229 
230 /*
231  * Got libnl?
232  */
233 #ifdef HAVE_LIBNL
234 #include <linux/nl80211.h>
235 
236 #include <netlink/genl/genl.h>
237 #include <netlink/genl/family.h>
238 #include <netlink/genl/ctrl.h>
239 #include <netlink/msg.h>
240 #include <netlink/attr.h>
241 #endif /* HAVE_LIBNL */
242 
243 /*
244  * Got ethtool support?
245  */
246 #ifdef HAVE_LINUX_ETHTOOL_H
247 #include <linux/ethtool.h>
248 #endif
249 
250 #ifndef HAVE_SOCKLEN_T
251 typedef int		socklen_t;
252 #endif
253 
254 #ifndef MSG_TRUNC
255 /*
256  * This is being compiled on a system that lacks MSG_TRUNC; define it
257  * with the value it has in the 2.2 and later kernels, so that, on
258  * those kernels, when we pass it in the flags argument to "recvfrom()"
259  * we're passing the right value and thus get the MSG_TRUNC behavior
260  * we want.  (We don't get that behavior on 2.0[.x] kernels, because
261  * they didn't support MSG_TRUNC.)
262  */
263 #define MSG_TRUNC	0x20
264 #endif
265 
266 #ifndef SOL_PACKET
267 /*
268  * This is being compiled on a system that lacks SOL_PACKET; define it
269  * with the value it has in the 2.2 and later kernels, so that we can
270  * set promiscuous mode in the good modern way rather than the old
271  * 2.0-kernel crappy way.
272  */
273 #define SOL_PACKET	263
274 #endif
275 
276 #define MAX_LINKHEADER_SIZE	256
277 
278 /*
279  * When capturing on all interfaces we use this as the buffer size.
280  * Should be bigger then all MTUs that occur in real life.
281  * 64kB should be enough for now.
282  */
283 #define BIGGER_THAN_ALL_MTUS	(64*1024)
284 
285 /*
286  * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
287  */
288 struct pcap_linux {
289 	u_int	packets_read;	/* count of packets read with recvfrom() */
290 	long	proc_dropped;	/* packets reported dropped by /proc/net/dev */
291 	struct pcap_stat stat;
292 
293 	char	*device;	/* device name */
294 	int	filter_in_userland; /* must filter in userland */
295 	int	blocks_to_filter_in_userland;
296 	int	must_do_on_close; /* stuff we must do when we close */
297 	int	timeout;	/* timeout for buffering */
298 	int	sock_packet;	/* using Linux 2.0 compatible interface */
299 	int	cooked;		/* using SOCK_DGRAM rather than SOCK_RAW */
300 	int	ifindex;	/* interface index of device we're bound to */
301 	int	lo_ifindex;	/* interface index of the loopback device */
302 	bpf_u_int32 oldmode;	/* mode to restore when turning monitor mode off */
303 	char	*mondevice;	/* mac80211 monitor device we created */
304 	u_char	*mmapbuf;	/* memory-mapped region pointer */
305 	size_t	mmapbuflen;	/* size of region */
306 	int	vlan_offset;	/* offset at which to insert vlan tags; if -1, don't insert */
307 	u_int	tp_version;	/* version of tpacket_hdr for mmaped ring */
308 	u_int	tp_hdrlen;	/* hdrlen of tpacket_hdr for mmaped ring */
309 	u_char	*oneshot_buffer; /* buffer for copy of packet */
310 #ifdef HAVE_TPACKET3
311 	unsigned char *current_packet; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
312 	int packets_left; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
313 #endif
314 };
315 
316 /*
317  * Stuff to do when we close.
318  */
319 #define MUST_CLEAR_PROMISC	0x00000001	/* clear promiscuous mode */
320 #define MUST_CLEAR_RFMON	0x00000002	/* clear rfmon (monitor) mode */
321 #define MUST_DELETE_MONIF	0x00000004	/* delete monitor-mode interface */
322 
323 /*
324  * Prototypes for internal functions and methods.
325  */
326 static void map_arphrd_to_dlt(pcap_t *, int, int, const char *, int);
327 #ifdef HAVE_PF_PACKET_SOCKETS
328 static short int map_packet_type_to_sll_type(short int);
329 #endif
330 static int pcap_activate_linux(pcap_t *);
331 static int activate_old(pcap_t *);
332 static int activate_new(pcap_t *);
333 static int activate_mmap(pcap_t *, int *);
334 static int pcap_can_set_rfmon_linux(pcap_t *);
335 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
336 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
337 static int pcap_inject_linux(pcap_t *, const void *, size_t);
338 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
339 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
340 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
341 static int pcap_set_datalink_linux(pcap_t *, int);
342 static void pcap_cleanup_linux(pcap_t *);
343 
344 /*
345  * This is what the header structure looks like in a 64-bit kernel;
346  * we use this, rather than struct tpacket_hdr, if we're using
347  * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
348  */
349 struct tpacket_hdr_64 {
350 	uint64_t	tp_status;
351 	unsigned int	tp_len;
352 	unsigned int	tp_snaplen;
353 	unsigned short	tp_mac;
354 	unsigned short	tp_net;
355 	unsigned int	tp_sec;
356 	unsigned int	tp_usec;
357 };
358 
359 /*
360  * We use this internally as the tpacket version for TPACKET_V1 in
361  * 32-bit code on a 64-bit kernel.
362  */
363 #define TPACKET_V1_64 99
364 
365 union thdr {
366 	struct tpacket_hdr		*h1;
367 	struct tpacket_hdr_64		*h1_64;
368 #ifdef HAVE_TPACKET2
369 	struct tpacket2_hdr		*h2;
370 #endif
371 #ifdef HAVE_TPACKET3
372 	struct tpacket_block_desc	*h3;
373 #endif
374 	void				*raw;
375 };
376 
377 #ifdef HAVE_PACKET_RING
378 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
379 
380 static void destroy_ring(pcap_t *handle);
381 static int create_ring(pcap_t *handle, int *status);
382 static int prepare_tpacket_socket(pcap_t *handle);
383 static void pcap_cleanup_linux_mmap(pcap_t *);
384 static int pcap_read_linux_mmap_v1(pcap_t *, int, pcap_handler , u_char *);
385 static int pcap_read_linux_mmap_v1_64(pcap_t *, int, pcap_handler , u_char *);
386 #ifdef HAVE_TPACKET2
387 static int pcap_read_linux_mmap_v2(pcap_t *, int, pcap_handler , u_char *);
388 #endif
389 #ifdef HAVE_TPACKET3
390 static int pcap_read_linux_mmap_v3(pcap_t *, int, pcap_handler , u_char *);
391 #endif
392 static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
393 static int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
394 static int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
395 static void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
396     const u_char *bytes);
397 #endif
398 
399 #ifdef TP_STATUS_VLAN_TPID_VALID
400 # define VLAN_TPID(hdr, hv)	(((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
401 #else
402 # define VLAN_TPID(hdr, hv)	ETH_P_8021Q
403 #endif
404 
405 /*
406  * Wrap some ioctl calls
407  */
408 #ifdef HAVE_PF_PACKET_SOCKETS
409 static int	iface_get_id(int fd, const char *device, char *ebuf);
410 #endif /* HAVE_PF_PACKET_SOCKETS */
411 static int	iface_get_mtu(int fd, const char *device, char *ebuf);
412 static int 	iface_get_arptype(int fd, const char *device, char *ebuf);
413 #ifdef HAVE_PF_PACKET_SOCKETS
414 static int 	iface_bind(int fd, int ifindex, char *ebuf);
415 #ifdef IW_MODE_MONITOR
416 static int	has_wext(int sock_fd, const char *device, char *ebuf);
417 #endif /* IW_MODE_MONITOR */
418 static int	enter_rfmon_mode(pcap_t *handle, int sock_fd,
419     const char *device);
420 #endif /* HAVE_PF_PACKET_SOCKETS */
421 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
422 static int	iface_ethtool_get_ts_info(pcap_t *handle, char *ebuf);
423 #endif
424 #ifdef HAVE_PACKET_RING
425 static int	iface_get_offload(pcap_t *handle);
426 #endif
427 static int 	iface_bind_old(int fd, const char *device, char *ebuf);
428 
429 #ifdef SO_ATTACH_FILTER
430 static int	fix_program(pcap_t *handle, struct sock_fprog *fcode,
431     int is_mapped);
432 static int	fix_offset(struct bpf_insn *p);
433 static int	set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
434 static int	reset_kernel_filter(pcap_t *handle);
435 
436 static struct sock_filter	total_insn
437 	= BPF_STMT(BPF_RET | BPF_K, 0);
438 static struct sock_fprog	total_fcode
439 	= { 1, &total_insn };
440 #endif /* SO_ATTACH_FILTER */
441 
442 pcap_t *
pcap_create_interface(const char * device,char * ebuf)443 pcap_create_interface(const char *device, char *ebuf)
444 {
445 	pcap_t *handle;
446 
447 	handle = pcap_create_common(device, ebuf, sizeof (struct pcap_linux));
448 	if (handle == NULL)
449 		return NULL;
450 
451 	handle->activate_op = pcap_activate_linux;
452 	handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
453 
454 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
455 	/*
456 	 * See what time stamp types we support.
457 	 */
458 	if (iface_ethtool_get_ts_info(handle, ebuf) == -1) {
459 		free(handle);
460 		return NULL;
461 	}
462 #endif
463 
464 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
465 	/*
466 	 * We claim that we support microsecond and nanosecond time
467 	 * stamps.
468 	 *
469 	 * XXX - with adapter-supplied time stamps, can we choose
470 	 * microsecond or nanosecond time stamps on arbitrary
471 	 * adapters?
472 	 */
473 	handle->tstamp_precision_count = 2;
474 	handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
475 	if (handle->tstamp_precision_list == NULL) {
476 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
477 		    pcap_strerror(errno));
478 		if (handle->tstamp_type_list != NULL)
479 			free(handle->tstamp_type_list);
480 		free(handle);
481 		return NULL;
482 	}
483 	handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
484 	handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
485 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
486 
487 	return handle;
488 }
489 
490 #ifdef HAVE_LIBNL
491 /*
492  * If interface {if} is a mac80211 driver, the file
493  * /sys/class/net/{if}/phy80211 is a symlink to
494  * /sys/class/ieee80211/{phydev}, for some {phydev}.
495  *
496  * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
497  * least, has a "wmaster0" device and a "wlan0" device; the
498  * latter is the one with the IP address.  Both show up in
499  * "tcpdump -D" output.  Capturing on the wmaster0 device
500  * captures with 802.11 headers.
501  *
502  * airmon-ng searches through /sys/class/net for devices named
503  * monN, starting with mon0; as soon as one *doesn't* exist,
504  * it chooses that as the monitor device name.  If the "iw"
505  * command exists, it does "iw dev {if} interface add {monif}
506  * type monitor", where {monif} is the monitor device.  It
507  * then (sigh) sleeps .1 second, and then configures the
508  * device up.  Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
509  * is a file, it writes {mondev}, without a newline, to that file,
510  * and again (sigh) sleeps .1 second, and then iwconfig's that
511  * device into monitor mode and configures it up.  Otherwise,
512  * you can't do monitor mode.
513  *
514  * All these devices are "glued" together by having the
515  * /sys/class/net/{device}/phy80211 links pointing to the same
516  * place, so, given a wmaster, wlan, or mon device, you can
517  * find the other devices by looking for devices with
518  * the same phy80211 link.
519  *
520  * To turn monitor mode off, delete the monitor interface,
521  * either with "iw dev {monif} interface del" or by sending
522  * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
523  *
524  * Note: if you try to create a monitor device named "monN", and
525  * there's already a "monN" device, it fails, as least with
526  * the netlink interface (which is what iw uses), with a return
527  * value of -ENFILE.  (Return values are negative errnos.)  We
528  * could probably use that to find an unused device.
529  *
530  * Yes, you can have multiple monitor devices for a given
531  * physical device.
532 */
533 
534 /*
535  * Is this a mac80211 device?  If so, fill in the physical device path and
536  * return 1; if not, return 0.  On an error, fill in handle->errbuf and
537  * return PCAP_ERROR.
538  */
539 static int
get_mac80211_phydev(pcap_t * handle,const char * device,char * phydev_path,size_t phydev_max_pathlen)540 get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
541     size_t phydev_max_pathlen)
542 {
543 	char *pathstr;
544 	ssize_t bytes_read;
545 
546 	/*
547 	 * Generate the path string for the symlink to the physical device.
548 	 */
549 	if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
550 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
551 		    "%s: Can't generate path name string for /sys/class/net device",
552 		    device);
553 		return PCAP_ERROR;
554 	}
555 	bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
556 	if (bytes_read == -1) {
557 		if (errno == ENOENT || errno == EINVAL) {
558 			/*
559 			 * Doesn't exist, or not a symlink; assume that
560 			 * means it's not a mac80211 device.
561 			 */
562 			free(pathstr);
563 			return 0;
564 		}
565 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
566 		    "%s: Can't readlink %s: %s", device, pathstr,
567 		    strerror(errno));
568 		free(pathstr);
569 		return PCAP_ERROR;
570 	}
571 	free(pathstr);
572 	phydev_path[bytes_read] = '\0';
573 	return 1;
574 }
575 
576 #ifdef HAVE_LIBNL_SOCKETS
577 #define get_nl_errmsg	nl_geterror
578 #else
579 /* libnl 2.x compatibility code */
580 
581 #define nl_sock nl_handle
582 
583 static inline struct nl_handle *
nl_socket_alloc(void)584 nl_socket_alloc(void)
585 {
586 	return nl_handle_alloc();
587 }
588 
589 static inline void
nl_socket_free(struct nl_handle * h)590 nl_socket_free(struct nl_handle *h)
591 {
592 	nl_handle_destroy(h);
593 }
594 
595 #define get_nl_errmsg	strerror
596 
597 static inline int
__genl_ctrl_alloc_cache(struct nl_handle * h,struct nl_cache ** cache)598 __genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
599 {
600 	struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
601 	if (!tmp)
602 		return -ENOMEM;
603 	*cache = tmp;
604 	return 0;
605 }
606 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
607 #endif /* !HAVE_LIBNL_SOCKETS */
608 
609 struct nl80211_state {
610 	struct nl_sock *nl_sock;
611 	struct nl_cache *nl_cache;
612 	struct genl_family *nl80211;
613 };
614 
615 static int
nl80211_init(pcap_t * handle,struct nl80211_state * state,const char * device)616 nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
617 {
618 	int err;
619 
620 	state->nl_sock = nl_socket_alloc();
621 	if (!state->nl_sock) {
622 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
623 		    "%s: failed to allocate netlink handle", device);
624 		return PCAP_ERROR;
625 	}
626 
627 	if (genl_connect(state->nl_sock)) {
628 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
629 		    "%s: failed to connect to generic netlink", device);
630 		goto out_handle_destroy;
631 	}
632 
633 	err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
634 	if (err < 0) {
635 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
636 		    "%s: failed to allocate generic netlink cache: %s",
637 		    device, get_nl_errmsg(-err));
638 		goto out_handle_destroy;
639 	}
640 
641 	state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
642 	if (!state->nl80211) {
643 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
644 		    "%s: nl80211 not found", device);
645 		goto out_cache_free;
646 	}
647 
648 	return 0;
649 
650 out_cache_free:
651 	nl_cache_free(state->nl_cache);
652 out_handle_destroy:
653 	nl_socket_free(state->nl_sock);
654 	return PCAP_ERROR;
655 }
656 
657 static void
nl80211_cleanup(struct nl80211_state * state)658 nl80211_cleanup(struct nl80211_state *state)
659 {
660 	genl_family_put(state->nl80211);
661 	nl_cache_free(state->nl_cache);
662 	nl_socket_free(state->nl_sock);
663 }
664 
665 static int
add_mon_if(pcap_t * handle,int sock_fd,struct nl80211_state * state,const char * device,const char * mondevice)666 add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
667     const char *device, const char *mondevice)
668 {
669 	int ifindex;
670 	struct nl_msg *msg;
671 	int err;
672 
673 	ifindex = iface_get_id(sock_fd, device, handle->errbuf);
674 	if (ifindex == -1)
675 		return PCAP_ERROR;
676 
677 	msg = nlmsg_alloc();
678 	if (!msg) {
679 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
680 		    "%s: failed to allocate netlink msg", device);
681 		return PCAP_ERROR;
682 	}
683 
684 	genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
685 		    0, NL80211_CMD_NEW_INTERFACE, 0);
686 	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
687 	NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
688 	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
689 
690 	err = nl_send_auto_complete(state->nl_sock, msg);
691 	if (err < 0) {
692 #if defined HAVE_LIBNL_NLE
693 		if (err == -NLE_FAILURE) {
694 #else
695 		if (err == -ENFILE) {
696 #endif
697 			/*
698 			 * Device not available; our caller should just
699 			 * keep trying.  (libnl 2.x maps ENFILE to
700 			 * NLE_FAILURE; it can also map other errors
701 			 * to that, but there's not much we can do
702 			 * about that.)
703 			 */
704 			nlmsg_free(msg);
705 			return 0;
706 		} else {
707 			/*
708 			 * Real failure, not just "that device is not
709 			 * available.
710 			 */
711 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
712 			    "%s: nl_send_auto_complete failed adding %s interface: %s",
713 			    device, mondevice, get_nl_errmsg(-err));
714 			nlmsg_free(msg);
715 			return PCAP_ERROR;
716 		}
717 	}
718 	err = nl_wait_for_ack(state->nl_sock);
719 	if (err < 0) {
720 #if defined HAVE_LIBNL_NLE
721 		if (err == -NLE_FAILURE) {
722 #else
723 		if (err == -ENFILE) {
724 #endif
725 			/*
726 			 * Device not available; our caller should just
727 			 * keep trying.  (libnl 2.x maps ENFILE to
728 			 * NLE_FAILURE; it can also map other errors
729 			 * to that, but there's not much we can do
730 			 * about that.)
731 			 */
732 			nlmsg_free(msg);
733 			return 0;
734 		} else {
735 			/*
736 			 * Real failure, not just "that device is not
737 			 * available.
738 			 */
739 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
740 			    "%s: nl_wait_for_ack failed adding %s interface: %s",
741 			    device, mondevice, get_nl_errmsg(-err));
742 			nlmsg_free(msg);
743 			return PCAP_ERROR;
744 		}
745 	}
746 
747 	/*
748 	 * Success.
749 	 */
750 	nlmsg_free(msg);
751 	return 1;
752 
753 nla_put_failure:
754 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
755 	    "%s: nl_put failed adding %s interface",
756 	    device, mondevice);
757 	nlmsg_free(msg);
758 	return PCAP_ERROR;
759 }
760 
761 static int
762 del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
763     const char *device, const char *mondevice)
764 {
765 	int ifindex;
766 	struct nl_msg *msg;
767 	int err;
768 
769 	ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
770 	if (ifindex == -1)
771 		return PCAP_ERROR;
772 
773 	msg = nlmsg_alloc();
774 	if (!msg) {
775 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
776 		    "%s: failed to allocate netlink msg", device);
777 		return PCAP_ERROR;
778 	}
779 
780 	genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
781 		    0, NL80211_CMD_DEL_INTERFACE, 0);
782 	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
783 
784 	err = nl_send_auto_complete(state->nl_sock, msg);
785 	if (err < 0) {
786 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
787 		    "%s: nl_send_auto_complete failed deleting %s interface: %s",
788 		    device, mondevice, get_nl_errmsg(-err));
789 		nlmsg_free(msg);
790 		return PCAP_ERROR;
791 	}
792 	err = nl_wait_for_ack(state->nl_sock);
793 	if (err < 0) {
794 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
795 		    "%s: nl_wait_for_ack failed adding %s interface: %s",
796 		    device, mondevice, get_nl_errmsg(-err));
797 		nlmsg_free(msg);
798 		return PCAP_ERROR;
799 	}
800 
801 	/*
802 	 * Success.
803 	 */
804 	nlmsg_free(msg);
805 	return 1;
806 
807 nla_put_failure:
808 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
809 	    "%s: nl_put failed deleting %s interface",
810 	    device, mondevice);
811 	nlmsg_free(msg);
812 	return PCAP_ERROR;
813 }
814 
815 static int
816 enter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
817 {
818 	struct pcap_linux *handlep = handle->priv;
819 	int ret;
820 	char phydev_path[PATH_MAX+1];
821 	struct nl80211_state nlstate;
822 	struct ifreq ifr;
823 	u_int n;
824 
825 	/*
826 	 * Is this a mac80211 device?
827 	 */
828 	ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
829 	if (ret < 0)
830 		return ret;	/* error */
831 	if (ret == 0)
832 		return 0;	/* no error, but not mac80211 device */
833 
834 	/*
835 	 * XXX - is this already a monN device?
836 	 * If so, we're done.
837 	 * Is that determined by old Wireless Extensions ioctls?
838 	 */
839 
840 	/*
841 	 * OK, it's apparently a mac80211 device.
842 	 * Try to find an unused monN device for it.
843 	 */
844 	ret = nl80211_init(handle, &nlstate, device);
845 	if (ret != 0)
846 		return ret;
847 	for (n = 0; n < UINT_MAX; n++) {
848 		/*
849 		 * Try mon{n}.
850 		 */
851 		char mondevice[3+10+1];	/* mon{UINT_MAX}\0 */
852 
853 		snprintf(mondevice, sizeof mondevice, "mon%u", n);
854 		ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
855 		if (ret == 1) {
856 			handlep->mondevice = strdup(mondevice);
857 			goto added;
858 		}
859 		if (ret < 0) {
860 			/*
861 			 * Hard failure.  Just return ret; handle->errbuf
862 			 * has already been set.
863 			 */
864 			nl80211_cleanup(&nlstate);
865 			return ret;
866 		}
867 	}
868 
869 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
870 	    "%s: No free monN interfaces", device);
871 	nl80211_cleanup(&nlstate);
872 	return PCAP_ERROR;
873 
874 added:
875 
876 #if 0
877 	/*
878 	 * Sleep for .1 seconds.
879 	 */
880 	delay.tv_sec = 0;
881 	delay.tv_nsec = 500000000;
882 	nanosleep(&delay, NULL);
883 #endif
884 
885 	/*
886 	 * If we haven't already done so, arrange to have
887 	 * "pcap_close_all()" called when we exit.
888 	 */
889 	if (!pcap_do_addexit(handle)) {
890 		/*
891 		 * "atexit()" failed; don't put the interface
892 		 * in rfmon mode, just give up.
893 		 */
894 		return PCAP_ERROR_RFMON_NOTSUP;
895 	}
896 
897 	/*
898 	 * Now configure the monitor interface up.
899 	 */
900 	memset(&ifr, 0, sizeof(ifr));
901 	strlcpy(ifr.ifr_name, handlep->mondevice, sizeof(ifr.ifr_name));
902 	if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
903 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
904 		    "%s: Can't get flags for %s: %s", device,
905 		    handlep->mondevice, strerror(errno));
906 		del_mon_if(handle, sock_fd, &nlstate, device,
907 		    handlep->mondevice);
908 		nl80211_cleanup(&nlstate);
909 		return PCAP_ERROR;
910 	}
911 	ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
912 	if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
913 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
914 		    "%s: Can't set flags for %s: %s", device,
915 		    handlep->mondevice, strerror(errno));
916 		del_mon_if(handle, sock_fd, &nlstate, device,
917 		    handlep->mondevice);
918 		nl80211_cleanup(&nlstate);
919 		return PCAP_ERROR;
920 	}
921 
922 	/*
923 	 * Success.  Clean up the libnl state.
924 	 */
925 	nl80211_cleanup(&nlstate);
926 
927 	/*
928 	 * Note that we have to delete the monitor device when we close
929 	 * the handle.
930 	 */
931 	handlep->must_do_on_close |= MUST_DELETE_MONIF;
932 
933 	/*
934 	 * Add this to the list of pcaps to close when we exit.
935 	 */
936 	pcap_add_to_pcaps_to_close(handle);
937 
938 	return 1;
939 }
940 #endif /* HAVE_LIBNL */
941 
942 static int
943 pcap_can_set_rfmon_linux(pcap_t *handle)
944 {
945 #ifdef HAVE_LIBNL
946 	char phydev_path[PATH_MAX+1];
947 	int ret;
948 #endif
949 #ifdef IW_MODE_MONITOR
950 	int sock_fd;
951 	struct iwreq ireq;
952 #endif
953 
954 	if (strcmp(handle->opt.source, "any") == 0) {
955 		/*
956 		 * Monitor mode makes no sense on the "any" device.
957 		 */
958 		return 0;
959 	}
960 
961 #ifdef HAVE_LIBNL
962 	/*
963 	 * Bleah.  There doesn't seem to be a way to ask a mac80211
964 	 * device, through libnl, whether it supports monitor mode;
965 	 * we'll just check whether the device appears to be a
966 	 * mac80211 device and, if so, assume the device supports
967 	 * monitor mode.
968 	 *
969 	 * wmaster devices don't appear to support the Wireless
970 	 * Extensions, but we can create a mon device for a
971 	 * wmaster device, so we don't bother checking whether
972 	 * a mac80211 device supports the Wireless Extensions.
973 	 */
974 	ret = get_mac80211_phydev(handle, handle->opt.source, phydev_path,
975 	    PATH_MAX);
976 	if (ret < 0)
977 		return ret;	/* error */
978 	if (ret == 1)
979 		return 1;	/* mac80211 device */
980 #endif
981 
982 #ifdef IW_MODE_MONITOR
983 	/*
984 	 * Bleah.  There doesn't appear to be an ioctl to use to ask
985 	 * whether a device supports monitor mode; we'll just do
986 	 * SIOCGIWMODE and, if it succeeds, assume the device supports
987 	 * monitor mode.
988 	 *
989 	 * Open a socket on which to attempt to get the mode.
990 	 * (We assume that if we have Wireless Extensions support
991 	 * we also have PF_PACKET support.)
992 	 */
993 	sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
994 	if (sock_fd == -1) {
995 		(void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
996 		    "socket: %s", pcap_strerror(errno));
997 		return PCAP_ERROR;
998 	}
999 
1000 	/*
1001 	 * Attempt to get the current mode.
1002 	 */
1003 	strlcpy(ireq.ifr_ifrn.ifrn_name, handle->opt.source,
1004 	    sizeof ireq.ifr_ifrn.ifrn_name);
1005 	if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
1006 		/*
1007 		 * Well, we got the mode; assume we can set it.
1008 		 */
1009 		close(sock_fd);
1010 		return 1;
1011 	}
1012 	if (errno == ENODEV) {
1013 		/* The device doesn't even exist. */
1014 		(void)snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1015 		    "SIOCGIWMODE failed: %s", pcap_strerror(errno));
1016 		close(sock_fd);
1017 		return PCAP_ERROR_NO_SUCH_DEVICE;
1018 	}
1019 	close(sock_fd);
1020 #endif
1021 	return 0;
1022 }
1023 
1024 /*
1025  * Grabs the number of dropped packets by the interface from /proc/net/dev.
1026  *
1027  * XXX - what about /sys/class/net/{interface name}/rx_*?  There are
1028  * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1029  *
1030  * Or can we get them in binary form from netlink?
1031  */
1032 static long int
1033 linux_if_drops(const char * if_name)
1034 {
1035 	char buffer[512];
1036 	char * bufptr;
1037 	FILE * file;
1038 	int field_to_convert = 3, if_name_sz = strlen(if_name);
1039 	long int dropped_pkts = 0;
1040 
1041 	file = fopen("/proc/net/dev", "r");
1042 	if (!file)
1043 		return 0;
1044 
1045 	while (!dropped_pkts && fgets( buffer, sizeof(buffer), file ))
1046 	{
1047 		/* 	search for 'bytes' -- if its in there, then
1048 			that means we need to grab the fourth field. otherwise
1049 			grab the third field. */
1050 		if (field_to_convert != 4 && strstr(buffer, "bytes"))
1051 		{
1052 			field_to_convert = 4;
1053 			continue;
1054 		}
1055 
1056 		/* find iface and make sure it actually matches -- space before the name and : after it */
1057 		if ((bufptr = strstr(buffer, if_name)) &&
1058 			(bufptr == buffer || *(bufptr-1) == ' ') &&
1059 			*(bufptr + if_name_sz) == ':')
1060 		{
1061 			bufptr = bufptr + if_name_sz + 1;
1062 
1063 			/* grab the nth field from it */
1064 			while( --field_to_convert && *bufptr != '\0')
1065 			{
1066 				while (*bufptr != '\0' && *(bufptr++) == ' ');
1067 				while (*bufptr != '\0' && *(bufptr++) != ' ');
1068 			}
1069 
1070 			/* get rid of any final spaces */
1071 			while (*bufptr != '\0' && *bufptr == ' ') bufptr++;
1072 
1073 			if (*bufptr != '\0')
1074 				dropped_pkts = strtol(bufptr, NULL, 10);
1075 
1076 			break;
1077 		}
1078 	}
1079 
1080 	fclose(file);
1081 	return dropped_pkts;
1082 }
1083 
1084 
1085 /*
1086  * With older kernels promiscuous mode is kind of interesting because we
1087  * have to reset the interface before exiting. The problem can't really
1088  * be solved without some daemon taking care of managing usage counts.
1089  * If we put the interface into promiscuous mode, we set a flag indicating
1090  * that we must take it out of that mode when the interface is closed,
1091  * and, when closing the interface, if that flag is set we take it out
1092  * of promiscuous mode.
1093  *
1094  * Even with newer kernels, we have the same issue with rfmon mode.
1095  */
1096 
1097 static void	pcap_cleanup_linux( pcap_t *handle )
1098 {
1099 	struct pcap_linux *handlep = handle->priv;
1100 	struct ifreq	ifr;
1101 #ifdef HAVE_LIBNL
1102 	struct nl80211_state nlstate;
1103 	int ret;
1104 #endif /* HAVE_LIBNL */
1105 #ifdef IW_MODE_MONITOR
1106 	int oldflags;
1107 	struct iwreq ireq;
1108 #endif /* IW_MODE_MONITOR */
1109 
1110 	if (handlep->must_do_on_close != 0) {
1111 		/*
1112 		 * There's something we have to do when closing this
1113 		 * pcap_t.
1114 		 */
1115 		if (handlep->must_do_on_close & MUST_CLEAR_PROMISC) {
1116 			/*
1117 			 * We put the interface into promiscuous mode;
1118 			 * take it out of promiscuous mode.
1119 			 *
1120 			 * XXX - if somebody else wants it in promiscuous
1121 			 * mode, this code cannot know that, so it'll take
1122 			 * it out of promiscuous mode.  That's not fixable
1123 			 * in 2.0[.x] kernels.
1124 			 */
1125 			memset(&ifr, 0, sizeof(ifr));
1126 			strlcpy(ifr.ifr_name, handlep->device,
1127 			    sizeof(ifr.ifr_name));
1128 			if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1129 				fprintf(stderr,
1130 				    "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1131 				    "Please adjust manually.\n"
1132 				    "Hint: This can't happen with Linux >= 2.2.0.\n",
1133 				    handlep->device, strerror(errno));
1134 			} else {
1135 				if (ifr.ifr_flags & IFF_PROMISC) {
1136 					/*
1137 					 * Promiscuous mode is currently on;
1138 					 * turn it off.
1139 					 */
1140 					ifr.ifr_flags &= ~IFF_PROMISC;
1141 					if (ioctl(handle->fd, SIOCSIFFLAGS,
1142 					    &ifr) == -1) {
1143 						fprintf(stderr,
1144 						    "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1145 						    "Please adjust manually.\n"
1146 						    "Hint: This can't happen with Linux >= 2.2.0.\n",
1147 						    handlep->device,
1148 						    strerror(errno));
1149 					}
1150 				}
1151 			}
1152 		}
1153 
1154 #ifdef HAVE_LIBNL
1155 		if (handlep->must_do_on_close & MUST_DELETE_MONIF) {
1156 			ret = nl80211_init(handle, &nlstate, handlep->device);
1157 			if (ret >= 0) {
1158 				ret = del_mon_if(handle, handle->fd, &nlstate,
1159 				    handlep->device, handlep->mondevice);
1160 				nl80211_cleanup(&nlstate);
1161 			}
1162 			if (ret < 0) {
1163 				fprintf(stderr,
1164 				    "Can't delete monitor interface %s (%s).\n"
1165 				    "Please delete manually.\n",
1166 				    handlep->mondevice, handle->errbuf);
1167 			}
1168 		}
1169 #endif /* HAVE_LIBNL */
1170 
1171 #ifdef IW_MODE_MONITOR
1172 		if (handlep->must_do_on_close & MUST_CLEAR_RFMON) {
1173 			/*
1174 			 * We put the interface into rfmon mode;
1175 			 * take it out of rfmon mode.
1176 			 *
1177 			 * XXX - if somebody else wants it in rfmon
1178 			 * mode, this code cannot know that, so it'll take
1179 			 * it out of rfmon mode.
1180 			 */
1181 
1182 			/*
1183 			 * First, take the interface down if it's up;
1184 			 * otherwise, we might get EBUSY.
1185 			 * If we get errors, just drive on and print
1186 			 * a warning if we can't restore the mode.
1187 			 */
1188 			oldflags = 0;
1189 			memset(&ifr, 0, sizeof(ifr));
1190 			strlcpy(ifr.ifr_name, handlep->device,
1191 			    sizeof(ifr.ifr_name));
1192 			if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
1193 				if (ifr.ifr_flags & IFF_UP) {
1194 					oldflags = ifr.ifr_flags;
1195 					ifr.ifr_flags &= ~IFF_UP;
1196 					if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
1197 						oldflags = 0;	/* didn't set, don't restore */
1198 				}
1199 			}
1200 
1201 			/*
1202 			 * Now restore the mode.
1203 			 */
1204 			strlcpy(ireq.ifr_ifrn.ifrn_name, handlep->device,
1205 			    sizeof ireq.ifr_ifrn.ifrn_name);
1206 			ireq.u.mode = handlep->oldmode;
1207 			if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
1208 				/*
1209 				 * Scientist, you've failed.
1210 				 */
1211 				fprintf(stderr,
1212 				    "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1213 				    "Please adjust manually.\n",
1214 				    handlep->device, strerror(errno));
1215 			}
1216 
1217 			/*
1218 			 * Now bring the interface back up if we brought
1219 			 * it down.
1220 			 */
1221 			if (oldflags != 0) {
1222 				ifr.ifr_flags = oldflags;
1223 				if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1224 					fprintf(stderr,
1225 					    "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1226 					    "Please adjust manually.\n",
1227 					    handlep->device, strerror(errno));
1228 				}
1229 			}
1230 		}
1231 #endif /* IW_MODE_MONITOR */
1232 
1233 		/*
1234 		 * Take this pcap out of the list of pcaps for which we
1235 		 * have to take the interface out of some mode.
1236 		 */
1237 		pcap_remove_from_pcaps_to_close(handle);
1238 	}
1239 
1240 	if (handlep->mondevice != NULL) {
1241 		free(handlep->mondevice);
1242 		handlep->mondevice = NULL;
1243 	}
1244 	if (handlep->device != NULL) {
1245 		free(handlep->device);
1246 		handlep->device = NULL;
1247 	}
1248 	pcap_cleanup_live_common(handle);
1249 }
1250 
1251 /*
1252  *  Get a handle for a live capture from the given device. You can
1253  *  pass NULL as device to get all packages (without link level
1254  *  information of course). If you pass 1 as promisc the interface
1255  *  will be set to promiscous mode (XXX: I think this usage should
1256  *  be deprecated and functions be added to select that later allow
1257  *  modification of that values -- Torsten).
1258  */
1259 static int
1260 pcap_activate_linux(pcap_t *handle)
1261 {
1262 	struct pcap_linux *handlep = handle->priv;
1263 	const char	*device;
1264 	struct ifreq	ifr;
1265 	int		status = 0;
1266 	int		ret;
1267 
1268 	device = handle->opt.source;
1269 
1270 	/*
1271 	 * Make sure the name we were handed will fit into the ioctls we
1272 	 * might perform on the device; if not, return a "No such device"
1273 	 * indication, as the Linux kernel shouldn't support creating
1274 	 * a device whose name won't fit into those ioctls.
1275 	 *
1276 	 * "Will fit" means "will fit, complete with a null terminator",
1277 	 * so if the length, which does *not* include the null terminator,
1278 	 * is greater than *or equal to* the size of the field into which
1279 	 * we'll be copying it, that won't fit.
1280 	 */
1281 	if (strlen(device) >= sizeof(ifr.ifr_name)) {
1282 		status = PCAP_ERROR_NO_SUCH_DEVICE;
1283 		goto fail;
1284 	}
1285 
1286 	handle->inject_op = pcap_inject_linux;
1287 	handle->setfilter_op = pcap_setfilter_linux;
1288 	handle->setdirection_op = pcap_setdirection_linux;
1289 	handle->set_datalink_op = pcap_set_datalink_linux;
1290 	handle->getnonblock_op = pcap_getnonblock_fd;
1291 	handle->setnonblock_op = pcap_setnonblock_fd;
1292 	handle->cleanup_op = pcap_cleanup_linux;
1293 	handle->read_op = pcap_read_linux;
1294 	handle->stats_op = pcap_stats_linux;
1295 
1296 	/*
1297 	 * The "any" device is a special device which causes us not
1298 	 * to bind to a particular device and thus to look at all
1299 	 * devices.
1300 	 */
1301 	if (strcmp(device, "any") == 0) {
1302 		if (handle->opt.promisc) {
1303 			handle->opt.promisc = 0;
1304 			/* Just a warning. */
1305 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1306 			    "Promiscuous mode not supported on the \"any\" device");
1307 			status = PCAP_WARNING_PROMISC_NOTSUP;
1308 		}
1309 	}
1310 
1311 	handlep->device	= strdup(device);
1312 	if (handlep->device == NULL) {
1313 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1314 			 pcap_strerror(errno) );
1315 		return PCAP_ERROR;
1316 	}
1317 
1318 	/* copy timeout value */
1319 	handlep->timeout = handle->opt.timeout;
1320 
1321 	/*
1322 	 * If we're in promiscuous mode, then we probably want
1323 	 * to see when the interface drops packets too, so get an
1324 	 * initial count from /proc/net/dev
1325 	 */
1326 	if (handle->opt.promisc)
1327 		handlep->proc_dropped = linux_if_drops(handlep->device);
1328 
1329 	/*
1330 	 * Current Linux kernels use the protocol family PF_PACKET to
1331 	 * allow direct access to all packets on the network while
1332 	 * older kernels had a special socket type SOCK_PACKET to
1333 	 * implement this feature.
1334 	 * While this old implementation is kind of obsolete we need
1335 	 * to be compatible with older kernels for a while so we are
1336 	 * trying both methods with the newer method preferred.
1337 	 */
1338 	ret = activate_new(handle);
1339 	if (ret < 0) {
1340 		/*
1341 		 * Fatal error with the new way; just fail.
1342 		 * ret has the error return; if it's PCAP_ERROR,
1343 		 * handle->errbuf has been set appropriately.
1344 		 */
1345 		status = ret;
1346 		goto fail;
1347 	}
1348 	if (ret == 1) {
1349 		/*
1350 		 * Success.
1351 		 * Try to use memory-mapped access.
1352 		 */
1353 		switch (activate_mmap(handle, &status)) {
1354 
1355 		case 1:
1356 			/*
1357 			 * We succeeded.  status has been
1358 			 * set to the status to return,
1359 			 * which might be 0, or might be
1360 			 * a PCAP_WARNING_ value.
1361 			 */
1362 			return status;
1363 
1364 		case 0:
1365 			/*
1366 			 * Kernel doesn't support it - just continue
1367 			 * with non-memory-mapped access.
1368 			 */
1369 			break;
1370 
1371 		case -1:
1372 			/*
1373 			 * We failed to set up to use it, or the kernel
1374 			 * supports it, but we failed to enable it.
1375 			 * ret has been set to the error status to
1376 			 * return and, if it's PCAP_ERROR, handle->errbuf
1377 			 * contains the error message.
1378 			 */
1379 			status = ret;
1380 			goto fail;
1381 		}
1382 	}
1383 	else if (ret == 0) {
1384 		/* Non-fatal error; try old way */
1385 		if ((ret = activate_old(handle)) != 1) {
1386 			/*
1387 			 * Both methods to open the packet socket failed.
1388 			 * Tidy up and report our failure (handle->errbuf
1389 			 * is expected to be set by the functions above).
1390 			 */
1391 			status = ret;
1392 			goto fail;
1393 		}
1394 	}
1395 
1396 	/*
1397 	 * We set up the socket, but not with memory-mapped access.
1398 	 */
1399 	if (handle->opt.buffer_size != 0) {
1400 		/*
1401 		 * Set the socket buffer size to the specified value.
1402 		 */
1403 		if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
1404 		    &handle->opt.buffer_size,
1405 		    sizeof(handle->opt.buffer_size)) == -1) {
1406 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1407 				 "SO_RCVBUF: %s", pcap_strerror(errno));
1408 			status = PCAP_ERROR;
1409 			goto fail;
1410 		}
1411 	}
1412 
1413 	/* Allocate the buffer */
1414 
1415 	handle->buffer	 = malloc(handle->bufsize + handle->offset);
1416 	if (!handle->buffer) {
1417 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1418 			 "malloc: %s", pcap_strerror(errno));
1419 		status = PCAP_ERROR;
1420 		goto fail;
1421 	}
1422 
1423 	/*
1424 	 * "handle->fd" is a socket, so "select()" and "poll()"
1425 	 * should work on it.
1426 	 */
1427 	handle->selectable_fd = handle->fd;
1428 
1429 	return status;
1430 
1431 fail:
1432 	pcap_cleanup_linux(handle);
1433 	return status;
1434 }
1435 
1436 /*
1437  *  Read at most max_packets from the capture stream and call the callback
1438  *  for each of them. Returns the number of packets handled or -1 if an
1439  *  error occured.
1440  */
1441 static int
1442 pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
1443 {
1444 	/*
1445 	 * Currently, on Linux only one packet is delivered per read,
1446 	 * so we don't loop.
1447 	 */
1448 	return pcap_read_packet(handle, callback, user);
1449 }
1450 
1451 static int
1452 pcap_set_datalink_linux(pcap_t *handle, int dlt)
1453 {
1454 	handle->linktype = dlt;
1455 	return 0;
1456 }
1457 
1458 /*
1459  * linux_check_direction()
1460  *
1461  * Do checks based on packet direction.
1462  */
1463 static inline int
1464 linux_check_direction(const pcap_t *handle, const struct sockaddr_ll *sll)
1465 {
1466 	struct pcap_linux	*handlep = handle->priv;
1467 
1468 	if (sll->sll_pkttype == PACKET_OUTGOING) {
1469 		/*
1470 		 * Outgoing packet.
1471 		 * If this is from the loopback device, reject it;
1472 		 * we'll see the packet as an incoming packet as well,
1473 		 * and we don't want to see it twice.
1474 		 */
1475 		if (sll->sll_ifindex == handlep->lo_ifindex)
1476 			return 0;
1477 
1478 		/*
1479 		 * If the user only wants incoming packets, reject it.
1480 		 */
1481 		if (handle->direction == PCAP_D_IN)
1482 			return 0;
1483 	} else {
1484 		/*
1485 		 * Incoming packet.
1486 		 * If the user only wants outgoing packets, reject it.
1487 		 */
1488 		if (handle->direction == PCAP_D_OUT)
1489 			return 0;
1490 	}
1491 	return 1;
1492 }
1493 
1494 /*
1495  *  Read a packet from the socket calling the handler provided by
1496  *  the user. Returns the number of packets received or -1 if an
1497  *  error occured.
1498  */
1499 static int
1500 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
1501 {
1502 	struct pcap_linux	*handlep = handle->priv;
1503 	u_char			*bp;
1504 	int			offset;
1505 #ifdef HAVE_PF_PACKET_SOCKETS
1506 	struct sockaddr_ll	from;
1507 	struct sll_header	*hdrp;
1508 #else
1509 	struct sockaddr		from;
1510 #endif
1511 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1512 	struct iovec		iov;
1513 	struct msghdr		msg;
1514 	struct cmsghdr		*cmsg;
1515 	union {
1516 		struct cmsghdr	cmsg;
1517 		char		buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
1518 	} cmsg_buf;
1519 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1520 	socklen_t		fromlen;
1521 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1522 	int			packet_len, caplen;
1523 	struct pcap_pkthdr	pcap_header;
1524 
1525         struct bpf_aux_data     aux_data;
1526 #ifdef HAVE_PF_PACKET_SOCKETS
1527 	/*
1528 	 * If this is a cooked device, leave extra room for a
1529 	 * fake packet header.
1530 	 */
1531 	if (handlep->cooked)
1532 		offset = SLL_HDR_LEN;
1533 	else
1534 		offset = 0;
1535 #else
1536 	/*
1537 	 * This system doesn't have PF_PACKET sockets, so it doesn't
1538 	 * support cooked devices.
1539 	 */
1540 	offset = 0;
1541 #endif
1542 
1543 	/*
1544 	 * Receive a single packet from the kernel.
1545 	 * We ignore EINTR, as that might just be due to a signal
1546 	 * being delivered - if the signal should interrupt the
1547 	 * loop, the signal handler should call pcap_breakloop()
1548 	 * to set handle->break_loop (we ignore it on other
1549 	 * platforms as well).
1550 	 * We also ignore ENETDOWN, so that we can continue to
1551 	 * capture traffic if the interface goes down and comes
1552 	 * back up again; comments in the kernel indicate that
1553 	 * we'll just block waiting for packets if we try to
1554 	 * receive from a socket that delivered ENETDOWN, and,
1555 	 * if we're using a memory-mapped buffer, we won't even
1556 	 * get notified of "network down" events.
1557 	 */
1558 	bp = handle->buffer + handle->offset;
1559 
1560 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1561 	msg.msg_name		= &from;
1562 	msg.msg_namelen		= sizeof(from);
1563 	msg.msg_iov		= &iov;
1564 	msg.msg_iovlen		= 1;
1565 	msg.msg_control		= &cmsg_buf;
1566 	msg.msg_controllen	= sizeof(cmsg_buf);
1567 	msg.msg_flags		= 0;
1568 
1569 	iov.iov_len		= handle->bufsize - offset;
1570 	iov.iov_base		= bp + offset;
1571 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1572 
1573 	do {
1574 		/*
1575 		 * Has "pcap_breakloop()" been called?
1576 		 */
1577 		if (handle->break_loop) {
1578 			/*
1579 			 * Yes - clear the flag that indicates that it has,
1580 			 * and return PCAP_ERROR_BREAK as an indication that
1581 			 * we were told to break out of the loop.
1582 			 */
1583 			handle->break_loop = 0;
1584 			return PCAP_ERROR_BREAK;
1585 		}
1586 
1587 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1588 		packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
1589 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1590 		fromlen = sizeof(from);
1591 		packet_len = recvfrom(
1592 			handle->fd, bp + offset,
1593 			handle->bufsize - offset, MSG_TRUNC,
1594 			(struct sockaddr *) &from, &fromlen);
1595 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1596 	} while (packet_len == -1 && errno == EINTR);
1597 
1598 	/* Check if an error occured */
1599 
1600 	if (packet_len == -1) {
1601 		switch (errno) {
1602 
1603 		case EAGAIN:
1604 			return 0;	/* no packet there */
1605 
1606 		case ENETDOWN:
1607 			/*
1608 			 * The device on which we're capturing went away.
1609 			 *
1610 			 * XXX - we should really return
1611 			 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
1612 			 * etc. aren't defined to return that.
1613 			 */
1614 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1615 				"The interface went down");
1616 			return PCAP_ERROR;
1617 
1618 		default:
1619 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1620 				 "recvfrom: %s", pcap_strerror(errno));
1621 			return PCAP_ERROR;
1622 		}
1623 	}
1624 
1625 #ifdef HAVE_PF_PACKET_SOCKETS
1626 	if (!handlep->sock_packet) {
1627 		/*
1628 		 * Unfortunately, there is a window between socket() and
1629 		 * bind() where the kernel may queue packets from any
1630 		 * interface.  If we're bound to a particular interface,
1631 		 * discard packets not from that interface.
1632 		 *
1633 		 * (If socket filters are supported, we could do the
1634 		 * same thing we do when changing the filter; however,
1635 		 * that won't handle packet sockets without socket
1636 		 * filter support, and it's a bit more complicated.
1637 		 * It would save some instructions per packet, however.)
1638 		 */
1639 		if (handlep->ifindex != -1 &&
1640 		    from.sll_ifindex != handlep->ifindex)
1641 			return 0;
1642 
1643 		/*
1644 		 * Do checks based on packet direction.
1645 		 * We can only do this if we're using PF_PACKET; the
1646 		 * address returned for SOCK_PACKET is a "sockaddr_pkt"
1647 		 * which lacks the relevant packet type information.
1648 		 */
1649 		if (!linux_check_direction(handle, &from))
1650 			return 0;
1651 	}
1652 #endif
1653 
1654 #ifdef HAVE_PF_PACKET_SOCKETS
1655 	/*
1656 	 * If this is a cooked device, fill in the fake packet header.
1657 	 */
1658 	if (handlep->cooked) {
1659 		/*
1660 		 * Add the length of the fake header to the length
1661 		 * of packet data we read.
1662 		 */
1663 		packet_len += SLL_HDR_LEN;
1664 
1665 		hdrp = (struct sll_header *)bp;
1666 		hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
1667 		hdrp->sll_hatype = htons(from.sll_hatype);
1668 		hdrp->sll_halen = htons(from.sll_halen);
1669 		memcpy(hdrp->sll_addr, from.sll_addr,
1670 		    (from.sll_halen > SLL_ADDRLEN) ?
1671 		      SLL_ADDRLEN :
1672 		      from.sll_halen);
1673 		hdrp->sll_protocol = from.sll_protocol;
1674 	}
1675 
1676 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
1677 	if (handlep->vlan_offset != -1) {
1678 		for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
1679 			struct tpacket_auxdata *aux;
1680 			unsigned int len;
1681 			struct vlan_tag *tag;
1682 
1683 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
1684 			    cmsg->cmsg_level != SOL_PACKET ||
1685 			    cmsg->cmsg_type != PACKET_AUXDATA)
1686 				continue;
1687 
1688 			aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
1689 #if defined(TP_STATUS_VLAN_VALID)
1690 			if ((aux->tp_vlan_tci == 0) && !(aux->tp_status & TP_STATUS_VLAN_VALID))
1691 #else
1692 			if (aux->tp_vlan_tci == 0) /* this is ambigious but without the
1693 						TP_STATUS_VLAN_VALID flag, there is
1694 						nothing that we can do */
1695 #endif
1696 				continue;
1697 
1698 			len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
1699 			if (len < (unsigned int) handlep->vlan_offset)
1700 				break;
1701 
1702 			bp -= VLAN_TAG_LEN;
1703 			memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
1704 
1705 			tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
1706 			tag->vlan_tpid = htons(VLAN_TPID(aux, aux));
1707 			tag->vlan_tci = htons(aux->tp_vlan_tci);
1708 
1709                         /* store vlan tci to bpf_aux_data struct for userland bpf filter */
1710 #if defined(TP_STATUS_VLAN_VALID)
1711                         aux_data.vlan_tag = htons(aux->tp_vlan_tci) & 0x0fff;
1712                         aux_data.vlan_tag_present = (aux->tp_status & TP_STATUS_VLAN_VALID);
1713 #endif
1714 			packet_len += VLAN_TAG_LEN;
1715 		}
1716 	}
1717 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
1718 #endif /* HAVE_PF_PACKET_SOCKETS */
1719 
1720 	/*
1721 	 * XXX: According to the kernel source we should get the real
1722 	 * packet len if calling recvfrom with MSG_TRUNC set. It does
1723 	 * not seem to work here :(, but it is supported by this code
1724 	 * anyway.
1725 	 * To be honest the code RELIES on that feature so this is really
1726 	 * broken with 2.2.x kernels.
1727 	 * I spend a day to figure out what's going on and I found out
1728 	 * that the following is happening:
1729 	 *
1730 	 * The packet comes from a random interface and the packet_rcv
1731 	 * hook is called with a clone of the packet. That code inserts
1732 	 * the packet into the receive queue of the packet socket.
1733 	 * If a filter is attached to that socket that filter is run
1734 	 * first - and there lies the problem. The default filter always
1735 	 * cuts the packet at the snaplen:
1736 	 *
1737 	 * # tcpdump -d
1738 	 * (000) ret      #68
1739 	 *
1740 	 * So the packet filter cuts down the packet. The recvfrom call
1741 	 * says "hey, it's only 68 bytes, it fits into the buffer" with
1742 	 * the result that we don't get the real packet length. This
1743 	 * is valid at least until kernel 2.2.17pre6.
1744 	 *
1745 	 * We currently handle this by making a copy of the filter
1746 	 * program, fixing all "ret" instructions with non-zero
1747 	 * operands to have an operand of MAXIMUM_SNAPLEN so that the
1748 	 * filter doesn't truncate the packet, and supplying that modified
1749 	 * filter to the kernel.
1750 	 */
1751 
1752 	caplen = packet_len;
1753 	if (caplen > handle->snapshot)
1754 		caplen = handle->snapshot;
1755 
1756 	/* Run the packet filter if not using kernel filter */
1757 	if (handlep->filter_in_userland && handle->fcode.bf_insns) {
1758 		if (bpf_filter_with_aux_data(handle->fcode.bf_insns, bp,
1759 		    packet_len, caplen, &aux_data) == 0) {
1760 			/* rejected by filter */
1761 			return 0;
1762 		}
1763 	}
1764 
1765 	/* Fill in our own header data */
1766 
1767 	/* get timestamp for this packet */
1768 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
1769 	if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
1770 		if (ioctl(handle->fd, SIOCGSTAMPNS, &pcap_header.ts) == -1) {
1771 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1772 					"SIOCGSTAMPNS: %s", pcap_strerror(errno));
1773 			return PCAP_ERROR;
1774 		}
1775         } else
1776 #endif
1777 	{
1778 		if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
1779 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1780 					"SIOCGSTAMP: %s", pcap_strerror(errno));
1781 			return PCAP_ERROR;
1782 		}
1783         }
1784 
1785 	pcap_header.caplen	= caplen;
1786 	pcap_header.len		= packet_len;
1787 
1788 	/*
1789 	 * Count the packet.
1790 	 *
1791 	 * Arguably, we should count them before we check the filter,
1792 	 * as on many other platforms "ps_recv" counts packets
1793 	 * handed to the filter rather than packets that passed
1794 	 * the filter, but if filtering is done in the kernel, we
1795 	 * can't get a count of packets that passed the filter,
1796 	 * and that would mean the meaning of "ps_recv" wouldn't
1797 	 * be the same on all Linux systems.
1798 	 *
1799 	 * XXX - it's not the same on all systems in any case;
1800 	 * ideally, we should have a "get the statistics" call
1801 	 * that supplies more counts and indicates which of them
1802 	 * it supplies, so that we supply a count of packets
1803 	 * handed to the filter only on platforms where that
1804 	 * information is available.
1805 	 *
1806 	 * We count them here even if we can get the packet count
1807 	 * from the kernel, as we can only determine at run time
1808 	 * whether we'll be able to get it from the kernel (if
1809 	 * HAVE_TPACKET_STATS isn't defined, we can't get it from
1810 	 * the kernel, but if it is defined, the library might
1811 	 * have been built with a 2.4 or later kernel, but we
1812 	 * might be running on a 2.2[.x] kernel without Alexey
1813 	 * Kuznetzov's turbopacket patches, and thus the kernel
1814 	 * might not be able to supply those statistics).  We
1815 	 * could, I guess, try, when opening the socket, to get
1816 	 * the statistics, and if we can not increment the count
1817 	 * here, but it's not clear that always incrementing
1818 	 * the count is more expensive than always testing a flag
1819 	 * in memory.
1820 	 *
1821 	 * We keep the count in "handlep->packets_read", and use that
1822 	 * for "ps_recv" if we can't get the statistics from the kernel.
1823 	 * We do that because, if we *can* get the statistics from
1824 	 * the kernel, we use "handlep->stat.ps_recv" and
1825 	 * "handlep->stat.ps_drop" as running counts, as reading the
1826 	 * statistics from the kernel resets the kernel statistics,
1827 	 * and if we directly increment "handlep->stat.ps_recv" here,
1828 	 * that means it will count packets *twice* on systems where
1829 	 * we can get kernel statistics - once here, and once in
1830 	 * pcap_stats_linux().
1831 	 */
1832 	handlep->packets_read++;
1833 
1834 	/* Call the user supplied callback function */
1835 	callback(userdata, &pcap_header, bp);
1836 
1837 	return 1;
1838 }
1839 
1840 static int
1841 pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
1842 {
1843 	struct pcap_linux *handlep = handle->priv;
1844 	int ret;
1845 
1846 #ifdef HAVE_PF_PACKET_SOCKETS
1847 	if (!handlep->sock_packet) {
1848 		/* PF_PACKET socket */
1849 		if (handlep->ifindex == -1) {
1850 			/*
1851 			 * We don't support sending on the "any" device.
1852 			 */
1853 			strlcpy(handle->errbuf,
1854 			    "Sending packets isn't supported on the \"any\" device",
1855 			    PCAP_ERRBUF_SIZE);
1856 			return (-1);
1857 		}
1858 
1859 		if (handlep->cooked) {
1860 			/*
1861 			 * We don't support sending on the "any" device.
1862 			 *
1863 			 * XXX - how do you send on a bound cooked-mode
1864 			 * socket?
1865 			 * Is a "sendto()" required there?
1866 			 */
1867 			strlcpy(handle->errbuf,
1868 			    "Sending packets isn't supported in cooked mode",
1869 			    PCAP_ERRBUF_SIZE);
1870 			return (-1);
1871 		}
1872 	}
1873 #endif
1874 
1875 	ret = send(handle->fd, buf, size, 0);
1876 	if (ret == -1) {
1877 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1878 		    pcap_strerror(errno));
1879 		return (-1);
1880 	}
1881 	return (ret);
1882 }
1883 
1884 /*
1885  *  Get the statistics for the given packet capture handle.
1886  *  Reports the number of dropped packets iff the kernel supports
1887  *  the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1888  *  kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1889  *  patches); otherwise, that information isn't available, and we lie
1890  *  and report 0 as the count of dropped packets.
1891  */
1892 static int
1893 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
1894 {
1895 	struct pcap_linux *handlep = handle->priv;
1896 #ifdef HAVE_TPACKET_STATS
1897 #ifdef HAVE_TPACKET3
1898 	/*
1899 	 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
1900 	 * stuff at the end of a struct tpacket_stats_v3 will not
1901 	 * be filled in, and we don't look at it so this is OK even
1902 	 * for those sockets.  In addition, the PF_PACKET socket
1903 	 * code in the kernel only uses the length parameter to
1904 	 * compute how much data to copy out and to indicate how
1905 	 * much data was copied out, so it's OK to base it on the
1906 	 * size of a struct tpacket_stats.
1907 	 *
1908 	 * XXX - it's probably OK, in fact, to just use a
1909 	 * struct tpacket_stats for V3 sockets, as we don't
1910 	 * care about the tp_freeze_q_cnt stat.
1911 	 */
1912 	struct tpacket_stats_v3 kstats;
1913 #else /* HAVE_TPACKET3 */
1914 	struct tpacket_stats kstats;
1915 #endif /* HAVE_TPACKET3 */
1916 	socklen_t len = sizeof (struct tpacket_stats);
1917 #endif /* HAVE_TPACKET_STATS */
1918 
1919 	long if_dropped = 0;
1920 
1921 	/*
1922 	 *	To fill in ps_ifdrop, we parse /proc/net/dev for the number
1923 	 */
1924 	if (handle->opt.promisc)
1925 	{
1926 		if_dropped = handlep->proc_dropped;
1927 		handlep->proc_dropped = linux_if_drops(handlep->device);
1928 		handlep->stat.ps_ifdrop += (handlep->proc_dropped - if_dropped);
1929 	}
1930 
1931 #ifdef HAVE_TPACKET_STATS
1932 	/*
1933 	 * Try to get the packet counts from the kernel.
1934 	 */
1935 	if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
1936 			&kstats, &len) > -1) {
1937 		/*
1938 		 * On systems where the PACKET_STATISTICS "getsockopt()"
1939 		 * argument is supported on PF_PACKET sockets:
1940 		 *
1941 		 *	"ps_recv" counts only packets that *passed* the
1942 		 *	filter, not packets that didn't pass the filter.
1943 		 *	This includes packets later dropped because we
1944 		 *	ran out of buffer space.
1945 		 *
1946 		 *	"ps_drop" counts packets dropped because we ran
1947 		 *	out of buffer space.  It doesn't count packets
1948 		 *	dropped by the interface driver.  It counts only
1949 		 *	packets that passed the filter.
1950 		 *
1951 		 *	See above for ps_ifdrop.
1952 		 *
1953 		 *	Both statistics include packets not yet read from
1954 		 *	the kernel by libpcap, and thus not yet seen by
1955 		 *	the application.
1956 		 *
1957 		 * In "linux/net/packet/af_packet.c", at least in the
1958 		 * 2.4.9 kernel, "tp_packets" is incremented for every
1959 		 * packet that passes the packet filter *and* is
1960 		 * successfully queued on the socket; "tp_drops" is
1961 		 * incremented for every packet dropped because there's
1962 		 * not enough free space in the socket buffer.
1963 		 *
1964 		 * When the statistics are returned for a PACKET_STATISTICS
1965 		 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1966 		 * so that "tp_packets" counts all packets handed to
1967 		 * the PF_PACKET socket, including packets dropped because
1968 		 * there wasn't room on the socket buffer - but not
1969 		 * including packets that didn't pass the filter.
1970 		 *
1971 		 * In the BSD BPF, the count of received packets is
1972 		 * incremented for every packet handed to BPF, regardless
1973 		 * of whether it passed the filter.
1974 		 *
1975 		 * We can't make "pcap_stats()" work the same on both
1976 		 * platforms, but the best approximation is to return
1977 		 * "tp_packets" as the count of packets and "tp_drops"
1978 		 * as the count of drops.
1979 		 *
1980 		 * Keep a running total because each call to
1981 		 *    getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1982 		 * resets the counters to zero.
1983 		 */
1984 		handlep->stat.ps_recv += kstats.tp_packets;
1985 		handlep->stat.ps_drop += kstats.tp_drops;
1986 		*stats = handlep->stat;
1987 		return 0;
1988 	}
1989 	else
1990 	{
1991 		/*
1992 		 * If the error was EOPNOTSUPP, fall through, so that
1993 		 * if you build the library on a system with
1994 		 * "struct tpacket_stats" and run it on a system
1995 		 * that doesn't, it works as it does if the library
1996 		 * is built on a system without "struct tpacket_stats".
1997 		 */
1998 		if (errno != EOPNOTSUPP) {
1999 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2000 			    "pcap_stats: %s", pcap_strerror(errno));
2001 			return -1;
2002 		}
2003 	}
2004 #endif
2005 	/*
2006 	 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2007 	 * is not supported on PF_PACKET sockets:
2008 	 *
2009 	 *	"ps_recv" counts only packets that *passed* the filter,
2010 	 *	not packets that didn't pass the filter.  It does not
2011 	 *	count packets dropped because we ran out of buffer
2012 	 *	space.
2013 	 *
2014 	 *	"ps_drop" is not supported.
2015 	 *
2016 	 *	"ps_ifdrop" is supported. It will return the number
2017 	 *	of drops the interface reports in /proc/net/dev,
2018 	 *	if that is available.
2019 	 *
2020 	 *	"ps_recv" doesn't include packets not yet read from
2021 	 *	the kernel by libpcap.
2022 	 *
2023 	 * We maintain the count of packets processed by libpcap in
2024 	 * "handlep->packets_read", for reasons described in the comment
2025 	 * at the end of pcap_read_packet().  We have no idea how many
2026 	 * packets were dropped by the kernel buffers -- but we know
2027 	 * how many the interface dropped, so we can return that.
2028 	 */
2029 
2030 	stats->ps_recv = handlep->packets_read;
2031 	stats->ps_drop = 0;
2032 	stats->ps_ifdrop = handlep->stat.ps_ifdrop;
2033 	return 0;
2034 }
2035 
2036 static int
2037 add_linux_if(pcap_if_t **devlistp, const char *ifname, int fd, char *errbuf)
2038 {
2039 	const char *p;
2040 	char name[512];	/* XXX - pick a size */
2041 	char *q, *saveq;
2042 	struct ifreq ifrflags;
2043 
2044 	/*
2045 	 * Get the interface name.
2046 	 */
2047 	p = ifname;
2048 	q = &name[0];
2049 	while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2050 		if (*p == ':') {
2051 			/*
2052 			 * This could be the separator between a
2053 			 * name and an alias number, or it could be
2054 			 * the separator between a name with no
2055 			 * alias number and the next field.
2056 			 *
2057 			 * If there's a colon after digits, it
2058 			 * separates the name and the alias number,
2059 			 * otherwise it separates the name and the
2060 			 * next field.
2061 			 */
2062 			saveq = q;
2063 			while (isascii(*p) && isdigit(*p))
2064 				*q++ = *p++;
2065 			if (*p != ':') {
2066 				/*
2067 				 * That was the next field,
2068 				 * not the alias number.
2069 				 */
2070 				q = saveq;
2071 			}
2072 			break;
2073 		} else
2074 			*q++ = *p++;
2075 	}
2076 	*q = '\0';
2077 
2078 	/*
2079 	 * Get the flags for this interface.
2080 	 */
2081 	strlcpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2082 	if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2083 		if (errno == ENXIO || errno == ENODEV)
2084 			return (0);	/* device doesn't actually exist - ignore it */
2085 		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2086 		    "SIOCGIFFLAGS: %.*s: %s",
2087 		    (int)sizeof(ifrflags.ifr_name),
2088 		    ifrflags.ifr_name,
2089 		    pcap_strerror(errno));
2090 		return (-1);
2091 	}
2092 
2093 	/*
2094 	 * Add an entry for this interface, with no addresses.
2095 	 */
2096 	if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2097 	    errbuf) == -1) {
2098 		/*
2099 		 * Failure.
2100 		 */
2101 		return (-1);
2102 	}
2103 
2104 	return (0);
2105 }
2106 
2107 /*
2108  * Get from "/sys/class/net" all interfaces listed there; if they're
2109  * already in the list of interfaces we have, that won't add another
2110  * instance, but if they're not, that'll add them.
2111  *
2112  * We don't bother getting any addresses for them; it appears you can't
2113  * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2114  * although some other types of addresses can be fetched with SIOCGIFADDR,
2115  * we don't bother with them for now.
2116  *
2117  * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2118  * the list of interfaces as is, and return 0, so that we can try
2119  * scanning /proc/net/dev.
2120  *
2121  * Otherwise, we return 1 if we don't get an error and -1 if we do.
2122  */
2123 static int
2124 scan_sys_class_net(pcap_if_t **devlistp, char *errbuf)
2125 {
2126 	DIR *sys_class_net_d;
2127 	int fd;
2128 	struct dirent *ent;
2129 	char subsystem_path[PATH_MAX+1];
2130 	struct stat statb;
2131 	int ret = 1;
2132 
2133 	sys_class_net_d = opendir("/sys/class/net");
2134 	if (sys_class_net_d == NULL) {
2135 		/*
2136 		 * Don't fail if it doesn't exist at all.
2137 		 */
2138 		if (errno == ENOENT)
2139 			return (0);
2140 
2141 		/*
2142 		 * Fail if we got some other error.
2143 		 */
2144 		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2145 		    "Can't open /sys/class/net: %s", pcap_strerror(errno));
2146 		return (-1);
2147 	}
2148 
2149 	/*
2150 	 * Create a socket from which to fetch interface information.
2151 	 */
2152 	fd = socket(AF_INET, SOCK_DGRAM, 0);
2153 	if (fd < 0) {
2154 		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2155 		    "socket: %s", pcap_strerror(errno));
2156 		(void)closedir(sys_class_net_d);
2157 		return (-1);
2158 	}
2159 
2160 	for (;;) {
2161 		errno = 0;
2162 		ent = readdir(sys_class_net_d);
2163 		if (ent == NULL) {
2164 			/*
2165 			 * Error or EOF; if errno != 0, it's an error.
2166 			 */
2167 			break;
2168 		}
2169 
2170 		/*
2171 		 * Ignore "." and "..".
2172 		 */
2173 		if (strcmp(ent->d_name, ".") == 0 ||
2174 		    strcmp(ent->d_name, "..") == 0)
2175 			continue;
2176 
2177 		/*
2178 		 * Ignore plain files; they do not have subdirectories
2179 		 * and thus have no attributes.
2180 		 */
2181 		if (ent->d_type == DT_REG)
2182 			continue;
2183 
2184 		/*
2185 		 * Is there an "ifindex" file under that name?
2186 		 * (We don't care whether it's a directory or
2187 		 * a symlink; older kernels have directories
2188 		 * for devices, newer kernels have symlinks to
2189 		 * directories.)
2190 		 */
2191 		snprintf(subsystem_path, sizeof subsystem_path,
2192 		    "/sys/class/net/%s/ifindex", ent->d_name);
2193 		if (lstat(subsystem_path, &statb) != 0) {
2194 			/*
2195 			 * Stat failed.  Either there was an error
2196 			 * other than ENOENT, and we don't know if
2197 			 * this is an interface, or it's ENOENT,
2198 			 * and either some part of "/sys/class/net/{if}"
2199 			 * disappeared, in which case it probably means
2200 			 * the interface disappeared, or there's no
2201 			 * "ifindex" file, which means it's not a
2202 			 * network interface.
2203 			 */
2204 			continue;
2205 		}
2206 
2207 		/*
2208 		 * Attempt to add the interface.
2209 		 */
2210 		if (add_linux_if(devlistp, &ent->d_name[0], fd, errbuf) == -1) {
2211 			/* Fail. */
2212 			ret = -1;
2213 			break;
2214 		}
2215 	}
2216 	if (ret != -1) {
2217 		/*
2218 		 * Well, we didn't fail for any other reason; did we
2219 		 * fail due to an error reading the directory?
2220 		 */
2221 		if (errno != 0) {
2222 			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2223 			    "Error reading /sys/class/net: %s",
2224 			    pcap_strerror(errno));
2225 			ret = -1;
2226 		}
2227 	}
2228 
2229 	(void)close(fd);
2230 	(void)closedir(sys_class_net_d);
2231 	return (ret);
2232 }
2233 
2234 /*
2235  * Get from "/proc/net/dev" all interfaces listed there; if they're
2236  * already in the list of interfaces we have, that won't add another
2237  * instance, but if they're not, that'll add them.
2238  *
2239  * See comments from scan_sys_class_net().
2240  */
2241 static int
2242 scan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
2243 {
2244 	FILE *proc_net_f;
2245 	int fd;
2246 	char linebuf[512];
2247 	int linenum;
2248 	char *p;
2249 	int ret = 0;
2250 
2251 	proc_net_f = fopen("/proc/net/dev", "r");
2252 	if (proc_net_f == NULL) {
2253 		/*
2254 		 * Don't fail if it doesn't exist at all.
2255 		 */
2256 		if (errno == ENOENT)
2257 			return (0);
2258 
2259 		/*
2260 		 * Fail if we got some other error.
2261 		 */
2262 		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2263 		    "Can't open /proc/net/dev: %s", pcap_strerror(errno));
2264 		return (-1);
2265 	}
2266 
2267 	/*
2268 	 * Create a socket from which to fetch interface information.
2269 	 */
2270 	fd = socket(AF_INET, SOCK_DGRAM, 0);
2271 	if (fd < 0) {
2272 		(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2273 		    "socket: %s", pcap_strerror(errno));
2274 		(void)fclose(proc_net_f);
2275 		return (-1);
2276 	}
2277 
2278 	for (linenum = 1;
2279 	    fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
2280 		/*
2281 		 * Skip the first two lines - they're headers.
2282 		 */
2283 		if (linenum <= 2)
2284 			continue;
2285 
2286 		p = &linebuf[0];
2287 
2288 		/*
2289 		 * Skip leading white space.
2290 		 */
2291 		while (*p != '\0' && isascii(*p) && isspace(*p))
2292 			p++;
2293 		if (*p == '\0' || *p == '\n')
2294 			continue;	/* blank line */
2295 
2296 		/*
2297 		 * Attempt to add the interface.
2298 		 */
2299 		if (add_linux_if(devlistp, p, fd, errbuf) == -1) {
2300 			/* Fail. */
2301 			ret = -1;
2302 			break;
2303 		}
2304 	}
2305 	if (ret != -1) {
2306 		/*
2307 		 * Well, we didn't fail for any other reason; did we
2308 		 * fail due to an error reading the file?
2309 		 */
2310 		if (ferror(proc_net_f)) {
2311 			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2312 			    "Error reading /proc/net/dev: %s",
2313 			    pcap_strerror(errno));
2314 			ret = -1;
2315 		}
2316 	}
2317 
2318 	(void)close(fd);
2319 	(void)fclose(proc_net_f);
2320 	return (ret);
2321 }
2322 
2323 /*
2324  * Description string for the "any" device.
2325  */
2326 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
2327 
2328 int
2329 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2330 {
2331 	int ret;
2332 
2333 	/*
2334 	 * Read "/sys/class/net", and add to the list of interfaces all
2335 	 * interfaces listed there that we don't already have, because,
2336 	 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2337 	 * and even getifaddrs() won't return information about
2338 	 * interfaces with no addresses, so you need to read "/sys/class/net"
2339 	 * to get the names of the rest of the interfaces.
2340 	 */
2341 	ret = scan_sys_class_net(alldevsp, errbuf);
2342 	if (ret == -1)
2343 		return (-1);	/* failed */
2344 	if (ret == 0) {
2345 		/*
2346 		 * No /sys/class/net; try reading /proc/net/dev instead.
2347 		 */
2348 		if (scan_proc_net_dev(alldevsp, errbuf) == -1)
2349 			return (-1);
2350 	}
2351 
2352 	/*
2353 	 * Add the "any" device.
2354 	 */
2355 	if (pcap_add_if(alldevsp, "any", IFF_UP|IFF_RUNNING,
2356 	    any_descr, errbuf) < 0)
2357 		return (-1);
2358 
2359 	return (0);
2360 }
2361 
2362 /*
2363  *  Attach the given BPF code to the packet capture device.
2364  */
2365 static int
2366 pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
2367     int is_mmapped)
2368 {
2369 	struct pcap_linux *handlep;
2370 #ifdef SO_ATTACH_FILTER
2371 	struct sock_fprog	fcode;
2372 	int			can_filter_in_kernel;
2373 	int			err = 0;
2374 #endif
2375 
2376 	if (!handle)
2377 		return -1;
2378 	if (!filter) {
2379 	        strlcpy(handle->errbuf, "setfilter: No filter specified",
2380 			PCAP_ERRBUF_SIZE);
2381 		return -1;
2382 	}
2383 
2384 	handlep = handle->priv;
2385 
2386 	/* Make our private copy of the filter */
2387 
2388 	if (install_bpf_program(handle, filter) < 0)
2389 		/* install_bpf_program() filled in errbuf */
2390 		return -1;
2391 
2392 	/*
2393 	 * Run user level packet filter by default. Will be overriden if
2394 	 * installing a kernel filter succeeds.
2395 	 */
2396 	handlep->filter_in_userland = 1;
2397 
2398 	/* Install kernel level filter if possible */
2399 
2400 #ifdef SO_ATTACH_FILTER
2401 #ifdef USHRT_MAX
2402 	if (handle->fcode.bf_len > USHRT_MAX) {
2403 		/*
2404 		 * fcode.len is an unsigned short for current kernel.
2405 		 * I have yet to see BPF-Code with that much
2406 		 * instructions but still it is possible. So for the
2407 		 * sake of correctness I added this check.
2408 		 */
2409 		fprintf(stderr, "Warning: Filter too complex for kernel\n");
2410 		fcode.len = 0;
2411 		fcode.filter = NULL;
2412 		can_filter_in_kernel = 0;
2413 	} else
2414 #endif /* USHRT_MAX */
2415 	{
2416 		/*
2417 		 * Oh joy, the Linux kernel uses struct sock_fprog instead
2418 		 * of struct bpf_program and of course the length field is
2419 		 * of different size. Pointed out by Sebastian
2420 		 *
2421 		 * Oh, and we also need to fix it up so that all "ret"
2422 		 * instructions with non-zero operands have MAXIMUM_SNAPLEN
2423 		 * as the operand if we're not capturing in memory-mapped
2424 		 * mode, and so that, if we're in cooked mode, all memory-
2425 		 * reference instructions use special magic offsets in
2426 		 * references to the link-layer header and assume that the
2427 		 * link-layer payload begins at 0; "fix_program()" will do
2428 		 * that.
2429 		 */
2430 		switch (fix_program(handle, &fcode, is_mmapped)) {
2431 
2432 		case -1:
2433 		default:
2434 			/*
2435 			 * Fatal error; just quit.
2436 			 * (The "default" case shouldn't happen; we
2437 			 * return -1 for that reason.)
2438 			 */
2439 			return -1;
2440 
2441 		case 0:
2442 			/*
2443 			 * The program performed checks that we can't make
2444 			 * work in the kernel.
2445 			 */
2446 			can_filter_in_kernel = 0;
2447 			break;
2448 
2449 		case 1:
2450 			/*
2451 			 * We have a filter that'll work in the kernel.
2452 			 */
2453 			can_filter_in_kernel = 1;
2454 			break;
2455 		}
2456 	}
2457 
2458 	/*
2459 	 * NOTE: at this point, we've set both the "len" and "filter"
2460 	 * fields of "fcode".  As of the 2.6.32.4 kernel, at least,
2461 	 * those are the only members of the "sock_fprog" structure,
2462 	 * so we initialize every member of that structure.
2463 	 *
2464 	 * If there is anything in "fcode" that is not initialized,
2465 	 * it is either a field added in a later kernel, or it's
2466 	 * padding.
2467 	 *
2468 	 * If a new field is added, this code needs to be updated
2469 	 * to set it correctly.
2470 	 *
2471 	 * If there are no other fields, then:
2472 	 *
2473 	 *	if the Linux kernel looks at the padding, it's
2474 	 *	buggy;
2475 	 *
2476 	 *	if the Linux kernel doesn't look at the padding,
2477 	 *	then if some tool complains that we're passing
2478 	 *	uninitialized data to the kernel, then the tool
2479 	 *	is buggy and needs to understand that it's just
2480 	 *	padding.
2481 	 */
2482 	if (can_filter_in_kernel) {
2483 		if ((err = set_kernel_filter(handle, &fcode)) == 0)
2484 		{
2485 			/*
2486 			 * Installation succeded - using kernel filter,
2487 			 * so userland filtering not needed.
2488 			 */
2489 			handlep->filter_in_userland = 0;
2490 		}
2491 		else if (err == -1)	/* Non-fatal error */
2492 		{
2493 			/*
2494 			 * Print a warning if we weren't able to install
2495 			 * the filter for a reason other than "this kernel
2496 			 * isn't configured to support socket filters.
2497 			 */
2498 			if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
2499 				fprintf(stderr,
2500 				    "Warning: Kernel filter failed: %s\n",
2501 					pcap_strerror(errno));
2502 			}
2503 		}
2504 	}
2505 
2506 	/*
2507 	 * If we're not using the kernel filter, get rid of any kernel
2508 	 * filter that might've been there before, e.g. because the
2509 	 * previous filter could work in the kernel, or because some other
2510 	 * code attached a filter to the socket by some means other than
2511 	 * calling "pcap_setfilter()".  Otherwise, the kernel filter may
2512 	 * filter out packets that would pass the new userland filter.
2513 	 */
2514 	if (handlep->filter_in_userland) {
2515 		if (reset_kernel_filter(handle) == -1) {
2516 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2517 			    "can't remove kernel filter: %s",
2518 			    pcap_strerror(errno));
2519 			err = -2;	/* fatal error */
2520 		}
2521 	}
2522 
2523 	/*
2524 	 * Free up the copy of the filter that was made by "fix_program()".
2525 	 */
2526 	if (fcode.filter != NULL)
2527 		free(fcode.filter);
2528 
2529 	if (err == -2)
2530 		/* Fatal error */
2531 		return -1;
2532 #endif /* SO_ATTACH_FILTER */
2533 
2534 	return 0;
2535 }
2536 
2537 static int
2538 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
2539 {
2540 	return pcap_setfilter_linux_common(handle, filter, 0);
2541 }
2542 
2543 
2544 /*
2545  * Set direction flag: Which packets do we accept on a forwarding
2546  * single device? IN, OUT or both?
2547  */
2548 static int
2549 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
2550 {
2551 #ifdef HAVE_PF_PACKET_SOCKETS
2552 	struct pcap_linux *handlep = handle->priv;
2553 
2554 	if (!handlep->sock_packet) {
2555 		handle->direction = d;
2556 		return 0;
2557 	}
2558 #endif
2559 	/*
2560 	 * We're not using PF_PACKET sockets, so we can't determine
2561 	 * the direction of the packet.
2562 	 */
2563 	snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2564 	    "Setting direction is not supported on SOCK_PACKET sockets");
2565 	return -1;
2566 }
2567 
2568 #ifdef HAVE_PF_PACKET_SOCKETS
2569 /*
2570  * Map the PACKET_ value to a LINUX_SLL_ value; we
2571  * want the same numerical value to be used in
2572  * the link-layer header even if the numerical values
2573  * for the PACKET_ #defines change, so that programs
2574  * that look at the packet type field will always be
2575  * able to handle DLT_LINUX_SLL captures.
2576  */
2577 static short int
2578 map_packet_type_to_sll_type(short int sll_pkttype)
2579 {
2580 	switch (sll_pkttype) {
2581 
2582 	case PACKET_HOST:
2583 		return htons(LINUX_SLL_HOST);
2584 
2585 	case PACKET_BROADCAST:
2586 		return htons(LINUX_SLL_BROADCAST);
2587 
2588 	case PACKET_MULTICAST:
2589 		return  htons(LINUX_SLL_MULTICAST);
2590 
2591 	case PACKET_OTHERHOST:
2592 		return htons(LINUX_SLL_OTHERHOST);
2593 
2594 	case PACKET_OUTGOING:
2595 		return htons(LINUX_SLL_OUTGOING);
2596 
2597 	default:
2598 		return -1;
2599 	}
2600 }
2601 #endif
2602 
2603 static int
2604 is_wifi(int sock_fd
2605 #ifndef IW_MODE_MONITOR
2606 _U_
2607 #endif
2608 , const char *device)
2609 {
2610 	char *pathstr;
2611 	struct stat statb;
2612 #ifdef IW_MODE_MONITOR
2613 	char errbuf[PCAP_ERRBUF_SIZE];
2614 #endif
2615 
2616 	/*
2617 	 * See if there's a sysfs wireless directory for it.
2618 	 * If so, it's a wireless interface.
2619 	 */
2620 	if (asprintf(&pathstr, "/sys/class/net/%s/wireless", device) == -1) {
2621 		/*
2622 		 * Just give up here.
2623 		 */
2624 		return 0;
2625 	}
2626 	if (stat(pathstr, &statb) == 0) {
2627 		free(pathstr);
2628 		return 1;
2629 	}
2630 	free(pathstr);
2631 
2632 #ifdef IW_MODE_MONITOR
2633 	/*
2634 	 * OK, maybe it's not wireless, or maybe this kernel doesn't
2635 	 * support sysfs.  Try the wireless extensions.
2636 	 */
2637 	if (has_wext(sock_fd, device, errbuf) == 1) {
2638 		/*
2639 		 * It supports the wireless extensions, so it's a Wi-Fi
2640 		 * device.
2641 		 */
2642 		return 1;
2643 	}
2644 #endif
2645 	return 0;
2646 }
2647 
2648 /*
2649  *  Linux uses the ARP hardware type to identify the type of an
2650  *  interface. pcap uses the DLT_xxx constants for this. This
2651  *  function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2652  *  constant, as arguments, and sets "handle->linktype" to the
2653  *  appropriate DLT_XXX constant and sets "handle->offset" to
2654  *  the appropriate value (to make "handle->offset" plus link-layer
2655  *  header length be a multiple of 4, so that the link-layer payload
2656  *  will be aligned on a 4-byte boundary when capturing packets).
2657  *  (If the offset isn't set here, it'll be 0; add code as appropriate
2658  *  for cases where it shouldn't be 0.)
2659  *
2660  *  If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2661  *  in cooked mode; otherwise, we can't use cooked mode, so we have
2662  *  to pick some type that works in raw mode, or fail.
2663  *
2664  *  Sets the link type to -1 if unable to map the type.
2665  */
2666 static void map_arphrd_to_dlt(pcap_t *handle, int sock_fd, int arptype,
2667 			      const char *device, int cooked_ok)
2668 {
2669 	static const char cdma_rmnet[] = "cdma_rmnet";
2670 
2671 	switch (arptype) {
2672 
2673 	case ARPHRD_ETHER:
2674 		/*
2675 		 * For various annoying reasons having to do with DHCP
2676 		 * software, some versions of Android give the mobile-
2677 		 * phone-network interface an ARPHRD_ value of
2678 		 * ARPHRD_ETHER, even though the packets supplied by
2679 		 * that interface have no link-layer header, and begin
2680 		 * with an IP header, so that the ARPHRD_ value should
2681 		 * be ARPHRD_NONE.
2682 		 *
2683 		 * Detect those devices by checking the device name, and
2684 		 * use DLT_RAW for them.
2685 		 */
2686 		if (strncmp(device, cdma_rmnet, sizeof cdma_rmnet - 1) == 0) {
2687 			handle->linktype = DLT_RAW;
2688 			return;
2689 		}
2690 
2691 		/*
2692 		 * Is this a real Ethernet device?  If so, give it a
2693 		 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2694 		 * that an application can let you choose it, in case you're
2695 		 * capturing DOCSIS traffic that a Cisco Cable Modem
2696 		 * Termination System is putting out onto an Ethernet (it
2697 		 * doesn't put an Ethernet header onto the wire, it puts raw
2698 		 * DOCSIS frames out on the wire inside the low-level
2699 		 * Ethernet framing).
2700 		 *
2701 		 * XXX - are there any other sorts of "fake Ethernet" that
2702 		 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
2703 		 * a Cisco CMTS won't put traffic onto it or get traffic
2704 		 * bridged onto it?  ISDN is handled in "activate_new()",
2705 		 * as we fall back on cooked mode there, and we use
2706 		 * is_wifi() to check for 802.11 devices; are there any
2707 		 * others?
2708 		 */
2709 		if (!is_wifi(sock_fd, device)) {
2710 			/*
2711 			 * It's not a Wi-Fi device; offer DOCSIS.
2712 			 */
2713 			handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2714 			/*
2715 			 * If that fails, just leave the list empty.
2716 			 */
2717 			if (handle->dlt_list != NULL) {
2718 				handle->dlt_list[0] = DLT_EN10MB;
2719 				handle->dlt_list[1] = DLT_DOCSIS;
2720 				handle->dlt_count = 2;
2721 			}
2722 		}
2723 		/* FALLTHROUGH */
2724 
2725 	case ARPHRD_METRICOM:
2726 	case ARPHRD_LOOPBACK:
2727 		handle->linktype = DLT_EN10MB;
2728 		handle->offset = 2;
2729 		break;
2730 
2731 	case ARPHRD_EETHER:
2732 		handle->linktype = DLT_EN3MB;
2733 		break;
2734 
2735 	case ARPHRD_AX25:
2736 		handle->linktype = DLT_AX25_KISS;
2737 		break;
2738 
2739 	case ARPHRD_PRONET:
2740 		handle->linktype = DLT_PRONET;
2741 		break;
2742 
2743 	case ARPHRD_CHAOS:
2744 		handle->linktype = DLT_CHAOS;
2745 		break;
2746 #ifndef ARPHRD_CAN
2747 #define ARPHRD_CAN 280
2748 #endif
2749 	case ARPHRD_CAN:
2750 		handle->linktype = DLT_CAN_SOCKETCAN;
2751 		break;
2752 
2753 #ifndef ARPHRD_IEEE802_TR
2754 #define ARPHRD_IEEE802_TR 800	/* From Linux 2.4 */
2755 #endif
2756 	case ARPHRD_IEEE802_TR:
2757 	case ARPHRD_IEEE802:
2758 		handle->linktype = DLT_IEEE802;
2759 		handle->offset = 2;
2760 		break;
2761 
2762 	case ARPHRD_ARCNET:
2763 		handle->linktype = DLT_ARCNET_LINUX;
2764 		break;
2765 
2766 #ifndef ARPHRD_FDDI	/* From Linux 2.2.13 */
2767 #define ARPHRD_FDDI	774
2768 #endif
2769 	case ARPHRD_FDDI:
2770 		handle->linktype = DLT_FDDI;
2771 		handle->offset = 3;
2772 		break;
2773 
2774 #ifndef ARPHRD_ATM  /* FIXME: How to #include this? */
2775 #define ARPHRD_ATM 19
2776 #endif
2777 	case ARPHRD_ATM:
2778 		/*
2779 		 * The Classical IP implementation in ATM for Linux
2780 		 * supports both what RFC 1483 calls "LLC Encapsulation",
2781 		 * in which each packet has an LLC header, possibly
2782 		 * with a SNAP header as well, prepended to it, and
2783 		 * what RFC 1483 calls "VC Based Multiplexing", in which
2784 		 * different virtual circuits carry different network
2785 		 * layer protocols, and no header is prepended to packets.
2786 		 *
2787 		 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2788 		 * you can't use the ARPHRD_ type to find out whether
2789 		 * captured packets will have an LLC header, and,
2790 		 * while there's a socket ioctl to *set* the encapsulation
2791 		 * type, there's no ioctl to *get* the encapsulation type.
2792 		 *
2793 		 * This means that
2794 		 *
2795 		 *	programs that dissect Linux Classical IP frames
2796 		 *	would have to check for an LLC header and,
2797 		 *	depending on whether they see one or not, dissect
2798 		 *	the frame as LLC-encapsulated or as raw IP (I
2799 		 *	don't know whether there's any traffic other than
2800 		 *	IP that would show up on the socket, or whether
2801 		 *	there's any support for IPv6 in the Linux
2802 		 *	Classical IP code);
2803 		 *
2804 		 *	filter expressions would have to compile into
2805 		 *	code that checks for an LLC header and does
2806 		 *	the right thing.
2807 		 *
2808 		 * Both of those are a nuisance - and, at least on systems
2809 		 * that support PF_PACKET sockets, we don't have to put
2810 		 * up with those nuisances; instead, we can just capture
2811 		 * in cooked mode.  That's what we'll do, if we can.
2812 		 * Otherwise, we'll just fail.
2813 		 */
2814 		if (cooked_ok)
2815 			handle->linktype = DLT_LINUX_SLL;
2816 		else
2817 			handle->linktype = -1;
2818 		break;
2819 
2820 #ifndef ARPHRD_IEEE80211  /* From Linux 2.4.6 */
2821 #define ARPHRD_IEEE80211 801
2822 #endif
2823 	case ARPHRD_IEEE80211:
2824 		handle->linktype = DLT_IEEE802_11;
2825 		break;
2826 
2827 #ifndef ARPHRD_IEEE80211_PRISM  /* From Linux 2.4.18 */
2828 #define ARPHRD_IEEE80211_PRISM 802
2829 #endif
2830 	case ARPHRD_IEEE80211_PRISM:
2831 		handle->linktype = DLT_PRISM_HEADER;
2832 		break;
2833 
2834 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2835 #define ARPHRD_IEEE80211_RADIOTAP 803
2836 #endif
2837 	case ARPHRD_IEEE80211_RADIOTAP:
2838 		handle->linktype = DLT_IEEE802_11_RADIO;
2839 		break;
2840 
2841 	case ARPHRD_PPP:
2842 		/*
2843 		 * Some PPP code in the kernel supplies no link-layer
2844 		 * header whatsoever to PF_PACKET sockets; other PPP
2845 		 * code supplies PPP link-layer headers ("syncppp.c");
2846 		 * some PPP code might supply random link-layer
2847 		 * headers (PPP over ISDN - there's code in Ethereal,
2848 		 * for example, to cope with PPP-over-ISDN captures
2849 		 * with which the Ethereal developers have had to cope,
2850 		 * heuristically trying to determine which of the
2851 		 * oddball link-layer headers particular packets have).
2852 		 *
2853 		 * As such, we just punt, and run all PPP interfaces
2854 		 * in cooked mode, if we can; otherwise, we just treat
2855 		 * it as DLT_RAW, for now - if somebody needs to capture,
2856 		 * on a 2.0[.x] kernel, on PPP devices that supply a
2857 		 * link-layer header, they'll have to add code here to
2858 		 * map to the appropriate DLT_ type (possibly adding a
2859 		 * new DLT_ type, if necessary).
2860 		 */
2861 		if (cooked_ok)
2862 			handle->linktype = DLT_LINUX_SLL;
2863 		else {
2864 			/*
2865 			 * XXX - handle ISDN types here?  We can't fall
2866 			 * back on cooked sockets, so we'd have to
2867 			 * figure out from the device name what type of
2868 			 * link-layer encapsulation it's using, and map
2869 			 * that to an appropriate DLT_ value, meaning
2870 			 * we'd map "isdnN" devices to DLT_RAW (they
2871 			 * supply raw IP packets with no link-layer
2872 			 * header) and "isdY" devices to a new DLT_I4L_IP
2873 			 * type that has only an Ethernet packet type as
2874 			 * a link-layer header.
2875 			 *
2876 			 * But sometimes we seem to get random crap
2877 			 * in the link-layer header when capturing on
2878 			 * ISDN devices....
2879 			 */
2880 			handle->linktype = DLT_RAW;
2881 		}
2882 		break;
2883 
2884 #ifndef ARPHRD_CISCO
2885 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2886 #endif
2887 	case ARPHRD_CISCO:
2888 		handle->linktype = DLT_C_HDLC;
2889 		break;
2890 
2891 	/* Not sure if this is correct for all tunnels, but it
2892 	 * works for CIPE */
2893 	case ARPHRD_TUNNEL:
2894 #ifndef ARPHRD_SIT
2895 #define ARPHRD_SIT 776	/* From Linux 2.2.13 */
2896 #endif
2897 	case ARPHRD_SIT:
2898 	case ARPHRD_CSLIP:
2899 	case ARPHRD_SLIP6:
2900 	case ARPHRD_CSLIP6:
2901 	case ARPHRD_ADAPT:
2902 	case ARPHRD_SLIP:
2903 #ifndef ARPHRD_RAWHDLC
2904 #define ARPHRD_RAWHDLC 518
2905 #endif
2906 	case ARPHRD_RAWHDLC:
2907 #ifndef ARPHRD_DLCI
2908 #define ARPHRD_DLCI 15
2909 #endif
2910 	case ARPHRD_DLCI:
2911 		/*
2912 		 * XXX - should some of those be mapped to DLT_LINUX_SLL
2913 		 * instead?  Should we just map all of them to DLT_LINUX_SLL?
2914 		 */
2915 		handle->linktype = DLT_RAW;
2916 		break;
2917 
2918 #ifndef ARPHRD_FRAD
2919 #define ARPHRD_FRAD 770
2920 #endif
2921 	case ARPHRD_FRAD:
2922 		handle->linktype = DLT_FRELAY;
2923 		break;
2924 
2925 	case ARPHRD_LOCALTLK:
2926 		handle->linktype = DLT_LTALK;
2927 		break;
2928 
2929 	case 18:
2930 		/*
2931 		 * RFC 4338 defines an encapsulation for IP and ARP
2932 		 * packets that's compatible with the RFC 2625
2933 		 * encapsulation, but that uses a different ARP
2934 		 * hardware type and hardware addresses.  That
2935 		 * ARP hardware type is 18; Linux doesn't define
2936 		 * any ARPHRD_ value as 18, but if it ever officially
2937 		 * supports RFC 4338-style IP-over-FC, it should define
2938 		 * one.
2939 		 *
2940 		 * For now, we map it to DLT_IP_OVER_FC, in the hopes
2941 		 * that this will encourage its use in the future,
2942 		 * should Linux ever officially support RFC 4338-style
2943 		 * IP-over-FC.
2944 		 */
2945 		handle->linktype = DLT_IP_OVER_FC;
2946 		break;
2947 
2948 #ifndef ARPHRD_FCPP
2949 #define ARPHRD_FCPP	784
2950 #endif
2951 	case ARPHRD_FCPP:
2952 #ifndef ARPHRD_FCAL
2953 #define ARPHRD_FCAL	785
2954 #endif
2955 	case ARPHRD_FCAL:
2956 #ifndef ARPHRD_FCPL
2957 #define ARPHRD_FCPL	786
2958 #endif
2959 	case ARPHRD_FCPL:
2960 #ifndef ARPHRD_FCFABRIC
2961 #define ARPHRD_FCFABRIC	787
2962 #endif
2963 	case ARPHRD_FCFABRIC:
2964 		/*
2965 		 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
2966 		 * IP-over-FC:
2967 		 *
2968 		 *	http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
2969 		 *
2970 		 * and one was assigned.
2971 		 *
2972 		 * In a later private discussion (spun off from a message
2973 		 * on the ethereal-users list) on how to get that DLT_
2974 		 * value in libpcap on Linux, I ended up deciding that
2975 		 * the best thing to do would be to have him tweak the
2976 		 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
2977 		 * type, and map all those types to DLT_IP_OVER_FC:
2978 		 *
2979 		 *	I've checked into the libpcap and tcpdump CVS tree
2980 		 *	support for DLT_IP_OVER_FC.  In order to use that,
2981 		 *	you'd have to modify your modified driver to return
2982 		 *	one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
2983 		 *	change it to set "dev->type" to ARPHRD_FCFABRIC, for
2984 		 *	example (the exact value doesn't matter, it can be
2985 		 *	any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
2986 		 *	ARPHRD_FCFABRIC).
2987 		 *
2988 		 * 11 years later, Christian Svensson wanted to map
2989 		 * various ARPHRD_ values to DLT_FC_2 and
2990 		 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
2991 		 * frames:
2992 		 *
2993 		 *	https://github.com/mcr/libpcap/pull/29
2994 		 *
2995 		 * There doesn't seem to be any network drivers that uses
2996 		 * any of the ARPHRD_FC* values for IP-over-FC, and
2997 		 * it's not exactly clear what the "Dummy types for non
2998 		 * ARP hardware" are supposed to mean (link-layer
2999 		 * header type?  Physical network type?), so it's
3000 		 * not exactly clear why the ARPHRD_FC* types exist
3001 		 * in the first place.
3002 		 *
3003 		 * For now, we map them to DLT_FC_2, and provide an
3004 		 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3005 		 * DLT_IP_OVER_FC just in case there's some old
3006 		 * driver out there that uses one of those types for
3007 		 * IP-over-FC on which somebody wants to capture
3008 		 * packets.
3009 		 */
3010 		handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
3011 		/*
3012 		 * If that fails, just leave the list empty.
3013 		 */
3014 		if (handle->dlt_list != NULL) {
3015 			handle->dlt_list[0] = DLT_FC_2;
3016 			handle->dlt_list[1] = DLT_FC_2_WITH_FRAME_DELIMS;
3017 			handle->dlt_list[2] = DLT_IP_OVER_FC;
3018 			handle->dlt_count = 3;
3019 		}
3020 		handle->linktype = DLT_FC_2;
3021 		break;
3022 
3023 #ifndef ARPHRD_IRDA
3024 #define ARPHRD_IRDA	783
3025 #endif
3026 	case ARPHRD_IRDA:
3027 		/* Don't expect IP packet out of this interfaces... */
3028 		handle->linktype = DLT_LINUX_IRDA;
3029 		/* We need to save packet direction for IrDA decoding,
3030 		 * so let's use "Linux-cooked" mode. Jean II
3031 		 *
3032 		 * XXX - this is handled in activate_new(). */
3033 		//handlep->cooked = 1;
3034 		break;
3035 
3036 	/* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3037 	 * is needed, please report it to <daniele@orlandi.com> */
3038 #ifndef ARPHRD_LAPD
3039 #define ARPHRD_LAPD	8445
3040 #endif
3041 	case ARPHRD_LAPD:
3042 		/* Don't expect IP packet out of this interfaces... */
3043 		handle->linktype = DLT_LINUX_LAPD;
3044 		break;
3045 
3046 #ifndef ARPHRD_NONE
3047 #define ARPHRD_NONE	0xFFFE
3048 #endif
3049 	case ARPHRD_NONE:
3050 		/*
3051 		 * No link-layer header; packets are just IP
3052 		 * packets, so use DLT_RAW.
3053 		 */
3054 		handle->linktype = DLT_RAW;
3055 		break;
3056 
3057 #ifndef ARPHRD_IEEE802154
3058 #define ARPHRD_IEEE802154      804
3059 #endif
3060        case ARPHRD_IEEE802154:
3061                handle->linktype =  DLT_IEEE802_15_4_NOFCS;
3062                break;
3063 
3064 #ifndef ARPHRD_NETLINK
3065 #define ARPHRD_NETLINK	824
3066 #endif
3067 	case ARPHRD_NETLINK:
3068 		handle->linktype = DLT_NETLINK;
3069 		/*
3070 		 * We need to use cooked mode, so that in sll_protocol we
3071 		 * pick up the netlink protocol type such as NETLINK_ROUTE,
3072 		 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3073 		 *
3074 		 * XXX - this is handled in activate_new().
3075 		 */
3076 		//handlep->cooked = 1;
3077 		break;
3078 
3079 	default:
3080 		handle->linktype = -1;
3081 		break;
3082 	}
3083 }
3084 
3085 /* ===== Functions to interface to the newer kernels ================== */
3086 
3087 /*
3088  * Try to open a packet socket using the new kernel PF_PACKET interface.
3089  * Returns 1 on success, 0 on an error that means the new interface isn't
3090  * present (so the old SOCK_PACKET interface should be tried), and a
3091  * PCAP_ERROR_ value on an error that means that the old mechanism won't
3092  * work either (so it shouldn't be tried).
3093  */
3094 static int
3095 activate_new(pcap_t *handle)
3096 {
3097 #ifdef HAVE_PF_PACKET_SOCKETS
3098 	struct pcap_linux *handlep = handle->priv;
3099 	const char		*device = handle->opt.source;
3100 	int			is_any_device = (strcmp(device, "any") == 0);
3101 	int			sock_fd = -1, arptype;
3102 #ifdef HAVE_PACKET_AUXDATA
3103 	int			val;
3104 #endif
3105 	int			err = 0;
3106 	struct packet_mreq	mr;
3107 #ifdef SO_BPF_EXTENSIONS
3108 	int			bpf_extensions;
3109 	socklen_t		len = sizeof(bpf_extensions);
3110 #endif
3111 
3112 	/*
3113 	 * Open a socket with protocol family packet. If the
3114 	 * "any" device was specified, we open a SOCK_DGRAM
3115 	 * socket for the cooked interface, otherwise we first
3116 	 * try a SOCK_RAW socket for the raw interface.
3117 	 */
3118 	sock_fd = is_any_device ?
3119 		socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
3120 		socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
3121 
3122 	if (sock_fd == -1) {
3123 		if (errno == EINVAL || errno == EAFNOSUPPORT) {
3124 			/*
3125 			 * We don't support PF_PACKET/SOCK_whatever
3126 			 * sockets; try the old mechanism.
3127 			 */
3128 			return 0;
3129 		}
3130 
3131 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
3132 			 pcap_strerror(errno) );
3133 		if (errno == EPERM || errno == EACCES) {
3134 			/*
3135 			 * You don't have permission to open the
3136 			 * socket.
3137 			 */
3138 			return PCAP_ERROR_PERM_DENIED;
3139 		} else {
3140 			/*
3141 			 * Other error.
3142 			 */
3143 			return PCAP_ERROR;
3144 		}
3145 	}
3146 
3147 	/* It seems the kernel supports the new interface. */
3148 	handlep->sock_packet = 0;
3149 
3150 	/*
3151 	 * Get the interface index of the loopback device.
3152 	 * If the attempt fails, don't fail, just set the
3153 	 * "handlep->lo_ifindex" to -1.
3154 	 *
3155 	 * XXX - can there be more than one device that loops
3156 	 * packets back, i.e. devices other than "lo"?  If so,
3157 	 * we'd need to find them all, and have an array of
3158 	 * indices for them, and check all of them in
3159 	 * "pcap_read_packet()".
3160 	 */
3161 	handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
3162 
3163 	/*
3164 	 * Default value for offset to align link-layer payload
3165 	 * on a 4-byte boundary.
3166 	 */
3167 	handle->offset	 = 0;
3168 
3169 	/*
3170 	 * What kind of frames do we have to deal with? Fall back
3171 	 * to cooked mode if we have an unknown interface type
3172 	 * or a type we know doesn't work well in raw mode.
3173 	 */
3174 	if (!is_any_device) {
3175 		/* Assume for now we don't need cooked mode. */
3176 		handlep->cooked = 0;
3177 
3178 		if (handle->opt.rfmon) {
3179 			/*
3180 			 * We were asked to turn on monitor mode.
3181 			 * Do so before we get the link-layer type,
3182 			 * because entering monitor mode could change
3183 			 * the link-layer type.
3184 			 */
3185 			err = enter_rfmon_mode(handle, sock_fd, device);
3186 			if (err < 0) {
3187 				/* Hard failure */
3188 				close(sock_fd);
3189 				return err;
3190 			}
3191 			if (err == 0) {
3192 				/*
3193 				 * Nothing worked for turning monitor mode
3194 				 * on.
3195 				 */
3196 				close(sock_fd);
3197 				return PCAP_ERROR_RFMON_NOTSUP;
3198 			}
3199 
3200 			/*
3201 			 * Either monitor mode has been turned on for
3202 			 * the device, or we've been given a different
3203 			 * device to open for monitor mode.  If we've
3204 			 * been given a different device, use it.
3205 			 */
3206 			if (handlep->mondevice != NULL)
3207 				device = handlep->mondevice;
3208 		}
3209 		arptype	= iface_get_arptype(sock_fd, device, handle->errbuf);
3210 		if (arptype < 0) {
3211 			close(sock_fd);
3212 			return arptype;
3213 		}
3214 		map_arphrd_to_dlt(handle, sock_fd, arptype, device, 1);
3215 		if (handle->linktype == -1 ||
3216 		    handle->linktype == DLT_LINUX_SLL ||
3217 		    handle->linktype == DLT_LINUX_IRDA ||
3218 		    handle->linktype == DLT_LINUX_LAPD ||
3219 		    handle->linktype == DLT_NETLINK ||
3220 		    (handle->linktype == DLT_EN10MB &&
3221 		     (strncmp("isdn", device, 4) == 0 ||
3222 		      strncmp("isdY", device, 4) == 0))) {
3223 			/*
3224 			 * Unknown interface type (-1), or a
3225 			 * device we explicitly chose to run
3226 			 * in cooked mode (e.g., PPP devices),
3227 			 * or an ISDN device (whose link-layer
3228 			 * type we can only determine by using
3229 			 * APIs that may be different on different
3230 			 * kernels) - reopen in cooked mode.
3231 			 */
3232 			if (close(sock_fd) == -1) {
3233 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3234 					 "close: %s", pcap_strerror(errno));
3235 				return PCAP_ERROR;
3236 			}
3237 			sock_fd = socket(PF_PACKET, SOCK_DGRAM,
3238 			    htons(ETH_P_ALL));
3239 			if (sock_fd == -1) {
3240 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3241 				    "socket: %s", pcap_strerror(errno));
3242 				if (errno == EPERM || errno == EACCES) {
3243 					/*
3244 					 * You don't have permission to
3245 					 * open the socket.
3246 					 */
3247 					return PCAP_ERROR_PERM_DENIED;
3248 				} else {
3249 					/*
3250 					 * Other error.
3251 					 */
3252 					return PCAP_ERROR;
3253 				}
3254 			}
3255 			handlep->cooked = 1;
3256 
3257 			/*
3258 			 * Get rid of any link-layer type list
3259 			 * we allocated - this only supports cooked
3260 			 * capture.
3261 			 */
3262 			if (handle->dlt_list != NULL) {
3263 				free(handle->dlt_list);
3264 				handle->dlt_list = NULL;
3265 				handle->dlt_count = 0;
3266 			}
3267 
3268 			if (handle->linktype == -1) {
3269 				/*
3270 				 * Warn that we're falling back on
3271 				 * cooked mode; we may want to
3272 				 * update "map_arphrd_to_dlt()"
3273 				 * to handle the new type.
3274 				 */
3275 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3276 					"arptype %d not "
3277 					"supported by libpcap - "
3278 					"falling back to cooked "
3279 					"socket",
3280 					arptype);
3281 			}
3282 
3283 			/*
3284 			 * IrDA capture is not a real "cooked" capture,
3285 			 * it's IrLAP frames, not IP packets.  The
3286 			 * same applies to LAPD capture.
3287 			 */
3288 			if (handle->linktype != DLT_LINUX_IRDA &&
3289 			    handle->linktype != DLT_LINUX_LAPD &&
3290 			    handle->linktype != DLT_NETLINK)
3291 				handle->linktype = DLT_LINUX_SLL;
3292 		}
3293 
3294 		handlep->ifindex = iface_get_id(sock_fd, device,
3295 		    handle->errbuf);
3296 		if (handlep->ifindex == -1) {
3297 			close(sock_fd);
3298 			return PCAP_ERROR;
3299 		}
3300 
3301 		if ((err = iface_bind(sock_fd, handlep->ifindex,
3302 		    handle->errbuf)) != 1) {
3303 		    	close(sock_fd);
3304 			if (err < 0)
3305 				return err;
3306 			else
3307 				return 0;	/* try old mechanism */
3308 		}
3309 	} else {
3310 		/*
3311 		 * The "any" device.
3312 		 */
3313 		if (handle->opt.rfmon) {
3314 			/*
3315 			 * It doesn't support monitor mode.
3316 			 */
3317 			close(sock_fd);
3318 			return PCAP_ERROR_RFMON_NOTSUP;
3319 		}
3320 
3321 		/*
3322 		 * It uses cooked mode.
3323 		 */
3324 		handlep->cooked = 1;
3325 		handle->linktype = DLT_LINUX_SLL;
3326 
3327 		/*
3328 		 * We're not bound to a device.
3329 		 * For now, we're using this as an indication
3330 		 * that we can't transmit; stop doing that only
3331 		 * if we figure out how to transmit in cooked
3332 		 * mode.
3333 		 */
3334 		handlep->ifindex = -1;
3335 	}
3336 
3337 	/*
3338 	 * Select promiscuous mode on if "promisc" is set.
3339 	 *
3340 	 * Do not turn allmulti mode on if we don't select
3341 	 * promiscuous mode - on some devices (e.g., Orinoco
3342 	 * wireless interfaces), allmulti mode isn't supported
3343 	 * and the driver implements it by turning promiscuous
3344 	 * mode on, and that screws up the operation of the
3345 	 * card as a normal networking interface, and on no
3346 	 * other platform I know of does starting a non-
3347 	 * promiscuous capture affect which multicast packets
3348 	 * are received by the interface.
3349 	 */
3350 
3351 	/*
3352 	 * Hmm, how can we set promiscuous mode on all interfaces?
3353 	 * I am not sure if that is possible at all.  For now, we
3354 	 * silently ignore attempts to turn promiscuous mode on
3355 	 * for the "any" device (so you don't have to explicitly
3356 	 * disable it in programs such as tcpdump).
3357 	 */
3358 
3359 	if (!is_any_device && handle->opt.promisc) {
3360 		memset(&mr, 0, sizeof(mr));
3361 		mr.mr_ifindex = handlep->ifindex;
3362 		mr.mr_type    = PACKET_MR_PROMISC;
3363 		if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
3364 		    &mr, sizeof(mr)) == -1) {
3365 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3366 				"setsockopt: %s", pcap_strerror(errno));
3367 			close(sock_fd);
3368 			return PCAP_ERROR;
3369 		}
3370 	}
3371 
3372 	/* Enable auxillary data if supported and reserve room for
3373 	 * reconstructing VLAN headers. */
3374 #ifdef HAVE_PACKET_AUXDATA
3375 	val = 1;
3376 	if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
3377 		       sizeof(val)) == -1 && errno != ENOPROTOOPT) {
3378 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3379 			 "setsockopt: %s", pcap_strerror(errno));
3380 		close(sock_fd);
3381 		return PCAP_ERROR;
3382 	}
3383 	handle->offset += VLAN_TAG_LEN;
3384 #endif /* HAVE_PACKET_AUXDATA */
3385 
3386 	/*
3387 	 * This is a 2.2[.x] or later kernel (we know that
3388 	 * because we're not using a SOCK_PACKET socket -
3389 	 * PF_PACKET is supported only in 2.2 and later
3390 	 * kernels).
3391 	 *
3392 	 * We can safely pass "recvfrom()" a byte count
3393 	 * based on the snapshot length.
3394 	 *
3395 	 * If we're in cooked mode, make the snapshot length
3396 	 * large enough to hold a "cooked mode" header plus
3397 	 * 1 byte of packet data (so we don't pass a byte
3398 	 * count of 0 to "recvfrom()").
3399 	 */
3400 	if (handlep->cooked) {
3401 		if (handle->snapshot < SLL_HDR_LEN + 1)
3402 			handle->snapshot = SLL_HDR_LEN + 1;
3403 	}
3404 	handle->bufsize = handle->snapshot;
3405 
3406 	/*
3407 	 * Set the offset at which to insert VLAN tags.
3408 	 */
3409 	switch (handle->linktype) {
3410 
3411 	case DLT_EN10MB:
3412 		handlep->vlan_offset = 2 * ETH_ALEN;
3413 		break;
3414 
3415 	case DLT_LINUX_SLL:
3416 		handlep->vlan_offset = 14;
3417 		break;
3418 
3419 	default:
3420 		handlep->vlan_offset = -1; /* unknown */
3421 		break;
3422 	}
3423 
3424 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
3425 	if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
3426 		int nsec_tstamps = 1;
3427 
3428 		if (setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)) < 0) {
3429 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "setsockopt: unable to set SO_TIMESTAMPNS");
3430 			close(sock_fd);
3431 			return PCAP_ERROR;
3432 		}
3433 	}
3434 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
3435 
3436 	/*
3437 	 * We've succeeded. Save the socket FD in the pcap structure.
3438 	 */
3439 	handle->fd = sock_fd;
3440 
3441 #ifdef SO_BPF_EXTENSIONS
3442 	/*
3443 	 * Can we generate special code for VLAN checks?
3444 	 * (XXX - what if we need the special code but it's not supported
3445 	 * by the OS?  Is that possible?)
3446 	 */
3447 	if (getsockopt(sock_fd, SOL_SOCKET, SO_BPF_EXTENSIONS,
3448 	    &bpf_extensions, &len) == 0) {
3449 		if (bpf_extensions >= SKF_AD_VLAN_TAG_PRESENT) {
3450 			/*
3451 			 * Yes, we can.  Request that we do so.
3452 			 */
3453 			handle->bpf_codegen_flags |= BPF_SPECIAL_VLAN_HANDLING;
3454 		}
3455 	}
3456 #endif /* SO_BPF_EXTENSIONS */
3457 
3458 	return 1;
3459 #else /* HAVE_PF_PACKET_SOCKETS */
3460 	strlcpy(ebuf,
3461 		"New packet capturing interface not supported by build "
3462 		"environment", PCAP_ERRBUF_SIZE);
3463 	return 0;
3464 #endif /* HAVE_PF_PACKET_SOCKETS */
3465 }
3466 
3467 #ifdef HAVE_PACKET_RING
3468 /*
3469  * Attempt to activate with memory-mapped access.
3470  *
3471  * On success, returns 1, and sets *status to 0 if there are no warnings
3472  * or to a PCAP_WARNING_ code if there is a warning.
3473  *
3474  * On failure due to lack of support for memory-mapped capture, returns
3475  * 0.
3476  *
3477  * On error, returns -1, and sets *status to the appropriate error code;
3478  * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3479  */
3480 static int
3481 activate_mmap(pcap_t *handle, int *status)
3482 {
3483 	struct pcap_linux *handlep = handle->priv;
3484 	int ret;
3485 
3486 	/*
3487 	 * Attempt to allocate a buffer to hold the contents of one
3488 	 * packet, for use by the oneshot callback.
3489 	 */
3490 	handlep->oneshot_buffer = malloc(handle->snapshot);
3491 	if (handlep->oneshot_buffer == NULL) {
3492 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3493 			 "can't allocate oneshot buffer: %s",
3494 			 pcap_strerror(errno));
3495 		*status = PCAP_ERROR;
3496 		return -1;
3497 	}
3498 
3499 	if (handle->opt.buffer_size == 0) {
3500 		/* by default request 2M for the ring buffer */
3501 		handle->opt.buffer_size = 2*1024*1024;
3502 	}
3503 	ret = prepare_tpacket_socket(handle);
3504 	if (ret == -1) {
3505 		free(handlep->oneshot_buffer);
3506 		*status = PCAP_ERROR;
3507 		return ret;
3508 	}
3509 	ret = create_ring(handle, status);
3510 	if (ret == 0) {
3511 		/*
3512 		 * We don't support memory-mapped capture; our caller
3513 		 * will fall back on reading from the socket.
3514 		 */
3515 		free(handlep->oneshot_buffer);
3516 		return 0;
3517 	}
3518 	if (ret == -1) {
3519 		/*
3520 		 * Error attempting to enable memory-mapped capture;
3521 		 * fail.  create_ring() has set *status.
3522 		 */
3523 		free(handlep->oneshot_buffer);
3524 		return -1;
3525 	}
3526 
3527 	/*
3528 	 * Success.  *status has been set either to 0 if there are no
3529 	 * warnings or to a PCAP_WARNING_ value if there is a warning.
3530 	 *
3531 	 * Override some defaults and inherit the other fields from
3532 	 * activate_new.
3533 	 * handle->offset is used to get the current position into the rx ring.
3534 	 * handle->cc is used to store the ring size.
3535 	 */
3536 
3537 	switch (handlep->tp_version) {
3538 	case TPACKET_V1:
3539 		handle->read_op = pcap_read_linux_mmap_v1;
3540 		break;
3541 	case TPACKET_V1_64:
3542 		handle->read_op = pcap_read_linux_mmap_v1_64;
3543 		break;
3544 #ifdef HAVE_TPACKET2
3545 	case TPACKET_V2:
3546 		handle->read_op = pcap_read_linux_mmap_v2;
3547 		break;
3548 #endif
3549 #ifdef HAVE_TPACKET3
3550 	case TPACKET_V3:
3551 		handle->read_op = pcap_read_linux_mmap_v3;
3552 		break;
3553 #endif
3554 	}
3555 	handle->cleanup_op = pcap_cleanup_linux_mmap;
3556 	handle->setfilter_op = pcap_setfilter_linux_mmap;
3557 	handle->setnonblock_op = pcap_setnonblock_mmap;
3558 	handle->getnonblock_op = pcap_getnonblock_mmap;
3559 	handle->oneshot_callback = pcap_oneshot_mmap;
3560 	handle->selectable_fd = handle->fd;
3561 	return 1;
3562 }
3563 #else /* HAVE_PACKET_RING */
3564 static int
3565 activate_mmap(pcap_t *handle _U_, int *status _U_)
3566 {
3567 	return 0;
3568 }
3569 #endif /* HAVE_PACKET_RING */
3570 
3571 #ifdef HAVE_PACKET_RING
3572 
3573 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3574 /*
3575  * Attempt to set the socket to the specified version of the memory-mapped
3576  * header.
3577  *
3578  * Return 0 if we succeed; return 1 if we fail because that version isn't
3579  * supported; return -1 on any other error, and set handle->errbuf.
3580  */
3581 static int
3582 init_tpacket(pcap_t *handle, int version, const char *version_str)
3583 {
3584 	struct pcap_linux *handlep = handle->priv;
3585 	int val = version;
3586 	socklen_t len = sizeof(val);
3587 
3588 	/*
3589 	 * Probe whether kernel supports the specified TPACKET version;
3590 	 * this also gets the length of the header for that version.
3591 	 */
3592 	if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
3593 		if (errno == ENOPROTOOPT || errno == EINVAL)
3594 			return 1;	/* no */
3595 
3596 		/* Failed to even find out; this is a fatal error. */
3597 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3598 			"can't get %s header len on packet socket: %s",
3599 			version_str,
3600 			pcap_strerror(errno));
3601 		return -1;
3602 	}
3603 	handlep->tp_hdrlen = val;
3604 
3605 	val = version;
3606 	if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
3607 			   sizeof(val)) < 0) {
3608 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3609 			"can't activate %s on packet socket: %s",
3610 			version_str,
3611 			pcap_strerror(errno));
3612 		return -1;
3613 	}
3614 	handlep->tp_version = version;
3615 
3616 	/* Reserve space for VLAN tag reconstruction */
3617 	val = VLAN_TAG_LEN;
3618 	if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
3619 			   sizeof(val)) < 0) {
3620 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3621 			"can't set up reserve on packet socket: %s",
3622 			pcap_strerror(errno));
3623 		return -1;
3624 	}
3625 
3626 	return 0;
3627 }
3628 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
3629 
3630 /*
3631  * If the instruction set for which we're compiling has both 32-bit
3632  * and 64-bit versions, and Linux support for the 64-bit version
3633  * predates TPACKET_V2, define ISA_64_BIT as the .machine value
3634  * you get from uname() for the 64-bit version.  Otherwise, leave
3635  * it undefined.  (This includes ARM, which has a 64-bit version,
3636  * but Linux support for it appeared well after TPACKET_V2 support
3637  * did, so there should never be a case where 32-bit ARM code is
3638  * running o a 64-bit kernel that only supports TPACKET_V1.)
3639  *
3640  * If we've omitted your favorite such architecture, please contribute
3641  * a patch.  (No patch is needed for architectures that are 32-bit-only
3642  * or for which Linux has no support for 32-bit userland - or for which,
3643  * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
3644  * did.)
3645  */
3646 #if defined(__i386__)
3647 #define ISA_64_BIT	"x86_64"
3648 #elif defined(__ppc__)
3649 #define ISA_64_BIT	"ppc64"
3650 #elif defined(__sparc__)
3651 #define ISA_64_BIT	"sparc64"
3652 #elif defined(__s390__)
3653 #define ISA_64_BIT	"s390x"
3654 #elif defined(__mips__)
3655 #define ISA_64_BIT	"mips64"
3656 #elif defined(__hppa__)
3657 #define ISA_64_BIT	"parisc64"
3658 #endif
3659 
3660 /*
3661  * Attempt to set the socket to version 3 of the memory-mapped header and,
3662  * if that fails because version 3 isn't supported, attempt to fall
3663  * back to version 2.  If version 2 isn't supported, just leave it at
3664  * version 1.
3665  *
3666  * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
3667  * supported; return -1 on any other error, and set handle->errbuf.
3668  */
3669 static int
3670 prepare_tpacket_socket(pcap_t *handle)
3671 {
3672 	struct pcap_linux *handlep = handle->priv;
3673 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
3674 	int ret;
3675 #endif
3676 
3677 #ifdef HAVE_TPACKET3
3678 	/*
3679 	 * Try setting the version to TPACKET_V3.
3680 	 *
3681 	 * The only mode in which buffering is done on PF_PACKET
3682 	 * sockets, so that packets might not be delivered
3683 	 * immediately, is TPACKET_V3 mode.
3684 	 *
3685 	 * The buffering cannot be disabled in that mode, so
3686 	 * if the user has requested immediate mode, we don't
3687 	 * use TPACKET_V3.
3688 	 */
3689 	if (!handle->opt.immediate) {
3690 		ret = init_tpacket(handle, TPACKET_V3, "TPACKET_V3");
3691 		if (ret == 0) {
3692 			/*
3693 			 * Success.
3694 			 */
3695 			return 1;
3696 		}
3697 		if (ret == -1) {
3698 			/*
3699 			 * We failed for some reason other than "the
3700 			 * kernel doesn't support TPACKET_V3".
3701 			 */
3702 			return -1;
3703 		}
3704 	}
3705 #endif /* HAVE_TPACKET3 */
3706 
3707 #ifdef HAVE_TPACKET2
3708 	/*
3709 	 * Try setting the version to TPACKET_V2.
3710 	 */
3711 	ret = init_tpacket(handle, TPACKET_V2, "TPACKET_V2");
3712 	if (ret == 0) {
3713 		/*
3714 		 * Success.
3715 		 */
3716 		return 1;
3717 	}
3718 	if (ret == -1) {
3719 		/*
3720 		 * We failed for some reason other than "the
3721 		 * kernel doesn't support TPACKET_V2".
3722 		 */
3723 		return -1;
3724 	}
3725 #endif /* HAVE_TPACKET2 */
3726 
3727 	/*
3728 	 * OK, we're using TPACKET_V1, as that's all the kernel supports.
3729 	 */
3730 	handlep->tp_version = TPACKET_V1;
3731 	handlep->tp_hdrlen = sizeof(struct tpacket_hdr);
3732 
3733 #ifdef ISA_64_BIT
3734 	/*
3735 	 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
3736 	 * each other due to platform-dependent data type size differences.
3737 	 *
3738 	 * If we have a 32-bit userland and a 64-bit kernel, use an
3739 	 * internally-defined TPACKET_V1_64, with which we use a 64-bit
3740 	 * version of the data structures.
3741 	 */
3742 	if (sizeof(long) == 4) {
3743 		/*
3744 		 * This is 32-bit code.
3745 		 */
3746 		struct utsname utsname;
3747 
3748 		if (uname(&utsname) == -1) {
3749 			/*
3750 			 * Failed.
3751 			 */
3752 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3753 			    "uname failed: %s", pcap_strerror(errno));
3754 			return -1;
3755 		}
3756 		if (strcmp(utsname.machine, ISA_64_BIT) == 0) {
3757 			/*
3758 			 * uname() tells us the machine is 64-bit,
3759 			 * so we presumably have a 64-bit kernel.
3760 			 *
3761 			 * XXX - this presumes that uname() won't lie
3762 			 * in 32-bit code and claim that the machine
3763 			 * has the 32-bit version of the ISA.
3764 			 */
3765 			handlep->tp_version = TPACKET_V1_64;
3766 			handlep->tp_hdrlen = sizeof(struct tpacket_hdr_64);
3767 		}
3768 	}
3769 #endif
3770 
3771 	return 1;
3772 }
3773 
3774 /*
3775  * Attempt to set up memory-mapped access.
3776  *
3777  * On success, returns 1, and sets *status to 0 if there are no warnings
3778  * or to a PCAP_WARNING_ code if there is a warning.
3779  *
3780  * On failure due to lack of support for memory-mapped capture, returns
3781  * 0.
3782  *
3783  * On error, returns -1, and sets *status to the appropriate error code;
3784  * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3785  */
3786 static int
3787 create_ring(pcap_t *handle, int *status)
3788 {
3789 	struct pcap_linux *handlep = handle->priv;
3790 	unsigned i, j, frames_per_block;
3791 #ifdef HAVE_TPACKET3
3792 	/*
3793 	 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
3794 	 * stuff at the end of a struct tpacket_req3 will be
3795 	 * ignored, so this is OK even for those sockets.
3796 	 */
3797 	struct tpacket_req3 req;
3798 #else
3799 	struct tpacket_req req;
3800 #endif
3801 	socklen_t len;
3802 	unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
3803 	unsigned int frame_size;
3804 
3805 	/*
3806 	 * Start out assuming no warnings or errors.
3807 	 */
3808 	*status = 0;
3809 
3810 	switch (handlep->tp_version) {
3811 
3812 	case TPACKET_V1:
3813 	case TPACKET_V1_64:
3814 #ifdef HAVE_TPACKET2
3815 	case TPACKET_V2:
3816 #endif
3817 		/* Note that with large snapshot length (say 64K, which is
3818 		 * the default for recent versions of tcpdump, the value that
3819 		 * "-s 0" has given for a long time with tcpdump, and the
3820 		 * default in Wireshark/TShark/dumpcap), if we use the snapshot
3821 		 * length to calculate the frame length, only a few frames
3822 		 * will be available in the ring even with pretty
3823 		 * large ring size (and a lot of memory will be unused).
3824 		 *
3825 		 * Ideally, we should choose a frame length based on the
3826 		 * minimum of the specified snapshot length and the maximum
3827 		 * packet size.  That's not as easy as it sounds; consider,
3828 		 * for example, an 802.11 interface in monitor mode, where
3829 		 * the frame would include a radiotap header, where the
3830 		 * maximum radiotap header length is device-dependent.
3831 		 *
3832 		 * So, for now, we just do this for Ethernet devices, where
3833 		 * there's no metadata header, and the link-layer header is
3834 		 * fixed length.  We can get the maximum packet size by
3835 		 * adding 18, the Ethernet header length plus the CRC length
3836 		 * (just in case we happen to get the CRC in the packet), to
3837 		 * the MTU of the interface; we fetch the MTU in the hopes
3838 		 * that it reflects support for jumbo frames.  (Even if the
3839 		 * interface is just being used for passive snooping, the
3840 		 * driver might set the size of buffers in the receive ring
3841 		 * based on the MTU, so that the MTU limits the maximum size
3842 		 * of packets that we can receive.)
3843 		 *
3844 		 * We don't do that if segmentation/fragmentation or receive
3845 		 * offload are enabled, so we don't get rudely surprised by
3846 		 * "packets" bigger than the MTU. */
3847 		frame_size = handle->snapshot;
3848 		if (handle->linktype == DLT_EN10MB) {
3849 			int mtu;
3850 			int offload;
3851 
3852 			offload = iface_get_offload(handle);
3853 			if (offload == -1) {
3854 				*status = PCAP_ERROR;
3855 				return -1;
3856 			}
3857 			if (!offload) {
3858 				mtu = iface_get_mtu(handle->fd, handle->opt.source,
3859 				    handle->errbuf);
3860 				if (mtu == -1) {
3861 					*status = PCAP_ERROR;
3862 					return -1;
3863 				}
3864 				if (frame_size > mtu + 18)
3865 					frame_size = mtu + 18;
3866 			}
3867 		}
3868 
3869 		/* NOTE: calculus matching those in tpacket_rcv()
3870 		 * in linux-2.6/net/packet/af_packet.c
3871 		 */
3872 		len = sizeof(sk_type);
3873 		if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type,
3874 		    &len) < 0) {
3875 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3876 			    "getsockopt: %s", pcap_strerror(errno));
3877 			*status = PCAP_ERROR;
3878 			return -1;
3879 		}
3880 #ifdef PACKET_RESERVE
3881 		len = sizeof(tp_reserve);
3882 		if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
3883 		    &tp_reserve, &len) < 0) {
3884 			if (errno != ENOPROTOOPT) {
3885 				/*
3886 				 * ENOPROTOOPT means "kernel doesn't support
3887 				 * PACKET_RESERVE", in which case we fall back
3888 				 * as best we can.
3889 				 */
3890 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3891 				    "getsockopt: %s", pcap_strerror(errno));
3892 				*status = PCAP_ERROR;
3893 				return -1;
3894 			}
3895 			tp_reserve = 0;	/* older kernel, reserve not supported */
3896 		}
3897 #else
3898 		tp_reserve = 0;	/* older kernel, reserve not supported */
3899 #endif
3900 		maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
3901 			/* XXX: in the kernel maclen is calculated from
3902 			 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3903 			 * in:  packet_snd()           in linux-2.6/net/packet/af_packet.c
3904 			 * then packet_alloc_skb()     in linux-2.6/net/packet/af_packet.c
3905 			 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3906 			 * but I see no way to get those sizes in userspace,
3907 			 * like for instance with an ifreq ioctl();
3908 			 * the best thing I've found so far is MAX_HEADER in
3909 			 * the kernel part of linux-2.6/include/linux/netdevice.h
3910 			 * which goes up to 128+48=176; since pcap-linux.c
3911 			 * defines a MAX_LINKHEADER_SIZE of 256 which is
3912 			 * greater than that, let's use it.. maybe is it even
3913 			 * large enough to directly replace macoff..
3914 			 */
3915 		tp_hdrlen = TPACKET_ALIGN(handlep->tp_hdrlen) + sizeof(struct sockaddr_ll) ;
3916 		netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
3917 			/* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
3918 			 * of netoff, which contradicts
3919 			 * linux-2.6/Documentation/networking/packet_mmap.txt
3920 			 * documenting that:
3921 			 * "- Gap, chosen so that packet data (Start+tp_net)
3922 			 * aligns to TPACKET_ALIGNMENT=16"
3923 			 */
3924 			/* NOTE: in linux-2.6/include/linux/skbuff.h:
3925 			 * "CPUs often take a performance hit
3926 			 *  when accessing unaligned memory locations"
3927 			 */
3928 		macoff = netoff - maclen;
3929 		req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
3930 		req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
3931 		break;
3932 
3933 #ifdef HAVE_TPACKET3
3934 	case TPACKET_V3:
3935 		/* The "frames" for this are actually buffers that
3936 		 * contain multiple variable-sized frames.
3937 		 *
3938 		 * We pick a "frame" size of 128K to leave enough
3939 		 * room for at least one reasonably-sized packet
3940 		 * in the "frame". */
3941 		req.tp_frame_size = MAXIMUM_SNAPLEN;
3942 		req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
3943 		break;
3944 #endif
3945 	default:
3946 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3947 		    "Internal error: unknown TPACKET_ value %u",
3948 		    handlep->tp_version);
3949 		*status = PCAP_ERROR;
3950 		return -1;
3951 	}
3952 
3953 	/* compute the minumum block size that will handle this frame.
3954 	 * The block has to be page size aligned.
3955 	 * The max block size allowed by the kernel is arch-dependent and
3956 	 * it's not explicitly checked here. */
3957 	req.tp_block_size = getpagesize();
3958 	while (req.tp_block_size < req.tp_frame_size)
3959 		req.tp_block_size <<= 1;
3960 
3961 	frames_per_block = req.tp_block_size/req.tp_frame_size;
3962 
3963 	/*
3964 	 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3965 	 * so we check for PACKET_TIMESTAMP.  We check for
3966 	 * linux/net_tstamp.h just in case a system somehow has
3967 	 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3968 	 * be unnecessary.
3969 	 *
3970 	 * SIOCSHWTSTAMP was introduced in the patch that introduced
3971 	 * linux/net_tstamp.h, so we don't bother checking whether
3972 	 * SIOCSHWTSTAMP is defined (if your Linux system has
3973 	 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3974 	 * Linux system is badly broken).
3975 	 */
3976 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3977 	/*
3978 	 * If we were told to do so, ask the kernel and the driver
3979 	 * to use hardware timestamps.
3980 	 *
3981 	 * Hardware timestamps are only supported with mmapped
3982 	 * captures.
3983 	 */
3984 	if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
3985 	    handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
3986 		struct hwtstamp_config hwconfig;
3987 		struct ifreq ifr;
3988 		int timesource;
3989 
3990 		/*
3991 		 * Ask for hardware time stamps on all packets,
3992 		 * including transmitted packets.
3993 		 */
3994 		memset(&hwconfig, 0, sizeof(hwconfig));
3995 		hwconfig.tx_type = HWTSTAMP_TX_ON;
3996 		hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
3997 
3998 		memset(&ifr, 0, sizeof(ifr));
3999 		strlcpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
4000 		ifr.ifr_data = (void *)&hwconfig;
4001 
4002 		if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
4003 			switch (errno) {
4004 
4005 			case EPERM:
4006 				/*
4007 				 * Treat this as an error, as the
4008 				 * user should try to run this
4009 				 * with the appropriate privileges -
4010 				 * and, if they can't, shouldn't
4011 				 * try requesting hardware time stamps.
4012 				 */
4013 				*status = PCAP_ERROR_PERM_DENIED;
4014 				return -1;
4015 
4016 			case EOPNOTSUPP:
4017 				/*
4018 				 * Treat this as a warning, as the
4019 				 * only way to fix the warning is to
4020 				 * get an adapter that supports hardware
4021 				 * time stamps.  We'll just fall back
4022 				 * on the standard host time stamps.
4023 				 */
4024 				*status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
4025 				break;
4026 
4027 			default:
4028 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4029 					"SIOCSHWTSTAMP failed: %s",
4030 					pcap_strerror(errno));
4031 				*status = PCAP_ERROR;
4032 				return -1;
4033 			}
4034 		} else {
4035 			/*
4036 			 * Well, that worked.  Now specify the type of
4037 			 * hardware time stamp we want for this
4038 			 * socket.
4039 			 */
4040 			if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
4041 				/*
4042 				 * Hardware timestamp, synchronized
4043 				 * with the system clock.
4044 				 */
4045 				timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
4046 			} else {
4047 				/*
4048 				 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4049 				 * timestamp, not synchronized with the
4050 				 * system clock.
4051 				 */
4052 				timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
4053 			}
4054 			if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
4055 				(void *)&timesource, sizeof(timesource))) {
4056 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4057 					"can't set PACKET_TIMESTAMP: %s",
4058 					pcap_strerror(errno));
4059 				*status = PCAP_ERROR;
4060 				return -1;
4061 			}
4062 		}
4063 	}
4064 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4065 
4066 	/* ask the kernel to create the ring */
4067 retry:
4068 	req.tp_block_nr = req.tp_frame_nr / frames_per_block;
4069 
4070 	/* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4071 	req.tp_frame_nr = req.tp_block_nr * frames_per_block;
4072 
4073 #ifdef HAVE_TPACKET3
4074 	/* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4075 	req.tp_retire_blk_tov = (handlep->timeout>=0)?handlep->timeout:0;
4076 	/* private data not used */
4077 	req.tp_sizeof_priv = 0;
4078 	/* Rx ring - feature request bits - none (rxhash will not be filled) */
4079 	req.tp_feature_req_word = 0;
4080 #endif
4081 
4082 	if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
4083 					(void *) &req, sizeof(req))) {
4084 		if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
4085 			/*
4086 			 * Memory failure; try to reduce the requested ring
4087 			 * size.
4088 			 *
4089 			 * We used to reduce this by half -- do 5% instead.
4090 			 * That may result in more iterations and a longer
4091 			 * startup, but the user will be much happier with
4092 			 * the resulting buffer size.
4093 			 */
4094 			if (req.tp_frame_nr < 20)
4095 				req.tp_frame_nr -= 1;
4096 			else
4097 				req.tp_frame_nr -= req.tp_frame_nr/20;
4098 			goto retry;
4099 		}
4100 		if (errno == ENOPROTOOPT) {
4101 			/*
4102 			 * We don't have ring buffer support in this kernel.
4103 			 */
4104 			return 0;
4105 		}
4106 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4107 		    "can't create rx ring on packet socket: %s",
4108 		    pcap_strerror(errno));
4109 		*status = PCAP_ERROR;
4110 		return -1;
4111 	}
4112 
4113 	/* memory map the rx ring */
4114 	handlep->mmapbuflen = req.tp_block_nr * req.tp_block_size;
4115 	handlep->mmapbuf = mmap(0, handlep->mmapbuflen,
4116 	    PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
4117 	if (handlep->mmapbuf == MAP_FAILED) {
4118 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4119 		    "can't mmap rx ring: %s", pcap_strerror(errno));
4120 
4121 		/* clear the allocated ring on error*/
4122 		destroy_ring(handle);
4123 		*status = PCAP_ERROR;
4124 		return -1;
4125 	}
4126 
4127 	/* allocate a ring for each frame header pointer*/
4128 	handle->cc = req.tp_frame_nr;
4129 	handle->buffer = malloc(handle->cc * sizeof(union thdr *));
4130 	if (!handle->buffer) {
4131 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4132 		    "can't allocate ring of frame headers: %s",
4133 		    pcap_strerror(errno));
4134 
4135 		destroy_ring(handle);
4136 		*status = PCAP_ERROR;
4137 		return -1;
4138 	}
4139 
4140 	/* fill the header ring with proper frame ptr*/
4141 	handle->offset = 0;
4142 	for (i=0; i<req.tp_block_nr; ++i) {
4143 		void *base = &handlep->mmapbuf[i*req.tp_block_size];
4144 		for (j=0; j<frames_per_block; ++j, ++handle->offset) {
4145 			RING_GET_FRAME(handle) = base;
4146 			base += req.tp_frame_size;
4147 		}
4148 	}
4149 
4150 	handle->bufsize = req.tp_frame_size;
4151 	handle->offset = 0;
4152 	return 1;
4153 }
4154 
4155 /* free all ring related resources*/
4156 static void
4157 destroy_ring(pcap_t *handle)
4158 {
4159 	struct pcap_linux *handlep = handle->priv;
4160 
4161 	/* tell the kernel to destroy the ring*/
4162 	struct tpacket_req req;
4163 	memset(&req, 0, sizeof(req));
4164 	/* do not test for setsockopt failure, as we can't recover from any error */
4165 	(void)setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
4166 				(void *) &req, sizeof(req));
4167 
4168 	/* if ring is mapped, unmap it*/
4169 	if (handlep->mmapbuf) {
4170 		/* do not test for mmap failure, as we can't recover from any error */
4171 		(void)munmap(handlep->mmapbuf, handlep->mmapbuflen);
4172 		handlep->mmapbuf = NULL;
4173 	}
4174 }
4175 
4176 /*
4177  * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4178  * for Linux mmapped capture.
4179  *
4180  * The problem is that pcap_next() and pcap_next_ex() expect the packet
4181  * data handed to the callback to be valid after the callback returns,
4182  * but pcap_read_linux_mmap() has to release that packet as soon as
4183  * the callback returns (otherwise, the kernel thinks there's still
4184  * at least one unprocessed packet available in the ring, so a select()
4185  * will immediately return indicating that there's data to process), so,
4186  * in the callback, we have to make a copy of the packet.
4187  *
4188  * Yes, this means that, if the capture is using the ring buffer, using
4189  * pcap_next() or pcap_next_ex() requires more copies than using
4190  * pcap_loop() or pcap_dispatch().  If that bothers you, don't use
4191  * pcap_next() or pcap_next_ex().
4192  */
4193 static void
4194 pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
4195     const u_char *bytes)
4196 {
4197 	struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
4198 	pcap_t *handle = sp->pd;
4199 	struct pcap_linux *handlep = handle->priv;
4200 
4201 	*sp->hdr = *h;
4202 	memcpy(handlep->oneshot_buffer, bytes, h->caplen);
4203 	*sp->pkt = handlep->oneshot_buffer;
4204 }
4205 
4206 static void
4207 pcap_cleanup_linux_mmap( pcap_t *handle )
4208 {
4209 	struct pcap_linux *handlep = handle->priv;
4210 
4211 	destroy_ring(handle);
4212 	if (handlep->oneshot_buffer != NULL) {
4213 		free(handlep->oneshot_buffer);
4214 		handlep->oneshot_buffer = NULL;
4215 	}
4216 	pcap_cleanup_linux(handle);
4217 }
4218 
4219 
4220 static int
4221 pcap_getnonblock_mmap(pcap_t *p, char *errbuf)
4222 {
4223 	struct pcap_linux *handlep = p->priv;
4224 
4225 	/* use negative value of timeout to indicate non blocking ops */
4226 	return (handlep->timeout<0);
4227 }
4228 
4229 static int
4230 pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
4231 {
4232 	struct pcap_linux *handlep = p->priv;
4233 
4234 	/*
4235 	 * Set the file descriptor to non-blocking mode, as we use
4236 	 * it for sending packets.
4237 	 */
4238 	if (pcap_setnonblock_fd(p, nonblock, errbuf) == -1)
4239 		return -1;
4240 
4241 	/*
4242 	 * Map each value to their corresponding negation to
4243 	 * preserve the timeout value provided with pcap_set_timeout.
4244 	 */
4245 	if (nonblock) {
4246 		if (handlep->timeout >= 0) {
4247 			/*
4248 			 * Indicate that we're switching to
4249 			 * non-blocking mode.
4250 			 */
4251 			handlep->timeout = ~handlep->timeout;
4252 		}
4253 	} else {
4254 		if (handlep->timeout < 0) {
4255 			handlep->timeout = ~handlep->timeout;
4256 		}
4257 	}
4258 	return 0;
4259 }
4260 
4261 static inline union thdr *
4262 pcap_get_ring_frame(pcap_t *handle, int status)
4263 {
4264 	struct pcap_linux *handlep = handle->priv;
4265 	union thdr h;
4266 
4267 	h.raw = RING_GET_FRAME(handle);
4268 	switch (handlep->tp_version) {
4269 	case TPACKET_V1:
4270 		if (status != (h.h1->tp_status ? TP_STATUS_USER :
4271 						TP_STATUS_KERNEL))
4272 			return NULL;
4273 		break;
4274 	case TPACKET_V1_64:
4275 		if (status != (h.h1_64->tp_status ? TP_STATUS_USER :
4276 						TP_STATUS_KERNEL))
4277 			return NULL;
4278 		break;
4279 #ifdef HAVE_TPACKET2
4280 	case TPACKET_V2:
4281 		if (status != (h.h2->tp_status ? TP_STATUS_USER :
4282 						TP_STATUS_KERNEL))
4283 			return NULL;
4284 		break;
4285 #endif
4286 #ifdef HAVE_TPACKET3
4287 	case TPACKET_V3:
4288 		if (status != (h.h3->hdr.bh1.block_status ? TP_STATUS_USER :
4289 						TP_STATUS_KERNEL))
4290 			return NULL;
4291 		break;
4292 #endif
4293 	}
4294 	return h.raw;
4295 }
4296 
4297 #ifndef POLLRDHUP
4298 #define POLLRDHUP 0
4299 #endif
4300 
4301 /* wait for frames availability.*/
4302 static int pcap_wait_for_frames_mmap(pcap_t *handle)
4303 {
4304 	if (!pcap_get_ring_frame(handle, TP_STATUS_USER)) {
4305 		struct pcap_linux *handlep = handle->priv;
4306 		int timeout;
4307 		char c;
4308 		struct pollfd pollinfo;
4309 		int ret;
4310 
4311 		pollinfo.fd = handle->fd;
4312 		pollinfo.events = POLLIN;
4313 
4314 		if (handlep->timeout == 0) {
4315 #ifdef HAVE_TPACKET3
4316 			/*
4317 			 * XXX - due to a set of (mis)features in the
4318 			 * TPACKET_V3 kernel code, blocking forever with
4319 			 * a TPACKET_V3 socket can, if few packets
4320 			 * are arriving and passing the socket filter,
4321 			 * cause most packets to be dropped.  See
4322 			 * libpcap issue #335 for the full painful
4323 			 * story.  The workaround is to have poll()
4324 			 * time out very quickly, so we grab the
4325 			 * frames handed to us, and return them to
4326 			 * the kernel, ASAP.
4327 			 *
4328 			 * If those issues are ever fixed, we might
4329 			 * want to check the kernel version and block
4330 			 * forever with TPACKET_V3 if we're running
4331 			 * with a kernel that has the fix.
4332 			 */
4333 			if (handlep->tp_version == TPACKET_V3)
4334 				timeout = 1;	/* don't block for very long */
4335 			else
4336 #endif
4337 				timeout = -1;	/* block forever */
4338 		} else if (handlep->timeout > 0)
4339 			timeout = handlep->timeout;	/* block for that amount of time */
4340 		else
4341 			timeout = 0;	/* non-blocking mode - poll to pick up errors */
4342 		do {
4343 			ret = poll(&pollinfo, 1, timeout);
4344 			if (ret < 0 && errno != EINTR) {
4345 				snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4346 					"can't poll on packet socket: %s",
4347 					pcap_strerror(errno));
4348 				return PCAP_ERROR;
4349 			} else if (ret > 0 &&
4350 				(pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
4351 				/*
4352 				 * There's some indication other than
4353 				 * "you can read on this descriptor" on
4354 				 * the descriptor.
4355 				 */
4356 				if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
4357 					snprintf(handle->errbuf,
4358 						PCAP_ERRBUF_SIZE,
4359 						"Hangup on packet socket");
4360 					return PCAP_ERROR;
4361 				}
4362 				if (pollinfo.revents & POLLERR) {
4363 					/*
4364 					 * A recv() will give us the
4365 					 * actual error code.
4366 					 *
4367 					 * XXX - make the socket non-blocking?
4368 					 */
4369 					if (recv(handle->fd, &c, sizeof c,
4370 						MSG_PEEK) != -1)
4371 						continue;	/* what, no error? */
4372 					if (errno == ENETDOWN) {
4373 						/*
4374 						 * The device on which we're
4375 						 * capturing went away.
4376 						 *
4377 						 * XXX - we should really return
4378 						 * PCAP_ERROR_IFACE_NOT_UP,
4379 						 * but pcap_dispatch() etc.
4380 						 * aren't defined to return
4381 						 * that.
4382 						 */
4383 						snprintf(handle->errbuf,
4384 							PCAP_ERRBUF_SIZE,
4385 							"The interface went down");
4386 					} else {
4387 						snprintf(handle->errbuf,
4388 							PCAP_ERRBUF_SIZE,
4389 							"Error condition on packet socket: %s",
4390 							strerror(errno));
4391 					}
4392 					return PCAP_ERROR;
4393 				}
4394 				if (pollinfo.revents & POLLNVAL) {
4395 					snprintf(handle->errbuf,
4396 						PCAP_ERRBUF_SIZE,
4397 						"Invalid polling request on packet socket");
4398 					return PCAP_ERROR;
4399 				}
4400 			}
4401 			/* check for break loop condition on interrupted syscall*/
4402 			if (handle->break_loop) {
4403 				handle->break_loop = 0;
4404 				return PCAP_ERROR_BREAK;
4405 			}
4406 		} while (ret < 0);
4407 	}
4408 	return 0;
4409 }
4410 
4411 /* handle a single memory mapped packet */
4412 static int pcap_handle_packet_mmap(
4413 		pcap_t *handle,
4414 		pcap_handler callback,
4415 		u_char *user,
4416 		unsigned char *frame,
4417 		unsigned int tp_len,
4418 		unsigned int tp_mac,
4419 		unsigned int tp_snaplen,
4420 		unsigned int tp_sec,
4421 		unsigned int tp_usec,
4422 		int tp_vlan_tci_valid,
4423 		__u16 tp_vlan_tci,
4424 		__u16 tp_vlan_tpid)
4425 {
4426 	struct pcap_linux *handlep = handle->priv;
4427 	unsigned char *bp;
4428 	struct sockaddr_ll *sll;
4429 	struct pcap_pkthdr pcaphdr;
4430 
4431 	/* perform sanity check on internal offset. */
4432 	if (tp_mac + tp_snaplen > handle->bufsize) {
4433 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4434 			"corrupted frame on kernel ring mac "
4435 			"offset %u + caplen %u > frame len %d",
4436 			tp_mac, tp_snaplen, handle->bufsize);
4437 		return -1;
4438 	}
4439 
4440 	/* run filter on received packet
4441 	 * If the kernel filtering is enabled we need to run the
4442 	 * filter until all the frames present into the ring
4443 	 * at filter creation time are processed.
4444 	 * In this case, blocks_to_filter_in_userland is used
4445 	 * as a counter for the packet we need to filter.
4446 	 * Note: alternatively it could be possible to stop applying
4447 	 * the filter when the ring became empty, but it can possibly
4448 	 * happen a lot later... */
4449 	bp = frame + tp_mac;
4450 
4451 	/* if required build in place the sll header*/
4452 	sll = (void *)frame + TPACKET_ALIGN(handlep->tp_hdrlen);
4453 	if (handlep->cooked) {
4454 		struct sll_header *hdrp;
4455 
4456 		/*
4457 		 * The kernel should have left us with enough
4458 		 * space for an sll header; back up the packet
4459 		 * data pointer into that space, as that'll be
4460 		 * the beginning of the packet we pass to the
4461 		 * callback.
4462 		 */
4463 		bp -= SLL_HDR_LEN;
4464 
4465 		/*
4466 		 * Let's make sure that's past the end of
4467 		 * the tpacket header, i.e. >=
4468 		 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4469 		 * don't step on the header when we construct
4470 		 * the sll header.
4471 		 */
4472 		if (bp < (u_char *)frame +
4473 				   TPACKET_ALIGN(handlep->tp_hdrlen) +
4474 				   sizeof(struct sockaddr_ll)) {
4475 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4476 				"cooked-mode frame doesn't have room for sll header");
4477 			return -1;
4478 		}
4479 
4480 		/*
4481 		 * OK, that worked; construct the sll header.
4482 		 */
4483 		hdrp = (struct sll_header *)bp;
4484 		hdrp->sll_pkttype = map_packet_type_to_sll_type(
4485 						sll->sll_pkttype);
4486 		hdrp->sll_hatype = htons(sll->sll_hatype);
4487 		hdrp->sll_halen = htons(sll->sll_halen);
4488 		memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
4489 		hdrp->sll_protocol = sll->sll_protocol;
4490 	}
4491 
4492 	if (handlep->filter_in_userland && handle->fcode.bf_insns) {
4493 		struct bpf_aux_data aux_data;
4494 
4495 		aux_data.vlan_tag = tp_vlan_tci & 0x0fff;
4496 		aux_data.vlan_tag_present = tp_vlan_tci_valid;
4497 
4498 		if (bpf_filter_with_aux_data(handle->fcode.bf_insns, bp,
4499 		    tp_len, tp_snaplen, &aux_data) == 0)
4500 			return 0;
4501 	}
4502 
4503 	if (!linux_check_direction(handle, sll))
4504 		return 0;
4505 
4506 	/* get required packet info from ring header */
4507 	pcaphdr.ts.tv_sec = tp_sec;
4508 	pcaphdr.ts.tv_usec = tp_usec;
4509 	pcaphdr.caplen = tp_snaplen;
4510 	pcaphdr.len = tp_len;
4511 
4512 	/* if required build in place the sll header*/
4513 	if (handlep->cooked) {
4514 		/* update packet len */
4515 		pcaphdr.caplen += SLL_HDR_LEN;
4516 		pcaphdr.len += SLL_HDR_LEN;
4517 	}
4518 
4519 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4520 	if (tp_vlan_tci_valid &&
4521 		handlep->vlan_offset != -1 &&
4522 		tp_snaplen >= (unsigned int) handlep->vlan_offset)
4523 	{
4524 		struct vlan_tag *tag;
4525 
4526 		bp -= VLAN_TAG_LEN;
4527 		memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
4528 
4529 		tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
4530 		tag->vlan_tpid = htons(tp_vlan_tpid);
4531 		tag->vlan_tci = htons(tp_vlan_tci);
4532 
4533 		pcaphdr.caplen += VLAN_TAG_LEN;
4534 		pcaphdr.len += VLAN_TAG_LEN;
4535 	}
4536 #endif
4537 
4538 	/*
4539 	 * The only way to tell the kernel to cut off the
4540 	 * packet at a snapshot length is with a filter program;
4541 	 * if there's no filter program, the kernel won't cut
4542 	 * the packet off.
4543 	 *
4544 	 * Trim the snapshot length to be no longer than the
4545 	 * specified snapshot length.
4546 	 */
4547 	if (pcaphdr.caplen > handle->snapshot)
4548 		pcaphdr.caplen = handle->snapshot;
4549 
4550 	/* pass the packet to the user */
4551 	callback(user, &pcaphdr, bp);
4552 
4553 	return 1;
4554 }
4555 
4556 static int
4557 pcap_read_linux_mmap_v1(pcap_t *handle, int max_packets, pcap_handler callback,
4558 		u_char *user)
4559 {
4560 	struct pcap_linux *handlep = handle->priv;
4561 	int pkts = 0;
4562 	int ret;
4563 
4564 	/* wait for frames availability.*/
4565 	ret = pcap_wait_for_frames_mmap(handle);
4566 	if (ret) {
4567 		return ret;
4568 	}
4569 
4570 	/* non-positive values of max_packets are used to require all
4571 	 * packets currently available in the ring */
4572 	while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
4573 		union thdr h;
4574 
4575 		h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
4576 		if (!h.raw)
4577 			break;
4578 
4579 		ret = pcap_handle_packet_mmap(
4580 				handle,
4581 				callback,
4582 				user,
4583 				h.raw,
4584 				h.h1->tp_len,
4585 				h.h1->tp_mac,
4586 				h.h1->tp_snaplen,
4587 				h.h1->tp_sec,
4588 				h.h1->tp_usec,
4589 				0,
4590 				0,
4591 				0);
4592 		if (ret == 1) {
4593 			pkts++;
4594 			handlep->packets_read++;
4595 		} else if (ret < 0) {
4596 			return ret;
4597 		}
4598 
4599 		/*
4600 		 * Hand this block back to the kernel, and, if we're
4601 		 * counting blocks that need to be filtered in userland
4602 		 * after having been filtered by the kernel, count
4603 		 * the one we've just processed.
4604 		 */
4605 		h.h1->tp_status = TP_STATUS_KERNEL;
4606 		if (handlep->blocks_to_filter_in_userland > 0) {
4607 			handlep->blocks_to_filter_in_userland--;
4608 			if (handlep->blocks_to_filter_in_userland == 0) {
4609 				/*
4610 				 * No more blocks need to be filtered
4611 				 * in userland.
4612 				 */
4613 				handlep->filter_in_userland = 0;
4614 			}
4615 		}
4616 
4617 		/* next block */
4618 		if (++handle->offset >= handle->cc)
4619 			handle->offset = 0;
4620 
4621 		/* check for break loop condition*/
4622 		if (handle->break_loop) {
4623 			handle->break_loop = 0;
4624 			return PCAP_ERROR_BREAK;
4625 		}
4626 	}
4627 	return pkts;
4628 }
4629 
4630 static int
4631 pcap_read_linux_mmap_v1_64(pcap_t *handle, int max_packets, pcap_handler callback,
4632 		u_char *user)
4633 {
4634 	struct pcap_linux *handlep = handle->priv;
4635 	int pkts = 0;
4636 	int ret;
4637 
4638 	/* wait for frames availability.*/
4639 	ret = pcap_wait_for_frames_mmap(handle);
4640 	if (ret) {
4641 		return ret;
4642 	}
4643 
4644 	/* non-positive values of max_packets are used to require all
4645 	 * packets currently available in the ring */
4646 	while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
4647 		union thdr h;
4648 
4649 		h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
4650 		if (!h.raw)
4651 			break;
4652 
4653 		ret = pcap_handle_packet_mmap(
4654 				handle,
4655 				callback,
4656 				user,
4657 				h.raw,
4658 				h.h1_64->tp_len,
4659 				h.h1_64->tp_mac,
4660 				h.h1_64->tp_snaplen,
4661 				h.h1_64->tp_sec,
4662 				h.h1_64->tp_usec,
4663 				0,
4664 				0,
4665 				0);
4666 		if (ret == 1) {
4667 			pkts++;
4668 			handlep->packets_read++;
4669 		} else if (ret < 0) {
4670 			return ret;
4671 		}
4672 
4673 		/*
4674 		 * Hand this block back to the kernel, and, if we're
4675 		 * counting blocks that need to be filtered in userland
4676 		 * after having been filtered by the kernel, count
4677 		 * the one we've just processed.
4678 		 */
4679 		h.h1_64->tp_status = TP_STATUS_KERNEL;
4680 		if (handlep->blocks_to_filter_in_userland > 0) {
4681 			handlep->blocks_to_filter_in_userland--;
4682 			if (handlep->blocks_to_filter_in_userland == 0) {
4683 				/*
4684 				 * No more blocks need to be filtered
4685 				 * in userland.
4686 				 */
4687 				handlep->filter_in_userland = 0;
4688 			}
4689 		}
4690 
4691 		/* next block */
4692 		if (++handle->offset >= handle->cc)
4693 			handle->offset = 0;
4694 
4695 		/* check for break loop condition*/
4696 		if (handle->break_loop) {
4697 			handle->break_loop = 0;
4698 			return PCAP_ERROR_BREAK;
4699 		}
4700 	}
4701 	return pkts;
4702 }
4703 
4704 #ifdef HAVE_TPACKET2
4705 static int
4706 pcap_read_linux_mmap_v2(pcap_t *handle, int max_packets, pcap_handler callback,
4707 		u_char *user)
4708 {
4709 	struct pcap_linux *handlep = handle->priv;
4710 	int pkts = 0;
4711 	int ret;
4712 
4713 	/* wait for frames availability.*/
4714 	ret = pcap_wait_for_frames_mmap(handle);
4715 	if (ret) {
4716 		return ret;
4717 	}
4718 
4719 	/* non-positive values of max_packets are used to require all
4720 	 * packets currently available in the ring */
4721 	while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
4722 		union thdr h;
4723 
4724 		h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
4725 		if (!h.raw)
4726 			break;
4727 
4728 		ret = pcap_handle_packet_mmap(
4729 				handle,
4730 				callback,
4731 				user,
4732 				h.raw,
4733 				h.h2->tp_len,
4734 				h.h2->tp_mac,
4735 				h.h2->tp_snaplen,
4736 				h.h2->tp_sec,
4737 				handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? h.h2->tp_nsec : h.h2->tp_nsec / 1000,
4738 #if defined(TP_STATUS_VLAN_VALID)
4739 				(h.h2->tp_vlan_tci || (h.h2->tp_status & TP_STATUS_VLAN_VALID)),
4740 #else
4741 				h.h2->tp_vlan_tci != 0,
4742 #endif
4743 				h.h2->tp_vlan_tci,
4744 				VLAN_TPID(h.h2, h.h2));
4745 		if (ret == 1) {
4746 			pkts++;
4747 			handlep->packets_read++;
4748 		} else if (ret < 0) {
4749 			return ret;
4750 		}
4751 
4752 		/*
4753 		 * Hand this block back to the kernel, and, if we're
4754 		 * counting blocks that need to be filtered in userland
4755 		 * after having been filtered by the kernel, count
4756 		 * the one we've just processed.
4757 		 */
4758 		h.h2->tp_status = TP_STATUS_KERNEL;
4759 		if (handlep->blocks_to_filter_in_userland > 0) {
4760 			handlep->blocks_to_filter_in_userland--;
4761 			if (handlep->blocks_to_filter_in_userland == 0) {
4762 				/*
4763 				 * No more blocks need to be filtered
4764 				 * in userland.
4765 				 */
4766 				handlep->filter_in_userland = 0;
4767 			}
4768 		}
4769 
4770 		/* next block */
4771 		if (++handle->offset >= handle->cc)
4772 			handle->offset = 0;
4773 
4774 		/* check for break loop condition*/
4775 		if (handle->break_loop) {
4776 			handle->break_loop = 0;
4777 			return PCAP_ERROR_BREAK;
4778 		}
4779 	}
4780 	return pkts;
4781 }
4782 #endif /* HAVE_TPACKET2 */
4783 
4784 #ifdef HAVE_TPACKET3
4785 static int
4786 pcap_read_linux_mmap_v3(pcap_t *handle, int max_packets, pcap_handler callback,
4787 		u_char *user)
4788 {
4789 	struct pcap_linux *handlep = handle->priv;
4790 	union thdr h;
4791 	int pkts = 0;
4792 	int ret;
4793 
4794 again:
4795 	if (handlep->current_packet == NULL) {
4796 		/* wait for frames availability.*/
4797 		ret = pcap_wait_for_frames_mmap(handle);
4798 		if (ret) {
4799 			return ret;
4800 		}
4801 	}
4802 	h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
4803 	if (!h.raw) {
4804 		if (pkts == 0 && handlep->timeout == 0) {
4805 			/* Block until we see a packet. */
4806 			goto again;
4807 		}
4808 		return pkts;
4809 	}
4810 
4811 	/* non-positive values of max_packets are used to require all
4812 	 * packets currently available in the ring */
4813 	while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
4814 		if (handlep->current_packet == NULL) {
4815 			h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
4816 			if (!h.raw)
4817 				break;
4818 
4819 			handlep->current_packet = h.raw + h.h3->hdr.bh1.offset_to_first_pkt;
4820 			handlep->packets_left = h.h3->hdr.bh1.num_pkts;
4821 		}
4822 		int packets_to_read = handlep->packets_left;
4823 
4824 		if (!PACKET_COUNT_IS_UNLIMITED(max_packets) && packets_to_read > max_packets) {
4825 			packets_to_read = max_packets;
4826 		}
4827 
4828 		while(packets_to_read--) {
4829 			struct tpacket3_hdr* tp3_hdr = (struct tpacket3_hdr*) handlep->current_packet;
4830 			ret = pcap_handle_packet_mmap(
4831 					handle,
4832 					callback,
4833 					user,
4834 					handlep->current_packet,
4835 					tp3_hdr->tp_len,
4836 					tp3_hdr->tp_mac,
4837 					tp3_hdr->tp_snaplen,
4838 					tp3_hdr->tp_sec,
4839 					handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? tp3_hdr->tp_nsec : tp3_hdr->tp_nsec / 1000,
4840 #if defined(TP_STATUS_VLAN_VALID)
4841 					(tp3_hdr->hv1.tp_vlan_tci || (tp3_hdr->tp_status & TP_STATUS_VLAN_VALID)),
4842 #else
4843 					tp3_hdr->hv1.tp_vlan_tci != 0,
4844 #endif
4845 					tp3_hdr->hv1.tp_vlan_tci,
4846 					VLAN_TPID(tp3_hdr, &tp3_hdr->hv1));
4847 			if (ret == 1) {
4848 				pkts++;
4849 				handlep->packets_read++;
4850 			} else if (ret < 0) {
4851 				handlep->current_packet = NULL;
4852 				return ret;
4853 			}
4854 			handlep->current_packet += tp3_hdr->tp_next_offset;
4855 			handlep->packets_left--;
4856 		}
4857 
4858 		if (handlep->packets_left <= 0) {
4859 			/*
4860 			 * Hand this block back to the kernel, and, if
4861 			 * we're counting blocks that need to be
4862 			 * filtered in userland after having been
4863 			 * filtered by the kernel, count the one we've
4864 			 * just processed.
4865 			 */
4866 			h.h3->hdr.bh1.block_status = TP_STATUS_KERNEL;
4867 			if (handlep->blocks_to_filter_in_userland > 0) {
4868 				handlep->blocks_to_filter_in_userland--;
4869 				if (handlep->blocks_to_filter_in_userland == 0) {
4870 					/*
4871 					 * No more blocks need to be filtered
4872 					 * in userland.
4873 					 */
4874 					handlep->filter_in_userland = 0;
4875 				}
4876 			}
4877 
4878 			/* next block */
4879 			if (++handle->offset >= handle->cc)
4880 				handle->offset = 0;
4881 
4882 			handlep->current_packet = NULL;
4883 		}
4884 
4885 		/* check for break loop condition*/
4886 		if (handle->break_loop) {
4887 			handle->break_loop = 0;
4888 			return PCAP_ERROR_BREAK;
4889 		}
4890 	}
4891 	if (pkts == 0 && handlep->timeout == 0) {
4892 		/* Block until we see a packet. */
4893 		goto again;
4894 	}
4895 	return pkts;
4896 }
4897 #endif /* HAVE_TPACKET3 */
4898 
4899 static int
4900 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
4901 {
4902 	struct pcap_linux *handlep = handle->priv;
4903 	int n, offset;
4904 	int ret;
4905 
4906 	/*
4907 	 * Don't rewrite "ret" instructions; we don't need to, as
4908 	 * we're not reading packets with recvmsg(), and we don't
4909 	 * want to, as, by not rewriting them, the kernel can avoid
4910 	 * copying extra data.
4911 	 */
4912 	ret = pcap_setfilter_linux_common(handle, filter, 1);
4913 	if (ret < 0)
4914 		return ret;
4915 
4916 	/*
4917 	 * If we're filtering in userland, there's nothing to do;
4918 	 * the new filter will be used for the next packet.
4919 	 */
4920 	if (handlep->filter_in_userland)
4921 		return ret;
4922 
4923 	/*
4924 	 * We're filtering in the kernel; the packets present in
4925 	 * all blocks currently in the ring were already filtered
4926 	 * by the old filter, and so will need to be filtered in
4927 	 * userland by the new filter.
4928 	 *
4929 	 * Get an upper bound for the number of such blocks; first,
4930 	 * walk the ring backward and count the free blocks.
4931 	 */
4932 	offset = handle->offset;
4933 	if (--handle->offset < 0)
4934 		handle->offset = handle->cc - 1;
4935 	for (n=0; n < handle->cc; ++n) {
4936 		if (--handle->offset < 0)
4937 			handle->offset = handle->cc - 1;
4938 		if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
4939 			break;
4940 	}
4941 
4942 	/*
4943 	 * If we found free blocks, decrement the count of free
4944 	 * blocks by 1, just in case we lost a race with another
4945 	 * thread of control that was adding a packet while
4946 	 * we were counting and that had run the filter before
4947 	 * we changed it.
4948 	 *
4949 	 * XXX - could there be more than one block added in
4950 	 * this fashion?
4951 	 *
4952 	 * XXX - is there a way to avoid that race, e.g. somehow
4953 	 * wait for all packets that passed the old filter to
4954 	 * be added to the ring?
4955 	 */
4956 	if (n != 0)
4957 		n--;
4958 
4959 	/* be careful to not change current ring position */
4960 	handle->offset = offset;
4961 
4962 	/*
4963 	 * Set the count of blocks worth of packets to filter
4964 	 * in userland to the total number of blocks in the
4965 	 * ring minus the number of free blocks we found, and
4966 	 * turn on userland filtering.  (The count of blocks
4967 	 * worth of packets to filter in userland is guaranteed
4968 	 * not to be zero - n, above, couldn't be set to a
4969 	 * value > handle->cc, and if it were equal to
4970 	 * handle->cc, it wouldn't be zero, and thus would
4971 	 * be decremented to handle->cc - 1.)
4972 	 */
4973 	handlep->blocks_to_filter_in_userland = handle->cc - n;
4974 	handlep->filter_in_userland = 1;
4975 	return ret;
4976 }
4977 
4978 #endif /* HAVE_PACKET_RING */
4979 
4980 
4981 #ifdef HAVE_PF_PACKET_SOCKETS
4982 /*
4983  *  Return the index of the given device name. Fill ebuf and return
4984  *  -1 on failure.
4985  */
4986 static int
4987 iface_get_id(int fd, const char *device, char *ebuf)
4988 {
4989 	struct ifreq	ifr;
4990 
4991 	memset(&ifr, 0, sizeof(ifr));
4992 	strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4993 
4994 	if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
4995 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
4996 			 "SIOCGIFINDEX: %s", pcap_strerror(errno));
4997 		return -1;
4998 	}
4999 
5000 	return ifr.ifr_ifindex;
5001 }
5002 
5003 /*
5004  *  Bind the socket associated with FD to the given device.
5005  *  Return 1 on success, 0 if we should try a SOCK_PACKET socket,
5006  *  or a PCAP_ERROR_ value on a hard error.
5007  */
5008 static int
5009 iface_bind(int fd, int ifindex, char *ebuf)
5010 {
5011 	struct sockaddr_ll	sll;
5012 	int			err;
5013 	socklen_t		errlen = sizeof(err);
5014 
5015 	memset(&sll, 0, sizeof(sll));
5016 	sll.sll_family		= AF_PACKET;
5017 	sll.sll_ifindex		= ifindex;
5018 	sll.sll_protocol	= htons(ETH_P_ALL);
5019 
5020 	if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
5021 		if (errno == ENETDOWN) {
5022 			/*
5023 			 * Return a "network down" indication, so that
5024 			 * the application can report that rather than
5025 			 * saying we had a mysterious failure and
5026 			 * suggest that they report a problem to the
5027 			 * libpcap developers.
5028 			 */
5029 			return PCAP_ERROR_IFACE_NOT_UP;
5030 		} else {
5031 			snprintf(ebuf, PCAP_ERRBUF_SIZE,
5032 				 "bind: %s", pcap_strerror(errno));
5033 			return PCAP_ERROR;
5034 		}
5035 	}
5036 
5037 	/* Any pending errors, e.g., network is down? */
5038 
5039 	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
5040 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
5041 			"getsockopt: %s", pcap_strerror(errno));
5042 		return 0;
5043 	}
5044 
5045 	if (err == ENETDOWN) {
5046 		/*
5047 		 * Return a "network down" indication, so that
5048 		 * the application can report that rather than
5049 		 * saying we had a mysterious failure and
5050 		 * suggest that they report a problem to the
5051 		 * libpcap developers.
5052 		 */
5053 		return PCAP_ERROR_IFACE_NOT_UP;
5054 	} else if (err > 0) {
5055 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
5056 			"bind: %s", pcap_strerror(err));
5057 		return 0;
5058 	}
5059 
5060 	return 1;
5061 }
5062 
5063 #ifdef IW_MODE_MONITOR
5064 /*
5065  * Check whether the device supports the Wireless Extensions.
5066  * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5067  * if the device doesn't even exist.
5068  */
5069 static int
5070 has_wext(int sock_fd, const char *device, char *ebuf)
5071 {
5072 	struct iwreq ireq;
5073 
5074 	strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5075 	    sizeof ireq.ifr_ifrn.ifrn_name);
5076 	if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
5077 		return 1;	/* yes */
5078 	snprintf(ebuf, PCAP_ERRBUF_SIZE,
5079 	    "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
5080 	if (errno == ENODEV)
5081 		return PCAP_ERROR_NO_SUCH_DEVICE;
5082 	return 0;
5083 }
5084 
5085 /*
5086  * Per me si va ne la citta dolente,
5087  * Per me si va ne l'etterno dolore,
5088  *	...
5089  * Lasciate ogne speranza, voi ch'intrate.
5090  *
5091  * XXX - airmon-ng does special stuff with the Orinoco driver and the
5092  * wlan-ng driver.
5093  */
5094 typedef enum {
5095 	MONITOR_WEXT,
5096 	MONITOR_HOSTAP,
5097 	MONITOR_PRISM,
5098 	MONITOR_PRISM54,
5099 	MONITOR_ACX100,
5100 	MONITOR_RT2500,
5101 	MONITOR_RT2570,
5102 	MONITOR_RT73,
5103 	MONITOR_RTL8XXX
5104 } monitor_type;
5105 
5106 /*
5107  * Use the Wireless Extensions, if we have them, to try to turn monitor mode
5108  * on if it's not already on.
5109  *
5110  * Returns 1 on success, 0 if we don't support the Wireless Extensions
5111  * on this device, or a PCAP_ERROR_ value if we do support them but
5112  * we weren't able to turn monitor mode on.
5113  */
5114 static int
5115 enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
5116 {
5117 	/*
5118 	 * XXX - at least some adapters require non-Wireless Extensions
5119 	 * mechanisms to turn monitor mode on.
5120 	 *
5121 	 * Atheros cards might require that a separate "monitor virtual access
5122 	 * point" be created, with later versions of the madwifi driver.
5123 	 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
5124 	 * monitor -bssid", which apparently spits out a line "athN"
5125 	 * where "athN" is the monitor mode device.  To leave monitor
5126 	 * mode, it destroys the monitor mode device.
5127 	 *
5128 	 * Some Intel Centrino adapters might require private ioctls to get
5129 	 * radio headers; the ipw2200 and ipw3945 drivers allow you to
5130 	 * configure a separate "rtapN" interface to capture in monitor
5131 	 * mode without preventing the adapter from operating normally.
5132 	 * (airmon-ng doesn't appear to use that, though.)
5133 	 *
5134 	 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
5135 	 * up, and if all drivers were converted to mac80211 drivers.
5136 	 *
5137 	 * If interface {if} is a mac80211 driver, the file
5138 	 * /sys/class/net/{if}/phy80211 is a symlink to
5139 	 * /sys/class/ieee80211/{phydev}, for some {phydev}.
5140 	 *
5141 	 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
5142 	 * least, has a "wmaster0" device and a "wlan0" device; the
5143 	 * latter is the one with the IP address.  Both show up in
5144 	 * "tcpdump -D" output.  Capturing on the wmaster0 device
5145 	 * captures with 802.11 headers.
5146 	 *
5147 	 * airmon-ng searches through /sys/class/net for devices named
5148 	 * monN, starting with mon0; as soon as one *doesn't* exist,
5149 	 * it chooses that as the monitor device name.  If the "iw"
5150 	 * command exists, it does "iw dev {if} interface add {monif}
5151 	 * type monitor", where {monif} is the monitor device.  It
5152 	 * then (sigh) sleeps .1 second, and then configures the
5153 	 * device up.  Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
5154 	 * is a file, it writes {mondev}, without a newline, to that file,
5155 	 * and again (sigh) sleeps .1 second, and then iwconfig's that
5156 	 * device into monitor mode and configures it up.  Otherwise,
5157 	 * you can't do monitor mode.
5158 	 *
5159 	 * All these devices are "glued" together by having the
5160 	 * /sys/class/net/{device}/phy80211 links pointing to the same
5161 	 * place, so, given a wmaster, wlan, or mon device, you can
5162 	 * find the other devices by looking for devices with
5163 	 * the same phy80211 link.
5164 	 *
5165 	 * To turn monitor mode off, delete the monitor interface,
5166 	 * either with "iw dev {monif} interface del" or by sending
5167 	 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
5168 	 *
5169 	 * Note: if you try to create a monitor device named "monN", and
5170 	 * there's already a "monN" device, it fails, as least with
5171 	 * the netlink interface (which is what iw uses), with a return
5172 	 * value of -ENFILE.  (Return values are negative errnos.)  We
5173 	 * could probably use that to find an unused device.
5174 	 */
5175 	struct pcap_linux *handlep = handle->priv;
5176 	int err;
5177 	struct iwreq ireq;
5178 	struct iw_priv_args *priv;
5179 	monitor_type montype;
5180 	int i;
5181 	__u32 cmd;
5182 	struct ifreq ifr;
5183 	int oldflags;
5184 	int args[2];
5185 	int channel;
5186 
5187 	/*
5188 	 * Does this device *support* the Wireless Extensions?
5189 	 */
5190 	err = has_wext(sock_fd, device, handle->errbuf);
5191 	if (err <= 0)
5192 		return err;	/* either it doesn't or the device doesn't even exist */
5193 	/*
5194 	 * Start out assuming we have no private extensions to control
5195 	 * radio metadata.
5196 	 */
5197 	montype = MONITOR_WEXT;
5198 	cmd = 0;
5199 
5200 	/*
5201 	 * Try to get all the Wireless Extensions private ioctls
5202 	 * supported by this device.
5203 	 *
5204 	 * First, get the size of the buffer we need, by supplying no
5205 	 * buffer and a length of 0.  If the device supports private
5206 	 * ioctls, it should return E2BIG, with ireq.u.data.length set
5207 	 * to the length we need.  If it doesn't support them, it should
5208 	 * return EOPNOTSUPP.
5209 	 */
5210 	memset(&ireq, 0, sizeof ireq);
5211 	strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5212 	    sizeof ireq.ifr_ifrn.ifrn_name);
5213 	ireq.u.data.pointer = (void *)args;
5214 	ireq.u.data.length = 0;
5215 	ireq.u.data.flags = 0;
5216 	if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
5217 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5218 		    "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
5219 		    device);
5220 		return PCAP_ERROR;
5221 	}
5222 	if (errno != EOPNOTSUPP) {
5223 		/*
5224 		 * OK, it's not as if there are no private ioctls.
5225 		 */
5226 		if (errno != E2BIG) {
5227 			/*
5228 			 * Failed.
5229 			 */
5230 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5231 			    "%s: SIOCGIWPRIV: %s", device,
5232 			    pcap_strerror(errno));
5233 			return PCAP_ERROR;
5234 		}
5235 
5236 		/*
5237 		 * OK, try to get the list of private ioctls.
5238 		 */
5239 		priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
5240 		if (priv == NULL) {
5241 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5242 			    "malloc: %s", pcap_strerror(errno));
5243 			return PCAP_ERROR;
5244 		}
5245 		ireq.u.data.pointer = (void *)priv;
5246 		if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
5247 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5248 			    "%s: SIOCGIWPRIV: %s", device,
5249 			    pcap_strerror(errno));
5250 			free(priv);
5251 			return PCAP_ERROR;
5252 		}
5253 
5254 		/*
5255 		 * Look for private ioctls to turn monitor mode on or, if
5256 		 * monitor mode is on, to set the header type.
5257 		 */
5258 		for (i = 0; i < ireq.u.data.length; i++) {
5259 			if (strcmp(priv[i].name, "monitor_type") == 0) {
5260 				/*
5261 				 * Hostap driver, use this one.
5262 				 * Set monitor mode first.
5263 				 * You can set it to 0 to get DLT_IEEE80211,
5264 				 * 1 to get DLT_PRISM, 2 to get
5265 				 * DLT_IEEE80211_RADIO_AVS, and, with more
5266 				 * recent versions of the driver, 3 to get
5267 				 * DLT_IEEE80211_RADIO.
5268 				 */
5269 				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
5270 					break;
5271 				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
5272 					break;
5273 				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
5274 					break;
5275 				montype = MONITOR_HOSTAP;
5276 				cmd = priv[i].cmd;
5277 				break;
5278 			}
5279 			if (strcmp(priv[i].name, "set_prismhdr") == 0) {
5280 				/*
5281 				 * Prism54 driver, use this one.
5282 				 * Set monitor mode first.
5283 				 * You can set it to 2 to get DLT_IEEE80211
5284 				 * or 3 or get DLT_PRISM.
5285 				 */
5286 				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
5287 					break;
5288 				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
5289 					break;
5290 				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
5291 					break;
5292 				montype = MONITOR_PRISM54;
5293 				cmd = priv[i].cmd;
5294 				break;
5295 			}
5296 			if (strcmp(priv[i].name, "forceprismheader") == 0) {
5297 				/*
5298 				 * RT2570 driver, use this one.
5299 				 * Do this after turning monitor mode on.
5300 				 * You can set it to 1 to get DLT_PRISM or 2
5301 				 * to get DLT_IEEE80211.
5302 				 */
5303 				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
5304 					break;
5305 				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
5306 					break;
5307 				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
5308 					break;
5309 				montype = MONITOR_RT2570;
5310 				cmd = priv[i].cmd;
5311 				break;
5312 			}
5313 			if (strcmp(priv[i].name, "forceprism") == 0) {
5314 				/*
5315 				 * RT73 driver, use this one.
5316 				 * Do this after turning monitor mode on.
5317 				 * Its argument is a *string*; you can
5318 				 * set it to "1" to get DLT_PRISM or "2"
5319 				 * to get DLT_IEEE80211.
5320 				 */
5321 				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
5322 					break;
5323 				if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
5324 					break;
5325 				montype = MONITOR_RT73;
5326 				cmd = priv[i].cmd;
5327 				break;
5328 			}
5329 			if (strcmp(priv[i].name, "prismhdr") == 0) {
5330 				/*
5331 				 * One of the RTL8xxx drivers, use this one.
5332 				 * It can only be done after monitor mode
5333 				 * has been turned on.  You can set it to 1
5334 				 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
5335 				 */
5336 				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
5337 					break;
5338 				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
5339 					break;
5340 				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
5341 					break;
5342 				montype = MONITOR_RTL8XXX;
5343 				cmd = priv[i].cmd;
5344 				break;
5345 			}
5346 			if (strcmp(priv[i].name, "rfmontx") == 0) {
5347 				/*
5348 				 * RT2500 or RT61 driver, use this one.
5349 				 * It has one one-byte parameter; set
5350 				 * u.data.length to 1 and u.data.pointer to
5351 				 * point to the parameter.
5352 				 * It doesn't itself turn monitor mode on.
5353 				 * You can set it to 1 to allow transmitting
5354 				 * in monitor mode(?) and get DLT_IEEE80211,
5355 				 * or set it to 0 to disallow transmitting in
5356 				 * monitor mode(?) and get DLT_PRISM.
5357 				 */
5358 				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
5359 					break;
5360 				if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
5361 					break;
5362 				montype = MONITOR_RT2500;
5363 				cmd = priv[i].cmd;
5364 				break;
5365 			}
5366 			if (strcmp(priv[i].name, "monitor") == 0) {
5367 				/*
5368 				 * Either ACX100 or hostap, use this one.
5369 				 * It turns monitor mode on.
5370 				 * If it takes two arguments, it's ACX100;
5371 				 * the first argument is 1 for DLT_PRISM
5372 				 * or 2 for DLT_IEEE80211, and the second
5373 				 * argument is the channel on which to
5374 				 * run.  If it takes one argument, it's
5375 				 * HostAP, and the argument is 2 for
5376 				 * DLT_IEEE80211 and 3 for DLT_PRISM.
5377 				 *
5378 				 * If we see this, we don't quit, as this
5379 				 * might be a version of the hostap driver
5380 				 * that also supports "monitor_type".
5381 				 */
5382 				if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
5383 					break;
5384 				if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
5385 					break;
5386 				switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
5387 
5388 				case 1:
5389 					montype = MONITOR_PRISM;
5390 					cmd = priv[i].cmd;
5391 					break;
5392 
5393 				case 2:
5394 					montype = MONITOR_ACX100;
5395 					cmd = priv[i].cmd;
5396 					break;
5397 
5398 				default:
5399 					break;
5400 				}
5401 			}
5402 		}
5403 		free(priv);
5404 	}
5405 
5406 	/*
5407 	 * XXX - ipw3945?  islism?
5408 	 */
5409 
5410 	/*
5411 	 * Get the old mode.
5412 	 */
5413 	strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5414 	    sizeof ireq.ifr_ifrn.ifrn_name);
5415 	if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
5416 		/*
5417 		 * We probably won't be able to set the mode, either.
5418 		 */
5419 		return PCAP_ERROR_RFMON_NOTSUP;
5420 	}
5421 
5422 	/*
5423 	 * Is it currently in monitor mode?
5424 	 */
5425 	if (ireq.u.mode == IW_MODE_MONITOR) {
5426 		/*
5427 		 * Yes.  Just leave things as they are.
5428 		 * We don't offer multiple link-layer types, as
5429 		 * changing the link-layer type out from under
5430 		 * somebody else capturing in monitor mode would
5431 		 * be considered rude.
5432 		 */
5433 		return 1;
5434 	}
5435 	/*
5436 	 * No.  We have to put the adapter into rfmon mode.
5437 	 */
5438 
5439 	/*
5440 	 * If we haven't already done so, arrange to have
5441 	 * "pcap_close_all()" called when we exit.
5442 	 */
5443 	if (!pcap_do_addexit(handle)) {
5444 		/*
5445 		 * "atexit()" failed; don't put the interface
5446 		 * in rfmon mode, just give up.
5447 		 */
5448 		return PCAP_ERROR_RFMON_NOTSUP;
5449 	}
5450 
5451 	/*
5452 	 * Save the old mode.
5453 	 */
5454 	handlep->oldmode = ireq.u.mode;
5455 
5456 	/*
5457 	 * Put the adapter in rfmon mode.  How we do this depends
5458 	 * on whether we have a special private ioctl or not.
5459 	 */
5460 	if (montype == MONITOR_PRISM) {
5461 		/*
5462 		 * We have the "monitor" private ioctl, but none of
5463 		 * the other private ioctls.  Use this, and select
5464 		 * the Prism header.
5465 		 *
5466 		 * If it fails, just fall back on SIOCSIWMODE.
5467 		 */
5468 		memset(&ireq, 0, sizeof ireq);
5469 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5470 		    sizeof ireq.ifr_ifrn.ifrn_name);
5471 		ireq.u.data.length = 1;	/* 1 argument */
5472 		args[0] = 3;	/* request Prism header */
5473 		memcpy(ireq.u.name, args, sizeof (int));
5474 		if (ioctl(sock_fd, cmd, &ireq) != -1) {
5475 			/*
5476 			 * Success.
5477 			 * Note that we have to put the old mode back
5478 			 * when we close the device.
5479 			 */
5480 			handlep->must_do_on_close |= MUST_CLEAR_RFMON;
5481 
5482 			/*
5483 			 * Add this to the list of pcaps to close
5484 			 * when we exit.
5485 			 */
5486 			pcap_add_to_pcaps_to_close(handle);
5487 
5488 			return 1;
5489 		}
5490 
5491 		/*
5492 		 * Failure.  Fall back on SIOCSIWMODE.
5493 		 */
5494 	}
5495 
5496 	/*
5497 	 * First, take the interface down if it's up; otherwise, we
5498 	 * might get EBUSY.
5499 	 */
5500 	memset(&ifr, 0, sizeof(ifr));
5501 	strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5502 	if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
5503 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5504 		    "%s: Can't get flags: %s", device, strerror(errno));
5505 		return PCAP_ERROR;
5506 	}
5507 	oldflags = 0;
5508 	if (ifr.ifr_flags & IFF_UP) {
5509 		oldflags = ifr.ifr_flags;
5510 		ifr.ifr_flags &= ~IFF_UP;
5511 		if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
5512 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5513 			    "%s: Can't set flags: %s", device, strerror(errno));
5514 			return PCAP_ERROR;
5515 		}
5516 	}
5517 
5518 	/*
5519 	 * Then turn monitor mode on.
5520 	 */
5521 	strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5522 	    sizeof ireq.ifr_ifrn.ifrn_name);
5523 	ireq.u.mode = IW_MODE_MONITOR;
5524 	if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
5525 		/*
5526 		 * Scientist, you've failed.
5527 		 * Bring the interface back up if we shut it down.
5528 		 */
5529 		ifr.ifr_flags = oldflags;
5530 		if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
5531 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5532 			    "%s: Can't set flags: %s", device, strerror(errno));
5533 			return PCAP_ERROR;
5534 		}
5535 		return PCAP_ERROR_RFMON_NOTSUP;
5536 	}
5537 
5538 	/*
5539 	 * XXX - airmon-ng does "iwconfig {if} key off" after setting
5540 	 * monitor mode and setting the channel, and then does
5541 	 * "iwconfig up".
5542 	 */
5543 
5544 	/*
5545 	 * Now select the appropriate radio header.
5546 	 */
5547 	switch (montype) {
5548 
5549 	case MONITOR_WEXT:
5550 		/*
5551 		 * We don't have any private ioctl to set the header.
5552 		 */
5553 		break;
5554 
5555 	case MONITOR_HOSTAP:
5556 		/*
5557 		 * Try to select the radiotap header.
5558 		 */
5559 		memset(&ireq, 0, sizeof ireq);
5560 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5561 		    sizeof ireq.ifr_ifrn.ifrn_name);
5562 		args[0] = 3;	/* request radiotap header */
5563 		memcpy(ireq.u.name, args, sizeof (int));
5564 		if (ioctl(sock_fd, cmd, &ireq) != -1)
5565 			break;	/* success */
5566 
5567 		/*
5568 		 * That failed.  Try to select the AVS header.
5569 		 */
5570 		memset(&ireq, 0, sizeof ireq);
5571 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5572 		    sizeof ireq.ifr_ifrn.ifrn_name);
5573 		args[0] = 2;	/* request AVS header */
5574 		memcpy(ireq.u.name, args, sizeof (int));
5575 		if (ioctl(sock_fd, cmd, &ireq) != -1)
5576 			break;	/* success */
5577 
5578 		/*
5579 		 * That failed.  Try to select the Prism header.
5580 		 */
5581 		memset(&ireq, 0, sizeof ireq);
5582 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5583 		    sizeof ireq.ifr_ifrn.ifrn_name);
5584 		args[0] = 1;	/* request Prism header */
5585 		memcpy(ireq.u.name, args, sizeof (int));
5586 		ioctl(sock_fd, cmd, &ireq);
5587 		break;
5588 
5589 	case MONITOR_PRISM:
5590 		/*
5591 		 * The private ioctl failed.
5592 		 */
5593 		break;
5594 
5595 	case MONITOR_PRISM54:
5596 		/*
5597 		 * Select the Prism header.
5598 		 */
5599 		memset(&ireq, 0, sizeof ireq);
5600 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5601 		    sizeof ireq.ifr_ifrn.ifrn_name);
5602 		args[0] = 3;	/* request Prism header */
5603 		memcpy(ireq.u.name, args, sizeof (int));
5604 		ioctl(sock_fd, cmd, &ireq);
5605 		break;
5606 
5607 	case MONITOR_ACX100:
5608 		/*
5609 		 * Get the current channel.
5610 		 */
5611 		memset(&ireq, 0, sizeof ireq);
5612 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5613 		    sizeof ireq.ifr_ifrn.ifrn_name);
5614 		if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
5615 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5616 			    "%s: SIOCGIWFREQ: %s", device,
5617 			    pcap_strerror(errno));
5618 			return PCAP_ERROR;
5619 		}
5620 		channel = ireq.u.freq.m;
5621 
5622 		/*
5623 		 * Select the Prism header, and set the channel to the
5624 		 * current value.
5625 		 */
5626 		memset(&ireq, 0, sizeof ireq);
5627 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5628 		    sizeof ireq.ifr_ifrn.ifrn_name);
5629 		args[0] = 1;		/* request Prism header */
5630 		args[1] = channel;	/* set channel */
5631 		memcpy(ireq.u.name, args, 2*sizeof (int));
5632 		ioctl(sock_fd, cmd, &ireq);
5633 		break;
5634 
5635 	case MONITOR_RT2500:
5636 		/*
5637 		 * Disallow transmission - that turns on the
5638 		 * Prism header.
5639 		 */
5640 		memset(&ireq, 0, sizeof ireq);
5641 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5642 		    sizeof ireq.ifr_ifrn.ifrn_name);
5643 		args[0] = 0;	/* disallow transmitting */
5644 		memcpy(ireq.u.name, args, sizeof (int));
5645 		ioctl(sock_fd, cmd, &ireq);
5646 		break;
5647 
5648 	case MONITOR_RT2570:
5649 		/*
5650 		 * Force the Prism header.
5651 		 */
5652 		memset(&ireq, 0, sizeof ireq);
5653 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5654 		    sizeof ireq.ifr_ifrn.ifrn_name);
5655 		args[0] = 1;	/* request Prism header */
5656 		memcpy(ireq.u.name, args, sizeof (int));
5657 		ioctl(sock_fd, cmd, &ireq);
5658 		break;
5659 
5660 	case MONITOR_RT73:
5661 		/*
5662 		 * Force the Prism header.
5663 		 */
5664 		memset(&ireq, 0, sizeof ireq);
5665 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5666 		    sizeof ireq.ifr_ifrn.ifrn_name);
5667 		ireq.u.data.length = 1;	/* 1 argument */
5668 		ireq.u.data.pointer = "1";
5669 		ireq.u.data.flags = 0;
5670 		ioctl(sock_fd, cmd, &ireq);
5671 		break;
5672 
5673 	case MONITOR_RTL8XXX:
5674 		/*
5675 		 * Force the Prism header.
5676 		 */
5677 		memset(&ireq, 0, sizeof ireq);
5678 		strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5679 		    sizeof ireq.ifr_ifrn.ifrn_name);
5680 		args[0] = 1;	/* request Prism header */
5681 		memcpy(ireq.u.name, args, sizeof (int));
5682 		ioctl(sock_fd, cmd, &ireq);
5683 		break;
5684 	}
5685 
5686 	/*
5687 	 * Now bring the interface back up if we brought it down.
5688 	 */
5689 	if (oldflags != 0) {
5690 		ifr.ifr_flags = oldflags;
5691 		if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
5692 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5693 			    "%s: Can't set flags: %s", device, strerror(errno));
5694 
5695 			/*
5696 			 * At least try to restore the old mode on the
5697 			 * interface.
5698 			 */
5699 			if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
5700 				/*
5701 				 * Scientist, you've failed.
5702 				 */
5703 				fprintf(stderr,
5704 				    "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
5705 				    "Please adjust manually.\n",
5706 				    strerror(errno));
5707 			}
5708 			return PCAP_ERROR;
5709 		}
5710 	}
5711 
5712 	/*
5713 	 * Note that we have to put the old mode back when we
5714 	 * close the device.
5715 	 */
5716 	handlep->must_do_on_close |= MUST_CLEAR_RFMON;
5717 
5718 	/*
5719 	 * Add this to the list of pcaps to close when we exit.
5720 	 */
5721 	pcap_add_to_pcaps_to_close(handle);
5722 
5723 	return 1;
5724 }
5725 #endif /* IW_MODE_MONITOR */
5726 
5727 /*
5728  * Try various mechanisms to enter monitor mode.
5729  */
5730 static int
5731 enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
5732 {
5733 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
5734 	int ret;
5735 #endif
5736 
5737 #ifdef HAVE_LIBNL
5738 	ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
5739 	if (ret < 0)
5740 		return ret;	/* error attempting to do so */
5741 	if (ret == 1)
5742 		return 1;	/* success */
5743 #endif /* HAVE_LIBNL */
5744 
5745 #ifdef IW_MODE_MONITOR
5746 	ret = enter_rfmon_mode_wext(handle, sock_fd, device);
5747 	if (ret < 0)
5748 		return ret;	/* error attempting to do so */
5749 	if (ret == 1)
5750 		return 1;	/* success */
5751 #endif /* IW_MODE_MONITOR */
5752 
5753 	/*
5754 	 * Either none of the mechanisms we know about work or none
5755 	 * of those mechanisms are available, so we can't do monitor
5756 	 * mode.
5757 	 */
5758 	return 0;
5759 }
5760 
5761 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
5762 /*
5763  * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
5764  */
5765 static const struct {
5766 	int soft_timestamping_val;
5767 	int pcap_tstamp_val;
5768 } sof_ts_type_map[3] = {
5769 	{ SOF_TIMESTAMPING_SOFTWARE, PCAP_TSTAMP_HOST },
5770 	{ SOF_TIMESTAMPING_SYS_HARDWARE, PCAP_TSTAMP_ADAPTER },
5771 	{ SOF_TIMESTAMPING_RAW_HARDWARE, PCAP_TSTAMP_ADAPTER_UNSYNCED }
5772 };
5773 #define NUM_SOF_TIMESTAMPING_TYPES	(sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
5774 
5775 static void
5776 iface_set_default_ts_types(pcap_t *handle)
5777 {
5778 	int i;
5779 
5780 	handle->tstamp_type_count = NUM_SOF_TIMESTAMPING_TYPES;
5781 	handle->tstamp_type_list = malloc(NUM_SOF_TIMESTAMPING_TYPES * sizeof(u_int));
5782 	for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++)
5783 		handle->tstamp_type_list[i] = sof_ts_type_map[i].pcap_tstamp_val;
5784 }
5785 
5786 #ifdef ETHTOOL_GET_TS_INFO
5787 /*
5788  * Get a list of time stamping capabilities.
5789  */
5790 static int
5791 iface_ethtool_get_ts_info(pcap_t *handle, char *ebuf)
5792 {
5793 	int fd;
5794 	struct ifreq ifr;
5795 	struct ethtool_ts_info info;
5796 	int num_ts_types;
5797 	int i, j;
5798 
5799 	/*
5800 	 * This doesn't apply to the "any" device; you have to ask
5801 	 * specific devices for their capabilities, so just default
5802 	 * to saying we support all of them.
5803 	 */
5804 	if (strcmp(handle->opt.source, "any") == 0) {
5805 		iface_set_default_ts_types(handle);
5806 		return 0;
5807 	}
5808 
5809 	/*
5810 	 * Create a socket from which to fetch time stamping capabilities.
5811 	 */
5812 	fd = socket(AF_INET, SOCK_DGRAM, 0);
5813 	if (fd < 0) {
5814 		(void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
5815 		    "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO): %s", pcap_strerror(errno));
5816 		return -1;
5817 	}
5818 
5819 	memset(&ifr, 0, sizeof(ifr));
5820 	strlcpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
5821 	memset(&info, 0, sizeof(info));
5822 	info.cmd = ETHTOOL_GET_TS_INFO;
5823 	ifr.ifr_data = (caddr_t)&info;
5824 	if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) {
5825 		close(fd);
5826 		if (errno == EOPNOTSUPP || errno == EINVAL) {
5827 			/*
5828 			 * OK, let's just return all the possible time
5829 			 * stamping types.
5830 			 */
5831 			iface_set_default_ts_types(handle);
5832 			return 0;
5833 		}
5834 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
5835 		    "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed: %s", handle->opt.source,
5836 		    strerror(errno));
5837 		return -1;
5838 	}
5839 	close(fd);
5840 
5841 	num_ts_types = 0;
5842 	for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
5843 		if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val)
5844 			num_ts_types++;
5845 	}
5846 	handle->tstamp_type_count = num_ts_types;
5847 	if (num_ts_types != 0) {
5848 		handle->tstamp_type_list = malloc(num_ts_types * sizeof(u_int));
5849 		for (i = 0, j = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
5850 			if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val) {
5851 				handle->tstamp_type_list[j] = sof_ts_type_map[i].pcap_tstamp_val;
5852 				j++;
5853 			}
5854 		}
5855 	} else
5856 		handle->tstamp_type_list = NULL;
5857 
5858 	return 0;
5859 }
5860 #else /* ETHTOOL_GET_TS_INFO */
5861 static int
5862 iface_ethtool_get_ts_info(pcap_t *handle, char *ebuf _U_)
5863 {
5864 	/*
5865 	 * We don't have an ioctl to use to ask what's supported,
5866 	 * so say we support everything.
5867 	 */
5868 	iface_set_default_ts_types(handle);
5869 	return 0;
5870 }
5871 #endif /* ETHTOOL_GET_TS_INFO */
5872 
5873 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
5874 
5875 #ifdef HAVE_PACKET_RING
5876 /*
5877  * Find out if we have any form of fragmentation/reassembly offloading.
5878  *
5879  * We do so using SIOCETHTOOL checking for various types of offloading;
5880  * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
5881  * of the types of offloading, there's nothing we can do to check, so
5882  * we just say "no, we don't".
5883  */
5884 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
5885 static int
5886 iface_ethtool_flag_ioctl(pcap_t *handle, int cmd, const char *cmdname)
5887 {
5888 	struct ifreq	ifr;
5889 	struct ethtool_value eval;
5890 
5891 	memset(&ifr, 0, sizeof(ifr));
5892 	strlcpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
5893 	eval.cmd = cmd;
5894 	eval.data = 0;
5895 	ifr.ifr_data = (caddr_t)&eval;
5896 	if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
5897 		if (errno == EOPNOTSUPP || errno == EINVAL) {
5898 			/*
5899 			 * OK, let's just return 0, which, in our
5900 			 * case, either means "no, what we're asking
5901 			 * about is not enabled" or "all the flags
5902 			 * are clear (i.e., nothing is enabled)".
5903 			 */
5904 			return 0;
5905 		}
5906 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5907 		    "%s: SIOCETHTOOL(%s) ioctl failed: %s", handle->opt.source,
5908 		    cmdname, strerror(errno));
5909 		return -1;
5910 	}
5911 	return eval.data;
5912 }
5913 
5914 static int
5915 iface_get_offload(pcap_t *handle)
5916 {
5917 	int ret;
5918 
5919 #ifdef ETHTOOL_GTSO
5920 	ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO");
5921 	if (ret == -1)
5922 		return -1;
5923 	if (ret)
5924 		return 1;	/* TCP segmentation offloading on */
5925 #endif
5926 
5927 #ifdef ETHTOOL_GUFO
5928 	ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO");
5929 	if (ret == -1)
5930 		return -1;
5931 	if (ret)
5932 		return 1;	/* UDP fragmentation offloading on */
5933 #endif
5934 
5935 #ifdef ETHTOOL_GGSO
5936 	/*
5937 	 * XXX - will this cause large unsegmented packets to be
5938 	 * handed to PF_PACKET sockets on transmission?  If not,
5939 	 * this need not be checked.
5940 	 */
5941 	ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO");
5942 	if (ret == -1)
5943 		return -1;
5944 	if (ret)
5945 		return 1;	/* generic segmentation offloading on */
5946 #endif
5947 
5948 #ifdef ETHTOOL_GFLAGS
5949 	ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS");
5950 	if (ret == -1)
5951 		return -1;
5952 	if (ret & ETH_FLAG_LRO)
5953 		return 1;	/* large receive offloading on */
5954 #endif
5955 
5956 #ifdef ETHTOOL_GGRO
5957 	/*
5958 	 * XXX - will this cause large reassembled packets to be
5959 	 * handed to PF_PACKET sockets on receipt?  If not,
5960 	 * this need not be checked.
5961 	 */
5962 	ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO");
5963 	if (ret == -1)
5964 		return -1;
5965 	if (ret)
5966 		return 1;	/* generic (large) receive offloading on */
5967 #endif
5968 
5969 	return 0;
5970 }
5971 #else /* SIOCETHTOOL */
5972 static int
5973 iface_get_offload(pcap_t *handle _U_)
5974 {
5975 	/*
5976 	 * XXX - do we need to get this information if we don't
5977 	 * have the ethtool ioctls?  If so, how do we do that?
5978 	 */
5979 	return 0;
5980 }
5981 #endif /* SIOCETHTOOL */
5982 
5983 #endif /* HAVE_PACKET_RING */
5984 
5985 #endif /* HAVE_PF_PACKET_SOCKETS */
5986 
5987 /* ===== Functions to interface to the older kernels ================== */
5988 
5989 /*
5990  * Try to open a packet socket using the old kernel interface.
5991  * Returns 1 on success and a PCAP_ERROR_ value on an error.
5992  */
5993 static int
5994 activate_old(pcap_t *handle)
5995 {
5996 	struct pcap_linux *handlep = handle->priv;
5997 	int		arptype;
5998 	struct ifreq	ifr;
5999 	const char	*device = handle->opt.source;
6000 	struct utsname	utsname;
6001 	int		mtu;
6002 
6003 	/* Open the socket */
6004 
6005 	handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
6006 	if (handle->fd == -1) {
6007 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6008 			 "socket: %s", pcap_strerror(errno));
6009 		if (errno == EPERM || errno == EACCES) {
6010 			/*
6011 			 * You don't have permission to open the
6012 			 * socket.
6013 			 */
6014 			return PCAP_ERROR_PERM_DENIED;
6015 		} else {
6016 			/*
6017 			 * Other error.
6018 			 */
6019 			return PCAP_ERROR;
6020 		}
6021 	}
6022 
6023 	/* It worked - we are using the old interface */
6024 	handlep->sock_packet = 1;
6025 
6026 	/* ...which means we get the link-layer header. */
6027 	handlep->cooked = 0;
6028 
6029 	/* Bind to the given device */
6030 
6031 	if (strcmp(device, "any") == 0) {
6032 		strlcpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
6033 			PCAP_ERRBUF_SIZE);
6034 		return PCAP_ERROR;
6035 	}
6036 	if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
6037 		return PCAP_ERROR;
6038 
6039 	/*
6040 	 * Try to get the link-layer type.
6041 	 */
6042 	arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
6043 	if (arptype < 0)
6044 		return PCAP_ERROR;
6045 
6046 	/*
6047 	 * Try to find the DLT_ type corresponding to that
6048 	 * link-layer type.
6049 	 */
6050 	map_arphrd_to_dlt(handle, handle->fd, arptype, device, 0);
6051 	if (handle->linktype == -1) {
6052 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6053 			 "unknown arptype %d", arptype);
6054 		return PCAP_ERROR;
6055 	}
6056 
6057 	/* Go to promisc mode if requested */
6058 
6059 	if (handle->opt.promisc) {
6060 		memset(&ifr, 0, sizeof(ifr));
6061 		strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6062 		if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
6063 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6064 				 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
6065 			return PCAP_ERROR;
6066 		}
6067 		if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
6068 			/*
6069 			 * Promiscuous mode isn't currently on,
6070 			 * so turn it on, and remember that
6071 			 * we should turn it off when the
6072 			 * pcap_t is closed.
6073 			 */
6074 
6075 			/*
6076 			 * If we haven't already done so, arrange
6077 			 * to have "pcap_close_all()" called when
6078 			 * we exit.
6079 			 */
6080 			if (!pcap_do_addexit(handle)) {
6081 				/*
6082 				 * "atexit()" failed; don't put
6083 				 * the interface in promiscuous
6084 				 * mode, just give up.
6085 				 */
6086 				return PCAP_ERROR;
6087 			}
6088 
6089 			ifr.ifr_flags |= IFF_PROMISC;
6090 			if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
6091 			        snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6092 					 "SIOCSIFFLAGS: %s",
6093 					 pcap_strerror(errno));
6094 				return PCAP_ERROR;
6095 			}
6096 			handlep->must_do_on_close |= MUST_CLEAR_PROMISC;
6097 
6098 			/*
6099 			 * Add this to the list of pcaps
6100 			 * to close when we exit.
6101 			 */
6102 			pcap_add_to_pcaps_to_close(handle);
6103 		}
6104 	}
6105 
6106 	/*
6107 	 * Compute the buffer size.
6108 	 *
6109 	 * We're using SOCK_PACKET, so this might be a 2.0[.x]
6110 	 * kernel, and might require special handling - check.
6111 	 */
6112 	if (uname(&utsname) < 0 ||
6113 	    strncmp(utsname.release, "2.0", 3) == 0) {
6114 		/*
6115 		 * Either we couldn't find out what kernel release
6116 		 * this is, or it's a 2.0[.x] kernel.
6117 		 *
6118 		 * In the 2.0[.x] kernel, a "recvfrom()" on
6119 		 * a SOCK_PACKET socket, with MSG_TRUNC set, will
6120 		 * return the number of bytes read, so if we pass
6121 		 * a length based on the snapshot length, it'll
6122 		 * return the number of bytes from the packet
6123 		 * copied to userland, not the actual length
6124 		 * of the packet.
6125 		 *
6126 		 * This means that, for example, the IP dissector
6127 		 * in tcpdump will get handed a packet length less
6128 		 * than the length in the IP header, and will
6129 		 * complain about "truncated-ip".
6130 		 *
6131 		 * So we don't bother trying to copy from the
6132 		 * kernel only the bytes in which we're interested,
6133 		 * but instead copy them all, just as the older
6134 		 * versions of libpcap for Linux did.
6135 		 *
6136 		 * The buffer therefore needs to be big enough to
6137 		 * hold the largest packet we can get from this
6138 		 * device.  Unfortunately, we can't get the MRU
6139 		 * of the network; we can only get the MTU.  The
6140 		 * MTU may be too small, in which case a packet larger
6141 		 * than the buffer size will be truncated *and* we
6142 		 * won't get the actual packet size.
6143 		 *
6144 		 * However, if the snapshot length is larger than
6145 		 * the buffer size based on the MTU, we use the
6146 		 * snapshot length as the buffer size, instead;
6147 		 * this means that with a sufficiently large snapshot
6148 		 * length we won't artificially truncate packets
6149 		 * to the MTU-based size.
6150 		 *
6151 		 * This mess just one of many problems with packet
6152 		 * capture on 2.0[.x] kernels; you really want a
6153 		 * 2.2[.x] or later kernel if you want packet capture
6154 		 * to work well.
6155 		 */
6156 		mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
6157 		if (mtu == -1)
6158 			return PCAP_ERROR;
6159 		handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
6160 		if (handle->bufsize < handle->snapshot)
6161 			handle->bufsize = handle->snapshot;
6162 	} else {
6163 		/*
6164 		 * This is a 2.2[.x] or later kernel.
6165 		 *
6166 		 * We can safely pass "recvfrom()" a byte count
6167 		 * based on the snapshot length.
6168 		 */
6169 		handle->bufsize = handle->snapshot;
6170 	}
6171 
6172 	/*
6173 	 * Default value for offset to align link-layer payload
6174 	 * on a 4-byte boundary.
6175 	 */
6176 	handle->offset	 = 0;
6177 
6178 	/*
6179 	 * SOCK_PACKET sockets don't supply information from
6180 	 * stripped VLAN tags.
6181 	 */
6182 	handlep->vlan_offset = -1; /* unknown */
6183 
6184 	return 1;
6185 }
6186 
6187 /*
6188  *  Bind the socket associated with FD to the given device using the
6189  *  interface of the old kernels.
6190  */
6191 static int
6192 iface_bind_old(int fd, const char *device, char *ebuf)
6193 {
6194 	struct sockaddr	saddr;
6195 	int		err;
6196 	socklen_t	errlen = sizeof(err);
6197 
6198 	memset(&saddr, 0, sizeof(saddr));
6199 	strlcpy(saddr.sa_data, device, sizeof(saddr.sa_data));
6200 	if (bind(fd, &saddr, sizeof(saddr)) == -1) {
6201 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
6202 			 "bind: %s", pcap_strerror(errno));
6203 		return -1;
6204 	}
6205 
6206 	/* Any pending errors, e.g., network is down? */
6207 
6208 	if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
6209 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
6210 			"getsockopt: %s", pcap_strerror(errno));
6211 		return -1;
6212 	}
6213 
6214 	if (err > 0) {
6215 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
6216 			"bind: %s", pcap_strerror(err));
6217 		return -1;
6218 	}
6219 
6220 	return 0;
6221 }
6222 
6223 
6224 /* ===== System calls available on all supported kernels ============== */
6225 
6226 /*
6227  *  Query the kernel for the MTU of the given interface.
6228  */
6229 static int
6230 iface_get_mtu(int fd, const char *device, char *ebuf)
6231 {
6232 	struct ifreq	ifr;
6233 
6234 	if (!device)
6235 		return BIGGER_THAN_ALL_MTUS;
6236 
6237 	memset(&ifr, 0, sizeof(ifr));
6238 	strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6239 
6240 	if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
6241 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
6242 			 "SIOCGIFMTU: %s", pcap_strerror(errno));
6243 		return -1;
6244 	}
6245 
6246 	return ifr.ifr_mtu;
6247 }
6248 
6249 /*
6250  *  Get the hardware type of the given interface as ARPHRD_xxx constant.
6251  */
6252 static int
6253 iface_get_arptype(int fd, const char *device, char *ebuf)
6254 {
6255 	struct ifreq	ifr;
6256 
6257 	memset(&ifr, 0, sizeof(ifr));
6258 	strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6259 
6260 	if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
6261 		snprintf(ebuf, PCAP_ERRBUF_SIZE,
6262 			 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
6263 		if (errno == ENODEV) {
6264 			/*
6265 			 * No such device.
6266 			 */
6267 			return PCAP_ERROR_NO_SUCH_DEVICE;
6268 		}
6269 		return PCAP_ERROR;
6270 	}
6271 
6272 	return ifr.ifr_hwaddr.sa_family;
6273 }
6274 
6275 #ifdef SO_ATTACH_FILTER
6276 static int
6277 fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
6278 {
6279 	struct pcap_linux *handlep = handle->priv;
6280 	size_t prog_size;
6281 	register int i;
6282 	register struct bpf_insn *p;
6283 	struct bpf_insn *f;
6284 	int len;
6285 
6286 	/*
6287 	 * Make a copy of the filter, and modify that copy if
6288 	 * necessary.
6289 	 */
6290 	prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
6291 	len = handle->fcode.bf_len;
6292 	f = (struct bpf_insn *)malloc(prog_size);
6293 	if (f == NULL) {
6294 		snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6295 			 "malloc: %s", pcap_strerror(errno));
6296 		return -1;
6297 	}
6298 	memcpy(f, handle->fcode.bf_insns, prog_size);
6299 	fcode->len = len;
6300 	fcode->filter = (struct sock_filter *) f;
6301 
6302 	for (i = 0; i < len; ++i) {
6303 		p = &f[i];
6304 		/*
6305 		 * What type of instruction is this?
6306 		 */
6307 		switch (BPF_CLASS(p->code)) {
6308 
6309 		case BPF_RET:
6310 			/*
6311 			 * It's a return instruction; are we capturing
6312 			 * in memory-mapped mode?
6313 			 */
6314 			if (!is_mmapped) {
6315 				/*
6316 				 * No; is the snapshot length a constant,
6317 				 * rather than the contents of the
6318 				 * accumulator?
6319 				 */
6320 				if (BPF_MODE(p->code) == BPF_K) {
6321 					/*
6322 					 * Yes - if the value to be returned,
6323 					 * i.e. the snapshot length, is
6324 					 * anything other than 0, make it
6325 					 * MAXIMUM_SNAPLEN, so that the packet
6326 					 * is truncated by "recvfrom()",
6327 					 * not by the filter.
6328 					 *
6329 					 * XXX - there's nothing we can
6330 					 * easily do if it's getting the
6331 					 * value from the accumulator; we'd
6332 					 * have to insert code to force
6333 					 * non-zero values to be
6334 					 * MAXIMUM_SNAPLEN.
6335 					 */
6336 					if (p->k != 0)
6337 						p->k = MAXIMUM_SNAPLEN;
6338 				}
6339 			}
6340 			break;
6341 
6342 		case BPF_LD:
6343 		case BPF_LDX:
6344 			/*
6345 			 * It's a load instruction; is it loading
6346 			 * from the packet?
6347 			 */
6348 			switch (BPF_MODE(p->code)) {
6349 
6350 			case BPF_ABS:
6351 			case BPF_IND:
6352 			case BPF_MSH:
6353 				/*
6354 				 * Yes; are we in cooked mode?
6355 				 */
6356 				if (handlep->cooked) {
6357 					/*
6358 					 * Yes, so we need to fix this
6359 					 * instruction.
6360 					 */
6361 					if (fix_offset(p) < 0) {
6362 						/*
6363 						 * We failed to do so.
6364 						 * Return 0, so our caller
6365 						 * knows to punt to userland.
6366 						 */
6367 						return 0;
6368 					}
6369 				}
6370 				break;
6371 			}
6372 			break;
6373 		}
6374 	}
6375 	return 1;	/* we succeeded */
6376 }
6377 
6378 static int
6379 fix_offset(struct bpf_insn *p)
6380 {
6381 	/*
6382 	 * What's the offset?
6383 	 */
6384 	if (p->k >= SLL_HDR_LEN) {
6385 		/*
6386 		 * It's within the link-layer payload; that starts at an
6387 		 * offset of 0, as far as the kernel packet filter is
6388 		 * concerned, so subtract the length of the link-layer
6389 		 * header.
6390 		 */
6391 		p->k -= SLL_HDR_LEN;
6392 	} else if (p->k == 0) {
6393 		/*
6394 		 * It's the packet type field; map it to the special magic
6395 		 * kernel offset for that field.
6396 		 */
6397 		p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
6398 	} else if (p->k == 14) {
6399 		/*
6400 		 * It's the protocol field; map it to the special magic
6401 		 * kernel offset for that field.
6402 		 */
6403 		p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
6404 	} else if ((bpf_int32)(p->k) > 0) {
6405 		/*
6406 		 * It's within the header, but it's not one of those
6407 		 * fields; we can't do that in the kernel, so punt
6408 		 * to userland.
6409 		 */
6410 		return -1;
6411 	}
6412 	return 0;
6413 }
6414 
6415 static int
6416 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
6417 {
6418 	int total_filter_on = 0;
6419 	int save_mode;
6420 	int ret;
6421 	int save_errno;
6422 
6423 	/*
6424 	 * The socket filter code doesn't discard all packets queued
6425 	 * up on the socket when the filter is changed; this means
6426 	 * that packets that don't match the new filter may show up
6427 	 * after the new filter is put onto the socket, if those
6428 	 * packets haven't yet been read.
6429 	 *
6430 	 * This means, for example, that if you do a tcpdump capture
6431 	 * with a filter, the first few packets in the capture might
6432 	 * be packets that wouldn't have passed the filter.
6433 	 *
6434 	 * We therefore discard all packets queued up on the socket
6435 	 * when setting a kernel filter.  (This isn't an issue for
6436 	 * userland filters, as the userland filtering is done after
6437 	 * packets are queued up.)
6438 	 *
6439 	 * To flush those packets, we put the socket in read-only mode,
6440 	 * and read packets from the socket until there are no more to
6441 	 * read.
6442 	 *
6443 	 * In order to keep that from being an infinite loop - i.e.,
6444 	 * to keep more packets from arriving while we're draining
6445 	 * the queue - we put the "total filter", which is a filter
6446 	 * that rejects all packets, onto the socket before draining
6447 	 * the queue.
6448 	 *
6449 	 * This code deliberately ignores any errors, so that you may
6450 	 * get bogus packets if an error occurs, rather than having
6451 	 * the filtering done in userland even if it could have been
6452 	 * done in the kernel.
6453 	 */
6454 	if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
6455 		       &total_fcode, sizeof(total_fcode)) == 0) {
6456 		char drain[1];
6457 
6458 		/*
6459 		 * Note that we've put the total filter onto the socket.
6460 		 */
6461 		total_filter_on = 1;
6462 
6463 		/*
6464 		 * Save the socket's current mode, and put it in
6465 		 * non-blocking mode; we drain it by reading packets
6466 		 * until we get an error (which is normally a
6467 		 * "nothing more to be read" error).
6468 		 */
6469 		save_mode = fcntl(handle->fd, F_GETFL, 0);
6470 		if (save_mode == -1) {
6471 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6472 			    "can't get FD flags when changing filter: %s",
6473 			    pcap_strerror(errno));
6474 			return -2;
6475 		}
6476 		if (fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) < 0) {
6477 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6478 			    "can't set nonblocking mode when changing filter: %s",
6479 			    pcap_strerror(errno));
6480 			return -2;
6481 		}
6482 		while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0)
6483 			;
6484 		save_errno = errno;
6485 		if (save_errno != EAGAIN) {
6486 			/*
6487 			 * Fatal error.
6488 			 *
6489 			 * If we can't restore the mode or reset the
6490 			 * kernel filter, there's nothing we can do.
6491 			 */
6492 			(void)fcntl(handle->fd, F_SETFL, save_mode);
6493 			(void)reset_kernel_filter(handle);
6494 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6495 			    "recv failed when changing filter: %s",
6496 			    pcap_strerror(save_errno));
6497 			return -2;
6498 		}
6499 		if (fcntl(handle->fd, F_SETFL, save_mode) == -1) {
6500 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6501 			    "can't restore FD flags when changing filter: %s",
6502 			    pcap_strerror(save_errno));
6503 			return -2;
6504 		}
6505 	}
6506 
6507 	/*
6508 	 * Now attach the new filter.
6509 	 */
6510 	ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
6511 			 fcode, sizeof(*fcode));
6512 	if (ret == -1 && total_filter_on) {
6513 		/*
6514 		 * Well, we couldn't set that filter on the socket,
6515 		 * but we could set the total filter on the socket.
6516 		 *
6517 		 * This could, for example, mean that the filter was
6518 		 * too big to put into the kernel, so we'll have to
6519 		 * filter in userland; in any case, we'll be doing
6520 		 * filtering in userland, so we need to remove the
6521 		 * total filter so we see packets.
6522 		 */
6523 		save_errno = errno;
6524 
6525 		/*
6526 		 * If this fails, we're really screwed; we have the
6527 		 * total filter on the socket, and it won't come off.
6528 		 * Report it as a fatal error.
6529 		 */
6530 		if (reset_kernel_filter(handle) == -1) {
6531 			snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6532 			    "can't remove kernel total filter: %s",
6533 			    pcap_strerror(errno));
6534 			return -2;	/* fatal error */
6535 		}
6536 
6537 		errno = save_errno;
6538 	}
6539 	return ret;
6540 }
6541 
6542 static int
6543 reset_kernel_filter(pcap_t *handle)
6544 {
6545 	/*
6546 	 * setsockopt() barfs unless it get a dummy parameter.
6547 	 * valgrind whines unless the value is initialized,
6548 	 * as it has no idea that setsockopt() ignores its
6549 	 * parameter.
6550 	 */
6551 	int dummy = 0;
6552 
6553 	return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
6554 				   &dummy, sizeof(dummy));
6555 }
6556 #endif
6557