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