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