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.129.2.14 2008-04-07 04:06:36 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_close_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_close_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
);
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_close_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_close_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
->close_op
= pcap_close_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");
519 handle
->md
.device
= strdup(device
);
521 if (handle
->md
.device
== NULL
) {
522 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
523 pcap_strerror(errno
) );
528 * Current Linux kernels use the protocol family PF_PACKET to
529 * allow direct access to all packets on the network while
530 * older kernels had a special socket type SOCK_PACKET to
531 * implement this feature.
532 * While this old implementation is kind of obsolete we need
533 * to be compatible with older kernels for a while so we are
534 * trying both methods with the newer method preferred.
537 if ((err
= activate_new(handle
)) == 1) {
540 * Try to use memory-mapped access.
542 if (activate_mmap(handle
) == 1)
543 return 0; /* we succeeded; nothing more to do */
546 /* Non-fatal error; try old way */
547 if ((err
= activate_old(handle
)) == 1)
552 * Both methods to open the packet socket failed. Tidy
553 * up and report our failure (ebuf is expected to be
554 * set by the functions above).
559 if (handle
->opt
.buffer_size
== 0) {
561 * Set the socket buffer size to the specified value.
563 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_RCVBUF
,
564 &handle
->opt
.buffer_size
,
565 sizeof(handle
->opt
.buffer_size
)) == -1) {
566 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
567 "SO_RCVBUF: %s", pcap_strerror(errno
));
573 /* Allocate the buffer */
575 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
576 if (!handle
->buffer
) {
577 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
578 "malloc: %s", pcap_strerror(errno
));
584 * "handle->fd" is a socket, so "select()" and "poll()"
587 handle
->selectable_fd
= handle
->fd
;
593 if (handle
->md
.device
!= NULL
) {
594 free(handle
->md
.device
);
595 handle
->md
.device
= NULL
;
601 * Read at most max_packets from the capture stream and call the callback
602 * for each of them. Returns the number of packets handled or -1 if an
606 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
609 * Currently, on Linux only one packet is delivered per read,
612 return pcap_read_packet(handle
, callback
, user
);
616 * Read a packet from the socket calling the handler provided by
617 * the user. Returns the number of packets received or -1 if an
621 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
625 #ifdef HAVE_PF_PACKET_SOCKETS
626 struct sockaddr_ll from
;
627 struct sll_header
*hdrp
;
629 struct sockaddr from
;
632 int packet_len
, caplen
;
633 struct pcap_pkthdr pcap_header
;
635 #ifdef HAVE_PF_PACKET_SOCKETS
637 * If this is a cooked device, leave extra room for a
638 * fake packet header.
640 if (handle
->md
.cooked
)
641 offset
= SLL_HDR_LEN
;
646 * This system doesn't have PF_PACKET sockets, so it doesn't
647 * support cooked devices.
652 /* Receive a single packet from the kernel */
654 bp
= handle
->buffer
+ handle
->offset
;
657 * Has "pcap_breakloop()" been called?
659 if (handle
->break_loop
) {
661 * Yes - clear the flag that indicates that it
662 * has, and return -2 as an indication that we
663 * were told to break out of the loop.
665 handle
->break_loop
= 0;
668 fromlen
= sizeof(from
);
669 packet_len
= recvfrom(
670 handle
->fd
, bp
+ offset
,
671 handle
->bufsize
- offset
, MSG_TRUNC
,
672 (struct sockaddr
*) &from
, &fromlen
);
673 } while (packet_len
== -1 && errno
== EINTR
);
675 /* Check if an error occured */
677 if (packet_len
== -1) {
679 return 0; /* no packet there */
681 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
682 "recvfrom: %s", pcap_strerror(errno
));
687 #ifdef HAVE_PF_PACKET_SOCKETS
688 if (!handle
->md
.sock_packet
) {
690 * Unfortunately, there is a window between socket() and
691 * bind() where the kernel may queue packets from any
692 * interface. If we're bound to a particular interface,
693 * discard packets not from that interface.
695 * (If socket filters are supported, we could do the
696 * same thing we do when changing the filter; however,
697 * that won't handle packet sockets without socket
698 * filter support, and it's a bit more complicated.
699 * It would save some instructions per packet, however.)
701 if (handle
->md
.ifindex
!= -1 &&
702 from
.sll_ifindex
!= handle
->md
.ifindex
)
706 * Do checks based on packet direction.
707 * We can only do this if we're using PF_PACKET; the
708 * address returned for SOCK_PACKET is a "sockaddr_pkt"
709 * which lacks the relevant packet type information.
711 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
714 * If this is from the loopback device, reject it;
715 * we'll see the packet as an incoming packet as well,
716 * and we don't want to see it twice.
718 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
722 * If the user only wants incoming packets, reject it.
724 if (handle
->direction
== PCAP_D_IN
)
729 * If the user only wants outgoing packets, reject it.
731 if (handle
->direction
== PCAP_D_OUT
)
737 #ifdef HAVE_PF_PACKET_SOCKETS
739 * If this is a cooked device, fill in the fake packet header.
741 if (handle
->md
.cooked
) {
743 * Add the length of the fake header to the length
744 * of packet data we read.
746 packet_len
+= SLL_HDR_LEN
;
748 hdrp
= (struct sll_header
*)bp
;
749 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
750 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
751 hdrp
->sll_halen
= htons(from
.sll_halen
);
752 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
753 (from
.sll_halen
> SLL_ADDRLEN
) ?
756 hdrp
->sll_protocol
= from
.sll_protocol
;
761 * XXX: According to the kernel source we should get the real
762 * packet len if calling recvfrom with MSG_TRUNC set. It does
763 * not seem to work here :(, but it is supported by this code
765 * To be honest the code RELIES on that feature so this is really
766 * broken with 2.2.x kernels.
767 * I spend a day to figure out what's going on and I found out
768 * that the following is happening:
770 * The packet comes from a random interface and the packet_rcv
771 * hook is called with a clone of the packet. That code inserts
772 * the packet into the receive queue of the packet socket.
773 * If a filter is attached to that socket that filter is run
774 * first - and there lies the problem. The default filter always
775 * cuts the packet at the snaplen:
780 * So the packet filter cuts down the packet. The recvfrom call
781 * says "hey, it's only 68 bytes, it fits into the buffer" with
782 * the result that we don't get the real packet length. This
783 * is valid at least until kernel 2.2.17pre6.
785 * We currently handle this by making a copy of the filter
786 * program, fixing all "ret" instructions with non-zero
787 * operands to have an operand of 65535 so that the filter
788 * doesn't truncate the packet, and supplying that modified
789 * filter to the kernel.
793 if (caplen
> handle
->snapshot
)
794 caplen
= handle
->snapshot
;
796 /* Run the packet filter if not using kernel filter */
797 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
798 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
799 packet_len
, caplen
) == 0)
801 /* rejected by filter */
806 /* Fill in our own header data */
808 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
809 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
810 "SIOCGSTAMP: %s", pcap_strerror(errno
));
813 pcap_header
.caplen
= caplen
;
814 pcap_header
.len
= packet_len
;
819 * Arguably, we should count them before we check the filter,
820 * as on many other platforms "ps_recv" counts packets
821 * handed to the filter rather than packets that passed
822 * the filter, but if filtering is done in the kernel, we
823 * can't get a count of packets that passed the filter,
824 * and that would mean the meaning of "ps_recv" wouldn't
825 * be the same on all Linux systems.
827 * XXX - it's not the same on all systems in any case;
828 * ideally, we should have a "get the statistics" call
829 * that supplies more counts and indicates which of them
830 * it supplies, so that we supply a count of packets
831 * handed to the filter only on platforms where that
832 * information is available.
834 * We count them here even if we can get the packet count
835 * from the kernel, as we can only determine at run time
836 * whether we'll be able to get it from the kernel (if
837 * HAVE_TPACKET_STATS isn't defined, we can't get it from
838 * the kernel, but if it is defined, the library might
839 * have been built with a 2.4 or later kernel, but we
840 * might be running on a 2.2[.x] kernel without Alexey
841 * Kuznetzov's turbopacket patches, and thus the kernel
842 * might not be able to supply those statistics). We
843 * could, I guess, try, when opening the socket, to get
844 * the statistics, and if we can not increment the count
845 * here, but it's not clear that always incrementing
846 * the count is more expensive than always testing a flag
849 * We keep the count in "md.packets_read", and use that for
850 * "ps_recv" if we can't get the statistics from the kernel.
851 * We do that because, if we *can* get the statistics from
852 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
853 * as running counts, as reading the statistics from the
854 * kernel resets the kernel statistics, and if we directly
855 * increment "md.stat.ps_recv" here, that means it will
856 * count packets *twice* on systems where we can get kernel
857 * statistics - once here, and once in pcap_stats_linux().
859 handle
->md
.packets_read
++;
861 /* Call the user supplied callback function */
862 callback(userdata
, &pcap_header
, bp
);
868 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
872 #ifdef HAVE_PF_PACKET_SOCKETS
873 if (!handle
->md
.sock_packet
) {
874 /* PF_PACKET socket */
875 if (handle
->md
.ifindex
== -1) {
877 * We don't support sending on the "any" device.
879 strlcpy(handle
->errbuf
,
880 "Sending packets isn't supported on the \"any\" device",
885 if (handle
->md
.cooked
) {
887 * We don't support sending on the "any" device.
889 * XXX - how do you send on a bound cooked-mode
891 * Is a "sendto()" required there?
893 strlcpy(handle
->errbuf
,
894 "Sending packets isn't supported in cooked mode",
901 ret
= send(handle
->fd
, buf
, size
, 0);
903 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
904 pcap_strerror(errno
));
911 * Get the statistics for the given packet capture handle.
912 * Reports the number of dropped packets iff the kernel supports
913 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
914 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
915 * patches); otherwise, that information isn't available, and we lie
916 * and report 0 as the count of dropped packets.
919 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
921 #ifdef HAVE_TPACKET_STATS
922 struct tpacket_stats kstats
;
923 socklen_t len
= sizeof (struct tpacket_stats
);
926 #ifdef HAVE_TPACKET_STATS
928 * Try to get the packet counts from the kernel.
930 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
931 &kstats
, &len
) > -1) {
933 * On systems where the PACKET_STATISTICS "getsockopt()"
934 * argument is supported on PF_PACKET sockets:
936 * "ps_recv" counts only packets that *passed* the
937 * filter, not packets that didn't pass the filter.
938 * This includes packets later dropped because we
939 * ran out of buffer space.
941 * "ps_drop" counts packets dropped because we ran
942 * out of buffer space. It doesn't count packets
943 * dropped by the interface driver. It counts only
944 * packets that passed the filter.
946 * Both statistics include packets not yet read from
947 * the kernel by libpcap, and thus not yet seen by
950 * In "linux/net/packet/af_packet.c", at least in the
951 * 2.4.9 kernel, "tp_packets" is incremented for every
952 * packet that passes the packet filter *and* is
953 * successfully queued on the socket; "tp_drops" is
954 * incremented for every packet dropped because there's
955 * not enough free space in the socket buffer.
957 * When the statistics are returned for a PACKET_STATISTICS
958 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
959 * so that "tp_packets" counts all packets handed to
960 * the PF_PACKET socket, including packets dropped because
961 * there wasn't room on the socket buffer - but not
962 * including packets that didn't pass the filter.
964 * In the BSD BPF, the count of received packets is
965 * incremented for every packet handed to BPF, regardless
966 * of whether it passed the filter.
968 * We can't make "pcap_stats()" work the same on both
969 * platforms, but the best approximation is to return
970 * "tp_packets" as the count of packets and "tp_drops"
971 * as the count of drops.
973 * Keep a running total because each call to
974 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
975 * resets the counters to zero.
977 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
978 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
979 *stats
= handle
->md
.stat
;
985 * If the error was EOPNOTSUPP, fall through, so that
986 * if you build the library on a system with
987 * "struct tpacket_stats" and run it on a system
988 * that doesn't, it works as it does if the library
989 * is built on a system without "struct tpacket_stats".
991 if (errno
!= EOPNOTSUPP
) {
992 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
993 "pcap_stats: %s", pcap_strerror(errno
));
999 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1000 * is not supported on PF_PACKET sockets:
1002 * "ps_recv" counts only packets that *passed* the filter,
1003 * not packets that didn't pass the filter. It does not
1004 * count packets dropped because we ran out of buffer
1007 * "ps_drop" is not supported.
1009 * "ps_recv" doesn't include packets not yet read from
1010 * the kernel by libpcap.
1012 * We maintain the count of packets processed by libpcap in
1013 * "md.packets_read", for reasons described in the comment
1014 * at the end of pcap_read_packet(). We have no idea how many
1015 * packets were dropped.
1017 stats
->ps_recv
= handle
->md
.packets_read
;
1023 * Description string for the "any" device.
1025 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1028 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
1030 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
1034 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
1036 #endif /* HAVE_DAG_API */
1038 #ifdef HAVE_SEPTEL_API
1039 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
1041 #endif /* HAVE_SEPTEL_API */
1043 #ifdef PCAP_SUPPORT_BT
1044 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
1048 #ifdef PCAP_SUPPORT_USB
1049 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
1057 * Attach the given BPF code to the packet capture device.
1060 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
1062 #ifdef SO_ATTACH_FILTER
1063 struct sock_fprog fcode
;
1064 int can_filter_in_kernel
;
1071 strncpy(handle
->errbuf
, "setfilter: No filter specified",
1076 /* Make our private copy of the filter */
1078 if (install_bpf_program(handle
, filter
) < 0)
1079 /* install_bpf_program() filled in errbuf */
1083 * Run user level packet filter by default. Will be overriden if
1084 * installing a kernel filter succeeds.
1086 handle
->md
.use_bpf
= 0;
1088 /* Install kernel level filter if possible */
1090 #ifdef SO_ATTACH_FILTER
1092 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
1094 * fcode.len is an unsigned short for current kernel.
1095 * I have yet to see BPF-Code with that much
1096 * instructions but still it is possible. So for the
1097 * sake of correctness I added this check.
1099 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
1101 fcode
.filter
= NULL
;
1102 can_filter_in_kernel
= 0;
1104 #endif /* USHRT_MAX */
1107 * Oh joy, the Linux kernel uses struct sock_fprog instead
1108 * of struct bpf_program and of course the length field is
1109 * of different size. Pointed out by Sebastian
1111 * Oh, and we also need to fix it up so that all "ret"
1112 * instructions with non-zero operands have 65535 as the
1113 * operand, and so that, if we're in cooked mode, all
1114 * memory-reference instructions use special magic offsets
1115 * in references to the link-layer header and assume that
1116 * the link-layer payload begins at 0; "fix_program()"
1119 switch (fix_program(handle
, &fcode
)) {
1124 * Fatal error; just quit.
1125 * (The "default" case shouldn't happen; we
1126 * return -1 for that reason.)
1132 * The program performed checks that we can't make
1133 * work in the kernel.
1135 can_filter_in_kernel
= 0;
1140 * We have a filter that'll work in the kernel.
1142 can_filter_in_kernel
= 1;
1147 if (can_filter_in_kernel
) {
1148 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
1150 /* Installation succeded - using kernel filter. */
1151 handle
->md
.use_bpf
= 1;
1153 else if (err
== -1) /* Non-fatal error */
1156 * Print a warning if we weren't able to install
1157 * the filter for a reason other than "this kernel
1158 * isn't configured to support socket filters.
1160 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
1162 "Warning: Kernel filter failed: %s\n",
1163 pcap_strerror(errno
));
1169 * If we're not using the kernel filter, get rid of any kernel
1170 * filter that might've been there before, e.g. because the
1171 * previous filter could work in the kernel, or because some other
1172 * code attached a filter to the socket by some means other than
1173 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1174 * filter out packets that would pass the new userland filter.
1176 if (!handle
->md
.use_bpf
)
1177 reset_kernel_filter(handle
);
1180 * Free up the copy of the filter that was made by "fix_program()".
1182 if (fcode
.filter
!= NULL
)
1188 #endif /* SO_ATTACH_FILTER */
1194 * Set direction flag: Which packets do we accept on a forwarding
1195 * single device? IN, OUT or both?
1198 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1200 #ifdef HAVE_PF_PACKET_SOCKETS
1201 if (!handle
->md
.sock_packet
) {
1202 handle
->direction
= d
;
1207 * We're not using PF_PACKET sockets, so we can't determine
1208 * the direction of the packet.
1210 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1211 "Setting direction is not supported on SOCK_PACKET sockets");
1216 #ifdef HAVE_PF_PACKET_SOCKETS
1218 * Map the PACKET_ value to a LINUX_SLL_ value; we
1219 * want the same numerical value to be used in
1220 * the link-layer header even if the numerical values
1221 * for the PACKET_ #defines change, so that programs
1222 * that look at the packet type field will always be
1223 * able to handle DLT_LINUX_SLL captures.
1226 map_packet_type_to_sll_type(short int sll_pkttype
)
1228 switch (sll_pkttype
) {
1231 return htons(LINUX_SLL_HOST
);
1233 case PACKET_BROADCAST
:
1234 return htons(LINUX_SLL_BROADCAST
);
1236 case PACKET_MULTICAST
:
1237 return htons(LINUX_SLL_MULTICAST
);
1239 case PACKET_OTHERHOST
:
1240 return htons(LINUX_SLL_OTHERHOST
);
1242 case PACKET_OUTGOING
:
1243 return htons(LINUX_SLL_OUTGOING
);
1252 * Linux uses the ARP hardware type to identify the type of an
1253 * interface. pcap uses the DLT_xxx constants for this. This
1254 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1255 * constant, as arguments, and sets "handle->linktype" to the
1256 * appropriate DLT_XXX constant and sets "handle->offset" to
1257 * the appropriate value (to make "handle->offset" plus link-layer
1258 * header length be a multiple of 4, so that the link-layer payload
1259 * will be aligned on a 4-byte boundary when capturing packets).
1260 * (If the offset isn't set here, it'll be 0; add code as appropriate
1261 * for cases where it shouldn't be 0.)
1263 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1264 * in cooked mode; otherwise, we can't use cooked mode, so we have
1265 * to pick some type that works in raw mode, or fail.
1267 * Sets the link type to -1 if unable to map the type.
1269 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1275 * This is (presumably) a real Ethernet capture; give it a
1276 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1277 * that an application can let you choose it, in case you're
1278 * capturing DOCSIS traffic that a Cisco Cable Modem
1279 * Termination System is putting out onto an Ethernet (it
1280 * doesn't put an Ethernet header onto the wire, it puts raw
1281 * DOCSIS frames out on the wire inside the low-level
1282 * Ethernet framing).
1284 * XXX - are there any sorts of "fake Ethernet" that have
1285 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1286 * a Cisco CMTS won't put traffic onto it or get traffic
1287 * bridged onto it? ISDN is handled in "activate_new()",
1288 * as we fall back on cooked mode there; are there any
1291 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1293 * If that fails, just leave the list empty.
1295 if (handle
->dlt_list
!= NULL
) {
1296 handle
->dlt_list
[0] = DLT_EN10MB
;
1297 handle
->dlt_list
[1] = DLT_DOCSIS
;
1298 handle
->dlt_count
= 2;
1302 case ARPHRD_METRICOM
:
1303 case ARPHRD_LOOPBACK
:
1304 handle
->linktype
= DLT_EN10MB
;
1309 handle
->linktype
= DLT_EN3MB
;
1313 handle
->linktype
= DLT_AX25_KISS
;
1317 handle
->linktype
= DLT_PRONET
;
1321 handle
->linktype
= DLT_CHAOS
;
1324 #ifndef ARPHRD_IEEE802_TR
1325 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1327 case ARPHRD_IEEE802_TR
:
1328 case ARPHRD_IEEE802
:
1329 handle
->linktype
= DLT_IEEE802
;
1334 handle
->linktype
= DLT_ARCNET_LINUX
;
1337 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1338 #define ARPHRD_FDDI 774
1341 handle
->linktype
= DLT_FDDI
;
1345 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1346 #define ARPHRD_ATM 19
1350 * The Classical IP implementation in ATM for Linux
1351 * supports both what RFC 1483 calls "LLC Encapsulation",
1352 * in which each packet has an LLC header, possibly
1353 * with a SNAP header as well, prepended to it, and
1354 * what RFC 1483 calls "VC Based Multiplexing", in which
1355 * different virtual circuits carry different network
1356 * layer protocols, and no header is prepended to packets.
1358 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1359 * you can't use the ARPHRD_ type to find out whether
1360 * captured packets will have an LLC header, and,
1361 * while there's a socket ioctl to *set* the encapsulation
1362 * type, there's no ioctl to *get* the encapsulation type.
1366 * programs that dissect Linux Classical IP frames
1367 * would have to check for an LLC header and,
1368 * depending on whether they see one or not, dissect
1369 * the frame as LLC-encapsulated or as raw IP (I
1370 * don't know whether there's any traffic other than
1371 * IP that would show up on the socket, or whether
1372 * there's any support for IPv6 in the Linux
1373 * Classical IP code);
1375 * filter expressions would have to compile into
1376 * code that checks for an LLC header and does
1379 * Both of those are a nuisance - and, at least on systems
1380 * that support PF_PACKET sockets, we don't have to put
1381 * up with those nuisances; instead, we can just capture
1382 * in cooked mode. That's what we'll do, if we can.
1383 * Otherwise, we'll just fail.
1386 handle
->linktype
= DLT_LINUX_SLL
;
1388 handle
->linktype
= -1;
1391 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1392 #define ARPHRD_IEEE80211 801
1394 case ARPHRD_IEEE80211
:
1395 handle
->linktype
= DLT_IEEE802_11
;
1398 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1399 #define ARPHRD_IEEE80211_PRISM 802
1401 case ARPHRD_IEEE80211_PRISM
:
1402 handle
->linktype
= DLT_PRISM_HEADER
;
1405 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1406 #define ARPHRD_IEEE80211_RADIOTAP 803
1408 case ARPHRD_IEEE80211_RADIOTAP
:
1409 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1414 * Some PPP code in the kernel supplies no link-layer
1415 * header whatsoever to PF_PACKET sockets; other PPP
1416 * code supplies PPP link-layer headers ("syncppp.c");
1417 * some PPP code might supply random link-layer
1418 * headers (PPP over ISDN - there's code in Ethereal,
1419 * for example, to cope with PPP-over-ISDN captures
1420 * with which the Ethereal developers have had to cope,
1421 * heuristically trying to determine which of the
1422 * oddball link-layer headers particular packets have).
1424 * As such, we just punt, and run all PPP interfaces
1425 * in cooked mode, if we can; otherwise, we just treat
1426 * it as DLT_RAW, for now - if somebody needs to capture,
1427 * on a 2.0[.x] kernel, on PPP devices that supply a
1428 * link-layer header, they'll have to add code here to
1429 * map to the appropriate DLT_ type (possibly adding a
1430 * new DLT_ type, if necessary).
1433 handle
->linktype
= DLT_LINUX_SLL
;
1436 * XXX - handle ISDN types here? We can't fall
1437 * back on cooked sockets, so we'd have to
1438 * figure out from the device name what type of
1439 * link-layer encapsulation it's using, and map
1440 * that to an appropriate DLT_ value, meaning
1441 * we'd map "isdnN" devices to DLT_RAW (they
1442 * supply raw IP packets with no link-layer
1443 * header) and "isdY" devices to a new DLT_I4L_IP
1444 * type that has only an Ethernet packet type as
1445 * a link-layer header.
1447 * But sometimes we seem to get random crap
1448 * in the link-layer header when capturing on
1451 handle
->linktype
= DLT_RAW
;
1455 #ifndef ARPHRD_CISCO
1456 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1459 handle
->linktype
= DLT_C_HDLC
;
1462 /* Not sure if this is correct for all tunnels, but it
1466 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1474 #ifndef ARPHRD_RAWHDLC
1475 #define ARPHRD_RAWHDLC 518
1477 case ARPHRD_RAWHDLC
:
1479 #define ARPHRD_DLCI 15
1483 * XXX - should some of those be mapped to DLT_LINUX_SLL
1484 * instead? Should we just map all of them to DLT_LINUX_SLL?
1486 handle
->linktype
= DLT_RAW
;
1490 #define ARPHRD_FRAD 770
1493 handle
->linktype
= DLT_FRELAY
;
1496 case ARPHRD_LOCALTLK
:
1497 handle
->linktype
= DLT_LTALK
;
1501 #define ARPHRD_FCPP 784
1505 #define ARPHRD_FCAL 785
1509 #define ARPHRD_FCPL 786
1512 #ifndef ARPHRD_FCFABRIC
1513 #define ARPHRD_FCFABRIC 787
1515 case ARPHRD_FCFABRIC
:
1517 * We assume that those all mean RFC 2625 IP-over-
1518 * Fibre Channel, with the RFC 2625 header at
1519 * the beginning of the packet.
1521 handle
->linktype
= DLT_IP_OVER_FC
;
1525 #define ARPHRD_IRDA 783
1528 /* Don't expect IP packet out of this interfaces... */
1529 handle
->linktype
= DLT_LINUX_IRDA
;
1530 /* We need to save packet direction for IrDA decoding,
1531 * so let's use "Linux-cooked" mode. Jean II */
1532 //handle->md.cooked = 1;
1535 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1536 * is needed, please report it to <daniele@orlandi.com> */
1538 #define ARPHRD_LAPD 8445
1541 /* Don't expect IP packet out of this interfaces... */
1542 handle
->linktype
= DLT_LINUX_LAPD
;
1546 handle
->linktype
= -1;
1551 /* ===== Functions to interface to the newer kernels ================== */
1554 * Try to open a packet socket using the new kernel PF_PACKET interface.
1555 * Returns 1 on success, 0 on an error that means the new interface isn't
1556 * present (so the old SOCK_PACKET interface should be tried), and a
1557 * PCAP_ERROR_ value on an error that means that the old mechanism won't
1558 * work either (so it shouldn't be tried).
1561 activate_new(pcap_t
*handle
)
1563 #ifdef HAVE_PF_PACKET_SOCKETS
1564 int sock_fd
= -1, arptype
;
1566 struct packet_mreq mr
;
1567 const char* device
= handle
->opt
.source
;
1570 * Open a socket with protocol family packet. If a device is
1571 * given we try to open it in raw mode otherwise we use
1572 * the cooked interface.
1575 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
1576 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
1578 if (sock_fd
== -1) {
1579 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
1580 pcap_strerror(errno
) );
1581 return 0; /* try old mechanism */
1584 /* It seems the kernel supports the new interface. */
1585 handle
->md
.sock_packet
= 0;
1588 * Get the interface index of the loopback device.
1589 * If the attempt fails, don't fail, just set the
1590 * "md.lo_ifindex" to -1.
1592 * XXX - can there be more than one device that loops
1593 * packets back, i.e. devices other than "lo"? If so,
1594 * we'd need to find them all, and have an array of
1595 * indices for them, and check all of them in
1596 * "pcap_read_packet()".
1598 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", handle
->errbuf
);
1601 * Default value for offset to align link-layer payload
1602 * on a 4-byte boundary.
1607 * What kind of frames do we have to deal with? Fall back
1608 * to cooked mode if we have an unknown interface type
1609 * or a type we know doesn't work well in raw mode.
1612 /* Assume for now we don't need cooked mode. */
1613 handle
->md
.cooked
= 0;
1615 if (handle
->opt
.rfmon
) {
1617 * We were asked to turn on monitor mode.
1618 * Do so before we get the link-layer type,
1619 * because entering monitor mode could change
1620 * the link-layer type.
1622 err
= enter_rfmon_mode_wext(handle
, sock_fd
, device
);
1630 * Nothing worked for turning monitor mode
1634 return PCAP_ERROR_RFMON_NOTSUP
;
1637 arptype
= iface_get_arptype(sock_fd
, device
, handle
->errbuf
);
1642 map_arphrd_to_dlt(handle
, arptype
, 1);
1643 if (handle
->linktype
== -1 ||
1644 handle
->linktype
== DLT_LINUX_SLL
||
1645 handle
->linktype
== DLT_LINUX_IRDA
||
1646 handle
->linktype
== DLT_LINUX_LAPD
||
1647 (handle
->linktype
== DLT_EN10MB
&&
1648 (strncmp("isdn", device
, 4) == 0 ||
1649 strncmp("isdY", device
, 4) == 0))) {
1651 * Unknown interface type (-1), or a
1652 * device we explicitly chose to run
1653 * in cooked mode (e.g., PPP devices),
1654 * or an ISDN device (whose link-layer
1655 * type we can only determine by using
1656 * APIs that may be different on different
1657 * kernels) - reopen in cooked mode.
1659 if (close(sock_fd
) == -1) {
1660 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1661 "close: %s", pcap_strerror(errno
));
1664 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1666 if (sock_fd
== -1) {
1667 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1668 "socket: %s", pcap_strerror(errno
));
1671 handle
->md
.cooked
= 1;
1674 * Get rid of any link-layer type list
1675 * we allocated - this only supports cooked
1678 if (handle
->dlt_list
!= NULL
) {
1679 free(handle
->dlt_list
);
1680 handle
->dlt_list
= NULL
;
1681 handle
->dlt_count
= 0;
1684 if (handle
->linktype
== -1) {
1686 * Warn that we're falling back on
1687 * cooked mode; we may want to
1688 * update "map_arphrd_to_dlt()"
1689 * to handle the new type.
1691 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1693 "supported by libpcap - "
1694 "falling back to cooked "
1700 * IrDA capture is not a real "cooked" capture,
1701 * it's IrLAP frames, not IP packets. The
1702 * same applies to LAPD capture.
1704 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
1705 handle
->linktype
!= DLT_LINUX_LAPD
)
1706 handle
->linktype
= DLT_LINUX_SLL
;
1709 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
,
1711 if (handle
->md
.ifindex
== -1) {
1716 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
1717 handle
->errbuf
)) < 0) {
1722 return 0; /* try old mechanism */
1726 * This is cooked mode.
1728 handle
->md
.cooked
= 1;
1729 handle
->linktype
= DLT_LINUX_SLL
;
1732 * We're not bound to a device.
1733 * XXX - true? Or true only if we're using
1735 * For now, we're using this as an indication
1736 * that we can't transmit; stop doing that only
1737 * if we figure out how to transmit in cooked
1740 handle
->md
.ifindex
= -1;
1744 * Select promiscuous mode on if "promisc" is set.
1746 * Do not turn allmulti mode on if we don't select
1747 * promiscuous mode - on some devices (e.g., Orinoco
1748 * wireless interfaces), allmulti mode isn't supported
1749 * and the driver implements it by turning promiscuous
1750 * mode on, and that screws up the operation of the
1751 * card as a normal networking interface, and on no
1752 * other platform I know of does starting a non-
1753 * promiscuous capture affect which multicast packets
1754 * are received by the interface.
1758 * Hmm, how can we set promiscuous mode on all interfaces?
1759 * I am not sure if that is possible at all.
1762 if (device
&& handle
->opt
.promisc
) {
1763 memset(&mr
, 0, sizeof(mr
));
1764 mr
.mr_ifindex
= handle
->md
.ifindex
;
1765 mr
.mr_type
= PACKET_MR_PROMISC
;
1766 if (setsockopt(sock_fd
, SOL_PACKET
, PACKET_ADD_MEMBERSHIP
,
1767 &mr
, sizeof(mr
)) == -1) {
1768 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1769 "setsockopt: %s", pcap_strerror(errno
));
1776 * This is a 2.2[.x] or later kernel (we know that
1777 * because we're not using a SOCK_PACKET socket -
1778 * PF_PACKET is supported only in 2.2 and later
1781 * We can safely pass "recvfrom()" a byte count
1782 * based on the snapshot length.
1784 * If we're in cooked mode, make the snapshot length
1785 * large enough to hold a "cooked mode" header plus
1786 * 1 byte of packet data (so we don't pass a byte
1787 * count of 0 to "recvfrom()").
1789 if (handle
->md
.cooked
) {
1790 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
1791 handle
->snapshot
= SLL_HDR_LEN
+ 1;
1793 handle
->bufsize
= handle
->snapshot
;
1795 /* Save the socket FD in the pcap structure */
1796 handle
->fd
= sock_fd
;
1801 "New packet capturing interface not supported by build "
1802 "environment", PCAP_ERRBUF_SIZE
);
1808 activate_mmap(pcap_t
*handle
)
1810 #ifdef HAVE_PACKET_RING
1813 if (handle
->opt
.buffer_size
== 0) {
1814 /* by default request 2M for the ring buffer */
1815 handle
->opt
.buffer_size
= 2*1024*1024;
1817 ret
= create_ring(handle
);
1821 /* override some defaults and inherit the other fields from
1823 * handle->offset is used to get the current position into the rx ring
1824 * handle->cc is used to store the ring size */
1825 handle
->read_op
= pcap_read_linux_mmap
;
1826 handle
->close_op
= pcap_close_linux_mmap
;
1827 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
1828 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
1829 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
1830 handle
->selectable_fd
= handle
->fd
;
1832 #else /* HAVE_PACKET_RING */
1834 #endif /* HAVE_PACKET_RING */
1837 #ifdef HAVE_PACKET_RING
1840 compute_ring_block(int frame_size
, unsigned *block_size
, unsigned *frames_per_block
)
1842 /* compute the minumum block size that will handle this frame.
1843 * The block has to be page size aligned.
1844 * The max block size allowed by the kernel is arch-dependent and
1845 * it's not explicitly checked here. */
1846 *block_size
= getpagesize();
1847 while (*block_size
< frame_size
)
1850 *frames_per_block
= *block_size
/frame_size
;
1854 create_ring(pcap_t
*handle
)
1856 unsigned i
, j
, ringsize
, frames_per_block
;
1857 struct tpacket_req req
;
1859 /* Note that with large snapshot (say 64K) only a few frames
1860 * will be available in the ring even with pretty large ring size
1861 * (and a lot of memory will be unused).
1862 * The snap len should be carefully chosen to achive best
1864 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+TPACKET_HDRLEN
);
1865 req
.tp_frame_nr
= handle
->opt
.buffer_size
/req
.tp_frame_size
;
1866 compute_ring_block(req
.tp_frame_size
, &req
.tp_block_size
, &frames_per_block
);
1867 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
1869 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
1870 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
1872 /* ask the kernel to create the ring */
1874 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1875 (void *) &req
, sizeof(req
))) {
1876 /* try to reduce requested ring size to prevent memory failure */
1877 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
1878 req
.tp_frame_nr
>>= 1;
1879 req
.tp_block_nr
= req
.tp_frame_nr
/frames_per_block
;
1882 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "can't create rx ring on "
1883 "packet socket %d: %d-%s", handle
->fd
, errno
,
1884 pcap_strerror(errno
));
1888 /* memory map the rx ring */
1889 ringsize
= req
.tp_block_nr
* req
.tp_block_size
;
1890 handle
->bp
= mmap(0, ringsize
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
1892 if (handle
->bp
== MAP_FAILED
) {
1893 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "can't mmap rx ring: %d-%s",
1894 errno
, pcap_strerror(errno
));
1896 /* clear the allocated ring on error*/
1897 destroy_ring(handle
);
1901 /* allocate a ring for each frame header pointer*/
1902 handle
->cc
= req
.tp_frame_nr
;
1903 handle
->buffer
= malloc(handle
->cc
* sizeof(struct tpacket_hdr
*));
1904 if (!handle
->buffer
) {
1905 destroy_ring(handle
);
1909 /* fill the header ring with proper frame ptr*/
1911 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
1912 u_char
*base
= &handle
->bp
[i
*req
.tp_block_size
];
1913 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
1914 RING_GET_FRAME(handle
) = (struct tpacket_hdr
*) base
;
1915 base
+= req
.tp_frame_size
;
1919 handle
->bufsize
= req
.tp_frame_size
;
1924 /* free all ring related resources*/
1926 destroy_ring(pcap_t
*handle
)
1928 /* tell the kernel to destroy the ring*/
1929 struct tpacket_req req
;
1930 memset(&req
, 0, sizeof(req
));
1931 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1932 (void *) &req
, sizeof(req
));
1934 /* if ring is mapped, unmap it*/
1936 /* need to re-compute the ring size */
1937 unsigned frames_per_block
, block_size
;
1938 compute_ring_block(handle
->bufsize
, &block_size
, &frames_per_block
);
1940 /* do not perform sanity check here: we can't recover any error */
1941 munmap(handle
->bp
, block_size
* handle
->cc
/ frames_per_block
);
1945 /* if the header ring is allocated, clear it*/
1946 if (handle
->buffer
) {
1947 free(handle
->buffer
);
1953 pcap_close_linux_mmap( pcap_t
*handle
)
1955 destroy_ring(handle
);
1956 pcap_close_linux(handle
);
1961 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
1963 /* use negative value of timeout to indicate non blocking ops */
1964 return (p
->md
.timeout
<0);
1968 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
1970 /* map each value to the corresponding 2's complement, to
1971 * preserve the timeout value provided with pcap_set_timeout */
1973 if (p
->md
.timeout
> 0)
1974 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
1976 if (p
->md
.timeout
< 0)
1977 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
1982 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
1987 /* wait for frames availability.*/
1988 if ((handle
->md
.timeout
>= 0) && !(RING_GET_FRAME(handle
)->tp_status
)) {
1989 struct pollfd pollinfo
;
1992 pollinfo
.fd
= handle
->fd
;
1993 pollinfo
.events
= POLLIN
;
1996 /* poll() requires a negative timeout to wait forever */
1997 ret
= poll(&pollinfo
, 1, (handle
->md
.timeout
> 0)?
1998 handle
->md
.timeout
: -1);
1999 if ((ret
< 0) && (errno
!= EINTR
)) {
2000 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2001 "can't poll on packet socket fd %d: %d-%s",
2002 handle
->fd
, errno
, pcap_strerror(errno
));
2005 /* check for break loop condition on interrupted syscall*/
2006 if (handle
->break_loop
) {
2007 handle
->break_loop
= 0;
2013 /* non-positive values of max_packets are used to require all
2014 * packets currently available in the ring */
2015 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
2017 struct sockaddr_ll
*sll
;
2018 struct pcap_pkthdr pcaphdr
;
2020 struct tpacket_hdr
* thdr
= RING_GET_FRAME(handle
);
2021 if (thdr
->tp_status
== TP_STATUS_KERNEL
)
2024 /* perform sanity check on internal offset. */
2025 if (thdr
->tp_mac
+thdr
->tp_snaplen
> handle
->bufsize
) {
2026 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2027 "corrupted frame on kernel ring mac "
2028 "offset %d + caplen %d > frame len %d",
2029 thdr
->tp_mac
, thdr
->tp_snaplen
, handle
->bufsize
);
2033 /* run filter on received packet
2034 * If the kernel filtering is enabled we need to run the
2035 * filter until all the frames present into the ring
2036 * at filter creation time are processed.
2037 * In such case md.use_bpf is used as a counter for the
2038 * packet we need to filter.
2039 * Note: alternatively it could be possible to stop applying
2040 * the filter when the ring became empty, but it can possibly
2041 * happen a lot later... */
2042 bp
= (unsigned char*)thdr
+ thdr
->tp_mac
;
2043 run_bpf
= (!handle
->md
.use_bpf
) ||
2044 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
2045 if (run_bpf
&& handle
->fcode
.bf_insns
&&
2046 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
2047 thdr
->tp_len
, thdr
->tp_snaplen
) == 0))
2050 /* check direction and interface index */
2051 sll
= (void*)thdr
+ TPACKET_ALIGN(sizeof(*thdr
));
2052 if ((sll
->sll_ifindex
== handle
->md
.lo_ifindex
) &&
2053 (sll
->sll_pkttype
== PACKET_OUTGOING
))
2056 /* get required packet info from ring header */
2057 pcaphdr
.ts
.tv_sec
= thdr
->tp_sec
;
2058 pcaphdr
.ts
.tv_usec
= thdr
->tp_usec
;
2059 pcaphdr
.caplen
= thdr
->tp_snaplen
;
2060 pcaphdr
.len
= thdr
->tp_len
;
2062 /* if required build in place the sll header*/
2063 if (handle
->md
.cooked
) {
2064 struct sll_header
*hdrp
;
2067 * The kernel should have left us with enough
2068 * space for an sll header; back up the packet
2069 * data pointer into that space, as that'll be
2070 * the beginning of the packet we pass to the
2076 * Let's make sure that's past the end of
2077 * the tpacket header, i.e. >=
2078 * ((u_char *)thdr + TPACKET_HDRLEN), so we
2079 * don't step on the header when we construct
2082 if (bp
< (u_char
*)thdr
+ TPACKET_HDRLEN
) {
2083 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2084 "cooked-mode frame doesn't have room for sll header");
2089 * OK, that worked; construct the sll header.
2091 hdrp
= (struct sll_header
*)bp
;
2092 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
2094 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
2095 hdrp
->sll_halen
= htons(sll
->sll_halen
);
2096 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
2097 hdrp
->sll_protocol
= sll
->sll_protocol
;
2099 /* update packet len */
2100 pcaphdr
.caplen
+= SLL_HDR_LEN
;
2101 pcaphdr
.len
+= SLL_HDR_LEN
;
2104 /* pass the packet to the user */
2106 callback(user
, &pcaphdr
, bp
);
2107 handle
->md
.packets_read
++;
2111 thdr
->tp_status
= TP_STATUS_KERNEL
;
2112 if (++handle
->offset
>= handle
->cc
)
2115 /* check for break loop condition*/
2116 if (handle
->break_loop
) {
2117 handle
->break_loop
= 0;
2125 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
2128 int ret
= pcap_setfilter_linux(handle
, filter
);
2132 /* if the kernel filter is enabled, we need to apply the filter on
2133 * all packets present into the ring. Get an upper bound of their number
2135 if (!handle
->md
.use_bpf
)
2138 /* walk the ring backward and count the free slot */
2139 offset
= handle
->offset
;
2140 if (--handle
->offset
< 0)
2141 handle
->offset
= handle
->cc
- 1;
2142 for (n
=0; n
< handle
->cc
; ++n
) {
2143 if (--handle
->offset
< 0)
2144 handle
->offset
= handle
->cc
- 1;
2145 if (RING_GET_FRAME(handle
)->tp_status
!= TP_STATUS_KERNEL
)
2149 /* be careful to not change current ring position */
2150 handle
->offset
= offset
;
2152 /* store the number of packets currently present in the ring */
2153 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
2157 #endif /* HAVE_PACKET_RING */
2160 #ifdef HAVE_PF_PACKET_SOCKETS
2162 * Return the index of the given device name. Fill ebuf and return
2166 iface_get_id(int fd
, const char *device
, char *ebuf
)
2170 memset(&ifr
, 0, sizeof(ifr
));
2171 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2173 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
2174 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2175 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
2179 return ifr
.ifr_ifindex
;
2183 * Bind the socket associated with FD to the given device.
2186 iface_bind(int fd
, int ifindex
, char *ebuf
)
2188 struct sockaddr_ll sll
;
2190 socklen_t errlen
= sizeof(err
);
2192 memset(&sll
, 0, sizeof(sll
));
2193 sll
.sll_family
= AF_PACKET
;
2194 sll
.sll_ifindex
= ifindex
;
2195 sll
.sll_protocol
= htons(ETH_P_ALL
);
2197 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
2198 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2199 "bind: %s", pcap_strerror(errno
));
2203 /* Any pending errors, e.g., network is down? */
2205 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2206 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2207 "getsockopt: %s", pcap_strerror(errno
));
2212 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2213 "bind: %s", pcap_strerror(err
));
2221 * Check whether the device supports the Wireless Extensions.
2222 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
2223 * if the device doesn't even exist.
2226 has_wext(int sock_fd
, const char *device
)
2228 #ifdef IW_MODE_MONITOR
2231 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2232 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2233 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2234 if (ioctl(sock_fd
, SIOCGIWNAME
, &ireq
) >= 0)
2236 if (errno
== ENODEV
)
2237 return PCAP_ERROR_NO_SUCH_DEVICE
;
2243 * Per me si va ne la citta dolente,
2244 * Per me si va ne l'etterno dolore,
2246 * Lasciate ogne speranza, voi ch'intrate.
2261 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
2262 * on if it's not already on.
2264 * Returns 1 on success, 0 if we don't support the Wireless Extensions
2265 * on this device, or a PCAP_ERROR_ value if we do support them but
2266 * we weren't able to turn monitor mode on.
2269 enter_rfmon_mode_wext(pcap_t
*handle
, int sock_fd
, const char *device
)
2271 #ifdef IW_MODE_MONITOR
2273 * XXX - at least some adapters require non-Wireless Extensions
2274 * mechanisms to turn monitor mode on.
2276 * Atheros cards might require that a separate "monitor virtual access
2277 * point" be created, with later versions of the madwifi driver.
2279 * Some Intel Centrino adapters might require private ioctls to get
2280 * radio headers; the ipw2200 and ipw3945 drivers allow you to
2281 * configure a separate "rtapN" interface to capture in monitor
2282 * mode without preventing the adapter from operating normally.
2284 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
2285 * up, and if all drivers were converted to mac80211 drivers.
2289 struct iw_priv_args
*priv
;
2290 monitor_type montype
;
2297 * Does this device *support* the Wireless Extensions?
2299 err
= has_wext(sock_fd
, device
);
2301 return err
; /* either it doesn't or the device doesn't even exist */
2303 * Try to get all the Wireless Extensions private ioctls
2304 * supported by this device.
2306 * First, get the size of the buffer we need, by supplying no
2307 * buffer and a length of 0. If the device supports private
2308 * ioctls, it should return E2BIG, with ireq.u.data.length set
2309 * to the length we need. If it doesn't support them, it should
2310 * return EOPNOTSUPP.
2312 memset(&ireq
, 0, sizeof ireq
);
2313 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2314 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2315 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2316 ireq
.u
.data
.pointer
= args
;
2317 ireq
.u
.data
.length
= 0;
2318 ireq
.u
.data
.flags
= 0;
2319 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) != -1) {
2320 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2321 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
2325 if (errno
== EOPNOTSUPP
) {
2327 * No private ioctls, so we assume that there's only one
2328 * DLT_ for monitor mode.
2332 if (errno
!= E2BIG
) {
2336 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2337 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
2340 priv
= malloc(ireq
.u
.data
.length
* sizeof (struct iw_priv_args
));
2342 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2343 "malloc: %s", pcap_strerror(errno
));
2346 ireq
.u
.data
.pointer
= priv
;
2347 if (ioctl(sock_fd
, SIOCGIWPRIV
, &ireq
) == -1) {
2348 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2349 "%s: SIOCGIWPRIV: %s", device
, pcap_strerror(errno
));
2355 * Look for private ioctls to turn monitor mode on or, if
2356 * monitor mode is on, to set the header type.
2358 montype
= MONITOR_WEXT
;
2360 for (i
= 0; i
< ireq
.u
.data
.length
; i
++) {
2361 if (strcmp(priv
[i
].name
, "monitor_type") == 0) {
2363 * Hostap driver, use this one.
2364 * Set monitor mode first.
2365 * You can set it to 0 to get DLT_IEEE80211,
2366 * 1 to get DLT_PRISM, or 2 to get
2367 * DLT_IEEE80211_RADIO_AVS.
2369 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2371 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2373 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2375 montype
= MONITOR_HOSTAP
;
2379 if (strcmp(priv
[i
].name
, "set_prismhdr") == 0) {
2381 * Prism54 driver, use this one.
2382 * Set monitor mode first.
2383 * You can set it to 2 to get DLT_IEEE80211
2384 * or 3 or get DLT_PRISM.
2386 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2388 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2390 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2392 montype
= MONITOR_PRISM54
;
2396 if (strcmp(priv
[i
].name
, "forceprismheader") == 0) {
2398 * RT2570 driver, use this one.
2399 * Do this after turning monitor mode on.
2400 * You can set it to 1 to get DLT_PRISM or 2
2401 * to get DLT_IEEE80211.
2403 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2405 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2407 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2409 montype
= MONITOR_RT2570
;
2413 if (strcmp(priv
[i
].name
, "forceprism") == 0) {
2415 * RT73 driver, use this one.
2416 * Do this after turning monitor mode on.
2417 * Its argument is a *string*; you can
2418 * set it to "1" to get DLT_PRISM or "2"
2419 * to get DLT_IEEE80211.
2421 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_CHAR
)
2423 if (priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
)
2425 montype
= MONITOR_RT73
;
2429 if (strcmp(priv
[i
].name
, "prismhdr") == 0) {
2431 * One of the RTL8xxx drivers, use this one.
2432 * It can only be done after monitor mode
2433 * has been turned on. You can set it to 1
2434 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
2436 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2438 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2440 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 1)
2442 montype
= MONITOR_RTL8XXX
;
2446 if (strcmp(priv
[i
].name
, "rfmontx") == 0) {
2448 * RT2500 or RT61 driver, use this one.
2449 * It has one one-byte parameter; set
2450 * u.data.length to 1 and u.data.pointer to
2451 * point to the parameter.
2452 * It doesn't itself turn monitor mode on.
2453 * You can set it to 1 to allow transmitting
2454 * in monitor mode(?) and get DLT_IEEE80211,
2455 * or set it to 0 to disallow transmitting in
2456 * monitor mode(?) and get DLT_PRISM.
2458 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2460 if ((priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) != 2)
2462 montype
= MONITOR_RT2500
;
2466 if (strcmp(priv
[i
].name
, "monitor") == 0) {
2468 * Either ACX100 or hostap, use this one.
2469 * It turns monitor mode on.
2470 * If it takes two arguments, it's ACX100;
2471 * the first argument is 1 for DLT_PRISM
2472 * or 2 for DLT_IEEE80211, and the second
2473 * argument is the channel on which to
2474 * run. If it takes one argument, it's
2475 * HostAP, and the argument is 2 for
2476 * DLT_IEEE80211 and 3 for DLT_PRISM.
2478 * If we see this, we don't quit, as this
2479 * might be a version of the hostap driver
2480 * that also supports "monitor_type".
2482 if ((priv
[i
].set_args
& IW_PRIV_TYPE_MASK
) != IW_PRIV_TYPE_INT
)
2484 if (!(priv
[i
].set_args
& IW_PRIV_SIZE_FIXED
))
2486 switch (priv
[i
].set_args
& IW_PRIV_SIZE_MASK
) {
2489 montype
= MONITOR_PRISM
;
2494 montype
= MONITOR_ACX100
;
2506 * XXX - ipw3945? islism?
2512 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2513 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2514 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2515 if (ioctl(sock_fd
, SIOCGIWMODE
, &ireq
) == -1) {
2517 * We probably won't be able to set the mode, either.
2519 return PCAP_ERROR_RFMON_NOTSUP
;
2523 * Is it currently in monitor mode?
2525 if (ireq
.u
.mode
== IW_MODE_MONITOR
) {
2527 * Yes. Just leave things as they are.
2528 * We don't offer multiple link-layer types, as
2529 * changing the link-layer type out from under
2530 * somebody else capturing in monitor mode would
2531 * be considered rude.
2536 * No. We have to put the adapter into rfmon mode.
2540 * If we haven't already done so, arrange to have
2541 * "pcap_close_all()" called when we exit.
2543 if (!pcap_do_addexit(handle
)) {
2545 * "atexit()" failed; don't put the interface
2546 * in rfmon mode, just give up.
2548 return PCAP_ERROR_RFMON_NOTSUP
;
2552 * Save the old mode.
2554 handle
->md
.oldmode
= ireq
.u
.mode
;
2557 * Put the adapter in rfmon mode. How we do this depends
2558 * on whether we have a special private ioctl or not.
2560 if (montype
== MONITOR_PRISM
) {
2562 * We have the "monitor" private ioctl, but none of
2563 * the other private ioctls. Use this, and select
2566 * If it fails, just fall back on SIOCSIWMODE.
2568 memset(&ireq
, 0, sizeof ireq
);
2569 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2570 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2571 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2572 ireq
.u
.data
.length
= 1; /* 1 argument */
2573 args
[0] = 3; /* request Prism header */
2574 memcpy(ireq
.u
.name
, args
, IFNAMSIZ
);
2575 if (ioctl(sock_fd
, cmd
, &ireq
) != -1) {
2578 * Note that we have to put the old mode back
2579 * when we close the device.
2581 handle
->md
.must_clear
|= MUST_CLEAR_RFMON
;
2584 * Add this to the list of pcaps to close
2587 pcap_add_to_pcaps_to_close(handle
);
2593 * Failure. Fall back on SIOCSIWMODE.
2598 * First, turn monitor mode on.
2600 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2601 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2602 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2603 ireq
.u
.mode
= IW_MODE_MONITOR
;
2604 if (ioctl(sock_fd
, SIOCSIWMODE
, &ireq
) == -1) {
2606 * Scientist, you've failed.
2608 return PCAP_ERROR_RFMON_NOTSUP
;
2612 * Now select the appropriate radio header.
2618 * We don't have any private ioctl to set the header.
2622 case MONITOR_HOSTAP
:
2624 * Select the AVS header if we can, otherwise
2625 * select the Prism header.
2627 memset(&ireq
, 0, sizeof ireq
);
2628 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2629 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2630 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2631 args
[0] = 2; /* request AVS header */
2632 memcpy(ireq
.u
.name
, args
, sizeof (int));
2633 if (ioctl(sock_fd
, cmd
, &ireq
) == -1) {
2635 * Failure - try the Prism header.
2637 memset(&ireq
, 0, sizeof ireq
);
2638 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2639 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2640 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2641 args
[0] = 1; /* request Prism header */
2642 memcpy(ireq
.u
.name
, args
, sizeof (int));
2643 ioctl(sock_fd
, cmd
, &ireq
);
2649 * The private ioctl failed.
2653 case MONITOR_PRISM54
:
2655 * Select the Prism header.
2657 memset(&ireq
, 0, sizeof ireq
);
2658 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2659 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2660 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2661 args
[0] = 3; /* request Prism header */
2662 memcpy(ireq
.u
.name
, args
, sizeof (int));
2663 ioctl(sock_fd
, cmd
, &ireq
);
2666 case MONITOR_ACX100
:
2668 * Get the current channel.
2670 memset(&ireq
, 0, sizeof ireq
);
2671 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2672 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2673 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2674 if (ioctl(sock_fd
, SIOCGIWFREQ
, &ireq
) == -1) {
2675 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2676 "%s: SIOCGIWFREQ: %s", device
,
2677 pcap_strerror(errno
));
2680 channel
= ireq
.u
.freq
.m
;
2683 * Select the Prism header, and set the channel to the
2686 memset(&ireq
, 0, sizeof ireq
);
2687 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2688 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2689 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2690 args
[0] = 1; /* request Prism header */
2691 args
[1] = channel
; /* set channel */
2692 memcpy(ireq
.u
.name
, args
, 2*sizeof (int));
2693 ioctl(sock_fd
, cmd
, &ireq
);
2696 case MONITOR_RT2500
:
2698 * Disallow transmission - that turns on the
2701 memset(&ireq
, 0, sizeof ireq
);
2702 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2703 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2704 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2705 args
[0] = 0; /* disallow transmitting */
2706 memcpy(ireq
.u
.name
, args
, sizeof (int));
2707 ioctl(sock_fd
, cmd
, &ireq
);
2710 case MONITOR_RT2570
:
2712 * Force the Prism header.
2714 memset(&ireq
, 0, sizeof ireq
);
2715 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2716 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2717 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2718 args
[0] = 1; /* request Prism header */
2719 memcpy(ireq
.u
.name
, args
, sizeof (int));
2720 ioctl(sock_fd
, cmd
, &ireq
);
2725 * Force the Prism header.
2727 memset(&ireq
, 0, sizeof ireq
);
2728 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2729 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2730 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2731 ireq
.u
.data
.length
= 1; /* 1 argument */
2732 ireq
.u
.data
.pointer
= "1";
2733 ireq
.u
.data
.flags
= 0;
2734 ioctl(sock_fd
, cmd
, &ireq
);
2737 case MONITOR_RTL8XXX
:
2739 * Force the Prism header.
2741 memset(&ireq
, 0, sizeof ireq
);
2742 strncpy(ireq
.ifr_ifrn
.ifrn_name
, device
,
2743 sizeof ireq
.ifr_ifrn
.ifrn_name
);
2744 ireq
.ifr_ifrn
.ifrn_name
[sizeof ireq
.ifr_ifrn
.ifrn_name
- 1] = 0;
2745 args
[0] = 1; /* request Prism header */
2746 memcpy(ireq
.u
.name
, args
, sizeof (int));
2747 ioctl(sock_fd
, cmd
, &ireq
);
2752 * Note that we have to put the old mode back when we
2755 handle
->md
.must_clear
|= MUST_CLEAR_RFMON
;
2758 * Add this to the list of pcaps to close when we exit.
2760 pcap_add_to_pcaps_to_close(handle
);
2765 * We don't have the Wireless Extensions available, so we can't
2772 #endif /* HAVE_PF_PACKET_SOCKETS */
2774 /* ===== Functions to interface to the older kernels ================== */
2777 * Try to open a packet socket using the old kernel interface.
2778 * Returns 1 on success and a PCAP_ERROR_ value on an error.
2781 activate_old(pcap_t
*handle
)
2785 const char *device
= handle
->opt
.source
;
2786 struct utsname utsname
;
2789 /* Open the socket */
2791 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
2792 if (handle
->fd
== -1) {
2793 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2794 "socket: %s", pcap_strerror(errno
));
2798 /* It worked - we are using the old interface */
2799 handle
->md
.sock_packet
= 1;
2801 /* ...which means we get the link-layer header. */
2802 handle
->md
.cooked
= 0;
2804 /* Bind to the given device */
2807 strncpy(handle
->errbuf
, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
2811 if (iface_bind_old(handle
->fd
, device
, handle
->errbuf
) == -1)
2815 * Try to get the link-layer type.
2817 arptype
= iface_get_arptype(handle
->fd
, device
, handle
->errbuf
);
2822 * Try to find the DLT_ type corresponding to that
2825 map_arphrd_to_dlt(handle
, arptype
, 0);
2826 if (handle
->linktype
== -1) {
2827 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2828 "unknown arptype %d", arptype
);
2832 /* Go to promisc mode if requested */
2834 if (handle
->opt
.promisc
) {
2835 memset(&ifr
, 0, sizeof(ifr
));
2836 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2837 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2838 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2839 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
2842 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
2844 * Promiscuous mode isn't currently on,
2845 * so turn it on, and remember that
2846 * we should turn it off when the
2851 * If we haven't already done so, arrange
2852 * to have "pcap_close_all()" called when
2855 if (!pcap_do_addexit(handle
)) {
2857 * "atexit()" failed; don't put
2858 * the interface in promiscuous
2859 * mode, just give up.
2864 ifr
.ifr_flags
|= IFF_PROMISC
;
2865 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2866 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
2868 pcap_strerror(errno
));
2871 handle
->md
.must_clear
|= MUST_CLEAR_PROMISC
;
2874 * Add this to the list of pcaps
2875 * to close when we exit.
2877 pcap_add_to_pcaps_to_close(handle
);
2882 * Compute the buffer size.
2884 * We're using SOCK_PACKET, so this might be a 2.0[.x]
2885 * kernel, and might require special handling - check.
2887 if (uname(&utsname
) < 0 ||
2888 strncmp(utsname
.release
, "2.0", 3) == 0) {
2890 * Either we couldn't find out what kernel release
2891 * this is, or it's a 2.0[.x] kernel.
2893 * In the 2.0[.x] kernel, a "recvfrom()" on
2894 * a SOCK_PACKET socket, with MSG_TRUNC set, will
2895 * return the number of bytes read, so if we pass
2896 * a length based on the snapshot length, it'll
2897 * return the number of bytes from the packet
2898 * copied to userland, not the actual length
2901 * This means that, for example, the IP dissector
2902 * in tcpdump will get handed a packet length less
2903 * than the length in the IP header, and will
2904 * complain about "truncated-ip".
2906 * So we don't bother trying to copy from the
2907 * kernel only the bytes in which we're interested,
2908 * but instead copy them all, just as the older
2909 * versions of libpcap for Linux did.
2911 * The buffer therefore needs to be big enough to
2912 * hold the largest packet we can get from this
2913 * device. Unfortunately, we can't get the MRU
2914 * of the network; we can only get the MTU. The
2915 * MTU may be too small, in which case a packet larger
2916 * than the buffer size will be truncated *and* we
2917 * won't get the actual packet size.
2919 * However, if the snapshot length is larger than
2920 * the buffer size based on the MTU, we use the
2921 * snapshot length as the buffer size, instead;
2922 * this means that with a sufficiently large snapshot
2923 * length we won't artificially truncate packets
2924 * to the MTU-based size.
2926 * This mess just one of many problems with packet
2927 * capture on 2.0[.x] kernels; you really want a
2928 * 2.2[.x] or later kernel if you want packet capture
2931 mtu
= iface_get_mtu(handle
->fd
, device
, handle
->errbuf
);
2934 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
2935 if (handle
->bufsize
< handle
->snapshot
)
2936 handle
->bufsize
= handle
->snapshot
;
2939 * This is a 2.2[.x] or later kernel.
2941 * We can safely pass "recvfrom()" a byte count
2942 * based on the snapshot length.
2944 handle
->bufsize
= handle
->snapshot
;
2948 * Default value for offset to align link-layer payload
2949 * on a 4-byte boundary.
2957 * Bind the socket associated with FD to the given device using the
2958 * interface of the old kernels.
2961 iface_bind_old(int fd
, const char *device
, char *ebuf
)
2963 struct sockaddr saddr
;
2965 socklen_t errlen
= sizeof(err
);
2967 memset(&saddr
, 0, sizeof(saddr
));
2968 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
2969 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
2970 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2971 "bind: %s", pcap_strerror(errno
));
2975 /* Any pending errors, e.g., network is down? */
2977 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2978 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2979 "getsockopt: %s", pcap_strerror(errno
));
2984 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2985 "bind: %s", pcap_strerror(err
));
2993 /* ===== System calls available on all supported kernels ============== */
2996 * Query the kernel for the MTU of the given interface.
2999 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
3004 return BIGGER_THAN_ALL_MTUS
;
3006 memset(&ifr
, 0, sizeof(ifr
));
3007 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3009 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
3010 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3011 "SIOCGIFMTU: %s", pcap_strerror(errno
));
3019 * Get the hardware type of the given interface as ARPHRD_xxx constant.
3022 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
3026 memset(&ifr
, 0, sizeof(ifr
));
3027 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
3029 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
3030 if (errno
== ENODEV
) {
3034 return PCAP_ERROR_NO_SUCH_DEVICE
;
3036 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
3037 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
3041 return ifr
.ifr_hwaddr
.sa_family
;
3044 #ifdef SO_ATTACH_FILTER
3046 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
3050 register struct bpf_insn
*p
;
3055 * Make a copy of the filter, and modify that copy if
3058 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
3059 len
= handle
->fcode
.bf_len
;
3060 f
= (struct bpf_insn
*)malloc(prog_size
);
3062 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3063 "malloc: %s", pcap_strerror(errno
));
3066 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
3068 fcode
->filter
= (struct sock_filter
*) f
;
3070 for (i
= 0; i
< len
; ++i
) {
3073 * What type of instruction is this?
3075 switch (BPF_CLASS(p
->code
)) {
3079 * It's a return instruction; is the snapshot
3080 * length a constant, rather than the contents
3081 * of the accumulator?
3083 if (BPF_MODE(p
->code
) == BPF_K
) {
3085 * Yes - if the value to be returned,
3086 * i.e. the snapshot length, is anything
3087 * other than 0, make it 65535, so that
3088 * the packet is truncated by "recvfrom()",
3089 * not by the filter.
3091 * XXX - there's nothing we can easily do
3092 * if it's getting the value from the
3093 * accumulator; we'd have to insert
3094 * code to force non-zero values to be
3105 * It's a load instruction; is it loading
3108 switch (BPF_MODE(p
->code
)) {
3114 * Yes; are we in cooked mode?
3116 if (handle
->md
.cooked
) {
3118 * Yes, so we need to fix this
3121 if (fix_offset(p
) < 0) {
3123 * We failed to do so.
3124 * Return 0, so our caller
3125 * knows to punt to userland.
3135 return 1; /* we succeeded */
3139 fix_offset(struct bpf_insn
*p
)
3142 * What's the offset?
3144 if (p
->k
>= SLL_HDR_LEN
) {
3146 * It's within the link-layer payload; that starts at an
3147 * offset of 0, as far as the kernel packet filter is
3148 * concerned, so subtract the length of the link-layer
3151 p
->k
-= SLL_HDR_LEN
;
3152 } else if (p
->k
== 14) {
3154 * It's the protocol field; map it to the special magic
3155 * kernel offset for that field.
3157 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
3160 * It's within the header, but it's not one of those
3161 * fields; we can't do that in the kernel, so punt
3170 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
3172 int total_filter_on
= 0;
3178 * The socket filter code doesn't discard all packets queued
3179 * up on the socket when the filter is changed; this means
3180 * that packets that don't match the new filter may show up
3181 * after the new filter is put onto the socket, if those
3182 * packets haven't yet been read.
3184 * This means, for example, that if you do a tcpdump capture
3185 * with a filter, the first few packets in the capture might
3186 * be packets that wouldn't have passed the filter.
3188 * We therefore discard all packets queued up on the socket
3189 * when setting a kernel filter. (This isn't an issue for
3190 * userland filters, as the userland filtering is done after
3191 * packets are queued up.)
3193 * To flush those packets, we put the socket in read-only mode,
3194 * and read packets from the socket until there are no more to
3197 * In order to keep that from being an infinite loop - i.e.,
3198 * to keep more packets from arriving while we're draining
3199 * the queue - we put the "total filter", which is a filter
3200 * that rejects all packets, onto the socket before draining
3203 * This code deliberately ignores any errors, so that you may
3204 * get bogus packets if an error occurs, rather than having
3205 * the filtering done in userland even if it could have been
3206 * done in the kernel.
3208 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
3209 &total_fcode
, sizeof(total_fcode
)) == 0) {
3213 * Note that we've put the total filter onto the socket.
3215 total_filter_on
= 1;
3218 * Save the socket's current mode, and put it in
3219 * non-blocking mode; we drain it by reading packets
3220 * until we get an error (which is normally a
3221 * "nothing more to be read" error).
3223 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
3224 if (save_mode
!= -1 &&
3225 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
3226 while (recv(handle
->fd
, &drain
, sizeof drain
,
3230 fcntl(handle
->fd
, F_SETFL
, save_mode
);
3231 if (save_errno
!= EAGAIN
) {
3233 reset_kernel_filter(handle
);
3234 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
3235 "recv: %s", pcap_strerror(save_errno
));
3242 * Now attach the new filter.
3244 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
3245 fcode
, sizeof(*fcode
));
3246 if (ret
== -1 && total_filter_on
) {
3248 * Well, we couldn't set that filter on the socket,
3249 * but we could set the total filter on the socket.
3251 * This could, for example, mean that the filter was
3252 * too big to put into the kernel, so we'll have to
3253 * filter in userland; in any case, we'll be doing
3254 * filtering in userland, so we need to remove the
3255 * total filter so we see packets.
3260 * XXX - if this fails, we're really screwed;
3261 * we have the total filter on the socket,
3262 * and it won't come off. What do we do then?
3264 reset_kernel_filter(handle
);
3272 reset_kernel_filter(pcap_t
*handle
)
3275 * setsockopt() barfs unless it get a dummy parameter.
3276 * valgrind whines unless the value is initialized,
3277 * as it has no idea that setsockopt() ignores its
3282 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
3283 &dummy
, sizeof(dummy
));