]>
The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
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.
29 static const char rcsid
[] _U_
=
30 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.114 2005-07-05 22:31:57 guy Exp $ (LBL)";
34 * Known problems with 2.0[.x] kernels:
36 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
37 * if we use PF_PACKET, we can filter out the transmitted version
38 * of the packet by using data in the "sockaddr_ll" returned by
39 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
40 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
41 * "sockaddr_pkt" which doesn't give us enough information to let
44 * - We have to set the interface's IFF_PROMISC flag ourselves, if
45 * we're to run in promiscuous mode, which means we have to turn
46 * it off ourselves when we're done; the kernel doesn't keep track
47 * of how many sockets are listening promiscuously, which means
48 * it won't get turned off automatically when no sockets are
49 * listening promiscuously. We catch "pcap_close()" and, for
50 * interfaces we put into promiscuous mode, take them out of
51 * promiscuous mode - which isn't necessarily the right thing to
52 * do, if another socket also requested promiscuous mode between
53 * the time when we opened the socket and the time when we close
56 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
57 * return the amount of data that you could have read, rather than
58 * the amount that was returned, so we can't just allocate a buffer
59 * whose size is the snapshot length and pass the snapshot length
60 * as the byte count, and also pass MSG_TRUNC, so that the return
61 * value tells us how long the packet was on the wire.
63 * This means that, if we want to get the actual size of the packet,
64 * so we can return it in the "len" field of the packet header,
65 * we have to read the entire packet, not just the part that fits
66 * within the snapshot length, and thus waste CPU time copying data
67 * from the kernel that our caller won't see.
69 * We have to get the actual size, and supply it in "len", because
70 * otherwise, the IP dissector in tcpdump, for example, will complain
71 * about "truncated-ip", as the packet will appear to have been
72 * shorter, on the wire, than the IP header said it should have been.
85 #endif /* HAVE_DAG_API */
87 #ifdef HAVE_SEPTEL_API
88 #include "pcap-septel.h"
89 #endif /* HAVE_SEPTEL_API */
96 #include <sys/socket.h>
97 #include <sys/ioctl.h>
98 #include <sys/utsname.h>
100 #include <netinet/in.h>
101 #include <linux/if_ether.h>
102 #include <net/if_arp.h>
105 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
106 * sockets rather than SOCK_PACKET sockets.
108 * To use them, we include <linux/if_packet.h> rather than
109 * <netpacket/packet.h>; we do so because
111 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
112 * later kernels and libc5, and don't provide a <netpacket/packet.h>
115 * not all versions of glibc2 have a <netpacket/packet.h> file
116 * that defines stuff needed for some of the 2.4-or-later-kernel
117 * features, so if the system has a 2.4 or later kernel, we
118 * still can't use those features.
120 * We're already including a number of other <linux/XXX.h> headers, and
121 * this code is Linux-specific (no other OS has PF_PACKET sockets as
122 * a raw packet capture mechanism), so it's not as if you gain any
123 * useful portability by using <netpacket/packet.h>
125 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
126 * isn't defined? It only defines one data structure in 2.0.x, so
127 * it shouldn't cause any problems.
130 # include <linux/if_packet.h>
133 * On at least some Linux distributions (for example, Red Hat 5.2),
134 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
135 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
136 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
137 * the PACKET_xxx stuff.
139 * So we check whether PACKET_HOST is defined, and assume that we have
140 * PF_PACKET sockets only if it is defined.
143 # define HAVE_PF_PACKET_SOCKETS
144 # endif /* PACKET_HOST */
145 #endif /* PF_PACKET */
147 #ifdef SO_ATTACH_FILTER
148 #include <linux/types.h>
149 #include <linux/filter.h>
153 typedef int socklen_t
;
158 * This is being compiled on a system that lacks MSG_TRUNC; define it
159 * with the value it has in the 2.2 and later kernels, so that, on
160 * those kernels, when we pass it in the flags argument to "recvfrom()"
161 * we're passing the right value and thus get the MSG_TRUNC behavior
162 * we want. (We don't get that behavior on 2.0[.x] kernels, because
163 * they didn't support MSG_TRUNC.)
165 #define MSG_TRUNC 0x20
170 * This is being compiled on a system that lacks SOL_PACKET; define it
171 * with the value it has in the 2.2 and later kernels, so that we can
172 * set promiscuous mode in the good modern way rather than the old
173 * 2.0-kernel crappy way.
175 #define SOL_PACKET 263
178 #define MAX_LINKHEADER_SIZE 256
181 * When capturing on all interfaces we use this as the buffer size.
182 * Should be bigger then all MTUs that occur in real life.
183 * 64kB should be enough for now.
185 #define BIGGER_THAN_ALL_MTUS (64*1024)
188 * Prototypes for internal functions
190 static void map_arphrd_to_dlt(pcap_t
*, int, int);
191 static int live_open_old(pcap_t
*, const char *, int, int, char *);
192 static int live_open_new(pcap_t
*, const char *, int, int, char *);
193 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
194 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
195 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
196 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
197 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
198 static int pcap_setdirection_linux(pcap_t
*, direction_t
);
199 static void pcap_close_linux(pcap_t
*);
202 * Wrap some ioctl calls
204 #ifdef HAVE_PF_PACKET_SOCKETS
205 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
207 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
208 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
209 #ifdef HAVE_PF_PACKET_SOCKETS
210 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
212 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
214 #ifdef SO_ATTACH_FILTER
215 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
216 static int fix_offset(struct bpf_insn
*p
);
217 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
218 static int reset_kernel_filter(pcap_t
*handle
);
220 static struct sock_filter total_insn
221 = BPF_STMT(BPF_RET
| BPF_K
, 0);
222 static struct sock_fprog total_fcode
223 = { 1, &total_insn
};
227 * Get a handle for a live capture from the given device. You can
228 * pass NULL as device to get all packages (without link level
229 * information of course). If you pass 1 as promisc the interface
230 * will be set to promiscous mode (XXX: I think this usage should
231 * be deprecated and functions be added to select that later allow
232 * modification of that values -- Torsten).
237 pcap_open_live(const char *device
, int snaplen
, int promisc
, int to_ms
,
243 int live_open_ok
= 0;
244 struct utsname utsname
;
247 if (strstr(device
, "dag")) {
248 return dag_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
250 #endif /* HAVE_DAG_API */
252 #ifdef HAVE_SEPTEL_API
253 if (strstr(device
, "septel")) {
254 return septel_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
256 #endif /* HAVE_SEPTEL_API */
258 /* Allocate a handle for this session. */
260 handle
= malloc(sizeof(*handle
));
261 if (handle
== NULL
) {
262 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
263 pcap_strerror(errno
));
267 /* Initialize some components of the pcap structure. */
269 memset(handle
, 0, sizeof(*handle
));
270 handle
->snapshot
= snaplen
;
271 handle
->md
.timeout
= to_ms
;
274 * NULL and "any" are special devices which give us the hint to
275 * monitor all devices.
277 if (!device
|| strcmp(device
, "any") == 0) {
279 handle
->md
.device
= strdup("any");
282 /* Just a warning. */
283 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
284 "Promiscuous mode not supported on the \"any\" device");
288 handle
->md
.device
= strdup(device
);
290 if (handle
->md
.device
== NULL
) {
291 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
292 pcap_strerror(errno
) );
298 * Current Linux kernels use the protocol family PF_PACKET to
299 * allow direct access to all packets on the network while
300 * older kernels had a special socket type SOCK_PACKET to
301 * implement this feature.
302 * While this old implementation is kind of obsolete we need
303 * to be compatible with older kernels for a while so we are
304 * trying both methods with the newer method preferred.
307 if ((err
= live_open_new(handle
, device
, promisc
, to_ms
, ebuf
)) == 1)
310 /* Non-fatal error; try old way */
311 if (live_open_old(handle
, device
, promisc
, to_ms
, ebuf
))
316 * Both methods to open the packet socket failed. Tidy
317 * up and report our failure (ebuf is expected to be
318 * set by the functions above).
321 if (handle
->md
.device
!= NULL
)
322 free(handle
->md
.device
);
328 * Compute the buffer size.
330 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
331 * and might require special handling - check.
333 if (handle
->md
.sock_packet
&& (uname(&utsname
) < 0 ||
334 strncmp(utsname
.release
, "2.0", 3) == 0)) {
336 * We're using a SOCK_PACKET structure, and either
337 * we couldn't find out what kernel release this is,
338 * or it's a 2.0[.x] kernel.
340 * In the 2.0[.x] kernel, a "recvfrom()" on
341 * a SOCK_PACKET socket, with MSG_TRUNC set, will
342 * return the number of bytes read, so if we pass
343 * a length based on the snapshot length, it'll
344 * return the number of bytes from the packet
345 * copied to userland, not the actual length
348 * This means that, for example, the IP dissector
349 * in tcpdump will get handed a packet length less
350 * than the length in the IP header, and will
351 * complain about "truncated-ip".
353 * So we don't bother trying to copy from the
354 * kernel only the bytes in which we're interested,
355 * but instead copy them all, just as the older
356 * versions of libpcap for Linux did.
358 * The buffer therefore needs to be big enough to
359 * hold the largest packet we can get from this
360 * device. Unfortunately, we can't get the MRU
361 * of the network; we can only get the MTU. The
362 * MTU may be too small, in which case a packet larger
363 * than the buffer size will be truncated *and* we
364 * won't get the actual packet size.
366 * However, if the snapshot length is larger than
367 * the buffer size based on the MTU, we use the
368 * snapshot length as the buffer size, instead;
369 * this means that with a sufficiently large snapshot
370 * length we won't artificially truncate packets
371 * to the MTU-based size.
373 * This mess just one of many problems with packet
374 * capture on 2.0[.x] kernels; you really want a
375 * 2.2[.x] or later kernel if you want packet capture
378 mtu
= iface_get_mtu(handle
->fd
, device
, ebuf
);
380 pcap_close_linux(handle
);
384 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
385 if (handle
->bufsize
< handle
->snapshot
)
386 handle
->bufsize
= handle
->snapshot
;
389 * This is a 2.2[.x] or later kernel (we know that
390 * either because we're not using a SOCK_PACKET
391 * socket - PF_PACKET is supported only in 2.2
392 * and later kernels - or because we checked the
395 * We can safely pass "recvfrom()" a byte count
396 * based on the snapshot length.
398 handle
->bufsize
= handle
->snapshot
;
401 /* Allocate the buffer */
403 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
404 if (!handle
->buffer
) {
405 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
406 "malloc: %s", pcap_strerror(errno
));
407 pcap_close_linux(handle
);
413 * "handle->fd" is a socket, so "select()" and "poll()"
416 handle
->selectable_fd
= handle
->fd
;
418 handle
->read_op
= pcap_read_linux
;
419 handle
->inject_op
= pcap_inject_linux
;
420 handle
->setfilter_op
= pcap_setfilter_linux
;
421 handle
->setdirection_op
= pcap_setdirection_linux
;
422 handle
->set_datalink_op
= NULL
; /* can't change data link type */
423 handle
->getnonblock_op
= pcap_getnonblock_fd
;
424 handle
->setnonblock_op
= pcap_setnonblock_fd
;
425 handle
->stats_op
= pcap_stats_linux
;
426 handle
->close_op
= pcap_close_linux
;
432 * Read at most max_packets from the capture stream and call the callback
433 * for each of them. Returns the number of packets handled or -1 if an
437 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
440 * Currently, on Linux only one packet is delivered per read,
443 return pcap_read_packet(handle
, callback
, user
);
447 * Read a packet from the socket calling the handler provided by
448 * the user. Returns the number of packets received or -1 if an
452 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
456 #ifdef HAVE_PF_PACKET_SOCKETS
457 struct sockaddr_ll from
;
458 struct sll_header
*hdrp
;
460 struct sockaddr from
;
463 int packet_len
, caplen
;
464 struct pcap_pkthdr pcap_header
;
466 #ifdef HAVE_PF_PACKET_SOCKETS
468 * If this is a cooked device, leave extra room for a
469 * fake packet header.
471 if (handle
->md
.cooked
)
472 offset
= SLL_HDR_LEN
;
477 * This system doesn't have PF_PACKET sockets, so it doesn't
478 * support cooked devices.
483 /* Receive a single packet from the kernel */
485 bp
= handle
->buffer
+ handle
->offset
;
488 * Has "pcap_breakloop()" been called?
490 if (handle
->break_loop
) {
492 * Yes - clear the flag that indicates that it
493 * has, and return -2 as an indication that we
494 * were told to break out of the loop.
496 handle
->break_loop
= 0;
499 fromlen
= sizeof(from
);
500 packet_len
= recvfrom(
501 handle
->fd
, bp
+ offset
,
502 handle
->bufsize
- offset
, MSG_TRUNC
,
503 (struct sockaddr
*) &from
, &fromlen
);
504 } while (packet_len
== -1 && errno
== EINTR
);
506 /* Check if an error occured */
508 if (packet_len
== -1) {
510 return 0; /* no packet there */
512 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
513 "recvfrom: %s", pcap_strerror(errno
));
518 #ifdef HAVE_PF_PACKET_SOCKETS
519 if (!handle
->md
.sock_packet
) {
521 * Do checks based on packet direction.
522 * We can only do this if we're using PF_PACKET; the
523 * address returned for SOCK_PACKET is a "sockaddr_pkt"
524 * which lacks the relevant packet type information.
526 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
529 * If this is from the loopback device, reject it;
530 * we'll see the packet as an incoming packet as well,
531 * and we don't want to see it twice.
533 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
537 * If the user only wants incoming packets, reject it.
539 if (handle
->direction
== D_IN
)
544 * If the user only wants outgoing packets, reject it.
546 if (handle
->direction
== D_OUT
)
552 #ifdef HAVE_PF_PACKET_SOCKETS
554 * If this is a cooked device, fill in the fake packet header.
556 if (handle
->md
.cooked
) {
558 * Add the length of the fake header to the length
559 * of packet data we read.
561 packet_len
+= SLL_HDR_LEN
;
563 hdrp
= (struct sll_header
*)bp
;
566 * Map the PACKET_ value to a LINUX_SLL_ value; we
567 * want the same numerical value to be used in
568 * the link-layer header even if the numerical values
569 * for the PACKET_ #defines change, so that programs
570 * that look at the packet type field will always be
571 * able to handle DLT_LINUX_SLL captures.
573 switch (from
.sll_pkttype
) {
576 hdrp
->sll_pkttype
= htons(LINUX_SLL_HOST
);
579 case PACKET_BROADCAST
:
580 hdrp
->sll_pkttype
= htons(LINUX_SLL_BROADCAST
);
583 case PACKET_MULTICAST
:
584 hdrp
->sll_pkttype
= htons(LINUX_SLL_MULTICAST
);
587 case PACKET_OTHERHOST
:
588 hdrp
->sll_pkttype
= htons(LINUX_SLL_OTHERHOST
);
591 case PACKET_OUTGOING
:
592 hdrp
->sll_pkttype
= htons(LINUX_SLL_OUTGOING
);
596 hdrp
->sll_pkttype
= -1;
600 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
601 hdrp
->sll_halen
= htons(from
.sll_halen
);
602 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
603 (from
.sll_halen
> SLL_ADDRLEN
) ?
606 hdrp
->sll_protocol
= from
.sll_protocol
;
611 * XXX: According to the kernel source we should get the real
612 * packet len if calling recvfrom with MSG_TRUNC set. It does
613 * not seem to work here :(, but it is supported by this code
615 * To be honest the code RELIES on that feature so this is really
616 * broken with 2.2.x kernels.
617 * I spend a day to figure out what's going on and I found out
618 * that the following is happening:
620 * The packet comes from a random interface and the packet_rcv
621 * hook is called with a clone of the packet. That code inserts
622 * the packet into the receive queue of the packet socket.
623 * If a filter is attached to that socket that filter is run
624 * first - and there lies the problem. The default filter always
625 * cuts the packet at the snaplen:
630 * So the packet filter cuts down the packet. The recvfrom call
631 * says "hey, it's only 68 bytes, it fits into the buffer" with
632 * the result that we don't get the real packet length. This
633 * is valid at least until kernel 2.2.17pre6.
635 * We currently handle this by making a copy of the filter
636 * program, fixing all "ret" instructions with non-zero
637 * operands to have an operand of 65535 so that the filter
638 * doesn't truncate the packet, and supplying that modified
639 * filter to the kernel.
643 if (caplen
> handle
->snapshot
)
644 caplen
= handle
->snapshot
;
646 /* Run the packet filter if not using kernel filter */
647 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
648 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
649 packet_len
, caplen
) == 0)
651 /* rejected by filter */
656 /* Fill in our own header data */
658 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
659 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
660 "ioctl: %s", pcap_strerror(errno
));
663 pcap_header
.caplen
= caplen
;
664 pcap_header
.len
= packet_len
;
669 * Arguably, we should count them before we check the filter,
670 * as on many other platforms "ps_recv" counts packets
671 * handed to the filter rather than packets that passed
672 * the filter, but if filtering is done in the kernel, we
673 * can't get a count of packets that passed the filter,
674 * and that would mean the meaning of "ps_recv" wouldn't
675 * be the same on all Linux systems.
677 * XXX - it's not the same on all systems in any case;
678 * ideally, we should have a "get the statistics" call
679 * that supplies more counts and indicates which of them
680 * it supplies, so that we supply a count of packets
681 * handed to the filter only on platforms where that
682 * information is available.
684 * We count them here even if we can get the packet count
685 * from the kernel, as we can only determine at run time
686 * whether we'll be able to get it from the kernel (if
687 * HAVE_TPACKET_STATS isn't defined, we can't get it from
688 * the kernel, but if it is defined, the library might
689 * have been built with a 2.4 or later kernel, but we
690 * might be running on a 2.2[.x] kernel without Alexey
691 * Kuznetzov's turbopacket patches, and thus the kernel
692 * might not be able to supply those statistics). We
693 * could, I guess, try, when opening the socket, to get
694 * the statistics, and if we can not increment the count
695 * here, but it's not clear that always incrementing
696 * the count is more expensive than always testing a flag
699 handle
->md
.stat
.ps_recv
++;
701 /* Call the user supplied callback function */
702 callback(userdata
, &pcap_header
, bp
);
708 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
712 #ifdef HAVE_PF_PACKET_SOCKETS
713 if (!handle
->md
.sock_packet
) {
714 /* PF_PACKET socket */
715 if (handle
->md
.ifindex
== -1) {
717 * We don't support sending on the "any" device.
719 strlcpy(handle
->errbuf
,
720 "Sending packets isn't supported on the \"any\" device",
725 if (handle
->md
.cooked
) {
727 * We don't support sending on the "any" device.
729 * XXX - how do you send on a bound cooked-mode
731 * Is a "sendto()" required there?
733 strlcpy(handle
->errbuf
,
734 "Sending packets isn't supported in cooked mode",
741 ret
= send(handle
->fd
, buf
, size
, 0);
743 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
744 pcap_strerror(errno
));
751 * Get the statistics for the given packet capture handle.
752 * Reports the number of dropped packets iff the kernel supports
753 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
754 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
755 * patches); otherwise, that information isn't available, and we lie
756 * and report 0 as the count of dropped packets.
759 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
761 #ifdef HAVE_TPACKET_STATS
762 struct tpacket_stats kstats
;
763 socklen_t len
= sizeof (struct tpacket_stats
);
766 #ifdef HAVE_TPACKET_STATS
768 * Try to get the packet counts from the kernel.
770 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
771 &kstats
, &len
) > -1) {
773 * In "linux/net/packet/af_packet.c", at least in the
774 * 2.4.9 kernel, "tp_packets" is incremented for every
775 * packet that passes the packet filter *and* is
776 * successfully queued on the socket; "tp_drops" is
777 * incremented for every packet dropped because there's
778 * not enough free space in the socket buffer.
780 * When the statistics are returned for a PACKET_STATISTICS
781 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
782 * so that "tp_packets" counts all packets handed to
783 * the PF_PACKET socket, including packets dropped because
784 * there wasn't room on the socket buffer - but not
785 * including packets that didn't pass the filter.
787 * In the BSD BPF, the count of received packets is
788 * incremented for every packet handed to BPF, regardless
789 * of whether it passed the filter.
791 * We can't make "pcap_stats()" work the same on both
792 * platforms, but the best approximation is to return
793 * "tp_packets" as the count of packets and "tp_drops"
794 * as the count of drops.
796 * Keep a running total because each call to
797 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
798 * resets the counters to zero.
800 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
801 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
806 * If the error was EOPNOTSUPP, fall through, so that
807 * if you build the library on a system with
808 * "struct tpacket_stats" and run it on a system
809 * that doesn't, it works as it does if the library
810 * is built on a system without "struct tpacket_stats".
812 if (errno
!= EOPNOTSUPP
) {
813 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
814 "pcap_stats: %s", pcap_strerror(errno
));
820 * On systems where the PACKET_STATISTICS "getsockopt()" argument
821 * is supported on PF_PACKET sockets:
823 * "ps_recv" counts only packets that *passed* the filter,
824 * not packets that didn't pass the filter. This includes
825 * packets later dropped because we ran out of buffer space.
827 * "ps_drop" counts packets dropped because we ran out of
828 * buffer space. It doesn't count packets dropped by the
829 * interface driver. It counts only packets that passed
832 * Both statistics include packets not yet read from the
833 * kernel by libpcap, and thus not yet seen by the application.
835 * On systems where the PACKET_STATISTICS "getsockopt()" argument
836 * is not supported on PF_PACKET sockets:
838 * "ps_recv" counts only packets that *passed* the filter,
839 * not packets that didn't pass the filter. It does not
840 * count packets dropped because we ran out of buffer
843 * "ps_drop" is not supported.
845 * "ps_recv" doesn't include packets not yet read from
846 * the kernel by libpcap.
848 *stats
= handle
->md
.stat
;
853 * Description string for the "any" device.
855 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
858 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
860 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
864 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
866 #endif /* HAVE_DAG_API */
868 #ifdef HAVE_SEPTEL_API
869 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
871 #endif /* HAVE_SEPTEL_API */
877 * Attach the given BPF code to the packet capture device.
880 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
882 #ifdef SO_ATTACH_FILTER
883 struct sock_fprog fcode
;
884 int can_filter_in_kernel
;
891 strncpy(handle
->errbuf
, "setfilter: No filter specified",
892 sizeof(handle
->errbuf
));
896 /* Make our private copy of the filter */
898 if (install_bpf_program(handle
, filter
) < 0)
899 /* install_bpf_program() filled in errbuf */
903 * Run user level packet filter by default. Will be overriden if
904 * installing a kernel filter succeeds.
906 handle
->md
.use_bpf
= 0;
908 /* Install kernel level filter if possible */
910 #ifdef SO_ATTACH_FILTER
912 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
914 * fcode.len is an unsigned short for current kernel.
915 * I have yet to see BPF-Code with that much
916 * instructions but still it is possible. So for the
917 * sake of correctness I added this check.
919 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
921 can_filter_in_kernel
= 0;
923 #endif /* USHRT_MAX */
926 * Oh joy, the Linux kernel uses struct sock_fprog instead
927 * of struct bpf_program and of course the length field is
928 * of different size. Pointed out by Sebastian
930 * Oh, and we also need to fix it up so that all "ret"
931 * instructions with non-zero operands have 65535 as the
932 * operand, and so that, if we're in cooked mode, all
933 * memory-reference instructions use special magic offsets
934 * in references to the link-layer header and assume that
935 * the link-layer payload begins at 0; "fix_program()"
938 switch (fix_program(handle
, &fcode
)) {
943 * Fatal error; just quit.
944 * (The "default" case shouldn't happen; we
945 * return -1 for that reason.)
951 * The program performed checks that we can't make
952 * work in the kernel.
954 can_filter_in_kernel
= 0;
959 * We have a filter that'll work in the kernel.
961 can_filter_in_kernel
= 1;
966 if (can_filter_in_kernel
) {
967 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
969 /* Installation succeded - using kernel filter. */
970 handle
->md
.use_bpf
= 1;
972 else if (err
== -1) /* Non-fatal error */
975 * Print a warning if we weren't able to install
976 * the filter for a reason other than "this kernel
977 * isn't configured to support socket filters.
979 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
981 "Warning: Kernel filter failed: %s\n",
982 pcap_strerror(errno
));
988 * If we're not using the kernel filter, get rid of any kernel
989 * filter that might've been there before, e.g. because the
990 * previous filter could work in the kernel, or because some other
991 * code attached a filter to the socket by some means other than
992 * calling "pcap_setfilter()". Otherwise, the kernel filter may
993 * filter out packets that would pass the new userland filter.
995 if (!handle
->md
.use_bpf
)
996 reset_kernel_filter(handle
);
999 * Free up the copy of the filter that was made by "fix_program()".
1001 if (fcode
.filter
!= NULL
)
1007 #endif /* SO_ATTACH_FILTER */
1013 * Set direction flag: Which packets do we accept on a forwarding
1014 * single device? IN, OUT or both?
1017 pcap_setdirection_linux(pcap_t
*handle
, direction_t d
)
1019 #ifdef HAVE_PF_PACKET_SOCKETS
1020 if (!handle
->md
.sock_packet
) {
1021 handle
->direction
= d
;
1026 * We're not using PF_PACKET sockets, so we can't determine
1027 * the direction of the packet.
1029 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1030 "Setting direction is not supported on SOCK_PACKET sockets");
1035 * Linux uses the ARP hardware type to identify the type of an
1036 * interface. pcap uses the DLT_xxx constants for this. This
1037 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1038 * constant, as arguments, and sets "handle->linktype" to the
1039 * appropriate DLT_XXX constant and sets "handle->offset" to
1040 * the appropriate value (to make "handle->offset" plus link-layer
1041 * header length be a multiple of 4, so that the link-layer payload
1042 * will be aligned on a 4-byte boundary when capturing packets).
1043 * (If the offset isn't set here, it'll be 0; add code as appropriate
1044 * for cases where it shouldn't be 0.)
1046 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1047 * in cooked mode; otherwise, we can't use cooked mode, so we have
1048 * to pick some type that works in raw mode, or fail.
1050 * Sets the link type to -1 if unable to map the type.
1052 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1058 * This is (presumably) a real Ethernet capture; give it a
1059 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1060 * that an application can let you choose it, in case you're
1061 * capturing DOCSIS traffic that a Cisco Cable Modem
1062 * Termination System is putting out onto an Ethernet (it
1063 * doesn't put an Ethernet header onto the wire, it puts raw
1064 * DOCSIS frames out on the wire inside the low-level
1065 * Ethernet framing).
1067 * XXX - are there any sorts of "fake Ethernet" that have
1068 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1069 * a Cisco CMTS won't put traffic onto it or get traffic
1070 * bridged onto it? ISDN is handled in "live_open_new()",
1071 * as we fall back on cooked mode there; are there any
1074 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1076 * If that fails, just leave the list empty.
1078 if (handle
->dlt_list
!= NULL
) {
1079 handle
->dlt_list
[0] = DLT_EN10MB
;
1080 handle
->dlt_list
[1] = DLT_DOCSIS
;
1081 handle
->dlt_count
= 2;
1085 case ARPHRD_METRICOM
:
1086 case ARPHRD_LOOPBACK
:
1087 handle
->linktype
= DLT_EN10MB
;
1092 handle
->linktype
= DLT_EN3MB
;
1096 handle
->linktype
= DLT_AX25
;
1100 handle
->linktype
= DLT_PRONET
;
1104 handle
->linktype
= DLT_CHAOS
;
1107 #ifndef ARPHRD_IEEE802_TR
1108 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1110 case ARPHRD_IEEE802_TR
:
1111 case ARPHRD_IEEE802
:
1112 handle
->linktype
= DLT_IEEE802
;
1117 handle
->linktype
= DLT_ARCNET_LINUX
;
1120 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1121 #define ARPHRD_FDDI 774
1124 handle
->linktype
= DLT_FDDI
;
1128 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1129 #define ARPHRD_ATM 19
1133 * The Classical IP implementation in ATM for Linux
1134 * supports both what RFC 1483 calls "LLC Encapsulation",
1135 * in which each packet has an LLC header, possibly
1136 * with a SNAP header as well, prepended to it, and
1137 * what RFC 1483 calls "VC Based Multiplexing", in which
1138 * different virtual circuits carry different network
1139 * layer protocols, and no header is prepended to packets.
1141 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1142 * you can't use the ARPHRD_ type to find out whether
1143 * captured packets will have an LLC header, and,
1144 * while there's a socket ioctl to *set* the encapsulation
1145 * type, there's no ioctl to *get* the encapsulation type.
1149 * programs that dissect Linux Classical IP frames
1150 * would have to check for an LLC header and,
1151 * depending on whether they see one or not, dissect
1152 * the frame as LLC-encapsulated or as raw IP (I
1153 * don't know whether there's any traffic other than
1154 * IP that would show up on the socket, or whether
1155 * there's any support for IPv6 in the Linux
1156 * Classical IP code);
1158 * filter expressions would have to compile into
1159 * code that checks for an LLC header and does
1162 * Both of those are a nuisance - and, at least on systems
1163 * that support PF_PACKET sockets, we don't have to put
1164 * up with those nuisances; instead, we can just capture
1165 * in cooked mode. That's what we'll do, if we can.
1166 * Otherwise, we'll just fail.
1169 handle
->linktype
= DLT_LINUX_SLL
;
1171 handle
->linktype
= -1;
1174 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1175 #define ARPHRD_IEEE80211 801
1177 case ARPHRD_IEEE80211
:
1178 handle
->linktype
= DLT_IEEE802_11
;
1181 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1182 #define ARPHRD_IEEE80211_PRISM 802
1184 case ARPHRD_IEEE80211_PRISM
:
1185 handle
->linktype
= DLT_PRISM_HEADER
;
1190 * Some PPP code in the kernel supplies no link-layer
1191 * header whatsoever to PF_PACKET sockets; other PPP
1192 * code supplies PPP link-layer headers ("syncppp.c");
1193 * some PPP code might supply random link-layer
1194 * headers (PPP over ISDN - there's code in Ethereal,
1195 * for example, to cope with PPP-over-ISDN captures
1196 * with which the Ethereal developers have had to cope,
1197 * heuristically trying to determine which of the
1198 * oddball link-layer headers particular packets have).
1200 * As such, we just punt, and run all PPP interfaces
1201 * in cooked mode, if we can; otherwise, we just treat
1202 * it as DLT_RAW, for now - if somebody needs to capture,
1203 * on a 2.0[.x] kernel, on PPP devices that supply a
1204 * link-layer header, they'll have to add code here to
1205 * map to the appropriate DLT_ type (possibly adding a
1206 * new DLT_ type, if necessary).
1209 handle
->linktype
= DLT_LINUX_SLL
;
1212 * XXX - handle ISDN types here? We can't fall
1213 * back on cooked sockets, so we'd have to
1214 * figure out from the device name what type of
1215 * link-layer encapsulation it's using, and map
1216 * that to an appropriate DLT_ value, meaning
1217 * we'd map "isdnN" devices to DLT_RAW (they
1218 * supply raw IP packets with no link-layer
1219 * header) and "isdY" devices to a new DLT_I4L_IP
1220 * type that has only an Ethernet packet type as
1221 * a link-layer header.
1223 * But sometimes we seem to get random crap
1224 * in the link-layer header when capturing on
1227 handle
->linktype
= DLT_RAW
;
1231 #ifndef ARPHRD_CISCO
1232 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1235 handle
->linktype
= DLT_C_HDLC
;
1238 /* Not sure if this is correct for all tunnels, but it
1242 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1250 #ifndef ARPHRD_RAWHDLC
1251 #define ARPHRD_RAWHDLC 518
1253 case ARPHRD_RAWHDLC
:
1255 #define ARPHRD_DLCI 15
1259 * XXX - should some of those be mapped to DLT_LINUX_SLL
1260 * instead? Should we just map all of them to DLT_LINUX_SLL?
1262 handle
->linktype
= DLT_RAW
;
1266 #define ARPHRD_FRAD 770
1269 handle
->linktype
= DLT_FRELAY
;
1272 case ARPHRD_LOCALTLK
:
1273 handle
->linktype
= DLT_LTALK
;
1277 #define ARPHRD_FCPP 784
1281 #define ARPHRD_FCAL 785
1285 #define ARPHRD_FCPL 786
1288 #ifndef ARPHRD_FCFABRIC
1289 #define ARPHRD_FCFABRIC 787
1291 case ARPHRD_FCFABRIC
:
1293 * We assume that those all mean RFC 2625 IP-over-
1294 * Fibre Channel, with the RFC 2625 header at
1295 * the beginning of the packet.
1297 handle
->linktype
= DLT_IP_OVER_FC
;
1301 #define ARPHRD_IRDA 783
1304 /* Don't expect IP packet out of this interfaces... */
1305 handle
->linktype
= DLT_LINUX_IRDA
;
1306 /* We need to save packet direction for IrDA decoding,
1307 * so let's use "Linux-cooked" mode. Jean II */
1308 //handle->md.cooked = 1;
1312 handle
->linktype
= -1;
1317 /* ===== Functions to interface to the newer kernels ================== */
1320 * Try to open a packet socket using the new kernel interface.
1321 * Returns 0 on failure.
1322 * FIXME: 0 uses to mean success (Sebastian)
1325 live_open_new(pcap_t
*handle
, const char *device
, int promisc
,
1326 int to_ms
, char *ebuf
)
1328 #ifdef HAVE_PF_PACKET_SOCKETS
1329 int sock_fd
= -1, arptype
;
1332 struct packet_mreq mr
;
1334 /* One shot loop used for error handling - bail out with break */
1338 * Open a socket with protocol family packet. If a device is
1339 * given we try to open it in raw mode otherwise we use
1340 * the cooked interface.
1343 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
1344 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
1346 if (sock_fd
== -1) {
1347 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
1348 pcap_strerror(errno
) );
1352 /* It seems the kernel supports the new interface. */
1353 handle
->md
.sock_packet
= 0;
1356 * Get the interface index of the loopback device.
1357 * If the attempt fails, don't fail, just set the
1358 * "md.lo_ifindex" to -1.
1360 * XXX - can there be more than one device that loops
1361 * packets back, i.e. devices other than "lo"? If so,
1362 * we'd need to find them all, and have an array of
1363 * indices for them, and check all of them in
1364 * "pcap_read_packet()".
1366 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", ebuf
);
1369 * Default value for offset to align link-layer payload
1370 * on a 4-byte boundary.
1375 * What kind of frames do we have to deal with? Fall back
1376 * to cooked mode if we have an unknown interface type.
1380 /* Assume for now we don't need cooked mode. */
1381 handle
->md
.cooked
= 0;
1383 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1384 if (arptype
== -1) {
1388 map_arphrd_to_dlt(handle
, arptype
, 1);
1389 if (handle
->linktype
== -1 ||
1390 handle
->linktype
== DLT_LINUX_SLL
||
1391 handle
->linktype
== DLT_LINUX_IRDA
||
1392 (handle
->linktype
== DLT_EN10MB
&&
1393 (strncmp("isdn", device
, 4) == 0 ||
1394 strncmp("isdY", device
, 4) == 0))) {
1396 * Unknown interface type (-1), or a
1397 * device we explicitly chose to run
1398 * in cooked mode (e.g., PPP devices),
1399 * or an ISDN device (whose link-layer
1400 * type we can only determine by using
1401 * APIs that may be different on different
1402 * kernels) - reopen in cooked mode.
1404 if (close(sock_fd
) == -1) {
1405 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1406 "close: %s", pcap_strerror(errno
));
1409 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1411 if (sock_fd
== -1) {
1412 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1413 "socket: %s", pcap_strerror(errno
));
1416 handle
->md
.cooked
= 1;
1419 * Get rid of any link-layer type list
1420 * we allocated - this only supports cooked
1423 if (handle
->dlt_list
!= NULL
) {
1424 free(handle
->dlt_list
);
1425 handle
->dlt_list
= NULL
;
1426 handle
->dlt_count
= 0;
1429 if (handle
->linktype
== -1) {
1431 * Warn that we're falling back on
1432 * cooked mode; we may want to
1433 * update "map_arphrd_to_dlt()"
1434 * to handle the new type.
1436 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1438 "supported by libpcap - "
1439 "falling back to cooked "
1443 /* IrDA capture is not a real "cooked" capture,
1444 * it's IrLAP frames, not IP packets. */
1445 if (handle
->linktype
!= DLT_LINUX_IRDA
)
1446 handle
->linktype
= DLT_LINUX_SLL
;
1449 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
, ebuf
);
1450 if (handle
->md
.ifindex
== -1)
1453 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
1461 * This is cooked mode.
1463 handle
->md
.cooked
= 1;
1464 handle
->linktype
= DLT_LINUX_SLL
;
1467 * We're not bound to a device.
1468 * XXX - true? Or true only if we're using
1470 * For now, we're using this as an indication
1471 * that we can't transmit; stop doing that only
1472 * if we figure out how to transmit in cooked
1475 handle
->md
.ifindex
= -1;
1479 * Select promiscuous mode on if "promisc" is set.
1481 * Do not turn allmulti mode on if we don't select
1482 * promiscuous mode - on some devices (e.g., Orinoco
1483 * wireless interfaces), allmulti mode isn't supported
1484 * and the driver implements it by turning promiscuous
1485 * mode on, and that screws up the operation of the
1486 * card as a normal networking interface, and on no
1487 * other platform I know of does starting a non-
1488 * promiscuous capture affect which multicast packets
1489 * are received by the interface.
1493 * Hmm, how can we set promiscuous mode on all interfaces?
1494 * I am not sure if that is possible at all.
1497 if (device
&& promisc
) {
1498 memset(&mr
, 0, sizeof(mr
));
1499 mr
.mr_ifindex
= handle
->md
.ifindex
;
1500 mr
.mr_type
= PACKET_MR_PROMISC
;
1501 if (setsockopt(sock_fd
, SOL_PACKET
,
1502 PACKET_ADD_MEMBERSHIP
, &mr
, sizeof(mr
)) == -1)
1504 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1505 "setsockopt: %s", pcap_strerror(errno
));
1510 /* Save the socket FD in the pcap structure */
1512 handle
->fd
= sock_fd
;
1523 * Get rid of any link-layer type list we allocated.
1525 if (handle
->dlt_list
!= NULL
)
1526 free(handle
->dlt_list
);
1532 "New packet capturing interface not supported by build "
1533 "environment", PCAP_ERRBUF_SIZE
);
1538 #ifdef HAVE_PF_PACKET_SOCKETS
1540 * Return the index of the given device name. Fill ebuf and return
1544 iface_get_id(int fd
, const char *device
, char *ebuf
)
1548 memset(&ifr
, 0, sizeof(ifr
));
1549 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1551 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
1552 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1553 "ioctl: %s", pcap_strerror(errno
));
1557 return ifr
.ifr_ifindex
;
1561 * Bind the socket associated with FD to the given device.
1564 iface_bind(int fd
, int ifindex
, char *ebuf
)
1566 struct sockaddr_ll sll
;
1568 socklen_t errlen
= sizeof(err
);
1570 memset(&sll
, 0, sizeof(sll
));
1571 sll
.sll_family
= AF_PACKET
;
1572 sll
.sll_ifindex
= ifindex
;
1573 sll
.sll_protocol
= htons(ETH_P_ALL
);
1575 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
1576 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1577 "bind: %s", pcap_strerror(errno
));
1581 /* Any pending errors, e.g., network is down? */
1583 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
1584 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1585 "getsockopt: %s", pcap_strerror(errno
));
1590 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1591 "bind: %s", pcap_strerror(err
));
1601 /* ===== Functions to interface to the older kernels ================== */
1604 * With older kernels promiscuous mode is kind of interesting because we
1605 * have to reset the interface before exiting. The problem can't really
1606 * be solved without some daemon taking care of managing usage counts.
1607 * If we put the interface into promiscuous mode, we set a flag indicating
1608 * that we must take it out of that mode when the interface is closed,
1609 * and, when closing the interface, if that flag is set we take it out
1610 * of promiscuous mode.
1614 * List of pcaps for which we turned promiscuous mode on by hand.
1615 * If there are any such pcaps, we arrange to call "pcap_close_all()"
1616 * when we exit, and have it close all of them to turn promiscuous mode
1619 static struct pcap
*pcaps_to_close
;
1622 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1623 * be called on exit.
1625 static int did_atexit
;
1627 static void pcap_close_all(void)
1629 struct pcap
*handle
;
1631 while ((handle
= pcaps_to_close
) != NULL
)
1635 static void pcap_close_linux( pcap_t
*handle
)
1637 struct pcap
*p
, *prevp
;
1640 if (handle
->md
.clear_promisc
) {
1642 * We put the interface into promiscuous mode; take
1643 * it out of promiscuous mode.
1645 * XXX - if somebody else wants it in promiscuous mode,
1646 * this code cannot know that, so it'll take it out
1647 * of promiscuous mode. That's not fixable in 2.0[.x]
1650 memset(&ifr
, 0, sizeof(ifr
));
1651 strncpy(ifr
.ifr_name
, handle
->md
.device
, sizeof(ifr
.ifr_name
));
1652 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1654 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1655 "Please adjust manually.\n"
1656 "Hint: This can't happen with Linux >= 2.2.0.\n",
1659 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1661 * Promiscuous mode is currently on; turn it
1664 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1665 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1667 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1668 "Please adjust manually.\n"
1669 "Hint: This can't happen with Linux >= 2.2.0.\n",
1676 * Take this pcap out of the list of pcaps for which we
1677 * have to take the interface out of promiscuous mode.
1679 for (p
= pcaps_to_close
, prevp
= NULL
; p
!= NULL
;
1680 prevp
= p
, p
= p
->md
.next
) {
1683 * Found it. Remove it from the list.
1685 if (prevp
== NULL
) {
1687 * It was at the head of the list.
1689 pcaps_to_close
= p
->md
.next
;
1692 * It was in the middle of the list.
1694 prevp
->md
.next
= p
->md
.next
;
1701 if (handle
->md
.device
!= NULL
)
1702 free(handle
->md
.device
);
1703 handle
->md
.device
= NULL
;
1704 pcap_close_common(handle
);
1708 * Try to open a packet socket using the old kernel interface.
1709 * Returns 0 on failure.
1710 * FIXME: 0 uses to mean success (Sebastian)
1713 live_open_old(pcap_t
*handle
, const char *device
, int promisc
,
1714 int to_ms
, char *ebuf
)
1720 /* Open the socket */
1722 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
1723 if (handle
->fd
== -1) {
1724 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1725 "socket: %s", pcap_strerror(errno
));
1729 /* It worked - we are using the old interface */
1730 handle
->md
.sock_packet
= 1;
1732 /* ...which means we get the link-layer header. */
1733 handle
->md
.cooked
= 0;
1735 /* Bind to the given device */
1738 strncpy(ebuf
, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
1742 if (iface_bind_old(handle
->fd
, device
, ebuf
) == -1)
1746 * Try to get the link-layer type.
1748 arptype
= iface_get_arptype(handle
->fd
, device
, ebuf
);
1753 * Try to find the DLT_ type corresponding to that
1756 map_arphrd_to_dlt(handle
, arptype
, 0);
1757 if (handle
->linktype
== -1) {
1758 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1759 "unknown arptype %d", arptype
);
1763 /* Go to promisc mode if requested */
1766 memset(&ifr
, 0, sizeof(ifr
));
1767 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1768 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1769 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1770 "ioctl: %s", pcap_strerror(errno
));
1773 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
1775 * Promiscuous mode isn't currently on,
1776 * so turn it on, and remember that
1777 * we should turn it off when the
1782 * If we haven't already done so, arrange
1783 * to have "pcap_close_all()" called when
1787 if (atexit(pcap_close_all
) == -1) {
1789 * "atexit()" failed; don't
1790 * put the interface in
1791 * promiscuous mode, just
1794 strncpy(ebuf
, "atexit failed",
1801 ifr
.ifr_flags
|= IFF_PROMISC
;
1802 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1803 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1805 pcap_strerror(errno
));
1808 handle
->md
.clear_promisc
= 1;
1811 * Add this to the list of pcaps
1812 * to close when we exit.
1814 handle
->md
.next
= pcaps_to_close
;
1815 pcaps_to_close
= handle
;
1820 * Default value for offset to align link-layer payload
1821 * on a 4-byte boundary.
1829 pcap_close_linux(handle
);
1834 * Bind the socket associated with FD to the given device using the
1835 * interface of the old kernels.
1838 iface_bind_old(int fd
, const char *device
, char *ebuf
)
1840 struct sockaddr saddr
;
1842 socklen_t errlen
= sizeof(err
);
1844 memset(&saddr
, 0, sizeof(saddr
));
1845 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
1846 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
1847 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1848 "bind: %s", pcap_strerror(errno
));
1852 /* Any pending errors, e.g., network is down? */
1854 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
1855 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1856 "getsockopt: %s", pcap_strerror(errno
));
1861 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1862 "bind: %s", pcap_strerror(err
));
1870 /* ===== System calls available on all supported kernels ============== */
1873 * Query the kernel for the MTU of the given interface.
1876 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
1881 return BIGGER_THAN_ALL_MTUS
;
1883 memset(&ifr
, 0, sizeof(ifr
));
1884 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1886 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
1887 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1888 "ioctl: %s", pcap_strerror(errno
));
1896 * Get the hardware type of the given interface as ARPHRD_xxx constant.
1899 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
1903 memset(&ifr
, 0, sizeof(ifr
));
1904 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1906 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
1907 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1908 "ioctl: %s", pcap_strerror(errno
));
1912 return ifr
.ifr_hwaddr
.sa_family
;
1915 #ifdef SO_ATTACH_FILTER
1917 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
1921 register struct bpf_insn
*p
;
1926 * Make a copy of the filter, and modify that copy if
1929 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
1930 len
= handle
->fcode
.bf_len
;
1931 f
= (struct bpf_insn
*)malloc(prog_size
);
1933 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1934 "malloc: %s", pcap_strerror(errno
));
1937 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
1939 fcode
->filter
= (struct sock_filter
*) f
;
1941 for (i
= 0; i
< len
; ++i
) {
1944 * What type of instruction is this?
1946 switch (BPF_CLASS(p
->code
)) {
1950 * It's a return instruction; is the snapshot
1951 * length a constant, rather than the contents
1952 * of the accumulator?
1954 if (BPF_MODE(p
->code
) == BPF_K
) {
1956 * Yes - if the value to be returned,
1957 * i.e. the snapshot length, is anything
1958 * other than 0, make it 65535, so that
1959 * the packet is truncated by "recvfrom()",
1960 * not by the filter.
1962 * XXX - there's nothing we can easily do
1963 * if it's getting the value from the
1964 * accumulator; we'd have to insert
1965 * code to force non-zero values to be
1976 * It's a load instruction; is it loading
1979 switch (BPF_MODE(p
->code
)) {
1985 * Yes; are we in cooked mode?
1987 if (handle
->md
.cooked
) {
1989 * Yes, so we need to fix this
1992 if (fix_offset(p
) < 0) {
1994 * We failed to do so.
1995 * Return 0, so our caller
1996 * knows to punt to userland.
2006 return 1; /* we succeeded */
2010 fix_offset(struct bpf_insn
*p
)
2013 * What's the offset?
2015 if (p
->k
>= SLL_HDR_LEN
) {
2017 * It's within the link-layer payload; that starts at an
2018 * offset of 0, as far as the kernel packet filter is
2019 * concerned, so subtract the length of the link-layer
2022 p
->k
-= SLL_HDR_LEN
;
2023 } else if (p
->k
== 14) {
2025 * It's the protocol field; map it to the special magic
2026 * kernel offset for that field.
2028 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
2031 * It's within the header, but it's not one of those
2032 * fields; we can't do that in the kernel, so punt
2041 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
2043 int total_filter_on
= 0;
2049 * The socket filter code doesn't discard all packets queued
2050 * up on the socket when the filter is changed; this means
2051 * that packets that don't match the new filter may show up
2052 * after the new filter is put onto the socket, if those
2053 * packets haven't yet been read.
2055 * This means, for example, that if you do a tcpdump capture
2056 * with a filter, the first few packets in the capture might
2057 * be packets that wouldn't have passed the filter.
2059 * We therefore discard all packets queued up on the socket
2060 * when setting a kernel filter. (This isn't an issue for
2061 * userland filters, as the userland filtering is done after
2062 * packets are queued up.)
2064 * To flush those packets, we put the socket in read-only mode,
2065 * and read packets from the socket until there are no more to
2068 * In order to keep that from being an infinite loop - i.e.,
2069 * to keep more packets from arriving while we're draining
2070 * the queue - we put the "total filter", which is a filter
2071 * that rejects all packets, onto the socket before draining
2074 * This code deliberately ignores any errors, so that you may
2075 * get bogus packets if an error occurs, rather than having
2076 * the filtering done in userland even if it could have been
2077 * done in the kernel.
2079 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2080 &total_fcode
, sizeof(total_fcode
)) == 0) {
2084 * Note that we've put the total filter onto the socket.
2086 total_filter_on
= 1;
2089 * Save the socket's current mode, and put it in
2090 * non-blocking mode; we drain it by reading packets
2091 * until we get an error (which is normally a
2092 * "nothing more to be read" error).
2094 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
2095 if (save_mode
!= -1 &&
2096 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
2097 while (recv(handle
->fd
, &drain
, sizeof drain
,
2101 fcntl(handle
->fd
, F_SETFL
, save_mode
);
2102 if (save_errno
!= EAGAIN
) {
2104 reset_kernel_filter(handle
);
2105 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2106 "recv: %s", pcap_strerror(save_errno
));
2113 * Now attach the new filter.
2115 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2116 fcode
, sizeof(*fcode
));
2117 if (ret
== -1 && total_filter_on
) {
2119 * Well, we couldn't set that filter on the socket,
2120 * but we could set the total filter on the socket.
2122 * This could, for example, mean that the filter was
2123 * too big to put into the kernel, so we'll have to
2124 * filter in userland; in any case, we'll be doing
2125 * filtering in userland, so we need to remove the
2126 * total filter so we see packets.
2131 * XXX - if this fails, we're really screwed;
2132 * we have the total filter on the socket,
2133 * and it won't come off. What do we do then?
2135 reset_kernel_filter(handle
);
2143 reset_kernel_filter(pcap_t
*handle
)
2145 /* setsockopt() barfs unless it get a dummy parameter */
2148 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
2149 &dummy
, sizeof(dummy
));