]>
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.
28 static const char rcsid
[] =
29 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.70 2001-10-25 08:27:18 guy Exp $ (LBL)";
33 * Known problems with 2.0[.x] kernels:
35 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
36 * if we use PF_PACKET, we can filter out the transmitted version
37 * of the packet by using data in the "sockaddr_ll" returned by
38 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
39 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
40 * "sockaddr_pkt" which doesn't give us enough information to let
43 * - We have to set the interface's IFF_PROMISC flag ourselves, if
44 * we're to run in promiscuous mode, which means we have to turn
45 * it off ourselves when we're done; the kernel doesn't keep track
46 * of how many sockets are listening promiscuously, which means
47 * it won't get turned off automatically when no sockets are
48 * listening promiscuously. We catch "pcap_close()" and, for
49 * interfaces we put into promiscuous mode, take them out of
50 * promiscuous mode - which isn't necessarily the right thing to
51 * do, if another socket also requested promiscuous mode between
52 * the time when we opened the socket and the time when we close
55 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
56 * return the amount of data that you could have read, rather than
57 * the amount that was returned, so we can't just allocate a buffer
58 * whose size is the snapshot length and pass the snapshot length
59 * as the byte count, and also pass MSG_TRUNC, so that the return
60 * value tells us how long the packet was on the wire.
62 * This means that, if we want to get the actual size of the packet,
63 * so we can return it in the "len" field of the packet header,
64 * we have to read the entire packet, not just the part that fits
65 * within the snapshot length, and thus waste CPU time copying data
66 * from the kernel that our caller won't see.
68 * We have to get the actual size, and supply it in "len", because
69 * otherwise, the IP dissector in tcpdump, for example, will complain
70 * about "truncated-ip", as the packet will appear to have been
71 * shorter, on the wire, than the IP header said it should have been.
87 #include <sys/socket.h>
88 #include <sys/ioctl.h>
89 #include <sys/utsname.h>
91 #include <netinet/in.h>
92 #include <linux/if_ether.h>
93 #include <net/if_arp.h>
96 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
97 * sockets rather than SOCK_PACKET sockets.
99 * To use them, we include <linux/if_packet.h> rather than
100 * <netpacket/packet.h>; we do so because
102 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
103 * later kernels and libc5, and don't provide a <netpacket/packet.h>
106 * not all versions of glibc2 have a <netpacket/packet.h> file
107 * that defines stuff needed for some of the 2.4-or-later-kernel
108 * features, so if the system has a 2.4 or later kernel, we
109 * still can't use those features.
111 * We're already including a number of other <linux/XXX.h> headers, and
112 * this code is Linux-specific (no other OS has PF_PACKET sockets as
113 * a raw packet capture mechanism), so it's not as if you gain any
114 * useful portability by using <netpacket/packet.h>
116 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
117 * isn't defined? It only defines one data structure in 2.0.x, so
118 * it shouldn't cause any problems.
121 # include <linux/if_packet.h>
124 * On at least some Linux distributions (for example, Red Hat 5.2),
125 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
126 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
127 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
128 * the PACKET_xxx stuff.
130 * So we check whether PACKET_HOST is defined, and assume that we have
131 * PF_PACKET sockets only if it is defined.
134 # define HAVE_PF_PACKET_SOCKETS
135 # endif /* PACKET_HOST */
136 #endif /* PF_PACKET */
138 #ifdef SO_ATTACH_FILTER
139 #include <linux/types.h>
140 #include <linux/filter.h>
144 typedef int socklen_t
;
149 * This is being compiled on a system that lacks MSG_TRUNC; define it
150 * with the value it has in the 2.2 and later kernels, so that, on
151 * those kernels, when we pass it in the flags argument to "recvfrom()"
152 * we're passing the right value and thus get the MSG_TRUNC behavior
153 * we want. (We don't get that behavior on 2.0[.x] kernels, because
154 * they didn't support MSG_TRUNC.)
156 #define MSG_TRUNC 0x20
159 #define MAX_LINKHEADER_SIZE 256
162 * When capturing on all interfaces we use this as the buffer size.
163 * Should be bigger then all MTUs that occur in real life.
164 * 64kB should be enough for now.
166 #define BIGGER_THAN_ALL_MTUS (64*1024)
169 * Prototypes for internal functions
171 static void map_arphrd_to_dlt(pcap_t
*, int);
172 static int live_open_old(pcap_t
*, char *, int, int, char *);
173 static int live_open_new(pcap_t
*, char *, int, int, char *);
174 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
177 * Wrap some ioctl calls
179 #ifdef HAVE_PF_PACKET_SOCKETS
180 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
182 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
183 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
184 #ifdef HAVE_PF_PACKET_SOCKETS
185 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
187 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
189 #ifdef SO_ATTACH_FILTER
190 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
191 static int fix_offset(struct bpf_insn
*p
);
192 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
193 static int reset_kernel_filter(pcap_t
*handle
);
195 static struct sock_filter total_insn
196 = BPF_STMT(BPF_RET
| BPF_K
, 0);
197 static struct sock_fprog total_fcode
198 = { 1, &total_insn
};
202 * Get a handle for a live capture from the given device. You can
203 * pass NULL as device to get all packages (without link level
204 * information of course). If you pass 1 as promisc the interface
205 * will be set to promiscous mode (XXX: I think this usage should
206 * be deprecated and functions be added to select that later allow
207 * modification of that values -- Torsten).
212 pcap_open_live(char *device
, int snaplen
, int promisc
, int to_ms
, char *ebuf
)
216 struct utsname utsname
;
218 /* Allocate a handle for this session. */
220 handle
= malloc(sizeof(*handle
));
221 if (handle
== NULL
) {
222 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
223 pcap_strerror(errno
));
227 /* Initialize some components of the pcap structure. */
229 memset(handle
, 0, sizeof(*handle
));
230 handle
->snapshot
= snaplen
;
231 handle
->md
.timeout
= to_ms
;
234 * NULL and "any" are special devices which give us the hint to
235 * monitor all devices.
237 if (!device
|| strcmp(device
, "any") == 0) {
239 handle
->md
.device
= strdup("any");
242 /* Just a warning. */
243 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
244 "Promiscuous mode not supported on the \"any\" device");
248 handle
->md
.device
= strdup(device
);
250 if (handle
->md
.device
== NULL
) {
251 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
252 pcap_strerror(errno
) );
258 * Current Linux kernels use the protocol family PF_PACKET to
259 * allow direct access to all packets on the network while
260 * older kernels had a special socket type SOCK_PACKET to
261 * implement this feature.
262 * While this old implementation is kind of obsolete we need
263 * to be compatible with older kernels for a while so we are
264 * trying both methods with the newer method preferred.
267 if (! (live_open_new(handle
, device
, promisc
, to_ms
, ebuf
) ||
268 live_open_old(handle
, device
, promisc
, to_ms
, ebuf
)) )
271 * Both methods to open the packet socket failed. Tidy
272 * up and report our failure (ebuf is expected to be
273 * set by the functions above).
276 free(handle
->md
.device
);
282 * Compute the buffer size.
284 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
285 * and might require special handling - check.
287 if (handle
->md
.sock_packet
&& (uname(&utsname
) < 0 ||
288 strncmp(utsname
.release
, "2.0", 3) == 0)) {
290 * We're using a SOCK_PACKET structure, and either
291 * we couldn't find out what kernel release this is,
292 * or it's a 2.0[.x] kernel.
294 * In the 2.0[.x] kernel, a "recvfrom()" on
295 * a SOCK_PACKET socket, with MSG_TRUNC set, will
296 * return the number of bytes read, so if we pass
297 * a length based on the snapshot length, it'll
298 * return the number of bytes from the packet
299 * copied to userland, not the actual length
302 * This means that, for example, the IP dissector
303 * in tcpdump will get handed a packet length less
304 * than the length in the IP header, and will
305 * complain about "truncated-ip".
307 * So we don't bother trying to copy from the
308 * kernel only the bytes in which we're interested,
309 * but instead copy them all, just as the older
310 * versions of libpcap for Linux did.
312 * The buffer therefore needs to be big enough to
313 * hold the largest packet we can get from this
314 * device. Unfortunately, we can't get the MRU
315 * of the network; we can only get the MTU. The
316 * MTU may be too small, in which case a packet larger
317 * than the buffer size will be truncated *and* we
318 * won't get the actual packet size.
320 * However, if the snapshot length is larger than
321 * the buffer size based on the MTU, we use the
322 * snapshot length as the buffer size, instead;
323 * this means that with a sufficiently large snapshot
324 * length we won't artificially truncate packets
325 * to the MTU-based size.
327 * This mess just one of many problems with packet
328 * capture on 2.0[.x] kernels; you really want a
329 * 2.2[.x] or later kernel if you want packet capture
332 mtu
= iface_get_mtu(handle
->fd
, device
, ebuf
);
335 free(handle
->md
.device
);
339 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
340 if (handle
->bufsize
< handle
->snapshot
)
341 handle
->bufsize
= handle
->snapshot
;
344 * This is a 2.2[.x] or later kernel (we know that
345 * either because we're not using a SOCK_PACKET
346 * socket - PF_PACKET is supported only in 2.2
347 * and later kernels - or because we checked the
350 * We can safely pass "recvfrom()" a byte count
351 * based on the snapshot length.
353 handle
->bufsize
= handle
->snapshot
;
356 /* Allocate the buffer */
358 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
359 if (!handle
->buffer
) {
360 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
361 "malloc: %s", pcap_strerror(errno
));
363 free(handle
->md
.device
);
372 * Read at most max_packets from the capture stream and call the callback
373 * for each of them. Returns the number of packets handled or -1 if an
377 pcap_read(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
380 * Currently, on Linux only one packet is delivered per read,
383 return pcap_read_packet(handle
, callback
, user
);
387 * Read a packet from the socket calling the handler provided by
388 * the user. Returns the number of packets received or -1 if an
392 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
396 #ifdef HAVE_PF_PACKET_SOCKETS
397 struct sockaddr_ll from
;
398 struct sll_header
*hdrp
;
400 struct sockaddr from
;
403 int packet_len
, caplen
;
404 struct pcap_pkthdr pcap_header
;
406 #ifdef HAVE_PF_PACKET_SOCKETS
408 * If this is a cooked device, leave extra room for a
409 * fake packet header.
411 if (handle
->md
.cooked
)
412 offset
= SLL_HDR_LEN
;
417 * This system doesn't have PF_PACKET sockets, so it doesn't
418 * support cooked devices.
423 /* Receive a single packet from the kernel */
425 bp
= handle
->buffer
+ handle
->offset
;
427 fromlen
= sizeof(from
);
428 packet_len
= recvfrom(
429 handle
->fd
, bp
+ offset
,
430 handle
->bufsize
- offset
, MSG_TRUNC
,
431 (struct sockaddr
*) &from
, &fromlen
);
432 } while (packet_len
== -1 && errno
== EINTR
);
434 /* Check if an error occured */
436 if (packet_len
== -1) {
438 return 0; /* no packet there */
440 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
441 "recvfrom: %s", pcap_strerror(errno
));
446 #ifdef HAVE_PF_PACKET_SOCKETS
448 * If this is from the loopback device, reject outgoing packets;
449 * we'll see the packet as an incoming packet as well, and
450 * we don't want to see it twice.
452 * We can only do this if we're using PF_PACKET; the address
453 * returned for SOCK_PACKET is a "sockaddr_pkt" which lacks
454 * the relevant packet type information.
456 if (!handle
->md
.sock_packet
&&
457 from
.sll_ifindex
== handle
->md
.lo_ifindex
&&
458 from
.sll_pkttype
== PACKET_OUTGOING
)
462 #ifdef HAVE_PF_PACKET_SOCKETS
464 * If this is a cooked device, fill in the fake packet header.
466 if (handle
->md
.cooked
) {
468 * Add the length of the fake header to the length
469 * of packet data we read.
471 packet_len
+= SLL_HDR_LEN
;
473 hdrp
= (struct sll_header
*)bp
;
476 * Map the PACKET_ value to a LINUX_SLL_ value; we
477 * want the same numerical value to be used in
478 * the link-layer header even if the numerical values
479 * for the PACKET_ #defines change, so that programs
480 * that look at the packet type field will always be
481 * able to handle DLT_LINUX_SLL captures.
483 switch (from
.sll_pkttype
) {
486 hdrp
->sll_pkttype
= htons(LINUX_SLL_HOST
);
489 case PACKET_BROADCAST
:
490 hdrp
->sll_pkttype
= htons(LINUX_SLL_BROADCAST
);
493 case PACKET_MULTICAST
:
494 hdrp
->sll_pkttype
= htons(LINUX_SLL_MULTICAST
);
497 case PACKET_OTHERHOST
:
498 hdrp
->sll_pkttype
= htons(LINUX_SLL_OTHERHOST
);
501 case PACKET_OUTGOING
:
502 hdrp
->sll_pkttype
= htons(LINUX_SLL_OUTGOING
);
506 hdrp
->sll_pkttype
= -1;
510 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
511 hdrp
->sll_halen
= htons(from
.sll_halen
);
512 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
513 (from
.sll_halen
> SLL_ADDRLEN
) ?
516 hdrp
->sll_protocol
= from
.sll_protocol
;
521 * XXX: According to the kernel source we should get the real
522 * packet len if calling recvfrom with MSG_TRUNC set. It does
523 * not seem to work here :(, but it is supported by this code
525 * To be honest the code RELIES on that feature so this is really
526 * broken with 2.2.x kernels.
527 * I spend a day to figure out what's going on and I found out
528 * that the following is happening:
530 * The packet comes from a random interface and the packet_rcv
531 * hook is called with a clone of the packet. That code inserts
532 * the packet into the receive queue of the packet socket.
533 * If a filter is attached to that socket that filter is run
534 * first - and there lies the problem. The default filter always
535 * cuts the packet at the snaplen:
540 * So the packet filter cuts down the packet. The recvfrom call
541 * says "hey, it's only 68 bytes, it fits into the buffer" with
542 * the result that we don't get the real packet length. This
543 * is valid at least until kernel 2.2.17pre6.
545 * We currently handle this by making a copy of the filter
546 * program, fixing all "ret" instructions with non-zero
547 * operands to have an operand of 65535 so that the filter
548 * doesn't truncate the packet, and supplying that modified
549 * filter to the kernel.
553 if (caplen
> handle
->snapshot
)
554 caplen
= handle
->snapshot
;
556 /* Run the packet filter if not using kernel filter */
557 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
558 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
559 packet_len
, caplen
) == 0)
561 /* rejected by filter */
566 /* Fill in our own header data */
568 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
569 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
570 "ioctl: %s", pcap_strerror(errno
));
573 pcap_header
.caplen
= caplen
;
574 pcap_header
.len
= packet_len
;
579 * Arguably, we should count them before we check the filter,
580 * as on many other platforms "ps_recv" counts packets
581 * handed to the filter rather than packets that passed
582 * the filter, but if filtering is done in the kernel, we
583 * can't get a count of packets that passed the filter,
584 * and that would mean the meaning of "ps_recv" wouldn't
585 * be the same on all Linux systems.
587 * XXX - it's not the same on all systems in any case;
588 * ideally, we should have a "get the statistics" call
589 * that supplies more counts and indicates which of them
590 * it supplies, so that we supply a count of packets
591 * handed to the filter only on platforms where that
592 * information is available.
594 * We count them here even if we can get the packet count
595 * from the kernel, as we can only determine at run time
596 * whether we'll be able to get it from the kernel (if
597 * HAVE_TPACKET_STATS isn't defined, we can't get it from
598 * the kernel, but if it is defined, the library might
599 * have been built with a 2.4 or later kernel, but we
600 * might be running on a 2.2[.x] kernel without Alexey
601 * Kuznetzov's turbopacket patches, and thus the kernel
602 * might not be able to supply those statistics). We
603 * could, I guess, try, when opening the socket, to get
604 * the statistics, and if we can not increment the count
605 * here, but it's not clear that always incrementing
606 * the count is more expensive than always testing a flag
609 handle
->md
.stat
.ps_recv
++;
611 /* Call the user supplied callback function */
612 callback(userdata
, &pcap_header
, bp
);
618 * Get the statistics for the given packet capture handle.
619 * Reports the number of dropped packets iff the kernel supports
620 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
621 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
622 * patches); otherwise, that information isn't available, and we lie
623 * and report 0 as the count of dropped packets.
626 pcap_stats(pcap_t
*handle
, struct pcap_stat
*stats
)
628 #ifdef HAVE_TPACKET_STATS
629 struct tpacket_stats kstats
;
633 * Try to get the packet counts from the kernel.
635 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
636 &kstats
, &len
) > -1) {
637 handle
->md
.stat
.ps_recv
= (kstats
.tp_packets
- kstats
.tp_drops
);
638 handle
->md
.stat
.ps_drop
= kstats
.tp_drops
;
642 * "ps_recv" counts only packets that passed the filter.
644 * "ps_drop" is maintained only on systems that support
645 * the PACKET_STATISTICS "getsockopt()" argument.
647 *stats
= handle
->md
.stat
;
652 * Attach the given BPF code to the packet capture device.
655 pcap_setfilter(pcap_t
*handle
, struct bpf_program
*filter
)
657 #ifdef SO_ATTACH_FILTER
658 struct sock_fprog fcode
;
659 int can_filter_in_kernel
;
665 strncpy(handle
->errbuf
, "setfilter: No filter specified",
666 sizeof(handle
->errbuf
));
670 /* Make our private copy of the filter */
672 if (install_bpf_program(handle
, filter
) < 0) {
673 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
674 "malloc: %s", pcap_strerror(errno
));
679 * Run user level packet filter by default. Will be overriden if
680 * installing a kernel filter succeeds.
682 handle
->md
.use_bpf
= 0;
685 * If we're reading from a savefile, don't try to install
688 if (handle
->sf
.rfile
!= NULL
)
691 /* Install kernel level filter if possible */
693 #ifdef SO_ATTACH_FILTER
695 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
697 * fcode.len is an unsigned short for current kernel.
698 * I have yet to see BPF-Code with that much
699 * instructions but still it is possible. So for the
700 * sake of correctness I added this check.
702 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
704 can_filter_in_kernel
= 0;
706 #endif /* USHRT_MAX */
709 * Oh joy, the Linux kernel uses struct sock_fprog instead
710 * of struct bpf_program and of course the length field is
711 * of different size. Pointed out by Sebastian
713 * Oh, and we also need to fix it up so that all "ret"
714 * instructions with non-zero operands have 65535 as the
715 * operand, and so that, if we're in cooked mode, all
716 * memory-reference instructions use special magic offsets
717 * in references to the link-layer header and assume that
718 * the link-layer payload begins at 0; "fix_program()"
721 switch (fix_program(handle
, &fcode
)) {
726 * Fatal error; just quit.
727 * (The "default" case shouldn't happen; we
728 * return -1 for that reason.)
734 * The program performed checks that we can't make
735 * work in the kernel.
737 can_filter_in_kernel
= 0;
742 * We have a filter that'll work in the kernel.
744 can_filter_in_kernel
= 1;
749 if (can_filter_in_kernel
) {
750 if (set_kernel_filter(handle
, &fcode
) == 0)
752 /* Installation succeded - using kernel filter. */
753 handle
->md
.use_bpf
= 1;
758 * Print a warning if we weren't able to install
759 * the filter for a reason other than "this kernel
760 * isn't configured to support socket filters.
762 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
764 "Warning: Kernel filter failed: %s\n",
765 pcap_strerror(errno
));
771 * If we're not using the kernel filter, get rid of any kernel
772 * filter that might've been there before, e.g. because the
773 * previous filter could work in the kernel, or because some other
774 * code attached a filter to the socket by some means other than
775 * calling "pcap_setfilter()". Otherwise, the kernel filter may
776 * filter out packets that would pass the new userland filter.
778 if (!handle
->md
.use_bpf
)
779 reset_kernel_filter(handle
);
782 * Free up the copy of the filter that was made by "fix_program()".
784 if (fcode
.filter
!= NULL
)
786 #endif /* SO_ATTACH_FILTER */
792 * Linux uses the ARP hardware type to identify the type of an
793 * interface. pcap uses the DLT_xxx constants for this. This
794 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
795 * constant, as arguments, and sets "handle->linktype" to the
796 * appropriate DLT_XXX constant and sets "handle->offset" to
797 * the appropriate value (to make "handle->offset" plus link-layer
798 * header length be a multiple of 4, so that the link-layer payload
799 * will be aligned on a 4-byte boundary when capturing packets).
800 * (If the offset isn't set here, it'll be 0; add code as appropriate
801 * for cases where it shouldn't be 0.)
803 * Sets the link type to -1 if unable to map the type.
805 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
)
810 case ARPHRD_METRICOM
:
811 case ARPHRD_LOOPBACK
:
812 handle
->linktype
= DLT_EN10MB
;
817 handle
->linktype
= DLT_EN3MB
;
821 handle
->linktype
= DLT_AX25
;
825 handle
->linktype
= DLT_PRONET
;
829 handle
->linktype
= DLT_CHAOS
;
832 #ifndef ARPHRD_IEEE802_TR
833 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
835 case ARPHRD_IEEE802_TR
:
837 handle
->linktype
= DLT_IEEE802
;
842 handle
->linktype
= DLT_ARCNET
;
846 handle
->linktype
= DLT_FDDI
;
850 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
851 #define ARPHRD_ATM 19
855 * The Classical IP implementation in ATM for Linux
856 * supports both what RFC 1483 calls "LLC Encapsulation",
857 * in which each packet has an LLC header, possibly
858 * with a SNAP header as well, prepended to it, and
859 * what RFC 1483 calls "VC Based Multiplexing", in which
860 * different virtual circuits carry different network
861 * layer protocols, and no header is prepended to packets.
863 * They both have an ARPHRD_ type of ARPHRD_ATM, so
864 * you can't use the ARPHRD_ type to find out whether
865 * captured packets will have an LLC header, and,
866 * while there's a socket ioctl to *set* the encapsulation
867 * type, there's no ioctl to *get* the encapsulation type.
871 * programs that dissect Linux Classical IP frames
872 * would have to check for an LLC header and,
873 * depending on whether they see one or not, dissect
874 * the frame as LLC-encapsulated or as raw IP (I
875 * don't know whether there's any traffic other than
876 * IP that would show up on the socket, or whether
877 * there's any support for IPv6 in the Linux
878 * Classical IP code);
880 * filter expressions would have to compile into
881 * code that checks for an LLC header and does
884 * Both of those are a nuisance - and, at least on systems
885 * that support PF_PACKET sockets, we don't have to put
886 * up with those nuisances; instead, we can just capture
887 * in cooked mode. That's what we'll do.
889 handle
->linktype
= DLT_LINUX_SLL
;
892 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
893 #define ARPHRD_IEEE80211 801
895 case ARPHRD_IEEE80211
:
896 handle
->linktype
= DLT_IEEE802_11
;
901 * Some PPP code in the kernel supplies no link-layer
902 * header whatsoever to PF_PACKET sockets; other PPP
903 * code supplies PPP link-layer headers ("syncppp.c");
904 * some PPP code might supply random link-layer
905 * headers (PPP over ISDN - there's code in Ethereal,
906 * for example, to cope with PPP-over-ISDN captures
907 * with which the Ethereal developers have had to cope,
908 * heuristically trying to determine which of the
909 * oddball link-layer headers particular packets have).
911 * As such, we just punt, and run all PPP interfaces
914 handle
->linktype
= DLT_LINUX_SLL
;
918 handle
->linktype
= DLT_C_HDLC
;
921 /* Not sure if this is correct for all tunnels, but it
925 #define ARPHRD_SIT 776 /* From Linux 2.2.14 */
934 * XXX - should some of those be mapped to DLT_LINUX_SLL
935 * instead? Should we just map all of them to DLT_LINUX_SLL?
937 handle
->linktype
= DLT_RAW
;
940 case ARPHRD_LOCALTLK
:
941 handle
->linktype
= DLT_LTALK
;
945 handle
->linktype
= -1;
950 /* ===== Functions to interface to the newer kernels ================== */
953 * Try to open a packet socket using the new kernel interface.
954 * Returns 0 on failure.
955 * FIXME: 0 uses to mean success (Sebastian)
958 live_open_new(pcap_t
*handle
, char *device
, int promisc
,
959 int to_ms
, char *ebuf
)
961 #ifdef HAVE_PF_PACKET_SOCKETS
962 int sock_fd
= -1, device_id
, arptype
;
963 struct packet_mreq mr
;
965 /* One shot loop used for error handling - bail out with break */
969 * Open a socket with protocol family packet. If a device is
970 * given we try to open it in raw mode otherwise we use
971 * the cooked interface.
974 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
975 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
978 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
979 pcap_strerror(errno
) );
983 /* It seems the kernel supports the new interface. */
984 handle
->md
.sock_packet
= 0;
987 * Get the interface index of the loopback device.
988 * If the attempt fails, don't fail, just set the
989 * "md.lo_ifindex" to -1.
991 * XXX - can there be more than one device that loops
992 * packets back, i.e. devices other than "lo"? If so,
993 * we'd need to find them all, and have an array of
994 * indices for them, and check all of them in
995 * "pcap_read_packet()".
997 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", ebuf
);
1000 * Default value for offset to align link-layer payload
1001 * on a 4-byte boundary.
1006 * What kind of frames do we have to deal with? Fall back
1007 * to cooked mode if we have an unknown interface type.
1011 /* Assume for now we don't need cooked mode. */
1012 handle
->md
.cooked
= 0;
1014 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1017 map_arphrd_to_dlt(handle
, arptype
);
1018 if (handle
->linktype
== -1 ||
1019 handle
->linktype
== DLT_LINUX_SLL
||
1020 (handle
->linktype
== DLT_EN10MB
&&
1021 (strncmp("isdn", device
, 4) == 0 ||
1022 strncmp("isdY", device
, 4) == 0))) {
1024 * Unknown interface type (-1), or a
1025 * device we explicitly chose to run
1026 * in cooked mode (e.g., PPP devices),
1027 * or an ISDN device (whose link-layer
1028 * type we can only determine by using
1029 * APIs that may be different on different
1030 * kernels) - reopen in cooked mode.
1032 if (close(sock_fd
) == -1) {
1033 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1034 "close: %s", pcap_strerror(errno
));
1037 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1039 if (sock_fd
== -1) {
1040 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1041 "socket: %s", pcap_strerror(errno
));
1044 handle
->md
.cooked
= 1;
1046 if (handle
->linktype
== -1) {
1048 * Warn that we're falling back on
1049 * cooked mode; we may want to
1050 * update "map_arphrd_to_dlt()"
1051 * to handle the new type.
1053 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1055 "supported by libpcap - "
1056 "falling back to cooked "
1060 handle
->linktype
= DLT_LINUX_SLL
;
1063 device_id
= iface_get_id(sock_fd
, device
, ebuf
);
1064 if (device_id
== -1)
1067 if (iface_bind(sock_fd
, device_id
, ebuf
) == -1)
1071 * This is cooked mode.
1073 handle
->md
.cooked
= 1;
1074 handle
->linktype
= DLT_LINUX_SLL
;
1077 * XXX - squelch GCC complaints about
1078 * uninitialized variables; if we can't
1079 * select promiscuous mode on all interfaces,
1080 * we should move the code below into the
1081 * "if (device)" branch of the "if" and
1082 * get rid of the next statement.
1087 /* Select promiscuous mode on/off */
1091 * Hmm, how can we set promiscuous mode on all interfaces?
1092 * I am not sure if that is possible at all.
1096 memset(&mr
, 0, sizeof(mr
));
1097 mr
.mr_ifindex
= device_id
;
1098 mr
.mr_type
= promisc
?
1099 PACKET_MR_PROMISC
: PACKET_MR_ALLMULTI
;
1100 if (setsockopt(sock_fd
, SOL_PACKET
,
1101 PACKET_ADD_MEMBERSHIP
, &mr
, sizeof(mr
)) == -1)
1103 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1104 "setsockopt: %s", pcap_strerror(errno
));
1110 /* Save the socket FD in the pcap structure */
1112 handle
->fd
= sock_fd
;
1123 "New packet capturing interface not supported by build "
1124 "environment", PCAP_ERRBUF_SIZE
);
1129 #ifdef HAVE_PF_PACKET_SOCKETS
1131 * Return the index of the given device name. Fill ebuf and return
1135 iface_get_id(int fd
, const char *device
, char *ebuf
)
1139 memset(&ifr
, 0, sizeof(ifr
));
1140 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1142 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
1143 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1144 "ioctl: %s", pcap_strerror(errno
));
1148 return ifr
.ifr_ifindex
;
1152 * Bind the socket associated with FD to the given device.
1155 iface_bind(int fd
, int ifindex
, char *ebuf
)
1157 struct sockaddr_ll sll
;
1159 memset(&sll
, 0, sizeof(sll
));
1160 sll
.sll_family
= AF_PACKET
;
1161 sll
.sll_ifindex
= ifindex
;
1162 sll
.sll_protocol
= htons(ETH_P_ALL
);
1164 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
1165 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1166 "bind: %s", pcap_strerror(errno
));
1176 /* ===== Functions to interface to the older kernels ================== */
1179 * With older kernels promiscuous mode is kind of interesting because we
1180 * have to reset the interface before exiting. The problem can't really
1181 * be solved without some daemon taking care of managing usage counts.
1182 * If we put the interface into promiscuous mode, we set a flag indicating
1183 * that we must take it out of that mode when the interface is closed,
1184 * and, when closing the interface, if that flag is set we take it out
1185 * of promiscuous mode.
1189 * List of pcaps for which we turned promiscuous mode on by hand.
1190 * If there are any such pcaps, we arrange to call "pcap_close_all()"
1191 * when we exit, and have it close all of them to turn promiscuous mode
1194 static struct pcap
*pcaps_to_close
;
1197 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1198 * be called on exit.
1200 static int did_atexit
;
1202 static void pcap_close_all(void)
1204 struct pcap
*handle
;
1206 while ((handle
= pcaps_to_close
) != NULL
)
1210 void pcap_close_linux( pcap_t
*handle
)
1212 struct pcap
*p
, *prevp
;
1215 if (handle
->md
.clear_promisc
) {
1217 * We put the interface into promiscuous mode; take
1218 * it out of promiscuous mode.
1220 * XXX - if somebody else wants it in promiscuous mode,
1221 * this code cannot know that, so it'll take it out
1222 * of promiscuous mode. That's not fixable in 2.0[.x]
1225 memset(&ifr
, 0, sizeof(ifr
));
1226 strncpy(ifr
.ifr_name
, handle
->md
.device
, sizeof(ifr
.ifr_name
));
1227 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1229 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1230 "Please adjust manually.\n"
1231 "Hint: This can't happen with Linux >= 2.2.0.\n",
1234 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1236 * Promiscuous mode is currently on; turn it
1239 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1240 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1242 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1243 "Please adjust manually.\n"
1244 "Hint: This can't happen with Linux >= 2.2.0.\n",
1251 * Take this pcap out of the list of pcaps for which we
1252 * have to take the interface out of promiscuous mode.
1254 for (p
= pcaps_to_close
, prevp
= NULL
; p
!= NULL
;
1255 prevp
= p
, p
= p
->md
.next
) {
1258 * Found it. Remove it from the list.
1260 if (prevp
== NULL
) {
1262 * It was at the head of the list.
1264 pcaps_to_close
= p
->md
.next
;
1267 * It was in the middle of the list.
1269 prevp
->md
.next
= p
->md
.next
;
1275 if (handle
->md
.device
!= NULL
)
1276 free(handle
->md
.device
);
1280 * Try to open a packet socket using the old kernel interface.
1281 * Returns 0 on failure.
1282 * FIXME: 0 uses to mean success (Sebastian)
1285 live_open_old(pcap_t
*handle
, char *device
, int promisc
,
1286 int to_ms
, char *ebuf
)
1288 int sock_fd
= -1, arptype
;
1292 /* Open the socket */
1294 sock_fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
1295 if (sock_fd
== -1) {
1296 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1297 "socket: %s", pcap_strerror(errno
));
1301 /* It worked - we are using the old interface */
1302 handle
->md
.sock_packet
= 1;
1304 /* ...which means we get the link-layer header. */
1305 handle
->md
.cooked
= 0;
1307 /* Bind to the given device */
1310 strncpy(ebuf
, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
1314 if (iface_bind_old(sock_fd
, device
, ebuf
) == -1)
1317 /* Go to promisc mode */
1319 memset(&ifr
, 0, sizeof(ifr
));
1320 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1321 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1322 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1323 "ioctl: %s", pcap_strerror(errno
));
1326 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
1328 * Promiscuous mode isn't currently on,
1329 * so turn it on, and remember that
1330 * we should turn it off when the
1335 * If we haven't already done so, arrange
1336 * to have "pcap_close_all()" called when
1340 if (atexit(pcap_close_all
) == -1) {
1342 * "atexit()" failed; don't
1343 * put the interface in
1344 * promiscuous mode, just
1347 strncpy(ebuf
, "atexit failed",
1353 ifr
.ifr_flags
|= IFF_PROMISC
;
1354 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1355 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1357 pcap_strerror(errno
));
1360 handle
->md
.clear_promisc
= 1;
1363 * Add this to the list of pcaps
1364 * to close when we exit.
1366 handle
->md
.next
= pcaps_to_close
;
1367 pcaps_to_close
= handle
;
1371 /* All done - fill in the pcap handle */
1373 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1377 /* Save the socket FD in the pcap structure */
1379 handle
->fd
= sock_fd
;
1382 * Default value for offset to align link-layer payload
1383 * on a 4-byte boundary.
1388 * XXX - handle ISDN types here? We can't fall back on
1389 * cooked sockets, so we'd have to figure out from the
1390 * device name what type of link-layer encapsulation
1391 * it's using, and map that to an appropriate DLT_
1392 * value, meaning we'd map "isdnN" devices to DLT_RAW
1393 * (they supply raw IP packets with no link-layer
1394 * header) and "isdY" devices to a new DLT_I4L_IP
1395 * type that has only an Ethernet packet type as
1396 * a link-layer header.
1398 map_arphrd_to_dlt(handle
, arptype
);
1399 if (handle
->linktype
== -1) {
1400 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1401 "interface type of %s not supported", device
);
1415 * Bind the socket associated with FD to the given device using the
1416 * interface of the old kernels.
1419 iface_bind_old(int fd
, const char *device
, char *ebuf
)
1421 struct sockaddr saddr
;
1423 memset(&saddr
, 0, sizeof(saddr
));
1424 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
1425 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
1426 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1427 "bind: %s", pcap_strerror(errno
));
1435 /* ===== System calls available on all supported kernels ============== */
1438 * Query the kernel for the MTU of the given interface.
1441 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
1446 return BIGGER_THAN_ALL_MTUS
;
1448 memset(&ifr
, 0, sizeof(ifr
));
1449 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1451 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
1452 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1453 "ioctl: %s", pcap_strerror(errno
));
1461 * Get the hardware type of the given interface as ARPHRD_xxx constant.
1464 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
1468 memset(&ifr
, 0, sizeof(ifr
));
1469 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1471 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
1472 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1473 "ioctl: %s", pcap_strerror(errno
));
1477 return ifr
.ifr_hwaddr
.sa_family
;
1480 #ifdef SO_ATTACH_FILTER
1482 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
1486 register struct bpf_insn
*p
;
1491 * Make a copy of the filter, and modify that copy if
1494 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
1495 len
= handle
->fcode
.bf_len
;
1496 f
= (struct bpf_insn
*)malloc(prog_size
);
1498 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1499 "malloc: %s", pcap_strerror(errno
));
1502 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
1504 fcode
->filter
= (struct sock_filter
*) f
;
1506 for (i
= 0; i
< len
; ++i
) {
1509 * What type of instruction is this?
1511 switch (BPF_CLASS(p
->code
)) {
1515 * It's a return instruction; is the snapshot
1516 * length a constant, rather than the contents
1517 * of the accumulator?
1519 if (BPF_MODE(p
->code
) == BPF_K
) {
1521 * Yes - if the value to be returned,
1522 * i.e. the snapshot length, is anything
1523 * other than 0, make it 65535, so that
1524 * the packet is truncated by "recvfrom()",
1525 * not by the filter.
1527 * XXX - there's nothing we can easily do
1528 * if it's getting the value from the
1529 * accumulator; we'd have to insert
1530 * code to force non-zero values to be
1541 * It's a load instruction; is it loading
1544 switch (BPF_MODE(p
->code
)) {
1550 * Yes; are we in cooked mode?
1552 if (handle
->md
.cooked
) {
1554 * Yes, so we need to fix this
1557 if (fix_offset(p
) < 0) {
1559 * We failed to do so.
1560 * Return 0, so our caller
1561 * knows to punt to userland.
1571 return 1; /* we succeeded */
1575 fix_offset(struct bpf_insn
*p
)
1578 * What's the offset?
1580 if (p
->k
>= SLL_HDR_LEN
) {
1582 * It's within the link-layer payload; that starts at an
1583 * offset of 0, as far as the kernel packet filter is
1584 * concerned, so subtract the length of the link-layer
1587 p
->k
-= SLL_HDR_LEN
;
1588 } else if (p
->k
== 14) {
1590 * It's the protocol field; map it to the special magic
1591 * kernel offset for that field.
1593 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
1596 * It's within the header, but it's not one of those
1597 * fields; we can't do that in the kernel, so punt
1606 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
1608 int total_filter_on
= 0;
1614 * The socket filter code doesn't discard all packets queued
1615 * up on the socket when the filter is changed; this means
1616 * that packets that don't match the new filter may show up
1617 * after the new filter is put onto the socket, if those
1618 * packets haven't yet been read.
1620 * This means, for example, that if you do a tcpdump capture
1621 * with a filter, the first few packets in the capture might
1622 * be packets that wouldn't have passed the filter.
1624 * We therefore discard all packets queued up on the socket
1625 * when setting a kernel filter. (This isn't an issue for
1626 * userland filters, as the userland filtering is done after
1627 * packets are queued up.)
1629 * To flush those packets, we put the socket in read-only mode,
1630 * and read packets from the socket until there are no more to
1633 * In order to keep that from being an infinite loop - i.e.,
1634 * to keep more packets from arriving while we're draining
1635 * the queue - we put the "total filter", which is a filter
1636 * that rejects all packets, onto the socket before draining
1639 * This code deliberately ignores any errors, so that you may
1640 * get bogus packets if an error occurs, rather than having
1641 * the filtering done in userland even if it could have been
1642 * done in the kernel.
1644 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
1645 &total_fcode
, sizeof(total_fcode
)) == 0) {
1649 * Note that we've put the total filter onto the socket.
1651 total_filter_on
= 1;
1654 * Save the socket's current mode, and put it in
1655 * non-blocking mode; we drain it by reading packets
1656 * until we get an error (which we assume is a
1657 * "nothing more to be read" error).
1659 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
1660 if (save_mode
!= -1 &&
1661 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
1662 while (recv(handle
->fd
, &drain
, sizeof drain
,
1665 fcntl(handle
->fd
, F_SETFL
, save_mode
);
1670 * Now attach the new filter.
1672 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
1673 fcode
, sizeof(*fcode
));
1674 if (ret
== -1 && total_filter_on
) {
1676 * Well, we couldn't set that filter on the socket,
1677 * but we could set the total filter on the socket.
1679 * This could, for example, mean that the filter was
1680 * too big to put into the kernel, so we'll have to
1681 * filter in userland; in any case, we'll be doing
1682 * filtering in userland, so we need to remove the
1683 * total filter so we see packets.
1688 * XXX - if this fails, we're really screwed;
1689 * we have the total filter on the socket,
1690 * and it won't come off. What do we do then?
1692 reset_kernel_filter(handle
);
1700 reset_kernel_filter(pcap_t
*handle
)
1702 /* setsockopt() barfs unless it get a dummy parameter */
1705 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
1706 &dummy
, sizeof(dummy
));