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