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