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