2 * pcap-linux.c: Packet capture interface to the Linux kernel
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
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.
27 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
30 * based on previous works of:
31 * Simon Patarin <patarin@cs.unibo.it>
32 * Phil Wood <cpw@lanl.gov>
36 static const char rcsid
[] _U_
=
37 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.148 2008-04-14 21:04:51 guy Exp $ (LBL)";
41 * Known problems with 2.0[.x] kernels:
43 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
44 * if we use PF_PACKET, we can filter out the transmitted version
45 * of the packet by using data in the "sockaddr_ll" returned by
46 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
47 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
48 * "sockaddr_pkt" which doesn't give us enough information to let
51 * - We have to set the interface's IFF_PROMISC flag ourselves, if
52 * we're to run in promiscuous mode, which means we have to turn
53 * it off ourselves when we're done; the kernel doesn't keep track
54 * of how many sockets are listening promiscuously, which means
55 * it won't get turned off automatically when no sockets are
56 * listening promiscuously. We catch "pcap_close()" and, for
57 * interfaces we put into promiscuous mode, take them out of
58 * promiscuous mode - which isn't necessarily the right thing to
59 * do, if another socket also requested promiscuous mode between
60 * the time when we opened the socket and the time when we close
63 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
64 * return the amount of data that you could have read, rather than
65 * the amount that was returned, so we can't just allocate a buffer
66 * whose size is the snapshot length and pass the snapshot length
67 * as the byte count, and also pass MSG_TRUNC, so that the return
68 * value tells us how long the packet was on the wire.
70 * This means that, if we want to get the actual size of the packet,
71 * so we can return it in the "len" field of the packet header,
72 * we have to read the entire packet, not just the part that fits
73 * within the snapshot length, and thus waste CPU time copying data
74 * from the kernel that our caller won't see.
76 * We have to get the actual size, and supply it in "len", because
77 * otherwise, the IP dissector in tcpdump, for example, will complain
78 * about "truncated-ip", as the packet will appear to have been
79 * shorter, on the wire, than the IP header said it should have been.
92 #include <sys/socket.h>
93 #include <sys/ioctl.h>
94 #include <sys/utsname.h>
97 #include <netinet/in.h>
98 #include <linux/if_ether.h>
99 #include <net/if_arp.h>
103 * Got Wireless Extensions?
105 #ifdef HAVE_LINUX_WIRELESS_H
106 #include <linux/wireless.h>
109 #include "pcap-int.h"
110 #include "pcap/sll.h"
113 #include "pcap-dag.h"
114 #endif /* HAVE_DAG_API */
116 #ifdef HAVE_SEPTEL_API
117 #include "pcap-septel.h"
118 #endif /* HAVE_SEPTEL_API */
120 #ifdef PCAP_SUPPORT_USB
121 #include "pcap-usb-linux.h"
124 #ifdef PCAP_SUPPORT_BT
125 #include "pcap-bt-linux.h"
129 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
130 * sockets rather than SOCK_PACKET sockets.
132 * To use them, we include <linux/if_packet.h> rather than
133 * <netpacket/packet.h>; we do so because
135 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
136 * later kernels and libc5, and don't provide a <netpacket/packet.h>
139 * not all versions of glibc2 have a <netpacket/packet.h> file
140 * that defines stuff needed for some of the 2.4-or-later-kernel
141 * features, so if the system has a 2.4 or later kernel, we
142 * still can't use those features.
144 * We're already including a number of other <linux/XXX.h> headers, and
145 * this code is Linux-specific (no other OS has PF_PACKET sockets as
146 * a raw packet capture mechanism), so it's not as if you gain any
147 * useful portability by using <netpacket/packet.h>
149 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
150 * isn't defined? It only defines one data structure in 2.0.x, so
151 * it shouldn't cause any problems.
154 # include <linux/if_packet.h>
157 * On at least some Linux distributions (for example, Red Hat 5.2),
158 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
159 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
160 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
161 * the PACKET_xxx stuff.
163 * So we check whether PACKET_HOST is defined, and assume that we have
164 * PF_PACKET sockets only if it is defined.
167 # define HAVE_PF_PACKET_SOCKETS
168 # endif /* PACKET_HOST */
171 /* check for memory mapped access avaibility. We assume every needed
172 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
173 * uses many ring related structs and macros */
174 # ifdef TPACKET_HDRLEN
175 # define HAVE_PACKET_RING
176 # endif /* TPACKET_HDRLEN */
177 #endif /* PF_PACKET */
179 #ifdef SO_ATTACH_FILTER
180 #include <linux/types.h>
181 #include <linux/filter.h>
184 #ifndef HAVE_SOCKLEN_T
185 typedef int socklen_t
;
190 * This is being compiled on a system that lacks MSG_TRUNC; define it
191 * with the value it has in the 2.2 and later kernels, so that, on
192 * those kernels, when we pass it in the flags argument to "recvfrom()"
193 * we're passing the right value and thus get the MSG_TRUNC behavior
194 * we want. (We don't get that behavior on 2.0[.x] kernels, because
195 * they didn't support MSG_TRUNC.)
197 #define MSG_TRUNC 0x20
202 * This is being compiled on a system that lacks SOL_PACKET; define it
203 * with the value it has in the 2.2 and later kernels, so that we can
204 * set promiscuous mode in the good modern way rather than the old
205 * 2.0-kernel crappy way.
207 #define SOL_PACKET 263
210 #define MAX_LINKHEADER_SIZE 256
213 * When capturing on all interfaces we use this as the buffer size.
214 * Should be bigger then all MTUs that occur in real life.
215 * 64kB should be enough for now.
217 #define BIGGER_THAN_ALL_MTUS (64*1024)
220 * Prototypes for internal functions and methods.
222 static void map_arphrd_to_dlt(pcap_t
*, int, int);
223 #ifdef HAVE_PF_PACKET_SOCKETS
224 static short int map_packet_type_to_sll_type(short int);
226 static int pcap_activate_linux(pcap_t
*);
227 static int activate_old(pcap_t
*);
228 static int activate_new(pcap_t
*);
229 static int activate_mmap(pcap_t
*);
230 static int pcap_can_set_rfmon_linux(pcap_t
*);
231 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
232 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
233 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
234 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
235 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
236 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
237 static void pcap_cleanup_linux(pcap_t
*);
239 #ifdef HAVE_PACKET_RING
240 #define RING_GET_FRAME(h) (((struct tpacket_hdr**)h->buffer)[h->offset])
242 static void destroy_ring(pcap_t
*handle
);
243 static int create_ring(pcap_t
*handle
);
244 static void pcap_cleanup_linux_mmap(pcap_t
*);
245 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
246 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
247 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
248 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
252 * Wrap some ioctl calls
254 #ifdef HAVE_PF_PACKET_SOCKETS
255 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
257 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
258 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
259 #ifdef HAVE_PF_PACKET_SOCKETS
260 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
261 static int has_wext(int sock_fd
, const char *device
, char *ebuf
);
262 static int enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
,
265 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
267 #ifdef SO_ATTACH_FILTER
268 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
269 static int fix_offset(struct bpf_insn
*p
);
270 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
271 static int reset_kernel_filter(pcap_t
*handle
);
273 static struct sock_filter total_insn
274 = BPF_STMT(BPF_RET
| BPF_K
, 0);
275 static struct sock_fprog total_fcode
276 = { 1, &total_insn
};
280 pcap_create(const char *device
, char *ebuf
)
285 if (strstr(device
, "dag")) {
286 return dag_create(device
, ebuf
);
288 #endif /* HAVE_DAG_API */
290 #ifdef HAVE_SEPTEL_API
291 if (strstr(device
, "septel")) {
292 return septel_create(device
, ebuf
);
294 #endif /* HAVE_SEPTEL_API */
296 #ifdef PCAP_SUPPORT_BT
297 if (strstr(device
, "bluetooth")) {
298 return bt_create(device
, ebuf
);
302 #ifdef PCAP_SUPPORT_USB
303 if (strstr(device
, "usb")) {
304 return usb_create(device
, ebuf
);
308 handle
= pcap_create_common(device
, ebuf
);
312 handle
->activate_op
= pcap_activate_linux
;
313 handle
->can_set_rfmon_op
= pcap_can_set_rfmon_linux
;
318 pcap_can_set_rfmon_linux(pcap_t
*p
)
320 #ifdef IW_MODE_MONITOR
325 if (p
->opt
.source
== NULL
) {
327 * This is equivalent to the "any" device, and we don't
328 * support monitor mode on it.
333 #ifdef IW_MODE_MONITOR
335 * Bleah. There doesn't appear to be an ioctl to use to ask
336 * whether a device supports monitor mode; we'll just do
337 * SIOCGIWMODE and, if it succeeds, assume the device supports
340 * Open a socket on which to attempt to get the mode.
341 * (We assume that if we have Wireless Extensions support
342 * we also have PF_PACKET support.)
344 sock_fd
= socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
));
346 (void)snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
347 "socket: %s", pcap_strerror(errno
));
352 * Attempt to get the current mode.
354 strncpy(ireq
.ifr_ifrn
.ifrn_name
, p
->opt
.source
,
355 sizeof ireq
.ifr_ifrn
.ifrn_name
);
356 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
357 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) != -1) {
359 * Well, we got the mode; assume we can set it.
364 if (errno
== ENODEV
) {
365 /* The device doesn't even exist. */
367 return PCAP_ERROR_NO_SUCH_DEVICE
;
375 * With older kernels promiscuous mode is kind of interesting because we
376 * have to reset the interface before exiting. The problem can't really
377 * be solved without some daemon taking care of managing usage counts.
378 * If we put the interface into promiscuous mode, we set a flag indicating
379 * that we must take it out of that mode when the interface is closed,
380 * and, when closing the interface, if that flag is set we take it out
381 * of promiscuous mode.
383 * Even with newer kernels, we have the same issue with rfmon mode.
386 static void pcap_cleanup_linux( pcap_t
*handle
)
389 #ifdef IW_MODE_MONITOR
393 if (handle
->md
.must_clear
!= 0) {
395 * There's something we have to do when closing this
398 if (handle
->md
.must_clear
& MUST_CLEAR_PROMISC
) {
400 * We put the interface into promiscuous mode;
401 * take it out of promiscuous mode.
403 * XXX - if somebody else wants it in promiscuous
404 * mode, this code cannot know that, so it'll take
405 * it out of promiscuous mode. That's not fixable
406 * in 2.0[.x] kernels.
408 memset(&ifr
, 0, sizeof(ifr
));
409 strncpy(ifr
.ifr_name
, handle
->md
.device
,
410 sizeof(ifr
.ifr_name
));
411 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
413 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
414 "Please adjust manually.\n"
415 "Hint: This can't happen with Linux >= 2.2.0.\n",
418 if (ifr
.ifr_flags
& IFF_PROMISC
) {
420 * Promiscuous mode is currently on;
423 ifr
.ifr_flags
&= ~IFF_PROMISC
;
424 if (ioctl(handle
->fd
, SIOCSIFFLAGS
,
427 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
428 "Please adjust manually.\n"
429 "Hint: This can't happen with Linux >= 2.2.0.\n",
436 #ifdef IW_MODE_MONITOR
437 if (handle
->md
.must_clear
& MUST_CLEAR_RFMON
) {
439 * We put the interface into rfmon mode;
440 * take it out of rfmon mode.
442 * XXX - if somebody else wants it in rfmon
443 * mode, this code cannot know that, so it'll take
444 * it out of rfmon mode.
446 strncpy(ireq
.ifr_ifrn
.ifrn_name
, handle
->md
.device
,
447 sizeof ireq
.ifr_ifrn
.ifrn_name
);
448 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1]
450 ireq
.u
.mode
= handle
->md
.oldmode
;
451 if (ioctl(handle
->fd
, SIOCSIWMODE
, &ireq
) == -1) {
453 * Scientist, you've failed.
456 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
457 "Please adjust manually.\n",
464 * Take this pcap out of the list of pcaps for which we
465 * have to take the interface out of some mode.
467 pcap_remove_from_pcaps_to_close(handle
);
470 if (handle
->md
.device
!= NULL
) {
471 free(handle
->md
.device
);
472 handle
->md
.device
= NULL
;
474 pcap_cleanup_live_common(handle
);
478 * Get a handle for a live capture from the given device. You can
479 * pass NULL as device to get all packages (without link level
480 * information of course). If you pass 1 as promisc the interface
481 * will be set to promiscous mode (XXX: I think this usage should
482 * be deprecated and functions be added to select that later allow
483 * modification of that values -- Torsten).
486 pcap_activate_linux(pcap_t
*handle
)
492 device
= handle
->opt
.source
;
494 handle
->inject_op
= pcap_inject_linux
;
495 handle
->setfilter_op
= pcap_setfilter_linux
;
496 handle
->setdirection_op
= pcap_setdirection_linux
;
497 handle
->set_datalink_op
= NULL
; /* can't change data link type */
498 handle
->getnonblock_op
= pcap_getnonblock_fd
;
499 handle
->setnonblock_op
= pcap_setnonblock_fd
;
500 handle
->cleanup_op
= pcap_cleanup_linux
;
501 handle
->read_op
= pcap_read_linux
;
502 handle
->stats_op
= pcap_stats_linux
;
505 * NULL and "any" are special devices which give us the hint to
506 * monitor all devices.
508 if (!device
|| strcmp(device
, "any") == 0) {
510 handle
->md
.device
= strdup("any");
511 if (handle
->opt
.promisc
) {
512 handle
->opt
.promisc
= 0;
513 /* Just a warning. */
514 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
515 "Promiscuous mode not supported on the \"any\" device");
516 status
= PCAP_WARNING_PROMISC_NOTSUP
;
520 handle
->md
.device
= strdup(device
);
522 if (handle
->md
.device
== NULL
) {
523 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
524 pcap_strerror(errno
) );
529 * Current Linux kernels use the protocol family PF_PACKET to
530 * allow direct access to all packets on the network while
531 * older kernels had a special socket type SOCK_PACKET to
532 * implement this feature.
533 * While this old implementation is kind of obsolete we need
534 * to be compatible with older kernels for a while so we are
535 * trying both methods with the newer method preferred.
538 if ((status
= activate_new(handle
)) == 1) {
541 * Try to use memory-mapped access.
543 if (activate_mmap(handle
) == 1)
544 return 0; /* we succeeded; nothing more to do */
546 else if (status
== 0) {
547 /* Non-fatal error; try old way */
548 if ((status
= activate_old(handle
)) == 1)
553 * Both methods to open the packet socket failed. Tidy
554 * up and report our failure (ebuf is expected to be
555 * set by the functions above).
560 if (handle
->opt
.buffer_size
== 0) {
562 * Set the socket buffer size to the specified value.
564 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
565 &handle
->opt
.buffer_size
,
566 sizeof(handle
->opt
.buffer_size
)) == -1) {
567 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
568 "SO_RCVBUF: %s", pcap_strerror(errno
));
574 /* Allocate the buffer */
576 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
577 if (!handle
->buffer
) {
578 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
579 "malloc: %s", pcap_strerror(errno
));
585 * "handle->fd" is a socket, so "select()" and "poll()"
588 handle
->selectable_fd
= handle
->fd
;
593 pcap_cleanup_linux(handle
);
598 * Read at most max_packets from the capture stream and call the callback
599 * for each of them. Returns the number of packets handled or -1 if an
603 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
606 * Currently, on Linux only one packet is delivered per read,
609 return pcap_read_packet(handle
, callback
, user
);
613 * Read a packet from the socket calling the handler provided by
614 * the user. Returns the number of packets received or -1 if an
618 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
622 #ifdef HAVE_PF_PACKET_SOCKETS
623 struct sockaddr_ll from
;
624 struct sll_header
*hdrp
;
626 struct sockaddr from
;
629 int packet_len
, caplen
;
630 struct pcap_pkthdr pcap_header
;
632 #ifdef HAVE_PF_PACKET_SOCKETS
634 * If this is a cooked device, leave extra room for a
635 * fake packet header.
637 if (handle
->md
.cooked
)
638 offset
= SLL_HDR_LEN
;
643 * This system doesn't have PF_PACKET sockets, so it doesn't
644 * support cooked devices.
649 /* Receive a single packet from the kernel */
651 bp
= handle
->buffer
+ handle
->offset
;
654 * Has "pcap_breakloop()" been called?
656 if (handle
->break_loop
) {
658 * Yes - clear the flag that indicates that it
659 * has, and return -2 as an indication that we
660 * were told to break out of the loop.
662 handle
->break_loop
= 0;
665 fromlen
= sizeof(from
);
666 packet_len
= recvfrom(
667 handle
->fd
, bp
+ offset
,
668 handle
->bufsize
- offset
, MSG_TRUNC
,
669 (struct sockaddr
*) &from
, &fromlen
);
670 } while (packet_len
== -1 && errno
== EINTR
);
672 /* Check if an error occured */
674 if (packet_len
== -1) {
676 return 0; /* no packet there */
678 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
679 "recvfrom: %s", pcap_strerror(errno
));
684 #ifdef HAVE_PF_PACKET_SOCKETS
685 if (!handle
->md
.sock_packet
) {
687 * Unfortunately, there is a window between socket() and
688 * bind() where the kernel may queue packets from any
689 * interface. If we're bound to a particular interface,
690 * discard packets not from that interface.
692 * (If socket filters are supported, we could do the
693 * same thing we do when changing the filter; however,
694 * that won't handle packet sockets without socket
695 * filter support, and it's a bit more complicated.
696 * It would save some instructions per packet, however.)
698 if (handle
->md
.ifindex
!= -1 &&
699 from
.sll_ifindex
!= handle
->md
.ifindex
)
703 * Do checks based on packet direction.
704 * We can only do this if we're using PF_PACKET; the
705 * address returned for SOCK_PACKET is a "sockaddr_pkt"
706 * which lacks the relevant packet type information.
708 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
711 * If this is from the loopback device, reject it;
712 * we'll see the packet as an incoming packet as well,
713 * and we don't want to see it twice.
715 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
719 * If the user only wants incoming packets, reject it.
721 if (handle
->direction
== PCAP_D_IN
)
726 * If the user only wants outgoing packets, reject it.
728 if (handle
->direction
== PCAP_D_OUT
)
734 #ifdef HAVE_PF_PACKET_SOCKETS
736 * If this is a cooked device, fill in the fake packet header.
738 if (handle
->md
.cooked
) {
740 * Add the length of the fake header to the length
741 * of packet data we read.
743 packet_len
+= SLL_HDR_LEN
;
745 hdrp
= (struct sll_header
*)bp
;
746 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
747 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
748 hdrp
->sll_halen
= htons(from
.sll_halen
);
749 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
750 (from
.sll_halen
> SLL_ADDRLEN
) ?
753 hdrp
->sll_protocol
= from
.sll_protocol
;
758 * XXX: According to the kernel source we should get the real
759 * packet len if calling recvfrom with MSG_TRUNC set. It does
760 * not seem to work here :(, but it is supported by this code
762 * To be honest the code RELIES on that feature so this is really
763 * broken with 2.2.x kernels.
764 * I spend a day to figure out what's going on and I found out
765 * that the following is happening:
767 * The packet comes from a random interface and the packet_rcv
768 * hook is called with a clone of the packet. That code inserts
769 * the packet into the receive queue of the packet socket.
770 * If a filter is attached to that socket that filter is run
771 * first - and there lies the problem. The default filter always
772 * cuts the packet at the snaplen:
777 * So the packet filter cuts down the packet. The recvfrom call
778 * says "hey, it's only 68 bytes, it fits into the buffer" with
779 * the result that we don't get the real packet length. This
780 * is valid at least until kernel 2.2.17pre6.
782 * We currently handle this by making a copy of the filter
783 * program, fixing all "ret" instructions with non-zero
784 * operands to have an operand of 65535 so that the filter
785 * doesn't truncate the packet, and supplying that modified
786 * filter to the kernel.
790 if (caplen
> handle
->snapshot
)
791 caplen
= handle
->snapshot
;
793 /* Run the packet filter if not using kernel filter */
794 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
795 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
796 packet_len
, caplen
) == 0)
798 /* rejected by filter */
803 /* Fill in our own header data */
805 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
806 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
807 "SIOCGSTAMP: %s", pcap_strerror(errno
));
810 pcap_header
.caplen
= caplen
;
811 pcap_header
.len
= packet_len
;
816 * Arguably, we should count them before we check the filter,
817 * as on many other platforms "ps_recv" counts packets
818 * handed to the filter rather than packets that passed
819 * the filter, but if filtering is done in the kernel, we
820 * can't get a count of packets that passed the filter,
821 * and that would mean the meaning of "ps_recv" wouldn't
822 * be the same on all Linux systems.
824 * XXX - it's not the same on all systems in any case;
825 * ideally, we should have a "get the statistics" call
826 * that supplies more counts and indicates which of them
827 * it supplies, so that we supply a count of packets
828 * handed to the filter only on platforms where that
829 * information is available.
831 * We count them here even if we can get the packet count
832 * from the kernel, as we can only determine at run time
833 * whether we'll be able to get it from the kernel (if
834 * HAVE_TPACKET_STATS isn't defined, we can't get it from
835 * the kernel, but if it is defined, the library might
836 * have been built with a 2.4 or later kernel, but we
837 * might be running on a 2.2[.x] kernel without Alexey
838 * Kuznetzov's turbopacket patches, and thus the kernel
839 * might not be able to supply those statistics). We
840 * could, I guess, try, when opening the socket, to get
841 * the statistics, and if we can not increment the count
842 * here, but it's not clear that always incrementing
843 * the count is more expensive than always testing a flag
846 * We keep the count in "md.packets_read", and use that for
847 * "ps_recv" if we can't get the statistics from the kernel.
848 * We do that because, if we *can* get the statistics from
849 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
850 * as running counts, as reading the statistics from the
851 * kernel resets the kernel statistics, and if we directly
852 * increment "md.stat.ps_recv" here, that means it will
853 * count packets *twice* on systems where we can get kernel
854 * statistics - once here, and once in pcap_stats_linux().
856 handle
->md
.packets_read
++;
858 /* Call the user supplied callback function */
859 callback(userdata
, &pcap_header
, bp
);
865 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
869 #ifdef HAVE_PF_PACKET_SOCKETS
870 if (!handle
->md
.sock_packet
) {
871 /* PF_PACKET socket */
872 if (handle
->md
.ifindex
== -1) {
874 * We don't support sending on the "any" device.
876 strlcpy(handle
->errbuf
,
877 "Sending packets isn't supported on the \"any\" device",
882 if (handle
->md
.cooked
) {
884 * We don't support sending on the "any" device.
886 * XXX - how do you send on a bound cooked-mode
888 * Is a "sendto()" required there?
890 strlcpy(handle
->errbuf
,
891 "Sending packets isn't supported in cooked mode",
898 ret
= send(handle
->fd
, buf
, size
, 0);
900 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
901 pcap_strerror(errno
));
908 * Get the statistics for the given packet capture handle.
909 * Reports the number of dropped packets iff the kernel supports
910 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
911 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
912 * patches); otherwise, that information isn't available, and we lie
913 * and report 0 as the count of dropped packets.
916 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
918 #ifdef HAVE_TPACKET_STATS
919 struct tpacket_stats kstats
;
920 socklen_t len
= sizeof (struct tpacket_stats
);
923 #ifdef HAVE_TPACKET_STATS
925 * Try to get the packet counts from the kernel.
927 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
928 &kstats
, &len
) > -1) {
930 * On systems where the PACKET_STATISTICS "getsockopt()"
931 * argument is supported on PF_PACKET sockets:
933 * "ps_recv" counts only packets that *passed* the
934 * filter, not packets that didn't pass the filter.
935 * This includes packets later dropped because we
936 * ran out of buffer space.
938 * "ps_drop" counts packets dropped because we ran
939 * out of buffer space. It doesn't count packets
940 * dropped by the interface driver. It counts only
941 * packets that passed the filter.
943 * Both statistics include packets not yet read from
944 * the kernel by libpcap, and thus not yet seen by
947 * In "linux/net/packet/af_packet.c", at least in the
948 * 2.4.9 kernel, "tp_packets" is incremented for every
949 * packet that passes the packet filter *and* is
950 * successfully queued on the socket; "tp_drops" is
951 * incremented for every packet dropped because there's
952 * not enough free space in the socket buffer.
954 * When the statistics are returned for a PACKET_STATISTICS
955 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
956 * so that "tp_packets" counts all packets handed to
957 * the PF_PACKET socket, including packets dropped because
958 * there wasn't room on the socket buffer - but not
959 * including packets that didn't pass the filter.
961 * In the BSD BPF, the count of received packets is
962 * incremented for every packet handed to BPF, regardless
963 * of whether it passed the filter.
965 * We can't make "pcap_stats()" work the same on both
966 * platforms, but the best approximation is to return
967 * "tp_packets" as the count of packets and "tp_drops"
968 * as the count of drops.
970 * Keep a running total because each call to
971 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
972 * resets the counters to zero.
974 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
975 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
976 *stats
= handle
->md
.stat
;
982 * If the error was EOPNOTSUPP, fall through, so that
983 * if you build the library on a system with
984 * "struct tpacket_stats" and run it on a system
985 * that doesn't, it works as it does if the library
986 * is built on a system without "struct tpacket_stats".
988 if (errno
!= EOPNOTSUPP
) {
989 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
990 "pcap_stats: %s", pcap_strerror(errno
));
996 * On systems where the PACKET_STATISTICS "getsockopt()" argument
997 * is not supported on PF_PACKET sockets:
999 * "ps_recv" counts only packets that *passed* the filter,
1000 * not packets that didn't pass the filter. It does not
1001 * count packets dropped because we ran out of buffer
1004 * "ps_drop" is not supported.
1006 * "ps_recv" doesn't include packets not yet read from
1007 * the kernel by libpcap.
1009 * We maintain the count of packets processed by libpcap in
1010 * "md.packets_read", for reasons described in the comment
1011 * at the end of pcap_read_packet(). We have no idea how many
1012 * packets were dropped.
1014 stats
->ps_recv
= handle
->md
.packets_read
;
1020 * Description string for the "any" device.
1022 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1025 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
1027 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
1031 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
1033 #endif /* HAVE_DAG_API */
1035 #ifdef HAVE_SEPTEL_API
1036 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
1038 #endif /* HAVE_SEPTEL_API */
1040 #ifdef PCAP_SUPPORT_BT
1041 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
1045 #ifdef PCAP_SUPPORT_USB
1046 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
1054 * Attach the given BPF code to the packet capture device.
1057 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
1059 #ifdef SO_ATTACH_FILTER
1060 struct sock_fprog fcode
;
1061 int can_filter_in_kernel
;
1068 strncpy(handle
->errbuf
, "setfilter: No filter specified",
1073 /* Make our private copy of the filter */
1075 if (install_bpf_program(handle
, filter
) < 0)
1076 /* install_bpf_program() filled in errbuf */
1080 * Run user level packet filter by default. Will be overriden if
1081 * installing a kernel filter succeeds.
1083 handle
->md
.use_bpf
= 0;
1085 /* Install kernel level filter if possible */
1087 #ifdef SO_ATTACH_FILTER
1089 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
1091 * fcode.len is an unsigned short for current kernel.
1092 * I have yet to see BPF-Code with that much
1093 * instructions but still it is possible. So for the
1094 * sake of correctness I added this check.
1096 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
1098 fcode
.filter
= NULL
;
1099 can_filter_in_kernel
= 0;
1101 #endif /* USHRT_MAX */
1104 * Oh joy, the Linux kernel uses struct sock_fprog instead
1105 * of struct bpf_program and of course the length field is
1106 * of different size. Pointed out by Sebastian
1108 * Oh, and we also need to fix it up so that all "ret"
1109 * instructions with non-zero operands have 65535 as the
1110 * operand, and so that, if we're in cooked mode, all
1111 * memory-reference instructions use special magic offsets
1112 * in references to the link-layer header and assume that
1113 * the link-layer payload begins at 0; "fix_program()"
1116 switch (fix_program(handle
, &fcode
)) {
1121 * Fatal error; just quit.
1122 * (The "default" case shouldn't happen; we
1123 * return -1 for that reason.)
1129 * The program performed checks that we can't make
1130 * work in the kernel.
1132 can_filter_in_kernel
= 0;
1137 * We have a filter that'll work in the kernel.
1139 can_filter_in_kernel
= 1;
1144 if (can_filter_in_kernel
) {
1145 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
1147 /* Installation succeded - using kernel filter. */
1148 handle
->md
.use_bpf
= 1;
1150 else if (err
== -1) /* Non-fatal error */
1153 * Print a warning if we weren't able to install
1154 * the filter for a reason other than "this kernel
1155 * isn't configured to support socket filters.
1157 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
1159 "Warning: Kernel filter failed: %s\n",
1160 pcap_strerror(errno
));
1166 * If we're not using the kernel filter, get rid of any kernel
1167 * filter that might've been there before, e.g. because the
1168 * previous filter could work in the kernel, or because some other
1169 * code attached a filter to the socket by some means other than
1170 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1171 * filter out packets that would pass the new userland filter.
1173 if (!handle
->md
.use_bpf
)
1174 reset_kernel_filter(handle
);
1177 * Free up the copy of the filter that was made by "fix_program()".
1179 if (fcode
.filter
!= NULL
)
1185 #endif /* SO_ATTACH_FILTER */
1191 * Set direction flag: Which packets do we accept on a forwarding
1192 * single device? IN, OUT or both?
1195 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1197 #ifdef HAVE_PF_PACKET_SOCKETS
1198 if (!handle
->md
.sock_packet
) {
1199 handle
->direction
= d
;
1204 * We're not using PF_PACKET sockets, so we can't determine
1205 * the direction of the packet.
1207 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1208 "Setting direction is not supported on SOCK_PACKET sockets");
1213 #ifdef HAVE_PF_PACKET_SOCKETS
1215 * Map the PACKET_ value to a LINUX_SLL_ value; we
1216 * want the same numerical value to be used in
1217 * the link-layer header even if the numerical values
1218 * for the PACKET_ #defines change, so that programs
1219 * that look at the packet type field will always be
1220 * able to handle DLT_LINUX_SLL captures.
1223 map_packet_type_to_sll_type(short int sll_pkttype
)
1225 switch (sll_pkttype
) {
1228 return htons(LINUX_SLL_HOST
);
1230 case PACKET_BROADCAST
:
1231 return htons(LINUX_SLL_BROADCAST
);
1233 case PACKET_MULTICAST
:
1234 return htons(LINUX_SLL_MULTICAST
);
1236 case PACKET_OTHERHOST
:
1237 return htons(LINUX_SLL_OTHERHOST
);
1239 case PACKET_OUTGOING
:
1240 return htons(LINUX_SLL_OUTGOING
);
1249 * Linux uses the ARP hardware type to identify the type of an
1250 * interface. pcap uses the DLT_xxx constants for this. This
1251 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1252 * constant, as arguments, and sets "handle->linktype" to the
1253 * appropriate DLT_XXX constant and sets "handle->offset" to
1254 * the appropriate value (to make "handle->offset" plus link-layer
1255 * header length be a multiple of 4, so that the link-layer payload
1256 * will be aligned on a 4-byte boundary when capturing packets).
1257 * (If the offset isn't set here, it'll be 0; add code as appropriate
1258 * for cases where it shouldn't be 0.)
1260 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1261 * in cooked mode; otherwise, we can't use cooked mode, so we have
1262 * to pick some type that works in raw mode, or fail.
1264 * Sets the link type to -1 if unable to map the type.
1266 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1272 * This is (presumably) a real Ethernet capture; give it a
1273 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1274 * that an application can let you choose it, in case you're
1275 * capturing DOCSIS traffic that a Cisco Cable Modem
1276 * Termination System is putting out onto an Ethernet (it
1277 * doesn't put an Ethernet header onto the wire, it puts raw
1278 * DOCSIS frames out on the wire inside the low-level
1279 * Ethernet framing).
1281 * XXX - are there any sorts of "fake Ethernet" that have
1282 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1283 * a Cisco CMTS won't put traffic onto it or get traffic
1284 * bridged onto it? ISDN is handled in "activate_new()",
1285 * as we fall back on cooked mode there; are there any
1288 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1290 * If that fails, just leave the list empty.
1292 if (handle
->dlt_list
!= NULL
) {
1293 handle
->dlt_list
[0] = DLT_EN10MB
;
1294 handle
->dlt_list
[1] = DLT_DOCSIS
;
1295 handle
->dlt_count
= 2;
1299 case ARPHRD_METRICOM
:
1300 case ARPHRD_LOOPBACK
:
1301 handle
->linktype
= DLT_EN10MB
;
1306 handle
->linktype
= DLT_EN3MB
;
1310 handle
->linktype
= DLT_AX25_KISS
;
1314 handle
->linktype
= DLT_PRONET
;
1318 handle
->linktype
= DLT_CHAOS
;
1321 #ifndef ARPHRD_IEEE802_TR
1322 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1324 case ARPHRD_IEEE802_TR
:
1325 case ARPHRD_IEEE802
:
1326 handle
->linktype
= DLT_IEEE802
;
1331 handle
->linktype
= DLT_ARCNET_LINUX
;
1334 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1335 #define ARPHRD_FDDI 774
1338 handle
->linktype
= DLT_FDDI
;
1342 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1343 #define ARPHRD_ATM 19
1347 * The Classical IP implementation in ATM for Linux
1348 * supports both what RFC 1483 calls "LLC Encapsulation",
1349 * in which each packet has an LLC header, possibly
1350 * with a SNAP header as well, prepended to it, and
1351 * what RFC 1483 calls "VC Based Multiplexing", in which
1352 * different virtual circuits carry different network
1353 * layer protocols, and no header is prepended to packets.
1355 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1356 * you can't use the ARPHRD_ type to find out whether
1357 * captured packets will have an LLC header, and,
1358 * while there's a socket ioctl to *set* the encapsulation
1359 * type, there's no ioctl to *get* the encapsulation type.
1363 * programs that dissect Linux Classical IP frames
1364 * would have to check for an LLC header and,
1365 * depending on whether they see one or not, dissect
1366 * the frame as LLC-encapsulated or as raw IP (I
1367 * don't know whether there's any traffic other than
1368 * IP that would show up on the socket, or whether
1369 * there's any support for IPv6 in the Linux
1370 * Classical IP code);
1372 * filter expressions would have to compile into
1373 * code that checks for an LLC header and does
1376 * Both of those are a nuisance - and, at least on systems
1377 * that support PF_PACKET sockets, we don't have to put
1378 * up with those nuisances; instead, we can just capture
1379 * in cooked mode. That's what we'll do, if we can.
1380 * Otherwise, we'll just fail.
1383 handle
->linktype
= DLT_LINUX_SLL
;
1385 handle
->linktype
= -1;
1388 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1389 #define ARPHRD_IEEE80211 801
1391 case ARPHRD_IEEE80211
:
1392 handle
->linktype
= DLT_IEEE802_11
;
1395 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1396 #define ARPHRD_IEEE80211_PRISM 802
1398 case ARPHRD_IEEE80211_PRISM
:
1399 handle
->linktype
= DLT_PRISM_HEADER
;
1402 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1403 #define ARPHRD_IEEE80211_RADIOTAP 803
1405 case ARPHRD_IEEE80211_RADIOTAP
:
1406 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1411 * Some PPP code in the kernel supplies no link-layer
1412 * header whatsoever to PF_PACKET sockets; other PPP
1413 * code supplies PPP link-layer headers ("syncppp.c");
1414 * some PPP code might supply random link-layer
1415 * headers (PPP over ISDN - there's code in Ethereal,
1416 * for example, to cope with PPP-over-ISDN captures
1417 * with which the Ethereal developers have had to cope,
1418 * heuristically trying to determine which of the
1419 * oddball link-layer headers particular packets have).
1421 * As such, we just punt, and run all PPP interfaces
1422 * in cooked mode, if we can; otherwise, we just treat
1423 * it as DLT_RAW, for now - if somebody needs to capture,
1424 * on a 2.0[.x] kernel, on PPP devices that supply a
1425 * link-layer header, they'll have to add code here to
1426 * map to the appropriate DLT_ type (possibly adding a
1427 * new DLT_ type, if necessary).
1430 handle
->linktype
= DLT_LINUX_SLL
;
1433 * XXX - handle ISDN types here? We can't fall
1434 * back on cooked sockets, so we'd have to
1435 * figure out from the device name what type of
1436 * link-layer encapsulation it's using, and map
1437 * that to an appropriate DLT_ value, meaning
1438 * we'd map "isdnN" devices to DLT_RAW (they
1439 * supply raw IP packets with no link-layer
1440 * header) and "isdY" devices to a new DLT_I4L_IP
1441 * type that has only an Ethernet packet type as
1442 * a link-layer header.
1444 * But sometimes we seem to get random crap
1445 * in the link-layer header when capturing on
1448 handle
->linktype
= DLT_RAW
;
1452 #ifndef ARPHRD_CISCO
1453 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1456 handle
->linktype
= DLT_C_HDLC
;
1459 /* Not sure if this is correct for all tunnels, but it
1463 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1471 #ifndef ARPHRD_RAWHDLC
1472 #define ARPHRD_RAWHDLC 518
1474 case ARPHRD_RAWHDLC
:
1476 #define ARPHRD_DLCI 15
1480 * XXX - should some of those be mapped to DLT_LINUX_SLL
1481 * instead? Should we just map all of them to DLT_LINUX_SLL?
1483 handle
->linktype
= DLT_RAW
;
1487 #define ARPHRD_FRAD 770
1490 handle
->linktype
= DLT_FRELAY
;
1493 case ARPHRD_LOCALTLK
:
1494 handle
->linktype
= DLT_LTALK
;
1498 #define ARPHRD_FCPP 784
1502 #define ARPHRD_FCAL 785
1506 #define ARPHRD_FCPL 786
1509 #ifndef ARPHRD_FCFABRIC
1510 #define ARPHRD_FCFABRIC 787
1512 case ARPHRD_FCFABRIC
:
1514 * We assume that those all mean RFC 2625 IP-over-
1515 * Fibre Channel, with the RFC 2625 header at
1516 * the beginning of the packet.
1518 handle
->linktype
= DLT_IP_OVER_FC
;
1522 #define ARPHRD_IRDA 783
1525 /* Don't expect IP packet out of this interfaces... */
1526 handle
->linktype
= DLT_LINUX_IRDA
;
1527 /* We need to save packet direction for IrDA decoding,
1528 * so let's use "Linux-cooked" mode. Jean II */
1529 //handle->md.cooked = 1;
1532 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1533 * is needed, please report it to <daniele@orlandi.com> */
1535 #define ARPHRD_LAPD 8445
1538 /* Don't expect IP packet out of this interfaces... */
1539 handle
->linktype
= DLT_LINUX_LAPD
;
1543 handle
->linktype
= -1;
1548 /* ===== Functions to interface to the newer kernels ================== */
1551 * Try to open a packet socket using the new kernel PF_PACKET interface.
1552 * Returns 1 on success, 0 on an error that means the new interface isn't
1553 * present (so the old SOCK_PACKET interface should be tried), and a
1554 * PCAP_ERROR_ value on an error that means that the old mechanism won't
1555 * work either (so it shouldn't be tried).
1558 activate_new(pcap_t
*handle
)
1560 #ifdef HAVE_PF_PACKET_SOCKETS
1561 int sock_fd
= -1, arptype
;
1563 struct packet_mreq mr
;
1564 const char* device
= handle
->opt
.source
;
1567 * Open a socket with protocol family packet. If a device is
1568 * given we try to open it in raw mode otherwise we use
1569 * the cooked interface.
1572 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
1573 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
1575 if (sock_fd
== -1) {
1576 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
1577 pcap_strerror(errno
) );
1578 return 0; /* try old mechanism */
1581 /* It seems the kernel supports the new interface. */
1582 handle
->md
.sock_packet
= 0;
1585 * Get the interface index of the loopback device.
1586 * If the attempt fails, don't fail, just set the
1587 * "md.lo_ifindex" to -1.
1589 * XXX - can there be more than one device that loops
1590 * packets back, i.e. devices other than "lo"? If so,
1591 * we'd need to find them all, and have an array of
1592 * indices for them, and check all of them in
1593 * "pcap_read_packet()".
1595 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
1598 * Default value for offset to align link-layer payload
1599 * on a 4-byte boundary.
1604 * What kind of frames do we have to deal with? Fall back
1605 * to cooked mode if we have an unknown interface type
1606 * or a type we know doesn't work well in raw mode.
1609 /* Assume for now we don't need cooked mode. */
1610 handle
->md
.cooked
= 0;
1612 if (handle
->opt
.rfmon
) {
1614 * We were asked to turn on monitor mode.
1615 * Do so before we get the link-layer type,
1616 * because entering monitor mode could change
1617 * the link-layer type.
1619 err
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
1627 * Nothing worked for turning monitor mode
1631 return PCAP_ERROR_RFMON_NOTSUP
;
1634 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
1639 map_arphrd_to_dlt(handle
, arptype
, 1);
1640 if (handle
->linktype
== -1 ||
1641 handle
->linktype
== DLT_LINUX_SLL
||
1642 handle
->linktype
== DLT_LINUX_IRDA
||
1643 handle
->linktype
== DLT_LINUX_LAPD
||
1644 (handle
->linktype
== DLT_EN10MB
&&
1645 (strncmp("isdn", device
, 4) == 0 ||
1646 strncmp("isdY", device
, 4) == 0))) {
1648 * Unknown interface type (-1), or a
1649 * device we explicitly chose to run
1650 * in cooked mode (e.g., PPP devices),
1651 * or an ISDN device (whose link-layer
1652 * type we can only determine by using
1653 * APIs that may be different on different
1654 * kernels) - reopen in cooked mode.
1656 if (close(sock_fd
) == -1) {
1657 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1658 "close: %s", pcap_strerror(errno
));
1661 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1663 if (sock_fd
== -1) {
1664 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1665 "socket: %s", pcap_strerror(errno
));
1668 handle
->md
.cooked
= 1;
1671 * Get rid of any link-layer type list
1672 * we allocated - this only supports cooked
1675 if (handle
->dlt_list
!= NULL
) {
1676 free(handle
->dlt_list
);
1677 handle
->dlt_list
= NULL
;
1678 handle
->dlt_count
= 0;
1681 if (handle
->linktype
== -1) {
1683 * Warn that we're falling back on
1684 * cooked mode; we may want to
1685 * update "map_arphrd_to_dlt()"
1686 * to handle the new type.
1688 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1690 "supported by libpcap - "
1691 "falling back to cooked "
1697 * IrDA capture is not a real "cooked" capture,
1698 * it's IrLAP frames, not IP packets. The
1699 * same applies to LAPD capture.
1701 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
1702 handle
->linktype
!= DLT_LINUX_LAPD
)
1703 handle
->linktype
= DLT_LINUX_SLL
;
1706 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
1708 if (handle
->md
.ifindex
== -1) {
1713 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
1714 handle
->errbuf
)) < 0) {
1719 return 0; /* try old mechanism */
1723 * This is cooked mode.
1725 handle
->md
.cooked
= 1;
1726 handle
->linktype
= DLT_LINUX_SLL
;
1729 * We're not bound to a device.
1730 * XXX - true? Or true only if we're using
1732 * For now, we're using this as an indication
1733 * that we can't transmit; stop doing that only
1734 * if we figure out how to transmit in cooked
1737 handle
->md
.ifindex
= -1;
1741 * Select promiscuous mode on if "promisc" is set.
1743 * Do not turn allmulti mode on if we don't select
1744 * promiscuous mode - on some devices (e.g., Orinoco
1745 * wireless interfaces), allmulti mode isn't supported
1746 * and the driver implements it by turning promiscuous
1747 * mode on, and that screws up the operation of the
1748 * card as a normal networking interface, and on no
1749 * other platform I know of does starting a non-
1750 * promiscuous capture affect which multicast packets
1751 * are received by the interface.
1755 * Hmm, how can we set promiscuous mode on all interfaces?
1756 * I am not sure if that is possible at all.
1759 if (device
&& handle
->opt
.promisc
) {
1760 memset(&mr
, 0, sizeof(mr
));
1761 mr
.mr_ifindex
= handle
->md
.ifindex
;
1762 mr
.mr_type
= PACKET_MR_PROMISC
;
1763 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
1764 &mr
, sizeof(mr
)) == -1) {
1765 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1766 "setsockopt: %s", pcap_strerror(errno
));
1773 * This is a 2.2[.x] or later kernel (we know that
1774 * because we're not using a SOCK_PACKET socket -
1775 * PF_PACKET is supported only in 2.2 and later
1778 * We can safely pass "recvfrom()" a byte count
1779 * based on the snapshot length.
1781 * If we're in cooked mode, make the snapshot length
1782 * large enough to hold a "cooked mode" header plus
1783 * 1 byte of packet data (so we don't pass a byte
1784 * count of 0 to "recvfrom()").
1786 if (handle
->md
.cooked
) {
1787 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
1788 handle
->snapshot
= SLL_HDR_LEN
+ 1;
1790 handle
->bufsize
= handle
->snapshot
;
1792 /* Save the socket FD in the pcap structure */
1793 handle
->fd
= sock_fd
;
1798 "New packet capturing interface not supported by build "
1799 "environment", PCAP_ERRBUF_SIZE
);
1805 activate_mmap(pcap_t
*handle
)
1807 #ifdef HAVE_PACKET_RING
1810 if (handle
->opt
.buffer_size
== 0) {
1811 /* by default request 2M for the ring buffer */
1812 handle
->opt
.buffer_size
= 2*1024*1024;
1814 ret
= create_ring(handle
);
1818 /* override some defaults and inherit the other fields from
1820 * handle->offset is used to get the current position into the rx ring
1821 * handle->cc is used to store the ring size */
1822 handle
->read_op
= pcap_read_linux_mmap
;
1823 handle
->cleanup_op
= pcap_cleanup_linux_mmap
;
1824 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
1825 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
1826 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
1827 handle
->selectable_fd
= handle
->fd
;
1829 #else /* HAVE_PACKET_RING */
1831 #endif /* HAVE_PACKET_RING */
1834 #ifdef HAVE_PACKET_RING
1837 compute_ring_block(int frame_size
, unsigned *block_size
, unsigned *frames_per_block
)
1839 /* compute the minumum block size that will handle this frame.
1840 * The block has to be page size aligned.
1841 * The max block size allowed by the kernel is arch-dependent and
1842 * it's not explicitly checked here. */
1843 *block_size
= getpagesize();
1844 while (*block_size
< frame_size
)
1847 *frames_per_block
= *block_size
/frame_size
;
1851 create_ring(pcap_t
*handle
)
1853 unsigned i
, j
, ringsize
, frames_per_block
;
1854 struct tpacket_req req
;
1856 /* Note that with large snapshot (say 64K) only a few frames
1857 * will be available in the ring even with pretty large ring size
1858 * (and a lot of memory will be unused).
1859 * The snap len should be carefully chosen to achive best
1861 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+TPACKET_HDRLEN
);
1862 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
1863 compute_ring_block(req
.tp_frame_size
, &req
.tp_block_size
, &frames_per_block
);
1864 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
1866 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
1867 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
1869 /* ask the kernel to create the ring */
1871 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1872 (void *) &req
, sizeof(req
))) {
1873 /* try to reduce requested ring size to prevent memory failure */
1874 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
1875 req
.tp_frame_nr
>>= 1;
1876 req
.tp_block_nr
= req
.tp_frame_nr
/frames_per_block
;
1879 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "can't create rx ring on "
1880 "packet socket %d: %d-%s", handle
->fd
, errno
,
1881 pcap_strerror(errno
));
1885 /* memory map the rx ring */
1886 ringsize
= req
.tp_block_nr
* req
.tp_block_size
;
1887 handle
->bp
= mmap(0, ringsize
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
1889 if (handle
->bp
== MAP_FAILED
) {
1890 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "can't mmap rx ring: %d-%s",
1891 errno
, pcap_strerror(errno
));
1893 /* clear the allocated ring on error*/
1894 destroy_ring(handle
);
1898 /* allocate a ring for each frame header pointer*/
1899 handle
->cc
= req
.tp_frame_nr
;
1900 handle
->buffer
= malloc(handle
->cc
* sizeof(struct tpacket_hdr
*));
1901 if (!handle
->buffer
) {
1902 destroy_ring(handle
);
1906 /* fill the header ring with proper frame ptr*/
1908 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
1909 u_char
*base
= &handle
->bp
[i
*req
.tp_block_size
];
1910 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
1911 RING_GET_FRAME(handle
) = (struct tpacket_hdr
*) base
;
1912 base
+= req
.tp_frame_size
;
1916 handle
->bufsize
= req
.tp_frame_size
;
1921 /* free all ring related resources*/
1923 destroy_ring(pcap_t
*handle
)
1925 /* tell the kernel to destroy the ring*/
1926 struct tpacket_req req
;
1927 memset(&req
, 0, sizeof(req
));
1928 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1929 (void *) &req
, sizeof(req
));
1931 /* if ring is mapped, unmap it*/
1933 /* need to re-compute the ring size */
1934 unsigned frames_per_block
, block_size
;
1935 compute_ring_block(handle
->bufsize
, &block_size
, &frames_per_block
);
1937 /* do not perform sanity check here: we can't recover any error */
1938 munmap(handle
->bp
, block_size
* handle
->cc
/ frames_per_block
);
1944 pcap_cleanup_linux_mmap( pcap_t
*handle
)
1946 destroy_ring(handle
);
1947 pcap_cleanup_linux(handle
);
1952 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
1954 /* use negative value of timeout to indicate non blocking ops */
1955 return (p
->md
.timeout
<0);
1959 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
1961 /* map each value to the corresponding 2's complement, to
1962 * preserve the timeout value provided with pcap_set_timeout */
1964 if (p
->md
.timeout
> 0)
1965 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
1967 if (p
->md
.timeout
< 0)
1968 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
1973 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
1978 /* wait for frames availability.*/
1979 if ((handle
->md
.timeout
>= 0) && !(RING_GET_FRAME(handle
)->tp_status
)) {
1980 struct pollfd pollinfo
;
1983 pollinfo
.fd
= handle
->fd
;
1984 pollinfo
.events
= POLLIN
;
1987 /* poll() requires a negative timeout to wait forever */
1988 ret
= poll(&pollinfo
, 1, (handle
->md
.timeout
> 0)?
1989 handle
->md
.timeout
: -1);
1990 if ((ret
< 0) && (errno
!= EINTR
)) {
1991 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1992 "can't poll on packet socket fd %d: %d-%s",
1993 handle
->fd
, errno
, pcap_strerror(errno
));
1996 /* check for break loop condition on interrupted syscall*/
1997 if (handle
->break_loop
) {
1998 handle
->break_loop
= 0;
2004 /* non-positive values of max_packets are used to require all
2005 * packets currently available in the ring */
2006 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
2008 struct sockaddr_ll
*sll
;
2009 struct pcap_pkthdr pcaphdr
;
2011 struct tpacket_hdr
* thdr
= RING_GET_FRAME(handle
);
2012 if (thdr
->tp_status
== TP_STATUS_KERNEL
)
2015 /* perform sanity check on internal offset. */
2016 if (thdr
->tp_mac
+thdr
->tp_snaplen
> handle
->bufsize
) {
2017 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2018 "corrupted frame on kernel ring mac "
2019 "offset %d + caplen %d > frame len %d",
2020 thdr
->tp_mac
, thdr
->tp_snaplen
, handle
->bufsize
);
2024 /* run filter on received packet
2025 * If the kernel filtering is enabled we need to run the
2026 * filter until all the frames present into the ring
2027 * at filter creation time are processed.
2028 * In such case md.use_bpf is used as a counter for the
2029 * packet we need to filter.
2030 * Note: alternatively it could be possible to stop applying
2031 * the filter when the ring became empty, but it can possibly
2032 * happen a lot later... */
2033 bp
= (unsigned char*)thdr
+ thdr
->tp_mac
;
2034 run_bpf
= (!handle
->md
.use_bpf
) ||
2035 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
2036 if (run_bpf
&& handle
->fcode
.bf_insns
&&
2037 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
2038 thdr
->tp_len
, thdr
->tp_snaplen
) == 0))
2041 /* check direction and interface index */
2042 sll
= (void*)thdr
+ TPACKET_ALIGN(sizeof(*thdr
));
2043 if ((sll
->sll_ifindex
== handle
->md
.lo_ifindex
) &&
2044 (sll
->sll_pkttype
== PACKET_OUTGOING
))
2047 /* get required packet info from ring header */
2048 pcaphdr
.ts
.tv_sec
= thdr
->tp_sec
;
2049 pcaphdr
.ts
.tv_usec
= thdr
->tp_usec
;
2050 pcaphdr
.caplen
= thdr
->tp_snaplen
;
2051 pcaphdr
.len
= thdr
->tp_len
;
2053 /* if required build in place the sll header*/
2054 if (handle
->md
.cooked
) {
2055 struct sll_header
*hdrp
;
2058 * The kernel should have left us with enough
2059 * space for an sll header; back up the packet
2060 * data pointer into that space, as that'll be
2061 * the beginning of the packet we pass to the
2067 * Let's make sure that's past the end of
2068 * the tpacket header, i.e. >=
2069 * ((u_char *)thdr + TPACKET_HDRLEN), so we
2070 * don't step on the header when we construct
2073 if (bp
< (u_char
*)thdr
+ TPACKET_HDRLEN
) {
2074 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2075 "cooked-mode frame doesn't have room for sll header");
2080 * OK, that worked; construct the sll header.
2082 hdrp
= (struct sll_header
*)bp
;
2083 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
2085 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
2086 hdrp
->sll_halen
= htons(sll
->sll_halen
);
2087 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
2088 hdrp
->sll_protocol
= sll
->sll_protocol
;
2090 /* update packet len */
2091 pcaphdr
.caplen
+= SLL_HDR_LEN
;
2092 pcaphdr
.len
+= SLL_HDR_LEN
;
2095 /* pass the packet to the user */
2097 callback(user
, &pcaphdr
, bp
);
2098 handle
->md
.packets_read
++;
2102 thdr
->tp_status
= TP_STATUS_KERNEL
;
2103 if (++handle
->offset
>= handle
->cc
)
2106 /* check for break loop condition*/
2107 if (handle
->break_loop
) {
2108 handle
->break_loop
= 0;
2116 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
2119 int ret
= pcap_setfilter_linux(handle
, filter
);
2123 /* if the kernel filter is enabled, we need to apply the filter on
2124 * all packets present into the ring. Get an upper bound of their number
2126 if (!handle
->md
.use_bpf
)
2129 /* walk the ring backward and count the free slot */
2130 offset
= handle
->offset
;
2131 if (--handle
->offset
< 0)
2132 handle
->offset
= handle
->cc
- 1;
2133 for (n
=0; n
< handle
->cc
; ++n
) {
2134 if (--handle
->offset
< 0)
2135 handle
->offset
= handle
->cc
- 1;
2136 if (RING_GET_FRAME(handle
)->tp_status
!= TP_STATUS_KERNEL
)
2140 /* be careful to not change current ring position */
2141 handle
->offset
= offset
;
2143 /* store the number of packets currently present in the ring */
2144 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
2148 #endif /* HAVE_PACKET_RING */
2151 #ifdef HAVE_PF_PACKET_SOCKETS
2153 * Return the index of the given device name. Fill ebuf and return
2157 iface_get_id(int fd
, const char *device
, char *ebuf
)
2161 memset(&ifr
, 0, sizeof(ifr
));
2162 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2164 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
2165 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2166 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
2170 return ifr
.ifr_ifindex
;
2174 * Bind the socket associated with FD to the given device.
2177 iface_bind(int fd
, int ifindex
, char *ebuf
)
2179 struct sockaddr_ll sll
;
2181 socklen_t errlen
= sizeof(err
);
2183 memset(&sll
, 0, sizeof(sll
));
2184 sll
.sll_family
= AF_PACKET
;
2185 sll
.sll_ifindex
= ifindex
;
2186 sll
.sll_protocol
= htons(ETH_P_ALL
);
2188 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
2189 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2190 "bind: %s", pcap_strerror(errno
));
2194 /* Any pending errors, e.g., network is down? */
2196 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2197 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2198 "getsockopt: %s", pcap_strerror(errno
));
2203 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2204 "bind: %s", pcap_strerror(err
));
2212 * Check whether the device supports the Wireless Extensions.
2213 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
2214 * if the device doesn't even exist.
2217 has_wext(int sock_fd
, const char *device
, char *ebuf
)
2219 #ifdef IW_MODE_MONITOR
2222 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2223 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2224 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2225 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
2227 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2228 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
2229 if (errno
== ENODEV
)
2230 return PCAP_ERROR_NO_SUCH_DEVICE
;
2236 * Per me si va ne la citta dolente,
2237 * Per me si va ne l'etterno dolore,
2239 * Lasciate ogne speranza, voi ch'intrate.
2254 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
2255 * on if it's not already on.
2257 * Returns 1 on success, 0 if we don't support the Wireless Extensions
2258 * on this device, or a PCAP_ERROR_ value if we do support them but
2259 * we weren't able to turn monitor mode on.
2262 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
2264 #ifdef IW_MODE_MONITOR
2266 * XXX - at least some adapters require non-Wireless Extensions
2267 * mechanisms to turn monitor mode on.
2269 * Atheros cards might require that a separate "monitor virtual access
2270 * point" be created, with later versions of the madwifi driver.
2272 * Some Intel Centrino adapters might require private ioctls to get
2273 * radio headers; the ipw2200 and ipw3945 drivers allow you to
2274 * configure a separate "rtapN" interface to capture in monitor
2275 * mode without preventing the adapter from operating normally.
2277 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
2278 * up, and if all drivers were converted to mac80211 drivers.
2282 struct iw_priv_args
*priv
;
2283 monitor_type montype
;
2290 * Does this device *support* the Wireless Extensions?
2292 err
= has_wext(sock_fd
, device
, handle
->errbuf
);
2294 return err
; /* either it doesn't or the device doesn't even exist */
2296 * Try to get all the Wireless Extensions private ioctls
2297 * supported by this device.
2299 * First, get the size of the buffer we need, by supplying no
2300 * buffer and a length of 0. If the device supports private
2301 * ioctls, it should return E2BIG, with ireq.u.data.length set
2302 * to the length we need. If it doesn't support them, it should
2303 * return EOPNOTSUPP.
2305 memset(&ireq
, 0, sizeof ireq
);
2306 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2307 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2308 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2309 ireq
.u
.data
.pointer
= args
;
2310 ireq
.u
.data
.length
= 0;
2311 ireq
.u
.data
.flags
= 0;
2312 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
2313 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2314 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
2318 if (errno
== EOPNOTSUPP
) {
2320 * No private ioctls, so we assume that there's only one
2321 * DLT_ for monitor mode.
2325 if (errno
!= E2BIG
) {
2329 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2330 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
2333 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
2335 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2336 "malloc: %s", pcap_strerror(errno
));
2339 ireq
.u
.data
.pointer
= priv
;
2340 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
2341 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2342 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
2348 * Look for private ioctls to turn monitor mode on or, if
2349 * monitor mode is on, to set the header type.
2351 montype
= MONITOR_WEXT
;
2353 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
2354 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
2356 * Hostap driver, use this one.
2357 * Set monitor mode first.
2358 * You can set it to 0 to get DLT_IEEE80211,
2359 * 1 to get DLT_PRISM, or 2 to get
2360 * DLT_IEEE80211_RADIO_AVS.
2362 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2364 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2366 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2368 montype
= MONITOR_HOSTAP
;
2372 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
2374 * Prism54 driver, use this one.
2375 * Set monitor mode first.
2376 * You can set it to 2 to get DLT_IEEE80211
2377 * or 3 or get DLT_PRISM.
2379 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2381 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2383 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2385 montype
= MONITOR_PRISM54
;
2389 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
2391 * RT2570 driver, use this one.
2392 * Do this after turning monitor mode on.
2393 * You can set it to 1 to get DLT_PRISM or 2
2394 * to get DLT_IEEE80211.
2396 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2398 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2400 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2402 montype
= MONITOR_RT2570
;
2406 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
2408 * RT73 driver, use this one.
2409 * Do this after turning monitor mode on.
2410 * Its argument is a *string*; you can
2411 * set it to "1" to get DLT_PRISM or "2"
2412 * to get DLT_IEEE80211.
2414 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
2416 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
2418 montype
= MONITOR_RT73
;
2422 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
2424 * One of the RTL8xxx drivers, use this one.
2425 * It can only be done after monitor mode
2426 * has been turned on. You can set it to 1
2427 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
2429 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2431 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2433 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2435 montype
= MONITOR_RTL8XXX
;
2439 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
2441 * RT2500 or RT61 driver, use this one.
2442 * It has one one-byte parameter; set
2443 * u.data.length to 1 and u.data.pointer to
2444 * point to the parameter.
2445 * It doesn't itself turn monitor mode on.
2446 * You can set it to 1 to allow transmitting
2447 * in monitor mode(?) and get DLT_IEEE80211,
2448 * or set it to 0 to disallow transmitting in
2449 * monitor mode(?) and get DLT_PRISM.
2451 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2453 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
2455 montype
= MONITOR_RT2500
;
2459 if (strcmp(priv
[i
].name
, "monitor") == 0) {
2461 * Either ACX100 or hostap, use this one.
2462 * It turns monitor mode on.
2463 * If it takes two arguments, it's ACX100;
2464 * the first argument is 1 for DLT_PRISM
2465 * or 2 for DLT_IEEE80211, and the second
2466 * argument is the channel on which to
2467 * run. If it takes one argument, it's
2468 * HostAP, and the argument is 2 for
2469 * DLT_IEEE80211 and 3 for DLT_PRISM.
2471 * If we see this, we don't quit, as this
2472 * might be a version of the hostap driver
2473 * that also supports "monitor_type".
2475 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2477 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2479 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
2482 montype
= MONITOR_PRISM
;
2487 montype
= MONITOR_ACX100
;
2499 * XXX - ipw3945? islism?
2505 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2506 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2507 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2508 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
2510 * We probably won't be able to set the mode, either.
2512 return PCAP_ERROR_RFMON_NOTSUP
;
2516 * Is it currently in monitor mode?
2518 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
2520 * Yes. Just leave things as they are.
2521 * We don't offer multiple link-layer types, as
2522 * changing the link-layer type out from under
2523 * somebody else capturing in monitor mode would
2524 * be considered rude.
2529 * No. We have to put the adapter into rfmon mode.
2533 * If we haven't already done so, arrange to have
2534 * "pcap_close_all()" called when we exit.
2536 if (!pcap_do_addexit(handle
)) {
2538 * "atexit()" failed; don't put the interface
2539 * in rfmon mode, just give up.
2541 return PCAP_ERROR_RFMON_NOTSUP
;
2545 * Save the old mode.
2547 handle
->md
.oldmode
= ireq
.u
.mode
;
2550 * Put the adapter in rfmon mode. How we do this depends
2551 * on whether we have a special private ioctl or not.
2553 if (montype
== MONITOR_PRISM
) {
2555 * We have the "monitor" private ioctl, but none of
2556 * the other private ioctls. Use this, and select
2559 * If it fails, just fall back on SIOCSIWMODE.
2561 memset(&ireq
, 0, sizeof ireq
);
2562 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2563 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2564 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2565 ireq
.u
.data
.length
= 1; /* 1 argument */
2566 args
[0] = 3; /* request Prism header */
2567 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
2568 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
2571 * Note that we have to put the old mode back
2572 * when we close the device.
2574 handle
->md
.must_clear
|= MUST_CLEAR_RFMON
;
2577 * Add this to the list of pcaps to close
2580 pcap_add_to_pcaps_to_close(handle
);
2586 * Failure. Fall back on SIOCSIWMODE.
2591 * First, turn monitor mode on.
2593 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2594 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2595 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2596 ireq
.u
.mode
= IW_MODE_MONITOR
;
2597 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
2599 * Scientist, you've failed.
2601 return PCAP_ERROR_RFMON_NOTSUP
;
2605 * Now select the appropriate radio header.
2611 * We don't have any private ioctl to set the header.
2615 case MONITOR_HOSTAP
:
2617 * Select the AVS header if we can, otherwise
2618 * select the Prism header.
2620 memset(&ireq
, 0, sizeof ireq
);
2621 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2622 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2623 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2624 args
[0] = 2; /* request AVS header */
2625 memcpy(ireq
.u
.name
, args
, sizeof (int));
2626 if (ioctl(sock_fd
, cmd
, &ireq
) == -1) {
2628 * Failure - try the Prism header.
2630 memset(&ireq
, 0, sizeof ireq
);
2631 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2632 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2633 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2634 args
[0] = 1; /* request Prism header */
2635 memcpy(ireq
.u
.name
, args
, sizeof (int));
2636 ioctl(sock_fd
, cmd
, &ireq
);
2642 * The private ioctl failed.
2646 case MONITOR_PRISM54
:
2648 * Select the Prism header.
2650 memset(&ireq
, 0, sizeof ireq
);
2651 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2652 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2653 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2654 args
[0] = 3; /* request Prism header */
2655 memcpy(ireq
.u
.name
, args
, sizeof (int));
2656 ioctl(sock_fd
, cmd
, &ireq
);
2659 case MONITOR_ACX100
:
2661 * Get the current channel.
2663 memset(&ireq
, 0, sizeof ireq
);
2664 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2665 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2666 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2667 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
2668 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2669 "%s: SIOCGIWFREQ: %s", device
,
2670 pcap_strerror(errno
));
2673 channel
= ireq
.u
.freq
.m
;
2676 * Select the Prism header, and set the channel to the
2679 memset(&ireq
, 0, sizeof ireq
);
2680 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2681 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2682 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2683 args
[0] = 1; /* request Prism header */
2684 args
[1] = channel
; /* set channel */
2685 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
2686 ioctl(sock_fd
, cmd
, &ireq
);
2689 case MONITOR_RT2500
:
2691 * Disallow transmission - that turns on the
2694 memset(&ireq
, 0, sizeof ireq
);
2695 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2696 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2697 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2698 args
[0] = 0; /* disallow transmitting */
2699 memcpy(ireq
.u
.name
, args
, sizeof (int));
2700 ioctl(sock_fd
, cmd
, &ireq
);
2703 case MONITOR_RT2570
:
2705 * Force the Prism header.
2707 memset(&ireq
, 0, sizeof ireq
);
2708 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2709 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2710 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2711 args
[0] = 1; /* request Prism header */
2712 memcpy(ireq
.u
.name
, args
, sizeof (int));
2713 ioctl(sock_fd
, cmd
, &ireq
);
2718 * Force the Prism header.
2720 memset(&ireq
, 0, sizeof ireq
);
2721 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2722 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2723 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2724 ireq
.u
.data
.length
= 1; /* 1 argument */
2725 ireq
.u
.data
.pointer
= "1";
2726 ireq
.u
.data
.flags
= 0;
2727 ioctl(sock_fd
, cmd
, &ireq
);
2730 case MONITOR_RTL8XXX
:
2732 * Force the Prism header.
2734 memset(&ireq
, 0, sizeof ireq
);
2735 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2736 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2737 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2738 args
[0] = 1; /* request Prism header */
2739 memcpy(ireq
.u
.name
, args
, sizeof (int));
2740 ioctl(sock_fd
, cmd
, &ireq
);
2745 * Note that we have to put the old mode back when we
2748 handle
->md
.must_clear
|= MUST_CLEAR_RFMON
;
2751 * Add this to the list of pcaps to close when we exit.
2753 pcap_add_to_pcaps_to_close(handle
);
2758 * We don't have the Wireless Extensions available, so we can't
2765 #endif /* HAVE_PF_PACKET_SOCKETS */
2767 /* ===== Functions to interface to the older kernels ================== */
2770 * Try to open a packet socket using the old kernel interface.
2771 * Returns 1 on success and a PCAP_ERROR_ value on an error.
2774 activate_old(pcap_t
*handle
)
2778 const char *device
= handle
->opt
.source
;
2779 struct utsname utsname
;
2782 /* Open the socket */
2784 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
2785 if (handle
->fd
== -1) {
2786 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2787 "socket: %s", pcap_strerror(errno
));
2788 return PCAP_ERROR_PERM_DENIED
;
2791 /* It worked - we are using the old interface */
2792 handle
->md
.sock_packet
= 1;
2794 /* ...which means we get the link-layer header. */
2795 handle
->md
.cooked
= 0;
2797 /* Bind to the given device */
2800 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
2804 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
2808 * Try to get the link-layer type.
2810 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
2815 * Try to find the DLT_ type corresponding to that
2818 map_arphrd_to_dlt(handle
, arptype
, 0);
2819 if (handle
->linktype
== -1) {
2820 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2821 "unknown arptype %d", arptype
);
2825 /* Go to promisc mode if requested */
2827 if (handle
->opt
.promisc
) {
2828 memset(&ifr
, 0, sizeof(ifr
));
2829 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2830 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2831 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2832 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
2835 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
2837 * Promiscuous mode isn't currently on,
2838 * so turn it on, and remember that
2839 * we should turn it off when the
2844 * If we haven't already done so, arrange
2845 * to have "pcap_close_all()" called when
2848 if (!pcap_do_addexit(handle
)) {
2850 * "atexit()" failed; don't put
2851 * the interface in promiscuous
2852 * mode, just give up.
2857 ifr
.ifr_flags
|= IFF_PROMISC
;
2858 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2859 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2861 pcap_strerror(errno
));
2864 handle
->md
.must_clear
|= MUST_CLEAR_PROMISC
;
2867 * Add this to the list of pcaps
2868 * to close when we exit.
2870 pcap_add_to_pcaps_to_close(handle
);
2875 * Compute the buffer size.
2877 * We're using SOCK_PACKET, so this might be a 2.0[.x]
2878 * kernel, and might require special handling - check.
2880 if (uname(&utsname
) < 0 ||
2881 strncmp(utsname
.release
, "2.0", 3) == 0) {
2883 * Either we couldn't find out what kernel release
2884 * this is, or it's a 2.0[.x] kernel.
2886 * In the 2.0[.x] kernel, a "recvfrom()" on
2887 * a SOCK_PACKET socket, with MSG_TRUNC set, will
2888 * return the number of bytes read, so if we pass
2889 * a length based on the snapshot length, it'll
2890 * return the number of bytes from the packet
2891 * copied to userland, not the actual length
2894 * This means that, for example, the IP dissector
2895 * in tcpdump will get handed a packet length less
2896 * than the length in the IP header, and will
2897 * complain about "truncated-ip".
2899 * So we don't bother trying to copy from the
2900 * kernel only the bytes in which we're interested,
2901 * but instead copy them all, just as the older
2902 * versions of libpcap for Linux did.
2904 * The buffer therefore needs to be big enough to
2905 * hold the largest packet we can get from this
2906 * device. Unfortunately, we can't get the MRU
2907 * of the network; we can only get the MTU. The
2908 * MTU may be too small, in which case a packet larger
2909 * than the buffer size will be truncated *and* we
2910 * won't get the actual packet size.
2912 * However, if the snapshot length is larger than
2913 * the buffer size based on the MTU, we use the
2914 * snapshot length as the buffer size, instead;
2915 * this means that with a sufficiently large snapshot
2916 * length we won't artificially truncate packets
2917 * to the MTU-based size.
2919 * This mess just one of many problems with packet
2920 * capture on 2.0[.x] kernels; you really want a
2921 * 2.2[.x] or later kernel if you want packet capture
2924 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
2927 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
2928 if (handle
->bufsize
< handle
->snapshot
)
2929 handle
->bufsize
= handle
->snapshot
;
2932 * This is a 2.2[.x] or later kernel.
2934 * We can safely pass "recvfrom()" a byte count
2935 * based on the snapshot length.
2937 handle
->bufsize
= handle
->snapshot
;
2941 * Default value for offset to align link-layer payload
2942 * on a 4-byte boundary.
2950 * Bind the socket associated with FD to the given device using the
2951 * interface of the old kernels.
2954 iface_bind_old(int fd
, const char *device
, char *ebuf
)
2956 struct sockaddr saddr
;
2958 socklen_t errlen
= sizeof(err
);
2960 memset(&saddr
, 0, sizeof(saddr
));
2961 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
2962 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
2963 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2964 "bind: %s", pcap_strerror(errno
));
2968 /* Any pending errors, e.g., network is down? */
2970 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2971 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2972 "getsockopt: %s", pcap_strerror(errno
));
2977 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2978 "bind: %s", pcap_strerror(err
));
2986 /* ===== System calls available on all supported kernels ============== */
2989 * Query the kernel for the MTU of the given interface.
2992 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
2997 return BIGGER_THAN_ALL_MTUS
;
2999 memset(&ifr
, 0, sizeof(ifr
));
3000 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3002 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
3003 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3004 "SIOCGIFMTU: %s", pcap_strerror(errno
));
3012 * Get the hardware type of the given interface as ARPHRD_xxx constant.
3015 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
3019 memset(&ifr
, 0, sizeof(ifr
));
3020 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3022 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
3023 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3024 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
3025 if (errno
== ENODEV
) {
3029 return PCAP_ERROR_NO_SUCH_DEVICE
;
3034 return ifr
.ifr_hwaddr
.sa_family
;
3037 #ifdef SO_ATTACH_FILTER
3039 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
3043 register struct bpf_insn
*p
;
3048 * Make a copy of the filter, and modify that copy if
3051 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
3052 len
= handle
->fcode
.bf_len
;
3053 f
= (struct bpf_insn
*)malloc(prog_size
);
3055 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3056 "malloc: %s", pcap_strerror(errno
));
3059 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
3061 fcode
->filter
= (struct sock_filter
*) f
;
3063 for (i
= 0; i
< len
; ++i
) {
3066 * What type of instruction is this?
3068 switch (BPF_CLASS(p
->code
)) {
3072 * It's a return instruction; is the snapshot
3073 * length a constant, rather than the contents
3074 * of the accumulator?
3076 if (BPF_MODE(p
->code
) == BPF_K
) {
3078 * Yes - if the value to be returned,
3079 * i.e. the snapshot length, is anything
3080 * other than 0, make it 65535, so that
3081 * the packet is truncated by "recvfrom()",
3082 * not by the filter.
3084 * XXX - there's nothing we can easily do
3085 * if it's getting the value from the
3086 * accumulator; we'd have to insert
3087 * code to force non-zero values to be
3098 * It's a load instruction; is it loading
3101 switch (BPF_MODE(p
->code
)) {
3107 * Yes; are we in cooked mode?
3109 if (handle
->md
.cooked
) {
3111 * Yes, so we need to fix this
3114 if (fix_offset(p
) < 0) {
3116 * We failed to do so.
3117 * Return 0, so our caller
3118 * knows to punt to userland.
3128 return 1; /* we succeeded */
3132 fix_offset(struct bpf_insn
*p
)
3135 * What's the offset?
3137 if (p
->k
>= SLL_HDR_LEN
) {
3139 * It's within the link-layer payload; that starts at an
3140 * offset of 0, as far as the kernel packet filter is
3141 * concerned, so subtract the length of the link-layer
3144 p
->k
-= SLL_HDR_LEN
;
3145 } else if (p
->k
== 14) {
3147 * It's the protocol field; map it to the special magic
3148 * kernel offset for that field.
3150 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
3153 * It's within the header, but it's not one of those
3154 * fields; we can't do that in the kernel, so punt
3163 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
3165 int total_filter_on
= 0;
3171 * The socket filter code doesn't discard all packets queued
3172 * up on the socket when the filter is changed; this means
3173 * that packets that don't match the new filter may show up
3174 * after the new filter is put onto the socket, if those
3175 * packets haven't yet been read.
3177 * This means, for example, that if you do a tcpdump capture
3178 * with a filter, the first few packets in the capture might
3179 * be packets that wouldn't have passed the filter.
3181 * We therefore discard all packets queued up on the socket
3182 * when setting a kernel filter. (This isn't an issue for
3183 * userland filters, as the userland filtering is done after
3184 * packets are queued up.)
3186 * To flush those packets, we put the socket in read-only mode,
3187 * and read packets from the socket until there are no more to
3190 * In order to keep that from being an infinite loop - i.e.,
3191 * to keep more packets from arriving while we're draining
3192 * the queue - we put the "total filter", which is a filter
3193 * that rejects all packets, onto the socket before draining
3196 * This code deliberately ignores any errors, so that you may
3197 * get bogus packets if an error occurs, rather than having
3198 * the filtering done in userland even if it could have been
3199 * done in the kernel.
3201 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
3202 &total_fcode
, sizeof(total_fcode
)) == 0) {
3206 * Note that we've put the total filter onto the socket.
3208 total_filter_on
= 1;
3211 * Save the socket's current mode, and put it in
3212 * non-blocking mode; we drain it by reading packets
3213 * until we get an error (which is normally a
3214 * "nothing more to be read" error).
3216 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
3217 if (save_mode
!= -1 &&
3218 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
3219 while (recv(handle
->fd
, &drain
, sizeof drain
,
3223 fcntl(handle
->fd
, F_SETFL
, save_mode
);
3224 if (save_errno
!= EAGAIN
) {
3226 reset_kernel_filter(handle
);
3227 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3228 "recv: %s", pcap_strerror(save_errno
));
3235 * Now attach the new filter.
3237 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
3238 fcode
, sizeof(*fcode
));
3239 if (ret
== -1 && total_filter_on
) {
3241 * Well, we couldn't set that filter on the socket,
3242 * but we could set the total filter on the socket.
3244 * This could, for example, mean that the filter was
3245 * too big to put into the kernel, so we'll have to
3246 * filter in userland; in any case, we'll be doing
3247 * filtering in userland, so we need to remove the
3248 * total filter so we see packets.
3253 * XXX - if this fails, we're really screwed;
3254 * we have the total filter on the socket,
3255 * and it won't come off. What do we do then?
3257 reset_kernel_filter(handle
);
3265 reset_kernel_filter(pcap_t
*handle
)
3268 * setsockopt() barfs unless it get a dummy parameter.
3269 * valgrind whines unless the value is initialized,
3270 * as it has no idea that setsockopt() ignores its
3275 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
3276 &dummy
, sizeof(dummy
));