]> The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
From Peter Fales <[email protected]>: support for Linux ARCNET,
[libpcap] / pcap-linux.c
1 /*
2 * pcap-linux.c: Packet capture interface to the Linux kernel
3 *
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
6 *
7 * License: BSD
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
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.
22 *
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.
26 */
27 #ifndef lint
28 static const char rcsid[] =
29 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.88 2003-01-23 07:24:52 guy Exp $ (LBL)";
30 #endif
31
32 /*
33 * Known problems with 2.0[.x] kernels:
34 *
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
41 * us do that.
42 *
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
53 * the socket.
54 *
55 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
56 * return the amount of data that you could have read, rather than
57 * the amount that was returned, so we can't just allocate a buffer
58 * whose size is the snapshot length and pass the snapshot length
59 * as the byte count, and also pass MSG_TRUNC, so that the return
60 * value tells us how long the packet was on the wire.
61 *
62 * This means that, if we want to get the actual size of the packet,
63 * so we can return it in the "len" field of the packet header,
64 * we have to read the entire packet, not just the part that fits
65 * within the snapshot length, and thus waste CPU time copying data
66 * from the kernel that our caller won't see.
67 *
68 * We have to get the actual size, and supply it in "len", because
69 * otherwise, the IP dissector in tcpdump, for example, will complain
70 * about "truncated-ip", as the packet will appear to have been
71 * shorter, on the wire, than the IP header said it should have been.
72 */
73
74
75 #ifdef HAVE_CONFIG_H
76 #include "config.h"
77 #endif
78
79 #include "pcap-int.h"
80 #include "sll.h"
81
82 #include <errno.h>
83 #include <stdlib.h>
84 #include <unistd.h>
85 #include <fcntl.h>
86 #include <string.h>
87 #include <sys/socket.h>
88 #include <sys/ioctl.h>
89 #include <sys/utsname.h>
90 #include <net/if.h>
91 #include <netinet/in.h>
92 #include <linux/if_ether.h>
93 #include <net/if_arp.h>
94
95 /*
96 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
97 * sockets rather than SOCK_PACKET sockets.
98 *
99 * To use them, we include <linux/if_packet.h> rather than
100 * <netpacket/packet.h>; we do so because
101 *
102 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
103 * later kernels and libc5, and don't provide a <netpacket/packet.h>
104 * file;
105 *
106 * not all versions of glibc2 have a <netpacket/packet.h> file
107 * that defines stuff needed for some of the 2.4-or-later-kernel
108 * features, so if the system has a 2.4 or later kernel, we
109 * still can't use those features.
110 *
111 * We're already including a number of other <linux/XXX.h> headers, and
112 * this code is Linux-specific (no other OS has PF_PACKET sockets as
113 * a raw packet capture mechanism), so it's not as if you gain any
114 * useful portability by using <netpacket/packet.h>
115 *
116 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
117 * isn't defined? It only defines one data structure in 2.0.x, so
118 * it shouldn't cause any problems.
119 */
120 #ifdef PF_PACKET
121 # include <linux/if_packet.h>
122
123 /*
124 * On at least some Linux distributions (for example, Red Hat 5.2),
125 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
126 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
127 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
128 * the PACKET_xxx stuff.
129 *
130 * So we check whether PACKET_HOST is defined, and assume that we have
131 * PF_PACKET sockets only if it is defined.
132 */
133 # ifdef PACKET_HOST
134 # define HAVE_PF_PACKET_SOCKETS
135 # endif /* PACKET_HOST */
136 #endif /* PF_PACKET */
137
138 #ifdef SO_ATTACH_FILTER
139 #include <linux/types.h>
140 #include <linux/filter.h>
141 #endif
142
143 #ifndef __GLIBC__
144 typedef int socklen_t;
145 #endif
146
147 #ifndef MSG_TRUNC
148 /*
149 * This is being compiled on a system that lacks MSG_TRUNC; define it
150 * with the value it has in the 2.2 and later kernels, so that, on
151 * those kernels, when we pass it in the flags argument to "recvfrom()"
152 * we're passing the right value and thus get the MSG_TRUNC behavior
153 * we want. (We don't get that behavior on 2.0[.x] kernels, because
154 * they didn't support MSG_TRUNC.)
155 */
156 #define MSG_TRUNC 0x20
157 #endif
158
159 #ifndef SOL_PACKET
160 /*
161 * This is being compiled on a system that lacks SOL_PACKET; define it
162 * with the value it has in the 2.2 and later kernels, so that we can
163 * set promiscuous mode in the good modern way rather than the old
164 * 2.0-kernel crappy way.
165 */
166 #define SOL_PACKET 263
167 #endif
168
169 #define MAX_LINKHEADER_SIZE 256
170
171 /*
172 * When capturing on all interfaces we use this as the buffer size.
173 * Should be bigger then all MTUs that occur in real life.
174 * 64kB should be enough for now.
175 */
176 #define BIGGER_THAN_ALL_MTUS (64*1024)
177
178 /*
179 * Prototypes for internal functions
180 */
181 static void map_arphrd_to_dlt(pcap_t *, int, int);
182 static int live_open_old(pcap_t *, const char *, int, int, char *);
183 static int live_open_new(pcap_t *, const char *, int, int, char *);
184 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
185
186 /*
187 * Wrap some ioctl calls
188 */
189 #ifdef HAVE_PF_PACKET_SOCKETS
190 static int iface_get_id(int fd, const char *device, char *ebuf);
191 #endif
192 static int iface_get_mtu(int fd, const char *device, char *ebuf);
193 static int iface_get_arptype(int fd, const char *device, char *ebuf);
194 #ifdef HAVE_PF_PACKET_SOCKETS
195 static int iface_bind(int fd, int ifindex, char *ebuf);
196 #endif
197 static int iface_bind_old(int fd, const char *device, char *ebuf);
198
199 #ifdef SO_ATTACH_FILTER
200 static int fix_program(pcap_t *handle, struct sock_fprog *fcode);
201 static int fix_offset(struct bpf_insn *p);
202 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
203 static int reset_kernel_filter(pcap_t *handle);
204
205 static struct sock_filter total_insn
206 = BPF_STMT(BPF_RET | BPF_K, 0);
207 static struct sock_fprog total_fcode
208 = { 1, &total_insn };
209 #endif
210
211 /*
212 * Get a handle for a live capture from the given device. You can
213 * pass NULL as device to get all packages (without link level
214 * information of course). If you pass 1 as promisc the interface
215 * will be set to promiscous mode (XXX: I think this usage should
216 * be deprecated and functions be added to select that later allow
217 * modification of that values -- Torsten).
218 *
219 * See also pcap(3).
220 */
221 pcap_t *
222 pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
223 char *ebuf)
224 {
225 pcap_t *handle;
226 int mtu;
227 int err;
228 int live_open_ok = 0;
229 struct utsname utsname;
230
231 /* Allocate a handle for this session. */
232
233 handle = malloc(sizeof(*handle));
234 if (handle == NULL) {
235 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
236 pcap_strerror(errno));
237 return NULL;
238 }
239
240 /* Initialize some components of the pcap structure. */
241
242 memset(handle, 0, sizeof(*handle));
243 handle->snapshot = snaplen;
244 handle->md.timeout = to_ms;
245
246 /*
247 * NULL and "any" are special devices which give us the hint to
248 * monitor all devices.
249 */
250 if (!device || strcmp(device, "any") == 0) {
251 device = NULL;
252 handle->md.device = strdup("any");
253 if (promisc) {
254 promisc = 0;
255 /* Just a warning. */
256 snprintf(ebuf, PCAP_ERRBUF_SIZE,
257 "Promiscuous mode not supported on the \"any\" device");
258 }
259
260 } else
261 handle->md.device = strdup(device);
262
263 if (handle->md.device == NULL) {
264 snprintf(ebuf, PCAP_ERRBUF_SIZE, "strdup: %s",
265 pcap_strerror(errno) );
266 free(handle);
267 return NULL;
268 }
269
270 /*
271 * Current Linux kernels use the protocol family PF_PACKET to
272 * allow direct access to all packets on the network while
273 * older kernels had a special socket type SOCK_PACKET to
274 * implement this feature.
275 * While this old implementation is kind of obsolete we need
276 * to be compatible with older kernels for a while so we are
277 * trying both methods with the newer method preferred.
278 */
279
280 if ((err = live_open_new(handle, device, promisc, to_ms, ebuf)) == 1)
281 live_open_ok = 1;
282 else if (err == 0) {
283 /* Non-fatal error; try old way */
284 if (live_open_old(handle, device, promisc, to_ms, ebuf))
285 live_open_ok = 1;
286 }
287 if (!live_open_ok) {
288 /*
289 * Both methods to open the packet socket failed. Tidy
290 * up and report our failure (ebuf is expected to be
291 * set by the functions above).
292 */
293
294 if (handle->md.device != NULL)
295 free(handle->md.device);
296 free(handle);
297 return NULL;
298 }
299
300 /*
301 * Compute the buffer size.
302 *
303 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
304 * and might require special handling - check.
305 */
306 if (handle->md.sock_packet && (uname(&utsname) < 0 ||
307 strncmp(utsname.release, "2.0", 3) == 0)) {
308 /*
309 * We're using a SOCK_PACKET structure, and either
310 * we couldn't find out what kernel release this is,
311 * or it's a 2.0[.x] kernel.
312 *
313 * In the 2.0[.x] kernel, a "recvfrom()" on
314 * a SOCK_PACKET socket, with MSG_TRUNC set, will
315 * return the number of bytes read, so if we pass
316 * a length based on the snapshot length, it'll
317 * return the number of bytes from the packet
318 * copied to userland, not the actual length
319 * of the packet.
320 *
321 * This means that, for example, the IP dissector
322 * in tcpdump will get handed a packet length less
323 * than the length in the IP header, and will
324 * complain about "truncated-ip".
325 *
326 * So we don't bother trying to copy from the
327 * kernel only the bytes in which we're interested,
328 * but instead copy them all, just as the older
329 * versions of libpcap for Linux did.
330 *
331 * The buffer therefore needs to be big enough to
332 * hold the largest packet we can get from this
333 * device. Unfortunately, we can't get the MRU
334 * of the network; we can only get the MTU. The
335 * MTU may be too small, in which case a packet larger
336 * than the buffer size will be truncated *and* we
337 * won't get the actual packet size.
338 *
339 * However, if the snapshot length is larger than
340 * the buffer size based on the MTU, we use the
341 * snapshot length as the buffer size, instead;
342 * this means that with a sufficiently large snapshot
343 * length we won't artificially truncate packets
344 * to the MTU-based size.
345 *
346 * This mess just one of many problems with packet
347 * capture on 2.0[.x] kernels; you really want a
348 * 2.2[.x] or later kernel if you want packet capture
349 * to work well.
350 */
351 mtu = iface_get_mtu(handle->fd, device, ebuf);
352 if (mtu == -1) {
353 if (handle->md.clear_promisc)
354 /* 2.0.x kernel */
355 pcap_close_linux(handle);
356 close(handle->fd);
357 if (handle->md.device != NULL)
358 free(handle->md.device);
359 free(handle);
360 return NULL;
361 }
362 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
363 if (handle->bufsize < handle->snapshot)
364 handle->bufsize = handle->snapshot;
365 } else {
366 /*
367 * This is a 2.2[.x] or later kernel (we know that
368 * either because we're not using a SOCK_PACKET
369 * socket - PF_PACKET is supported only in 2.2
370 * and later kernels - or because we checked the
371 * kernel version).
372 *
373 * We can safely pass "recvfrom()" a byte count
374 * based on the snapshot length.
375 */
376 handle->bufsize = handle->snapshot;
377 }
378
379 /* Allocate the buffer */
380
381 handle->buffer = malloc(handle->bufsize + handle->offset);
382 if (!handle->buffer) {
383 snprintf(ebuf, PCAP_ERRBUF_SIZE,
384 "malloc: %s", pcap_strerror(errno));
385 if (handle->md.clear_promisc)
386 /* 2.0.x kernel */
387 pcap_close_linux(handle);
388 close(handle->fd);
389 if (handle->md.device != NULL)
390 free(handle->md.device);
391 free(handle);
392 return NULL;
393 }
394
395 return handle;
396 }
397
398 /*
399 * Read at most max_packets from the capture stream and call the callback
400 * for each of them. Returns the number of packets handled or -1 if an
401 * error occured.
402 */
403 int
404 pcap_read(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
405 {
406 /*
407 * Currently, on Linux only one packet is delivered per read,
408 * so we don't loop.
409 */
410 return pcap_read_packet(handle, callback, user);
411 }
412
413 /*
414 * Read a packet from the socket calling the handler provided by
415 * the user. Returns the number of packets received or -1 if an
416 * error occured.
417 */
418 static int
419 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
420 {
421 u_char *bp;
422 int offset;
423 #ifdef HAVE_PF_PACKET_SOCKETS
424 struct sockaddr_ll from;
425 struct sll_header *hdrp;
426 #else
427 struct sockaddr from;
428 #endif
429 socklen_t fromlen;
430 int packet_len, caplen;
431 struct pcap_pkthdr pcap_header;
432
433 #ifdef HAVE_PF_PACKET_SOCKETS
434 /*
435 * If this is a cooked device, leave extra room for a
436 * fake packet header.
437 */
438 if (handle->md.cooked)
439 offset = SLL_HDR_LEN;
440 else
441 offset = 0;
442 #else
443 /*
444 * This system doesn't have PF_PACKET sockets, so it doesn't
445 * support cooked devices.
446 */
447 offset = 0;
448 #endif
449
450 /* Receive a single packet from the kernel */
451
452 bp = handle->buffer + handle->offset;
453 do {
454 fromlen = sizeof(from);
455 packet_len = recvfrom(
456 handle->fd, bp + offset,
457 handle->bufsize - offset, MSG_TRUNC,
458 (struct sockaddr *) &from, &fromlen);
459 } while (packet_len == -1 && errno == EINTR);
460
461 /* Check if an error occured */
462
463 if (packet_len == -1) {
464 if (errno == EAGAIN)
465 return 0; /* no packet there */
466 else {
467 snprintf(handle->errbuf, sizeof(handle->errbuf),
468 "recvfrom: %s", pcap_strerror(errno));
469 return -1;
470 }
471 }
472
473 #ifdef HAVE_PF_PACKET_SOCKETS
474 /*
475 * If this is from the loopback device, reject outgoing packets;
476 * we'll see the packet as an incoming packet as well, and
477 * we don't want to see it twice.
478 *
479 * We can only do this if we're using PF_PACKET; the address
480 * returned for SOCK_PACKET is a "sockaddr_pkt" which lacks
481 * the relevant packet type information.
482 */
483 if (!handle->md.sock_packet &&
484 from.sll_ifindex == handle->md.lo_ifindex &&
485 from.sll_pkttype == PACKET_OUTGOING)
486 return 0;
487 #endif
488
489 #ifdef HAVE_PF_PACKET_SOCKETS
490 /*
491 * If this is a cooked device, fill in the fake packet header.
492 */
493 if (handle->md.cooked) {
494 /*
495 * Add the length of the fake header to the length
496 * of packet data we read.
497 */
498 packet_len += SLL_HDR_LEN;
499
500 hdrp = (struct sll_header *)bp;
501
502 /*
503 * Map the PACKET_ value to a LINUX_SLL_ value; we
504 * want the same numerical value to be used in
505 * the link-layer header even if the numerical values
506 * for the PACKET_ #defines change, so that programs
507 * that look at the packet type field will always be
508 * able to handle DLT_LINUX_SLL captures.
509 */
510 switch (from.sll_pkttype) {
511
512 case PACKET_HOST:
513 hdrp->sll_pkttype = htons(LINUX_SLL_HOST);
514 break;
515
516 case PACKET_BROADCAST:
517 hdrp->sll_pkttype = htons(LINUX_SLL_BROADCAST);
518 break;
519
520 case PACKET_MULTICAST:
521 hdrp->sll_pkttype = htons(LINUX_SLL_MULTICAST);
522 break;
523
524 case PACKET_OTHERHOST:
525 hdrp->sll_pkttype = htons(LINUX_SLL_OTHERHOST);
526 break;
527
528 case PACKET_OUTGOING:
529 hdrp->sll_pkttype = htons(LINUX_SLL_OUTGOING);
530 break;
531
532 default:
533 hdrp->sll_pkttype = -1;
534 break;
535 }
536
537 hdrp->sll_hatype = htons(from.sll_hatype);
538 hdrp->sll_halen = htons(from.sll_halen);
539 memcpy(hdrp->sll_addr, from.sll_addr,
540 (from.sll_halen > SLL_ADDRLEN) ?
541 SLL_ADDRLEN :
542 from.sll_halen);
543 hdrp->sll_protocol = from.sll_protocol;
544 }
545 #endif
546
547 /*
548 * XXX: According to the kernel source we should get the real
549 * packet len if calling recvfrom with MSG_TRUNC set. It does
550 * not seem to work here :(, but it is supported by this code
551 * anyway.
552 * To be honest the code RELIES on that feature so this is really
553 * broken with 2.2.x kernels.
554 * I spend a day to figure out what's going on and I found out
555 * that the following is happening:
556 *
557 * The packet comes from a random interface and the packet_rcv
558 * hook is called with a clone of the packet. That code inserts
559 * the packet into the receive queue of the packet socket.
560 * If a filter is attached to that socket that filter is run
561 * first - and there lies the problem. The default filter always
562 * cuts the packet at the snaplen:
563 *
564 * # tcpdump -d
565 * (000) ret #68
566 *
567 * So the packet filter cuts down the packet. The recvfrom call
568 * says "hey, it's only 68 bytes, it fits into the buffer" with
569 * the result that we don't get the real packet length. This
570 * is valid at least until kernel 2.2.17pre6.
571 *
572 * We currently handle this by making a copy of the filter
573 * program, fixing all "ret" instructions with non-zero
574 * operands to have an operand of 65535 so that the filter
575 * doesn't truncate the packet, and supplying that modified
576 * filter to the kernel.
577 */
578
579 caplen = packet_len;
580 if (caplen > handle->snapshot)
581 caplen = handle->snapshot;
582
583 /* Run the packet filter if not using kernel filter */
584 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
585 if (bpf_filter(handle->fcode.bf_insns, bp,
586 packet_len, caplen) == 0)
587 {
588 /* rejected by filter */
589 return 0;
590 }
591 }
592
593 /* Fill in our own header data */
594
595 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
596 snprintf(handle->errbuf, sizeof(handle->errbuf),
597 "ioctl: %s", pcap_strerror(errno));
598 return -1;
599 }
600 pcap_header.caplen = caplen;
601 pcap_header.len = packet_len;
602
603 /*
604 * Count the packet.
605 *
606 * Arguably, we should count them before we check the filter,
607 * as on many other platforms "ps_recv" counts packets
608 * handed to the filter rather than packets that passed
609 * the filter, but if filtering is done in the kernel, we
610 * can't get a count of packets that passed the filter,
611 * and that would mean the meaning of "ps_recv" wouldn't
612 * be the same on all Linux systems.
613 *
614 * XXX - it's not the same on all systems in any case;
615 * ideally, we should have a "get the statistics" call
616 * that supplies more counts and indicates which of them
617 * it supplies, so that we supply a count of packets
618 * handed to the filter only on platforms where that
619 * information is available.
620 *
621 * We count them here even if we can get the packet count
622 * from the kernel, as we can only determine at run time
623 * whether we'll be able to get it from the kernel (if
624 * HAVE_TPACKET_STATS isn't defined, we can't get it from
625 * the kernel, but if it is defined, the library might
626 * have been built with a 2.4 or later kernel, but we
627 * might be running on a 2.2[.x] kernel without Alexey
628 * Kuznetzov's turbopacket patches, and thus the kernel
629 * might not be able to supply those statistics). We
630 * could, I guess, try, when opening the socket, to get
631 * the statistics, and if we can not increment the count
632 * here, but it's not clear that always incrementing
633 * the count is more expensive than always testing a flag
634 * in memory.
635 */
636 handle->md.stat.ps_recv++;
637
638 /* Call the user supplied callback function */
639 callback(userdata, &pcap_header, bp);
640
641 return 1;
642 }
643
644 /*
645 * Get the statistics for the given packet capture handle.
646 * Reports the number of dropped packets iff the kernel supports
647 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
648 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
649 * patches); otherwise, that information isn't available, and we lie
650 * and report 0 as the count of dropped packets.
651 */
652 int
653 pcap_stats(pcap_t *handle, struct pcap_stat *stats)
654 {
655 #ifdef HAVE_TPACKET_STATS
656 struct tpacket_stats kstats;
657 socklen_t len = sizeof (struct tpacket_stats);
658
659 /*
660 * Try to get the packet counts from the kernel.
661 */
662 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
663 &kstats, &len) > -1) {
664 /*
665 * In "linux/net/packet/af_packet.c", at least in the
666 * 2.4.9 kernel, "tp_packets" is incremented for every
667 * packet that passes the packet filter *and* is
668 * successfully queued on the socket; "tp_drops" is
669 * incremented for every packet dropped because there's
670 * not enough free space in the socket buffer.
671 *
672 * When the statistics are returned for a PACKET_STATISTICS
673 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
674 * so that "tp_packets" counts all packets handed to
675 * the PF_PACKET socket, including packets dropped because
676 * there wasn't room on the socket buffer - but not
677 * including packets that didn't pass the filter.
678 *
679 * In the BSD BPF, the count of received packets is
680 * incremented for every packet handed to BPF, regardless
681 * of whether it passed the filter.
682 *
683 * We can't make "pcap_stats()" work the same on both
684 * platforms, but the best approximation is to return
685 * "tp_packets" as the count of packets and "tp_drops"
686 * as the count of drops.
687 */
688 handle->md.stat.ps_recv = kstats.tp_packets;
689 handle->md.stat.ps_drop = kstats.tp_drops;
690 }
691 else
692 {
693 /*
694 * If the error was EOPNOTSUPP, fall through, so that
695 * if you build the library on a system with
696 * "struct tpacket_stats" and run it on a system
697 * that doesn't, it works as it does if the library
698 * is built on a system without "struct tpacket_stats".
699 */
700 if (errno != EOPNOTSUPP) {
701 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
702 "pcap_stats: %s", pcap_strerror(errno));
703 return -1;
704 }
705 }
706 #endif
707 /*
708 * On systems where the PACKET_STATISTICS "getsockopt()" argument
709 * is supported on PF_PACKET sockets:
710 *
711 * "ps_recv" counts only packets that *passed* the filter,
712 * not packets that didn't pass the filter. This includes
713 * packets later dropped because we ran out of buffer space.
714 *
715 * "ps_drop" counts packets dropped because we ran out of
716 * buffer space. It doesn't count packets dropped by the
717 * interface driver. It counts only packets that passed
718 * the filter.
719 *
720 * Both statistics include packets not yet read from the
721 * kernel by libpcap, and thus not yet seen by the application.
722 *
723 * On systems where the PACKET_STATISTICS "getsockopt()" argument
724 * is not supported on PF_PACKET sockets:
725 *
726 * "ps_recv" counts only packets that *passed* the filter,
727 * not packets that didn't pass the filter. It does not
728 * count packets dropped because we ran out of buffer
729 * space.
730 *
731 * "ps_drop" is not supported.
732 *
733 * "ps_recv" doesn't include packets not yet read from
734 * the kernel by libpcap.
735 */
736 *stats = handle->md.stat;
737 return 0;
738 }
739
740 /*
741 * Description string for the "any" device.
742 */
743 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
744
745 int
746 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
747 {
748 if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
749 return (-1);
750
751 return (0);
752 }
753
754 /*
755 * Attach the given BPF code to the packet capture device.
756 */
757 int
758 pcap_setfilter(pcap_t *handle, struct bpf_program *filter)
759 {
760 #ifdef SO_ATTACH_FILTER
761 struct sock_fprog fcode;
762 int can_filter_in_kernel;
763 int err = 0;
764 #endif
765
766 if (!handle)
767 return -1;
768 if (!filter) {
769 strncpy(handle->errbuf, "setfilter: No filter specified",
770 sizeof(handle->errbuf));
771 return -1;
772 }
773
774 /* Make our private copy of the filter */
775
776 if (install_bpf_program(handle, filter) < 0)
777 /* install_bpf_program() filled in errbuf */
778 return -1;
779
780 /*
781 * Run user level packet filter by default. Will be overriden if
782 * installing a kernel filter succeeds.
783 */
784 handle->md.use_bpf = 0;
785
786 /*
787 * If we're reading from a savefile, don't try to install
788 * a kernel filter.
789 */
790 if (handle->sf.rfile != NULL)
791 return 0;
792
793 /* Install kernel level filter if possible */
794
795 #ifdef SO_ATTACH_FILTER
796 #ifdef USHRT_MAX
797 if (handle->fcode.bf_len > USHRT_MAX) {
798 /*
799 * fcode.len is an unsigned short for current kernel.
800 * I have yet to see BPF-Code with that much
801 * instructions but still it is possible. So for the
802 * sake of correctness I added this check.
803 */
804 fprintf(stderr, "Warning: Filter too complex for kernel\n");
805 fcode.filter = NULL;
806 can_filter_in_kernel = 0;
807 } else
808 #endif /* USHRT_MAX */
809 {
810 /*
811 * Oh joy, the Linux kernel uses struct sock_fprog instead
812 * of struct bpf_program and of course the length field is
813 * of different size. Pointed out by Sebastian
814 *
815 * Oh, and we also need to fix it up so that all "ret"
816 * instructions with non-zero operands have 65535 as the
817 * operand, and so that, if we're in cooked mode, all
818 * memory-reference instructions use special magic offsets
819 * in references to the link-layer header and assume that
820 * the link-layer payload begins at 0; "fix_program()"
821 * will do that.
822 */
823 switch (fix_program(handle, &fcode)) {
824
825 case -1:
826 default:
827 /*
828 * Fatal error; just quit.
829 * (The "default" case shouldn't happen; we
830 * return -1 for that reason.)
831 */
832 return -1;
833
834 case 0:
835 /*
836 * The program performed checks that we can't make
837 * work in the kernel.
838 */
839 can_filter_in_kernel = 0;
840 break;
841
842 case 1:
843 /*
844 * We have a filter that'll work in the kernel.
845 */
846 can_filter_in_kernel = 1;
847 break;
848 }
849 }
850
851 if (can_filter_in_kernel) {
852 if ((err = set_kernel_filter(handle, &fcode)) == 0)
853 {
854 /* Installation succeded - using kernel filter. */
855 handle->md.use_bpf = 1;
856 }
857 else if (err == -1) /* Non-fatal error */
858 {
859 /*
860 * Print a warning if we weren't able to install
861 * the filter for a reason other than "this kernel
862 * isn't configured to support socket filters.
863 */
864 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
865 fprintf(stderr,
866 "Warning: Kernel filter failed: %s\n",
867 pcap_strerror(errno));
868 }
869 }
870 }
871
872 /*
873 * If we're not using the kernel filter, get rid of any kernel
874 * filter that might've been there before, e.g. because the
875 * previous filter could work in the kernel, or because some other
876 * code attached a filter to the socket by some means other than
877 * calling "pcap_setfilter()". Otherwise, the kernel filter may
878 * filter out packets that would pass the new userland filter.
879 */
880 if (!handle->md.use_bpf)
881 reset_kernel_filter(handle);
882
883 /*
884 * Free up the copy of the filter that was made by "fix_program()".
885 */
886 if (fcode.filter != NULL)
887 free(fcode.filter);
888
889 if (err == -2)
890 /* Fatal error */
891 return -1;
892 #endif /* SO_ATTACH_FILTER */
893
894 return 0;
895 }
896
897 /*
898 * Linux uses the ARP hardware type to identify the type of an
899 * interface. pcap uses the DLT_xxx constants for this. This
900 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
901 * constant, as arguments, and sets "handle->linktype" to the
902 * appropriate DLT_XXX constant and sets "handle->offset" to
903 * the appropriate value (to make "handle->offset" plus link-layer
904 * header length be a multiple of 4, so that the link-layer payload
905 * will be aligned on a 4-byte boundary when capturing packets).
906 * (If the offset isn't set here, it'll be 0; add code as appropriate
907 * for cases where it shouldn't be 0.)
908 *
909 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
910 * in cooked mode; otherwise, we can't use cooked mode, so we have
911 * to pick some type that works in raw mode, or fail.
912 *
913 * Sets the link type to -1 if unable to map the type.
914 */
915 static void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
916 {
917 switch (arptype) {
918
919 case ARPHRD_ETHER:
920 case ARPHRD_METRICOM:
921 case ARPHRD_LOOPBACK:
922 handle->linktype = DLT_EN10MB;
923 handle->offset = 2;
924 break;
925
926 case ARPHRD_EETHER:
927 handle->linktype = DLT_EN3MB;
928 break;
929
930 case ARPHRD_AX25:
931 handle->linktype = DLT_AX25;
932 break;
933
934 case ARPHRD_PRONET:
935 handle->linktype = DLT_PRONET;
936 break;
937
938 case ARPHRD_CHAOS:
939 handle->linktype = DLT_CHAOS;
940 break;
941
942 #ifndef ARPHRD_IEEE802_TR
943 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
944 #endif
945 case ARPHRD_IEEE802_TR:
946 case ARPHRD_IEEE802:
947 handle->linktype = DLT_IEEE802;
948 handle->offset = 2;
949 break;
950
951 case ARPHRD_ARCNET:
952 handle->linktype = DLT_ARCNET_LINUX;
953 break;
954
955 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
956 #define ARPHRD_FDDI 774
957 #endif
958 case ARPHRD_FDDI:
959 handle->linktype = DLT_FDDI;
960 handle->offset = 3;
961 break;
962
963 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
964 #define ARPHRD_ATM 19
965 #endif
966 case ARPHRD_ATM:
967 /*
968 * The Classical IP implementation in ATM for Linux
969 * supports both what RFC 1483 calls "LLC Encapsulation",
970 * in which each packet has an LLC header, possibly
971 * with a SNAP header as well, prepended to it, and
972 * what RFC 1483 calls "VC Based Multiplexing", in which
973 * different virtual circuits carry different network
974 * layer protocols, and no header is prepended to packets.
975 *
976 * They both have an ARPHRD_ type of ARPHRD_ATM, so
977 * you can't use the ARPHRD_ type to find out whether
978 * captured packets will have an LLC header, and,
979 * while there's a socket ioctl to *set* the encapsulation
980 * type, there's no ioctl to *get* the encapsulation type.
981 *
982 * This means that
983 *
984 * programs that dissect Linux Classical IP frames
985 * would have to check for an LLC header and,
986 * depending on whether they see one or not, dissect
987 * the frame as LLC-encapsulated or as raw IP (I
988 * don't know whether there's any traffic other than
989 * IP that would show up on the socket, or whether
990 * there's any support for IPv6 in the Linux
991 * Classical IP code);
992 *
993 * filter expressions would have to compile into
994 * code that checks for an LLC header and does
995 * the right thing.
996 *
997 * Both of those are a nuisance - and, at least on systems
998 * that support PF_PACKET sockets, we don't have to put
999 * up with those nuisances; instead, we can just capture
1000 * in cooked mode. That's what we'll do, if we can.
1001 * Otherwise, we'll just fail.
1002 */
1003 if (cooked_ok)
1004 handle->linktype = DLT_LINUX_SLL;
1005 else
1006 handle->linktype = -1;
1007 break;
1008
1009 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1010 #define ARPHRD_IEEE80211 801
1011 #endif
1012 case ARPHRD_IEEE80211:
1013 handle->linktype = DLT_IEEE802_11;
1014 break;
1015
1016 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1017 #define ARPHRD_IEEE80211_PRISM 802
1018 #endif
1019 case ARPHRD_IEEE80211_PRISM:
1020 handle->linktype = DLT_PRISM_HEADER;
1021 break;
1022
1023 case ARPHRD_PPP:
1024 /*
1025 * Some PPP code in the kernel supplies no link-layer
1026 * header whatsoever to PF_PACKET sockets; other PPP
1027 * code supplies PPP link-layer headers ("syncppp.c");
1028 * some PPP code might supply random link-layer
1029 * headers (PPP over ISDN - there's code in Ethereal,
1030 * for example, to cope with PPP-over-ISDN captures
1031 * with which the Ethereal developers have had to cope,
1032 * heuristically trying to determine which of the
1033 * oddball link-layer headers particular packets have).
1034 *
1035 * As such, we just punt, and run all PPP interfaces
1036 * in cooked mode, if we can; otherwise, we just treat
1037 * it as DLT_RAW, for now - if somebody needs to capture,
1038 * on a 2.0[.x] kernel, on PPP devices that supply a
1039 * link-layer header, they'll have to add code here to
1040 * map to the appropriate DLT_ type (possibly adding a
1041 * new DLT_ type, if necessary).
1042 */
1043 if (cooked_ok)
1044 handle->linktype = DLT_LINUX_SLL;
1045 else {
1046 /*
1047 * XXX - handle ISDN types here? We can't fall
1048 * back on cooked sockets, so we'd have to
1049 * figure out from the device name what type of
1050 * link-layer encapsulation it's using, and map
1051 * that to an appropriate DLT_ value, meaning
1052 * we'd map "isdnN" devices to DLT_RAW (they
1053 * supply raw IP packets with no link-layer
1054 * header) and "isdY" devices to a new DLT_I4L_IP
1055 * type that has only an Ethernet packet type as
1056 * a link-layer header.
1057 *
1058 * But sometimes we seem to get random crap
1059 * in the link-layer header when capturing on
1060 * ISDN devices....
1061 */
1062 handle->linktype = DLT_RAW;
1063 }
1064 break;
1065
1066 #ifndef ARPHRD_HDLC
1067 #define ARPHRD_HDLC 513 /* From Linux 2.2.13 */
1068 #endif
1069 case ARPHRD_HDLC:
1070 handle->linktype = DLT_C_HDLC;
1071 break;
1072
1073 /* Not sure if this is correct for all tunnels, but it
1074 * works for CIPE */
1075 case ARPHRD_TUNNEL:
1076 #ifndef ARPHRD_SIT
1077 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1078 #endif
1079 case ARPHRD_SIT:
1080 case ARPHRD_CSLIP:
1081 case ARPHRD_SLIP6:
1082 case ARPHRD_CSLIP6:
1083 case ARPHRD_ADAPT:
1084 case ARPHRD_SLIP:
1085 #ifndef ARPHRD_RAWHDLC
1086 #define ARPHRD_RAWHDLC 518
1087 #endif
1088 case ARPHRD_RAWHDLC:
1089 /*
1090 * XXX - should some of those be mapped to DLT_LINUX_SLL
1091 * instead? Should we just map all of them to DLT_LINUX_SLL?
1092 */
1093 handle->linktype = DLT_RAW;
1094 break;
1095
1096 case ARPHRD_LOCALTLK:
1097 handle->linktype = DLT_LTALK;
1098 break;
1099
1100 #ifndef ARPHRD_FCPP
1101 #define ARPHRD_FCPP 784
1102 #endif
1103 case ARPHRD_FCPP:
1104 #ifndef ARPHRD_FCAL
1105 #define ARPHRD_FCAL 785
1106 #endif
1107 case ARPHRD_FCAL:
1108 #ifndef ARPHRD_FCPL
1109 #define ARPHRD_FCPL 786
1110 #endif
1111 case ARPHRD_FCPL:
1112 #ifndef ARPHRD_FCFABRIC
1113 #define ARPHRD_FCFABRIC 787
1114 #endif
1115 case ARPHRD_FCFABRIC:
1116 /*
1117 * We assume that those all mean RFC 2625 IP-over-
1118 * Fibre Channel, with the RFC 2625 header at
1119 * the beginning of the packet.
1120 */
1121 handle->linktype = DLT_IP_OVER_FC;
1122 break;
1123
1124 default:
1125 handle->linktype = -1;
1126 break;
1127 }
1128 }
1129
1130 /* ===== Functions to interface to the newer kernels ================== */
1131
1132 /*
1133 * Try to open a packet socket using the new kernel interface.
1134 * Returns 0 on failure.
1135 * FIXME: 0 uses to mean success (Sebastian)
1136 */
1137 static int
1138 live_open_new(pcap_t *handle, const char *device, int promisc,
1139 int to_ms, char *ebuf)
1140 {
1141 #ifdef HAVE_PF_PACKET_SOCKETS
1142 int sock_fd = -1, device_id, arptype;
1143 int err;
1144 int fatal_err = 0;
1145 struct packet_mreq mr;
1146
1147 /* One shot loop used for error handling - bail out with break */
1148
1149 do {
1150 /*
1151 * Open a socket with protocol family packet. If a device is
1152 * given we try to open it in raw mode otherwise we use
1153 * the cooked interface.
1154 */
1155 sock_fd = device ?
1156 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
1157 : socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
1158
1159 if (sock_fd == -1) {
1160 snprintf(ebuf, PCAP_ERRBUF_SIZE, "socket: %s",
1161 pcap_strerror(errno) );
1162 break;
1163 }
1164
1165 /* It seems the kernel supports the new interface. */
1166 handle->md.sock_packet = 0;
1167
1168 /*
1169 * Get the interface index of the loopback device.
1170 * If the attempt fails, don't fail, just set the
1171 * "md.lo_ifindex" to -1.
1172 *
1173 * XXX - can there be more than one device that loops
1174 * packets back, i.e. devices other than "lo"? If so,
1175 * we'd need to find them all, and have an array of
1176 * indices for them, and check all of them in
1177 * "pcap_read_packet()".
1178 */
1179 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", ebuf);
1180
1181 /*
1182 * Default value for offset to align link-layer payload
1183 * on a 4-byte boundary.
1184 */
1185 handle->offset = 0;
1186
1187 /*
1188 * What kind of frames do we have to deal with? Fall back
1189 * to cooked mode if we have an unknown interface type.
1190 */
1191
1192 if (device) {
1193 /* Assume for now we don't need cooked mode. */
1194 handle->md.cooked = 0;
1195
1196 arptype = iface_get_arptype(sock_fd, device, ebuf);
1197 if (arptype == -1) {
1198 fatal_err = 1;
1199 break;
1200 }
1201 map_arphrd_to_dlt(handle, arptype, 1);
1202 if (handle->linktype == -1 ||
1203 handle->linktype == DLT_LINUX_SLL ||
1204 (handle->linktype == DLT_EN10MB &&
1205 (strncmp("isdn", device, 4) == 0 ||
1206 strncmp("isdY", device, 4) == 0))) {
1207 /*
1208 * Unknown interface type (-1), or a
1209 * device we explicitly chose to run
1210 * in cooked mode (e.g., PPP devices),
1211 * or an ISDN device (whose link-layer
1212 * type we can only determine by using
1213 * APIs that may be different on different
1214 * kernels) - reopen in cooked mode.
1215 */
1216 if (close(sock_fd) == -1) {
1217 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1218 "close: %s", pcap_strerror(errno));
1219 break;
1220 }
1221 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
1222 htons(ETH_P_ALL));
1223 if (sock_fd == -1) {
1224 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1225 "socket: %s", pcap_strerror(errno));
1226 break;
1227 }
1228 handle->md.cooked = 1;
1229
1230 if (handle->linktype == -1) {
1231 /*
1232 * Warn that we're falling back on
1233 * cooked mode; we may want to
1234 * update "map_arphrd_to_dlt()"
1235 * to handle the new type.
1236 */
1237 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1238 "arptype %d not "
1239 "supported by libpcap - "
1240 "falling back to cooked "
1241 "socket",
1242 arptype);
1243 }
1244 handle->linktype = DLT_LINUX_SLL;
1245 }
1246
1247 device_id = iface_get_id(sock_fd, device, ebuf);
1248 if (device_id == -1)
1249 break;
1250
1251 if ((err = iface_bind(sock_fd, device_id, ebuf)) < 0) {
1252 if (err == -2)
1253 fatal_err = 1;
1254 break;
1255 }
1256 } else {
1257 /*
1258 * This is cooked mode.
1259 */
1260 handle->md.cooked = 1;
1261 handle->linktype = DLT_LINUX_SLL;
1262
1263 /*
1264 * XXX - squelch GCC complaints about
1265 * uninitialized variables; if we can't
1266 * select promiscuous mode on all interfaces,
1267 * we should move the code below into the
1268 * "if (device)" branch of the "if" and
1269 * get rid of the next statement.
1270 */
1271 device_id = -1;
1272 }
1273
1274 /* Select promiscuous mode on/off */
1275
1276 /*
1277 * Hmm, how can we set promiscuous mode on all interfaces?
1278 * I am not sure if that is possible at all.
1279 */
1280
1281 if (device) {
1282 memset(&mr, 0, sizeof(mr));
1283 mr.mr_ifindex = device_id;
1284 mr.mr_type = promisc ?
1285 PACKET_MR_PROMISC : PACKET_MR_ALLMULTI;
1286 if (setsockopt(sock_fd, SOL_PACKET,
1287 PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == -1)
1288 {
1289 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1290 "setsockopt: %s", pcap_strerror(errno));
1291 break;
1292 }
1293 }
1294
1295 /* Save the socket FD in the pcap structure */
1296
1297 handle->fd = sock_fd;
1298
1299 return 1;
1300
1301 } while(0);
1302
1303 if (sock_fd != -1)
1304 close(sock_fd);
1305
1306 if (fatal_err)
1307 return -2;
1308 else
1309 return 0;
1310 #else
1311 strncpy(ebuf,
1312 "New packet capturing interface not supported by build "
1313 "environment", PCAP_ERRBUF_SIZE);
1314 return 0;
1315 #endif
1316 }
1317
1318 #ifdef HAVE_PF_PACKET_SOCKETS
1319 /*
1320 * Return the index of the given device name. Fill ebuf and return
1321 * -1 on failure.
1322 */
1323 static int
1324 iface_get_id(int fd, const char *device, char *ebuf)
1325 {
1326 struct ifreq ifr;
1327
1328 memset(&ifr, 0, sizeof(ifr));
1329 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1330
1331 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
1332 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1333 "ioctl: %s", pcap_strerror(errno));
1334 return -1;
1335 }
1336
1337 return ifr.ifr_ifindex;
1338 }
1339
1340 /*
1341 * Bind the socket associated with FD to the given device.
1342 */
1343 static int
1344 iface_bind(int fd, int ifindex, char *ebuf)
1345 {
1346 struct sockaddr_ll sll;
1347 int err;
1348 socklen_t errlen = sizeof(err);
1349
1350 memset(&sll, 0, sizeof(sll));
1351 sll.sll_family = AF_PACKET;
1352 sll.sll_ifindex = ifindex;
1353 sll.sll_protocol = htons(ETH_P_ALL);
1354
1355 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
1356 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1357 "bind: %s", pcap_strerror(errno));
1358 return -1;
1359 }
1360
1361 /* Any pending errors, e.g., network is down? */
1362
1363 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
1364 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1365 "getsockopt: %s", pcap_strerror(errno));
1366 return -2;
1367 }
1368
1369 if (err > 0) {
1370 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1371 "bind: %s", pcap_strerror(err));
1372 return -2;
1373 }
1374
1375 return 0;
1376 }
1377
1378 #endif
1379
1380
1381 /* ===== Functions to interface to the older kernels ================== */
1382
1383 /*
1384 * With older kernels promiscuous mode is kind of interesting because we
1385 * have to reset the interface before exiting. The problem can't really
1386 * be solved without some daemon taking care of managing usage counts.
1387 * If we put the interface into promiscuous mode, we set a flag indicating
1388 * that we must take it out of that mode when the interface is closed,
1389 * and, when closing the interface, if that flag is set we take it out
1390 * of promiscuous mode.
1391 */
1392
1393 /*
1394 * List of pcaps for which we turned promiscuous mode on by hand.
1395 * If there are any such pcaps, we arrange to call "pcap_close_all()"
1396 * when we exit, and have it close all of them to turn promiscuous mode
1397 * off.
1398 */
1399 static struct pcap *pcaps_to_close;
1400
1401 /*
1402 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1403 * be called on exit.
1404 */
1405 static int did_atexit;
1406
1407 static void pcap_close_all(void)
1408 {
1409 struct pcap *handle;
1410
1411 while ((handle = pcaps_to_close) != NULL)
1412 pcap_close(handle);
1413 }
1414
1415 void pcap_close_linux( pcap_t *handle )
1416 {
1417 struct pcap *p, *prevp;
1418 struct ifreq ifr;
1419
1420 if (handle->md.clear_promisc) {
1421 /*
1422 * We put the interface into promiscuous mode; take
1423 * it out of promiscuous mode.
1424 *
1425 * XXX - if somebody else wants it in promiscuous mode,
1426 * this code cannot know that, so it'll take it out
1427 * of promiscuous mode. That's not fixable in 2.0[.x]
1428 * kernels.
1429 */
1430 memset(&ifr, 0, sizeof(ifr));
1431 strncpy(ifr.ifr_name, handle->md.device, sizeof(ifr.ifr_name));
1432 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1433 fprintf(stderr,
1434 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1435 "Please adjust manually.\n"
1436 "Hint: This can't happen with Linux >= 2.2.0.\n",
1437 strerror(errno));
1438 } else {
1439 if (ifr.ifr_flags & IFF_PROMISC) {
1440 /*
1441 * Promiscuous mode is currently on; turn it
1442 * off.
1443 */
1444 ifr.ifr_flags &= ~IFF_PROMISC;
1445 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1446 fprintf(stderr,
1447 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1448 "Please adjust manually.\n"
1449 "Hint: This can't happen with Linux >= 2.2.0.\n",
1450 strerror(errno));
1451 }
1452 }
1453 }
1454
1455 /*
1456 * Take this pcap out of the list of pcaps for which we
1457 * have to take the interface out of promiscuous mode.
1458 */
1459 for (p = pcaps_to_close, prevp = NULL; p != NULL;
1460 prevp = p, p = p->md.next) {
1461 if (p == handle) {
1462 /*
1463 * Found it. Remove it from the list.
1464 */
1465 if (prevp == NULL) {
1466 /*
1467 * It was at the head of the list.
1468 */
1469 pcaps_to_close = p->md.next;
1470 } else {
1471 /*
1472 * It was in the middle of the list.
1473 */
1474 prevp->md.next = p->md.next;
1475 }
1476 break;
1477 }
1478 }
1479 }
1480
1481 if (handle->md.device != NULL)
1482 free(handle->md.device);
1483 handle->md.device = NULL;
1484 }
1485
1486 /*
1487 * Try to open a packet socket using the old kernel interface.
1488 * Returns 0 on failure.
1489 * FIXME: 0 uses to mean success (Sebastian)
1490 */
1491 static int
1492 live_open_old(pcap_t *handle, const char *device, int promisc,
1493 int to_ms, char *ebuf)
1494 {
1495 int sock_fd = -1, arptype;
1496 struct ifreq ifr;
1497
1498 do {
1499 /* Open the socket */
1500
1501 sock_fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
1502 if (sock_fd == -1) {
1503 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1504 "socket: %s", pcap_strerror(errno));
1505 break;
1506 }
1507
1508 /* It worked - we are using the old interface */
1509 handle->md.sock_packet = 1;
1510
1511 /* ...which means we get the link-layer header. */
1512 handle->md.cooked = 0;
1513
1514 /* Bind to the given device */
1515
1516 if (!device) {
1517 strncpy(ebuf, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
1518 PCAP_ERRBUF_SIZE);
1519 break;
1520 }
1521 if (iface_bind_old(sock_fd, device, ebuf) == -1)
1522 break;
1523
1524 /*
1525 * Try to get the link-layer type.
1526 */
1527 arptype = iface_get_arptype(sock_fd, device, ebuf);
1528 if (arptype == -1)
1529 break;
1530
1531 /*
1532 * Try to find the DLT_ type corresponding to that
1533 * link-layer type.
1534 */
1535 map_arphrd_to_dlt(handle, arptype, 0);
1536 if (handle->linktype == -1) {
1537 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1538 "unknown arptype %d", arptype);
1539 break;
1540 }
1541
1542 /* Go to promisc mode if requested */
1543
1544 if (promisc) {
1545 memset(&ifr, 0, sizeof(ifr));
1546 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1547 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
1548 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1549 "ioctl: %s", pcap_strerror(errno));
1550 break;
1551 }
1552 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
1553 /*
1554 * Promiscuous mode isn't currently on,
1555 * so turn it on, and remember that
1556 * we should turn it off when the
1557 * pcap_t is closed.
1558 */
1559
1560 /*
1561 * If we haven't already done so, arrange
1562 * to have "pcap_close_all()" called when
1563 * we exit.
1564 */
1565 if (!did_atexit) {
1566 if (atexit(pcap_close_all) == -1) {
1567 /*
1568 * "atexit()" failed; don't
1569 * put the interface in
1570 * promiscuous mode, just
1571 * give up.
1572 */
1573 strncpy(ebuf, "atexit failed",
1574 PCAP_ERRBUF_SIZE);
1575 break;
1576 }
1577 did_atexit = 1;
1578 }
1579
1580 ifr.ifr_flags |= IFF_PROMISC;
1581 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
1582 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1583 "ioctl: %s",
1584 pcap_strerror(errno));
1585 break;
1586 }
1587 handle->md.clear_promisc = 1;
1588
1589 /*
1590 * Add this to the list of pcaps
1591 * to close when we exit.
1592 */
1593 handle->md.next = pcaps_to_close;
1594 pcaps_to_close = handle;
1595 }
1596 }
1597
1598 /* Save the socket FD in the pcap structure */
1599
1600 handle->fd = sock_fd;
1601
1602 /*
1603 * Default value for offset to align link-layer payload
1604 * on a 4-byte boundary.
1605 */
1606 handle->offset = 0;
1607
1608 return 1;
1609
1610 } while (0);
1611
1612 if (handle->md.clear_promisc)
1613 pcap_close_linux(handle);
1614 if (sock_fd != -1)
1615 close(sock_fd);
1616 return 0;
1617 }
1618
1619 /*
1620 * Bind the socket associated with FD to the given device using the
1621 * interface of the old kernels.
1622 */
1623 static int
1624 iface_bind_old(int fd, const char *device, char *ebuf)
1625 {
1626 struct sockaddr saddr;
1627 int err;
1628 socklen_t errlen = sizeof(err);
1629
1630 memset(&saddr, 0, sizeof(saddr));
1631 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
1632 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
1633 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1634 "bind: %s", pcap_strerror(errno));
1635 return -1;
1636 }
1637
1638 /* Any pending errors, e.g., network is down? */
1639
1640 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
1641 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1642 "getsockopt: %s", pcap_strerror(errno));
1643 return -1;
1644 }
1645
1646 if (err > 0) {
1647 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1648 "bind: %s", pcap_strerror(err));
1649 return -1;
1650 }
1651
1652 return 0;
1653 }
1654
1655
1656 /* ===== System calls available on all supported kernels ============== */
1657
1658 /*
1659 * Query the kernel for the MTU of the given interface.
1660 */
1661 static int
1662 iface_get_mtu(int fd, const char *device, char *ebuf)
1663 {
1664 struct ifreq ifr;
1665
1666 if (!device)
1667 return BIGGER_THAN_ALL_MTUS;
1668
1669 memset(&ifr, 0, sizeof(ifr));
1670 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1671
1672 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
1673 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1674 "ioctl: %s", pcap_strerror(errno));
1675 return -1;
1676 }
1677
1678 return ifr.ifr_mtu;
1679 }
1680
1681 /*
1682 * Get the hardware type of the given interface as ARPHRD_xxx constant.
1683 */
1684 static int
1685 iface_get_arptype(int fd, const char *device, char *ebuf)
1686 {
1687 struct ifreq ifr;
1688
1689 memset(&ifr, 0, sizeof(ifr));
1690 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1691
1692 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
1693 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1694 "ioctl: %s", pcap_strerror(errno));
1695 return -1;
1696 }
1697
1698 return ifr.ifr_hwaddr.sa_family;
1699 }
1700
1701 #ifdef SO_ATTACH_FILTER
1702 static int
1703 fix_program(pcap_t *handle, struct sock_fprog *fcode)
1704 {
1705 size_t prog_size;
1706 register int i;
1707 register struct bpf_insn *p;
1708 struct bpf_insn *f;
1709 int len;
1710
1711 /*
1712 * Make a copy of the filter, and modify that copy if
1713 * necessary.
1714 */
1715 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
1716 len = handle->fcode.bf_len;
1717 f = (struct bpf_insn *)malloc(prog_size);
1718 if (f == NULL) {
1719 snprintf(handle->errbuf, sizeof(handle->errbuf),
1720 "malloc: %s", pcap_strerror(errno));
1721 return -1;
1722 }
1723 memcpy(f, handle->fcode.bf_insns, prog_size);
1724 fcode->len = len;
1725 fcode->filter = (struct sock_filter *) f;
1726
1727 for (i = 0; i < len; ++i) {
1728 p = &f[i];
1729 /*
1730 * What type of instruction is this?
1731 */
1732 switch (BPF_CLASS(p->code)) {
1733
1734 case BPF_RET:
1735 /*
1736 * It's a return instruction; is the snapshot
1737 * length a constant, rather than the contents
1738 * of the accumulator?
1739 */
1740 if (BPF_MODE(p->code) == BPF_K) {
1741 /*
1742 * Yes - if the value to be returned,
1743 * i.e. the snapshot length, is anything
1744 * other than 0, make it 65535, so that
1745 * the packet is truncated by "recvfrom()",
1746 * not by the filter.
1747 *
1748 * XXX - there's nothing we can easily do
1749 * if it's getting the value from the
1750 * accumulator; we'd have to insert
1751 * code to force non-zero values to be
1752 * 65535.
1753 */
1754 if (p->k != 0)
1755 p->k = 65535;
1756 }
1757 break;
1758
1759 case BPF_LD:
1760 case BPF_LDX:
1761 /*
1762 * It's a load instruction; is it loading
1763 * from the packet?
1764 */
1765 switch (BPF_MODE(p->code)) {
1766
1767 case BPF_ABS:
1768 case BPF_IND:
1769 case BPF_MSH:
1770 /*
1771 * Yes; are we in cooked mode?
1772 */
1773 if (handle->md.cooked) {
1774 /*
1775 * Yes, so we need to fix this
1776 * instruction.
1777 */
1778 if (fix_offset(p) < 0) {
1779 /*
1780 * We failed to do so.
1781 * Return 0, so our caller
1782 * knows to punt to userland.
1783 */
1784 return 0;
1785 }
1786 }
1787 break;
1788 }
1789 break;
1790 }
1791 }
1792 return 1; /* we succeeded */
1793 }
1794
1795 static int
1796 fix_offset(struct bpf_insn *p)
1797 {
1798 /*
1799 * What's the offset?
1800 */
1801 if (p->k >= SLL_HDR_LEN) {
1802 /*
1803 * It's within the link-layer payload; that starts at an
1804 * offset of 0, as far as the kernel packet filter is
1805 * concerned, so subtract the length of the link-layer
1806 * header.
1807 */
1808 p->k -= SLL_HDR_LEN;
1809 } else if (p->k == 14) {
1810 /*
1811 * It's the protocol field; map it to the special magic
1812 * kernel offset for that field.
1813 */
1814 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
1815 } else {
1816 /*
1817 * It's within the header, but it's not one of those
1818 * fields; we can't do that in the kernel, so punt
1819 * to userland.
1820 */
1821 return -1;
1822 }
1823 return 0;
1824 }
1825
1826 static int
1827 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
1828 {
1829 int total_filter_on = 0;
1830 int save_mode;
1831 int ret;
1832 int save_errno;
1833
1834 /*
1835 * The socket filter code doesn't discard all packets queued
1836 * up on the socket when the filter is changed; this means
1837 * that packets that don't match the new filter may show up
1838 * after the new filter is put onto the socket, if those
1839 * packets haven't yet been read.
1840 *
1841 * This means, for example, that if you do a tcpdump capture
1842 * with a filter, the first few packets in the capture might
1843 * be packets that wouldn't have passed the filter.
1844 *
1845 * We therefore discard all packets queued up on the socket
1846 * when setting a kernel filter. (This isn't an issue for
1847 * userland filters, as the userland filtering is done after
1848 * packets are queued up.)
1849 *
1850 * To flush those packets, we put the socket in read-only mode,
1851 * and read packets from the socket until there are no more to
1852 * read.
1853 *
1854 * In order to keep that from being an infinite loop - i.e.,
1855 * to keep more packets from arriving while we're draining
1856 * the queue - we put the "total filter", which is a filter
1857 * that rejects all packets, onto the socket before draining
1858 * the queue.
1859 *
1860 * This code deliberately ignores any errors, so that you may
1861 * get bogus packets if an error occurs, rather than having
1862 * the filtering done in userland even if it could have been
1863 * done in the kernel.
1864 */
1865 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
1866 &total_fcode, sizeof(total_fcode)) == 0) {
1867 char drain[1];
1868
1869 /*
1870 * Note that we've put the total filter onto the socket.
1871 */
1872 total_filter_on = 1;
1873
1874 /*
1875 * Save the socket's current mode, and put it in
1876 * non-blocking mode; we drain it by reading packets
1877 * until we get an error (which is normally a
1878 * "nothing more to be read" error).
1879 */
1880 save_mode = fcntl(handle->fd, F_GETFL, 0);
1881 if (save_mode != -1 &&
1882 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
1883 while (recv(handle->fd, &drain, sizeof drain,
1884 MSG_TRUNC) >= 0)
1885 ;
1886 save_errno = errno;
1887 fcntl(handle->fd, F_SETFL, save_mode);
1888 if (save_errno != EAGAIN) {
1889 /* Fatal error */
1890 reset_kernel_filter(handle);
1891 snprintf(handle->errbuf, sizeof(handle->errbuf),
1892 "recv: %s", pcap_strerror(save_errno));
1893 return -2;
1894 }
1895 }
1896 }
1897
1898 /*
1899 * Now attach the new filter.
1900 */
1901 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
1902 fcode, sizeof(*fcode));
1903 if (ret == -1 && total_filter_on) {
1904 /*
1905 * Well, we couldn't set that filter on the socket,
1906 * but we could set the total filter on the socket.
1907 *
1908 * This could, for example, mean that the filter was
1909 * too big to put into the kernel, so we'll have to
1910 * filter in userland; in any case, we'll be doing
1911 * filtering in userland, so we need to remove the
1912 * total filter so we see packets.
1913 */
1914 save_errno = errno;
1915
1916 /*
1917 * XXX - if this fails, we're really screwed;
1918 * we have the total filter on the socket,
1919 * and it won't come off. What do we do then?
1920 */
1921 reset_kernel_filter(handle);
1922
1923 errno = save_errno;
1924 }
1925 return ret;
1926 }
1927
1928 static int
1929 reset_kernel_filter(pcap_t *handle)
1930 {
1931 /* setsockopt() barfs unless it get a dummy parameter */
1932 int dummy;
1933
1934 return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
1935 &dummy, sizeof(dummy));
1936 }
1937 #endif
1938
1939 int
1940 pcap_set_datalink_platform(pcap_t *p, int dlt)
1941 {
1942 return (0);
1943 }