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