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