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.136 2008-02-02 21:27:28 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 #ifdef HAVE_PF_PACKET_SOCKETS
217 static short int map_packet_type_to_sll_type(short int);
219 static int live_open_old(pcap_t
*, const char *, int, int, char *);
220 static int live_open_new(pcap_t
*, const char *, int, int, char *);
221 static int live_open_mmap(pcap_t
*, char *);
222 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
223 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
224 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
225 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
226 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
227 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
228 static void pcap_close_linux(pcap_t
*);
230 #ifdef HAVE_PACKET_RING
231 #define RING_GET_FRAME(h) (((struct tpacket_hdr**)h->buffer)[h->offset])
233 static void destroy_ring(pcap_t
*handle
);
234 static int create_ring(pcap_t
* handle
, unsigned size
, char* errmsg
);
235 static void pcap_close_linux_mmap(pcap_t
*);
236 static int pcap_read_linux_mmap(pcap_t
*, int, pcap_handler
, u_char
*);
237 static int pcap_setfilter_linux_mmap(pcap_t
*, struct bpf_program
*);
238 static int pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
);
239 static int pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
);
243 * Wrap some ioctl calls
245 #ifdef HAVE_PF_PACKET_SOCKETS
246 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
248 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
249 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
250 #ifdef HAVE_PF_PACKET_SOCKETS
251 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
253 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
255 #ifdef SO_ATTACH_FILTER
256 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
257 static int fix_offset(struct bpf_insn
*p
);
258 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
259 static int reset_kernel_filter(pcap_t
*handle
);
261 static struct sock_filter total_insn
262 = BPF_STMT(BPF_RET
| BPF_K
, 0);
263 static struct sock_fprog total_fcode
264 = { 1, &total_insn
};
268 * Get a handle for a live capture from the given device. You can
269 * pass NULL as device to get all packages (without link level
270 * information of course). If you pass 1 as promisc the interface
271 * will be set to promiscous mode (XXX: I think this usage should
272 * be deprecated and functions be added to select that later allow
273 * modification of that values -- Torsten).
278 pcap_open_live(const char *device
, int snaplen
, int promisc
, int to_ms
,
283 int live_open_ok
= 0;
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
);
391 /* Allocate the buffer */
393 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
394 if (!handle
->buffer
) {
395 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
396 "malloc: %s", pcap_strerror(errno
));
397 pcap_close_linux(handle
);
403 * "handle->fd" is a socket, so "select()" and "poll()"
406 handle
->selectable_fd
= handle
->fd
;
412 * Read at most max_packets from the capture stream and call the callback
413 * for each of them. Returns the number of packets handled or -1 if an
417 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
420 * Currently, on Linux only one packet is delivered per read,
423 return pcap_read_packet(handle
, callback
, user
);
427 * Read a packet from the socket calling the handler provided by
428 * the user. Returns the number of packets received or -1 if an
432 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
436 #ifdef HAVE_PF_PACKET_SOCKETS
437 struct sockaddr_ll from
;
438 struct sll_header
*hdrp
;
440 struct sockaddr from
;
443 int packet_len
, caplen
;
444 struct pcap_pkthdr pcap_header
;
446 #ifdef HAVE_PF_PACKET_SOCKETS
448 * If this is a cooked device, leave extra room for a
449 * fake packet header.
451 if (handle
->md
.cooked
)
452 offset
= SLL_HDR_LEN
;
457 * This system doesn't have PF_PACKET sockets, so it doesn't
458 * support cooked devices.
463 /* Receive a single packet from the kernel */
465 bp
= handle
->buffer
+ handle
->offset
;
468 * Has "pcap_breakloop()" been called?
470 if (handle
->break_loop
) {
472 * Yes - clear the flag that indicates that it
473 * has, and return -2 as an indication that we
474 * were told to break out of the loop.
476 handle
->break_loop
= 0;
479 fromlen
= sizeof(from
);
480 packet_len
= recvfrom(
481 handle
->fd
, bp
+ offset
,
482 handle
->bufsize
- offset
, MSG_TRUNC
,
483 (struct sockaddr
*) &from
, &fromlen
);
484 } while (packet_len
== -1 && errno
== EINTR
);
486 /* Check if an error occured */
488 if (packet_len
== -1) {
490 return 0; /* no packet there */
492 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
493 "recvfrom: %s", pcap_strerror(errno
));
498 #ifdef HAVE_PF_PACKET_SOCKETS
499 if (!handle
->md
.sock_packet
) {
501 * Unfortunately, there is a window between socket() and
502 * bind() where the kernel may queue packets from any
503 * interface. If we're bound to a particular interface,
504 * discard packets not from that interface.
506 * (If socket filters are supported, we could do the
507 * same thing we do when changing the filter; however,
508 * that won't handle packet sockets without socket
509 * filter support, and it's a bit more complicated.
510 * It would save some instructions per packet, however.)
512 if (handle
->md
.ifindex
!= -1 &&
513 from
.sll_ifindex
!= handle
->md
.ifindex
)
517 * Do checks based on packet direction.
518 * We can only do this if we're using PF_PACKET; the
519 * address returned for SOCK_PACKET is a "sockaddr_pkt"
520 * which lacks the relevant packet type information.
522 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
525 * If this is from the loopback device, reject it;
526 * we'll see the packet as an incoming packet as well,
527 * and we don't want to see it twice.
529 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
533 * If the user only wants incoming packets, reject it.
535 if (handle
->direction
== PCAP_D_IN
)
540 * If the user only wants outgoing packets, reject it.
542 if (handle
->direction
== PCAP_D_OUT
)
548 #ifdef HAVE_PF_PACKET_SOCKETS
550 * If this is a cooked device, fill in the fake packet header.
552 if (handle
->md
.cooked
) {
554 * Add the length of the fake header to the length
555 * of packet data we read.
557 packet_len
+= SLL_HDR_LEN
;
559 hdrp
= (struct sll_header
*)bp
;
560 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(from
.sll_pkttype
);
561 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
562 hdrp
->sll_halen
= htons(from
.sll_halen
);
563 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
564 (from
.sll_halen
> SLL_ADDRLEN
) ?
567 hdrp
->sll_protocol
= from
.sll_protocol
;
572 * XXX: According to the kernel source we should get the real
573 * packet len if calling recvfrom with MSG_TRUNC set. It does
574 * not seem to work here :(, but it is supported by this code
576 * To be honest the code RELIES on that feature so this is really
577 * broken with 2.2.x kernels.
578 * I spend a day to figure out what's going on and I found out
579 * that the following is happening:
581 * The packet comes from a random interface and the packet_rcv
582 * hook is called with a clone of the packet. That code inserts
583 * the packet into the receive queue of the packet socket.
584 * If a filter is attached to that socket that filter is run
585 * first - and there lies the problem. The default filter always
586 * cuts the packet at the snaplen:
591 * So the packet filter cuts down the packet. The recvfrom call
592 * says "hey, it's only 68 bytes, it fits into the buffer" with
593 * the result that we don't get the real packet length. This
594 * is valid at least until kernel 2.2.17pre6.
596 * We currently handle this by making a copy of the filter
597 * program, fixing all "ret" instructions with non-zero
598 * operands to have an operand of 65535 so that the filter
599 * doesn't truncate the packet, and supplying that modified
600 * filter to the kernel.
604 if (caplen
> handle
->snapshot
)
605 caplen
= handle
->snapshot
;
607 /* Run the packet filter if not using kernel filter */
608 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
609 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
610 packet_len
, caplen
) == 0)
612 /* rejected by filter */
617 /* Fill in our own header data */
619 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
620 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
621 "SIOCGSTAMP: %s", pcap_strerror(errno
));
624 pcap_header
.caplen
= caplen
;
625 pcap_header
.len
= packet_len
;
630 * Arguably, we should count them before we check the filter,
631 * as on many other platforms "ps_recv" counts packets
632 * handed to the filter rather than packets that passed
633 * the filter, but if filtering is done in the kernel, we
634 * can't get a count of packets that passed the filter,
635 * and that would mean the meaning of "ps_recv" wouldn't
636 * be the same on all Linux systems.
638 * XXX - it's not the same on all systems in any case;
639 * ideally, we should have a "get the statistics" call
640 * that supplies more counts and indicates which of them
641 * it supplies, so that we supply a count of packets
642 * handed to the filter only on platforms where that
643 * information is available.
645 * We count them here even if we can get the packet count
646 * from the kernel, as we can only determine at run time
647 * whether we'll be able to get it from the kernel (if
648 * HAVE_TPACKET_STATS isn't defined, we can't get it from
649 * the kernel, but if it is defined, the library might
650 * have been built with a 2.4 or later kernel, but we
651 * might be running on a 2.2[.x] kernel without Alexey
652 * Kuznetzov's turbopacket patches, and thus the kernel
653 * might not be able to supply those statistics). We
654 * could, I guess, try, when opening the socket, to get
655 * the statistics, and if we can not increment the count
656 * here, but it's not clear that always incrementing
657 * the count is more expensive than always testing a flag
660 * We keep the count in "md.packets_read", and use that for
661 * "ps_recv" if we can't get the statistics from the kernel.
662 * We do that because, if we *can* get the statistics from
663 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
664 * as running counts, as reading the statistics from the
665 * kernel resets the kernel statistics, and if we directly
666 * increment "md.stat.ps_recv" here, that means it will
667 * count packets *twice* on systems where we can get kernel
668 * statistics - once here, and once in pcap_stats_linux().
670 handle
->md
.packets_read
++;
672 /* Call the user supplied callback function */
673 callback(userdata
, &pcap_header
, bp
);
679 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
683 #ifdef HAVE_PF_PACKET_SOCKETS
684 if (!handle
->md
.sock_packet
) {
685 /* PF_PACKET socket */
686 if (handle
->md
.ifindex
== -1) {
688 * We don't support sending on the "any" device.
690 strlcpy(handle
->errbuf
,
691 "Sending packets isn't supported on the \"any\" device",
696 if (handle
->md
.cooked
) {
698 * We don't support sending on the "any" device.
700 * XXX - how do you send on a bound cooked-mode
702 * Is a "sendto()" required there?
704 strlcpy(handle
->errbuf
,
705 "Sending packets isn't supported in cooked mode",
712 ret
= send(handle
->fd
, buf
, size
, 0);
714 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
715 pcap_strerror(errno
));
722 * Get the statistics for the given packet capture handle.
723 * Reports the number of dropped packets iff the kernel supports
724 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
725 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
726 * patches); otherwise, that information isn't available, and we lie
727 * and report 0 as the count of dropped packets.
730 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
732 #ifdef HAVE_TPACKET_STATS
733 struct tpacket_stats kstats
;
734 socklen_t len
= sizeof (struct tpacket_stats
);
737 #ifdef HAVE_TPACKET_STATS
739 * Try to get the packet counts from the kernel.
741 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
742 &kstats
, &len
) > -1) {
744 * On systems where the PACKET_STATISTICS "getsockopt()"
745 * argument is supported on PF_PACKET sockets:
747 * "ps_recv" counts only packets that *passed* the
748 * filter, not packets that didn't pass the filter.
749 * This includes packets later dropped because we
750 * ran out of buffer space.
752 * "ps_drop" counts packets dropped because we ran
753 * out of buffer space. It doesn't count packets
754 * dropped by the interface driver. It counts only
755 * packets that passed the filter.
757 * Both statistics include packets not yet read from
758 * the kernel by libpcap, and thus not yet seen by
761 * In "linux/net/packet/af_packet.c", at least in the
762 * 2.4.9 kernel, "tp_packets" is incremented for every
763 * packet that passes the packet filter *and* is
764 * successfully queued on the socket; "tp_drops" is
765 * incremented for every packet dropped because there's
766 * not enough free space in the socket buffer.
768 * When the statistics are returned for a PACKET_STATISTICS
769 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
770 * so that "tp_packets" counts all packets handed to
771 * the PF_PACKET socket, including packets dropped because
772 * there wasn't room on the socket buffer - but not
773 * including packets that didn't pass the filter.
775 * In the BSD BPF, the count of received packets is
776 * incremented for every packet handed to BPF, regardless
777 * of whether it passed the filter.
779 * We can't make "pcap_stats()" work the same on both
780 * platforms, but the best approximation is to return
781 * "tp_packets" as the count of packets and "tp_drops"
782 * as the count of drops.
784 * Keep a running total because each call to
785 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
786 * resets the counters to zero.
788 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
789 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
790 *stats
= handle
->md
.stat
;
796 * If the error was EOPNOTSUPP, fall through, so that
797 * if you build the library on a system with
798 * "struct tpacket_stats" and run it on a system
799 * that doesn't, it works as it does if the library
800 * is built on a system without "struct tpacket_stats".
802 if (errno
!= EOPNOTSUPP
) {
803 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
804 "pcap_stats: %s", pcap_strerror(errno
));
810 * On systems where the PACKET_STATISTICS "getsockopt()" argument
811 * is not supported on PF_PACKET sockets:
813 * "ps_recv" counts only packets that *passed* the filter,
814 * not packets that didn't pass the filter. It does not
815 * count packets dropped because we ran out of buffer
818 * "ps_drop" is not supported.
820 * "ps_recv" doesn't include packets not yet read from
821 * the kernel by libpcap.
823 * We maintain the count of packets processed by libpcap in
824 * "md.packets_read", for reasons described in the comment
825 * at the end of pcap_read_packet(). We have no idea how many
826 * packets were dropped.
828 stats
->ps_recv
= handle
->md
.packets_read
;
834 * Description string for the "any" device.
836 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
839 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
841 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
845 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
847 #endif /* HAVE_DAG_API */
849 #ifdef HAVE_SEPTEL_API
850 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
852 #endif /* HAVE_SEPTEL_API */
854 #ifdef PCAP_SUPPORT_BT
855 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
859 #ifdef PCAP_SUPPORT_USB
860 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
868 * Attach the given BPF code to the packet capture device.
871 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
873 #ifdef SO_ATTACH_FILTER
874 struct sock_fprog fcode
;
875 int can_filter_in_kernel
;
882 strncpy(handle
->errbuf
, "setfilter: No filter specified",
883 sizeof(handle
->errbuf
));
887 /* Make our private copy of the filter */
889 if (install_bpf_program(handle
, filter
) < 0)
890 /* install_bpf_program() filled in errbuf */
894 * Run user level packet filter by default. Will be overriden if
895 * installing a kernel filter succeeds.
897 handle
->md
.use_bpf
= 0;
899 /* Install kernel level filter if possible */
901 #ifdef SO_ATTACH_FILTER
903 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
905 * fcode.len is an unsigned short for current kernel.
906 * I have yet to see BPF-Code with that much
907 * instructions but still it is possible. So for the
908 * sake of correctness I added this check.
910 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
913 can_filter_in_kernel
= 0;
915 #endif /* USHRT_MAX */
918 * Oh joy, the Linux kernel uses struct sock_fprog instead
919 * of struct bpf_program and of course the length field is
920 * of different size. Pointed out by Sebastian
922 * Oh, and we also need to fix it up so that all "ret"
923 * instructions with non-zero operands have 65535 as the
924 * operand, and so that, if we're in cooked mode, all
925 * memory-reference instructions use special magic offsets
926 * in references to the link-layer header and assume that
927 * the link-layer payload begins at 0; "fix_program()"
930 switch (fix_program(handle
, &fcode
)) {
935 * Fatal error; just quit.
936 * (The "default" case shouldn't happen; we
937 * return -1 for that reason.)
943 * The program performed checks that we can't make
944 * work in the kernel.
946 can_filter_in_kernel
= 0;
951 * We have a filter that'll work in the kernel.
953 can_filter_in_kernel
= 1;
958 if (can_filter_in_kernel
) {
959 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
961 /* Installation succeded - using kernel filter. */
962 handle
->md
.use_bpf
= 1;
964 else if (err
== -1) /* Non-fatal error */
967 * Print a warning if we weren't able to install
968 * the filter for a reason other than "this kernel
969 * isn't configured to support socket filters.
971 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
973 "Warning: Kernel filter failed: %s\n",
974 pcap_strerror(errno
));
980 * If we're not using the kernel filter, get rid of any kernel
981 * filter that might've been there before, e.g. because the
982 * previous filter could work in the kernel, or because some other
983 * code attached a filter to the socket by some means other than
984 * calling "pcap_setfilter()". Otherwise, the kernel filter may
985 * filter out packets that would pass the new userland filter.
987 if (!handle
->md
.use_bpf
)
988 reset_kernel_filter(handle
);
991 * Free up the copy of the filter that was made by "fix_program()".
993 if (fcode
.filter
!= NULL
)
999 #endif /* SO_ATTACH_FILTER */
1005 * Set direction flag: Which packets do we accept on a forwarding
1006 * single device? IN, OUT or both?
1009 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1011 #ifdef HAVE_PF_PACKET_SOCKETS
1012 if (!handle
->md
.sock_packet
) {
1013 handle
->direction
= d
;
1018 * We're not using PF_PACKET sockets, so we can't determine
1019 * the direction of the packet.
1021 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1022 "Setting direction is not supported on SOCK_PACKET sockets");
1027 #ifdef HAVE_PF_PACKET_SOCKETS
1029 * Map the PACKET_ value to a LINUX_SLL_ value; we
1030 * want the same numerical value to be used in
1031 * the link-layer header even if the numerical values
1032 * for the PACKET_ #defines change, so that programs
1033 * that look at the packet type field will always be
1034 * able to handle DLT_LINUX_SLL captures.
1037 map_packet_type_to_sll_type(short int sll_pkttype
)
1039 switch (sll_pkttype
) {
1042 return htons(LINUX_SLL_HOST
);
1044 case PACKET_BROADCAST
:
1045 return htons(LINUX_SLL_BROADCAST
);
1047 case PACKET_MULTICAST
:
1048 return htons(LINUX_SLL_MULTICAST
);
1050 case PACKET_OTHERHOST
:
1051 return htons(LINUX_SLL_OTHERHOST
);
1053 case PACKET_OUTGOING
:
1054 return htons(LINUX_SLL_OUTGOING
);
1063 * Linux uses the ARP hardware type to identify the type of an
1064 * interface. pcap uses the DLT_xxx constants for this. This
1065 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1066 * constant, as arguments, and sets "handle->linktype" to the
1067 * appropriate DLT_XXX constant and sets "handle->offset" to
1068 * the appropriate value (to make "handle->offset" plus link-layer
1069 * header length be a multiple of 4, so that the link-layer payload
1070 * will be aligned on a 4-byte boundary when capturing packets).
1071 * (If the offset isn't set here, it'll be 0; add code as appropriate
1072 * for cases where it shouldn't be 0.)
1074 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1075 * in cooked mode; otherwise, we can't use cooked mode, so we have
1076 * to pick some type that works in raw mode, or fail.
1078 * Sets the link type to -1 if unable to map the type.
1080 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1086 * This is (presumably) a real Ethernet capture; give it a
1087 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1088 * that an application can let you choose it, in case you're
1089 * capturing DOCSIS traffic that a Cisco Cable Modem
1090 * Termination System is putting out onto an Ethernet (it
1091 * doesn't put an Ethernet header onto the wire, it puts raw
1092 * DOCSIS frames out on the wire inside the low-level
1093 * Ethernet framing).
1095 * XXX - are there any sorts of "fake Ethernet" that have
1096 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1097 * a Cisco CMTS won't put traffic onto it or get traffic
1098 * bridged onto it? ISDN is handled in "live_open_new()",
1099 * as we fall back on cooked mode there; are there any
1102 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1104 * If that fails, just leave the list empty.
1106 if (handle
->dlt_list
!= NULL
) {
1107 handle
->dlt_list
[0] = DLT_EN10MB
;
1108 handle
->dlt_list
[1] = DLT_DOCSIS
;
1109 handle
->dlt_count
= 2;
1113 case ARPHRD_METRICOM
:
1114 case ARPHRD_LOOPBACK
:
1115 handle
->linktype
= DLT_EN10MB
;
1120 handle
->linktype
= DLT_EN3MB
;
1124 handle
->linktype
= DLT_AX25_KISS
;
1128 handle
->linktype
= DLT_PRONET
;
1132 handle
->linktype
= DLT_CHAOS
;
1135 #ifndef ARPHRD_IEEE802_TR
1136 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1138 case ARPHRD_IEEE802_TR
:
1139 case ARPHRD_IEEE802
:
1140 handle
->linktype
= DLT_IEEE802
;
1145 handle
->linktype
= DLT_ARCNET_LINUX
;
1148 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1149 #define ARPHRD_FDDI 774
1152 handle
->linktype
= DLT_FDDI
;
1156 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1157 #define ARPHRD_ATM 19
1161 * The Classical IP implementation in ATM for Linux
1162 * supports both what RFC 1483 calls "LLC Encapsulation",
1163 * in which each packet has an LLC header, possibly
1164 * with a SNAP header as well, prepended to it, and
1165 * what RFC 1483 calls "VC Based Multiplexing", in which
1166 * different virtual circuits carry different network
1167 * layer protocols, and no header is prepended to packets.
1169 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1170 * you can't use the ARPHRD_ type to find out whether
1171 * captured packets will have an LLC header, and,
1172 * while there's a socket ioctl to *set* the encapsulation
1173 * type, there's no ioctl to *get* the encapsulation type.
1177 * programs that dissect Linux Classical IP frames
1178 * would have to check for an LLC header and,
1179 * depending on whether they see one or not, dissect
1180 * the frame as LLC-encapsulated or as raw IP (I
1181 * don't know whether there's any traffic other than
1182 * IP that would show up on the socket, or whether
1183 * there's any support for IPv6 in the Linux
1184 * Classical IP code);
1186 * filter expressions would have to compile into
1187 * code that checks for an LLC header and does
1190 * Both of those are a nuisance - and, at least on systems
1191 * that support PF_PACKET sockets, we don't have to put
1192 * up with those nuisances; instead, we can just capture
1193 * in cooked mode. That's what we'll do, if we can.
1194 * Otherwise, we'll just fail.
1197 handle
->linktype
= DLT_LINUX_SLL
;
1199 handle
->linktype
= -1;
1202 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1203 #define ARPHRD_IEEE80211 801
1205 case ARPHRD_IEEE80211
:
1206 handle
->linktype
= DLT_IEEE802_11
;
1209 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1210 #define ARPHRD_IEEE80211_PRISM 802
1212 case ARPHRD_IEEE80211_PRISM
:
1213 handle
->linktype
= DLT_PRISM_HEADER
;
1216 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1217 #define ARPHRD_IEEE80211_RADIOTAP 803
1219 case ARPHRD_IEEE80211_RADIOTAP
:
1220 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1225 * Some PPP code in the kernel supplies no link-layer
1226 * header whatsoever to PF_PACKET sockets; other PPP
1227 * code supplies PPP link-layer headers ("syncppp.c");
1228 * some PPP code might supply random link-layer
1229 * headers (PPP over ISDN - there's code in Ethereal,
1230 * for example, to cope with PPP-over-ISDN captures
1231 * with which the Ethereal developers have had to cope,
1232 * heuristically trying to determine which of the
1233 * oddball link-layer headers particular packets have).
1235 * As such, we just punt, and run all PPP interfaces
1236 * in cooked mode, if we can; otherwise, we just treat
1237 * it as DLT_RAW, for now - if somebody needs to capture,
1238 * on a 2.0[.x] kernel, on PPP devices that supply a
1239 * link-layer header, they'll have to add code here to
1240 * map to the appropriate DLT_ type (possibly adding a
1241 * new DLT_ type, if necessary).
1244 handle
->linktype
= DLT_LINUX_SLL
;
1247 * XXX - handle ISDN types here? We can't fall
1248 * back on cooked sockets, so we'd have to
1249 * figure out from the device name what type of
1250 * link-layer encapsulation it's using, and map
1251 * that to an appropriate DLT_ value, meaning
1252 * we'd map "isdnN" devices to DLT_RAW (they
1253 * supply raw IP packets with no link-layer
1254 * header) and "isdY" devices to a new DLT_I4L_IP
1255 * type that has only an Ethernet packet type as
1256 * a link-layer header.
1258 * But sometimes we seem to get random crap
1259 * in the link-layer header when capturing on
1262 handle
->linktype
= DLT_RAW
;
1266 #ifndef ARPHRD_CISCO
1267 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1270 handle
->linktype
= DLT_C_HDLC
;
1273 /* Not sure if this is correct for all tunnels, but it
1277 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1285 #ifndef ARPHRD_RAWHDLC
1286 #define ARPHRD_RAWHDLC 518
1288 case ARPHRD_RAWHDLC
:
1290 #define ARPHRD_DLCI 15
1294 * XXX - should some of those be mapped to DLT_LINUX_SLL
1295 * instead? Should we just map all of them to DLT_LINUX_SLL?
1297 handle
->linktype
= DLT_RAW
;
1301 #define ARPHRD_FRAD 770
1304 handle
->linktype
= DLT_FRELAY
;
1307 case ARPHRD_LOCALTLK
:
1308 handle
->linktype
= DLT_LTALK
;
1312 #define ARPHRD_FCPP 784
1316 #define ARPHRD_FCAL 785
1320 #define ARPHRD_FCPL 786
1323 #ifndef ARPHRD_FCFABRIC
1324 #define ARPHRD_FCFABRIC 787
1326 case ARPHRD_FCFABRIC
:
1328 * We assume that those all mean RFC 2625 IP-over-
1329 * Fibre Channel, with the RFC 2625 header at
1330 * the beginning of the packet.
1332 handle
->linktype
= DLT_IP_OVER_FC
;
1336 #define ARPHRD_IRDA 783
1339 /* Don't expect IP packet out of this interfaces... */
1340 handle
->linktype
= DLT_LINUX_IRDA
;
1341 /* We need to save packet direction for IrDA decoding,
1342 * so let's use "Linux-cooked" mode. Jean II */
1343 //handle->md.cooked = 1;
1346 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1347 * is needed, please report it to <daniele@orlandi.com> */
1349 #define ARPHRD_LAPD 8445
1352 /* Don't expect IP packet out of this interfaces... */
1353 handle
->linktype
= DLT_LINUX_LAPD
;
1357 handle
->linktype
= -1;
1362 /* ===== Functions to interface to the newer kernels ================== */
1365 * Try to open a packet socket using the new kernel interface.
1366 * Returns 0 on failure.
1367 * FIXME: 0 uses to mean success (Sebastian)
1370 live_open_new(pcap_t
*handle
, const char *device
, int promisc
,
1371 int to_ms
, char *ebuf
)
1373 #ifdef HAVE_PF_PACKET_SOCKETS
1374 int sock_fd
= -1, arptype
;
1377 struct packet_mreq mr
;
1379 /* One shot loop used for error handling - bail out with break */
1383 * Open a socket with protocol family packet. If a device is
1384 * given we try to open it in raw mode otherwise we use
1385 * the cooked interface.
1388 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
1389 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
1391 if (sock_fd
== -1) {
1392 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
1393 pcap_strerror(errno
) );
1397 /* It seems the kernel supports the new interface. */
1398 handle
->md
.sock_packet
= 0;
1401 * Get the interface index of the loopback device.
1402 * If the attempt fails, don't fail, just set the
1403 * "md.lo_ifindex" to -1.
1405 * XXX - can there be more than one device that loops
1406 * packets back, i.e. devices other than "lo"? If so,
1407 * we'd need to find them all, and have an array of
1408 * indices for them, and check all of them in
1409 * "pcap_read_packet()".
1411 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", ebuf
);
1414 * Default value for offset to align link-layer payload
1415 * on a 4-byte boundary.
1420 * What kind of frames do we have to deal with? Fall back
1421 * to cooked mode if we have an unknown interface type.
1425 /* Assume for now we don't need cooked mode. */
1426 handle
->md
.cooked
= 0;
1428 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1429 if (arptype
== -1) {
1433 map_arphrd_to_dlt(handle
, arptype
, 1);
1434 if (handle
->linktype
== -1 ||
1435 handle
->linktype
== DLT_LINUX_SLL
||
1436 handle
->linktype
== DLT_LINUX_IRDA
||
1437 handle
->linktype
== DLT_LINUX_LAPD
||
1438 (handle
->linktype
== DLT_EN10MB
&&
1439 (strncmp("isdn", device
, 4) == 0 ||
1440 strncmp("isdY", device
, 4) == 0))) {
1442 * Unknown interface type (-1), or a
1443 * device we explicitly chose to run
1444 * in cooked mode (e.g., PPP devices),
1445 * or an ISDN device (whose link-layer
1446 * type we can only determine by using
1447 * APIs that may be different on different
1448 * kernels) - reopen in cooked mode.
1450 if (close(sock_fd
) == -1) {
1451 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1452 "close: %s", pcap_strerror(errno
));
1455 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1457 if (sock_fd
== -1) {
1458 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1459 "socket: %s", pcap_strerror(errno
));
1462 handle
->md
.cooked
= 1;
1465 * Get rid of any link-layer type list
1466 * we allocated - this only supports cooked
1469 if (handle
->dlt_list
!= NULL
) {
1470 free(handle
->dlt_list
);
1471 handle
->dlt_list
= NULL
;
1472 handle
->dlt_count
= 0;
1475 if (handle
->linktype
== -1) {
1477 * Warn that we're falling back on
1478 * cooked mode; we may want to
1479 * update "map_arphrd_to_dlt()"
1480 * to handle the new type.
1482 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1484 "supported by libpcap - "
1485 "falling back to cooked "
1489 /* IrDA capture is not a real "cooked" capture,
1490 * it's IrLAP frames, not IP packets. */
1491 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
1492 handle
->linktype
!= DLT_LINUX_LAPD
)
1493 handle
->linktype
= DLT_LINUX_SLL
;
1496 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
, ebuf
);
1497 if (handle
->md
.ifindex
== -1)
1500 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
1508 * This is cooked mode.
1510 handle
->md
.cooked
= 1;
1511 handle
->linktype
= DLT_LINUX_SLL
;
1514 * We're not bound to a device.
1515 * XXX - true? Or true only if we're using
1517 * For now, we're using this as an indication
1518 * that we can't transmit; stop doing that only
1519 * if we figure out how to transmit in cooked
1522 handle
->md
.ifindex
= -1;
1526 * Select promiscuous mode on if "promisc" is set.
1528 * Do not turn allmulti mode on if we don't select
1529 * promiscuous mode - on some devices (e.g., Orinoco
1530 * wireless interfaces), allmulti mode isn't supported
1531 * and the driver implements it by turning promiscuous
1532 * mode on, and that screws up the operation of the
1533 * card as a normal networking interface, and on no
1534 * other platform I know of does starting a non-
1535 * promiscuous capture affect which multicast packets
1536 * are received by the interface.
1540 * Hmm, how can we set promiscuous mode on all interfaces?
1541 * I am not sure if that is possible at all.
1544 if (device
&& promisc
) {
1545 memset(&mr
, 0, sizeof(mr
));
1546 mr
.mr_ifindex
= handle
->md
.ifindex
;
1547 mr
.mr_type
= PACKET_MR_PROMISC
;
1548 if (setsockopt(sock_fd
, SOL_PACKET
,
1549 PACKET_ADD_MEMBERSHIP
, &mr
, sizeof(mr
)) == -1)
1551 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1552 "setsockopt: %s", pcap_strerror(errno
));
1558 * This is a 2.2[.x] or later kernel (we know that
1559 * because we're not using a SOCK_PACKET socket -
1560 * PF_PACKET is supported only in 2.2 and later
1563 * We can safely pass "recvfrom()" a byte count
1564 * based on the snapshot length.
1566 * If we're in cooked mode, make the snapshot length
1567 * large enough to hold a "cooked mode" header plus
1568 * 1 byte of packet data (so we don't pass a byte
1569 * count of 0 to "recvfrom()").
1571 if (handle
->md
.cooked
) {
1572 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
1573 handle
->snapshot
= SLL_HDR_LEN
+ 1;
1575 handle
->bufsize
= handle
->snapshot
;
1577 /* Save the socket FD in the pcap structure */
1579 handle
->fd
= sock_fd
;
1590 * Get rid of any link-layer type list we allocated.
1592 if (handle
->dlt_list
!= NULL
)
1593 free(handle
->dlt_list
);
1599 "New packet capturing interface not supported by build "
1600 "environment", PCAP_ERRBUF_SIZE
);
1606 live_open_mmap(pcap_t
* handle
, char* errmsg
)
1608 #ifdef HAVE_PACKET_RING
1609 /* by default request 4M for the ring buffer */
1610 int ret
= create_ring(handle
, 4*1024*1024, errmsg
);
1614 /* override some defaults and inherit the other fields from
1616 * handle->offset is used to get the current position into the rx ring
1617 * handle->cc is used to store the ring size */
1618 handle
->read_op
= pcap_read_linux_mmap
;
1619 handle
->close_op
= pcap_close_linux_mmap
;
1620 handle
->setfilter_op
= pcap_setfilter_linux_mmap
;
1621 handle
->setnonblock_op
= pcap_setnonblock_mmap
;
1622 handle
->getnonblock_op
= pcap_getnonblock_mmap
;
1623 handle
->selectable_fd
= handle
->fd
;
1625 #else /* HAVE_PACKET_RING */
1627 #endif /* HAVE_PACKET_RING */
1630 #ifdef HAVE_PACKET_RING
1633 compute_ring_block(int frame_size
, unsigned *block_size
, unsigned *frames_per_block
)
1635 /* compute the minumum block size that will handle this frame.
1636 * The block has to be page size aligned.
1637 * The max block size allowed by the kernel is arch-dependent and
1638 * it's not explicitly checked here. */
1639 *block_size
= getpagesize();
1640 while (*block_size
< frame_size
)
1643 *frames_per_block
= *block_size
/frame_size
;
1647 create_ring(pcap_t
* handle
, unsigned size
, char* errmsg
)
1649 unsigned i
, j
, ringsize
, frames_per_block
;
1650 struct tpacket_req req
;
1652 /* Note that with large snapshot (say 64K) only a few frames
1653 * will be available in the ring even with pretty large ring size
1654 * (and a lot of memory will be unused).
1655 * The snap len should be carefully chosen to achive best
1657 req
.tp_frame_size
= TPACKET_ALIGN(handle
->snapshot
+TPACKET_HDRLEN
);
1658 req
.tp_frame_nr
= size
/req
.tp_frame_size
;
1659 compute_ring_block(req
.tp_frame_size
, &req
.tp_block_size
, &frames_per_block
);
1660 req
.tp_block_nr
= req
.tp_frame_nr
/ frames_per_block
;
1662 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
1663 req
.tp_frame_nr
= req
.tp_block_nr
* frames_per_block
;
1665 /* ask the kernel to create the ring */
1667 if (setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1668 (void *) &req
, sizeof(req
))) {
1669 /* try to reduce requested ring size to prevent memory failure */
1670 if ((errno
== ENOMEM
) && (req
.tp_block_nr
> 1)) {
1671 req
.tp_frame_nr
>>= 1;
1672 req
.tp_block_nr
= req
.tp_frame_nr
/frames_per_block
;
1675 snprintf(errmsg
, PCAP_ERRBUF_SIZE
, "can't create rx ring on "
1676 "packet socket %d: %d-%s", handle
->fd
, errno
,
1677 pcap_strerror(errno
));
1681 /* memory map the rx ring */
1682 ringsize
= req
.tp_block_nr
* req
.tp_block_size
;
1683 handle
->bp
= mmap(0, ringsize
, PROT_READ
| PROT_WRITE
, MAP_SHARED
,
1685 if (handle
->bp
== MAP_FAILED
) {
1686 snprintf(errmsg
, PCAP_ERRBUF_SIZE
, "can't mmap rx ring: %d-%s",
1687 errno
, pcap_strerror(errno
));
1689 /* clear the allocated ring on error*/
1690 destroy_ring(handle
);
1694 /* allocate a ring for each frame header pointer*/
1695 handle
->cc
= req
.tp_frame_nr
;
1696 handle
->buffer
= malloc(handle
->cc
* sizeof(struct tpacket_hdr
*));
1697 if (!handle
->buffer
) {
1698 destroy_ring(handle
);
1702 /* fill the header ring with proper frame ptr*/
1704 for (i
=0; i
<req
.tp_block_nr
; ++i
) {
1705 u_char
*base
= &handle
->bp
[i
*req
.tp_block_size
];
1706 for (j
=0; j
<frames_per_block
; ++j
, ++handle
->offset
) {
1707 RING_GET_FRAME(handle
) = (struct tpacket_hdr
*) base
;
1708 base
+= req
.tp_frame_size
;
1712 handle
->bufsize
= req
.tp_frame_size
;
1717 /* free all ring related resources*/
1719 destroy_ring(pcap_t
*handle
)
1721 /* tell the kernel to destroy the ring*/
1722 struct tpacket_req req
;
1723 memset(&req
, 0, sizeof(req
));
1724 setsockopt(handle
->fd
, SOL_PACKET
, PACKET_RX_RING
,
1725 (void *) &req
, sizeof(req
));
1727 /* if ring is mapped, unmap it*/
1729 /* need to re-compute the ring size */
1730 unsigned frames_per_block
, block_size
;
1731 compute_ring_block(handle
->bufsize
, &block_size
, &frames_per_block
);
1733 /* do not perform sanity check here: we can't recover any error */
1734 munmap(handle
->bp
, block_size
* handle
->cc
/ frames_per_block
);
1738 /* if the header ring is allocated, clear it*/
1739 if (handle
->buffer
) {
1740 free(handle
->buffer
);
1746 pcap_close_linux_mmap( pcap_t
*handle
)
1748 destroy_ring(handle
);
1749 pcap_close_linux(handle
);
1754 pcap_getnonblock_mmap(pcap_t
*p
, char *errbuf
)
1756 /* use negative value of timeout to indicate non blocking ops */
1757 return (p
->md
.timeout
<0);
1761 pcap_setnonblock_mmap(pcap_t
*p
, int nonblock
, char *errbuf
)
1763 /* map each value to the corresponding 2's complement, to
1764 * preserve the timeout value provided with pcap_open_live */
1766 if (p
->md
.timeout
> 0)
1767 p
->md
.timeout
= p
->md
.timeout
*-1 - 1;
1769 if (p
->md
.timeout
< 0)
1770 p
->md
.timeout
= (p
->md
.timeout
+1)*-1;
1775 pcap_read_linux_mmap(pcap_t
*handle
, int max_packets
, pcap_handler callback
,
1780 /* wait for frames availability.*/
1781 if ((handle
->md
.timeout
>= 0) && !(RING_GET_FRAME(handle
)->tp_status
)) {
1782 struct pollfd pollinfo
;
1785 pollinfo
.fd
= handle
->fd
;
1786 pollinfo
.events
= POLLIN
;
1789 /* poll() requires a negative timeout to wait forever */
1790 ret
= poll(&pollinfo
, 1, (handle
->md
.timeout
> 0)?
1791 handle
->md
.timeout
: -1);
1792 if ((ret
< 0) && (errno
!= EINTR
)) {
1793 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1794 "can't poll on packet socket fd %d: %d-%s",
1795 handle
->fd
, errno
, pcap_strerror(errno
));
1798 /* check for break loop condition on interrupted syscall*/
1799 if (handle
->break_loop
) {
1800 handle
->break_loop
= 0;
1806 /* non-positive values of max_packets are used to require all
1807 * packets currently available in the ring */
1808 while ((pkts
< max_packets
) || (max_packets
<= 0)) {
1810 struct sockaddr_ll
*sll
;
1811 struct pcap_pkthdr pcaphdr
;
1813 struct tpacket_hdr
* thdr
= RING_GET_FRAME(handle
);
1814 if (thdr
->tp_status
== TP_STATUS_KERNEL
)
1817 /* perform sanity check on internal offset. */
1818 if (thdr
->tp_mac
+thdr
->tp_snaplen
> handle
->bufsize
) {
1819 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
1820 "corrupted frame on kernel ring mac "
1821 "offset %d + caplen %d > frame len %d\n",
1822 thdr
->tp_mac
, thdr
->tp_snaplen
, handle
->bufsize
);
1826 /* run filter on received packet
1827 * If the kernel filtering is enabled we need to run the
1828 * filter until all the frames present into the ring
1829 * at filter creation time are processed.
1830 * In such case md.use_bpf is used as a counter for the
1831 * packet we need to filter.
1832 * Note: alternatively it could be possible to stop applying
1833 * the filter when the ring became empty, but it can possibly
1834 * happen a lot later... */
1835 bp
= (unsigned char*)thdr
+ thdr
->tp_mac
;
1836 run_bpf
= (!handle
->md
.use_bpf
) ||
1837 ((handle
->md
.use_bpf
>1) && handle
->md
.use_bpf
--);
1838 if (run_bpf
&& handle
->fcode
.bf_insns
&&
1839 (bpf_filter(handle
->fcode
.bf_insns
, bp
,
1840 thdr
->tp_len
, thdr
->tp_snaplen
) == 0))
1843 /* check direction and interface index */
1844 sll
= (void*)thdr
+ TPACKET_ALIGN(sizeof(*thdr
));
1845 if ((sll
->sll_ifindex
== handle
->md
.lo_ifindex
) &&
1846 (sll
->sll_pkttype
== PACKET_OUTGOING
))
1849 /* get required packet info from ring header */
1850 pcaphdr
.ts
.tv_sec
= thdr
->tp_sec
;
1851 pcaphdr
.ts
.tv_usec
= thdr
->tp_usec
;
1852 pcaphdr
.caplen
= thdr
->tp_snaplen
;
1853 pcaphdr
.len
= thdr
->tp_len
;
1855 /* if required build in place the sll header*/
1856 if (handle
->md
.cooked
) {
1857 struct sll_header
*hdrp
= (struct sll_header
*)((char *)bp
- sizeof(struct sll_header
));
1859 hdrp
->sll_pkttype
= map_packet_type_to_sll_type(
1861 hdrp
->sll_hatype
= htons(sll
->sll_hatype
);
1862 hdrp
->sll_halen
= htons(sll
->sll_halen
);
1863 memcpy(hdrp
->sll_addr
, sll
->sll_addr
, SLL_ADDRLEN
);
1864 hdrp
->sll_protocol
= sll
->sll_protocol
;
1866 /* update packet len */
1867 pcaphdr
.caplen
+= SLL_HDR_LEN
;
1868 pcaphdr
.len
+= SLL_HDR_LEN
;
1871 /* pass the packet to the user */
1873 callback(user
, &pcaphdr
, bp
);
1874 handle
->md
.packets_read
++;
1878 thdr
->tp_status
= TP_STATUS_KERNEL
;
1879 if (++handle
->offset
>= handle
->cc
)
1882 /* check for break loop condition*/
1883 if (handle
->break_loop
) {
1884 handle
->break_loop
= 0;
1892 pcap_setfilter_linux_mmap(pcap_t
*handle
, struct bpf_program
*filter
)
1895 int ret
= pcap_setfilter_linux(handle
, filter
);
1899 /* if the kernel filter is enabled, we need to apply the filter on
1900 * all packets present into the ring. Get an upper bound of their number
1902 if (!handle
->md
.use_bpf
)
1905 /* walk the ring backward and count the free slot */
1906 offset
= handle
->offset
;
1907 if (--handle
->offset
< 0)
1908 handle
->offset
= handle
->cc
- 1;
1909 for (n
=0; n
< handle
->cc
; ++n
) {
1910 if (--handle
->offset
< 0)
1911 handle
->offset
= handle
->cc
- 1;
1912 if (RING_GET_FRAME(handle
)->tp_status
!= TP_STATUS_KERNEL
)
1916 /* be careful to not change current ring position */
1917 handle
->offset
= offset
;
1919 /* store the number of packets currently present in the ring */
1920 handle
->md
.use_bpf
= 1 + (handle
->cc
- n
);
1924 #endif /* HAVE_PACKET_RING */
1927 #ifdef HAVE_PF_PACKET_SOCKETS
1929 * Return the index of the given device name. Fill ebuf and return
1933 iface_get_id(int fd
, const char *device
, char *ebuf
)
1937 memset(&ifr
, 0, sizeof(ifr
));
1938 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1940 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
1941 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1942 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
1946 return ifr
.ifr_ifindex
;
1950 * Bind the socket associated with FD to the given device.
1953 iface_bind(int fd
, int ifindex
, char *ebuf
)
1955 struct sockaddr_ll sll
;
1957 socklen_t errlen
= sizeof(err
);
1959 memset(&sll
, 0, sizeof(sll
));
1960 sll
.sll_family
= AF_PACKET
;
1961 sll
.sll_ifindex
= ifindex
;
1962 sll
.sll_protocol
= htons(ETH_P_ALL
);
1964 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
1965 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1966 "bind: %s", pcap_strerror(errno
));
1970 /* Any pending errors, e.g., network is down? */
1972 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
1973 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1974 "getsockopt: %s", pcap_strerror(errno
));
1979 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1980 "bind: %s", pcap_strerror(err
));
1990 /* ===== Functions to interface to the older kernels ================== */
1993 * With older kernels promiscuous mode is kind of interesting because we
1994 * have to reset the interface before exiting. The problem can't really
1995 * be solved without some daemon taking care of managing usage counts.
1996 * If we put the interface into promiscuous mode, we set a flag indicating
1997 * that we must take it out of that mode when the interface is closed,
1998 * and, when closing the interface, if that flag is set we take it out
1999 * of promiscuous mode.
2003 * List of pcaps for which we turned promiscuous mode on by hand.
2004 * If there are any such pcaps, we arrange to call "pcap_close_all()"
2005 * when we exit, and have it close all of them to turn promiscuous mode
2008 static struct pcap
*pcaps_to_close
;
2011 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
2012 * be called on exit.
2014 static int did_atexit
;
2016 static void pcap_close_all(void)
2018 struct pcap
*handle
;
2020 while ((handle
= pcaps_to_close
) != NULL
)
2024 static void pcap_close_linux( pcap_t
*handle
)
2026 struct pcap
*p
, *prevp
;
2029 if (handle
->md
.clear_promisc
) {
2031 * We put the interface into promiscuous mode; take
2032 * it out of promiscuous mode.
2034 * XXX - if somebody else wants it in promiscuous mode,
2035 * this code cannot know that, so it'll take it out
2036 * of promiscuous mode. That's not fixable in 2.0[.x]
2039 memset(&ifr
, 0, sizeof(ifr
));
2040 strncpy(ifr
.ifr_name
, handle
->md
.device
, sizeof(ifr
.ifr_name
));
2041 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2043 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
2044 "Please adjust manually.\n"
2045 "Hint: This can't happen with Linux >= 2.2.0.\n",
2048 if (ifr
.ifr_flags
& IFF_PROMISC
) {
2050 * Promiscuous mode is currently on; turn it
2053 ifr
.ifr_flags
&= ~IFF_PROMISC
;
2054 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2056 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
2057 "Please adjust manually.\n"
2058 "Hint: This can't happen with Linux >= 2.2.0.\n",
2065 * Take this pcap out of the list of pcaps for which we
2066 * have to take the interface out of promiscuous mode.
2068 for (p
= pcaps_to_close
, prevp
= NULL
; p
!= NULL
;
2069 prevp
= p
, p
= p
->md
.next
) {
2072 * Found it. Remove it from the list.
2074 if (prevp
== NULL
) {
2076 * It was at the head of the list.
2078 pcaps_to_close
= p
->md
.next
;
2081 * It was in the middle of the list.
2083 prevp
->md
.next
= p
->md
.next
;
2090 if (handle
->md
.device
!= NULL
)
2091 free(handle
->md
.device
);
2092 handle
->md
.device
= NULL
;
2093 pcap_close_common(handle
);
2097 * Try to open a packet socket using the old kernel interface.
2098 * Returns 0 on failure.
2099 * FIXME: 0 uses to mean success (Sebastian)
2102 live_open_old(pcap_t
*handle
, const char *device
, int promisc
,
2103 int to_ms
, char *ebuf
)
2107 struct utsname utsname
;
2111 /* Open the socket */
2113 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
2114 if (handle
->fd
== -1) {
2115 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2116 "socket: %s", pcap_strerror(errno
));
2120 /* It worked - we are using the old interface */
2121 handle
->md
.sock_packet
= 1;
2123 /* ...which means we get the link-layer header. */
2124 handle
->md
.cooked
= 0;
2126 /* Bind to the given device */
2129 strncpy(ebuf
, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
2133 if (iface_bind_old(handle
->fd
, device
, ebuf
) == -1)
2137 * Try to get the link-layer type.
2139 arptype
= iface_get_arptype(handle
->fd
, device
, ebuf
);
2144 * Try to find the DLT_ type corresponding to that
2147 map_arphrd_to_dlt(handle
, arptype
, 0);
2148 if (handle
->linktype
== -1) {
2149 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2150 "unknown arptype %d", arptype
);
2154 /* Go to promisc mode if requested */
2157 memset(&ifr
, 0, sizeof(ifr
));
2158 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2159 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
2160 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2161 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
2164 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
2166 * Promiscuous mode isn't currently on,
2167 * so turn it on, and remember that
2168 * we should turn it off when the
2173 * If we haven't already done so, arrange
2174 * to have "pcap_close_all()" called when
2178 if (atexit(pcap_close_all
) == -1) {
2180 * "atexit()" failed; don't
2181 * put the interface in
2182 * promiscuous mode, just
2185 strncpy(ebuf
, "atexit failed",
2192 ifr
.ifr_flags
|= IFF_PROMISC
;
2193 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
2194 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2196 pcap_strerror(errno
));
2199 handle
->md
.clear_promisc
= 1;
2202 * Add this to the list of pcaps
2203 * to close when we exit.
2205 handle
->md
.next
= pcaps_to_close
;
2206 pcaps_to_close
= handle
;
2211 * Compute the buffer size.
2213 * We're using SOCK_PACKET, so this might be a 2.0[.x]
2214 * kernel, and might require special handling - check.
2216 if (uname(&utsname
) < 0 ||
2217 strncmp(utsname
.release
, "2.0", 3) == 0) {
2219 * Either we couldn't find out what kernel release
2220 * this is, or it's a 2.0[.x] kernel.
2222 * In the 2.0[.x] kernel, a "recvfrom()" on
2223 * a SOCK_PACKET socket, with MSG_TRUNC set, will
2224 * return the number of bytes read, so if we pass
2225 * a length based on the snapshot length, it'll
2226 * return the number of bytes from the packet
2227 * copied to userland, not the actual length
2230 * This means that, for example, the IP dissector
2231 * in tcpdump will get handed a packet length less
2232 * than the length in the IP header, and will
2233 * complain about "truncated-ip".
2235 * So we don't bother trying to copy from the
2236 * kernel only the bytes in which we're interested,
2237 * but instead copy them all, just as the older
2238 * versions of libpcap for Linux did.
2240 * The buffer therefore needs to be big enough to
2241 * hold the largest packet we can get from this
2242 * device. Unfortunately, we can't get the MRU
2243 * of the network; we can only get the MTU. The
2244 * MTU may be too small, in which case a packet larger
2245 * than the buffer size will be truncated *and* we
2246 * won't get the actual packet size.
2248 * However, if the snapshot length is larger than
2249 * the buffer size based on the MTU, we use the
2250 * snapshot length as the buffer size, instead;
2251 * this means that with a sufficiently large snapshot
2252 * length we won't artificially truncate packets
2253 * to the MTU-based size.
2255 * This mess just one of many problems with packet
2256 * capture on 2.0[.x] kernels; you really want a
2257 * 2.2[.x] or later kernel if you want packet capture
2260 mtu
= iface_get_mtu(handle
->fd
, device
, ebuf
);
2263 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
2264 if (handle
->bufsize
< handle
->snapshot
)
2265 handle
->bufsize
= handle
->snapshot
;
2268 * This is a 2.2[.x] or later kernel.
2270 * We can safely pass "recvfrom()" a byte count
2271 * based on the snapshot length.
2273 handle
->bufsize
= handle
->snapshot
;
2277 * Default value for offset to align link-layer payload
2278 * on a 4-byte boundary.
2286 pcap_close_linux(handle
);
2291 * Bind the socket associated with FD to the given device using the
2292 * interface of the old kernels.
2295 iface_bind_old(int fd
, const char *device
, char *ebuf
)
2297 struct sockaddr saddr
;
2299 socklen_t errlen
= sizeof(err
);
2301 memset(&saddr
, 0, sizeof(saddr
));
2302 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
2303 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
2304 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2305 "bind: %s", pcap_strerror(errno
));
2309 /* Any pending errors, e.g., network is down? */
2311 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
2312 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2313 "getsockopt: %s", pcap_strerror(errno
));
2318 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2319 "bind: %s", pcap_strerror(err
));
2327 /* ===== System calls available on all supported kernels ============== */
2330 * Query the kernel for the MTU of the given interface.
2333 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
2338 return BIGGER_THAN_ALL_MTUS
;
2340 memset(&ifr
, 0, sizeof(ifr
));
2341 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2343 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
2344 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2345 "SIOCGIFMTU: %s", pcap_strerror(errno
));
2353 * Get the hardware type of the given interface as ARPHRD_xxx constant.
2356 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
2360 memset(&ifr
, 0, sizeof(ifr
));
2361 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2363 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
2364 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2365 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
2369 return ifr
.ifr_hwaddr
.sa_family
;
2372 #ifdef SO_ATTACH_FILTER
2374 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
2378 register struct bpf_insn
*p
;
2383 * Make a copy of the filter, and modify that copy if
2386 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
2387 len
= handle
->fcode
.bf_len
;
2388 f
= (struct bpf_insn
*)malloc(prog_size
);
2390 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2391 "malloc: %s", pcap_strerror(errno
));
2394 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
2396 fcode
->filter
= (struct sock_filter
*) f
;
2398 for (i
= 0; i
< len
; ++i
) {
2401 * What type of instruction is this?
2403 switch (BPF_CLASS(p
->code
)) {
2407 * It's a return instruction; is the snapshot
2408 * length a constant, rather than the contents
2409 * of the accumulator?
2411 if (BPF_MODE(p
->code
) == BPF_K
) {
2413 * Yes - if the value to be returned,
2414 * i.e. the snapshot length, is anything
2415 * other than 0, make it 65535, so that
2416 * the packet is truncated by "recvfrom()",
2417 * not by the filter.
2419 * XXX - there's nothing we can easily do
2420 * if it's getting the value from the
2421 * accumulator; we'd have to insert
2422 * code to force non-zero values to be
2433 * It's a load instruction; is it loading
2436 switch (BPF_MODE(p
->code
)) {
2442 * Yes; are we in cooked mode?
2444 if (handle
->md
.cooked
) {
2446 * Yes, so we need to fix this
2449 if (fix_offset(p
) < 0) {
2451 * We failed to do so.
2452 * Return 0, so our caller
2453 * knows to punt to userland.
2463 return 1; /* we succeeded */
2467 fix_offset(struct bpf_insn
*p
)
2470 * What's the offset?
2472 if (p
->k
>= SLL_HDR_LEN
) {
2474 * It's within the link-layer payload; that starts at an
2475 * offset of 0, as far as the kernel packet filter is
2476 * concerned, so subtract the length of the link-layer
2479 p
->k
-= SLL_HDR_LEN
;
2480 } else if (p
->k
== 14) {
2482 * It's the protocol field; map it to the special magic
2483 * kernel offset for that field.
2485 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
2488 * It's within the header, but it's not one of those
2489 * fields; we can't do that in the kernel, so punt
2498 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
2500 int total_filter_on
= 0;
2506 * The socket filter code doesn't discard all packets queued
2507 * up on the socket when the filter is changed; this means
2508 * that packets that don't match the new filter may show up
2509 * after the new filter is put onto the socket, if those
2510 * packets haven't yet been read.
2512 * This means, for example, that if you do a tcpdump capture
2513 * with a filter, the first few packets in the capture might
2514 * be packets that wouldn't have passed the filter.
2516 * We therefore discard all packets queued up on the socket
2517 * when setting a kernel filter. (This isn't an issue for
2518 * userland filters, as the userland filtering is done after
2519 * packets are queued up.)
2521 * To flush those packets, we put the socket in read-only mode,
2522 * and read packets from the socket until there are no more to
2525 * In order to keep that from being an infinite loop - i.e.,
2526 * to keep more packets from arriving while we're draining
2527 * the queue - we put the "total filter", which is a filter
2528 * that rejects all packets, onto the socket before draining
2531 * This code deliberately ignores any errors, so that you may
2532 * get bogus packets if an error occurs, rather than having
2533 * the filtering done in userland even if it could have been
2534 * done in the kernel.
2536 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2537 &total_fcode
, sizeof(total_fcode
)) == 0) {
2541 * Note that we've put the total filter onto the socket.
2543 total_filter_on
= 1;
2546 * Save the socket's current mode, and put it in
2547 * non-blocking mode; we drain it by reading packets
2548 * until we get an error (which is normally a
2549 * "nothing more to be read" error).
2551 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
2552 if (save_mode
!= -1 &&
2553 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
2554 while (recv(handle
->fd
, &drain
, sizeof drain
,
2558 fcntl(handle
->fd
, F_SETFL
, save_mode
);
2559 if (save_errno
!= EAGAIN
) {
2561 reset_kernel_filter(handle
);
2562 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2563 "recv: %s", pcap_strerror(save_errno
));
2570 * Now attach the new filter.
2572 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2573 fcode
, sizeof(*fcode
));
2574 if (ret
== -1 && total_filter_on
) {
2576 * Well, we couldn't set that filter on the socket,
2577 * but we could set the total filter on the socket.
2579 * This could, for example, mean that the filter was
2580 * too big to put into the kernel, so we'll have to
2581 * filter in userland; in any case, we'll be doing
2582 * filtering in userland, so we need to remove the
2583 * total filter so we see packets.
2588 * XXX - if this fails, we're really screwed;
2589 * we have the total filter on the socket,
2590 * and it won't come off. What do we do then?
2592 reset_kernel_filter(handle
);
2600 reset_kernel_filter(pcap_t
*handle
)
2603 * setsockopt() barfs unless it get a dummy parameter.
2604 * valgrind whines unless the value is initialized,
2605 * as it has no idea that setsockopt() ignores its
2610 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
2611 &dummy
, sizeof(dummy
));