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