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