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