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