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.132 2008-01-05 22:32:31 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 #endif /* HAVE_DAG_API */
94 #ifdef HAVE_SEPTEL_API
95 #include "pcap-septel.h"
96 #endif /* HAVE_SEPTEL_API */
98 #ifdef PCAP_SUPPORT_USB
99 #include "pcap-usb-linux.h"
102 #ifdef PCAP_SUPPORT_BT
103 #include "pcap-bt-linux.h"
107 #include "pcap-sita.h"
115 #include <sys/socket.h>
116 #include <sys/ioctl.h>
117 #include <sys/utsname.h>
118 #include <sys/mman.h>
120 #include <netinet/in.h>
121 #include <linux/if_ether.h>
122 #include <net/if_arp.h>
126 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
127 * sockets rather than SOCK_PACKET sockets.
129 * To use them, we include <linux/if_packet.h> rather than
130 * <netpacket/packet.h>; we do so because
132 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
133 * later kernels and libc5, and don't provide a <netpacket/packet.h>
136 * not all versions of glibc2 have a <netpacket/packet.h> file
137 * that defines stuff needed for some of the 2.4-or-later-kernel
138 * features, so if the system has a 2.4 or later kernel, we
139 * still can't use those features.
141 * We're already including a number of other <linux/XXX.h> headers, and
142 * this code is Linux-specific (no other OS has PF_PACKET sockets as
143 * a raw packet capture mechanism), so it's not as if you gain any
144 * useful portability by using <netpacket/packet.h>
146 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
147 * isn't defined? It only defines one data structure in 2.0.x, so
148 * it shouldn't cause any problems.
151 # include <linux/if_packet.h>
154 * On at least some Linux distributions (for example, Red Hat 5.2),
155 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
156 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
157 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
158 * the PACKET_xxx stuff.
160 * So we check whether PACKET_HOST is defined, and assume that we have
161 * PF_PACKET sockets only if it is defined.
164 # define HAVE_PF_PACKET_SOCKETS
165 # endif /* PACKET_HOST */
168 /* check for memory mapped access avaibility. We assume every needed
169 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
170 * uses many ring related structs and macros */
171 # ifdef TPACKET_HDRLEN
172 # define HAVE_PACKET_RING
173 # endif /* TPACKET_HDRLEN */
174 #endif /* PF_PACKET */
176 #ifdef SO_ATTACH_FILTER
177 #include <linux/types.h>
178 #include <linux/filter.h>
182 typedef int socklen_t
;
187 * This is being compiled on a system that lacks MSG_TRUNC; define it
188 * with the value it has in the 2.2 and later kernels, so that, on
189 * those kernels, when we pass it in the flags argument to "recvfrom()"
190 * we're passing the right value and thus get the MSG_TRUNC behavior
191 * we want. (We don't get that behavior on 2.0[.x] kernels, because
192 * they didn't support MSG_TRUNC.)
194 #define MSG_TRUNC 0x20
199 * This is being compiled on a system that lacks SOL_PACKET; define it
200 * with the value it has in the 2.2 and later kernels, so that we can
201 * set promiscuous mode in the good modern way rather than the old
202 * 2.0-kernel crappy way.
204 #define SOL_PACKET 263
207 #define MAX_LINKHEADER_SIZE 256
210 * When capturing on all interfaces we use this as the buffer size.
211 * Should be bigger then all MTUs that occur in real life.
212 * 64kB should be enough for now.
214 #define BIGGER_THAN_ALL_MTUS (64*1024)
217 * Prototypes for internal functions
219 static void map_arphrd_to_dlt(pcap_t
*, int, int);
220 static short int map_packet_type_to_sll_type(short int);
221 static int live_open_old(pcap_t
*, const char *, int, int, char *);
222 static int live_open_new(pcap_t
*, const char *, int, int, char *);
223 static int live_open_mmap(pcap_t
*, char *);
224 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
225 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
226 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
227 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
228 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
229 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
230 static void pcap_close_linux(pcap_t
*);
232 #ifdef HAVE_PACKET_RING
233 #define RING_GET_FRAME(h) (((struct tpacket_hdr**)h->buffer)[handle->offset])
235 static void destroy_ring(pcap_t
*handle
);
236 static int create_ring(pcap_t
* handle
, unsigned size
, char* errmsg
);
237 static void pcap_close_linux_mmap(pcap_t
*);
238 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
239 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
240 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
241 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
245 * Wrap some ioctl calls
247 #ifdef HAVE_PF_PACKET_SOCKETS
248 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
250 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
251 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
252 #ifdef HAVE_PF_PACKET_SOCKETS
253 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
255 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
257 #ifdef SO_ATTACH_FILTER
258 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
259 static int fix_offset(struct bpf_insn
*p
);
260 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
261 static int reset_kernel_filter(pcap_t
*handle
);
263 static struct sock_filter total_insn
264 = BPF_STMT(BPF_RET
| BPF_K
, 0);
265 static struct sock_fprog total_fcode
266 = { 1, &total_insn
};
270 * Get a handle for a live capture from the given device. You can
271 * pass NULL as device to get all packages (without link level
272 * information of course). If you pass 1 as promisc the interface
273 * will be set to promiscous mode (XXX: I think this usage should
274 * be deprecated and functions be added to select that later allow
275 * modification of that values -- Torsten).
280 pcap_open_live(const char *device
, int snaplen
, int promisc
, int to_ms
,
286 int live_open_ok
= 0;
287 struct utsname utsname
;
290 if (strstr(device
, "dag")) {
291 return dag_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
293 #endif /* HAVE_DAG_API */
295 #ifdef HAVE_SEPTEL_API
296 if (strstr(device
, "septel")) {
297 return septel_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
299 #endif /* HAVE_SEPTEL_API */
301 #ifdef PCAP_SUPPORT_BT
302 if (strstr(device
, "bluetooth")) {
303 return bt_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
307 #ifdef PCAP_SUPPORT_USB
308 if (strstr(device
, "usb")) {
309 return usb_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
313 /* Allocate a handle for this session. */
315 handle
= malloc(sizeof(*handle
));
316 if (handle
== NULL
) {
317 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
318 pcap_strerror(errno
));
322 /* Initialize some components of the pcap structure. */
324 memset(handle
, 0, sizeof(*handle
));
325 handle
->snapshot
= snaplen
;
326 handle
->md
.timeout
= to_ms
;
328 handle
->inject_op
= pcap_inject_linux
;
329 handle
->setfilter_op
= pcap_setfilter_linux
;
330 handle
->setdirection_op
= pcap_setdirection_linux
;
331 handle
->set_datalink_op
= NULL
; /* can't change data link type */
332 handle
->getnonblock_op
= pcap_getnonblock_fd
;
333 handle
->setnonblock_op
= pcap_setnonblock_fd
;
334 handle
->close_op
= pcap_close_linux
;
337 handle
->read_op
= pcap_read_acn
;
338 handle
->stats_op
= pcap_stats_acn
;
340 handle
->read_op
= pcap_read_linux
;
341 handle
->stats_op
= pcap_stats_linux
;
345 * NULL and "any" are special devices which give us the hint to
346 * monitor all devices.
348 if (!device
|| strcmp(device
, "any") == 0) {
350 handle
->md
.device
= strdup("any");
353 /* Just a warning. */
354 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
355 "Promiscuous mode not supported on the \"any\" device");
359 handle
->md
.device
= strdup(device
);
361 if (handle
->md
.device
== NULL
) {
362 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
363 pcap_strerror(errno
) );
369 * Current Linux kernels use the protocol family PF_PACKET to
370 * allow direct access to all packets on the network while
371 * older kernels had a special socket type SOCK_PACKET to
372 * implement this feature.
373 * While this old implementation is kind of obsolete we need
374 * to be compatible with older kernels for a while so we are
375 * trying both methods with the newer method preferred.
379 live_open_ok
= acn_open_live((unsigned char *)device
, ebuf
, &handle
->linktype
);
380 handle
->md
.clear_promisc
= promisc
;
381 handle
->fd
= live_open_ok
;
382 handle
->bufsize
= handle
->snapshot
;
384 if ((err
= live_open_new(handle
, device
, promisc
, to_ms
, ebuf
)) == 1) {
386 if (live_open_mmap(handle
, ebuf
) == 1)
390 /* Non-fatal error; try old way */
391 if (live_open_old(handle
, device
, promisc
, to_ms
, ebuf
))
397 * Both methods to open the packet socket failed. Tidy
398 * up and report our failure (ebuf is expected to be
399 * set by the functions above).
402 if (handle
->md
.device
!= NULL
)
403 free(handle
->md
.device
);
410 * Compute the buffer size.
412 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
413 * and might require special handling - check.
415 if (handle
->md
.sock_packet
&& (uname(&utsname
) < 0 ||
416 strncmp(utsname
.release
, "2.0", 3) == 0)) {
418 * We're using a SOCK_PACKET structure, and either
419 * we couldn't find out what kernel release this is,
420 * or it's a 2.0[.x] kernel.
422 * In the 2.0[.x] kernel, a "recvfrom()" on
423 * a SOCK_PACKET socket, with MSG_TRUNC set, will
424 * return the number of bytes read, so if we pass
425 * a length based on the snapshot length, it'll
426 * return the number of bytes from the packet
427 * copied to userland, not the actual length
430 * This means that, for example, the IP dissector
431 * in tcpdump will get handed a packet length less
432 * than the length in the IP header, and will
433 * complain about "truncated-ip".
435 * So we don't bother trying to copy from the
436 * kernel only the bytes in which we're interested,
437 * but instead copy them all, just as the older
438 * versions of libpcap for Linux did.
440 * The buffer therefore needs to be big enough to
441 * hold the largest packet we can get from this
442 * device. Unfortunately, we can't get the MRU
443 * of the network; we can only get the MTU. The
444 * MTU may be too small, in which case a packet larger
445 * than the buffer size will be truncated *and* we
446 * won't get the actual packet size.
448 * However, if the snapshot length is larger than
449 * the buffer size based on the MTU, we use the
450 * snapshot length as the buffer size, instead;
451 * this means that with a sufficiently large snapshot
452 * length we won't artificially truncate packets
453 * to the MTU-based size.
455 * This mess just one of many problems with packet
456 * capture on 2.0[.x] kernels; you really want a
457 * 2.2[.x] or later kernel if you want packet capture
460 mtu
= iface_get_mtu(handle
->fd
, device
, ebuf
);
462 pcap_close_linux(handle
);
466 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
467 if (handle
->bufsize
< handle
->snapshot
)
468 handle
->bufsize
= handle
->snapshot
;
471 * This is a 2.2[.x] or later kernel (we know that
472 * either because we're not using a SOCK_PACKET
473 * socket - PF_PACKET is supported only in 2.2
474 * and later kernels - or because we checked the
477 * We can safely pass "recvfrom()" a byte count
478 * based on the snapshot length.
480 * If we're in cooked mode, make the snapshot length
481 * large enough to hold a "cooked mode" header plus
482 * 1 byte of packet data (so we don't pass a byte
483 * count of 0 to "recvfrom()").
485 if (handle
->md
.cooked
) {
486 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
487 handle
->snapshot
= SLL_HDR_LEN
+ 1;
489 handle
->bufsize
= handle
->snapshot
;
493 /* Allocate the buffer */
495 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
496 if (!handle
->buffer
) {
497 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
498 "malloc: %s", pcap_strerror(errno
));
499 pcap_close_linux(handle
);
505 * "handle->fd" is a socket, so "select()" and "poll()"
508 handle
->selectable_fd
= handle
->fd
;
514 * Read at most max_packets from the capture stream and call the callback
515 * for each of them. Returns the number of packets handled or -1 if an
519 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
522 * Currently, on Linux only one packet is delivered per read,
525 return pcap_read_packet(handle
, callback
, user
);
529 * Read a packet from the socket calling the handler provided by
530 * the user. Returns the number of packets received or -1 if an
534 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
538 #ifdef HAVE_PF_PACKET_SOCKETS
539 struct sockaddr_ll from
;
540 struct sll_header
*hdrp
;
542 struct sockaddr from
;
545 int packet_len
, caplen
;
546 struct pcap_pkthdr pcap_header
;
548 #ifdef HAVE_PF_PACKET_SOCKETS
550 * If this is a cooked device, leave extra room for a
551 * fake packet header.
553 if (handle
->md
.cooked
)
554 offset
= SLL_HDR_LEN
;
559 * This system doesn't have PF_PACKET sockets, so it doesn't
560 * support cooked devices.
565 /* Receive a single packet from the kernel */
567 bp
= handle
->buffer
+ handle
->offset
;
570 * Has "pcap_breakloop()" been called?
572 if (handle
->break_loop
) {
574 * Yes - clear the flag that indicates that it
575 * has, and return -2 as an indication that we
576 * were told to break out of the loop.
578 handle
->break_loop
= 0;
581 fromlen
= sizeof(from
);
582 packet_len
= recvfrom(
583 handle
->fd
, bp
+ offset
,
584 handle
->bufsize
- offset
, MSG_TRUNC
,
585 (struct sockaddr
*) &from
, &fromlen
);
586 } while (packet_len
== -1 && errno
== EINTR
);
588 /* Check if an error occured */
590 if (packet_len
== -1) {
592 return 0; /* no packet there */
594 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
595 "recvfrom: %s", pcap_strerror(errno
));
600 #ifdef HAVE_PF_PACKET_SOCKETS
601 if (!handle
->md
.sock_packet
) {
603 * Unfortunately, there is a window between socket() and
604 * bind() where the kernel may queue packets from any
605 * interface. If we're bound to a particular interface,
606 * discard packets not from that interface.
608 * (If socket filters are supported, we could do the
609 * same thing we do when changing the filter; however,
610 * that won't handle packet sockets without socket
611 * filter support, and it's a bit more complicated.
612 * It would save some instructions per packet, however.)
614 if (handle
->md
.ifindex
!= -1 &&
615 from
.sll_ifindex
!= handle
->md
.ifindex
)
619 * Do checks based on packet direction.
620 * We can only do this if we're using PF_PACKET; the
621 * address returned for SOCK_PACKET is a "sockaddr_pkt"
622 * which lacks the relevant packet type information.
624 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
627 * If this is from the loopback device, reject it;
628 * we'll see the packet as an incoming packet as well,
629 * and we don't want to see it twice.
631 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
635 * If the user only wants incoming packets, reject it.
637 if (handle
->direction
== PCAP_D_IN
)
642 * If the user only wants outgoing packets, reject it.
644 if (handle
->direction
== PCAP_D_OUT
)
650 #ifdef HAVE_PF_PACKET_SOCKETS
652 * If this is a cooked device, fill in the fake packet header.
654 if (handle
->md
.cooked
) {
656 * Add the length of the fake header to the length
657 * of packet data we read.
659 packet_len
+= SLL_HDR_LEN
;
661 hdrp
= (struct sll_header
*)bp
;
662 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
663 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
664 hdrp
->sll_halen
= htons(from
.sll_halen
);
665 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
666 (from
.sll_halen
> SLL_ADDRLEN
) ?
669 hdrp
->sll_protocol
= from
.sll_protocol
;
674 * XXX: According to the kernel source we should get the real
675 * packet len if calling recvfrom with MSG_TRUNC set. It does
676 * not seem to work here :(, but it is supported by this code
678 * To be honest the code RELIES on that feature so this is really
679 * broken with 2.2.x kernels.
680 * I spend a day to figure out what's going on and I found out
681 * that the following is happening:
683 * The packet comes from a random interface and the packet_rcv
684 * hook is called with a clone of the packet. That code inserts
685 * the packet into the receive queue of the packet socket.
686 * If a filter is attached to that socket that filter is run
687 * first - and there lies the problem. The default filter always
688 * cuts the packet at the snaplen:
693 * So the packet filter cuts down the packet. The recvfrom call
694 * says "hey, it's only 68 bytes, it fits into the buffer" with
695 * the result that we don't get the real packet length. This
696 * is valid at least until kernel 2.2.17pre6.
698 * We currently handle this by making a copy of the filter
699 * program, fixing all "ret" instructions with non-zero
700 * operands to have an operand of 65535 so that the filter
701 * doesn't truncate the packet, and supplying that modified
702 * filter to the kernel.
706 if (caplen
> handle
->snapshot
)
707 caplen
= handle
->snapshot
;
709 /* Run the packet filter if not using kernel filter */
710 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
711 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
712 packet_len
, caplen
) == 0)
714 /* rejected by filter */
719 /* Fill in our own header data */
721 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
722 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
723 "SIOCGSTAMP: %s", pcap_strerror(errno
));
726 pcap_header
.caplen
= caplen
;
727 pcap_header
.len
= packet_len
;
732 * Arguably, we should count them before we check the filter,
733 * as on many other platforms "ps_recv" counts packets
734 * handed to the filter rather than packets that passed
735 * the filter, but if filtering is done in the kernel, we
736 * can't get a count of packets that passed the filter,
737 * and that would mean the meaning of "ps_recv" wouldn't
738 * be the same on all Linux systems.
740 * XXX - it's not the same on all systems in any case;
741 * ideally, we should have a "get the statistics" call
742 * that supplies more counts and indicates which of them
743 * it supplies, so that we supply a count of packets
744 * handed to the filter only on platforms where that
745 * information is available.
747 * We count them here even if we can get the packet count
748 * from the kernel, as we can only determine at run time
749 * whether we'll be able to get it from the kernel (if
750 * HAVE_TPACKET_STATS isn't defined, we can't get it from
751 * the kernel, but if it is defined, the library might
752 * have been built with a 2.4 or later kernel, but we
753 * might be running on a 2.2[.x] kernel without Alexey
754 * Kuznetzov's turbopacket patches, and thus the kernel
755 * might not be able to supply those statistics). We
756 * could, I guess, try, when opening the socket, to get
757 * the statistics, and if we can not increment the count
758 * here, but it's not clear that always incrementing
759 * the count is more expensive than always testing a flag
762 * We keep the count in "md.packets_read", and use that for
763 * "ps_recv" if we can't get the statistics from the kernel.
764 * We do that because, if we *can* get the statistics from
765 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
766 * as running counts, as reading the statistics from the
767 * kernel resets the kernel statistics, and if we directly
768 * increment "md.stat.ps_recv" here, that means it will
769 * count packets *twice* on systems where we can get kernel
770 * statistics - once here, and once in pcap_stats_linux().
772 handle
->md
.packets_read
++;
774 /* Call the user supplied callback function */
775 callback(userdata
, &pcap_header
, bp
);
781 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
785 #ifdef HAVE_PF_PACKET_SOCKETS
786 if (!handle
->md
.sock_packet
) {
787 /* PF_PACKET socket */
788 if (handle
->md
.ifindex
== -1) {
790 * We don't support sending on the "any" device.
792 strlcpy(handle
->errbuf
,
793 "Sending packets isn't supported on the \"any\" device",
798 if (handle
->md
.cooked
) {
800 * We don't support sending on the "any" device.
802 * XXX - how do you send on a bound cooked-mode
804 * Is a "sendto()" required there?
806 strlcpy(handle
->errbuf
,
807 "Sending packets isn't supported in cooked mode",
814 ret
= send(handle
->fd
, buf
, size
, 0);
816 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
817 pcap_strerror(errno
));
824 * Get the statistics for the given packet capture handle.
825 * Reports the number of dropped packets iff the kernel supports
826 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
827 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
828 * patches); otherwise, that information isn't available, and we lie
829 * and report 0 as the count of dropped packets.
832 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
834 #ifdef HAVE_TPACKET_STATS
835 struct tpacket_stats kstats
;
836 socklen_t len
= sizeof (struct tpacket_stats
);
839 #ifdef HAVE_TPACKET_STATS
841 * Try to get the packet counts from the kernel.
843 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
844 &kstats
, &len
) > -1) {
846 * On systems where the PACKET_STATISTICS "getsockopt()"
847 * argument is supported on PF_PACKET sockets:
849 * "ps_recv" counts only packets that *passed* the
850 * filter, not packets that didn't pass the filter.
851 * This includes packets later dropped because we
852 * ran out of buffer space.
854 * "ps_drop" counts packets dropped because we ran
855 * out of buffer space. It doesn't count packets
856 * dropped by the interface driver. It counts only
857 * packets that passed the filter.
859 * Both statistics include packets not yet read from
860 * the kernel by libpcap, and thus not yet seen by
863 * In "linux/net/packet/af_packet.c", at least in the
864 * 2.4.9 kernel, "tp_packets" is incremented for every
865 * packet that passes the packet filter *and* is
866 * successfully queued on the socket; "tp_drops" is
867 * incremented for every packet dropped because there's
868 * not enough free space in the socket buffer.
870 * When the statistics are returned for a PACKET_STATISTICS
871 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
872 * so that "tp_packets" counts all packets handed to
873 * the PF_PACKET socket, including packets dropped because
874 * there wasn't room on the socket buffer - but not
875 * including packets that didn't pass the filter.
877 * In the BSD BPF, the count of received packets is
878 * incremented for every packet handed to BPF, regardless
879 * of whether it passed the filter.
881 * We can't make "pcap_stats()" work the same on both
882 * platforms, but the best approximation is to return
883 * "tp_packets" as the count of packets and "tp_drops"
884 * as the count of drops.
886 * Keep a running total because each call to
887 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
888 * resets the counters to zero.
890 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
891 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
892 *stats
= handle
->md
.stat
;
898 * If the error was EOPNOTSUPP, fall through, so that
899 * if you build the library on a system with
900 * "struct tpacket_stats" and run it on a system
901 * that doesn't, it works as it does if the library
902 * is built on a system without "struct tpacket_stats".
904 if (errno
!= EOPNOTSUPP
) {
905 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
906 "pcap_stats: %s", pcap_strerror(errno
));
912 * On systems where the PACKET_STATISTICS "getsockopt()" argument
913 * is not supported on PF_PACKET sockets:
915 * "ps_recv" counts only packets that *passed* the filter,
916 * not packets that didn't pass the filter. It does not
917 * count packets dropped because we ran out of buffer
920 * "ps_drop" is not supported.
922 * "ps_recv" doesn't include packets not yet read from
923 * the kernel by libpcap.
925 * We maintain the count of packets processed by libpcap in
926 * "md.packets_read", for reasons described in the comment
927 * at the end of pcap_read_packet(). We have no idea how many
928 * packets were dropped.
930 stats
->ps_recv
= handle
->md
.packets_read
;
936 * Description string for the "any" device.
938 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
941 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
943 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
947 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
949 #endif /* HAVE_DAG_API */
951 #ifdef HAVE_SEPTEL_API
952 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
954 #endif /* HAVE_SEPTEL_API */
956 #ifdef PCAP_SUPPORT_BT
957 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
961 #ifdef PCAP_SUPPORT_USB
962 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
970 * Attach the given BPF code to the packet capture device.
973 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
975 #ifdef SO_ATTACH_FILTER
976 struct sock_fprog fcode
;
977 int can_filter_in_kernel
;
984 strncpy(handle
->errbuf
, "setfilter: No filter specified",
985 sizeof(handle
->errbuf
));
990 return acn_setfilter(handle
->fd
, filter
);
992 /* Make our private copy of the filter */
994 if (install_bpf_program(handle
, filter
) < 0)
995 /* install_bpf_program() filled in errbuf */
999 * Run user level packet filter by default. Will be overriden if
1000 * installing a kernel filter succeeds.
1002 handle
->md
.use_bpf
= 0;
1004 /* Install kernel level filter if possible */
1006 #ifdef SO_ATTACH_FILTER
1008 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
1010 * fcode.len is an unsigned short for current kernel.
1011 * I have yet to see BPF-Code with that much
1012 * instructions but still it is possible. So for the
1013 * sake of correctness I added this check.
1015 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
1017 fcode
.filter
= NULL
;
1018 can_filter_in_kernel
= 0;
1020 #endif /* USHRT_MAX */
1023 * Oh joy, the Linux kernel uses struct sock_fprog instead
1024 * of struct bpf_program and of course the length field is
1025 * of different size. Pointed out by Sebastian
1027 * Oh, and we also need to fix it up so that all "ret"
1028 * instructions with non-zero operands have 65535 as the
1029 * operand, and so that, if we're in cooked mode, all
1030 * memory-reference instructions use special magic offsets
1031 * in references to the link-layer header and assume that
1032 * the link-layer payload begins at 0; "fix_program()"
1035 switch (fix_program(handle
, &fcode
)) {
1040 * Fatal error; just quit.
1041 * (The "default" case shouldn't happen; we
1042 * return -1 for that reason.)
1048 * The program performed checks that we can't make
1049 * work in the kernel.
1051 can_filter_in_kernel
= 0;
1056 * We have a filter that'll work in the kernel.
1058 can_filter_in_kernel
= 1;
1063 if (can_filter_in_kernel
) {
1064 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
1066 /* Installation succeded - using kernel filter. */
1067 handle
->md
.use_bpf
= 1;
1069 else if (err
== -1) /* Non-fatal error */
1072 * Print a warning if we weren't able to install
1073 * the filter for a reason other than "this kernel
1074 * isn't configured to support socket filters.
1076 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
1078 "Warning: Kernel filter failed: %s\n",
1079 pcap_strerror(errno
));
1085 * If we're not using the kernel filter, get rid of any kernel
1086 * filter that might've been there before, e.g. because the
1087 * previous filter could work in the kernel, or because some other
1088 * code attached a filter to the socket by some means other than
1089 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1090 * filter out packets that would pass the new userland filter.
1092 if (!handle
->md
.use_bpf
)
1093 reset_kernel_filter(handle
);
1096 * Free up the copy of the filter that was made by "fix_program()".
1098 if (fcode
.filter
!= NULL
)
1104 #endif /* SO_ATTACH_FILTER */
1111 * Set direction flag: Which packets do we accept on a forwarding
1112 * single device? IN, OUT or both?
1115 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1117 #ifdef HAVE_PF_PACKET_SOCKETS
1118 if (!handle
->md
.sock_packet
) {
1119 handle
->direction
= d
;
1124 * We're not using PF_PACKET sockets, so we can't determine
1125 * the direction of the packet.
1127 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1128 "Setting direction is not supported on SOCK_PACKET sockets");
1134 * Map the PACKET_ value to a LINUX_SLL_ value; we
1135 * want the same numerical value to be used in
1136 * the link-layer header even if the numerical values
1137 * for the PACKET_ #defines change, so that programs
1138 * that look at the packet type field will always be
1139 * able to handle DLT_LINUX_SLL captures.
1142 map_packet_type_to_sll_type(short int sll_pkttype
)
1144 switch (sll_pkttype
) {
1147 return htons(LINUX_SLL_HOST
);
1149 case PACKET_BROADCAST
:
1150 return htons(LINUX_SLL_BROADCAST
);
1152 case PACKET_MULTICAST
:
1153 return htons(LINUX_SLL_MULTICAST
);
1155 case PACKET_OTHERHOST
:
1156 return htons(LINUX_SLL_OTHERHOST
);
1158 case PACKET_OUTGOING
:
1159 return htons(LINUX_SLL_OUTGOING
);
1167 * Linux uses the ARP hardware type to identify the type of an
1168 * interface. pcap uses the DLT_xxx constants for this. This
1169 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1170 * constant, as arguments, and sets "handle->linktype" to the
1171 * appropriate DLT_XXX constant and sets "handle->offset" to
1172 * the appropriate value (to make "handle->offset" plus link-layer
1173 * header length be a multiple of 4, so that the link-layer payload
1174 * will be aligned on a 4-byte boundary when capturing packets).
1175 * (If the offset isn't set here, it'll be 0; add code as appropriate
1176 * for cases where it shouldn't be 0.)
1178 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1179 * in cooked mode; otherwise, we can't use cooked mode, so we have
1180 * to pick some type that works in raw mode, or fail.
1182 * Sets the link type to -1 if unable to map the type.
1184 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1190 * This is (presumably) a real Ethernet capture; give it a
1191 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1192 * that an application can let you choose it, in case you're
1193 * capturing DOCSIS traffic that a Cisco Cable Modem
1194 * Termination System is putting out onto an Ethernet (it
1195 * doesn't put an Ethernet header onto the wire, it puts raw
1196 * DOCSIS frames out on the wire inside the low-level
1197 * Ethernet framing).
1199 * XXX - are there any sorts of "fake Ethernet" that have
1200 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1201 * a Cisco CMTS won't put traffic onto it or get traffic
1202 * bridged onto it? ISDN is handled in "live_open_new()",
1203 * as we fall back on cooked mode there; are there any
1206 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1208 * If that fails, just leave the list empty.
1210 if (handle
->dlt_list
!= NULL
) {
1211 handle
->dlt_list
[0] = DLT_EN10MB
;
1212 handle
->dlt_list
[1] = DLT_DOCSIS
;
1213 handle
->dlt_count
= 2;
1217 case ARPHRD_METRICOM
:
1218 case ARPHRD_LOOPBACK
:
1219 handle
->linktype
= DLT_EN10MB
;
1224 handle
->linktype
= DLT_EN3MB
;
1228 handle
->linktype
= DLT_AX25_KISS
;
1232 handle
->linktype
= DLT_PRONET
;
1236 handle
->linktype
= DLT_CHAOS
;
1239 #ifndef ARPHRD_IEEE802_TR
1240 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1242 case ARPHRD_IEEE802_TR
:
1243 case ARPHRD_IEEE802
:
1244 handle
->linktype
= DLT_IEEE802
;
1249 handle
->linktype
= DLT_ARCNET_LINUX
;
1252 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1253 #define ARPHRD_FDDI 774
1256 handle
->linktype
= DLT_FDDI
;
1260 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1261 #define ARPHRD_ATM 19
1265 * The Classical IP implementation in ATM for Linux
1266 * supports both what RFC 1483 calls "LLC Encapsulation",
1267 * in which each packet has an LLC header, possibly
1268 * with a SNAP header as well, prepended to it, and
1269 * what RFC 1483 calls "VC Based Multiplexing", in which
1270 * different virtual circuits carry different network
1271 * layer protocols, and no header is prepended to packets.
1273 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1274 * you can't use the ARPHRD_ type to find out whether
1275 * captured packets will have an LLC header, and,
1276 * while there's a socket ioctl to *set* the encapsulation
1277 * type, there's no ioctl to *get* the encapsulation type.
1281 * programs that dissect Linux Classical IP frames
1282 * would have to check for an LLC header and,
1283 * depending on whether they see one or not, dissect
1284 * the frame as LLC-encapsulated or as raw IP (I
1285 * don't know whether there's any traffic other than
1286 * IP that would show up on the socket, or whether
1287 * there's any support for IPv6 in the Linux
1288 * Classical IP code);
1290 * filter expressions would have to compile into
1291 * code that checks for an LLC header and does
1294 * Both of those are a nuisance - and, at least on systems
1295 * that support PF_PACKET sockets, we don't have to put
1296 * up with those nuisances; instead, we can just capture
1297 * in cooked mode. That's what we'll do, if we can.
1298 * Otherwise, we'll just fail.
1301 handle
->linktype
= DLT_LINUX_SLL
;
1303 handle
->linktype
= -1;
1306 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1307 #define ARPHRD_IEEE80211 801
1309 case ARPHRD_IEEE80211
:
1310 handle
->linktype
= DLT_IEEE802_11
;
1313 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1314 #define ARPHRD_IEEE80211_PRISM 802
1316 case ARPHRD_IEEE80211_PRISM
:
1317 handle
->linktype
= DLT_PRISM_HEADER
;
1320 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1321 #define ARPHRD_IEEE80211_RADIOTAP 803
1323 case ARPHRD_IEEE80211_RADIOTAP
:
1324 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1329 * Some PPP code in the kernel supplies no link-layer
1330 * header whatsoever to PF_PACKET sockets; other PPP
1331 * code supplies PPP link-layer headers ("syncppp.c");
1332 * some PPP code might supply random link-layer
1333 * headers (PPP over ISDN - there's code in Ethereal,
1334 * for example, to cope with PPP-over-ISDN captures
1335 * with which the Ethereal developers have had to cope,
1336 * heuristically trying to determine which of the
1337 * oddball link-layer headers particular packets have).
1339 * As such, we just punt, and run all PPP interfaces
1340 * in cooked mode, if we can; otherwise, we just treat
1341 * it as DLT_RAW, for now - if somebody needs to capture,
1342 * on a 2.0[.x] kernel, on PPP devices that supply a
1343 * link-layer header, they'll have to add code here to
1344 * map to the appropriate DLT_ type (possibly adding a
1345 * new DLT_ type, if necessary).
1348 handle
->linktype
= DLT_LINUX_SLL
;
1351 * XXX - handle ISDN types here? We can't fall
1352 * back on cooked sockets, so we'd have to
1353 * figure out from the device name what type of
1354 * link-layer encapsulation it's using, and map
1355 * that to an appropriate DLT_ value, meaning
1356 * we'd map "isdnN" devices to DLT_RAW (they
1357 * supply raw IP packets with no link-layer
1358 * header) and "isdY" devices to a new DLT_I4L_IP
1359 * type that has only an Ethernet packet type as
1360 * a link-layer header.
1362 * But sometimes we seem to get random crap
1363 * in the link-layer header when capturing on
1366 handle
->linktype
= DLT_RAW
;
1370 #ifndef ARPHRD_CISCO
1371 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1374 handle
->linktype
= DLT_C_HDLC
;
1377 /* Not sure if this is correct for all tunnels, but it
1381 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1389 #ifndef ARPHRD_RAWHDLC
1390 #define ARPHRD_RAWHDLC 518
1392 case ARPHRD_RAWHDLC
:
1394 #define ARPHRD_DLCI 15
1398 * XXX - should some of those be mapped to DLT_LINUX_SLL
1399 * instead? Should we just map all of them to DLT_LINUX_SLL?
1401 handle
->linktype
= DLT_RAW
;
1405 #define ARPHRD_FRAD 770
1408 handle
->linktype
= DLT_FRELAY
;
1411 case ARPHRD_LOCALTLK
:
1412 handle
->linktype
= DLT_LTALK
;
1416 #define ARPHRD_FCPP 784
1420 #define ARPHRD_FCAL 785
1424 #define ARPHRD_FCPL 786
1427 #ifndef ARPHRD_FCFABRIC
1428 #define ARPHRD_FCFABRIC 787
1430 case ARPHRD_FCFABRIC
:
1432 * We assume that those all mean RFC 2625 IP-over-
1433 * Fibre Channel, with the RFC 2625 header at
1434 * the beginning of the packet.
1436 handle
->linktype
= DLT_IP_OVER_FC
;
1440 #define ARPHRD_IRDA 783
1443 /* Don't expect IP packet out of this interfaces... */
1444 handle
->linktype
= DLT_LINUX_IRDA
;
1445 /* We need to save packet direction for IrDA decoding,
1446 * so let's use "Linux-cooked" mode. Jean II */
1447 //handle->md.cooked = 1;
1450 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1451 * is needed, please report it to <daniele@orlandi.com> */
1453 #define ARPHRD_LAPD 8445
1456 /* Don't expect IP packet out of this interfaces... */
1457 handle
->linktype
= DLT_LINUX_LAPD
;
1461 handle
->linktype
= -1;
1466 /* ===== Functions to interface to the newer kernels ================== */
1469 * Try to open a packet socket using the new kernel interface.
1470 * Returns 0 on failure.
1471 * FIXME: 0 uses to mean success (Sebastian)
1474 live_open_new(pcap_t
*handle
, const char *device
, int promisc
,
1475 int to_ms
, char *ebuf
)
1477 #ifdef HAVE_PF_PACKET_SOCKETS
1478 int sock_fd
= -1, arptype
;
1481 struct packet_mreq mr
;
1483 /* One shot loop used for error handling - bail out with break */
1487 * Open a socket with protocol family packet. If a device is
1488 * given we try to open it in raw mode otherwise we use
1489 * the cooked interface.
1492 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
1493 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
1495 if (sock_fd
== -1) {
1496 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
1497 pcap_strerror(errno
) );
1501 /* It seems the kernel supports the new interface. */
1502 handle
->md
.sock_packet
= 0;
1505 * Get the interface index of the loopback device.
1506 * If the attempt fails, don't fail, just set the
1507 * "md.lo_ifindex" to -1.
1509 * XXX - can there be more than one device that loops
1510 * packets back, i.e. devices other than "lo"? If so,
1511 * we'd need to find them all, and have an array of
1512 * indices for them, and check all of them in
1513 * "pcap_read_packet()".
1515 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", ebuf
);
1518 * Default value for offset to align link-layer payload
1519 * on a 4-byte boundary.
1524 * What kind of frames do we have to deal with? Fall back
1525 * to cooked mode if we have an unknown interface type.
1529 /* Assume for now we don't need cooked mode. */
1530 handle
->md
.cooked
= 0;
1532 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1533 if (arptype
== -1) {
1537 map_arphrd_to_dlt(handle
, arptype
, 1);
1538 if (handle
->linktype
== -1 ||
1539 handle
->linktype
== DLT_LINUX_SLL
||
1540 handle
->linktype
== DLT_LINUX_IRDA
||
1541 handle
->linktype
== DLT_LINUX_LAPD
||
1542 (handle
->linktype
== DLT_EN10MB
&&
1543 (strncmp("isdn", device
, 4) == 0 ||
1544 strncmp("isdY", device
, 4) == 0))) {
1546 * Unknown interface type (-1), or a
1547 * device we explicitly chose to run
1548 * in cooked mode (e.g., PPP devices),
1549 * or an ISDN device (whose link-layer
1550 * type we can only determine by using
1551 * APIs that may be different on different
1552 * kernels) - reopen in cooked mode.
1554 if (close(sock_fd
) == -1) {
1555 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1556 "close: %s", pcap_strerror(errno
));
1559 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1561 if (sock_fd
== -1) {
1562 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1563 "socket: %s", pcap_strerror(errno
));
1566 handle
->md
.cooked
= 1;
1569 * Get rid of any link-layer type list
1570 * we allocated - this only supports cooked
1573 if (handle
->dlt_list
!= NULL
) {
1574 free(handle
->dlt_list
);
1575 handle
->dlt_list
= NULL
;
1576 handle
->dlt_count
= 0;
1579 if (handle
->linktype
== -1) {
1581 * Warn that we're falling back on
1582 * cooked mode; we may want to
1583 * update "map_arphrd_to_dlt()"
1584 * to handle the new type.
1586 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1588 "supported by libpcap - "
1589 "falling back to cooked "
1593 /* IrDA capture is not a real "cooked" capture,
1594 * it's IrLAP frames, not IP packets. */
1595 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
1596 handle
->linktype
!= DLT_LINUX_LAPD
)
1597 handle
->linktype
= DLT_LINUX_SLL
;
1600 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
, ebuf
);
1601 if (handle
->md
.ifindex
== -1)
1604 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
1612 * This is cooked mode.
1614 handle
->md
.cooked
= 1;
1615 handle
->linktype
= DLT_LINUX_SLL
;
1618 * We're not bound to a device.
1619 * XXX - true? Or true only if we're using
1621 * For now, we're using this as an indication
1622 * that we can't transmit; stop doing that only
1623 * if we figure out how to transmit in cooked
1626 handle
->md
.ifindex
= -1;
1630 * Select promiscuous mode on if "promisc" is set.
1632 * Do not turn allmulti mode on if we don't select
1633 * promiscuous mode - on some devices (e.g., Orinoco
1634 * wireless interfaces), allmulti mode isn't supported
1635 * and the driver implements it by turning promiscuous
1636 * mode on, and that screws up the operation of the
1637 * card as a normal networking interface, and on no
1638 * other platform I know of does starting a non-
1639 * promiscuous capture affect which multicast packets
1640 * are received by the interface.
1644 * Hmm, how can we set promiscuous mode on all interfaces?
1645 * I am not sure if that is possible at all.
1648 if (device
&& promisc
) {
1649 memset(&mr
, 0, sizeof(mr
));
1650 mr
.mr_ifindex
= handle
->md
.ifindex
;
1651 mr
.mr_type
= PACKET_MR_PROMISC
;
1652 if (setsockopt(sock_fd
, SOL_PACKET
,
1653 PACKET_ADD_MEMBERSHIP
, &mr
, sizeof(mr
)) == -1)
1655 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1656 "setsockopt: %s", pcap_strerror(errno
));
1661 /* Save the socket FD in the pcap structure */
1663 handle
->fd
= sock_fd
;
1674 * Get rid of any link-layer type list we allocated.
1676 if (handle
->dlt_list
!= NULL
)
1677 free(handle
->dlt_list
);
1683 "New packet capturing interface not supported by build "
1684 "environment", PCAP_ERRBUF_SIZE
);
1690 live_open_mmap(pcap_t
* handle
, char* errmsg
)
1692 #ifdef HAVE_PACKET_RING
1693 /* by default request 4M for the ring buffer */
1694 int ret
= create_ring(handle
, 4*1024*1024, errmsg
);
1698 /* override some defaults and inherit the other fields from
1700 * handle->offset is used to get the current position into the rx ring
1701 * handle->cc is used to store the ring size */
1702 handle
->read_op
= pcap_read_linux_mmap
;
1703 handle
->close_op
= pcap_close_linux_mmap
;
1704 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
1705 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
1706 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
1707 handle
->selectable_fd
= handle
->fd
;
1709 #else /* HAVE_PACKET_RING */
1711 #endif /* HAVE_PACKET_RING */
1714 #ifdef HAVE_PACKET_RING
1717 compute_ring_block(int frame_size
, unsigned *block_size
, unsigned *frames_per_block
)
1719 /* compute the minumum block size that will handle this frame.
1720 * The block has to be page size aligned.
1721 * The max block size allowed by the kernel is arch-dependent and
1722 * it's not explicitly checked here. */
1723 *block_size
= getpagesize();
1724 while (*block_size
< frame_size
)
1727 *frames_per_block
= *block_size
/frame_size
;
1731 create_ring(pcap_t
* handle
, unsigned size
, char* errmsg
)
1733 unsigned i
, j
, ringsize
, frames_per_block
;
1734 struct tpacket_req req
;
1736 /* Note that with large snapshot (say 64K) only a few frames
1737 * will be available in the ring even with pretty large ring size
1738 * (and a lot of memory will be unused).
1739 * The snap len should be carefully chosen to achive best
1741 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+TPACKET_HDRLEN
);
1742 req
.tp_frame_nr
= size
/req
.tp_frame_size
;
1743 compute_ring_block(req
.tp_frame_size
, &req
.tp_block_size
, &frames_per_block
);
1744 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
1746 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
1747 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
1749 /* ask the kernel to create the ring */
1751 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1752 (void *) &req
, sizeof(req
))) {
1753 /* try to reduce requested ring size to prevent memory failure */
1754 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
1755 req
.tp_frame_nr
>>= 1;
1756 req
.tp_block_nr
= req
.tp_frame_nr
/frames_per_block
;
1759 snprintf(errmsg
, PCAP_ERRBUF_SIZE
, "can't create rx ring on "
1760 "packet socket %d: %d-%s", handle
->fd
, errno
,
1761 pcap_strerror(errno
));
1765 /* memory map the rx ring */
1766 ringsize
= req
.tp_block_nr
* req
.tp_block_size
;
1767 handle
->bp
= mmap(0, ringsize
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
1769 if (handle
->bp
== MAP_FAILED
) {
1770 snprintf(errmsg
, PCAP_ERRBUF_SIZE
, "can't mmap rx ring: %d-%s",
1771 errno
, pcap_strerror(errno
));
1773 /* clear the allocated ring on error*/
1774 destroy_ring(handle
);
1778 /* allocate a ring for each frame header pointer*/
1779 handle
->cc
= req
.tp_frame_nr
;
1780 handle
->buffer
= malloc(handle
->cc
* sizeof(struct tpacket_hdr
*));
1781 if (!handle
->buffer
) {
1782 destroy_ring(handle
);
1786 /* fill the header ring with proper frame ptr*/
1788 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
1789 u_char
*base
= &handle
->bp
[i
*req
.tp_block_size
];
1790 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
1791 RING_GET_FRAME(handle
) = (struct tpacket_hdr
*) base
;
1792 base
+= req
.tp_frame_size
;
1796 handle
->bufsize
= req
.tp_frame_size
;
1801 /* free all ring related resources*/
1803 destroy_ring(pcap_t
*handle
)
1805 /* tell the kernel to destroy the ring*/
1806 struct tpacket_req req
;
1807 memset(&req
, 0, sizeof(req
));
1808 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1809 (void *) &req
, sizeof(req
));
1811 /* if ring is mapped, unmap it*/
1813 /* need to re-compute the ring size */
1814 unsigned frames_per_block
, block_size
;
1815 compute_ring_block(handle
->bufsize
, &block_size
, &frames_per_block
);
1817 /* do not perform sanity check here: we can't recover any error */
1818 munmap(handle
->bp
, block_size
* handle
->cc
/ frames_per_block
);
1822 /* if the header ring is allocated, clear it*/
1823 if (handle
->buffer
) {
1824 free(handle
->buffer
);
1830 pcap_close_linux_mmap( pcap_t
*handle
)
1832 destroy_ring(handle
);
1833 pcap_close_linux(handle
);
1838 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
1840 /* use negative value of timeout to indicate non blocking ops */
1841 return (p
->md
.timeout
<0);
1845 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
1847 /* map each value to the corresponding 2's complement, to
1848 * preserve the timeout value provided with pcap_open_live */
1850 if (p
->md
.timeout
> 0)
1851 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
1853 if (p
->md
.timeout
< 0)
1854 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
1859 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
1864 /* wait for frames availability.*/
1865 if ((handle
->md
.timeout
>= 0) && !(RING_GET_FRAME(handle
)->tp_status
)) {
1866 struct pollfd pollinfo
;
1869 pollinfo
.fd
= handle
->fd
;
1870 pollinfo
.events
= POLLIN
;
1873 /* poll() requires a negative timeout to wait forever */
1874 ret
= poll(&pollinfo
, 1, (handle
->md
.timeout
> 0)?
1875 handle
->md
.timeout
: -1);
1876 if ((ret
< 0) && (errno
!= EINTR
)) {
1877 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1878 "can't poll on packet socket fd %d: %d-%s",
1879 handle
->fd
, errno
, pcap_strerror(errno
));
1882 /* check for break loop condition on interrupted syscall*/
1883 if (handle
->break_loop
) {
1884 handle
->break_loop
= 0;
1890 /* negative values of max_packets are used to require all
1891 * packets available in the ring */
1892 while ((pkts
< max_packets
) || (max_packets
<0)) {
1894 struct sockaddr_ll
*sll
;
1895 struct pcap_pkthdr pcaphdr
;
1897 struct tpacket_hdr
* thdr
= RING_GET_FRAME(handle
);
1898 if (thdr
->tp_status
== TP_STATUS_KERNEL
)
1901 /* perform sanity check on internal offset. */
1902 if (thdr
->tp_mac
+thdr
->tp_snaplen
> handle
->bufsize
) {
1903 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1904 "corrupted frame on kernel ring mac "
1905 "offset %d + caplen %d > frame len %d\n",
1906 thdr
->tp_mac
, thdr
->tp_snaplen
, handle
->bufsize
);
1910 /* run filter on received packet
1911 * If the kernel filtering is enabled we need to run the
1912 * filter until all the frames present into the ring
1913 * at filter creation time are processed.
1914 * In such case md.use_bpf is used as a counter for the
1915 * packet we need to filter.
1916 * Note: alternatively it could be possible to stop applying
1917 * the filter when the ring became empty, but it can possibly
1918 * happen a lot later... */
1919 bp
= (unsigned char*)thdr
+ thdr
->tp_mac
;
1920 run_bpf
= (!handle
->md
.use_bpf
) ||
1921 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
1922 if (run_bpf
&& handle
->fcode
.bf_insns
&&
1923 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1924 thdr
->tp_len
, thdr
->tp_snaplen
) == 0))
1927 /* check direction and interface index */
1928 sll
= (void*)thdr
+ TPACKET_ALIGN(sizeof(*thdr
));
1929 if ((sll
->sll_ifindex
== handle
->md
.lo_ifindex
) &&
1930 (sll
->sll_pkttype
== PACKET_OUTGOING
))
1933 /* get required packet info from ring header */
1934 pcaphdr
.ts
.tv_sec
= thdr
->tp_sec
;
1935 pcaphdr
.ts
.tv_usec
= thdr
->tp_usec
;
1936 pcaphdr
.caplen
= thdr
->tp_snaplen
;
1937 pcaphdr
.len
= thdr
->tp_len
;
1939 /* if required build in place the sll header*/
1940 if (handle
->md
.cooked
) {
1941 struct sll_header
*hdrp
= (struct sll_header
*)((char *)bp
- sizeof(struct sll_header
));
1943 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
1945 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
1946 hdrp
->sll_halen
= htons(sll
->sll_halen
);
1947 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
1948 hdrp
->sll_protocol
= sll
->sll_protocol
;
1950 /* update packet len */
1951 pcaphdr
.caplen
+= SLL_HDR_LEN
;
1952 pcaphdr
.len
+= SLL_HDR_LEN
;
1955 /* pass the packet to the user */
1957 callback(user
, &pcaphdr
, bp
);
1958 handle
->md
.packets_read
++;
1962 thdr
->tp_status
= TP_STATUS_KERNEL
;
1963 if (++handle
->offset
>= handle
->cc
)
1966 /* check for break loop condition*/
1967 if (handle
->break_loop
) {
1968 handle
->break_loop
= 0;
1976 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
1979 int ret
= pcap_setfilter_linux(handle
, filter
);
1983 /* if the kernel filter is enabled, we need to apply the filter on
1984 * all packets present into the ring. Get an upper bound of their number
1986 if (!handle
->md
.use_bpf
)
1989 /* walk the ring backward and count the free slot */
1990 offset
= handle
->offset
;
1991 if (--handle
->offset
< 0)
1992 handle
->offset
= handle
->cc
- 1;
1993 for (n
=0; n
< handle
->cc
; ++n
) {
1994 if (--handle
->offset
< 0)
1995 handle
->offset
= handle
->cc
- 1;
1996 if (RING_GET_FRAME(handle
)->tp_status
!= TP_STATUS_KERNEL
)
2000 /* be careful to not change current ring position */
2001 handle
->offset
= offset
;
2003 /* store the number of packets currently present in the ring */
2004 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
2008 #endif /* HAVE_PACKET_RING */
2011 #ifdef HAVE_PF_PACKET_SOCKETS
2013 * Return the index of the given device name. Fill ebuf and return
2017 iface_get_id(int fd
, const char *device
, char *ebuf
)
2021 memset(&ifr
, 0, sizeof(ifr
));
2022 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2024 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
2025 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2026 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
2030 return ifr
.ifr_ifindex
;
2034 * Bind the socket associated with FD to the given device.
2037 iface_bind(int fd
, int ifindex
, char *ebuf
)
2039 struct sockaddr_ll sll
;
2041 socklen_t errlen
= sizeof(err
);
2043 memset(&sll
, 0, sizeof(sll
));
2044 sll
.sll_family
= AF_PACKET
;
2045 sll
.sll_ifindex
= ifindex
;
2046 sll
.sll_protocol
= htons(ETH_P_ALL
);
2048 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
2049 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2050 "bind: %s", pcap_strerror(errno
));
2054 /* Any pending errors, e.g., network is down? */
2056 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2057 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2058 "getsockopt: %s", pcap_strerror(errno
));
2063 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2064 "bind: %s", pcap_strerror(err
));
2074 /* ===== Functions to interface to the older kernels ================== */
2077 * With older kernels promiscuous mode is kind of interesting because we
2078 * have to reset the interface before exiting. The problem can't really
2079 * be solved without some daemon taking care of managing usage counts.
2080 * If we put the interface into promiscuous mode, we set a flag indicating
2081 * that we must take it out of that mode when the interface is closed,
2082 * and, when closing the interface, if that flag is set we take it out
2083 * of promiscuous mode.
2087 * List of pcaps for which we turned promiscuous mode on by hand.
2088 * If there are any such pcaps, we arrange to call "pcap_close_all()"
2089 * when we exit, and have it close all of them to turn promiscuous mode
2092 static struct pcap
*pcaps_to_close
;
2095 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
2096 * be called on exit.
2098 static int did_atexit
;
2100 static void pcap_close_all(void)
2102 struct pcap
*handle
;
2104 while ((handle
= pcaps_to_close
) != NULL
)
2108 static void pcap_close_linux( pcap_t
*handle
)
2111 pcap_close_acn(handle
);
2113 struct pcap
*p
, *prevp
;
2116 if (handle
->md
.clear_promisc
) {
2118 * We put the interface into promiscuous mode; take
2119 * it out of promiscuous mode.
2121 * XXX - if somebody else wants it in promiscuous mode,
2122 * this code cannot know that, so it'll take it out
2123 * of promiscuous mode. That's not fixable in 2.0[.x]
2126 memset(&ifr
, 0, sizeof(ifr
));
2127 strncpy(ifr
.ifr_name
, handle
->md
.device
, sizeof(ifr
.ifr_name
));
2128 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2130 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
2131 "Please adjust manually.\n"
2132 "Hint: This can't happen with Linux >= 2.2.0.\n",
2135 if (ifr
.ifr_flags
& IFF_PROMISC
) {
2137 * Promiscuous mode is currently on; turn it
2140 ifr
.ifr_flags
&= ~IFF_PROMISC
;
2141 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2143 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
2144 "Please adjust manually.\n"
2145 "Hint: This can't happen with Linux >= 2.2.0.\n",
2152 * Take this pcap out of the list of pcaps for which we
2153 * have to take the interface out of promiscuous mode.
2155 for (p
= pcaps_to_close
, prevp
= NULL
; p
!= NULL
;
2156 prevp
= p
, p
= p
->md
.next
) {
2159 * Found it. Remove it from the list.
2161 if (prevp
== NULL
) {
2163 * It was at the head of the list.
2165 pcaps_to_close
= p
->md
.next
;
2168 * It was in the middle of the list.
2170 prevp
->md
.next
= p
->md
.next
;
2177 if (handle
->md
.device
!= NULL
)
2178 free(handle
->md
.device
);
2179 handle
->md
.device
= NULL
;
2180 pcap_close_common(handle
);
2185 * Try to open a packet socket using the old kernel interface.
2186 * Returns 0 on failure.
2187 * FIXME: 0 uses to mean success (Sebastian)
2190 live_open_old(pcap_t
*handle
, const char *device
, int promisc
,
2191 int to_ms
, char *ebuf
)
2197 /* Open the socket */
2199 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
2200 if (handle
->fd
== -1) {
2201 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2202 "socket: %s", pcap_strerror(errno
));
2206 /* It worked - we are using the old interface */
2207 handle
->md
.sock_packet
= 1;
2209 /* ...which means we get the link-layer header. */
2210 handle
->md
.cooked
= 0;
2212 /* Bind to the given device */
2215 strncpy(ebuf
, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
2219 if (iface_bind_old(handle
->fd
, device
, ebuf
) == -1)
2223 * Try to get the link-layer type.
2225 arptype
= iface_get_arptype(handle
->fd
, device
, ebuf
);
2230 * Try to find the DLT_ type corresponding to that
2233 map_arphrd_to_dlt(handle
, arptype
, 0);
2234 if (handle
->linktype
== -1) {
2235 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2236 "unknown arptype %d", arptype
);
2240 /* Go to promisc mode if requested */
2243 memset(&ifr
, 0, sizeof(ifr
));
2244 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2245 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2246 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2247 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
2250 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
2252 * Promiscuous mode isn't currently on,
2253 * so turn it on, and remember that
2254 * we should turn it off when the
2259 * If we haven't already done so, arrange
2260 * to have "pcap_close_all()" called when
2264 if (atexit(pcap_close_all
) == -1) {
2266 * "atexit()" failed; don't
2267 * put the interface in
2268 * promiscuous mode, just
2271 strncpy(ebuf
, "atexit failed",
2278 ifr
.ifr_flags
|= IFF_PROMISC
;
2279 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2280 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2282 pcap_strerror(errno
));
2285 handle
->md
.clear_promisc
= 1;
2288 * Add this to the list of pcaps
2289 * to close when we exit.
2291 handle
->md
.next
= pcaps_to_close
;
2292 pcaps_to_close
= handle
;
2297 * Default value for offset to align link-layer payload
2298 * on a 4-byte boundary.
2306 pcap_close_linux(handle
);
2311 * Bind the socket associated with FD to the given device using the
2312 * interface of the old kernels.
2315 iface_bind_old(int fd
, const char *device
, char *ebuf
)
2317 struct sockaddr saddr
;
2319 socklen_t errlen
= sizeof(err
);
2321 memset(&saddr
, 0, sizeof(saddr
));
2322 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
2323 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
2324 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2325 "bind: %s", pcap_strerror(errno
));
2329 /* Any pending errors, e.g., network is down? */
2331 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2332 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2333 "getsockopt: %s", pcap_strerror(errno
));
2338 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2339 "bind: %s", pcap_strerror(err
));
2347 /* ===== System calls available on all supported kernels ============== */
2350 * Query the kernel for the MTU of the given interface.
2353 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
2358 return BIGGER_THAN_ALL_MTUS
;
2360 memset(&ifr
, 0, sizeof(ifr
));
2361 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2363 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
2364 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2365 "SIOCGIFMTU: %s", pcap_strerror(errno
));
2373 * Get the hardware type of the given interface as ARPHRD_xxx constant.
2376 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
2380 memset(&ifr
, 0, sizeof(ifr
));
2381 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2383 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
2384 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2385 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
2389 return ifr
.ifr_hwaddr
.sa_family
;
2392 #ifdef SO_ATTACH_FILTER
2394 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
2398 register struct bpf_insn
*p
;
2403 * Make a copy of the filter, and modify that copy if
2406 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
2407 len
= handle
->fcode
.bf_len
;
2408 f
= (struct bpf_insn
*)malloc(prog_size
);
2410 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2411 "malloc: %s", pcap_strerror(errno
));
2414 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
2416 fcode
->filter
= (struct sock_filter
*) f
;
2418 for (i
= 0; i
< len
; ++i
) {
2421 * What type of instruction is this?
2423 switch (BPF_CLASS(p
->code
)) {
2427 * It's a return instruction; is the snapshot
2428 * length a constant, rather than the contents
2429 * of the accumulator?
2431 if (BPF_MODE(p
->code
) == BPF_K
) {
2433 * Yes - if the value to be returned,
2434 * i.e. the snapshot length, is anything
2435 * other than 0, make it 65535, so that
2436 * the packet is truncated by "recvfrom()",
2437 * not by the filter.
2439 * XXX - there's nothing we can easily do
2440 * if it's getting the value from the
2441 * accumulator; we'd have to insert
2442 * code to force non-zero values to be
2453 * It's a load instruction; is it loading
2456 switch (BPF_MODE(p
->code
)) {
2462 * Yes; are we in cooked mode?
2464 if (handle
->md
.cooked
) {
2466 * Yes, so we need to fix this
2469 if (fix_offset(p
) < 0) {
2471 * We failed to do so.
2472 * Return 0, so our caller
2473 * knows to punt to userland.
2483 return 1; /* we succeeded */
2487 fix_offset(struct bpf_insn
*p
)
2490 * What's the offset?
2492 if (p
->k
>= SLL_HDR_LEN
) {
2494 * It's within the link-layer payload; that starts at an
2495 * offset of 0, as far as the kernel packet filter is
2496 * concerned, so subtract the length of the link-layer
2499 p
->k
-= SLL_HDR_LEN
;
2500 } else if (p
->k
== 14) {
2502 * It's the protocol field; map it to the special magic
2503 * kernel offset for that field.
2505 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
2508 * It's within the header, but it's not one of those
2509 * fields; we can't do that in the kernel, so punt
2518 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
2520 int total_filter_on
= 0;
2526 * The socket filter code doesn't discard all packets queued
2527 * up on the socket when the filter is changed; this means
2528 * that packets that don't match the new filter may show up
2529 * after the new filter is put onto the socket, if those
2530 * packets haven't yet been read.
2532 * This means, for example, that if you do a tcpdump capture
2533 * with a filter, the first few packets in the capture might
2534 * be packets that wouldn't have passed the filter.
2536 * We therefore discard all packets queued up on the socket
2537 * when setting a kernel filter. (This isn't an issue for
2538 * userland filters, as the userland filtering is done after
2539 * packets are queued up.)
2541 * To flush those packets, we put the socket in read-only mode,
2542 * and read packets from the socket until there are no more to
2545 * In order to keep that from being an infinite loop - i.e.,
2546 * to keep more packets from arriving while we're draining
2547 * the queue - we put the "total filter", which is a filter
2548 * that rejects all packets, onto the socket before draining
2551 * This code deliberately ignores any errors, so that you may
2552 * get bogus packets if an error occurs, rather than having
2553 * the filtering done in userland even if it could have been
2554 * done in the kernel.
2556 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2557 &total_fcode
, sizeof(total_fcode
)) == 0) {
2561 * Note that we've put the total filter onto the socket.
2563 total_filter_on
= 1;
2566 * Save the socket's current mode, and put it in
2567 * non-blocking mode; we drain it by reading packets
2568 * until we get an error (which is normally a
2569 * "nothing more to be read" error).
2571 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
2572 if (save_mode
!= -1 &&
2573 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
2574 while (recv(handle
->fd
, &drain
, sizeof drain
,
2578 fcntl(handle
->fd
, F_SETFL
, save_mode
);
2579 if (save_errno
!= EAGAIN
) {
2581 reset_kernel_filter(handle
);
2582 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2583 "recv: %s", pcap_strerror(save_errno
));
2590 * Now attach the new filter.
2592 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2593 fcode
, sizeof(*fcode
));
2594 if (ret
== -1 && total_filter_on
) {
2596 * Well, we couldn't set that filter on the socket,
2597 * but we could set the total filter on the socket.
2599 * This could, for example, mean that the filter was
2600 * too big to put into the kernel, so we'll have to
2601 * filter in userland; in any case, we'll be doing
2602 * filtering in userland, so we need to remove the
2603 * total filter so we see packets.
2608 * XXX - if this fails, we're really screwed;
2609 * we have the total filter on the socket,
2610 * and it won't come off. What do we do then?
2612 reset_kernel_filter(handle
);
2620 reset_kernel_filter(pcap_t
*handle
)
2623 * setsockopt() barfs unless it get a dummy parameter.
2624 * valgrind whines unless the value is initialized,
2625 * as it has no idea that setsockopt() ignores its
2630 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
2631 &dummy
, sizeof(dummy
));