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