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