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