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