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