add winpcap 4.0.2 from url http://www.winpcap.org/
[natblaster.git] / winpcap / wpcap / libpcap / pcap-linux.c
blob29422d79d86959d40ccf0f9d5976987ab08568e5
1 /*
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>
7 * License: BSD
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
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
18 * distribution.
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
21 * written permission.
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 #ifndef lint
29 static const char rcsid[] _U_ =
30 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.110.2.12 2006/09/18 17:34:31 guy Exp $ (LBL)";
31 #endif
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
42 * us do that.
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
54 * the socket.
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.
76 #ifdef HAVE_CONFIG_H
77 #include "config.h"
78 #endif
80 #include "pcap-int.h"
81 #include "sll.h"
83 #ifdef HAVE_DAG_API
84 #include "pcap-dag.h"
85 #endif /* HAVE_DAG_API */
87 #ifdef HAVE_SEPTEL_API
88 #include "pcap-septel.h"
89 #endif /* HAVE_SEPTEL_API */
91 #include <errno.h>
92 #include <stdlib.h>
93 #include <unistd.h>
94 #include <fcntl.h>
95 #include <string.h>
96 #include <sys/socket.h>
97 #include <sys/ioctl.h>
98 #include <sys/utsname.h>
99 #include <net/if.h>
100 #include <netinet/in.h>
101 #include <linux/if_ether.h>
102 #include <net/if_arp.h>
104 #ifdef HAVE_REMOTE
105 #include <pcap-remote.h>
106 #endif
109 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
110 * sockets rather than SOCK_PACKET sockets.
112 * To use them, we include <linux/if_packet.h> rather than
113 * <netpacket/packet.h>; we do so because
115 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
116 * later kernels and libc5, and don't provide a <netpacket/packet.h>
117 * file;
119 * not all versions of glibc2 have a <netpacket/packet.h> file
120 * that defines stuff needed for some of the 2.4-or-later-kernel
121 * features, so if the system has a 2.4 or later kernel, we
122 * still can't use those features.
124 * We're already including a number of other <linux/XXX.h> headers, and
125 * this code is Linux-specific (no other OS has PF_PACKET sockets as
126 * a raw packet capture mechanism), so it's not as if you gain any
127 * useful portability by using <netpacket/packet.h>
129 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
130 * isn't defined? It only defines one data structure in 2.0.x, so
131 * it shouldn't cause any problems.
133 #ifdef PF_PACKET
134 # include <linux/if_packet.h>
137 * On at least some Linux distributions (for example, Red Hat 5.2),
138 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
139 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
140 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
141 * the PACKET_xxx stuff.
143 * So we check whether PACKET_HOST is defined, and assume that we have
144 * PF_PACKET sockets only if it is defined.
146 # ifdef PACKET_HOST
147 # define HAVE_PF_PACKET_SOCKETS
148 # endif /* PACKET_HOST */
149 #endif /* PF_PACKET */
151 #ifdef SO_ATTACH_FILTER
152 #include <linux/types.h>
153 #include <linux/filter.h>
154 #endif
156 #ifndef __GLIBC__
157 typedef int socklen_t;
158 #endif
160 #ifndef MSG_TRUNC
162 * This is being compiled on a system that lacks MSG_TRUNC; define it
163 * with the value it has in the 2.2 and later kernels, so that, on
164 * those kernels, when we pass it in the flags argument to "recvfrom()"
165 * we're passing the right value and thus get the MSG_TRUNC behavior
166 * we want. (We don't get that behavior on 2.0[.x] kernels, because
167 * they didn't support MSG_TRUNC.)
169 #define MSG_TRUNC 0x20
170 #endif
172 #ifndef SOL_PACKET
174 * This is being compiled on a system that lacks SOL_PACKET; define it
175 * with the value it has in the 2.2 and later kernels, so that we can
176 * set promiscuous mode in the good modern way rather than the old
177 * 2.0-kernel crappy way.
179 #define SOL_PACKET 263
180 #endif
182 #define MAX_LINKHEADER_SIZE 256
185 * When capturing on all interfaces we use this as the buffer size.
186 * Should be bigger then all MTUs that occur in real life.
187 * 64kB should be enough for now.
189 #define BIGGER_THAN_ALL_MTUS (64*1024)
192 * Prototypes for internal functions
194 static void map_arphrd_to_dlt(pcap_t *, int, int);
195 static int live_open_old(pcap_t *, const char *, int, int, char *);
196 static int live_open_new(pcap_t *, const char *, int, int, char *);
197 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
198 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
199 static int pcap_inject_linux(pcap_t *, const void *, size_t);
200 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
201 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
202 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
203 static void pcap_close_linux(pcap_t *);
206 * Wrap some ioctl calls
208 #ifdef HAVE_PF_PACKET_SOCKETS
209 static int iface_get_id(int fd, const char *device, char *ebuf);
210 #endif
211 static int iface_get_mtu(int fd, const char *device, char *ebuf);
212 static int iface_get_arptype(int fd, const char *device, char *ebuf);
213 #ifdef HAVE_PF_PACKET_SOCKETS
214 static int iface_bind(int fd, int ifindex, char *ebuf);
215 #endif
216 static int iface_bind_old(int fd, const char *device, char *ebuf);
218 #ifdef SO_ATTACH_FILTER
219 static int fix_program(pcap_t *handle, struct sock_fprog *fcode);
220 static int fix_offset(struct bpf_insn *p);
221 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
222 static int reset_kernel_filter(pcap_t *handle);
224 static struct sock_filter total_insn
225 = BPF_STMT(BPF_RET | BPF_K, 0);
226 static struct sock_fprog total_fcode
227 = { 1, &total_insn };
228 #endif
231 * Get a handle for a live capture from the given device. You can
232 * pass NULL as device to get all packages (without link level
233 * information of course). If you pass 1 as promisc the interface
234 * will be set to promiscous mode (XXX: I think this usage should
235 * be deprecated and functions be added to select that later allow
236 * modification of that values -- Torsten).
238 * See also pcap(3).
240 pcap_t *
241 pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
242 char *ebuf)
244 pcap_t *handle;
245 int mtu;
246 int err;
247 int live_open_ok = 0;
248 struct utsname utsname;
250 #ifdef HAVE_REMOTE
252 Retrofit; we have to make older applications compatible with the remote capture
253 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
254 Obviously, we cannot exploit all the new features; for instance, we cannot
255 send authentication, we cannot use a UDP data connection, and so on.
258 char host[PCAP_BUF_SIZE + 1];
259 char port[PCAP_BUF_SIZE + 1];
260 char name[PCAP_BUF_SIZE + 1];
261 int srctype;
263 if (pcap_parsesrcstr(device, &srctype, host, port, name, ebuf) )
264 return NULL;
266 if (srctype == PCAP_SRC_IFREMOTE)
268 handle= pcap_opensource_remote(device, NULL, ebuf);
270 if (handle == NULL)
271 return NULL;
273 handle->snapshot= snaplen;
274 handle->md.timeout= to_ms;
275 handle->rmt_flags= (promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0;
277 return handle;
279 #endif /* HAVE_REMOTE */
281 #ifdef HAVE_DAG_API
282 if (strstr(device, "dag")) {
283 return dag_open_live(device, snaplen, promisc, to_ms, ebuf);
285 #endif /* HAVE_DAG_API */
287 #ifdef HAVE_SEPTEL_API
288 if (strstr(device, "septel")) {
289 return septel_open_live(device, snaplen, promisc, to_ms, ebuf);
291 #endif /* HAVE_SEPTEL_API */
293 /* Allocate a handle for this session. */
295 handle = malloc(sizeof(*handle));
296 if (handle == NULL) {
297 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
298 pcap_strerror(errno));
299 return NULL;
302 /* Initialize some components of the pcap structure. */
304 memset(handle, 0, sizeof(*handle));
305 handle->snapshot = snaplen;
306 handle->md.timeout = to_ms;
309 * NULL and "any" are special devices which give us the hint to
310 * monitor all devices.
312 if (!device || strcmp(device, "any") == 0) {
313 device = NULL;
314 handle->md.device = strdup("any");
315 if (promisc) {
316 promisc = 0;
317 /* Just a warning. */
318 snprintf(ebuf, PCAP_ERRBUF_SIZE,
319 "Promiscuous mode not supported on the \"any\" device");
322 } else
323 handle->md.device = strdup(device);
325 if (handle->md.device == NULL) {
326 snprintf(ebuf, PCAP_ERRBUF_SIZE, "strdup: %s",
327 pcap_strerror(errno) );
328 free(handle);
329 return NULL;
333 * Current Linux kernels use the protocol family PF_PACKET to
334 * allow direct access to all packets on the network while
335 * older kernels had a special socket type SOCK_PACKET to
336 * implement this feature.
337 * While this old implementation is kind of obsolete we need
338 * to be compatible with older kernels for a while so we are
339 * trying both methods with the newer method preferred.
342 if ((err = live_open_new(handle, device, promisc, to_ms, ebuf)) == 1)
343 live_open_ok = 1;
344 else if (err == 0) {
345 /* Non-fatal error; try old way */
346 if (live_open_old(handle, device, promisc, to_ms, ebuf))
347 live_open_ok = 1;
349 if (!live_open_ok) {
351 * Both methods to open the packet socket failed. Tidy
352 * up and report our failure (ebuf is expected to be
353 * set by the functions above).
356 if (handle->md.device != NULL)
357 free(handle->md.device);
358 free(handle);
359 return NULL;
363 * Compute the buffer size.
365 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
366 * and might require special handling - check.
368 if (handle->md.sock_packet && (uname(&utsname) < 0 ||
369 strncmp(utsname.release, "2.0", 3) == 0)) {
371 * We're using a SOCK_PACKET structure, and either
372 * we couldn't find out what kernel release this is,
373 * or it's a 2.0[.x] kernel.
375 * In the 2.0[.x] kernel, a "recvfrom()" on
376 * a SOCK_PACKET socket, with MSG_TRUNC set, will
377 * return the number of bytes read, so if we pass
378 * a length based on the snapshot length, it'll
379 * return the number of bytes from the packet
380 * copied to userland, not the actual length
381 * of the packet.
383 * This means that, for example, the IP dissector
384 * in tcpdump will get handed a packet length less
385 * than the length in the IP header, and will
386 * complain about "truncated-ip".
388 * So we don't bother trying to copy from the
389 * kernel only the bytes in which we're interested,
390 * but instead copy them all, just as the older
391 * versions of libpcap for Linux did.
393 * The buffer therefore needs to be big enough to
394 * hold the largest packet we can get from this
395 * device. Unfortunately, we can't get the MRU
396 * of the network; we can only get the MTU. The
397 * MTU may be too small, in which case a packet larger
398 * than the buffer size will be truncated *and* we
399 * won't get the actual packet size.
401 * However, if the snapshot length is larger than
402 * the buffer size based on the MTU, we use the
403 * snapshot length as the buffer size, instead;
404 * this means that with a sufficiently large snapshot
405 * length we won't artificially truncate packets
406 * to the MTU-based size.
408 * This mess just one of many problems with packet
409 * capture on 2.0[.x] kernels; you really want a
410 * 2.2[.x] or later kernel if you want packet capture
411 * to work well.
413 mtu = iface_get_mtu(handle->fd, device, ebuf);
414 if (mtu == -1) {
415 pcap_close_linux(handle);
416 free(handle);
417 return NULL;
419 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
420 if (handle->bufsize < handle->snapshot)
421 handle->bufsize = handle->snapshot;
422 } else {
424 * This is a 2.2[.x] or later kernel (we know that
425 * either because we're not using a SOCK_PACKET
426 * socket - PF_PACKET is supported only in 2.2
427 * and later kernels - or because we checked the
428 * kernel version).
430 * We can safely pass "recvfrom()" a byte count
431 * based on the snapshot length.
433 * If we're in cooked mode, make the snapshot length
434 * large enough to hold a "cooked mode" header plus
435 * 1 byte of packet data (so we don't pass a byte
436 * count of 0 to "recvfrom()").
438 if (handle->md.cooked) {
439 if (handle->snapshot < SLL_HDR_LEN + 1)
440 handle->snapshot = SLL_HDR_LEN + 1;
442 handle->bufsize = handle->snapshot;
445 /* Allocate the buffer */
447 handle->buffer = malloc(handle->bufsize + handle->offset);
448 if (!handle->buffer) {
449 snprintf(ebuf, PCAP_ERRBUF_SIZE,
450 "malloc: %s", pcap_strerror(errno));
451 pcap_close_linux(handle);
452 free(handle);
453 return NULL;
457 * "handle->fd" is a socket, so "select()" and "poll()"
458 * should work on it.
460 handle->selectable_fd = handle->fd;
462 handle->read_op = pcap_read_linux;
463 handle->inject_op = pcap_inject_linux;
464 handle->setfilter_op = pcap_setfilter_linux;
465 handle->setdirection_op = pcap_setdirection_linux;
466 handle->set_datalink_op = NULL; /* can't change data link type */
467 handle->getnonblock_op = pcap_getnonblock_fd;
468 handle->setnonblock_op = pcap_setnonblock_fd;
469 handle->stats_op = pcap_stats_linux;
470 handle->close_op = pcap_close_linux;
472 return handle;
476 * Read at most max_packets from the capture stream and call the callback
477 * for each of them. Returns the number of packets handled or -1 if an
478 * error occured.
480 static int
481 pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
484 * Currently, on Linux only one packet is delivered per read,
485 * so we don't loop.
487 return pcap_read_packet(handle, callback, user);
491 * Read a packet from the socket calling the handler provided by
492 * the user. Returns the number of packets received or -1 if an
493 * error occured.
495 static int
496 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
498 u_char *bp;
499 int offset;
500 #ifdef HAVE_PF_PACKET_SOCKETS
501 struct sockaddr_ll from;
502 struct sll_header *hdrp;
503 #else
504 struct sockaddr from;
505 #endif
506 socklen_t fromlen;
507 int packet_len, caplen;
508 struct pcap_pkthdr pcap_header;
510 #ifdef HAVE_PF_PACKET_SOCKETS
512 * If this is a cooked device, leave extra room for a
513 * fake packet header.
515 if (handle->md.cooked)
516 offset = SLL_HDR_LEN;
517 else
518 offset = 0;
519 #else
521 * This system doesn't have PF_PACKET sockets, so it doesn't
522 * support cooked devices.
524 offset = 0;
525 #endif
527 /* Receive a single packet from the kernel */
529 bp = handle->buffer + handle->offset;
530 do {
532 * Has "pcap_breakloop()" been called?
534 if (handle->break_loop) {
536 * Yes - clear the flag that indicates that it
537 * has, and return -2 as an indication that we
538 * were told to break out of the loop.
540 handle->break_loop = 0;
541 return -2;
543 fromlen = sizeof(from);
544 packet_len = recvfrom(
545 handle->fd, bp + offset,
546 handle->bufsize - offset, MSG_TRUNC,
547 (struct sockaddr *) &from, &fromlen);
548 } while (packet_len == -1 && errno == EINTR);
550 /* Check if an error occured */
552 if (packet_len == -1) {
553 if (errno == EAGAIN)
554 return 0; /* no packet there */
555 else {
556 snprintf(handle->errbuf, sizeof(handle->errbuf),
557 "recvfrom: %s", pcap_strerror(errno));
558 return -1;
562 #ifdef HAVE_PF_PACKET_SOCKETS
563 if (!handle->md.sock_packet) {
565 * Unfortunately, there is a window between socket() and
566 * bind() where the kernel may queue packets from any
567 * interface. If we're bound to a particular interface,
568 * discard packets not from that interface.
570 * (If socket filters are supported, we could do the
571 * same thing we do when changing the filter; however,
572 * that won't handle packet sockets without socket
573 * filter support, and it's a bit more complicated.
574 * It would save some instructions per packet, however.)
576 if (handle->md.ifindex != -1 &&
577 from.sll_ifindex != handle->md.ifindex)
578 return 0;
581 * Do checks based on packet direction.
582 * We can only do this if we're using PF_PACKET; the
583 * address returned for SOCK_PACKET is a "sockaddr_pkt"
584 * which lacks the relevant packet type information.
586 if (from.sll_pkttype == PACKET_OUTGOING) {
588 * Outgoing packet.
589 * If this is from the loopback device, reject it;
590 * we'll see the packet as an incoming packet as well,
591 * and we don't want to see it twice.
593 if (from.sll_ifindex == handle->md.lo_ifindex)
594 return 0;
597 * If the user only wants incoming packets, reject it.
599 if (handle->direction == PCAP_D_IN)
600 return 0;
601 } else {
603 * Incoming packet.
604 * If the user only wants outgoing packets, reject it.
606 if (handle->direction == PCAP_D_OUT)
607 return 0;
610 #endif
612 #ifdef HAVE_PF_PACKET_SOCKETS
614 * If this is a cooked device, fill in the fake packet header.
616 if (handle->md.cooked) {
618 * Add the length of the fake header to the length
619 * of packet data we read.
621 packet_len += SLL_HDR_LEN;
623 hdrp = (struct sll_header *)bp;
626 * Map the PACKET_ value to a LINUX_SLL_ value; we
627 * want the same numerical value to be used in
628 * the link-layer header even if the numerical values
629 * for the PACKET_ #defines change, so that programs
630 * that look at the packet type field will always be
631 * able to handle DLT_LINUX_SLL captures.
633 switch (from.sll_pkttype) {
635 case PACKET_HOST:
636 hdrp->sll_pkttype = htons(LINUX_SLL_HOST);
637 break;
639 case PACKET_BROADCAST:
640 hdrp->sll_pkttype = htons(LINUX_SLL_BROADCAST);
641 break;
643 case PACKET_MULTICAST:
644 hdrp->sll_pkttype = htons(LINUX_SLL_MULTICAST);
645 break;
647 case PACKET_OTHERHOST:
648 hdrp->sll_pkttype = htons(LINUX_SLL_OTHERHOST);
649 break;
651 case PACKET_OUTGOING:
652 hdrp->sll_pkttype = htons(LINUX_SLL_OUTGOING);
653 break;
655 default:
656 hdrp->sll_pkttype = -1;
657 break;
660 hdrp->sll_hatype = htons(from.sll_hatype);
661 hdrp->sll_halen = htons(from.sll_halen);
662 memcpy(hdrp->sll_addr, from.sll_addr,
663 (from.sll_halen > SLL_ADDRLEN) ?
664 SLL_ADDRLEN :
665 from.sll_halen);
666 hdrp->sll_protocol = from.sll_protocol;
668 #endif
671 * XXX: According to the kernel source we should get the real
672 * packet len if calling recvfrom with MSG_TRUNC set. It does
673 * not seem to work here :(, but it is supported by this code
674 * anyway.
675 * To be honest the code RELIES on that feature so this is really
676 * broken with 2.2.x kernels.
677 * I spend a day to figure out what's going on and I found out
678 * that the following is happening:
680 * The packet comes from a random interface and the packet_rcv
681 * hook is called with a clone of the packet. That code inserts
682 * the packet into the receive queue of the packet socket.
683 * If a filter is attached to that socket that filter is run
684 * first - and there lies the problem. The default filter always
685 * cuts the packet at the snaplen:
687 * # tcpdump -d
688 * (000) ret #68
690 * So the packet filter cuts down the packet. The recvfrom call
691 * says "hey, it's only 68 bytes, it fits into the buffer" with
692 * the result that we don't get the real packet length. This
693 * is valid at least until kernel 2.2.17pre6.
695 * We currently handle this by making a copy of the filter
696 * program, fixing all "ret" instructions with non-zero
697 * operands to have an operand of 65535 so that the filter
698 * doesn't truncate the packet, and supplying that modified
699 * filter to the kernel.
702 caplen = packet_len;
703 if (caplen > handle->snapshot)
704 caplen = handle->snapshot;
706 /* Run the packet filter if not using kernel filter */
707 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
708 if (bpf_filter(handle->fcode.bf_insns, bp,
709 packet_len, caplen) == 0)
711 /* rejected by filter */
712 return 0;
716 /* Fill in our own header data */
718 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
719 snprintf(handle->errbuf, sizeof(handle->errbuf),
720 "SIOCGSTAMP: %s", pcap_strerror(errno));
721 return -1;
723 pcap_header.caplen = caplen;
724 pcap_header.len = packet_len;
727 * Count the packet.
729 * Arguably, we should count them before we check the filter,
730 * as on many other platforms "ps_recv" counts packets
731 * handed to the filter rather than packets that passed
732 * the filter, but if filtering is done in the kernel, we
733 * can't get a count of packets that passed the filter,
734 * and that would mean the meaning of "ps_recv" wouldn't
735 * be the same on all Linux systems.
737 * XXX - it's not the same on all systems in any case;
738 * ideally, we should have a "get the statistics" call
739 * that supplies more counts and indicates which of them
740 * it supplies, so that we supply a count of packets
741 * handed to the filter only on platforms where that
742 * information is available.
744 * We count them here even if we can get the packet count
745 * from the kernel, as we can only determine at run time
746 * whether we'll be able to get it from the kernel (if
747 * HAVE_TPACKET_STATS isn't defined, we can't get it from
748 * the kernel, but if it is defined, the library might
749 * have been built with a 2.4 or later kernel, but we
750 * might be running on a 2.2[.x] kernel without Alexey
751 * Kuznetzov's turbopacket patches, and thus the kernel
752 * might not be able to supply those statistics). We
753 * could, I guess, try, when opening the socket, to get
754 * the statistics, and if we can not increment the count
755 * here, but it's not clear that always incrementing
756 * the count is more expensive than always testing a flag
757 * in memory.
759 * We keep the count in "md.packets_read", and use that for
760 * "ps_recv" if we can't get the statistics from the kernel.
761 * We do that because, if we *can* get the statistics from
762 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
763 * as running counts, as reading the statistics from the
764 * kernel resets the kernel statistics, and if we directly
765 * increment "md.stat.ps_recv" here, that means it will
766 * count packets *twice* on systems where we can get kernel
767 * statistics - once here, and once in pcap_stats_linux().
769 handle->md.packets_read++;
771 /* Call the user supplied callback function */
772 callback(userdata, &pcap_header, bp);
774 return 1;
777 static int
778 pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
780 int ret;
782 #ifdef HAVE_PF_PACKET_SOCKETS
783 if (!handle->md.sock_packet) {
784 /* PF_PACKET socket */
785 if (handle->md.ifindex == -1) {
787 * We don't support sending on the "any" device.
789 strlcpy(handle->errbuf,
790 "Sending packets isn't supported on the \"any\" device",
791 PCAP_ERRBUF_SIZE);
792 return (-1);
795 if (handle->md.cooked) {
797 * We don't support sending on the "any" device.
799 * XXX - how do you send on a bound cooked-mode
800 * socket?
801 * Is a "sendto()" required there?
803 strlcpy(handle->errbuf,
804 "Sending packets isn't supported in cooked mode",
805 PCAP_ERRBUF_SIZE);
806 return (-1);
809 #endif
811 ret = send(handle->fd, buf, size, 0);
812 if (ret == -1) {
813 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
814 pcap_strerror(errno));
815 return (-1);
817 return (ret);
821 * Get the statistics for the given packet capture handle.
822 * Reports the number of dropped packets iff the kernel supports
823 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
824 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
825 * patches); otherwise, that information isn't available, and we lie
826 * and report 0 as the count of dropped packets.
828 static int
829 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
831 #ifdef HAVE_TPACKET_STATS
832 struct tpacket_stats kstats;
833 socklen_t len = sizeof (struct tpacket_stats);
834 #endif
836 #ifdef HAVE_TPACKET_STATS
838 * Try to get the packet counts from the kernel.
840 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
841 &kstats, &len) > -1) {
843 * On systems where the PACKET_STATISTICS "getsockopt()"
844 * argument is supported on PF_PACKET sockets:
846 * "ps_recv" counts only packets that *passed* the
847 * filter, not packets that didn't pass the filter.
848 * This includes packets later dropped because we
849 * ran out of buffer space.
851 * "ps_drop" counts packets dropped because we ran
852 * out of buffer space. It doesn't count packets
853 * dropped by the interface driver. It counts only
854 * packets that passed the filter.
856 * Both statistics include packets not yet read from
857 * the kernel by libpcap, and thus not yet seen by
858 * the application.
860 * In "linux/net/packet/af_packet.c", at least in the
861 * 2.4.9 kernel, "tp_packets" is incremented for every
862 * packet that passes the packet filter *and* is
863 * successfully queued on the socket; "tp_drops" is
864 * incremented for every packet dropped because there's
865 * not enough free space in the socket buffer.
867 * When the statistics are returned for a PACKET_STATISTICS
868 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
869 * so that "tp_packets" counts all packets handed to
870 * the PF_PACKET socket, including packets dropped because
871 * there wasn't room on the socket buffer - but not
872 * including packets that didn't pass the filter.
874 * In the BSD BPF, the count of received packets is
875 * incremented for every packet handed to BPF, regardless
876 * of whether it passed the filter.
878 * We can't make "pcap_stats()" work the same on both
879 * platforms, but the best approximation is to return
880 * "tp_packets" as the count of packets and "tp_drops"
881 * as the count of drops.
883 * Keep a running total because each call to
884 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
885 * resets the counters to zero.
887 handle->md.stat.ps_recv += kstats.tp_packets;
888 handle->md.stat.ps_drop += kstats.tp_drops;
889 *stats = handle->md.stat;
890 return 0;
892 else
895 * If the error was EOPNOTSUPP, fall through, so that
896 * if you build the library on a system with
897 * "struct tpacket_stats" and run it on a system
898 * that doesn't, it works as it does if the library
899 * is built on a system without "struct tpacket_stats".
901 if (errno != EOPNOTSUPP) {
902 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
903 "pcap_stats: %s", pcap_strerror(errno));
904 return -1;
907 #endif
909 * On systems where the PACKET_STATISTICS "getsockopt()" argument
910 * is not supported on PF_PACKET sockets:
912 * "ps_recv" counts only packets that *passed* the filter,
913 * not packets that didn't pass the filter. It does not
914 * count packets dropped because we ran out of buffer
915 * space.
917 * "ps_drop" is not supported.
919 * "ps_recv" doesn't include packets not yet read from
920 * the kernel by libpcap.
922 * We maintain the count of packets processed by libpcap in
923 * "md.packets_read", for reasons described in the comment
924 * at the end of pcap_read_packet(). We have no idea how many
925 * packets were dropped.
927 stats->ps_recv = handle->md.packets_read;
928 stats->ps_drop = 0;
929 return 0;
933 * Description string for the "any" device.
935 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
938 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
940 if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
941 return (-1);
943 #ifdef HAVE_DAG_API
944 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
945 return (-1);
946 #endif /* HAVE_DAG_API */
948 #ifdef HAVE_SEPTEL_API
949 if (septel_platform_finddevs(alldevsp, errbuf) < 0)
950 return (-1);
951 #endif /* HAVE_SEPTEL_API */
953 return (0);
957 * Attach the given BPF code to the packet capture device.
959 static int
960 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
962 #ifdef SO_ATTACH_FILTER
963 struct sock_fprog fcode;
964 int can_filter_in_kernel;
965 int err = 0;
966 #endif
968 if (!handle)
969 return -1;
970 if (!filter) {
971 strncpy(handle->errbuf, "setfilter: No filter specified",
972 sizeof(handle->errbuf));
973 return -1;
976 /* Make our private copy of the filter */
978 if (install_bpf_program(handle, filter) < 0)
979 /* install_bpf_program() filled in errbuf */
980 return -1;
983 * Run user level packet filter by default. Will be overriden if
984 * installing a kernel filter succeeds.
986 handle->md.use_bpf = 0;
988 /* Install kernel level filter if possible */
990 #ifdef SO_ATTACH_FILTER
991 #ifdef USHRT_MAX
992 if (handle->fcode.bf_len > USHRT_MAX) {
994 * fcode.len is an unsigned short for current kernel.
995 * I have yet to see BPF-Code with that much
996 * instructions but still it is possible. So for the
997 * sake of correctness I added this check.
999 fprintf(stderr, "Warning: Filter too complex for kernel\n");
1000 fcode.filter = NULL;
1001 can_filter_in_kernel = 0;
1002 } else
1003 #endif /* USHRT_MAX */
1006 * Oh joy, the Linux kernel uses struct sock_fprog instead
1007 * of struct bpf_program and of course the length field is
1008 * of different size. Pointed out by Sebastian
1010 * Oh, and we also need to fix it up so that all "ret"
1011 * instructions with non-zero operands have 65535 as the
1012 * operand, and so that, if we're in cooked mode, all
1013 * memory-reference instructions use special magic offsets
1014 * in references to the link-layer header and assume that
1015 * the link-layer payload begins at 0; "fix_program()"
1016 * will do that.
1018 switch (fix_program(handle, &fcode)) {
1020 case -1:
1021 default:
1023 * Fatal error; just quit.
1024 * (The "default" case shouldn't happen; we
1025 * return -1 for that reason.)
1027 return -1;
1029 case 0:
1031 * The program performed checks that we can't make
1032 * work in the kernel.
1034 can_filter_in_kernel = 0;
1035 break;
1037 case 1:
1039 * We have a filter that'll work in the kernel.
1041 can_filter_in_kernel = 1;
1042 break;
1046 if (can_filter_in_kernel) {
1047 if ((err = set_kernel_filter(handle, &fcode)) == 0)
1049 /* Installation succeded - using kernel filter. */
1050 handle->md.use_bpf = 1;
1052 else if (err == -1) /* Non-fatal error */
1055 * Print a warning if we weren't able to install
1056 * the filter for a reason other than "this kernel
1057 * isn't configured to support socket filters.
1059 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
1060 fprintf(stderr,
1061 "Warning: Kernel filter failed: %s\n",
1062 pcap_strerror(errno));
1068 * If we're not using the kernel filter, get rid of any kernel
1069 * filter that might've been there before, e.g. because the
1070 * previous filter could work in the kernel, or because some other
1071 * code attached a filter to the socket by some means other than
1072 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1073 * filter out packets that would pass the new userland filter.
1075 if (!handle->md.use_bpf)
1076 reset_kernel_filter(handle);
1079 * Free up the copy of the filter that was made by "fix_program()".
1081 if (fcode.filter != NULL)
1082 free(fcode.filter);
1084 if (err == -2)
1085 /* Fatal error */
1086 return -1;
1087 #endif /* SO_ATTACH_FILTER */
1089 return 0;
1093 * Set direction flag: Which packets do we accept on a forwarding
1094 * single device? IN, OUT or both?
1096 static int
1097 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
1099 #ifdef HAVE_PF_PACKET_SOCKETS
1100 if (!handle->md.sock_packet) {
1101 handle->direction = d;
1102 return 0;
1104 #endif
1106 * We're not using PF_PACKET sockets, so we can't determine
1107 * the direction of the packet.
1109 snprintf(handle->errbuf, sizeof(handle->errbuf),
1110 "Setting direction is not supported on SOCK_PACKET sockets");
1111 return -1;
1115 * Linux uses the ARP hardware type to identify the type of an
1116 * interface. pcap uses the DLT_xxx constants for this. This
1117 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1118 * constant, as arguments, and sets "handle->linktype" to the
1119 * appropriate DLT_XXX constant and sets "handle->offset" to
1120 * the appropriate value (to make "handle->offset" plus link-layer
1121 * header length be a multiple of 4, so that the link-layer payload
1122 * will be aligned on a 4-byte boundary when capturing packets).
1123 * (If the offset isn't set here, it'll be 0; add code as appropriate
1124 * for cases where it shouldn't be 0.)
1126 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1127 * in cooked mode; otherwise, we can't use cooked mode, so we have
1128 * to pick some type that works in raw mode, or fail.
1130 * Sets the link type to -1 if unable to map the type.
1132 static void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
1134 switch (arptype) {
1136 case ARPHRD_ETHER:
1138 * This is (presumably) a real Ethernet capture; give it a
1139 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1140 * that an application can let you choose it, in case you're
1141 * capturing DOCSIS traffic that a Cisco Cable Modem
1142 * Termination System is putting out onto an Ethernet (it
1143 * doesn't put an Ethernet header onto the wire, it puts raw
1144 * DOCSIS frames out on the wire inside the low-level
1145 * Ethernet framing).
1147 * XXX - are there any sorts of "fake Ethernet" that have
1148 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1149 * a Cisco CMTS won't put traffic onto it or get traffic
1150 * bridged onto it? ISDN is handled in "live_open_new()",
1151 * as we fall back on cooked mode there; are there any
1152 * others?
1154 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1156 * If that fails, just leave the list empty.
1158 if (handle->dlt_list != NULL) {
1159 handle->dlt_list[0] = DLT_EN10MB;
1160 handle->dlt_list[1] = DLT_DOCSIS;
1161 handle->dlt_count = 2;
1163 /* FALLTHROUGH */
1165 case ARPHRD_METRICOM:
1166 case ARPHRD_LOOPBACK:
1167 handle->linktype = DLT_EN10MB;
1168 handle->offset = 2;
1169 break;
1171 case ARPHRD_EETHER:
1172 handle->linktype = DLT_EN3MB;
1173 break;
1175 case ARPHRD_AX25:
1176 handle->linktype = DLT_AX25;
1177 break;
1179 case ARPHRD_PRONET:
1180 handle->linktype = DLT_PRONET;
1181 break;
1183 case ARPHRD_CHAOS:
1184 handle->linktype = DLT_CHAOS;
1185 break;
1187 #ifndef ARPHRD_IEEE802_TR
1188 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1189 #endif
1190 case ARPHRD_IEEE802_TR:
1191 case ARPHRD_IEEE802:
1192 handle->linktype = DLT_IEEE802;
1193 handle->offset = 2;
1194 break;
1196 case ARPHRD_ARCNET:
1197 handle->linktype = DLT_ARCNET_LINUX;
1198 break;
1200 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1201 #define ARPHRD_FDDI 774
1202 #endif
1203 case ARPHRD_FDDI:
1204 handle->linktype = DLT_FDDI;
1205 handle->offset = 3;
1206 break;
1208 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1209 #define ARPHRD_ATM 19
1210 #endif
1211 case ARPHRD_ATM:
1213 * The Classical IP implementation in ATM for Linux
1214 * supports both what RFC 1483 calls "LLC Encapsulation",
1215 * in which each packet has an LLC header, possibly
1216 * with a SNAP header as well, prepended to it, and
1217 * what RFC 1483 calls "VC Based Multiplexing", in which
1218 * different virtual circuits carry different network
1219 * layer protocols, and no header is prepended to packets.
1221 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1222 * you can't use the ARPHRD_ type to find out whether
1223 * captured packets will have an LLC header, and,
1224 * while there's a socket ioctl to *set* the encapsulation
1225 * type, there's no ioctl to *get* the encapsulation type.
1227 * This means that
1229 * programs that dissect Linux Classical IP frames
1230 * would have to check for an LLC header and,
1231 * depending on whether they see one or not, dissect
1232 * the frame as LLC-encapsulated or as raw IP (I
1233 * don't know whether there's any traffic other than
1234 * IP that would show up on the socket, or whether
1235 * there's any support for IPv6 in the Linux
1236 * Classical IP code);
1238 * filter expressions would have to compile into
1239 * code that checks for an LLC header and does
1240 * the right thing.
1242 * Both of those are a nuisance - and, at least on systems
1243 * that support PF_PACKET sockets, we don't have to put
1244 * up with those nuisances; instead, we can just capture
1245 * in cooked mode. That's what we'll do, if we can.
1246 * Otherwise, we'll just fail.
1248 if (cooked_ok)
1249 handle->linktype = DLT_LINUX_SLL;
1250 else
1251 handle->linktype = -1;
1252 break;
1254 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1255 #define ARPHRD_IEEE80211 801
1256 #endif
1257 case ARPHRD_IEEE80211:
1258 handle->linktype = DLT_IEEE802_11;
1259 break;
1261 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1262 #define ARPHRD_IEEE80211_PRISM 802
1263 #endif
1264 case ARPHRD_IEEE80211_PRISM:
1265 handle->linktype = DLT_PRISM_HEADER;
1266 break;
1268 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1269 #define ARPHRD_IEEE80211_RADIOTAP 803
1270 #endif
1271 case ARPHRD_IEEE80211_RADIOTAP:
1272 handle->linktype = DLT_IEEE802_11_RADIO;
1273 break;
1275 case ARPHRD_PPP:
1277 * Some PPP code in the kernel supplies no link-layer
1278 * header whatsoever to PF_PACKET sockets; other PPP
1279 * code supplies PPP link-layer headers ("syncppp.c");
1280 * some PPP code might supply random link-layer
1281 * headers (PPP over ISDN - there's code in Ethereal,
1282 * for example, to cope with PPP-over-ISDN captures
1283 * with which the Ethereal developers have had to cope,
1284 * heuristically trying to determine which of the
1285 * oddball link-layer headers particular packets have).
1287 * As such, we just punt, and run all PPP interfaces
1288 * in cooked mode, if we can; otherwise, we just treat
1289 * it as DLT_RAW, for now - if somebody needs to capture,
1290 * on a 2.0[.x] kernel, on PPP devices that supply a
1291 * link-layer header, they'll have to add code here to
1292 * map to the appropriate DLT_ type (possibly adding a
1293 * new DLT_ type, if necessary).
1295 if (cooked_ok)
1296 handle->linktype = DLT_LINUX_SLL;
1297 else {
1299 * XXX - handle ISDN types here? We can't fall
1300 * back on cooked sockets, so we'd have to
1301 * figure out from the device name what type of
1302 * link-layer encapsulation it's using, and map
1303 * that to an appropriate DLT_ value, meaning
1304 * we'd map "isdnN" devices to DLT_RAW (they
1305 * supply raw IP packets with no link-layer
1306 * header) and "isdY" devices to a new DLT_I4L_IP
1307 * type that has only an Ethernet packet type as
1308 * a link-layer header.
1310 * But sometimes we seem to get random crap
1311 * in the link-layer header when capturing on
1312 * ISDN devices....
1314 handle->linktype = DLT_RAW;
1316 break;
1318 #ifndef ARPHRD_CISCO
1319 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1320 #endif
1321 case ARPHRD_CISCO:
1322 handle->linktype = DLT_C_HDLC;
1323 break;
1325 /* Not sure if this is correct for all tunnels, but it
1326 * works for CIPE */
1327 case ARPHRD_TUNNEL:
1328 #ifndef ARPHRD_SIT
1329 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1330 #endif
1331 case ARPHRD_SIT:
1332 case ARPHRD_CSLIP:
1333 case ARPHRD_SLIP6:
1334 case ARPHRD_CSLIP6:
1335 case ARPHRD_ADAPT:
1336 case ARPHRD_SLIP:
1337 #ifndef ARPHRD_RAWHDLC
1338 #define ARPHRD_RAWHDLC 518
1339 #endif
1340 case ARPHRD_RAWHDLC:
1341 #ifndef ARPHRD_DLCI
1342 #define ARPHRD_DLCI 15
1343 #endif
1344 case ARPHRD_DLCI:
1346 * XXX - should some of those be mapped to DLT_LINUX_SLL
1347 * instead? Should we just map all of them to DLT_LINUX_SLL?
1349 handle->linktype = DLT_RAW;
1350 break;
1352 #ifndef ARPHRD_FRAD
1353 #define ARPHRD_FRAD 770
1354 #endif
1355 case ARPHRD_FRAD:
1356 handle->linktype = DLT_FRELAY;
1357 break;
1359 case ARPHRD_LOCALTLK:
1360 handle->linktype = DLT_LTALK;
1361 break;
1363 #ifndef ARPHRD_FCPP
1364 #define ARPHRD_FCPP 784
1365 #endif
1366 case ARPHRD_FCPP:
1367 #ifndef ARPHRD_FCAL
1368 #define ARPHRD_FCAL 785
1369 #endif
1370 case ARPHRD_FCAL:
1371 #ifndef ARPHRD_FCPL
1372 #define ARPHRD_FCPL 786
1373 #endif
1374 case ARPHRD_FCPL:
1375 #ifndef ARPHRD_FCFABRIC
1376 #define ARPHRD_FCFABRIC 787
1377 #endif
1378 case ARPHRD_FCFABRIC:
1380 * We assume that those all mean RFC 2625 IP-over-
1381 * Fibre Channel, with the RFC 2625 header at
1382 * the beginning of the packet.
1384 handle->linktype = DLT_IP_OVER_FC;
1385 break;
1387 #ifndef ARPHRD_IRDA
1388 #define ARPHRD_IRDA 783
1389 #endif
1390 case ARPHRD_IRDA:
1391 /* Don't expect IP packet out of this interfaces... */
1392 handle->linktype = DLT_LINUX_IRDA;
1393 /* We need to save packet direction for IrDA decoding,
1394 * so let's use "Linux-cooked" mode. Jean II */
1395 //handle->md.cooked = 1;
1396 break;
1398 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1399 * is needed, please report it to <daniele@orlandi.com> */
1400 #ifndef ARPHRD_LAPD
1401 #define ARPHRD_LAPD 8445
1402 #endif
1403 case ARPHRD_LAPD:
1404 /* Don't expect IP packet out of this interfaces... */
1405 handle->linktype = DLT_LINUX_LAPD;
1406 break;
1408 default:
1409 handle->linktype = -1;
1410 break;
1414 /* ===== Functions to interface to the newer kernels ================== */
1417 * Try to open a packet socket using the new kernel interface.
1418 * Returns 0 on failure.
1419 * FIXME: 0 uses to mean success (Sebastian)
1421 static int
1422 live_open_new(pcap_t *handle, const char *device, int promisc,
1423 int to_ms, char *ebuf)
1425 #ifdef HAVE_PF_PACKET_SOCKETS
1426 int sock_fd = -1, arptype;
1427 int err;
1428 int fatal_err = 0;
1429 struct packet_mreq mr;
1431 /* One shot loop used for error handling - bail out with break */
1433 do {
1435 * Open a socket with protocol family packet. If a device is
1436 * given we try to open it in raw mode otherwise we use
1437 * the cooked interface.
1439 sock_fd = device ?
1440 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
1441 : socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
1443 if (sock_fd == -1) {
1444 snprintf(ebuf, PCAP_ERRBUF_SIZE, "socket: %s",
1445 pcap_strerror(errno) );
1446 break;
1449 /* It seems the kernel supports the new interface. */
1450 handle->md.sock_packet = 0;
1453 * Get the interface index of the loopback device.
1454 * If the attempt fails, don't fail, just set the
1455 * "md.lo_ifindex" to -1.
1457 * XXX - can there be more than one device that loops
1458 * packets back, i.e. devices other than "lo"? If so,
1459 * we'd need to find them all, and have an array of
1460 * indices for them, and check all of them in
1461 * "pcap_read_packet()".
1463 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", ebuf);
1466 * Default value for offset to align link-layer payload
1467 * on a 4-byte boundary.
1469 handle->offset = 0;
1472 * What kind of frames do we have to deal with? Fall back
1473 * to cooked mode if we have an unknown interface type.
1476 if (device) {
1477 /* Assume for now we don't need cooked mode. */
1478 handle->md.cooked = 0;
1480 arptype = iface_get_arptype(sock_fd, device, ebuf);
1481 if (arptype == -1) {
1482 fatal_err = 1;
1483 break;
1485 map_arphrd_to_dlt(handle, arptype, 1);
1486 if (handle->linktype == -1 ||
1487 handle->linktype == DLT_LINUX_SLL ||
1488 handle->linktype == DLT_LINUX_IRDA ||
1489 handle->linktype == DLT_LINUX_LAPD ||
1490 (handle->linktype == DLT_EN10MB &&
1491 (strncmp("isdn", device, 4) == 0 ||
1492 strncmp("isdY", device, 4) == 0))) {
1494 * Unknown interface type (-1), or a
1495 * device we explicitly chose to run
1496 * in cooked mode (e.g., PPP devices),
1497 * or an ISDN device (whose link-layer
1498 * type we can only determine by using
1499 * APIs that may be different on different
1500 * kernels) - reopen in cooked mode.
1502 if (close(sock_fd) == -1) {
1503 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1504 "close: %s", pcap_strerror(errno));
1505 break;
1507 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
1508 htons(ETH_P_ALL));
1509 if (sock_fd == -1) {
1510 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1511 "socket: %s", pcap_strerror(errno));
1512 break;
1514 handle->md.cooked = 1;
1517 * Get rid of any link-layer type list
1518 * we allocated - this only supports cooked
1519 * capture.
1521 if (handle->dlt_list != NULL) {
1522 free(handle->dlt_list);
1523 handle->dlt_list = NULL;
1524 handle->dlt_count = 0;
1527 if (handle->linktype == -1) {
1529 * Warn that we're falling back on
1530 * cooked mode; we may want to
1531 * update "map_arphrd_to_dlt()"
1532 * to handle the new type.
1534 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1535 "arptype %d not "
1536 "supported by libpcap - "
1537 "falling back to cooked "
1538 "socket",
1539 arptype);
1541 /* IrDA capture is not a real "cooked" capture,
1542 * it's IrLAP frames, not IP packets. */
1543 if (handle->linktype != DLT_LINUX_IRDA &&
1544 handle->linktype != DLT_LINUX_LAPD)
1545 handle->linktype = DLT_LINUX_SLL;
1548 handle->md.ifindex = iface_get_id(sock_fd, device, ebuf);
1549 if (handle->md.ifindex == -1)
1550 break;
1552 if ((err = iface_bind(sock_fd, handle->md.ifindex,
1553 ebuf)) < 0) {
1554 if (err == -2)
1555 fatal_err = 1;
1556 break;
1558 } else {
1560 * This is cooked mode.
1562 handle->md.cooked = 1;
1563 handle->linktype = DLT_LINUX_SLL;
1566 * We're not bound to a device.
1567 * XXX - true? Or true only if we're using
1568 * the "any" device?
1569 * For now, we're using this as an indication
1570 * that we can't transmit; stop doing that only
1571 * if we figure out how to transmit in cooked
1572 * mode.
1574 handle->md.ifindex = -1;
1578 * Select promiscuous mode on if "promisc" is set.
1580 * Do not turn allmulti mode on if we don't select
1581 * promiscuous mode - on some devices (e.g., Orinoco
1582 * wireless interfaces), allmulti mode isn't supported
1583 * and the driver implements it by turning promiscuous
1584 * mode on, and that screws up the operation of the
1585 * card as a normal networking interface, and on no
1586 * other platform I know of does starting a non-
1587 * promiscuous capture affect which multicast packets
1588 * are received by the interface.
1592 * Hmm, how can we set promiscuous mode on all interfaces?
1593 * I am not sure if that is possible at all.
1596 if (device && promisc) {
1597 memset(&mr, 0, sizeof(mr));
1598 mr.mr_ifindex = handle->md.ifindex;
1599 mr.mr_type = PACKET_MR_PROMISC;
1600 if (setsockopt(sock_fd, SOL_PACKET,
1601 PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == -1)
1603 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1604 "setsockopt: %s", pcap_strerror(errno));
1605 break;
1609 /* Save the socket FD in the pcap structure */
1611 handle->fd = sock_fd;
1613 return 1;
1615 } while(0);
1617 if (sock_fd != -1)
1618 close(sock_fd);
1620 if (fatal_err) {
1622 * Get rid of any link-layer type list we allocated.
1624 if (handle->dlt_list != NULL)
1625 free(handle->dlt_list);
1626 return -2;
1627 } else
1628 return 0;
1629 #else
1630 strncpy(ebuf,
1631 "New packet capturing interface not supported by build "
1632 "environment", PCAP_ERRBUF_SIZE);
1633 return 0;
1634 #endif
1637 #ifdef HAVE_PF_PACKET_SOCKETS
1639 * Return the index of the given device name. Fill ebuf and return
1640 * -1 on failure.
1642 static int
1643 iface_get_id(int fd, const char *device, char *ebuf)
1645 struct ifreq ifr;
1647 memset(&ifr, 0, sizeof(ifr));
1648 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1650 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
1651 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1652 "SIOCGIFINDEX: %s", pcap_strerror(errno));
1653 return -1;
1656 return ifr.ifr_ifindex;
1660 * Bind the socket associated with FD to the given device.
1662 static int
1663 iface_bind(int fd, int ifindex, char *ebuf)
1665 struct sockaddr_ll sll;
1666 int err;
1667 socklen_t errlen = sizeof(err);
1669 memset(&sll, 0, sizeof(sll));
1670 sll.sll_family = AF_PACKET;
1671 sll.sll_ifindex = ifindex;
1672 sll.sll_protocol = htons(ETH_P_ALL);
1674 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
1675 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1676 "bind: %s", pcap_strerror(errno));
1677 return -1;
1680 /* Any pending errors, e.g., network is down? */
1682 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
1683 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1684 "getsockopt: %s", pcap_strerror(errno));
1685 return -2;
1688 if (err > 0) {
1689 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1690 "bind: %s", pcap_strerror(err));
1691 return -2;
1694 return 0;
1697 #endif
1700 /* ===== Functions to interface to the older kernels ================== */
1703 * With older kernels promiscuous mode is kind of interesting because we
1704 * have to reset the interface before exiting. The problem can't really
1705 * be solved without some daemon taking care of managing usage counts.
1706 * If we put the interface into promiscuous mode, we set a flag indicating
1707 * that we must take it out of that mode when the interface is closed,
1708 * and, when closing the interface, if that flag is set we take it out
1709 * of promiscuous mode.
1713 * List of pcaps for which we turned promiscuous mode on by hand.
1714 * If there are any such pcaps, we arrange to call "pcap_close_all()"
1715 * when we exit, and have it close all of them to turn promiscuous mode
1716 * off.
1718 static struct pcap *pcaps_to_close;
1721 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1722 * be called on exit.
1724 static int did_atexit;
1726 static void pcap_close_all(void)
1728 struct pcap *handle;
1730 while ((handle = pcaps_to_close) != NULL)
1731 pcap_close(handle);
1734 static void pcap_close_linux( pcap_t *handle )
1736 struct pcap *p, *prevp;
1737 struct ifreq ifr;
1739 if (handle->md.clear_promisc) {
1741 * We put the interface into promiscuous mode; take
1742 * it out of promiscuous mode.
1744 * XXX - if somebody else wants it in promiscuous mode,
1745 * this code cannot know that, so it'll take it out
1746 * of promiscuous mode. That's not fixable in 2.0[.x]
1747 * kernels.
1749 memset(&ifr, 0, sizeof(ifr));
1750 strncpy(ifr.ifr_name, handle->md.device, sizeof(ifr.ifr_name));
1751 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1752 fprintf(stderr,
1753 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1754 "Please adjust manually.\n"
1755 "Hint: This can't happen with Linux >= 2.2.0.\n",
1756 strerror(errno));
1757 } else {
1758 if (ifr.ifr_flags & IFF_PROMISC) {
1760 * Promiscuous mode is currently on; turn it
1761 * off.
1763 ifr.ifr_flags &= ~IFF_PROMISC;
1764 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1765 fprintf(stderr,
1766 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1767 "Please adjust manually.\n"
1768 "Hint: This can't happen with Linux >= 2.2.0.\n",
1769 strerror(errno));
1775 * Take this pcap out of the list of pcaps for which we
1776 * have to take the interface out of promiscuous mode.
1778 for (p = pcaps_to_close, prevp = NULL; p != NULL;
1779 prevp = p, p = p->md.next) {
1780 if (p == handle) {
1782 * Found it. Remove it from the list.
1784 if (prevp == NULL) {
1786 * It was at the head of the list.
1788 pcaps_to_close = p->md.next;
1789 } else {
1791 * It was in the middle of the list.
1793 prevp->md.next = p->md.next;
1795 break;
1800 if (handle->md.device != NULL)
1801 free(handle->md.device);
1802 handle->md.device = NULL;
1803 pcap_close_common(handle);
1807 * Try to open a packet socket using the old kernel interface.
1808 * Returns 0 on failure.
1809 * FIXME: 0 uses to mean success (Sebastian)
1811 static int
1812 live_open_old(pcap_t *handle, const char *device, int promisc,
1813 int to_ms, char *ebuf)
1815 int arptype;
1816 struct ifreq ifr;
1818 do {
1819 /* Open the socket */
1821 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
1822 if (handle->fd == -1) {
1823 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1824 "socket: %s", pcap_strerror(errno));
1825 break;
1828 /* It worked - we are using the old interface */
1829 handle->md.sock_packet = 1;
1831 /* ...which means we get the link-layer header. */
1832 handle->md.cooked = 0;
1834 /* Bind to the given device */
1836 if (!device) {
1837 strncpy(ebuf, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
1838 PCAP_ERRBUF_SIZE);
1839 break;
1841 if (iface_bind_old(handle->fd, device, ebuf) == -1)
1842 break;
1845 * Try to get the link-layer type.
1847 arptype = iface_get_arptype(handle->fd, device, ebuf);
1848 if (arptype == -1)
1849 break;
1852 * Try to find the DLT_ type corresponding to that
1853 * link-layer type.
1855 map_arphrd_to_dlt(handle, arptype, 0);
1856 if (handle->linktype == -1) {
1857 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1858 "unknown arptype %d", arptype);
1859 break;
1862 /* Go to promisc mode if requested */
1864 if (promisc) {
1865 memset(&ifr, 0, sizeof(ifr));
1866 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1867 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1868 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1869 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
1870 break;
1872 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
1874 * Promiscuous mode isn't currently on,
1875 * so turn it on, and remember that
1876 * we should turn it off when the
1877 * pcap_t is closed.
1881 * If we haven't already done so, arrange
1882 * to have "pcap_close_all()" called when
1883 * we exit.
1885 if (!did_atexit) {
1886 if (atexit(pcap_close_all) == -1) {
1888 * "atexit()" failed; don't
1889 * put the interface in
1890 * promiscuous mode, just
1891 * give up.
1893 strncpy(ebuf, "atexit failed",
1894 PCAP_ERRBUF_SIZE);
1895 break;
1897 did_atexit = 1;
1900 ifr.ifr_flags |= IFF_PROMISC;
1901 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1902 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1903 "SIOCSIFFLAGS: %s",
1904 pcap_strerror(errno));
1905 break;
1907 handle->md.clear_promisc = 1;
1910 * Add this to the list of pcaps
1911 * to close when we exit.
1913 handle->md.next = pcaps_to_close;
1914 pcaps_to_close = handle;
1919 * Default value for offset to align link-layer payload
1920 * on a 4-byte boundary.
1922 handle->offset = 0;
1924 return 1;
1926 } while (0);
1928 pcap_close_linux(handle);
1929 return 0;
1933 * Bind the socket associated with FD to the given device using the
1934 * interface of the old kernels.
1936 static int
1937 iface_bind_old(int fd, const char *device, char *ebuf)
1939 struct sockaddr saddr;
1940 int err;
1941 socklen_t errlen = sizeof(err);
1943 memset(&saddr, 0, sizeof(saddr));
1944 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
1945 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
1946 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1947 "bind: %s", pcap_strerror(errno));
1948 return -1;
1951 /* Any pending errors, e.g., network is down? */
1953 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
1954 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1955 "getsockopt: %s", pcap_strerror(errno));
1956 return -1;
1959 if (err > 0) {
1960 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1961 "bind: %s", pcap_strerror(err));
1962 return -1;
1965 return 0;
1969 /* ===== System calls available on all supported kernels ============== */
1972 * Query the kernel for the MTU of the given interface.
1974 static int
1975 iface_get_mtu(int fd, const char *device, char *ebuf)
1977 struct ifreq ifr;
1979 if (!device)
1980 return BIGGER_THAN_ALL_MTUS;
1982 memset(&ifr, 0, sizeof(ifr));
1983 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1985 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
1986 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1987 "SIOCGIFMTU: %s", pcap_strerror(errno));
1988 return -1;
1991 return ifr.ifr_mtu;
1995 * Get the hardware type of the given interface as ARPHRD_xxx constant.
1997 static int
1998 iface_get_arptype(int fd, const char *device, char *ebuf)
2000 struct ifreq ifr;
2002 memset(&ifr, 0, sizeof(ifr));
2003 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
2005 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
2006 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2007 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
2008 return -1;
2011 return ifr.ifr_hwaddr.sa_family;
2014 #ifdef SO_ATTACH_FILTER
2015 static int
2016 fix_program(pcap_t *handle, struct sock_fprog *fcode)
2018 size_t prog_size;
2019 register int i;
2020 register struct bpf_insn *p;
2021 struct bpf_insn *f;
2022 int len;
2025 * Make a copy of the filter, and modify that copy if
2026 * necessary.
2028 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
2029 len = handle->fcode.bf_len;
2030 f = (struct bpf_insn *)malloc(prog_size);
2031 if (f == NULL) {
2032 snprintf(handle->errbuf, sizeof(handle->errbuf),
2033 "malloc: %s", pcap_strerror(errno));
2034 return -1;
2036 memcpy(f, handle->fcode.bf_insns, prog_size);
2037 fcode->len = len;
2038 fcode->filter = (struct sock_filter *) f;
2040 for (i = 0; i < len; ++i) {
2041 p = &f[i];
2043 * What type of instruction is this?
2045 switch (BPF_CLASS(p->code)) {
2047 case BPF_RET:
2049 * It's a return instruction; is the snapshot
2050 * length a constant, rather than the contents
2051 * of the accumulator?
2053 if (BPF_MODE(p->code) == BPF_K) {
2055 * Yes - if the value to be returned,
2056 * i.e. the snapshot length, is anything
2057 * other than 0, make it 65535, so that
2058 * the packet is truncated by "recvfrom()",
2059 * not by the filter.
2061 * XXX - there's nothing we can easily do
2062 * if it's getting the value from the
2063 * accumulator; we'd have to insert
2064 * code to force non-zero values to be
2065 * 65535.
2067 if (p->k != 0)
2068 p->k = 65535;
2070 break;
2072 case BPF_LD:
2073 case BPF_LDX:
2075 * It's a load instruction; is it loading
2076 * from the packet?
2078 switch (BPF_MODE(p->code)) {
2080 case BPF_ABS:
2081 case BPF_IND:
2082 case BPF_MSH:
2084 * Yes; are we in cooked mode?
2086 if (handle->md.cooked) {
2088 * Yes, so we need to fix this
2089 * instruction.
2091 if (fix_offset(p) < 0) {
2093 * We failed to do so.
2094 * Return 0, so our caller
2095 * knows to punt to userland.
2097 return 0;
2100 break;
2102 break;
2105 return 1; /* we succeeded */
2108 static int
2109 fix_offset(struct bpf_insn *p)
2112 * What's the offset?
2114 if (p->k >= SLL_HDR_LEN) {
2116 * It's within the link-layer payload; that starts at an
2117 * offset of 0, as far as the kernel packet filter is
2118 * concerned, so subtract the length of the link-layer
2119 * header.
2121 p->k -= SLL_HDR_LEN;
2122 } else if (p->k == 14) {
2124 * It's the protocol field; map it to the special magic
2125 * kernel offset for that field.
2127 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
2128 } else {
2130 * It's within the header, but it's not one of those
2131 * fields; we can't do that in the kernel, so punt
2132 * to userland.
2134 return -1;
2136 return 0;
2139 static int
2140 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
2142 int total_filter_on = 0;
2143 int save_mode;
2144 int ret;
2145 int save_errno;
2148 * The socket filter code doesn't discard all packets queued
2149 * up on the socket when the filter is changed; this means
2150 * that packets that don't match the new filter may show up
2151 * after the new filter is put onto the socket, if those
2152 * packets haven't yet been read.
2154 * This means, for example, that if you do a tcpdump capture
2155 * with a filter, the first few packets in the capture might
2156 * be packets that wouldn't have passed the filter.
2158 * We therefore discard all packets queued up on the socket
2159 * when setting a kernel filter. (This isn't an issue for
2160 * userland filters, as the userland filtering is done after
2161 * packets are queued up.)
2163 * To flush those packets, we put the socket in read-only mode,
2164 * and read packets from the socket until there are no more to
2165 * read.
2167 * In order to keep that from being an infinite loop - i.e.,
2168 * to keep more packets from arriving while we're draining
2169 * the queue - we put the "total filter", which is a filter
2170 * that rejects all packets, onto the socket before draining
2171 * the queue.
2173 * This code deliberately ignores any errors, so that you may
2174 * get bogus packets if an error occurs, rather than having
2175 * the filtering done in userland even if it could have been
2176 * done in the kernel.
2178 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
2179 &total_fcode, sizeof(total_fcode)) == 0) {
2180 char drain[1];
2183 * Note that we've put the total filter onto the socket.
2185 total_filter_on = 1;
2188 * Save the socket's current mode, and put it in
2189 * non-blocking mode; we drain it by reading packets
2190 * until we get an error (which is normally a
2191 * "nothing more to be read" error).
2193 save_mode = fcntl(handle->fd, F_GETFL, 0);
2194 if (save_mode != -1 &&
2195 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
2196 while (recv(handle->fd, &drain, sizeof drain,
2197 MSG_TRUNC) >= 0)
2199 save_errno = errno;
2200 fcntl(handle->fd, F_SETFL, save_mode);
2201 if (save_errno != EAGAIN) {
2202 /* Fatal error */
2203 reset_kernel_filter(handle);
2204 snprintf(handle->errbuf, sizeof(handle->errbuf),
2205 "recv: %s", pcap_strerror(save_errno));
2206 return -2;
2212 * Now attach the new filter.
2214 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
2215 fcode, sizeof(*fcode));
2216 if (ret == -1 && total_filter_on) {
2218 * Well, we couldn't set that filter on the socket,
2219 * but we could set the total filter on the socket.
2221 * This could, for example, mean that the filter was
2222 * too big to put into the kernel, so we'll have to
2223 * filter in userland; in any case, we'll be doing
2224 * filtering in userland, so we need to remove the
2225 * total filter so we see packets.
2227 save_errno = errno;
2230 * XXX - if this fails, we're really screwed;
2231 * we have the total filter on the socket,
2232 * and it won't come off. What do we do then?
2234 reset_kernel_filter(handle);
2236 errno = save_errno;
2238 return ret;
2241 static int
2242 reset_kernel_filter(pcap_t *handle)
2244 /* setsockopt() barfs unless it get a dummy parameter */
2245 int dummy;
2247 return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
2248 &dummy, sizeof(dummy));
2250 #endif