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