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