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