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.133 2008-01-06 20:23:17 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"
111 #include <sys/socket.h>
112 #include <sys/ioctl.h>
113 #include <sys/utsname.h>
114 #include <sys/mman.h>
116 #include <netinet/in.h>
117 #include <linux/if_ether.h>
118 #include <net/if_arp.h>
122 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
123 * sockets rather than SOCK_PACKET sockets.
125 * To use them, we include <linux/if_packet.h> rather than
126 * <netpacket/packet.h>; we do so because
128 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
129 * later kernels and libc5, and don't provide a <netpacket/packet.h>
132 * not all versions of glibc2 have a <netpacket/packet.h> file
133 * that defines stuff needed for some of the 2.4-or-later-kernel
134 * features, so if the system has a 2.4 or later kernel, we
135 * still can't use those features.
137 * We're already including a number of other <linux/XXX.h> headers, and
138 * this code is Linux-specific (no other OS has PF_PACKET sockets as
139 * a raw packet capture mechanism), so it's not as if you gain any
140 * useful portability by using <netpacket/packet.h>
142 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
143 * isn't defined? It only defines one data structure in 2.0.x, so
144 * it shouldn't cause any problems.
147 # include <linux/if_packet.h>
150 * On at least some Linux distributions (for example, Red Hat 5.2),
151 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
152 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
153 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
154 * the PACKET_xxx stuff.
156 * So we check whether PACKET_HOST is defined, and assume that we have
157 * PF_PACKET sockets only if it is defined.
160 # define HAVE_PF_PACKET_SOCKETS
161 # endif /* PACKET_HOST */
164 /* check for memory mapped access avaibility. We assume every needed
165 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
166 * uses many ring related structs and macros */
167 # ifdef TPACKET_HDRLEN
168 # define HAVE_PACKET_RING
169 # endif /* TPACKET_HDRLEN */
170 #endif /* PF_PACKET */
172 #ifdef SO_ATTACH_FILTER
173 #include <linux/types.h>
174 #include <linux/filter.h>
178 typedef int socklen_t
;
183 * This is being compiled on a system that lacks MSG_TRUNC; define it
184 * with the value it has in the 2.2 and later kernels, so that, on
185 * those kernels, when we pass it in the flags argument to "recvfrom()"
186 * we're passing the right value and thus get the MSG_TRUNC behavior
187 * we want. (We don't get that behavior on 2.0[.x] kernels, because
188 * they didn't support MSG_TRUNC.)
190 #define MSG_TRUNC 0x20
195 * This is being compiled on a system that lacks SOL_PACKET; define it
196 * with the value it has in the 2.2 and later kernels, so that we can
197 * set promiscuous mode in the good modern way rather than the old
198 * 2.0-kernel crappy way.
200 #define SOL_PACKET 263
203 #define MAX_LINKHEADER_SIZE 256
206 * When capturing on all interfaces we use this as the buffer size.
207 * Should be bigger then all MTUs that occur in real life.
208 * 64kB should be enough for now.
210 #define BIGGER_THAN_ALL_MTUS (64*1024)
213 * Prototypes for internal functions
215 static void map_arphrd_to_dlt(pcap_t
*, int, int);
216 static short int map_packet_type_to_sll_type(short int);
217 static int live_open_old(pcap_t
*, const char *, int, int, char *);
218 static int live_open_new(pcap_t
*, const char *, int, int, char *);
219 static int live_open_mmap(pcap_t
*, char *);
220 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
221 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
222 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
223 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
224 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
225 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
226 static void pcap_close_linux(pcap_t
*);
228 #ifdef HAVE_PACKET_RING
229 #define RING_GET_FRAME(h) (((struct tpacket_hdr**)h->buffer)[handle->offset])
231 static void destroy_ring(pcap_t
*handle
);
232 static int create_ring(pcap_t
* handle
, unsigned size
, char* errmsg
);
233 static void pcap_close_linux_mmap(pcap_t
*);
234 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
235 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
236 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
237 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
241 * Wrap some ioctl calls
243 #ifdef HAVE_PF_PACKET_SOCKETS
244 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
246 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
247 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
248 #ifdef HAVE_PF_PACKET_SOCKETS
249 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
251 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
253 #ifdef SO_ATTACH_FILTER
254 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
255 static int fix_offset(struct bpf_insn
*p
);
256 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
257 static int reset_kernel_filter(pcap_t
*handle
);
259 static struct sock_filter total_insn
260 = BPF_STMT(BPF_RET
| BPF_K
, 0);
261 static struct sock_fprog total_fcode
262 = { 1, &total_insn
};
266 * Get a handle for a live capture from the given device. You can
267 * pass NULL as device to get all packages (without link level
268 * information of course). If you pass 1 as promisc the interface
269 * will be set to promiscous mode (XXX: I think this usage should
270 * be deprecated and functions be added to select that later allow
271 * modification of that values -- Torsten).
276 pcap_open_live(const char *device
, int snaplen
, int promisc
, int to_ms
,
282 int live_open_ok
= 0;
283 struct utsname utsname
;
286 if (strstr(device
, "dag")) {
287 return dag_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
289 #endif /* HAVE_DAG_API */
291 #ifdef HAVE_SEPTEL_API
292 if (strstr(device
, "septel")) {
293 return septel_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
295 #endif /* HAVE_SEPTEL_API */
297 #ifdef PCAP_SUPPORT_BT
298 if (strstr(device
, "bluetooth")) {
299 return bt_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
303 #ifdef PCAP_SUPPORT_USB
304 if (strstr(device
, "usb")) {
305 return usb_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
309 /* Allocate a handle for this session. */
311 handle
= malloc(sizeof(*handle
));
312 if (handle
== NULL
) {
313 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
314 pcap_strerror(errno
));
318 /* Initialize some components of the pcap structure. */
320 memset(handle
, 0, sizeof(*handle
));
321 handle
->snapshot
= snaplen
;
322 handle
->md
.timeout
= to_ms
;
324 handle
->inject_op
= pcap_inject_linux
;
325 handle
->setfilter_op
= pcap_setfilter_linux
;
326 handle
->setdirection_op
= pcap_setdirection_linux
;
327 handle
->set_datalink_op
= NULL
; /* can't change data link type */
328 handle
->getnonblock_op
= pcap_getnonblock_fd
;
329 handle
->setnonblock_op
= pcap_setnonblock_fd
;
330 handle
->close_op
= pcap_close_linux
;
331 handle
->read_op
= pcap_read_linux
;
332 handle
->stats_op
= pcap_stats_linux
;
335 * NULL and "any" are special devices which give us the hint to
336 * monitor all devices.
338 if (!device
|| strcmp(device
, "any") == 0) {
340 handle
->md
.device
= strdup("any");
343 /* Just a warning. */
344 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
345 "Promiscuous mode not supported on the \"any\" device");
349 handle
->md
.device
= strdup(device
);
351 if (handle
->md
.device
== NULL
) {
352 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
353 pcap_strerror(errno
) );
359 * Current Linux kernels use the protocol family PF_PACKET to
360 * allow direct access to all packets on the network while
361 * older kernels had a special socket type SOCK_PACKET to
362 * implement this feature.
363 * While this old implementation is kind of obsolete we need
364 * to be compatible with older kernels for a while so we are
365 * trying both methods with the newer method preferred.
368 if ((err
= live_open_new(handle
, device
, promisc
, to_ms
, ebuf
)) == 1) {
370 if (live_open_mmap(handle
, ebuf
) == 1)
374 /* Non-fatal error; try old way */
375 if (live_open_old(handle
, device
, promisc
, to_ms
, ebuf
))
380 * Both methods to open the packet socket failed. Tidy
381 * up and report our failure (ebuf is expected to be
382 * set by the functions above).
385 if (handle
->md
.device
!= NULL
)
386 free(handle
->md
.device
);
392 * Compute the buffer size.
394 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
395 * and might require special handling - check.
397 if (handle
->md
.sock_packet
&& (uname(&utsname
) < 0 ||
398 strncmp(utsname
.release
, "2.0", 3) == 0)) {
400 * We're using a SOCK_PACKET structure, and either
401 * we couldn't find out what kernel release this is,
402 * or it's a 2.0[.x] kernel.
404 * In the 2.0[.x] kernel, a "recvfrom()" on
405 * a SOCK_PACKET socket, with MSG_TRUNC set, will
406 * return the number of bytes read, so if we pass
407 * a length based on the snapshot length, it'll
408 * return the number of bytes from the packet
409 * copied to userland, not the actual length
412 * This means that, for example, the IP dissector
413 * in tcpdump will get handed a packet length less
414 * than the length in the IP header, and will
415 * complain about "truncated-ip".
417 * So we don't bother trying to copy from the
418 * kernel only the bytes in which we're interested,
419 * but instead copy them all, just as the older
420 * versions of libpcap for Linux did.
422 * The buffer therefore needs to be big enough to
423 * hold the largest packet we can get from this
424 * device. Unfortunately, we can't get the MRU
425 * of the network; we can only get the MTU. The
426 * MTU may be too small, in which case a packet larger
427 * than the buffer size will be truncated *and* we
428 * won't get the actual packet size.
430 * However, if the snapshot length is larger than
431 * the buffer size based on the MTU, we use the
432 * snapshot length as the buffer size, instead;
433 * this means that with a sufficiently large snapshot
434 * length we won't artificially truncate packets
435 * to the MTU-based size.
437 * This mess just one of many problems with packet
438 * capture on 2.0[.x] kernels; you really want a
439 * 2.2[.x] or later kernel if you want packet capture
442 mtu
= iface_get_mtu(handle
->fd
, device
, ebuf
);
444 pcap_close_linux(handle
);
448 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
449 if (handle
->bufsize
< handle
->snapshot
)
450 handle
->bufsize
= handle
->snapshot
;
453 * This is a 2.2[.x] or later kernel (we know that
454 * either because we're not using a SOCK_PACKET
455 * socket - PF_PACKET is supported only in 2.2
456 * and later kernels - or because we checked the
459 * We can safely pass "recvfrom()" a byte count
460 * based on the snapshot length.
462 * If we're in cooked mode, make the snapshot length
463 * large enough to hold a "cooked mode" header plus
464 * 1 byte of packet data (so we don't pass a byte
465 * count of 0 to "recvfrom()").
467 if (handle
->md
.cooked
) {
468 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
469 handle
->snapshot
= SLL_HDR_LEN
+ 1;
471 handle
->bufsize
= handle
->snapshot
;
474 /* Allocate the buffer */
476 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
477 if (!handle
->buffer
) {
478 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
479 "malloc: %s", pcap_strerror(errno
));
480 pcap_close_linux(handle
);
486 * "handle->fd" is a socket, so "select()" and "poll()"
489 handle
->selectable_fd
= handle
->fd
;
495 * Read at most max_packets from the capture stream and call the callback
496 * for each of them. Returns the number of packets handled or -1 if an
500 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
503 * Currently, on Linux only one packet is delivered per read,
506 return pcap_read_packet(handle
, callback
, user
);
510 * Read a packet from the socket calling the handler provided by
511 * the user. Returns the number of packets received or -1 if an
515 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
519 #ifdef HAVE_PF_PACKET_SOCKETS
520 struct sockaddr_ll from
;
521 struct sll_header
*hdrp
;
523 struct sockaddr from
;
526 int packet_len
, caplen
;
527 struct pcap_pkthdr pcap_header
;
529 #ifdef HAVE_PF_PACKET_SOCKETS
531 * If this is a cooked device, leave extra room for a
532 * fake packet header.
534 if (handle
->md
.cooked
)
535 offset
= SLL_HDR_LEN
;
540 * This system doesn't have PF_PACKET sockets, so it doesn't
541 * support cooked devices.
546 /* Receive a single packet from the kernel */
548 bp
= handle
->buffer
+ handle
->offset
;
551 * Has "pcap_breakloop()" been called?
553 if (handle
->break_loop
) {
555 * Yes - clear the flag that indicates that it
556 * has, and return -2 as an indication that we
557 * were told to break out of the loop.
559 handle
->break_loop
= 0;
562 fromlen
= sizeof(from
);
563 packet_len
= recvfrom(
564 handle
->fd
, bp
+ offset
,
565 handle
->bufsize
- offset
, MSG_TRUNC
,
566 (struct sockaddr
*) &from
, &fromlen
);
567 } while (packet_len
== -1 && errno
== EINTR
);
569 /* Check if an error occured */
571 if (packet_len
== -1) {
573 return 0; /* no packet there */
575 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
576 "recvfrom: %s", pcap_strerror(errno
));
581 #ifdef HAVE_PF_PACKET_SOCKETS
582 if (!handle
->md
.sock_packet
) {
584 * Unfortunately, there is a window between socket() and
585 * bind() where the kernel may queue packets from any
586 * interface. If we're bound to a particular interface,
587 * discard packets not from that interface.
589 * (If socket filters are supported, we could do the
590 * same thing we do when changing the filter; however,
591 * that won't handle packet sockets without socket
592 * filter support, and it's a bit more complicated.
593 * It would save some instructions per packet, however.)
595 if (handle
->md
.ifindex
!= -1 &&
596 from
.sll_ifindex
!= handle
->md
.ifindex
)
600 * Do checks based on packet direction.
601 * We can only do this if we're using PF_PACKET; the
602 * address returned for SOCK_PACKET is a "sockaddr_pkt"
603 * which lacks the relevant packet type information.
605 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
608 * If this is from the loopback device, reject it;
609 * we'll see the packet as an incoming packet as well,
610 * and we don't want to see it twice.
612 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
616 * If the user only wants incoming packets, reject it.
618 if (handle
->direction
== PCAP_D_IN
)
623 * If the user only wants outgoing packets, reject it.
625 if (handle
->direction
== PCAP_D_OUT
)
631 #ifdef HAVE_PF_PACKET_SOCKETS
633 * If this is a cooked device, fill in the fake packet header.
635 if (handle
->md
.cooked
) {
637 * Add the length of the fake header to the length
638 * of packet data we read.
640 packet_len
+= SLL_HDR_LEN
;
642 hdrp
= (struct sll_header
*)bp
;
643 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
644 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
645 hdrp
->sll_halen
= htons(from
.sll_halen
);
646 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
647 (from
.sll_halen
> SLL_ADDRLEN
) ?
650 hdrp
->sll_protocol
= from
.sll_protocol
;
655 * XXX: According to the kernel source we should get the real
656 * packet len if calling recvfrom with MSG_TRUNC set. It does
657 * not seem to work here :(, but it is supported by this code
659 * To be honest the code RELIES on that feature so this is really
660 * broken with 2.2.x kernels.
661 * I spend a day to figure out what's going on and I found out
662 * that the following is happening:
664 * The packet comes from a random interface and the packet_rcv
665 * hook is called with a clone of the packet. That code inserts
666 * the packet into the receive queue of the packet socket.
667 * If a filter is attached to that socket that filter is run
668 * first - and there lies the problem. The default filter always
669 * cuts the packet at the snaplen:
674 * So the packet filter cuts down the packet. The recvfrom call
675 * says "hey, it's only 68 bytes, it fits into the buffer" with
676 * the result that we don't get the real packet length. This
677 * is valid at least until kernel 2.2.17pre6.
679 * We currently handle this by making a copy of the filter
680 * program, fixing all "ret" instructions with non-zero
681 * operands to have an operand of 65535 so that the filter
682 * doesn't truncate the packet, and supplying that modified
683 * filter to the kernel.
687 if (caplen
> handle
->snapshot
)
688 caplen
= handle
->snapshot
;
690 /* Run the packet filter if not using kernel filter */
691 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
692 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
693 packet_len
, caplen
) == 0)
695 /* rejected by filter */
700 /* Fill in our own header data */
702 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
703 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
704 "SIOCGSTAMP: %s", pcap_strerror(errno
));
707 pcap_header
.caplen
= caplen
;
708 pcap_header
.len
= packet_len
;
713 * Arguably, we should count them before we check the filter,
714 * as on many other platforms "ps_recv" counts packets
715 * handed to the filter rather than packets that passed
716 * the filter, but if filtering is done in the kernel, we
717 * can't get a count of packets that passed the filter,
718 * and that would mean the meaning of "ps_recv" wouldn't
719 * be the same on all Linux systems.
721 * XXX - it's not the same on all systems in any case;
722 * ideally, we should have a "get the statistics" call
723 * that supplies more counts and indicates which of them
724 * it supplies, so that we supply a count of packets
725 * handed to the filter only on platforms where that
726 * information is available.
728 * We count them here even if we can get the packet count
729 * from the kernel, as we can only determine at run time
730 * whether we'll be able to get it from the kernel (if
731 * HAVE_TPACKET_STATS isn't defined, we can't get it from
732 * the kernel, but if it is defined, the library might
733 * have been built with a 2.4 or later kernel, but we
734 * might be running on a 2.2[.x] kernel without Alexey
735 * Kuznetzov's turbopacket patches, and thus the kernel
736 * might not be able to supply those statistics). We
737 * could, I guess, try, when opening the socket, to get
738 * the statistics, and if we can not increment the count
739 * here, but it's not clear that always incrementing
740 * the count is more expensive than always testing a flag
743 * We keep the count in "md.packets_read", and use that for
744 * "ps_recv" if we can't get the statistics from the kernel.
745 * We do that because, if we *can* get the statistics from
746 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
747 * as running counts, as reading the statistics from the
748 * kernel resets the kernel statistics, and if we directly
749 * increment "md.stat.ps_recv" here, that means it will
750 * count packets *twice* on systems where we can get kernel
751 * statistics - once here, and once in pcap_stats_linux().
753 handle
->md
.packets_read
++;
755 /* Call the user supplied callback function */
756 callback(userdata
, &pcap_header
, bp
);
762 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
766 #ifdef HAVE_PF_PACKET_SOCKETS
767 if (!handle
->md
.sock_packet
) {
768 /* PF_PACKET socket */
769 if (handle
->md
.ifindex
== -1) {
771 * We don't support sending on the "any" device.
773 strlcpy(handle
->errbuf
,
774 "Sending packets isn't supported on the \"any\" device",
779 if (handle
->md
.cooked
) {
781 * We don't support sending on the "any" device.
783 * XXX - how do you send on a bound cooked-mode
785 * Is a "sendto()" required there?
787 strlcpy(handle
->errbuf
,
788 "Sending packets isn't supported in cooked mode",
795 ret
= send(handle
->fd
, buf
, size
, 0);
797 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
798 pcap_strerror(errno
));
805 * Get the statistics for the given packet capture handle.
806 * Reports the number of dropped packets iff the kernel supports
807 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
808 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
809 * patches); otherwise, that information isn't available, and we lie
810 * and report 0 as the count of dropped packets.
813 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
815 #ifdef HAVE_TPACKET_STATS
816 struct tpacket_stats kstats
;
817 socklen_t len
= sizeof (struct tpacket_stats
);
820 #ifdef HAVE_TPACKET_STATS
822 * Try to get the packet counts from the kernel.
824 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
825 &kstats
, &len
) > -1) {
827 * On systems where the PACKET_STATISTICS "getsockopt()"
828 * argument is supported on PF_PACKET sockets:
830 * "ps_recv" counts only packets that *passed* the
831 * filter, not packets that didn't pass the filter.
832 * This includes packets later dropped because we
833 * ran out of buffer space.
835 * "ps_drop" counts packets dropped because we ran
836 * out of buffer space. It doesn't count packets
837 * dropped by the interface driver. It counts only
838 * packets that passed the filter.
840 * Both statistics include packets not yet read from
841 * the kernel by libpcap, and thus not yet seen by
844 * In "linux/net/packet/af_packet.c", at least in the
845 * 2.4.9 kernel, "tp_packets" is incremented for every
846 * packet that passes the packet filter *and* is
847 * successfully queued on the socket; "tp_drops" is
848 * incremented for every packet dropped because there's
849 * not enough free space in the socket buffer.
851 * When the statistics are returned for a PACKET_STATISTICS
852 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
853 * so that "tp_packets" counts all packets handed to
854 * the PF_PACKET socket, including packets dropped because
855 * there wasn't room on the socket buffer - but not
856 * including packets that didn't pass the filter.
858 * In the BSD BPF, the count of received packets is
859 * incremented for every packet handed to BPF, regardless
860 * of whether it passed the filter.
862 * We can't make "pcap_stats()" work the same on both
863 * platforms, but the best approximation is to return
864 * "tp_packets" as the count of packets and "tp_drops"
865 * as the count of drops.
867 * Keep a running total because each call to
868 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
869 * resets the counters to zero.
871 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
872 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
873 *stats
= handle
->md
.stat
;
879 * If the error was EOPNOTSUPP, fall through, so that
880 * if you build the library on a system with
881 * "struct tpacket_stats" and run it on a system
882 * that doesn't, it works as it does if the library
883 * is built on a system without "struct tpacket_stats".
885 if (errno
!= EOPNOTSUPP
) {
886 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
887 "pcap_stats: %s", pcap_strerror(errno
));
893 * On systems where the PACKET_STATISTICS "getsockopt()" argument
894 * is not supported on PF_PACKET sockets:
896 * "ps_recv" counts only packets that *passed* the filter,
897 * not packets that didn't pass the filter. It does not
898 * count packets dropped because we ran out of buffer
901 * "ps_drop" is not supported.
903 * "ps_recv" doesn't include packets not yet read from
904 * the kernel by libpcap.
906 * We maintain the count of packets processed by libpcap in
907 * "md.packets_read", for reasons described in the comment
908 * at the end of pcap_read_packet(). We have no idea how many
909 * packets were dropped.
911 stats
->ps_recv
= handle
->md
.packets_read
;
917 * Description string for the "any" device.
919 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
922 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
924 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
928 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
930 #endif /* HAVE_DAG_API */
932 #ifdef HAVE_SEPTEL_API
933 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
935 #endif /* HAVE_SEPTEL_API */
937 #ifdef PCAP_SUPPORT_BT
938 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
942 #ifdef PCAP_SUPPORT_USB
943 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
951 * Attach the given BPF code to the packet capture device.
954 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
956 #ifdef SO_ATTACH_FILTER
957 struct sock_fprog fcode
;
958 int can_filter_in_kernel
;
965 strncpy(handle
->errbuf
, "setfilter: No filter specified",
966 sizeof(handle
->errbuf
));
970 /* Make our private copy of the filter */
972 if (install_bpf_program(handle
, filter
) < 0)
973 /* install_bpf_program() filled in errbuf */
977 * Run user level packet filter by default. Will be overriden if
978 * installing a kernel filter succeeds.
980 handle
->md
.use_bpf
= 0;
982 /* Install kernel level filter if possible */
984 #ifdef SO_ATTACH_FILTER
986 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
988 * fcode.len is an unsigned short for current kernel.
989 * I have yet to see BPF-Code with that much
990 * instructions but still it is possible. So for the
991 * sake of correctness I added this check.
993 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
996 can_filter_in_kernel
= 0;
998 #endif /* USHRT_MAX */
1001 * Oh joy, the Linux kernel uses struct sock_fprog instead
1002 * of struct bpf_program and of course the length field is
1003 * of different size. Pointed out by Sebastian
1005 * Oh, and we also need to fix it up so that all "ret"
1006 * instructions with non-zero operands have 65535 as the
1007 * operand, and so that, if we're in cooked mode, all
1008 * memory-reference instructions use special magic offsets
1009 * in references to the link-layer header and assume that
1010 * the link-layer payload begins at 0; "fix_program()"
1013 switch (fix_program(handle
, &fcode
)) {
1018 * Fatal error; just quit.
1019 * (The "default" case shouldn't happen; we
1020 * return -1 for that reason.)
1026 * The program performed checks that we can't make
1027 * work in the kernel.
1029 can_filter_in_kernel
= 0;
1034 * We have a filter that'll work in the kernel.
1036 can_filter_in_kernel
= 1;
1041 if (can_filter_in_kernel
) {
1042 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
1044 /* Installation succeded - using kernel filter. */
1045 handle
->md
.use_bpf
= 1;
1047 else if (err
== -1) /* Non-fatal error */
1050 * Print a warning if we weren't able to install
1051 * the filter for a reason other than "this kernel
1052 * isn't configured to support socket filters.
1054 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
1056 "Warning: Kernel filter failed: %s\n",
1057 pcap_strerror(errno
));
1063 * If we're not using the kernel filter, get rid of any kernel
1064 * filter that might've been there before, e.g. because the
1065 * previous filter could work in the kernel, or because some other
1066 * code attached a filter to the socket by some means other than
1067 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1068 * filter out packets that would pass the new userland filter.
1070 if (!handle
->md
.use_bpf
)
1071 reset_kernel_filter(handle
);
1074 * Free up the copy of the filter that was made by "fix_program()".
1076 if (fcode
.filter
!= NULL
)
1082 #endif /* SO_ATTACH_FILTER */
1088 * Set direction flag: Which packets do we accept on a forwarding
1089 * single device? IN, OUT or both?
1092 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1094 #ifdef HAVE_PF_PACKET_SOCKETS
1095 if (!handle
->md
.sock_packet
) {
1096 handle
->direction
= d
;
1101 * We're not using PF_PACKET sockets, so we can't determine
1102 * the direction of the packet.
1104 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1105 "Setting direction is not supported on SOCK_PACKET sockets");
1111 * Map the PACKET_ value to a LINUX_SLL_ value; we
1112 * want the same numerical value to be used in
1113 * the link-layer header even if the numerical values
1114 * for the PACKET_ #defines change, so that programs
1115 * that look at the packet type field will always be
1116 * able to handle DLT_LINUX_SLL captures.
1119 map_packet_type_to_sll_type(short int sll_pkttype
)
1121 switch (sll_pkttype
) {
1124 return htons(LINUX_SLL_HOST
);
1126 case PACKET_BROADCAST
:
1127 return htons(LINUX_SLL_BROADCAST
);
1129 case PACKET_MULTICAST
:
1130 return htons(LINUX_SLL_MULTICAST
);
1132 case PACKET_OTHERHOST
:
1133 return htons(LINUX_SLL_OTHERHOST
);
1135 case PACKET_OUTGOING
:
1136 return htons(LINUX_SLL_OUTGOING
);
1144 * Linux uses the ARP hardware type to identify the type of an
1145 * interface. pcap uses the DLT_xxx constants for this. This
1146 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1147 * constant, as arguments, and sets "handle->linktype" to the
1148 * appropriate DLT_XXX constant and sets "handle->offset" to
1149 * the appropriate value (to make "handle->offset" plus link-layer
1150 * header length be a multiple of 4, so that the link-layer payload
1151 * will be aligned on a 4-byte boundary when capturing packets).
1152 * (If the offset isn't set here, it'll be 0; add code as appropriate
1153 * for cases where it shouldn't be 0.)
1155 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1156 * in cooked mode; otherwise, we can't use cooked mode, so we have
1157 * to pick some type that works in raw mode, or fail.
1159 * Sets the link type to -1 if unable to map the type.
1161 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1167 * This is (presumably) a real Ethernet capture; give it a
1168 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1169 * that an application can let you choose it, in case you're
1170 * capturing DOCSIS traffic that a Cisco Cable Modem
1171 * Termination System is putting out onto an Ethernet (it
1172 * doesn't put an Ethernet header onto the wire, it puts raw
1173 * DOCSIS frames out on the wire inside the low-level
1174 * Ethernet framing).
1176 * XXX - are there any sorts of "fake Ethernet" that have
1177 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1178 * a Cisco CMTS won't put traffic onto it or get traffic
1179 * bridged onto it? ISDN is handled in "live_open_new()",
1180 * as we fall back on cooked mode there; are there any
1183 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1185 * If that fails, just leave the list empty.
1187 if (handle
->dlt_list
!= NULL
) {
1188 handle
->dlt_list
[0] = DLT_EN10MB
;
1189 handle
->dlt_list
[1] = DLT_DOCSIS
;
1190 handle
->dlt_count
= 2;
1194 case ARPHRD_METRICOM
:
1195 case ARPHRD_LOOPBACK
:
1196 handle
->linktype
= DLT_EN10MB
;
1201 handle
->linktype
= DLT_EN3MB
;
1205 handle
->linktype
= DLT_AX25_KISS
;
1209 handle
->linktype
= DLT_PRONET
;
1213 handle
->linktype
= DLT_CHAOS
;
1216 #ifndef ARPHRD_IEEE802_TR
1217 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1219 case ARPHRD_IEEE802_TR
:
1220 case ARPHRD_IEEE802
:
1221 handle
->linktype
= DLT_IEEE802
;
1226 handle
->linktype
= DLT_ARCNET_LINUX
;
1229 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1230 #define ARPHRD_FDDI 774
1233 handle
->linktype
= DLT_FDDI
;
1237 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1238 #define ARPHRD_ATM 19
1242 * The Classical IP implementation in ATM for Linux
1243 * supports both what RFC 1483 calls "LLC Encapsulation",
1244 * in which each packet has an LLC header, possibly
1245 * with a SNAP header as well, prepended to it, and
1246 * what RFC 1483 calls "VC Based Multiplexing", in which
1247 * different virtual circuits carry different network
1248 * layer protocols, and no header is prepended to packets.
1250 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1251 * you can't use the ARPHRD_ type to find out whether
1252 * captured packets will have an LLC header, and,
1253 * while there's a socket ioctl to *set* the encapsulation
1254 * type, there's no ioctl to *get* the encapsulation type.
1258 * programs that dissect Linux Classical IP frames
1259 * would have to check for an LLC header and,
1260 * depending on whether they see one or not, dissect
1261 * the frame as LLC-encapsulated or as raw IP (I
1262 * don't know whether there's any traffic other than
1263 * IP that would show up on the socket, or whether
1264 * there's any support for IPv6 in the Linux
1265 * Classical IP code);
1267 * filter expressions would have to compile into
1268 * code that checks for an LLC header and does
1271 * Both of those are a nuisance - and, at least on systems
1272 * that support PF_PACKET sockets, we don't have to put
1273 * up with those nuisances; instead, we can just capture
1274 * in cooked mode. That's what we'll do, if we can.
1275 * Otherwise, we'll just fail.
1278 handle
->linktype
= DLT_LINUX_SLL
;
1280 handle
->linktype
= -1;
1283 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1284 #define ARPHRD_IEEE80211 801
1286 case ARPHRD_IEEE80211
:
1287 handle
->linktype
= DLT_IEEE802_11
;
1290 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1291 #define ARPHRD_IEEE80211_PRISM 802
1293 case ARPHRD_IEEE80211_PRISM
:
1294 handle
->linktype
= DLT_PRISM_HEADER
;
1297 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1298 #define ARPHRD_IEEE80211_RADIOTAP 803
1300 case ARPHRD_IEEE80211_RADIOTAP
:
1301 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1306 * Some PPP code in the kernel supplies no link-layer
1307 * header whatsoever to PF_PACKET sockets; other PPP
1308 * code supplies PPP link-layer headers ("syncppp.c");
1309 * some PPP code might supply random link-layer
1310 * headers (PPP over ISDN - there's code in Ethereal,
1311 * for example, to cope with PPP-over-ISDN captures
1312 * with which the Ethereal developers have had to cope,
1313 * heuristically trying to determine which of the
1314 * oddball link-layer headers particular packets have).
1316 * As such, we just punt, and run all PPP interfaces
1317 * in cooked mode, if we can; otherwise, we just treat
1318 * it as DLT_RAW, for now - if somebody needs to capture,
1319 * on a 2.0[.x] kernel, on PPP devices that supply a
1320 * link-layer header, they'll have to add code here to
1321 * map to the appropriate DLT_ type (possibly adding a
1322 * new DLT_ type, if necessary).
1325 handle
->linktype
= DLT_LINUX_SLL
;
1328 * XXX - handle ISDN types here? We can't fall
1329 * back on cooked sockets, so we'd have to
1330 * figure out from the device name what type of
1331 * link-layer encapsulation it's using, and map
1332 * that to an appropriate DLT_ value, meaning
1333 * we'd map "isdnN" devices to DLT_RAW (they
1334 * supply raw IP packets with no link-layer
1335 * header) and "isdY" devices to a new DLT_I4L_IP
1336 * type that has only an Ethernet packet type as
1337 * a link-layer header.
1339 * But sometimes we seem to get random crap
1340 * in the link-layer header when capturing on
1343 handle
->linktype
= DLT_RAW
;
1347 #ifndef ARPHRD_CISCO
1348 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1351 handle
->linktype
= DLT_C_HDLC
;
1354 /* Not sure if this is correct for all tunnels, but it
1358 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1366 #ifndef ARPHRD_RAWHDLC
1367 #define ARPHRD_RAWHDLC 518
1369 case ARPHRD_RAWHDLC
:
1371 #define ARPHRD_DLCI 15
1375 * XXX - should some of those be mapped to DLT_LINUX_SLL
1376 * instead? Should we just map all of them to DLT_LINUX_SLL?
1378 handle
->linktype
= DLT_RAW
;
1382 #define ARPHRD_FRAD 770
1385 handle
->linktype
= DLT_FRELAY
;
1388 case ARPHRD_LOCALTLK
:
1389 handle
->linktype
= DLT_LTALK
;
1393 #define ARPHRD_FCPP 784
1397 #define ARPHRD_FCAL 785
1401 #define ARPHRD_FCPL 786
1404 #ifndef ARPHRD_FCFABRIC
1405 #define ARPHRD_FCFABRIC 787
1407 case ARPHRD_FCFABRIC
:
1409 * We assume that those all mean RFC 2625 IP-over-
1410 * Fibre Channel, with the RFC 2625 header at
1411 * the beginning of the packet.
1413 handle
->linktype
= DLT_IP_OVER_FC
;
1417 #define ARPHRD_IRDA 783
1420 /* Don't expect IP packet out of this interfaces... */
1421 handle
->linktype
= DLT_LINUX_IRDA
;
1422 /* We need to save packet direction for IrDA decoding,
1423 * so let's use "Linux-cooked" mode. Jean II */
1424 //handle->md.cooked = 1;
1427 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1428 * is needed, please report it to <daniele@orlandi.com> */
1430 #define ARPHRD_LAPD 8445
1433 /* Don't expect IP packet out of this interfaces... */
1434 handle
->linktype
= DLT_LINUX_LAPD
;
1438 handle
->linktype
= -1;
1443 /* ===== Functions to interface to the newer kernels ================== */
1446 * Try to open a packet socket using the new kernel interface.
1447 * Returns 0 on failure.
1448 * FIXME: 0 uses to mean success (Sebastian)
1451 live_open_new(pcap_t
*handle
, const char *device
, int promisc
,
1452 int to_ms
, char *ebuf
)
1454 #ifdef HAVE_PF_PACKET_SOCKETS
1455 int sock_fd
= -1, arptype
;
1458 struct packet_mreq mr
;
1460 /* One shot loop used for error handling - bail out with break */
1464 * Open a socket with protocol family packet. If a device is
1465 * given we try to open it in raw mode otherwise we use
1466 * the cooked interface.
1469 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
1470 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
1472 if (sock_fd
== -1) {
1473 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
1474 pcap_strerror(errno
) );
1478 /* It seems the kernel supports the new interface. */
1479 handle
->md
.sock_packet
= 0;
1482 * Get the interface index of the loopback device.
1483 * If the attempt fails, don't fail, just set the
1484 * "md.lo_ifindex" to -1.
1486 * XXX - can there be more than one device that loops
1487 * packets back, i.e. devices other than "lo"? If so,
1488 * we'd need to find them all, and have an array of
1489 * indices for them, and check all of them in
1490 * "pcap_read_packet()".
1492 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", ebuf
);
1495 * Default value for offset to align link-layer payload
1496 * on a 4-byte boundary.
1501 * What kind of frames do we have to deal with? Fall back
1502 * to cooked mode if we have an unknown interface type.
1506 /* Assume for now we don't need cooked mode. */
1507 handle
->md
.cooked
= 0;
1509 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1510 if (arptype
== -1) {
1514 map_arphrd_to_dlt(handle
, arptype
, 1);
1515 if (handle
->linktype
== -1 ||
1516 handle
->linktype
== DLT_LINUX_SLL
||
1517 handle
->linktype
== DLT_LINUX_IRDA
||
1518 handle
->linktype
== DLT_LINUX_LAPD
||
1519 (handle
->linktype
== DLT_EN10MB
&&
1520 (strncmp("isdn", device
, 4) == 0 ||
1521 strncmp("isdY", device
, 4) == 0))) {
1523 * Unknown interface type (-1), or a
1524 * device we explicitly chose to run
1525 * in cooked mode (e.g., PPP devices),
1526 * or an ISDN device (whose link-layer
1527 * type we can only determine by using
1528 * APIs that may be different on different
1529 * kernels) - reopen in cooked mode.
1531 if (close(sock_fd
) == -1) {
1532 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1533 "close: %s", pcap_strerror(errno
));
1536 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1538 if (sock_fd
== -1) {
1539 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1540 "socket: %s", pcap_strerror(errno
));
1543 handle
->md
.cooked
= 1;
1546 * Get rid of any link-layer type list
1547 * we allocated - this only supports cooked
1550 if (handle
->dlt_list
!= NULL
) {
1551 free(handle
->dlt_list
);
1552 handle
->dlt_list
= NULL
;
1553 handle
->dlt_count
= 0;
1556 if (handle
->linktype
== -1) {
1558 * Warn that we're falling back on
1559 * cooked mode; we may want to
1560 * update "map_arphrd_to_dlt()"
1561 * to handle the new type.
1563 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1565 "supported by libpcap - "
1566 "falling back to cooked "
1570 /* IrDA capture is not a real "cooked" capture,
1571 * it's IrLAP frames, not IP packets. */
1572 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
1573 handle
->linktype
!= DLT_LINUX_LAPD
)
1574 handle
->linktype
= DLT_LINUX_SLL
;
1577 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
, ebuf
);
1578 if (handle
->md
.ifindex
== -1)
1581 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
1589 * This is cooked mode.
1591 handle
->md
.cooked
= 1;
1592 handle
->linktype
= DLT_LINUX_SLL
;
1595 * We're not bound to a device.
1596 * XXX - true? Or true only if we're using
1598 * For now, we're using this as an indication
1599 * that we can't transmit; stop doing that only
1600 * if we figure out how to transmit in cooked
1603 handle
->md
.ifindex
= -1;
1607 * Select promiscuous mode on if "promisc" is set.
1609 * Do not turn allmulti mode on if we don't select
1610 * promiscuous mode - on some devices (e.g., Orinoco
1611 * wireless interfaces), allmulti mode isn't supported
1612 * and the driver implements it by turning promiscuous
1613 * mode on, and that screws up the operation of the
1614 * card as a normal networking interface, and on no
1615 * other platform I know of does starting a non-
1616 * promiscuous capture affect which multicast packets
1617 * are received by the interface.
1621 * Hmm, how can we set promiscuous mode on all interfaces?
1622 * I am not sure if that is possible at all.
1625 if (device
&& promisc
) {
1626 memset(&mr
, 0, sizeof(mr
));
1627 mr
.mr_ifindex
= handle
->md
.ifindex
;
1628 mr
.mr_type
= PACKET_MR_PROMISC
;
1629 if (setsockopt(sock_fd
, SOL_PACKET
,
1630 PACKET_ADD_MEMBERSHIP
, &mr
, sizeof(mr
)) == -1)
1632 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1633 "setsockopt: %s", pcap_strerror(errno
));
1638 /* Save the socket FD in the pcap structure */
1640 handle
->fd
= sock_fd
;
1651 * Get rid of any link-layer type list we allocated.
1653 if (handle
->dlt_list
!= NULL
)
1654 free(handle
->dlt_list
);
1660 "New packet capturing interface not supported by build "
1661 "environment", PCAP_ERRBUF_SIZE
);
1667 live_open_mmap(pcap_t
* handle
, char* errmsg
)
1669 #ifdef HAVE_PACKET_RING
1670 /* by default request 4M for the ring buffer */
1671 int ret
= create_ring(handle
, 4*1024*1024, errmsg
);
1675 /* override some defaults and inherit the other fields from
1677 * handle->offset is used to get the current position into the rx ring
1678 * handle->cc is used to store the ring size */
1679 handle
->read_op
= pcap_read_linux_mmap
;
1680 handle
->close_op
= pcap_close_linux_mmap
;
1681 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
1682 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
1683 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
1684 handle
->selectable_fd
= handle
->fd
;
1686 #else /* HAVE_PACKET_RING */
1688 #endif /* HAVE_PACKET_RING */
1691 #ifdef HAVE_PACKET_RING
1694 compute_ring_block(int frame_size
, unsigned *block_size
, unsigned *frames_per_block
)
1696 /* compute the minumum block size that will handle this frame.
1697 * The block has to be page size aligned.
1698 * The max block size allowed by the kernel is arch-dependent and
1699 * it's not explicitly checked here. */
1700 *block_size
= getpagesize();
1701 while (*block_size
< frame_size
)
1704 *frames_per_block
= *block_size
/frame_size
;
1708 create_ring(pcap_t
* handle
, unsigned size
, char* errmsg
)
1710 unsigned i
, j
, ringsize
, frames_per_block
;
1711 struct tpacket_req req
;
1713 /* Note that with large snapshot (say 64K) only a few frames
1714 * will be available in the ring even with pretty large ring size
1715 * (and a lot of memory will be unused).
1716 * The snap len should be carefully chosen to achive best
1718 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+TPACKET_HDRLEN
);
1719 req
.tp_frame_nr
= size
/req
.tp_frame_size
;
1720 compute_ring_block(req
.tp_frame_size
, &req
.tp_block_size
, &frames_per_block
);
1721 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
1723 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
1724 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
1726 /* ask the kernel to create the ring */
1728 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1729 (void *) &req
, sizeof(req
))) {
1730 /* try to reduce requested ring size to prevent memory failure */
1731 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
1732 req
.tp_frame_nr
>>= 1;
1733 req
.tp_block_nr
= req
.tp_frame_nr
/frames_per_block
;
1736 snprintf(errmsg
, PCAP_ERRBUF_SIZE
, "can't create rx ring on "
1737 "packet socket %d: %d-%s", handle
->fd
, errno
,
1738 pcap_strerror(errno
));
1742 /* memory map the rx ring */
1743 ringsize
= req
.tp_block_nr
* req
.tp_block_size
;
1744 handle
->bp
= mmap(0, ringsize
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
1746 if (handle
->bp
== MAP_FAILED
) {
1747 snprintf(errmsg
, PCAP_ERRBUF_SIZE
, "can't mmap rx ring: %d-%s",
1748 errno
, pcap_strerror(errno
));
1750 /* clear the allocated ring on error*/
1751 destroy_ring(handle
);
1755 /* allocate a ring for each frame header pointer*/
1756 handle
->cc
= req
.tp_frame_nr
;
1757 handle
->buffer
= malloc(handle
->cc
* sizeof(struct tpacket_hdr
*));
1758 if (!handle
->buffer
) {
1759 destroy_ring(handle
);
1763 /* fill the header ring with proper frame ptr*/
1765 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
1766 u_char
*base
= &handle
->bp
[i
*req
.tp_block_size
];
1767 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
1768 RING_GET_FRAME(handle
) = (struct tpacket_hdr
*) base
;
1769 base
+= req
.tp_frame_size
;
1773 handle
->bufsize
= req
.tp_frame_size
;
1778 /* free all ring related resources*/
1780 destroy_ring(pcap_t
*handle
)
1782 /* tell the kernel to destroy the ring*/
1783 struct tpacket_req req
;
1784 memset(&req
, 0, sizeof(req
));
1785 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1786 (void *) &req
, sizeof(req
));
1788 /* if ring is mapped, unmap it*/
1790 /* need to re-compute the ring size */
1791 unsigned frames_per_block
, block_size
;
1792 compute_ring_block(handle
->bufsize
, &block_size
, &frames_per_block
);
1794 /* do not perform sanity check here: we can't recover any error */
1795 munmap(handle
->bp
, block_size
* handle
->cc
/ frames_per_block
);
1799 /* if the header ring is allocated, clear it*/
1800 if (handle
->buffer
) {
1801 free(handle
->buffer
);
1807 pcap_close_linux_mmap( pcap_t
*handle
)
1809 destroy_ring(handle
);
1810 pcap_close_linux(handle
);
1815 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
1817 /* use negative value of timeout to indicate non blocking ops */
1818 return (p
->md
.timeout
<0);
1822 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
1824 /* map each value to the corresponding 2's complement, to
1825 * preserve the timeout value provided with pcap_open_live */
1827 if (p
->md
.timeout
> 0)
1828 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
1830 if (p
->md
.timeout
< 0)
1831 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
1836 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
1841 /* wait for frames availability.*/
1842 if ((handle
->md
.timeout
>= 0) && !(RING_GET_FRAME(handle
)->tp_status
)) {
1843 struct pollfd pollinfo
;
1846 pollinfo
.fd
= handle
->fd
;
1847 pollinfo
.events
= POLLIN
;
1850 /* poll() requires a negative timeout to wait forever */
1851 ret
= poll(&pollinfo
, 1, (handle
->md
.timeout
> 0)?
1852 handle
->md
.timeout
: -1);
1853 if ((ret
< 0) && (errno
!= EINTR
)) {
1854 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1855 "can't poll on packet socket fd %d: %d-%s",
1856 handle
->fd
, errno
, pcap_strerror(errno
));
1859 /* check for break loop condition on interrupted syscall*/
1860 if (handle
->break_loop
) {
1861 handle
->break_loop
= 0;
1867 /* negative values of max_packets are used to require all
1868 * packets available in the ring */
1869 while ((pkts
< max_packets
) || (max_packets
<0)) {
1871 struct sockaddr_ll
*sll
;
1872 struct pcap_pkthdr pcaphdr
;
1874 struct tpacket_hdr
* thdr
= RING_GET_FRAME(handle
);
1875 if (thdr
->tp_status
== TP_STATUS_KERNEL
)
1878 /* perform sanity check on internal offset. */
1879 if (thdr
->tp_mac
+thdr
->tp_snaplen
> handle
->bufsize
) {
1880 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1881 "corrupted frame on kernel ring mac "
1882 "offset %d + caplen %d > frame len %d\n",
1883 thdr
->tp_mac
, thdr
->tp_snaplen
, handle
->bufsize
);
1887 /* run filter on received packet
1888 * If the kernel filtering is enabled we need to run the
1889 * filter until all the frames present into the ring
1890 * at filter creation time are processed.
1891 * In such case md.use_bpf is used as a counter for the
1892 * packet we need to filter.
1893 * Note: alternatively it could be possible to stop applying
1894 * the filter when the ring became empty, but it can possibly
1895 * happen a lot later... */
1896 bp
= (unsigned char*)thdr
+ thdr
->tp_mac
;
1897 run_bpf
= (!handle
->md
.use_bpf
) ||
1898 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
1899 if (run_bpf
&& handle
->fcode
.bf_insns
&&
1900 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1901 thdr
->tp_len
, thdr
->tp_snaplen
) == 0))
1904 /* check direction and interface index */
1905 sll
= (void*)thdr
+ TPACKET_ALIGN(sizeof(*thdr
));
1906 if ((sll
->sll_ifindex
== handle
->md
.lo_ifindex
) &&
1907 (sll
->sll_pkttype
== PACKET_OUTGOING
))
1910 /* get required packet info from ring header */
1911 pcaphdr
.ts
.tv_sec
= thdr
->tp_sec
;
1912 pcaphdr
.ts
.tv_usec
= thdr
->tp_usec
;
1913 pcaphdr
.caplen
= thdr
->tp_snaplen
;
1914 pcaphdr
.len
= thdr
->tp_len
;
1916 /* if required build in place the sll header*/
1917 if (handle
->md
.cooked
) {
1918 struct sll_header
*hdrp
= (struct sll_header
*)((char *)bp
- sizeof(struct sll_header
));
1920 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
1922 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
1923 hdrp
->sll_halen
= htons(sll
->sll_halen
);
1924 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
1925 hdrp
->sll_protocol
= sll
->sll_protocol
;
1927 /* update packet len */
1928 pcaphdr
.caplen
+= SLL_HDR_LEN
;
1929 pcaphdr
.len
+= SLL_HDR_LEN
;
1932 /* pass the packet to the user */
1934 callback(user
, &pcaphdr
, bp
);
1935 handle
->md
.packets_read
++;
1939 thdr
->tp_status
= TP_STATUS_KERNEL
;
1940 if (++handle
->offset
>= handle
->cc
)
1943 /* check for break loop condition*/
1944 if (handle
->break_loop
) {
1945 handle
->break_loop
= 0;
1953 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
1956 int ret
= pcap_setfilter_linux(handle
, filter
);
1960 /* if the kernel filter is enabled, we need to apply the filter on
1961 * all packets present into the ring. Get an upper bound of their number
1963 if (!handle
->md
.use_bpf
)
1966 /* walk the ring backward and count the free slot */
1967 offset
= handle
->offset
;
1968 if (--handle
->offset
< 0)
1969 handle
->offset
= handle
->cc
- 1;
1970 for (n
=0; n
< handle
->cc
; ++n
) {
1971 if (--handle
->offset
< 0)
1972 handle
->offset
= handle
->cc
- 1;
1973 if (RING_GET_FRAME(handle
)->tp_status
!= TP_STATUS_KERNEL
)
1977 /* be careful to not change current ring position */
1978 handle
->offset
= offset
;
1980 /* store the number of packets currently present in the ring */
1981 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
1985 #endif /* HAVE_PACKET_RING */
1988 #ifdef HAVE_PF_PACKET_SOCKETS
1990 * Return the index of the given device name. Fill ebuf and return
1994 iface_get_id(int fd
, const char *device
, char *ebuf
)
1998 memset(&ifr
, 0, sizeof(ifr
));
1999 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2001 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
2002 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2003 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
2007 return ifr
.ifr_ifindex
;
2011 * Bind the socket associated with FD to the given device.
2014 iface_bind(int fd
, int ifindex
, char *ebuf
)
2016 struct sockaddr_ll sll
;
2018 socklen_t errlen
= sizeof(err
);
2020 memset(&sll
, 0, sizeof(sll
));
2021 sll
.sll_family
= AF_PACKET
;
2022 sll
.sll_ifindex
= ifindex
;
2023 sll
.sll_protocol
= htons(ETH_P_ALL
);
2025 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
2026 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2027 "bind: %s", pcap_strerror(errno
));
2031 /* Any pending errors, e.g., network is down? */
2033 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2034 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2035 "getsockopt: %s", pcap_strerror(errno
));
2040 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2041 "bind: %s", pcap_strerror(err
));
2051 /* ===== Functions to interface to the older kernels ================== */
2054 * With older kernels promiscuous mode is kind of interesting because we
2055 * have to reset the interface before exiting. The problem can't really
2056 * be solved without some daemon taking care of managing usage counts.
2057 * If we put the interface into promiscuous mode, we set a flag indicating
2058 * that we must take it out of that mode when the interface is closed,
2059 * and, when closing the interface, if that flag is set we take it out
2060 * of promiscuous mode.
2064 * List of pcaps for which we turned promiscuous mode on by hand.
2065 * If there are any such pcaps, we arrange to call "pcap_close_all()"
2066 * when we exit, and have it close all of them to turn promiscuous mode
2069 static struct pcap
*pcaps_to_close
;
2072 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
2073 * be called on exit.
2075 static int did_atexit
;
2077 static void pcap_close_all(void)
2079 struct pcap
*handle
;
2081 while ((handle
= pcaps_to_close
) != NULL
)
2085 static void pcap_close_linux( pcap_t
*handle
)
2087 struct pcap
*p
, *prevp
;
2090 if (handle
->md
.clear_promisc
) {
2092 * We put the interface into promiscuous mode; take
2093 * it out of promiscuous mode.
2095 * XXX - if somebody else wants it in promiscuous mode,
2096 * this code cannot know that, so it'll take it out
2097 * of promiscuous mode. That's not fixable in 2.0[.x]
2100 memset(&ifr
, 0, sizeof(ifr
));
2101 strncpy(ifr
.ifr_name
, handle
->md
.device
, sizeof(ifr
.ifr_name
));
2102 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2104 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
2105 "Please adjust manually.\n"
2106 "Hint: This can't happen with Linux >= 2.2.0.\n",
2109 if (ifr
.ifr_flags
& IFF_PROMISC
) {
2111 * Promiscuous mode is currently on; turn it
2114 ifr
.ifr_flags
&= ~IFF_PROMISC
;
2115 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2117 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
2118 "Please adjust manually.\n"
2119 "Hint: This can't happen with Linux >= 2.2.0.\n",
2126 * Take this pcap out of the list of pcaps for which we
2127 * have to take the interface out of promiscuous mode.
2129 for (p
= pcaps_to_close
, prevp
= NULL
; p
!= NULL
;
2130 prevp
= p
, p
= p
->md
.next
) {
2133 * Found it. Remove it from the list.
2135 if (prevp
== NULL
) {
2137 * It was at the head of the list.
2139 pcaps_to_close
= p
->md
.next
;
2142 * It was in the middle of the list.
2144 prevp
->md
.next
= p
->md
.next
;
2151 if (handle
->md
.device
!= NULL
)
2152 free(handle
->md
.device
);
2153 handle
->md
.device
= NULL
;
2154 pcap_close_common(handle
);
2158 * Try to open a packet socket using the old kernel interface.
2159 * Returns 0 on failure.
2160 * FIXME: 0 uses to mean success (Sebastian)
2163 live_open_old(pcap_t
*handle
, const char *device
, int promisc
,
2164 int to_ms
, char *ebuf
)
2170 /* Open the socket */
2172 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
2173 if (handle
->fd
== -1) {
2174 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2175 "socket: %s", pcap_strerror(errno
));
2179 /* It worked - we are using the old interface */
2180 handle
->md
.sock_packet
= 1;
2182 /* ...which means we get the link-layer header. */
2183 handle
->md
.cooked
= 0;
2185 /* Bind to the given device */
2188 strncpy(ebuf
, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
2192 if (iface_bind_old(handle
->fd
, device
, ebuf
) == -1)
2196 * Try to get the link-layer type.
2198 arptype
= iface_get_arptype(handle
->fd
, device
, ebuf
);
2203 * Try to find the DLT_ type corresponding to that
2206 map_arphrd_to_dlt(handle
, arptype
, 0);
2207 if (handle
->linktype
== -1) {
2208 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2209 "unknown arptype %d", arptype
);
2213 /* Go to promisc mode if requested */
2216 memset(&ifr
, 0, sizeof(ifr
));
2217 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2218 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2219 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2220 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
2223 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
2225 * Promiscuous mode isn't currently on,
2226 * so turn it on, and remember that
2227 * we should turn it off when the
2232 * If we haven't already done so, arrange
2233 * to have "pcap_close_all()" called when
2237 if (atexit(pcap_close_all
) == -1) {
2239 * "atexit()" failed; don't
2240 * put the interface in
2241 * promiscuous mode, just
2244 strncpy(ebuf
, "atexit failed",
2251 ifr
.ifr_flags
|= IFF_PROMISC
;
2252 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2253 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2255 pcap_strerror(errno
));
2258 handle
->md
.clear_promisc
= 1;
2261 * Add this to the list of pcaps
2262 * to close when we exit.
2264 handle
->md
.next
= pcaps_to_close
;
2265 pcaps_to_close
= handle
;
2270 * Default value for offset to align link-layer payload
2271 * on a 4-byte boundary.
2279 pcap_close_linux(handle
);
2284 * Bind the socket associated with FD to the given device using the
2285 * interface of the old kernels.
2288 iface_bind_old(int fd
, const char *device
, char *ebuf
)
2290 struct sockaddr saddr
;
2292 socklen_t errlen
= sizeof(err
);
2294 memset(&saddr
, 0, sizeof(saddr
));
2295 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
2296 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
2297 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2298 "bind: %s", pcap_strerror(errno
));
2302 /* Any pending errors, e.g., network is down? */
2304 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2305 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2306 "getsockopt: %s", pcap_strerror(errno
));
2311 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2312 "bind: %s", pcap_strerror(err
));
2320 /* ===== System calls available on all supported kernels ============== */
2323 * Query the kernel for the MTU of the given interface.
2326 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
2331 return BIGGER_THAN_ALL_MTUS
;
2333 memset(&ifr
, 0, sizeof(ifr
));
2334 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2336 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
2337 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2338 "SIOCGIFMTU: %s", pcap_strerror(errno
));
2346 * Get the hardware type of the given interface as ARPHRD_xxx constant.
2349 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
2353 memset(&ifr
, 0, sizeof(ifr
));
2354 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2356 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
2357 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2358 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
2362 return ifr
.ifr_hwaddr
.sa_family
;
2365 #ifdef SO_ATTACH_FILTER
2367 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
2371 register struct bpf_insn
*p
;
2376 * Make a copy of the filter, and modify that copy if
2379 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
2380 len
= handle
->fcode
.bf_len
;
2381 f
= (struct bpf_insn
*)malloc(prog_size
);
2383 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2384 "malloc: %s", pcap_strerror(errno
));
2387 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
2389 fcode
->filter
= (struct sock_filter
*) f
;
2391 for (i
= 0; i
< len
; ++i
) {
2394 * What type of instruction is this?
2396 switch (BPF_CLASS(p
->code
)) {
2400 * It's a return instruction; is the snapshot
2401 * length a constant, rather than the contents
2402 * of the accumulator?
2404 if (BPF_MODE(p
->code
) == BPF_K
) {
2406 * Yes - if the value to be returned,
2407 * i.e. the snapshot length, is anything
2408 * other than 0, make it 65535, so that
2409 * the packet is truncated by "recvfrom()",
2410 * not by the filter.
2412 * XXX - there's nothing we can easily do
2413 * if it's getting the value from the
2414 * accumulator; we'd have to insert
2415 * code to force non-zero values to be
2426 * It's a load instruction; is it loading
2429 switch (BPF_MODE(p
->code
)) {
2435 * Yes; are we in cooked mode?
2437 if (handle
->md
.cooked
) {
2439 * Yes, so we need to fix this
2442 if (fix_offset(p
) < 0) {
2444 * We failed to do so.
2445 * Return 0, so our caller
2446 * knows to punt to userland.
2456 return 1; /* we succeeded */
2460 fix_offset(struct bpf_insn
*p
)
2463 * What's the offset?
2465 if (p
->k
>= SLL_HDR_LEN
) {
2467 * It's within the link-layer payload; that starts at an
2468 * offset of 0, as far as the kernel packet filter is
2469 * concerned, so subtract the length of the link-layer
2472 p
->k
-= SLL_HDR_LEN
;
2473 } else if (p
->k
== 14) {
2475 * It's the protocol field; map it to the special magic
2476 * kernel offset for that field.
2478 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
2481 * It's within the header, but it's not one of those
2482 * fields; we can't do that in the kernel, so punt
2491 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
2493 int total_filter_on
= 0;
2499 * The socket filter code doesn't discard all packets queued
2500 * up on the socket when the filter is changed; this means
2501 * that packets that don't match the new filter may show up
2502 * after the new filter is put onto the socket, if those
2503 * packets haven't yet been read.
2505 * This means, for example, that if you do a tcpdump capture
2506 * with a filter, the first few packets in the capture might
2507 * be packets that wouldn't have passed the filter.
2509 * We therefore discard all packets queued up on the socket
2510 * when setting a kernel filter. (This isn't an issue for
2511 * userland filters, as the userland filtering is done after
2512 * packets are queued up.)
2514 * To flush those packets, we put the socket in read-only mode,
2515 * and read packets from the socket until there are no more to
2518 * In order to keep that from being an infinite loop - i.e.,
2519 * to keep more packets from arriving while we're draining
2520 * the queue - we put the "total filter", which is a filter
2521 * that rejects all packets, onto the socket before draining
2524 * This code deliberately ignores any errors, so that you may
2525 * get bogus packets if an error occurs, rather than having
2526 * the filtering done in userland even if it could have been
2527 * done in the kernel.
2529 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2530 &total_fcode
, sizeof(total_fcode
)) == 0) {
2534 * Note that we've put the total filter onto the socket.
2536 total_filter_on
= 1;
2539 * Save the socket's current mode, and put it in
2540 * non-blocking mode; we drain it by reading packets
2541 * until we get an error (which is normally a
2542 * "nothing more to be read" error).
2544 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
2545 if (save_mode
!= -1 &&
2546 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
2547 while (recv(handle
->fd
, &drain
, sizeof drain
,
2551 fcntl(handle
->fd
, F_SETFL
, save_mode
);
2552 if (save_errno
!= EAGAIN
) {
2554 reset_kernel_filter(handle
);
2555 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2556 "recv: %s", pcap_strerror(save_errno
));
2563 * Now attach the new filter.
2565 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2566 fcode
, sizeof(*fcode
));
2567 if (ret
== -1 && total_filter_on
) {
2569 * Well, we couldn't set that filter on the socket,
2570 * but we could set the total filter on the socket.
2572 * This could, for example, mean that the filter was
2573 * too big to put into the kernel, so we'll have to
2574 * filter in userland; in any case, we'll be doing
2575 * filtering in userland, so we need to remove the
2576 * total filter so we see packets.
2581 * XXX - if this fails, we're really screwed;
2582 * we have the total filter on the socket,
2583 * and it won't come off. What do we do then?
2585 reset_kernel_filter(handle
);
2593 reset_kernel_filter(pcap_t
*handle
)
2596 * setsockopt() barfs unless it get a dummy parameter.
2597 * valgrind whines unless the value is initialized,
2598 * as it has no idea that setsockopt() ignores its
2603 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
2604 &dummy
, sizeof(dummy
));