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