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