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