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