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