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