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