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