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