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