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