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