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.129.2.2 2007-11-18 04:37:53 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 */
91 #ifdef PCAP_SUPPORT_USB
92 #include "pcap-usb-linux.h"
95 #ifdef PCAP_SUPPORT_BT
96 #include "pcap-bt-linux.h"
100 #include "pcap-sita.h"
108 #include <sys/socket.h>
109 #include <sys/ioctl.h>
110 #include <sys/utsname.h>
112 #include <netinet/in.h>
113 #include <linux/if_ether.h>
114 #include <net/if_arp.h>
117 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
118 * sockets rather than SOCK_PACKET sockets.
120 * To use them, we include <linux/if_packet.h> rather than
121 * <netpacket/packet.h>; we do so because
123 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
124 * later kernels and libc5, and don't provide a <netpacket/packet.h>
127 * not all versions of glibc2 have a <netpacket/packet.h> file
128 * that defines stuff needed for some of the 2.4-or-later-kernel
129 * features, so if the system has a 2.4 or later kernel, we
130 * still can't use those features.
132 * We're already including a number of other <linux/XXX.h> headers, and
133 * this code is Linux-specific (no other OS has PF_PACKET sockets as
134 * a raw packet capture mechanism), so it's not as if you gain any
135 * useful portability by using <netpacket/packet.h>
137 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
138 * isn't defined? It only defines one data structure in 2.0.x, so
139 * it shouldn't cause any problems.
142 # include <linux/if_packet.h>
145 * On at least some Linux distributions (for example, Red Hat 5.2),
146 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
147 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
148 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
149 * the PACKET_xxx stuff.
151 * So we check whether PACKET_HOST is defined, and assume that we have
152 * PF_PACKET sockets only if it is defined.
155 # define HAVE_PF_PACKET_SOCKETS
156 # endif /* PACKET_HOST */
157 #endif /* PF_PACKET */
159 #ifdef SO_ATTACH_FILTER
160 #include <linux/types.h>
161 #include <linux/filter.h>
165 typedef int socklen_t
;
170 * This is being compiled on a system that lacks MSG_TRUNC; define it
171 * with the value it has in the 2.2 and later kernels, so that, on
172 * those kernels, when we pass it in the flags argument to "recvfrom()"
173 * we're passing the right value and thus get the MSG_TRUNC behavior
174 * we want. (We don't get that behavior on 2.0[.x] kernels, because
175 * they didn't support MSG_TRUNC.)
177 #define MSG_TRUNC 0x20
182 * This is being compiled on a system that lacks SOL_PACKET; define it
183 * with the value it has in the 2.2 and later kernels, so that we can
184 * set promiscuous mode in the good modern way rather than the old
185 * 2.0-kernel crappy way.
187 #define SOL_PACKET 263
190 #define MAX_LINKHEADER_SIZE 256
193 * When capturing on all interfaces we use this as the buffer size.
194 * Should be bigger then all MTUs that occur in real life.
195 * 64kB should be enough for now.
197 #define BIGGER_THAN_ALL_MTUS (64*1024)
200 * Prototypes for internal functions
202 static void map_arphrd_to_dlt(pcap_t
*, int, int);
203 static int live_open_old(pcap_t
*, const char *, int, int, char *);
204 static int live_open_new(pcap_t
*, const char *, int, int, char *);
205 static int pcap_read_linux(pcap_t
*, int, pcap_handler
, u_char
*);
206 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
207 static int pcap_inject_linux(pcap_t
*, const void *, size_t);
208 static int pcap_stats_linux(pcap_t
*, struct pcap_stat
*);
209 static int pcap_setfilter_linux(pcap_t
*, struct bpf_program
*);
210 static int pcap_setdirection_linux(pcap_t
*, pcap_direction_t
);
211 static void pcap_close_linux(pcap_t
*);
214 * Wrap some ioctl calls
216 #ifdef HAVE_PF_PACKET_SOCKETS
217 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
219 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
220 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
221 #ifdef HAVE_PF_PACKET_SOCKETS
222 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
224 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
226 #ifdef SO_ATTACH_FILTER
227 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
228 static int fix_offset(struct bpf_insn
*p
);
229 static int set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
);
230 static int reset_kernel_filter(pcap_t
*handle
);
232 static struct sock_filter total_insn
233 = BPF_STMT(BPF_RET
| BPF_K
, 0);
234 static struct sock_fprog total_fcode
235 = { 1, &total_insn
};
239 * Get a handle for a live capture from the given device. You can
240 * pass NULL as device to get all packages (without link level
241 * information of course). If you pass 1 as promisc the interface
242 * will be set to promiscous mode (XXX: I think this usage should
243 * be deprecated and functions be added to select that later allow
244 * modification of that values -- Torsten).
249 pcap_open_live(const char *device
, int snaplen
, int promisc
, int to_ms
,
255 int live_open_ok
= 0;
256 struct utsname utsname
;
259 if (strstr(device
, "dag")) {
260 return dag_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
262 #endif /* HAVE_DAG_API */
264 #ifdef HAVE_SEPTEL_API
265 if (strstr(device
, "septel")) {
266 return septel_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
268 #endif /* HAVE_SEPTEL_API */
270 #ifdef PCAP_SUPPORT_BT
271 if (strstr(device
, "bluetooth")) {
272 return bt_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
276 #ifdef PCAP_SUPPORT_USB
277 if (strstr(device
, "usb")) {
278 return usb_open_live(device
, snaplen
, promisc
, to_ms
, ebuf
);
282 /* Allocate a handle for this session. */
284 handle
= malloc(sizeof(*handle
));
285 if (handle
== NULL
) {
286 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
287 pcap_strerror(errno
));
291 /* Initialize some components of the pcap structure. */
293 memset(handle
, 0, sizeof(*handle
));
294 handle
->snapshot
= snaplen
;
295 handle
->md
.timeout
= to_ms
;
298 * NULL and "any" are special devices which give us the hint to
299 * monitor all devices.
301 if (!device
|| strcmp(device
, "any") == 0) {
303 handle
->md
.device
= strdup("any");
306 /* Just a warning. */
307 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
308 "Promiscuous mode not supported on the \"any\" device");
312 handle
->md
.device
= strdup(device
);
314 if (handle
->md
.device
== NULL
) {
315 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
316 pcap_strerror(errno
) );
322 * Current Linux kernels use the protocol family PF_PACKET to
323 * allow direct access to all packets on the network while
324 * older kernels had a special socket type SOCK_PACKET to
325 * implement this feature.
326 * While this old implementation is kind of obsolete we need
327 * to be compatible with older kernels for a while so we are
328 * trying both methods with the newer method preferred.
332 live_open_ok
= acn_open_live((unsigned char *)device
, ebuf
, &handle
->linktype
);
333 handle
->md
.clear_promisc
= promisc
;
334 handle
->fd
= live_open_ok
;
335 handle
->bufsize
= handle
->snapshot
;
337 if ((err
= live_open_new(handle
, device
, promisc
, to_ms
, ebuf
)) == 1)
340 /* Non-fatal error; try old way */
341 if (live_open_old(handle
, device
, promisc
, to_ms
, ebuf
))
347 * Both methods to open the packet socket failed. Tidy
348 * up and report our failure (ebuf is expected to be
349 * set by the functions above).
352 if (handle
->md
.device
!= NULL
)
353 free(handle
->md
.device
);
360 * Compute the buffer size.
362 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
363 * and might require special handling - check.
365 if (handle
->md
.sock_packet
&& (uname(&utsname
) < 0 ||
366 strncmp(utsname
.release
, "2.0", 3) == 0)) {
368 * We're using a SOCK_PACKET structure, and either
369 * we couldn't find out what kernel release this is,
370 * or it's a 2.0[.x] kernel.
372 * In the 2.0[.x] kernel, a "recvfrom()" on
373 * a SOCK_PACKET socket, with MSG_TRUNC set, will
374 * return the number of bytes read, so if we pass
375 * a length based on the snapshot length, it'll
376 * return the number of bytes from the packet
377 * copied to userland, not the actual length
380 * This means that, for example, the IP dissector
381 * in tcpdump will get handed a packet length less
382 * than the length in the IP header, and will
383 * complain about "truncated-ip".
385 * So we don't bother trying to copy from the
386 * kernel only the bytes in which we're interested,
387 * but instead copy them all, just as the older
388 * versions of libpcap for Linux did.
390 * The buffer therefore needs to be big enough to
391 * hold the largest packet we can get from this
392 * device. Unfortunately, we can't get the MRU
393 * of the network; we can only get the MTU. The
394 * MTU may be too small, in which case a packet larger
395 * than the buffer size will be truncated *and* we
396 * won't get the actual packet size.
398 * However, if the snapshot length is larger than
399 * the buffer size based on the MTU, we use the
400 * snapshot length as the buffer size, instead;
401 * this means that with a sufficiently large snapshot
402 * length we won't artificially truncate packets
403 * to the MTU-based size.
405 * This mess just one of many problems with packet
406 * capture on 2.0[.x] kernels; you really want a
407 * 2.2[.x] or later kernel if you want packet capture
410 mtu
= iface_get_mtu(handle
->fd
, device
, ebuf
);
412 pcap_close_linux(handle
);
416 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
417 if (handle
->bufsize
< handle
->snapshot
)
418 handle
->bufsize
= handle
->snapshot
;
421 * This is a 2.2[.x] or later kernel (we know that
422 * either because we're not using a SOCK_PACKET
423 * socket - PF_PACKET is supported only in 2.2
424 * and later kernels - or because we checked the
427 * We can safely pass "recvfrom()" a byte count
428 * based on the snapshot length.
430 * If we're in cooked mode, make the snapshot length
431 * large enough to hold a "cooked mode" header plus
432 * 1 byte of packet data (so we don't pass a byte
433 * count of 0 to "recvfrom()").
435 if (handle
->md
.cooked
) {
436 if (handle
->snapshot
< SLL_HDR_LEN
+ 1)
437 handle
->snapshot
= SLL_HDR_LEN
+ 1;
439 handle
->bufsize
= handle
->snapshot
;
443 /* Allocate the buffer */
445 handle
->buffer
= malloc(handle
->bufsize
+ handle
->offset
);
446 if (!handle
->buffer
) {
447 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
448 "malloc: %s", pcap_strerror(errno
));
449 pcap_close_linux(handle
);
455 * "handle->fd" is a socket, so "select()" and "poll()"
458 handle
->selectable_fd
= handle
->fd
;
460 handle
->inject_op
= pcap_inject_linux
;
461 handle
->setfilter_op
= pcap_setfilter_linux
;
462 handle
->setdirection_op
= pcap_setdirection_linux
;
463 handle
->set_datalink_op
= NULL
; /* can't change data link type */
464 handle
->getnonblock_op
= pcap_getnonblock_fd
;
465 handle
->setnonblock_op
= pcap_setnonblock_fd
;
466 handle
->close_op
= pcap_close_linux
;
469 handle
->read_op
= pcap_read_acn
;
470 handle
->stats_op
= pcap_stats_acn
;
472 handle
->read_op
= pcap_read_linux
;
473 handle
->stats_op
= pcap_stats_linux
;
480 * Read at most max_packets from the capture stream and call the callback
481 * for each of them. Returns the number of packets handled or -1 if an
485 pcap_read_linux(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
488 * Currently, on Linux only one packet is delivered per read,
491 return pcap_read_packet(handle
, callback
, user
);
495 * Read a packet from the socket calling the handler provided by
496 * the user. Returns the number of packets received or -1 if an
500 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
504 #ifdef HAVE_PF_PACKET_SOCKETS
505 struct sockaddr_ll from
;
506 struct sll_header
*hdrp
;
508 struct sockaddr from
;
511 int packet_len
, caplen
;
512 struct pcap_pkthdr pcap_header
;
514 #ifdef HAVE_PF_PACKET_SOCKETS
516 * If this is a cooked device, leave extra room for a
517 * fake packet header.
519 if (handle
->md
.cooked
)
520 offset
= SLL_HDR_LEN
;
525 * This system doesn't have PF_PACKET sockets, so it doesn't
526 * support cooked devices.
531 /* Receive a single packet from the kernel */
533 bp
= handle
->buffer
+ handle
->offset
;
536 * Has "pcap_breakloop()" been called?
538 if (handle
->break_loop
) {
540 * Yes - clear the flag that indicates that it
541 * has, and return -2 as an indication that we
542 * were told to break out of the loop.
544 handle
->break_loop
= 0;
547 fromlen
= sizeof(from
);
548 packet_len
= recvfrom(
549 handle
->fd
, bp
+ offset
,
550 handle
->bufsize
- offset
, MSG_TRUNC
,
551 (struct sockaddr
*) &from
, &fromlen
);
552 } while (packet_len
== -1 && errno
== EINTR
);
554 /* Check if an error occured */
556 if (packet_len
== -1) {
558 return 0; /* no packet there */
560 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
561 "recvfrom: %s", pcap_strerror(errno
));
566 #ifdef HAVE_PF_PACKET_SOCKETS
567 if (!handle
->md
.sock_packet
) {
569 * Unfortunately, there is a window between socket() and
570 * bind() where the kernel may queue packets from any
571 * interface. If we're bound to a particular interface,
572 * discard packets not from that interface.
574 * (If socket filters are supported, we could do the
575 * same thing we do when changing the filter; however,
576 * that won't handle packet sockets without socket
577 * filter support, and it's a bit more complicated.
578 * It would save some instructions per packet, however.)
580 if (handle
->md
.ifindex
!= -1 &&
581 from
.sll_ifindex
!= handle
->md
.ifindex
)
585 * Do checks based on packet direction.
586 * We can only do this if we're using PF_PACKET; the
587 * address returned for SOCK_PACKET is a "sockaddr_pkt"
588 * which lacks the relevant packet type information.
590 if (from
.sll_pkttype
== PACKET_OUTGOING
) {
593 * If this is from the loopback device, reject it;
594 * we'll see the packet as an incoming packet as well,
595 * and we don't want to see it twice.
597 if (from
.sll_ifindex
== handle
->md
.lo_ifindex
)
601 * If the user only wants incoming packets, reject it.
603 if (handle
->direction
== PCAP_D_IN
)
608 * If the user only wants outgoing packets, reject it.
610 if (handle
->direction
== PCAP_D_OUT
)
616 #ifdef HAVE_PF_PACKET_SOCKETS
618 * If this is a cooked device, fill in the fake packet header.
620 if (handle
->md
.cooked
) {
622 * Add the length of the fake header to the length
623 * of packet data we read.
625 packet_len
+= SLL_HDR_LEN
;
627 hdrp
= (struct sll_header
*)bp
;
630 * Map the PACKET_ value to a LINUX_SLL_ value; we
631 * want the same numerical value to be used in
632 * the link-layer header even if the numerical values
633 * for the PACKET_ #defines change, so that programs
634 * that look at the packet type field will always be
635 * able to handle DLT_LINUX_SLL captures.
637 switch (from
.sll_pkttype
) {
640 hdrp
->sll_pkttype
= htons(LINUX_SLL_HOST
);
643 case PACKET_BROADCAST
:
644 hdrp
->sll_pkttype
= htons(LINUX_SLL_BROADCAST
);
647 case PACKET_MULTICAST
:
648 hdrp
->sll_pkttype
= htons(LINUX_SLL_MULTICAST
);
651 case PACKET_OTHERHOST
:
652 hdrp
->sll_pkttype
= htons(LINUX_SLL_OTHERHOST
);
655 case PACKET_OUTGOING
:
656 hdrp
->sll_pkttype
= htons(LINUX_SLL_OUTGOING
);
660 hdrp
->sll_pkttype
= -1;
664 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
665 hdrp
->sll_halen
= htons(from
.sll_halen
);
666 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
667 (from
.sll_halen
> SLL_ADDRLEN
) ?
670 hdrp
->sll_protocol
= from
.sll_protocol
;
675 * XXX: According to the kernel source we should get the real
676 * packet len if calling recvfrom with MSG_TRUNC set. It does
677 * not seem to work here :(, but it is supported by this code
679 * To be honest the code RELIES on that feature so this is really
680 * broken with 2.2.x kernels.
681 * I spend a day to figure out what's going on and I found out
682 * that the following is happening:
684 * The packet comes from a random interface and the packet_rcv
685 * hook is called with a clone of the packet. That code inserts
686 * the packet into the receive queue of the packet socket.
687 * If a filter is attached to that socket that filter is run
688 * first - and there lies the problem. The default filter always
689 * cuts the packet at the snaplen:
694 * So the packet filter cuts down the packet. The recvfrom call
695 * says "hey, it's only 68 bytes, it fits into the buffer" with
696 * the result that we don't get the real packet length. This
697 * is valid at least until kernel 2.2.17pre6.
699 * We currently handle this by making a copy of the filter
700 * program, fixing all "ret" instructions with non-zero
701 * operands to have an operand of 65535 so that the filter
702 * doesn't truncate the packet, and supplying that modified
703 * filter to the kernel.
707 if (caplen
> handle
->snapshot
)
708 caplen
= handle
->snapshot
;
710 /* Run the packet filter if not using kernel filter */
711 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
712 if (bpf_filter(handle
->fcode
.bf_insns
, bp
,
713 packet_len
, caplen
) == 0)
715 /* rejected by filter */
720 /* Fill in our own header data */
722 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
723 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
724 "SIOCGSTAMP: %s", pcap_strerror(errno
));
727 pcap_header
.caplen
= caplen
;
728 pcap_header
.len
= packet_len
;
733 * Arguably, we should count them before we check the filter,
734 * as on many other platforms "ps_recv" counts packets
735 * handed to the filter rather than packets that passed
736 * the filter, but if filtering is done in the kernel, we
737 * can't get a count of packets that passed the filter,
738 * and that would mean the meaning of "ps_recv" wouldn't
739 * be the same on all Linux systems.
741 * XXX - it's not the same on all systems in any case;
742 * ideally, we should have a "get the statistics" call
743 * that supplies more counts and indicates which of them
744 * it supplies, so that we supply a count of packets
745 * handed to the filter only on platforms where that
746 * information is available.
748 * We count them here even if we can get the packet count
749 * from the kernel, as we can only determine at run time
750 * whether we'll be able to get it from the kernel (if
751 * HAVE_TPACKET_STATS isn't defined, we can't get it from
752 * the kernel, but if it is defined, the library might
753 * have been built with a 2.4 or later kernel, but we
754 * might be running on a 2.2[.x] kernel without Alexey
755 * Kuznetzov's turbopacket patches, and thus the kernel
756 * might not be able to supply those statistics). We
757 * could, I guess, try, when opening the socket, to get
758 * the statistics, and if we can not increment the count
759 * here, but it's not clear that always incrementing
760 * the count is more expensive than always testing a flag
763 * We keep the count in "md.packets_read", and use that for
764 * "ps_recv" if we can't get the statistics from the kernel.
765 * We do that because, if we *can* get the statistics from
766 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
767 * as running counts, as reading the statistics from the
768 * kernel resets the kernel statistics, and if we directly
769 * increment "md.stat.ps_recv" here, that means it will
770 * count packets *twice* on systems where we can get kernel
771 * statistics - once here, and once in pcap_stats_linux().
773 handle
->md
.packets_read
++;
775 /* Call the user supplied callback function */
776 callback(userdata
, &pcap_header
, bp
);
782 pcap_inject_linux(pcap_t
*handle
, const void *buf
, size_t size
)
786 #ifdef HAVE_PF_PACKET_SOCKETS
787 if (!handle
->md
.sock_packet
) {
788 /* PF_PACKET socket */
789 if (handle
->md
.ifindex
== -1) {
791 * We don't support sending on the "any" device.
793 strlcpy(handle
->errbuf
,
794 "Sending packets isn't supported on the \"any\" device",
799 if (handle
->md
.cooked
) {
801 * We don't support sending on the "any" device.
803 * XXX - how do you send on a bound cooked-mode
805 * Is a "sendto()" required there?
807 strlcpy(handle
->errbuf
,
808 "Sending packets isn't supported in cooked mode",
815 ret
= send(handle
->fd
, buf
, size
, 0);
817 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
, "send: %s",
818 pcap_strerror(errno
));
825 * Get the statistics for the given packet capture handle.
826 * Reports the number of dropped packets iff the kernel supports
827 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
828 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
829 * patches); otherwise, that information isn't available, and we lie
830 * and report 0 as the count of dropped packets.
833 pcap_stats_linux(pcap_t
*handle
, struct pcap_stat
*stats
)
835 #ifdef HAVE_TPACKET_STATS
836 struct tpacket_stats kstats
;
837 socklen_t len
= sizeof (struct tpacket_stats
);
840 #ifdef HAVE_TPACKET_STATS
842 * Try to get the packet counts from the kernel.
844 if (getsockopt(handle
->fd
, SOL_PACKET
, PACKET_STATISTICS
,
845 &kstats
, &len
) > -1) {
847 * On systems where the PACKET_STATISTICS "getsockopt()"
848 * argument is supported on PF_PACKET sockets:
850 * "ps_recv" counts only packets that *passed* the
851 * filter, not packets that didn't pass the filter.
852 * This includes packets later dropped because we
853 * ran out of buffer space.
855 * "ps_drop" counts packets dropped because we ran
856 * out of buffer space. It doesn't count packets
857 * dropped by the interface driver. It counts only
858 * packets that passed the filter.
860 * Both statistics include packets not yet read from
861 * the kernel by libpcap, and thus not yet seen by
864 * In "linux/net/packet/af_packet.c", at least in the
865 * 2.4.9 kernel, "tp_packets" is incremented for every
866 * packet that passes the packet filter *and* is
867 * successfully queued on the socket; "tp_drops" is
868 * incremented for every packet dropped because there's
869 * not enough free space in the socket buffer.
871 * When the statistics are returned for a PACKET_STATISTICS
872 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
873 * so that "tp_packets" counts all packets handed to
874 * the PF_PACKET socket, including packets dropped because
875 * there wasn't room on the socket buffer - but not
876 * including packets that didn't pass the filter.
878 * In the BSD BPF, the count of received packets is
879 * incremented for every packet handed to BPF, regardless
880 * of whether it passed the filter.
882 * We can't make "pcap_stats()" work the same on both
883 * platforms, but the best approximation is to return
884 * "tp_packets" as the count of packets and "tp_drops"
885 * as the count of drops.
887 * Keep a running total because each call to
888 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
889 * resets the counters to zero.
891 handle
->md
.stat
.ps_recv
+= kstats
.tp_packets
;
892 handle
->md
.stat
.ps_drop
+= kstats
.tp_drops
;
893 *stats
= handle
->md
.stat
;
899 * If the error was EOPNOTSUPP, fall through, so that
900 * if you build the library on a system with
901 * "struct tpacket_stats" and run it on a system
902 * that doesn't, it works as it does if the library
903 * is built on a system without "struct tpacket_stats".
905 if (errno
!= EOPNOTSUPP
) {
906 snprintf(handle
->errbuf
, PCAP_ERRBUF_SIZE
,
907 "pcap_stats: %s", pcap_strerror(errno
));
913 * On systems where the PACKET_STATISTICS "getsockopt()" argument
914 * is not supported on PF_PACKET sockets:
916 * "ps_recv" counts only packets that *passed* the filter,
917 * not packets that didn't pass the filter. It does not
918 * count packets dropped because we ran out of buffer
921 * "ps_drop" is not supported.
923 * "ps_recv" doesn't include packets not yet read from
924 * the kernel by libpcap.
926 * We maintain the count of packets processed by libpcap in
927 * "md.packets_read", for reasons described in the comment
928 * at the end of pcap_read_packet(). We have no idea how many
929 * packets were dropped.
931 stats
->ps_recv
= handle
->md
.packets_read
;
937 * Description string for the "any" device.
939 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
942 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
944 if (pcap_add_if(alldevsp
, "any", 0, any_descr
, errbuf
) < 0)
948 if (dag_platform_finddevs(alldevsp
, errbuf
) < 0)
950 #endif /* HAVE_DAG_API */
952 #ifdef HAVE_SEPTEL_API
953 if (septel_platform_finddevs(alldevsp
, errbuf
) < 0)
955 #endif /* HAVE_SEPTEL_API */
957 #ifdef PCAP_SUPPORT_BT
958 if (bt_platform_finddevs(alldevsp
, errbuf
) < 0)
962 #ifdef PCAP_SUPPORT_USB
963 if (usb_platform_finddevs(alldevsp
, errbuf
) < 0)
971 * Attach the given BPF code to the packet capture device.
974 pcap_setfilter_linux(pcap_t
*handle
, struct bpf_program
*filter
)
976 #ifdef SO_ATTACH_FILTER
977 struct sock_fprog fcode
;
978 int can_filter_in_kernel
;
985 strncpy(handle
->errbuf
, "setfilter: No filter specified",
986 sizeof(handle
->errbuf
));
991 return acn_setfilter(handle
->fd
, filter
);
993 /* Make our private copy of the filter */
995 if (install_bpf_program(handle
, filter
) < 0)
996 /* install_bpf_program() filled in errbuf */
1000 * Run user level packet filter by default. Will be overriden if
1001 * installing a kernel filter succeeds.
1003 handle
->md
.use_bpf
= 0;
1005 /* Install kernel level filter if possible */
1007 #ifdef SO_ATTACH_FILTER
1009 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
1011 * fcode.len is an unsigned short for current kernel.
1012 * I have yet to see BPF-Code with that much
1013 * instructions but still it is possible. So for the
1014 * sake of correctness I added this check.
1016 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
1018 fcode
.filter
= NULL
;
1019 can_filter_in_kernel
= 0;
1021 #endif /* USHRT_MAX */
1024 * Oh joy, the Linux kernel uses struct sock_fprog instead
1025 * of struct bpf_program and of course the length field is
1026 * of different size. Pointed out by Sebastian
1028 * Oh, and we also need to fix it up so that all "ret"
1029 * instructions with non-zero operands have 65535 as the
1030 * operand, and so that, if we're in cooked mode, all
1031 * memory-reference instructions use special magic offsets
1032 * in references to the link-layer header and assume that
1033 * the link-layer payload begins at 0; "fix_program()"
1036 switch (fix_program(handle
, &fcode
)) {
1041 * Fatal error; just quit.
1042 * (The "default" case shouldn't happen; we
1043 * return -1 for that reason.)
1049 * The program performed checks that we can't make
1050 * work in the kernel.
1052 can_filter_in_kernel
= 0;
1057 * We have a filter that'll work in the kernel.
1059 can_filter_in_kernel
= 1;
1064 if (can_filter_in_kernel
) {
1065 if ((err
= set_kernel_filter(handle
, &fcode
)) == 0)
1067 /* Installation succeded - using kernel filter. */
1068 handle
->md
.use_bpf
= 1;
1070 else if (err
== -1) /* Non-fatal error */
1073 * Print a warning if we weren't able to install
1074 * the filter for a reason other than "this kernel
1075 * isn't configured to support socket filters.
1077 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
1079 "Warning: Kernel filter failed: %s\n",
1080 pcap_strerror(errno
));
1086 * If we're not using the kernel filter, get rid of any kernel
1087 * filter that might've been there before, e.g. because the
1088 * previous filter could work in the kernel, or because some other
1089 * code attached a filter to the socket by some means other than
1090 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1091 * filter out packets that would pass the new userland filter.
1093 if (!handle
->md
.use_bpf
)
1094 reset_kernel_filter(handle
);
1097 * Free up the copy of the filter that was made by "fix_program()".
1099 if (fcode
.filter
!= NULL
)
1105 #endif /* SO_ATTACH_FILTER */
1112 * Set direction flag: Which packets do we accept on a forwarding
1113 * single device? IN, OUT or both?
1116 pcap_setdirection_linux(pcap_t
*handle
, pcap_direction_t d
)
1118 #ifdef HAVE_PF_PACKET_SOCKETS
1119 if (!handle
->md
.sock_packet
) {
1120 handle
->direction
= d
;
1125 * We're not using PF_PACKET sockets, so we can't determine
1126 * the direction of the packet.
1128 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1129 "Setting direction is not supported on SOCK_PACKET sockets");
1134 * Linux uses the ARP hardware type to identify the type of an
1135 * interface. pcap uses the DLT_xxx constants for this. This
1136 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1137 * constant, as arguments, and sets "handle->linktype" to the
1138 * appropriate DLT_XXX constant and sets "handle->offset" to
1139 * the appropriate value (to make "handle->offset" plus link-layer
1140 * header length be a multiple of 4, so that the link-layer payload
1141 * will be aligned on a 4-byte boundary when capturing packets).
1142 * (If the offset isn't set here, it'll be 0; add code as appropriate
1143 * for cases where it shouldn't be 0.)
1145 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1146 * in cooked mode; otherwise, we can't use cooked mode, so we have
1147 * to pick some type that works in raw mode, or fail.
1149 * Sets the link type to -1 if unable to map the type.
1151 static void map_arphrd_to_dlt(pcap_t
*handle
, int arptype
, int cooked_ok
)
1157 * This is (presumably) a real Ethernet capture; give it a
1158 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1159 * that an application can let you choose it, in case you're
1160 * capturing DOCSIS traffic that a Cisco Cable Modem
1161 * Termination System is putting out onto an Ethernet (it
1162 * doesn't put an Ethernet header onto the wire, it puts raw
1163 * DOCSIS frames out on the wire inside the low-level
1164 * Ethernet framing).
1166 * XXX - are there any sorts of "fake Ethernet" that have
1167 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1168 * a Cisco CMTS won't put traffic onto it or get traffic
1169 * bridged onto it? ISDN is handled in "live_open_new()",
1170 * as we fall back on cooked mode there; are there any
1173 handle
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1175 * If that fails, just leave the list empty.
1177 if (handle
->dlt_list
!= NULL
) {
1178 handle
->dlt_list
[0] = DLT_EN10MB
;
1179 handle
->dlt_list
[1] = DLT_DOCSIS
;
1180 handle
->dlt_count
= 2;
1184 case ARPHRD_METRICOM
:
1185 case ARPHRD_LOOPBACK
:
1186 handle
->linktype
= DLT_EN10MB
;
1191 handle
->linktype
= DLT_EN3MB
;
1195 handle
->linktype
= DLT_AX25_KISS
;
1199 handle
->linktype
= DLT_PRONET
;
1203 handle
->linktype
= DLT_CHAOS
;
1206 #ifndef ARPHRD_IEEE802_TR
1207 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1209 case ARPHRD_IEEE802_TR
:
1210 case ARPHRD_IEEE802
:
1211 handle
->linktype
= DLT_IEEE802
;
1216 handle
->linktype
= DLT_ARCNET_LINUX
;
1219 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1220 #define ARPHRD_FDDI 774
1223 handle
->linktype
= DLT_FDDI
;
1227 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1228 #define ARPHRD_ATM 19
1232 * The Classical IP implementation in ATM for Linux
1233 * supports both what RFC 1483 calls "LLC Encapsulation",
1234 * in which each packet has an LLC header, possibly
1235 * with a SNAP header as well, prepended to it, and
1236 * what RFC 1483 calls "VC Based Multiplexing", in which
1237 * different virtual circuits carry different network
1238 * layer protocols, and no header is prepended to packets.
1240 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1241 * you can't use the ARPHRD_ type to find out whether
1242 * captured packets will have an LLC header, and,
1243 * while there's a socket ioctl to *set* the encapsulation
1244 * type, there's no ioctl to *get* the encapsulation type.
1248 * programs that dissect Linux Classical IP frames
1249 * would have to check for an LLC header and,
1250 * depending on whether they see one or not, dissect
1251 * the frame as LLC-encapsulated or as raw IP (I
1252 * don't know whether there's any traffic other than
1253 * IP that would show up on the socket, or whether
1254 * there's any support for IPv6 in the Linux
1255 * Classical IP code);
1257 * filter expressions would have to compile into
1258 * code that checks for an LLC header and does
1261 * Both of those are a nuisance - and, at least on systems
1262 * that support PF_PACKET sockets, we don't have to put
1263 * up with those nuisances; instead, we can just capture
1264 * in cooked mode. That's what we'll do, if we can.
1265 * Otherwise, we'll just fail.
1268 handle
->linktype
= DLT_LINUX_SLL
;
1270 handle
->linktype
= -1;
1273 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1274 #define ARPHRD_IEEE80211 801
1276 case ARPHRD_IEEE80211
:
1277 handle
->linktype
= DLT_IEEE802_11
;
1280 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1281 #define ARPHRD_IEEE80211_PRISM 802
1283 case ARPHRD_IEEE80211_PRISM
:
1284 handle
->linktype
= DLT_PRISM_HEADER
;
1287 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1288 #define ARPHRD_IEEE80211_RADIOTAP 803
1290 case ARPHRD_IEEE80211_RADIOTAP
:
1291 handle
->linktype
= DLT_IEEE802_11_RADIO
;
1296 * Some PPP code in the kernel supplies no link-layer
1297 * header whatsoever to PF_PACKET sockets; other PPP
1298 * code supplies PPP link-layer headers ("syncppp.c");
1299 * some PPP code might supply random link-layer
1300 * headers (PPP over ISDN - there's code in Ethereal,
1301 * for example, to cope with PPP-over-ISDN captures
1302 * with which the Ethereal developers have had to cope,
1303 * heuristically trying to determine which of the
1304 * oddball link-layer headers particular packets have).
1306 * As such, we just punt, and run all PPP interfaces
1307 * in cooked mode, if we can; otherwise, we just treat
1308 * it as DLT_RAW, for now - if somebody needs to capture,
1309 * on a 2.0[.x] kernel, on PPP devices that supply a
1310 * link-layer header, they'll have to add code here to
1311 * map to the appropriate DLT_ type (possibly adding a
1312 * new DLT_ type, if necessary).
1315 handle
->linktype
= DLT_LINUX_SLL
;
1318 * XXX - handle ISDN types here? We can't fall
1319 * back on cooked sockets, so we'd have to
1320 * figure out from the device name what type of
1321 * link-layer encapsulation it's using, and map
1322 * that to an appropriate DLT_ value, meaning
1323 * we'd map "isdnN" devices to DLT_RAW (they
1324 * supply raw IP packets with no link-layer
1325 * header) and "isdY" devices to a new DLT_I4L_IP
1326 * type that has only an Ethernet packet type as
1327 * a link-layer header.
1329 * But sometimes we seem to get random crap
1330 * in the link-layer header when capturing on
1333 handle
->linktype
= DLT_RAW
;
1337 #ifndef ARPHRD_CISCO
1338 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1341 handle
->linktype
= DLT_C_HDLC
;
1344 /* Not sure if this is correct for all tunnels, but it
1348 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1356 #ifndef ARPHRD_RAWHDLC
1357 #define ARPHRD_RAWHDLC 518
1359 case ARPHRD_RAWHDLC
:
1361 #define ARPHRD_DLCI 15
1365 * XXX - should some of those be mapped to DLT_LINUX_SLL
1366 * instead? Should we just map all of them to DLT_LINUX_SLL?
1368 handle
->linktype
= DLT_RAW
;
1372 #define ARPHRD_FRAD 770
1375 handle
->linktype
= DLT_FRELAY
;
1378 case ARPHRD_LOCALTLK
:
1379 handle
->linktype
= DLT_LTALK
;
1383 #define ARPHRD_FCPP 784
1387 #define ARPHRD_FCAL 785
1391 #define ARPHRD_FCPL 786
1394 #ifndef ARPHRD_FCFABRIC
1395 #define ARPHRD_FCFABRIC 787
1397 case ARPHRD_FCFABRIC
:
1399 * We assume that those all mean RFC 2625 IP-over-
1400 * Fibre Channel, with the RFC 2625 header at
1401 * the beginning of the packet.
1403 handle
->linktype
= DLT_IP_OVER_FC
;
1407 #define ARPHRD_IRDA 783
1410 /* Don't expect IP packet out of this interfaces... */
1411 handle
->linktype
= DLT_LINUX_IRDA
;
1412 /* We need to save packet direction for IrDA decoding,
1413 * so let's use "Linux-cooked" mode. Jean II */
1414 //handle->md.cooked = 1;
1417 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1418 * is needed, please report it to <daniele@orlandi.com> */
1420 #define ARPHRD_LAPD 8445
1423 /* Don't expect IP packet out of this interfaces... */
1424 handle
->linktype
= DLT_LINUX_LAPD
;
1428 handle
->linktype
= -1;
1433 /* ===== Functions to interface to the newer kernels ================== */
1436 * Try to open a packet socket using the new kernel interface.
1437 * Returns 0 on failure.
1438 * FIXME: 0 uses to mean success (Sebastian)
1441 live_open_new(pcap_t
*handle
, const char *device
, int promisc
,
1442 int to_ms
, char *ebuf
)
1444 #ifdef HAVE_PF_PACKET_SOCKETS
1445 int sock_fd
= -1, arptype
;
1448 struct packet_mreq mr
;
1450 /* One shot loop used for error handling - bail out with break */
1454 * Open a socket with protocol family packet. If a device is
1455 * given we try to open it in raw mode otherwise we use
1456 * the cooked interface.
1459 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
1460 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
1462 if (sock_fd
== -1) {
1463 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
1464 pcap_strerror(errno
) );
1468 /* It seems the kernel supports the new interface. */
1469 handle
->md
.sock_packet
= 0;
1472 * Get the interface index of the loopback device.
1473 * If the attempt fails, don't fail, just set the
1474 * "md.lo_ifindex" to -1.
1476 * XXX - can there be more than one device that loops
1477 * packets back, i.e. devices other than "lo"? If so,
1478 * we'd need to find them all, and have an array of
1479 * indices for them, and check all of them in
1480 * "pcap_read_packet()".
1482 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", ebuf
);
1485 * Default value for offset to align link-layer payload
1486 * on a 4-byte boundary.
1491 * What kind of frames do we have to deal with? Fall back
1492 * to cooked mode if we have an unknown interface type.
1496 /* Assume for now we don't need cooked mode. */
1497 handle
->md
.cooked
= 0;
1499 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1500 if (arptype
== -1) {
1504 map_arphrd_to_dlt(handle
, arptype
, 1);
1505 if (handle
->linktype
== -1 ||
1506 handle
->linktype
== DLT_LINUX_SLL
||
1507 handle
->linktype
== DLT_LINUX_IRDA
||
1508 handle
->linktype
== DLT_LINUX_LAPD
||
1509 (handle
->linktype
== DLT_EN10MB
&&
1510 (strncmp("isdn", device
, 4) == 0 ||
1511 strncmp("isdY", device
, 4) == 0))) {
1513 * Unknown interface type (-1), or a
1514 * device we explicitly chose to run
1515 * in cooked mode (e.g., PPP devices),
1516 * or an ISDN device (whose link-layer
1517 * type we can only determine by using
1518 * APIs that may be different on different
1519 * kernels) - reopen in cooked mode.
1521 if (close(sock_fd
) == -1) {
1522 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1523 "close: %s", pcap_strerror(errno
));
1526 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
1528 if (sock_fd
== -1) {
1529 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1530 "socket: %s", pcap_strerror(errno
));
1533 handle
->md
.cooked
= 1;
1536 * Get rid of any link-layer type list
1537 * we allocated - this only supports cooked
1540 if (handle
->dlt_list
!= NULL
) {
1541 free(handle
->dlt_list
);
1542 handle
->dlt_list
= NULL
;
1543 handle
->dlt_count
= 0;
1546 if (handle
->linktype
== -1) {
1548 * Warn that we're falling back on
1549 * cooked mode; we may want to
1550 * update "map_arphrd_to_dlt()"
1551 * to handle the new type.
1553 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1555 "supported by libpcap - "
1556 "falling back to cooked "
1560 /* IrDA capture is not a real "cooked" capture,
1561 * it's IrLAP frames, not IP packets. */
1562 if (handle
->linktype
!= DLT_LINUX_IRDA
&&
1563 handle
->linktype
!= DLT_LINUX_LAPD
)
1564 handle
->linktype
= DLT_LINUX_SLL
;
1567 handle
->md
.ifindex
= iface_get_id(sock_fd
, device
, ebuf
);
1568 if (handle
->md
.ifindex
== -1)
1571 if ((err
= iface_bind(sock_fd
, handle
->md
.ifindex
,
1579 * This is cooked mode.
1581 handle
->md
.cooked
= 1;
1582 handle
->linktype
= DLT_LINUX_SLL
;
1585 * We're not bound to a device.
1586 * XXX - true? Or true only if we're using
1588 * For now, we're using this as an indication
1589 * that we can't transmit; stop doing that only
1590 * if we figure out how to transmit in cooked
1593 handle
->md
.ifindex
= -1;
1597 * Select promiscuous mode on if "promisc" is set.
1599 * Do not turn allmulti mode on if we don't select
1600 * promiscuous mode - on some devices (e.g., Orinoco
1601 * wireless interfaces), allmulti mode isn't supported
1602 * and the driver implements it by turning promiscuous
1603 * mode on, and that screws up the operation of the
1604 * card as a normal networking interface, and on no
1605 * other platform I know of does starting a non-
1606 * promiscuous capture affect which multicast packets
1607 * are received by the interface.
1611 * Hmm, how can we set promiscuous mode on all interfaces?
1612 * I am not sure if that is possible at all.
1615 if (device
&& promisc
) {
1616 memset(&mr
, 0, sizeof(mr
));
1617 mr
.mr_ifindex
= handle
->md
.ifindex
;
1618 mr
.mr_type
= PACKET_MR_PROMISC
;
1619 if (setsockopt(sock_fd
, SOL_PACKET
,
1620 PACKET_ADD_MEMBERSHIP
, &mr
, sizeof(mr
)) == -1)
1622 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1623 "setsockopt: %s", pcap_strerror(errno
));
1628 /* Save the socket FD in the pcap structure */
1630 handle
->fd
= sock_fd
;
1641 * Get rid of any link-layer type list we allocated.
1643 if (handle
->dlt_list
!= NULL
)
1644 free(handle
->dlt_list
);
1650 "New packet capturing interface not supported by build "
1651 "environment", PCAP_ERRBUF_SIZE
);
1656 #ifdef HAVE_PF_PACKET_SOCKETS
1658 * Return the index of the given device name. Fill ebuf and return
1662 iface_get_id(int fd
, const char *device
, char *ebuf
)
1666 memset(&ifr
, 0, sizeof(ifr
));
1667 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1669 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
1670 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1671 "SIOCGIFINDEX: %s", pcap_strerror(errno
));
1675 return ifr
.ifr_ifindex
;
1679 * Bind the socket associated with FD to the given device.
1682 iface_bind(int fd
, int ifindex
, char *ebuf
)
1684 struct sockaddr_ll sll
;
1686 socklen_t errlen
= sizeof(err
);
1688 memset(&sll
, 0, sizeof(sll
));
1689 sll
.sll_family
= AF_PACKET
;
1690 sll
.sll_ifindex
= ifindex
;
1691 sll
.sll_protocol
= htons(ETH_P_ALL
);
1693 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
1694 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1695 "bind: %s", pcap_strerror(errno
));
1699 /* Any pending errors, e.g., network is down? */
1701 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
1702 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1703 "getsockopt: %s", pcap_strerror(errno
));
1708 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1709 "bind: %s", pcap_strerror(err
));
1719 /* ===== Functions to interface to the older kernels ================== */
1722 * With older kernels promiscuous mode is kind of interesting because we
1723 * have to reset the interface before exiting. The problem can't really
1724 * be solved without some daemon taking care of managing usage counts.
1725 * If we put the interface into promiscuous mode, we set a flag indicating
1726 * that we must take it out of that mode when the interface is closed,
1727 * and, when closing the interface, if that flag is set we take it out
1728 * of promiscuous mode.
1732 * List of pcaps for which we turned promiscuous mode on by hand.
1733 * If there are any such pcaps, we arrange to call "pcap_close_all()"
1734 * when we exit, and have it close all of them to turn promiscuous mode
1737 static struct pcap
*pcaps_to_close
;
1740 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1741 * be called on exit.
1743 static int did_atexit
;
1745 static void pcap_close_all(void)
1747 struct pcap
*handle
;
1749 while ((handle
= pcaps_to_close
) != NULL
)
1753 static void pcap_close_linux( pcap_t
*handle
)
1756 pcap_close_acn(handle
);
1758 struct pcap
*p
, *prevp
;
1761 if (handle
->md
.clear_promisc
) {
1763 * We put the interface into promiscuous mode; take
1764 * it out of promiscuous mode.
1766 * XXX - if somebody else wants it in promiscuous mode,
1767 * this code cannot know that, so it'll take it out
1768 * of promiscuous mode. That's not fixable in 2.0[.x]
1771 memset(&ifr
, 0, sizeof(ifr
));
1772 strncpy(ifr
.ifr_name
, handle
->md
.device
, sizeof(ifr
.ifr_name
));
1773 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1775 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1776 "Please adjust manually.\n"
1777 "Hint: This can't happen with Linux >= 2.2.0.\n",
1780 if (ifr
.ifr_flags
& IFF_PROMISC
) {
1782 * Promiscuous mode is currently on; turn it
1785 ifr
.ifr_flags
&= ~IFF_PROMISC
;
1786 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1788 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1789 "Please adjust manually.\n"
1790 "Hint: This can't happen with Linux >= 2.2.0.\n",
1797 * Take this pcap out of the list of pcaps for which we
1798 * have to take the interface out of promiscuous mode.
1800 for (p
= pcaps_to_close
, prevp
= NULL
; p
!= NULL
;
1801 prevp
= p
, p
= p
->md
.next
) {
1804 * Found it. Remove it from the list.
1806 if (prevp
== NULL
) {
1808 * It was at the head of the list.
1810 pcaps_to_close
= p
->md
.next
;
1813 * It was in the middle of the list.
1815 prevp
->md
.next
= p
->md
.next
;
1822 if (handle
->md
.device
!= NULL
)
1823 free(handle
->md
.device
);
1824 handle
->md
.device
= NULL
;
1825 pcap_close_common(handle
);
1830 * Try to open a packet socket using the old kernel interface.
1831 * Returns 0 on failure.
1832 * FIXME: 0 uses to mean success (Sebastian)
1835 live_open_old(pcap_t
*handle
, const char *device
, int promisc
,
1836 int to_ms
, char *ebuf
)
1842 /* Open the socket */
1844 handle
->fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
1845 if (handle
->fd
== -1) {
1846 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1847 "socket: %s", pcap_strerror(errno
));
1851 /* It worked - we are using the old interface */
1852 handle
->md
.sock_packet
= 1;
1854 /* ...which means we get the link-layer header. */
1855 handle
->md
.cooked
= 0;
1857 /* Bind to the given device */
1860 strncpy(ebuf
, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
1864 if (iface_bind_old(handle
->fd
, device
, ebuf
) == -1)
1868 * Try to get the link-layer type.
1870 arptype
= iface_get_arptype(handle
->fd
, device
, ebuf
);
1875 * Try to find the DLT_ type corresponding to that
1878 map_arphrd_to_dlt(handle
, arptype
, 0);
1879 if (handle
->linktype
== -1) {
1880 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1881 "unknown arptype %d", arptype
);
1885 /* Go to promisc mode if requested */
1888 memset(&ifr
, 0, sizeof(ifr
));
1889 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1890 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1891 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1892 "SIOCGIFFLAGS: %s", pcap_strerror(errno
));
1895 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
1897 * Promiscuous mode isn't currently on,
1898 * so turn it on, and remember that
1899 * we should turn it off when the
1904 * If we haven't already done so, arrange
1905 * to have "pcap_close_all()" called when
1909 if (atexit(pcap_close_all
) == -1) {
1911 * "atexit()" failed; don't
1912 * put the interface in
1913 * promiscuous mode, just
1916 strncpy(ebuf
, "atexit failed",
1923 ifr
.ifr_flags
|= IFF_PROMISC
;
1924 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1925 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1927 pcap_strerror(errno
));
1930 handle
->md
.clear_promisc
= 1;
1933 * Add this to the list of pcaps
1934 * to close when we exit.
1936 handle
->md
.next
= pcaps_to_close
;
1937 pcaps_to_close
= handle
;
1942 * Default value for offset to align link-layer payload
1943 * on a 4-byte boundary.
1951 pcap_close_linux(handle
);
1956 * Bind the socket associated with FD to the given device using the
1957 * interface of the old kernels.
1960 iface_bind_old(int fd
, const char *device
, char *ebuf
)
1962 struct sockaddr saddr
;
1964 socklen_t errlen
= sizeof(err
);
1966 memset(&saddr
, 0, sizeof(saddr
));
1967 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
1968 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
1969 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1970 "bind: %s", pcap_strerror(errno
));
1974 /* Any pending errors, e.g., network is down? */
1976 if (getsockopt(fd
, SOL_SOCKET
, SO_ERROR
, &err
, &errlen
) == -1) {
1977 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1978 "getsockopt: %s", pcap_strerror(errno
));
1983 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1984 "bind: %s", pcap_strerror(err
));
1992 /* ===== System calls available on all supported kernels ============== */
1995 * Query the kernel for the MTU of the given interface.
1998 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
2003 return BIGGER_THAN_ALL_MTUS
;
2005 memset(&ifr
, 0, sizeof(ifr
));
2006 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2008 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
2009 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2010 "SIOCGIFMTU: %s", pcap_strerror(errno
));
2018 * Get the hardware type of the given interface as ARPHRD_xxx constant.
2021 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
2025 memset(&ifr
, 0, sizeof(ifr
));
2026 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
2028 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
2029 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
2030 "SIOCGIFHWADDR: %s", pcap_strerror(errno
));
2034 return ifr
.ifr_hwaddr
.sa_family
;
2037 #ifdef SO_ATTACH_FILTER
2039 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
2043 register struct bpf_insn
*p
;
2048 * Make a copy of the filter, and modify that copy if
2051 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
2052 len
= handle
->fcode
.bf_len
;
2053 f
= (struct bpf_insn
*)malloc(prog_size
);
2055 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2056 "malloc: %s", pcap_strerror(errno
));
2059 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
2061 fcode
->filter
= (struct sock_filter
*) f
;
2063 for (i
= 0; i
< len
; ++i
) {
2066 * What type of instruction is this?
2068 switch (BPF_CLASS(p
->code
)) {
2072 * It's a return instruction; is the snapshot
2073 * length a constant, rather than the contents
2074 * of the accumulator?
2076 if (BPF_MODE(p
->code
) == BPF_K
) {
2078 * Yes - if the value to be returned,
2079 * i.e. the snapshot length, is anything
2080 * other than 0, make it 65535, so that
2081 * the packet is truncated by "recvfrom()",
2082 * not by the filter.
2084 * XXX - there's nothing we can easily do
2085 * if it's getting the value from the
2086 * accumulator; we'd have to insert
2087 * code to force non-zero values to be
2098 * It's a load instruction; is it loading
2101 switch (BPF_MODE(p
->code
)) {
2107 * Yes; are we in cooked mode?
2109 if (handle
->md
.cooked
) {
2111 * Yes, so we need to fix this
2114 if (fix_offset(p
) < 0) {
2116 * We failed to do so.
2117 * Return 0, so our caller
2118 * knows to punt to userland.
2128 return 1; /* we succeeded */
2132 fix_offset(struct bpf_insn
*p
)
2135 * What's the offset?
2137 if (p
->k
>= SLL_HDR_LEN
) {
2139 * It's within the link-layer payload; that starts at an
2140 * offset of 0, as far as the kernel packet filter is
2141 * concerned, so subtract the length of the link-layer
2144 p
->k
-= SLL_HDR_LEN
;
2145 } else if (p
->k
== 14) {
2147 * It's the protocol field; map it to the special magic
2148 * kernel offset for that field.
2150 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
2153 * It's within the header, but it's not one of those
2154 * fields; we can't do that in the kernel, so punt
2163 set_kernel_filter(pcap_t
*handle
, struct sock_fprog
*fcode
)
2165 int total_filter_on
= 0;
2171 * The socket filter code doesn't discard all packets queued
2172 * up on the socket when the filter is changed; this means
2173 * that packets that don't match the new filter may show up
2174 * after the new filter is put onto the socket, if those
2175 * packets haven't yet been read.
2177 * This means, for example, that if you do a tcpdump capture
2178 * with a filter, the first few packets in the capture might
2179 * be packets that wouldn't have passed the filter.
2181 * We therefore discard all packets queued up on the socket
2182 * when setting a kernel filter. (This isn't an issue for
2183 * userland filters, as the userland filtering is done after
2184 * packets are queued up.)
2186 * To flush those packets, we put the socket in read-only mode,
2187 * and read packets from the socket until there are no more to
2190 * In order to keep that from being an infinite loop - i.e.,
2191 * to keep more packets from arriving while we're draining
2192 * the queue - we put the "total filter", which is a filter
2193 * that rejects all packets, onto the socket before draining
2196 * This code deliberately ignores any errors, so that you may
2197 * get bogus packets if an error occurs, rather than having
2198 * the filtering done in userland even if it could have been
2199 * done in the kernel.
2201 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2202 &total_fcode
, sizeof(total_fcode
)) == 0) {
2206 * Note that we've put the total filter onto the socket.
2208 total_filter_on
= 1;
2211 * Save the socket's current mode, and put it in
2212 * non-blocking mode; we drain it by reading packets
2213 * until we get an error (which is normally a
2214 * "nothing more to be read" error).
2216 save_mode
= fcntl(handle
->fd
, F_GETFL
, 0);
2217 if (save_mode
!= -1 &&
2218 fcntl(handle
->fd
, F_SETFL
, save_mode
| O_NONBLOCK
) >= 0) {
2219 while (recv(handle
->fd
, &drain
, sizeof drain
,
2223 fcntl(handle
->fd
, F_SETFL
, save_mode
);
2224 if (save_errno
!= EAGAIN
) {
2226 reset_kernel_filter(handle
);
2227 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
2228 "recv: %s", pcap_strerror(save_errno
));
2235 * Now attach the new filter.
2237 ret
= setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
2238 fcode
, sizeof(*fcode
));
2239 if (ret
== -1 && total_filter_on
) {
2241 * Well, we couldn't set that filter on the socket,
2242 * but we could set the total filter on the socket.
2244 * This could, for example, mean that the filter was
2245 * too big to put into the kernel, so we'll have to
2246 * filter in userland; in any case, we'll be doing
2247 * filtering in userland, so we need to remove the
2248 * total filter so we see packets.
2253 * XXX - if this fails, we're really screwed;
2254 * we have the total filter on the socket,
2255 * and it won't come off. What do we do then?
2257 reset_kernel_filter(handle
);
2265 reset_kernel_filter(pcap_t
*handle
)
2268 * setsockopt() barfs unless it get a dummy parameter.
2269 * valgrind whines unless the value is initialized,
2270 * as it has no idea that setsockopt() ignores its
2275 return setsockopt(handle
->fd
, SOL_SOCKET
, SO_DETACH_FILTER
,
2276 &dummy
, sizeof(dummy
));