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