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