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