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