]>
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.47 2000-12-22 12:24:20 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
69 #include <sys/socket.h>
70 #include <sys/ioctl.h>
71 #include <sys/utsname.h>
73 #include <netinet/in.h>
74 #include <linux/if_ether.h>
75 #include <netinet/if_ether.h>
77 #ifdef HAVE_NETPACKET_PACKET_H
78 #include <netpacket/packet.h>
80 #ifdef SO_ATTACH_FILTER
81 #include <linux/types.h>
82 #include <linux/filter.h>
86 typedef int socklen_t
;
93 #define MAX_LINKHEADER_SIZE 256
96 * When capturing on all interfaces we use this as the buffer size.
97 * Should be bigger then all MTUs that occur in real life.
98 * 64kB should be enough for now.
100 #define BIGGER_THAN_ALL_MTUS (64*1024)
103 * Prototypes for internal functions
105 static int map_arphrd_to_dlt(int arptype
);
106 static int live_open_old(pcap_t
*, char *, int, int, char *);
107 static int live_open_new(pcap_t
*, char *, int, int, char *);
108 static int pcap_read_packet(pcap_t
*, pcap_handler
, u_char
*);
111 * Wrap some ioctl calls
113 #ifdef HAVE_NETPACKET_PACKET_H
114 static int iface_get_id(int fd
, const char *device
, char *ebuf
);
116 static int iface_get_mtu(int fd
, const char *device
, char *ebuf
);
117 static int iface_get_arptype(int fd
, const char *device
, char *ebuf
);
118 #ifdef HAVE_NETPACKET_PACKET_H
119 static int iface_bind(int fd
, int ifindex
, char *ebuf
);
121 static int iface_bind_old(int fd
, const char *device
, char *ebuf
);
123 #ifdef SO_ATTACH_FILTER
124 static int fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
);
125 static int fix_offset(struct bpf_insn
*p
);
129 * Get a handle for a live capture from the given device. You can
130 * pass NULL as device to get all packages (without link level
131 * information of course). If you pass 1 as promisc the interface
132 * will be set to promiscous mode (XXX: I think this usage should
133 * be deprecated and functions be added to select that later allow
134 * modification of that values -- Torsten).
139 pcap_open_live(char *device
, int snaplen
, int promisc
, int to_ms
, char *ebuf
)
141 /* Allocate a handle for this session. */
143 pcap_t
*handle
= malloc(sizeof(*handle
));
144 if (handle
== NULL
) {
145 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s",
146 pcap_strerror(errno
));
150 /* Initialize some components of the pcap structure. */
152 memset(handle
, 0, sizeof(*handle
));
153 handle
->snapshot
= snaplen
;
154 handle
->md
.timeout
= to_ms
;
157 * NULL and "any" are special devices which give us the hint to
158 * monitor all devices.
160 if (!device
|| strcmp(device
, "any") == 0) {
162 handle
->md
.device
= strdup("any");
164 handle
->md
.device
= strdup(device
);
166 if (handle
->md
.device
== NULL
) {
167 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "strdup: %s",
168 pcap_strerror(errno
) );
174 * Current Linux kernels use the protocol family PF_PACKET to
175 * allow direct access to all packets on the network while
176 * older kernels had a special socket type SOCK_PACKET to
177 * implement this feature.
178 * While this old implementation is kind of obsolete we need
179 * to be compatible with older kernels for a while so we are
180 * trying both methods with the newer method preferred.
183 if (! (live_open_new(handle
, device
, promisc
, to_ms
, ebuf
) ||
184 live_open_old(handle
, device
, promisc
, to_ms
, ebuf
)) )
187 * Both methods to open the packet socket failed. Tidy
188 * up and report our failure (ebuf is expected to be
189 * set by the functions above).
192 free(handle
->md
.device
);
198 * Okay, now we have a packet stream open. Maybe we need to handle
199 * a timeout? In that case we set the filehandle to nonblocking
200 * so pcap_read can try reading the fd and call select if no data
201 * is available at first.
205 int flags
= fcntl(handle
->fd
, F_GETFL
);
208 flags
= fcntl(handle
->fd
, F_SETFL
, flags
);
211 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "fcntl: %s",
212 pcap_strerror(errno
));
222 * Read at most max_packets from the capture stream and call the callback
223 * for each of them. Returns the number of packets handled or -1 if an
226 * XXX: Can I rely on the Linux-specified behaviour of select (returning
227 * the time left in the timeval structure)? I really don't want to query
228 * the system time before each select call...
230 * pcap_read currently gets not only a packet from the kernel but also
231 * the sockaddr_ll returned as source of the packet. This way we can at
232 * some time extend tcpdump and libpcap to sniff on all devices at a time
233 * and find the right printing routine by using the information in the
234 * sockaddr_ll structure.
237 pcap_read(pcap_t
*handle
, int max_packets
, pcap_handler callback
, u_char
*user
)
244 * Fill in a timeval structure for select if we need to obeye a
247 if (handle
->md
.timeout
> 0) {
248 tv
.tv_usec
= (handle
->md
.timeout
% 1000) * 1000;
249 tv
.tv_sec
= (handle
->md
.timeout
/ 1000);
253 * Read packets until the packet limit has been reached or
254 * an error occured while reading. Call the user function
255 * for each received packet.
257 for (packets
= 0; max_packets
== -1 || packets
< max_packets
;)
259 status
= pcap_read_packet(handle
, callback
, user
);
264 } else if (status
== -1)
268 * If no packet is available we go to sleep. FIXME: This
269 * might be better implemented using poll(?)
272 FD_SET(handle
->fd
, &read_fds
);
273 status
= select(handle
->fd
+ 1,
274 &read_fds
, NULL
, NULL
, &tv
);
279 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
280 "select: %s", pcap_strerror(errno
));
283 else if (status
== 0 ||
284 (tv
.tv_usec
== 0 && tv
.tv_sec
== 0))
292 * Read a packet from the socket calling the handler provided by
293 * the user. Returns the number of packets received or -1 if an
297 pcap_read_packet(pcap_t
*handle
, pcap_handler callback
, u_char
*userdata
)
300 #ifdef HAVE_NETPACKET_PACKET_H
301 struct sockaddr_ll from
;
302 struct sll_header
*hdrp
;
304 struct sockaddr from
;
307 int packet_len
, caplen
;
308 struct pcap_pkthdr pcap_header
;
310 #ifdef HAVE_NETPACKET_PACKET_H
312 * If this is a cooked device, leave extra room for a
313 * fake packet header.
315 if (handle
->md
.cooked
)
316 offset
= SLL_HDR_LEN
;
321 * This system doesn't have PF_PACKET sockets, so it doesn't
322 * support cooked devices.
327 /* Receive a single packet from the kernel */
330 fromlen
= sizeof(from
);
331 packet_len
= recvfrom(
332 handle
->fd
, handle
->buffer
+ offset
+ handle
->offset
,
333 handle
->md
.readlen
- offset
, MSG_TRUNC
,
334 (struct sockaddr
*) &from
, &fromlen
);
335 } while (packet_len
== -1 && errno
== EINTR
);
337 /* Check if an error occured */
339 if (packet_len
== -1) {
341 return 0; /* no packet there */
343 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
344 "recvfrom: %s", pcap_strerror(errno
));
349 #ifdef HAVE_NETPACKET_PACKET_H
351 * If this is from the loopback device, reject outgoing packets;
352 * we'll see the packet as an incoming packet as well, and
353 * we don't want to see it twice.
355 * We can only do this if we're using PF_PACKET; the address
356 * returned for SOCK_PACKET is a "sockaddr_pkt" which lacks
357 * the relevant packet type information.
359 if (!handle
->md
.sock_packet
&&
360 from
.sll_ifindex
== handle
->md
.lo_ifindex
&&
361 from
.sll_pkttype
== PACKET_OUTGOING
)
365 #ifdef HAVE_NETPACKET_PACKET_H
367 * If this is a cooked device, fill in the fake packet header.
369 if (handle
->md
.cooked
) {
371 * Add the length of the fake header to the length
372 * of packet data we read.
374 packet_len
+= SLL_HDR_LEN
;
376 hdrp
= (struct sll_header
*)handle
->buffer
;
379 * Map the PACKET_ value to a LINUX_SLL_ value; we
380 * want the same numerical value to be used in
381 * the link-layer header even if the numerical values
382 * for the PACKET_ #defines change, so that programs
383 * that look at the packet type field will always be
384 * able to handle DLT_LINUX_SLL captures.
386 switch (from
.sll_pktttype
) {
389 hdrp
->sll_pkttype
= htons(LINUX_SLL_HOST
);
392 case PACKET_BROADCAST
:
393 hdrp
->sll_pkttype
= htons(LINUX_SLL_BROADCAST
);
396 case PACKET_MULTICAST
:
397 hdrp
->sll_pkttype
= htons(LINUX_SLL_MULTICAST
);
400 case PACKET_OTHERHOST
:
401 hdrp
->sll_pkttype
= htons(LINUX_SLL_OTHERHOST
);
404 case PACKET_OUTGOING
:
405 hdrp
->sll_pkttype
= htons(LINUX_SLL_OUTGOING
);
409 hdrp
->sll_pkttype
= -1;
413 hdrp
->sll_protocol
= from
.sll_protocol
;
414 hdrp
->sll_hatype
= htons(from
.sll_hatype
);
415 hdrp
->sll_halen
= htons(from
.sll_halen
);
416 memcpy(hdrp
->sll_addr
, from
.sll_addr
,
417 (from
.sll_halen
> SLL_ADDRLEN
) ?
424 * XXX: According to the kernel source we should get the real
425 * packet len if calling recvfrom with MSG_TRUNC set. It does
426 * not seem to work here :(, but it is supported by this code
428 * To be honest the code RELIES on that feature so this is really
429 * broken with 2.2.x kernels.
430 * I spend a day to figure out what's going on and I found out
431 * that the following is happening:
433 * The packet comes from a random interface and the packet_rcv
434 * hook is called with a clone of the packet. That code inserts
435 * the packet into the receive queue of the packet socket.
436 * If a filter is attached to that socket that filter is run
437 * first - and there lies the problem. The default filter always
438 * cuts the packet at the snaplen:
443 * So the packet filter cuts down the packet. The recvfrom call
444 * says "hey, it's only 68 bytes, it fits into the buffer" with
445 * the result that we don't get the real packet length. This
446 * is valid at least until kernel 2.2.17pre6.
448 * We currently handle this by making a copy of the filter
449 * program, fixing all "ret" instructions with non-zero
450 * operands to have an operand of 65535 so that the filter
451 * doesn't truncate the packet, and supplying that modified
452 * filter to the kernel.
456 if (caplen
> handle
->snapshot
)
457 caplen
= handle
->snapshot
;
459 /* Run the packet filter if not using kernel filter */
460 if (!handle
->md
.use_bpf
&& handle
->fcode
.bf_insns
) {
461 if (bpf_filter(handle
->fcode
.bf_insns
, handle
->buffer
,
462 packet_len
, caplen
) == 0)
464 /* rejected by filter */
469 /* Fill in our own header data */
471 if (ioctl(handle
->fd
, SIOCGSTAMP
, &pcap_header
.ts
) == -1) {
472 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
473 "ioctl: %s", pcap_strerror(errno
));
476 pcap_header
.caplen
= caplen
;
477 pcap_header
.len
= packet_len
;
479 /* Call the user supplied callback function */
480 handle
->md
.stat
.ps_recv
++;
481 callback(userdata
, &pcap_header
, handle
->buffer
+ handle
->offset
);
487 * Get the statistics for the given packet capture handle.
488 * FIXME: Currently does not report the number of dropped packets.
491 pcap_stats(pcap_t
*handle
, struct pcap_stat
*stats
)
493 *stats
= handle
->md
.stat
;
498 * Attach the given BPF code to the packet capture device.
501 pcap_setfilter(pcap_t
*handle
, struct bpf_program
*filter
)
503 #ifdef SO_ATTACH_FILTER
504 struct sock_fprog fcode
;
505 int can_filter_in_kernel
;
511 strncpy(handle
->errbuf
, "setfilter: No filter specified",
512 sizeof(handle
->errbuf
));
516 /* Make our private copy of the filter */
518 if (install_bpf_program(handle
, filter
) < 0) {
519 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
520 "malloc: %s", pcap_strerror(errno
));
525 * Run user level packet filter by default. Will be overriden if
526 * installing a kernel filter succeeds.
528 handle
->md
.use_bpf
= 0;
531 * If we're reading from a savefile, don't try to install
534 if (handle
->sf
.rfile
!= NULL
)
537 /* Install kernel level filter if possible */
539 #ifdef SO_ATTACH_FILTER
541 if (handle
->fcode
.bf_len
> USHRT_MAX
) {
543 * fcode.len is an unsigned short for current kernel.
544 * I have yet to see BPF-Code with that much
545 * instructions but still it is possible. So for the
546 * sake of correctness I added this check.
548 fprintf(stderr
, "Warning: Filter too complex for kernel\n");
550 can_filter_in_kernel
= 0;
552 #endif /* USHRT_MAX */
555 * Oh joy, the Linux kernel uses struct sock_fprog instead
556 * of struct bpf_program and of course the length field is
557 * of different size. Pointed out by Sebastian
559 * Oh, and we also need to fix it up so that all "ret"
560 * instructions with non-zero operands have 65535 as the
561 * operand, and so that, if we're in cooked mode, all
562 * memory-reference instructions use special magic offsets
563 * in references to the link-layer header and assume that
564 * the link-layer payload begins at 0; "fix_program()"
567 switch (fix_program(handle
, &fcode
)) {
572 * Fatal error; just quit.
573 * (The "default" case shouldn't happen; we
574 * return -1 for that reason.)
580 * The program performed checks that we can't make
581 * work in the kernel.
583 can_filter_in_kernel
= 0;
588 * We have a filter that'll work in the kernel.
590 can_filter_in_kernel
= 1;
595 if (can_filter_in_kernel
) {
596 if (setsockopt(handle
->fd
, SOL_SOCKET
, SO_ATTACH_FILTER
,
597 &fcode
, sizeof(fcode
)) == 0)
599 /* Installation succeded - using kernel filter. */
600 handle
->md
.use_bpf
= 1;
605 * Print a warning if we weren't able to install
606 * the filter for a reason other than "this kernel
607 * isn't configured to support socket filters.
609 if (errno
!= ENOPROTOOPT
&& errno
!= EOPNOTSUPP
) {
611 "Warning: Kernel filter failed: %s\n",
612 pcap_strerror(errno
));
618 * Free up the copy of the filter that was made by "fix_program()".
620 if (fcode
.filter
!= NULL
)
622 #endif /* SO_ATTACH_FILTER */
628 * Linux uses the ARP hardware type to identify the type of an
629 * interface. pcap uses the DLT_xxx constants for this. This
630 * function maps the ARPHRD_xxx constant to an appropriate
633 * Returns -1 if unable to map the type; we print a message and,
634 * if we're using PF_PACKET/SOCK_RAW rather than PF_INET/SOCK_PACKET,
635 * we fall back on using PF_PACKET/SOCK_DGRAM.
637 static int map_arphrd_to_dlt(int arptype
)
641 case ARPHRD_METRICOM
:
642 case ARPHRD_LOOPBACK
: return DLT_EN10MB
;
643 case ARPHRD_EETHER
: return DLT_EN3MB
;
644 case ARPHRD_AX25
: return DLT_AX25
;
645 case ARPHRD_PRONET
: return DLT_PRONET
;
646 case ARPHRD_CHAOS
: return DLT_CHAOS
;
647 #ifndef ARPHRD_IEEE802_TR
648 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
650 case ARPHRD_IEEE802_TR
:
651 case ARPHRD_IEEE802
: return DLT_IEEE802
;
652 case ARPHRD_ARCNET
: return DLT_ARCNET
;
653 case ARPHRD_FDDI
: return DLT_FDDI
;
655 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
656 #define ARPHRD_ATM 19
658 case ARPHRD_ATM
: return DLT_ATM_CLIP
;
661 /* Not sure if this is correct for all tunnels, but it
668 case ARPHRD_SLIP
: return DLT_RAW
;
674 /* ===== Functions to interface to the newer kernels ================== */
677 * Try to open a packet socket using the new kernel interface.
678 * Returns 0 on failure.
679 * FIXME: 0 uses to mean success (Sebastian)
682 live_open_new(pcap_t
*handle
, char *device
, int promisc
,
683 int to_ms
, char *ebuf
)
685 #ifdef HAVE_NETPACKET_PACKET_H
686 int sock_fd
= -1, device_id
, mtu
, arptype
;
687 struct packet_mreq mr
;
689 /* One shot loop used for error handling - bail out with break */
693 * Open a socket with protocol family packet. If a device is
694 * given we try to open it in raw mode otherwise we use
695 * the cooked interface.
698 socket(PF_PACKET
, SOCK_RAW
, htons(ETH_P_ALL
))
699 : socket(PF_PACKET
, SOCK_DGRAM
, htons(ETH_P_ALL
));
702 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "socket: %s",
703 pcap_strerror(errno
) );
707 /* It seems the kernel supports the new interface. */
708 handle
->md
.sock_packet
= 0;
711 * Get the interface index of the loopback device.
712 * If the attempt fails, don't fail, just set the
713 * "md.lo_ifindex" to -1.
715 * XXX - can there be more than one device that loops
716 * packets back, i.e. devices other than "lo"? If so,
717 * we'd need to find them all, and have an array of
718 * indices for them, and check all of them in
719 * "pcap_read_packet()".
721 handle
->md
.lo_ifindex
= iface_get_id(sock_fd
, "lo", ebuf
);
724 * What kind of frames do we have to deal with? Fall back
725 * to cooked mode if we have an unknown interface type.
729 /* Assume for now we don't need cooked mode. */
730 handle
->md
.cooked
= 0;
732 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
735 handle
->linktype
= map_arphrd_to_dlt(arptype
);
736 if (handle
->linktype
== -1 ||
737 (handle
->linktype
== DLT_EN10MB
&&
738 (strncmp("isdn", device
, 4) == 0 ||
739 strncmp("isdY", device
, 4) == 0))) {
741 * Unknown interface type (-1), or an ISDN
742 * device (whose link-layer type we
743 * can only determine by using APIs
744 * that may be different on different
745 * kernels) - reopen in cooked mode.
747 * XXX - do that with DLT_RAW as well?
749 if (close(sock_fd
) == -1) {
750 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
751 "close: %s", pcap_strerror(errno
));
754 sock_fd
= socket(PF_PACKET
, SOCK_DGRAM
,
757 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
758 "socket: %s", pcap_strerror(errno
));
761 handle
->md
.cooked
= 1;
763 if (handle
->linktype
== -1) {
765 * Warn that we're falling back on
766 * cooked mode; we may want to
767 * update "map_arphrd_to_dlt()"
768 * to handle the new type.
771 "Warning: arptype %d not "
772 "supported by libpcap - "
773 "falling back to cooked "
777 handle
->linktype
= DLT_LINUX_SLL
;
780 device_id
= iface_get_id(sock_fd
, device
, ebuf
);
784 if (iface_bind(sock_fd
, device_id
, ebuf
) == -1)
788 * This is cooked mode.
790 handle
->md
.cooked
= 1;
791 handle
->linktype
= DLT_LINUX_SLL
;
794 * XXX - squelch GCC complaints about
795 * uninitialized variables; if we can't
796 * select promiscuous mode on all interfaces,
797 * we should move the code below into the
798 * "if (device)" branch of the "if" and
799 * get rid of the next statement.
804 /* Select promiscuous mode on/off */
808 * Hmm, how can we set promiscuous mode on all interfaces?
809 * I am not sure if that is possible at all.
813 memset(&mr
, 0, sizeof(mr
));
814 mr
.mr_ifindex
= device_id
;
815 mr
.mr_type
= promisc
?
816 PACKET_MR_PROMISC
: PACKET_MR_ALLMULTI
;
817 if (setsockopt(sock_fd
, SOL_PACKET
,
818 PACKET_ADD_MEMBERSHIP
, &mr
, sizeof(mr
)) == -1)
820 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
821 "setsockopt: %s", pcap_strerror(errno
));
827 /* Compute the buffersize */
829 mtu
= iface_get_mtu(sock_fd
, device
, ebuf
);
832 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
834 /* Fill in the pcap structure */
836 handle
->fd
= sock_fd
;
839 handle
->buffer
= malloc(handle
->bufsize
);
840 if (!handle
->buffer
) {
841 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
842 "malloc: %s", pcap_strerror(errno
));
847 * This is a 2.2 or later kernel, as it has PF_PACKET;
848 * "recvfrom()", when passed the MSG_TRUNC flag, will
849 * return the actual length of the packet, not the
850 * number of bytes from the packet copied to userland,
851 * so we can safely pass it a byte count based on the
854 handle
->md
.readlen
= handle
->snapshot
;
864 "New packet capturing interface not supported by build "
865 "environment", PCAP_ERRBUF_SIZE
);
870 #ifdef HAVE_NETPACKET_PACKET_H
872 * Return the index of the given device name. Fill ebuf and return
876 iface_get_id(int fd
, const char *device
, char *ebuf
)
880 memset(&ifr
, 0, sizeof(ifr
));
881 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
883 if (ioctl(fd
, SIOCGIFINDEX
, &ifr
) == -1) {
884 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
885 "ioctl: %s", pcap_strerror(errno
));
889 return ifr
.ifr_ifindex
;
893 * Bind the socket associated with FD to the given device.
896 iface_bind(int fd
, int ifindex
, char *ebuf
)
898 struct sockaddr_ll sll
;
900 memset(&sll
, 0, sizeof(sll
));
901 sll
.sll_family
= AF_PACKET
;
902 sll
.sll_ifindex
= ifindex
;
903 sll
.sll_protocol
= htons(ETH_P_ALL
);
905 if (bind(fd
, (struct sockaddr
*) &sll
, sizeof(sll
)) == -1) {
906 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
907 "bind: %s", pcap_strerror(errno
));
917 /* ===== Functions to interface to the older kernels ================== */
920 * With older kernels promiscuous mode is kind of interesting because we
921 * have to reset the interface before exiting. The problem can't really
922 * be solved without some daemon taking care of managing usage counts.
923 * If we put the interface into promiscuous mode, we set a flag indicating
924 * that we must take it out of that mode when the interface is closed,
925 * and, when closing the interface, if that flag is set we take it out
926 * of promiscuous mode.
930 * List of pcaps for which we turned promiscuous mode on by hand.
931 * If there are any such pcaps, we arrange to call "pcap_close_all()"
932 * when we exit, and have it close all of them to turn promiscuous mode
935 static struct pcap
*pcaps_to_close
;
938 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
941 static int did_atexit
;
943 static void pcap_close_all(void)
947 while ((handle
= pcaps_to_close
) != NULL
)
951 void pcap_close_linux( pcap_t
*handle
)
953 struct pcap
*p
, *prevp
;
956 if (handle
->md
.clear_promisc
) {
958 * We put the interface into promiscuous mode; take
959 * it out of promiscuous mode.
961 * XXX - if somebody else wants it in promiscuous mode,
962 * this code cannot know that, so it'll take it out
963 * of promiscuous mode. That's not fixable in 2.0[.x]
966 memset(&ifr
, 0, sizeof(ifr
));
967 strncpy(ifr
.ifr_name
, handle
->md
.device
, sizeof(ifr
.ifr_name
));
968 if (ioctl(handle
->fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
970 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
971 "Please adjust manually.\n"
972 "Hint: This can't happen with Linux >= 2.2.0.\n",
975 if (ifr
.ifr_flags
& IFF_PROMISC
) {
977 * Promiscuous mode is currently on; turn it
980 ifr
.ifr_flags
&= ~IFF_PROMISC
;
981 if (ioctl(handle
->fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
983 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
984 "Please adjust manually.\n"
985 "Hint: This can't happen with Linux >= 2.2.0.\n",
992 * Take this pcap out of the list of pcaps for which we
993 * have to take the interface out of promiscuous mode.
995 for (p
= pcaps_to_close
, prevp
= NULL
; p
!= NULL
;
996 prevp
= p
, p
= p
->md
.next
) {
999 * Found it. Remove it from the list.
1001 if (prevp
== NULL
) {
1003 * It was at the head of the list.
1005 pcaps_to_close
= p
->md
.next
;
1008 * It was in the middle of the list.
1010 prevp
->md
.next
= p
->md
.next
;
1016 if (handle
->md
.device
!= NULL
)
1017 free(handle
->md
.device
);
1021 * Try to open a packet socket using the old kernel interface.
1022 * Returns 0 on failure.
1023 * FIXME: 0 uses to mean success (Sebastian)
1026 live_open_old(pcap_t
*handle
, char *device
, int promisc
,
1027 int to_ms
, char *ebuf
)
1029 int sock_fd
= -1, mtu
, arptype
;
1030 struct utsname utsname
;
1034 /* Open the socket */
1036 sock_fd
= socket(PF_INET
, SOCK_PACKET
, htons(ETH_P_ALL
));
1037 if (sock_fd
== -1) {
1038 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1039 "socket: %s", pcap_strerror(errno
));
1043 /* It worked - we are using the old interface */
1044 handle
->md
.sock_packet
= 1;
1046 /* ...which means we get the link-layer header. */
1047 handle
->md
.cooked
= 0;
1049 /* Bind to the given device */
1052 strncpy(ebuf
, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
1056 if (iface_bind_old(sock_fd
, device
, ebuf
) == -1)
1059 /* Go to promisc mode */
1061 memset(&ifr
, 0, sizeof(ifr
));
1062 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1063 if (ioctl(sock_fd
, SIOCGIFFLAGS
, &ifr
) == -1) {
1064 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1065 "ioctl: %s", pcap_strerror(errno
));
1068 if ((ifr
.ifr_flags
& IFF_PROMISC
) == 0) {
1070 * Promiscuous mode isn't currently on,
1071 * so turn it on, and remember that
1072 * we should turn it off when the
1077 * If we haven't already done so, arrange
1078 * to have "pcap_close_all()" called when
1082 if (atexit(pcap_close_all
) == -1) {
1084 * "atexit()" failed; don't
1085 * put the interface in
1086 * promiscuous mode, just
1089 strncpy(ebuf
, "atexit failed",
1095 ifr
.ifr_flags
|= IFF_PROMISC
;
1096 if (ioctl(sock_fd
, SIOCSIFFLAGS
, &ifr
) == -1) {
1097 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1099 pcap_strerror(errno
));
1102 handle
->md
.clear_promisc
= 1;
1105 * Add this to the list of pcaps
1106 * to close when we exit.
1108 handle
->md
.next
= pcaps_to_close
;
1109 pcaps_to_close
= handle
;
1113 /* Compute the buffersize */
1115 mtu
= iface_get_mtu(sock_fd
, device
, ebuf
);
1118 handle
->bufsize
= MAX_LINKHEADER_SIZE
+ mtu
;
1119 if (handle
->bufsize
< handle
->snapshot
)
1120 handle
->bufsize
= handle
->snapshot
;
1122 /* All done - fill in the pcap handle */
1124 arptype
= iface_get_arptype(sock_fd
, device
, ebuf
);
1128 handle
->fd
= sock_fd
;
1130 handle
->linktype
= map_arphrd_to_dlt(arptype
);
1132 * XXX - handle ISDN types here? We can't fall back on
1133 * cooked sockets, so we'd have to figure out from the
1134 * device name what type of link-layer encapsulation
1135 * it's using, and map that to an appropriate DLT_
1136 * value, meaning we'd map "isdnN" devices to DLT_RAW
1137 * (they supply raw IP packets with no link-layer
1138 * header) and "isdY" devices to a new DLT_I4L_IP
1139 * type that has only an Ethernet packet type as
1140 * a link-layer header.
1142 if (handle
->linktype
== -1) {
1143 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1144 "interface type of %s not supported", device
);
1147 handle
->buffer
= malloc(handle
->bufsize
);
1148 if (!handle
->buffer
) {
1149 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1150 "malloc: %s", pcap_strerror(errno
));
1155 * This might be a 2.0[.x] kernel - check.
1157 if (uname(&utsname
) < 0 ||
1158 strncmp(utsname
.release
, "2.0", 3) == 0) {
1160 * Either we couldn't find out what kernel release
1161 * this is, or it's a 2.0[.x] kernel.
1163 * In the 2.0[.x] kernel, a "recvfrom()" on
1164 * a SOCK_PACKET socket, with MSG_TRUNC set, will
1165 * return the number of bytes read, so if we pass
1166 * a length based on the snapshot length, it'll
1167 * return the number of bytes from the packet
1168 * copied to userland, not the actual length
1171 * This means that, for example, the IP dissector
1172 * in tcpdump will get handed a packet length less
1173 * than the length in the IP header, and will
1174 * complain about "truncated-ip".
1176 * So we don't bother trying to copy from the
1177 * kernel only the bytes in which we're interested,
1178 * but instead copy them all, just as the older
1179 * versions of libpcap for Linux did.
1181 * Just one of many problems with packet capture
1182 * on 2.0[.x] kernels; you really want a 2.2[.x]
1183 * or later kernel if you want packet capture to
1186 handle
->md
.readlen
= handle
->bufsize
;
1189 * This is a 2.2[.x] or later kernel (although
1190 * why we're using SOCK_PACKET on such a system
1191 * is unknown to me).
1193 * We can safely pass "recvfrom()" a byte count
1194 * based on the snapshot length.
1196 handle
->md
.readlen
= handle
->snapshot
;
1208 * Bind the socket associated with FD to the given device using the
1209 * interface of the old kernels.
1212 iface_bind_old(int fd
, const char *device
, char *ebuf
)
1214 struct sockaddr saddr
;
1216 memset(&saddr
, 0, sizeof(saddr
));
1217 strncpy(saddr
.sa_data
, device
, sizeof(saddr
.sa_data
));
1218 if (bind(fd
, &saddr
, sizeof(saddr
)) == -1) {
1219 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1220 "bind: %s", pcap_strerror(errno
));
1228 /* ===== System calls available on all supported kernels ============== */
1231 * Query the kernel for the MTU of the given interface.
1234 iface_get_mtu(int fd
, const char *device
, char *ebuf
)
1239 return BIGGER_THAN_ALL_MTUS
;
1241 memset(&ifr
, 0, sizeof(ifr
));
1242 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1244 if (ioctl(fd
, SIOCGIFMTU
, &ifr
) == -1) {
1245 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1246 "ioctl: %s", pcap_strerror(errno
));
1254 * Get the hardware type of the given interface as ARPHRD_xxx constant.
1257 iface_get_arptype(int fd
, const char *device
, char *ebuf
)
1261 memset(&ifr
, 0, sizeof(ifr
));
1262 strncpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1264 if (ioctl(fd
, SIOCGIFHWADDR
, &ifr
) == -1) {
1265 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1266 "ioctl: %s", pcap_strerror(errno
));
1270 return ifr
.ifr_hwaddr
.sa_family
;
1273 #ifdef HAVE_NETPACKET_PACKET_H
1275 fix_program(pcap_t
*handle
, struct sock_fprog
*fcode
)
1279 register struct bpf_insn
*p
;
1284 * Make a copy of the filter, and modify that copy if
1287 prog_size
= sizeof(*handle
->fcode
.bf_insns
) * handle
->fcode
.bf_len
;
1288 len
= handle
->fcode
.bf_len
;
1289 f
= (struct bpf_insn
*)malloc(prog_size
);
1291 snprintf(handle
->errbuf
, sizeof(handle
->errbuf
),
1292 "malloc: %s", pcap_strerror(errno
));
1295 memcpy(f
, handle
->fcode
.bf_insns
, prog_size
);
1297 fcode
->filter
= (struct sock_filter
*) f
;
1299 for (i
= 0; i
< len
; ++i
) {
1302 * What type of instruction is this?
1304 switch (BPF_CLASS(p
->code
)) {
1308 * It's a return instruction; is the snapshot
1309 * length a constant, rather than the contents
1310 * of the accumulator?
1312 if (BPF_MODE(p
->code
) == BPF_K
) {
1314 * Yes - if the value to be returned,
1315 * i.e. the snapshot length, is anything
1316 * other than 0, make it 65535, so that
1317 * the packet is truncated by "recvfrom()",
1318 * not by the filter.
1320 * XXX - there's nothing we can easily do
1321 * if it's getting the value from the
1322 * accumulator; we'd have to insert
1323 * code to force non-zero values to be
1334 * It's a load instruction; is it loading
1337 switch (BPF_MODE(p
->code
)) {
1343 * Yes; are we in cooked mode?
1345 if (handle
->md
.cooked
) {
1347 * Yes, so we need to fix this
1350 if (fix_offset(p
) < 0) {
1352 * We failed to do so.
1353 * Return 0, so our caller
1354 * knows to punt to userland.
1364 return 1; /* we succeeded */
1368 fix_offset(struct bpf_insn
*p
)
1371 * What's the offset?
1373 if (p
->k
>= SLL_HDR_LEN
) {
1375 * It's within the link-layer payload; that starts at an
1376 * offset of 0, as far as the kernel packet filter is
1377 * concerned, so subtract the length of the link-layer
1380 p
->k
-= SLL_HDR_LEN
;
1381 } else if (p
->k
== 2) {
1383 * It's the protocol field; map it to the special magic
1384 * kernel offset for that field.
1386 p
->k
= SKF_AD_OFF
+ SKF_AD_PROTOCOL
;
1389 * It's within the header, but it's not one of those
1390 * fields; we can't do that in the kernel, so punt