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