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