]> The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
Patch, based on a patch from Pavel Kankovsky <[email protected]>, to flush all
[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.65 2001-08-25 05:08:26 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 #define MAX_LINKHEADER_SIZE 256
160
161 /*
162 * When capturing on all interfaces we use this as the buffer size.
163 * Should be bigger then all MTUs that occur in real life.
164 * 64kB should be enough for now.
165 */
166 #define BIGGER_THAN_ALL_MTUS (64*1024)
167
168 /*
169 * Prototypes for internal functions
170 */
171 static int map_arphrd_to_dlt(pcap_t *, int);
172 static int live_open_old(pcap_t *, char *, int, int, char *);
173 static int live_open_new(pcap_t *, char *, int, int, char *);
174 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
175
176 /*
177 * Wrap some ioctl calls
178 */
179 #ifdef HAVE_PF_PACKET_SOCKETS
180 static int iface_get_id(int fd, const char *device, char *ebuf);
181 #endif
182 static int iface_get_mtu(int fd, const char *device, char *ebuf);
183 static int iface_get_arptype(int fd, const char *device, char *ebuf);
184 #ifdef HAVE_PF_PACKET_SOCKETS
185 static int iface_bind(int fd, int ifindex, char *ebuf);
186 #endif
187 static int iface_bind_old(int fd, const char *device, char *ebuf);
188
189 #ifdef SO_ATTACH_FILTER
190 static int fix_program(pcap_t *handle, struct sock_fprog *fcode);
191 static int fix_offset(struct bpf_insn *p);
192 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
193
194 static struct sock_filter total_insn
195 = BPF_STMT(BPF_RET | BPF_K, 0);
196 static struct sock_fprog total_fcode
197 = { 1, &total_insn };
198 #endif
199
200 /*
201 * Get a handle for a live capture from the given device. You can
202 * pass NULL as device to get all packages (without link level
203 * information of course). If you pass 1 as promisc the interface
204 * will be set to promiscous mode (XXX: I think this usage should
205 * be deprecated and functions be added to select that later allow
206 * modification of that values -- Torsten).
207 *
208 * See also pcap(3).
209 */
210 pcap_t *
211 pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *ebuf)
212 {
213 pcap_t *handle;
214 int mtu;
215 struct utsname utsname;
216
217 /* Allocate a handle for this session. */
218
219 handle = malloc(sizeof(*handle));
220 if (handle == NULL) {
221 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
222 pcap_strerror(errno));
223 return NULL;
224 }
225
226 /* Initialize some components of the pcap structure. */
227
228 memset(handle, 0, sizeof(*handle));
229 handle->snapshot = snaplen;
230 handle->md.timeout = to_ms;
231
232 /*
233 * NULL and "any" are special devices which give us the hint to
234 * monitor all devices.
235 */
236 if (!device || strcmp(device, "any") == 0) {
237 device = NULL;
238 handle->md.device = strdup("any");
239 } else
240 handle->md.device = strdup(device);
241
242 if (handle->md.device == NULL) {
243 snprintf(ebuf, PCAP_ERRBUF_SIZE, "strdup: %s",
244 pcap_strerror(errno) );
245 free(handle);
246 return NULL;
247 }
248
249 /*
250 * Current Linux kernels use the protocol family PF_PACKET to
251 * allow direct access to all packets on the network while
252 * older kernels had a special socket type SOCK_PACKET to
253 * implement this feature.
254 * While this old implementation is kind of obsolete we need
255 * to be compatible with older kernels for a while so we are
256 * trying both methods with the newer method preferred.
257 */
258
259 if (! (live_open_new(handle, device, promisc, to_ms, ebuf) ||
260 live_open_old(handle, device, promisc, to_ms, ebuf)) )
261 {
262 /*
263 * Both methods to open the packet socket failed. Tidy
264 * up and report our failure (ebuf is expected to be
265 * set by the functions above).
266 */
267
268 free(handle->md.device);
269 free(handle);
270 return NULL;
271 }
272
273 /*
274 * Compute the buffer size.
275 *
276 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
277 * and might require special handling - check.
278 */
279 if (handle->md.sock_packet && (uname(&utsname) < 0 ||
280 strncmp(utsname.release, "2.0", 3) == 0)) {
281 /*
282 * We're using a SOCK_PACKET structure, and either
283 * we couldn't find out what kernel release this is,
284 * or it's a 2.0[.x] kernel.
285 *
286 * In the 2.0[.x] kernel, a "recvfrom()" on
287 * a SOCK_PACKET socket, with MSG_TRUNC set, will
288 * return the number of bytes read, so if we pass
289 * a length based on the snapshot length, it'll
290 * return the number of bytes from the packet
291 * copied to userland, not the actual length
292 * of the packet.
293 *
294 * This means that, for example, the IP dissector
295 * in tcpdump will get handed a packet length less
296 * than the length in the IP header, and will
297 * complain about "truncated-ip".
298 *
299 * So we don't bother trying to copy from the
300 * kernel only the bytes in which we're interested,
301 * but instead copy them all, just as the older
302 * versions of libpcap for Linux did.
303 *
304 * The buffer therefore needs to be big enough to
305 * hold the largest packet we can get from this
306 * device. Unfortunately, we can't get the MRU
307 * of the network; we can only get the MTU. The
308 * MTU may be too small, in which case a packet larger
309 * than the buffer size will be truncated *and* we
310 * won't get the actual packet size.
311 *
312 * However, if the snapshot length is larger than
313 * the buffer size based on the MTU, we use the
314 * snapshot length as the buffer size, instead;
315 * this means that with a sufficiently large snapshot
316 * length we won't artificially truncate packets
317 * to the MTU-based size.
318 *
319 * This mess just one of many problems with packet
320 * capture on 2.0[.x] kernels; you really want a
321 * 2.2[.x] or later kernel if you want packet capture
322 * to work well.
323 */
324 mtu = iface_get_mtu(handle->fd, device, ebuf);
325 if (mtu == -1) {
326 close(handle->fd);
327 free(handle->md.device);
328 free(handle);
329 return NULL;
330 }
331 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
332 if (handle->bufsize < handle->snapshot)
333 handle->bufsize = handle->snapshot;
334 } else {
335 /*
336 * This is a 2.2[.x] or later kernel (we know that
337 * either because we're not using a SOCK_PACKET
338 * socket - PF_PACKET is supported only in 2.2
339 * and later kernels - or because we checked the
340 * kernel version).
341 *
342 * We can safely pass "recvfrom()" a byte count
343 * based on the snapshot length.
344 */
345 handle->bufsize = handle->snapshot;
346 }
347
348 /* Allocate the buffer */
349
350 handle->buffer = malloc(handle->bufsize + handle->offset);
351 if (!handle->buffer) {
352 snprintf(ebuf, PCAP_ERRBUF_SIZE,
353 "malloc: %s", pcap_strerror(errno));
354 close(handle->fd);
355 free(handle->md.device);
356 free(handle);
357 return NULL;
358 }
359
360 return handle;
361 }
362
363 /*
364 * Read at most max_packets from the capture stream and call the callback
365 * for each of them. Returns the number of packets handled or -1 if an
366 * error occured.
367 */
368 int
369 pcap_read(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
370 {
371 /*
372 * Currently, on Linux only one packet is delivered per read,
373 * so we don't loop.
374 */
375 return pcap_read_packet(handle, callback, user);
376 }
377
378 /*
379 * Read a packet from the socket calling the handler provided by
380 * the user. Returns the number of packets received or -1 if an
381 * error occured.
382 */
383 static int
384 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
385 {
386 u_char *bp;
387 int offset;
388 #ifdef HAVE_PF_PACKET_SOCKETS
389 struct sockaddr_ll from;
390 struct sll_header *hdrp;
391 #else
392 struct sockaddr from;
393 #endif
394 socklen_t fromlen;
395 int packet_len, caplen;
396 struct pcap_pkthdr pcap_header;
397
398 #ifdef HAVE_PF_PACKET_SOCKETS
399 /*
400 * If this is a cooked device, leave extra room for a
401 * fake packet header.
402 */
403 if (handle->md.cooked)
404 offset = SLL_HDR_LEN;
405 else
406 offset = 0;
407 #else
408 /*
409 * This system doesn't have PF_PACKET sockets, so it doesn't
410 * support cooked devices.
411 */
412 offset = 0;
413 #endif
414
415 /* Receive a single packet from the kernel */
416
417 bp = handle->buffer + handle->offset;
418 do {
419 fromlen = sizeof(from);
420 packet_len = recvfrom(
421 handle->fd, bp + offset,
422 handle->bufsize - offset, MSG_TRUNC,
423 (struct sockaddr *) &from, &fromlen);
424 } while (packet_len == -1 && errno == EINTR);
425
426 /* Check if an error occured */
427
428 if (packet_len == -1) {
429 if (errno == EAGAIN)
430 return 0; /* no packet there */
431 else {
432 snprintf(handle->errbuf, sizeof(handle->errbuf),
433 "recvfrom: %s", pcap_strerror(errno));
434 return -1;
435 }
436 }
437
438 #ifdef HAVE_PF_PACKET_SOCKETS
439 /*
440 * If this is from the loopback device, reject outgoing packets;
441 * we'll see the packet as an incoming packet as well, and
442 * we don't want to see it twice.
443 *
444 * We can only do this if we're using PF_PACKET; the address
445 * returned for SOCK_PACKET is a "sockaddr_pkt" which lacks
446 * the relevant packet type information.
447 */
448 if (!handle->md.sock_packet &&
449 from.sll_ifindex == handle->md.lo_ifindex &&
450 from.sll_pkttype == PACKET_OUTGOING)
451 return 0;
452 #endif
453
454 #ifdef HAVE_PF_PACKET_SOCKETS
455 /*
456 * If this is a cooked device, fill in the fake packet header.
457 */
458 if (handle->md.cooked) {
459 /*
460 * Add the length of the fake header to the length
461 * of packet data we read.
462 */
463 packet_len += SLL_HDR_LEN;
464
465 hdrp = (struct sll_header *)bp;
466
467 /*
468 * Map the PACKET_ value to a LINUX_SLL_ value; we
469 * want the same numerical value to be used in
470 * the link-layer header even if the numerical values
471 * for the PACKET_ #defines change, so that programs
472 * that look at the packet type field will always be
473 * able to handle DLT_LINUX_SLL captures.
474 */
475 switch (from.sll_pkttype) {
476
477 case PACKET_HOST:
478 hdrp->sll_pkttype = htons(LINUX_SLL_HOST);
479 break;
480
481 case PACKET_BROADCAST:
482 hdrp->sll_pkttype = htons(LINUX_SLL_BROADCAST);
483 break;
484
485 case PACKET_MULTICAST:
486 hdrp->sll_pkttype = htons(LINUX_SLL_MULTICAST);
487 break;
488
489 case PACKET_OTHERHOST:
490 hdrp->sll_pkttype = htons(LINUX_SLL_OTHERHOST);
491 break;
492
493 case PACKET_OUTGOING:
494 hdrp->sll_pkttype = htons(LINUX_SLL_OUTGOING);
495 break;
496
497 default:
498 hdrp->sll_pkttype = -1;
499 break;
500 }
501
502 hdrp->sll_hatype = htons(from.sll_hatype);
503 hdrp->sll_halen = htons(from.sll_halen);
504 memcpy(hdrp->sll_addr, from.sll_addr,
505 (from.sll_halen > SLL_ADDRLEN) ?
506 SLL_ADDRLEN :
507 from.sll_halen);
508 hdrp->sll_protocol = from.sll_protocol;
509 }
510 #endif
511
512 /*
513 * XXX: According to the kernel source we should get the real
514 * packet len if calling recvfrom with MSG_TRUNC set. It does
515 * not seem to work here :(, but it is supported by this code
516 * anyway.
517 * To be honest the code RELIES on that feature so this is really
518 * broken with 2.2.x kernels.
519 * I spend a day to figure out what's going on and I found out
520 * that the following is happening:
521 *
522 * The packet comes from a random interface and the packet_rcv
523 * hook is called with a clone of the packet. That code inserts
524 * the packet into the receive queue of the packet socket.
525 * If a filter is attached to that socket that filter is run
526 * first - and there lies the problem. The default filter always
527 * cuts the packet at the snaplen:
528 *
529 * # tcpdump -d
530 * (000) ret #68
531 *
532 * So the packet filter cuts down the packet. The recvfrom call
533 * says "hey, it's only 68 bytes, it fits into the buffer" with
534 * the result that we don't get the real packet length. This
535 * is valid at least until kernel 2.2.17pre6.
536 *
537 * We currently handle this by making a copy of the filter
538 * program, fixing all "ret" instructions with non-zero
539 * operands to have an operand of 65535 so that the filter
540 * doesn't truncate the packet, and supplying that modified
541 * filter to the kernel.
542 */
543
544 caplen = packet_len;
545 if (caplen > handle->snapshot)
546 caplen = handle->snapshot;
547
548 /* Run the packet filter if not using kernel filter */
549 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
550 if (bpf_filter(handle->fcode.bf_insns, bp,
551 packet_len, caplen) == 0)
552 {
553 /* rejected by filter */
554 return 0;
555 }
556 }
557
558 /* Fill in our own header data */
559
560 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
561 snprintf(handle->errbuf, sizeof(handle->errbuf),
562 "ioctl: %s", pcap_strerror(errno));
563 return -1;
564 }
565 pcap_header.caplen = caplen;
566 pcap_header.len = packet_len;
567
568 /*
569 * Count the packet.
570 *
571 * Arguably, we should count them before we check the filter,
572 * as on many other platforms "ps_recv" counts packets
573 * handed to the filter rather than packets that passed
574 * the filter, but if filtering is done in the kernel, we
575 * can't get a count of packets that passed the filter,
576 * and that would mean the meaning of "ps_recv" wouldn't
577 * be the same on all Linux systems.
578 *
579 * XXX - it's not the same on all systems in any case;
580 * ideally, we should have a "get the statistics" call
581 * that supplies more counts and indicates which of them
582 * it supplies, so that we supply a count of packets
583 * handed to the filter only on platforms where that
584 * information is available.
585 *
586 * We count them here even if we can get the packet count
587 * from the kernel, as we can only determine at run time
588 * whether we'll be able to get it from the kernel (if
589 * HAVE_TPACKET_STATS isn't defined, we can't get it from
590 * the kernel, but if it is defined, the library might
591 * have been built with a 2.4 or later kernel, but we
592 * might be running on a 2.2[.x] kernel without Alexey
593 * Kuznetzov's turbopacket patches, and thus the kernel
594 * might not be able to supply those statistics). We
595 * could, I guess, try, when opening the socket, to get
596 * the statistics, and if we can not increment the count
597 * here, but it's not clear that always incrementing
598 * the count is more expensive than always testing a flag
599 * in memory.
600 */
601 handle->md.stat.ps_recv++;
602
603 /* Call the user supplied callback function */
604 callback(userdata, &pcap_header, bp);
605
606 return 1;
607 }
608
609 /*
610 * Get the statistics for the given packet capture handle.
611 * Reports the number of dropped packets iff the kernel supports
612 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
613 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
614 * patches); otherwise, that information isn't available, and we lie
615 * and report 0 as the count of dropped packets.
616 */
617 int
618 pcap_stats(pcap_t *handle, struct pcap_stat *stats)
619 {
620 #ifdef HAVE_TPACKET_STATS
621 struct tpacket_stats kstats;
622 socklen_t len;
623
624 /*
625 * Try to get the packet counts from the kernel.
626 */
627 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
628 &kstats, &len) > -1) {
629 handle->md.stat.ps_recv = (kstats.tp_packets - kstats.tp_drops);
630 handle->md.stat.ps_drop = kstats.tp_drops;
631 }
632 #endif
633 /*
634 * "ps_recv" counts only packets that passed the filter.
635 *
636 * "ps_drop" is maintained only on systems that support
637 * the PACKET_STATISTICS "getsockopt()" argument.
638 */
639 *stats = handle->md.stat;
640 return 0;
641 }
642
643 /*
644 * Attach the given BPF code to the packet capture device.
645 */
646 int
647 pcap_setfilter(pcap_t *handle, struct bpf_program *filter)
648 {
649 #ifdef SO_ATTACH_FILTER
650 struct sock_fprog fcode;
651 int can_filter_in_kernel;
652 #endif
653
654 if (!handle)
655 return -1;
656 if (!filter) {
657 strncpy(handle->errbuf, "setfilter: No filter specified",
658 sizeof(handle->errbuf));
659 return -1;
660 }
661
662 /* Make our private copy of the filter */
663
664 if (install_bpf_program(handle, filter) < 0) {
665 snprintf(handle->errbuf, sizeof(handle->errbuf),
666 "malloc: %s", pcap_strerror(errno));
667 return -1;
668 }
669
670 /*
671 * Run user level packet filter by default. Will be overriden if
672 * installing a kernel filter succeeds.
673 */
674 handle->md.use_bpf = 0;
675
676 /*
677 * If we're reading from a savefile, don't try to install
678 * a kernel filter.
679 */
680 if (handle->sf.rfile != NULL)
681 return 0;
682
683 /* Install kernel level filter if possible */
684
685 #ifdef SO_ATTACH_FILTER
686 #ifdef USHRT_MAX
687 if (handle->fcode.bf_len > USHRT_MAX) {
688 /*
689 * fcode.len is an unsigned short for current kernel.
690 * I have yet to see BPF-Code with that much
691 * instructions but still it is possible. So for the
692 * sake of correctness I added this check.
693 */
694 fprintf(stderr, "Warning: Filter too complex for kernel\n");
695 fcode.filter = NULL;
696 can_filter_in_kernel = 0;
697 } else
698 #endif /* USHRT_MAX */
699 {
700 /*
701 * Oh joy, the Linux kernel uses struct sock_fprog instead
702 * of struct bpf_program and of course the length field is
703 * of different size. Pointed out by Sebastian
704 *
705 * Oh, and we also need to fix it up so that all "ret"
706 * instructions with non-zero operands have 65535 as the
707 * operand, and so that, if we're in cooked mode, all
708 * memory-reference instructions use special magic offsets
709 * in references to the link-layer header and assume that
710 * the link-layer payload begins at 0; "fix_program()"
711 * will do that.
712 */
713 switch (fix_program(handle, &fcode)) {
714
715 case -1:
716 default:
717 /*
718 * Fatal error; just quit.
719 * (The "default" case shouldn't happen; we
720 * return -1 for that reason.)
721 */
722 return -1;
723
724 case 0:
725 /*
726 * The program performed checks that we can't make
727 * work in the kernel.
728 */
729 can_filter_in_kernel = 0;
730 break;
731
732 case 1:
733 /*
734 * We have a filter that'll work in the kernel.
735 */
736 can_filter_in_kernel = 1;
737 break;
738 }
739 }
740
741 if (can_filter_in_kernel) {
742 if (set_kernel_filter(handle, &fcode) == 0)
743 {
744 /* Installation succeded - using kernel filter. */
745 handle->md.use_bpf = 1;
746 }
747 else
748 {
749 /*
750 * Print a warning if we weren't able to install
751 * the filter for a reason other than "this kernel
752 * isn't configured to support socket filters.
753 */
754 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
755 fprintf(stderr,
756 "Warning: Kernel filter failed: %s\n",
757 pcap_strerror(errno));
758 }
759 }
760 }
761
762 /*
763 * Free up the copy of the filter that was made by "fix_program()".
764 */
765 if (fcode.filter != NULL)
766 free(fcode.filter);
767 #endif /* SO_ATTACH_FILTER */
768
769 return 0;
770 }
771
772 /*
773 * Linux uses the ARP hardware type to identify the type of an
774 * interface. pcap uses the DLT_xxx constants for this. This
775 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
776 * constant, as arguments, and sets "handle->linktype" to the
777 * appropriate DLT_XXX constant and sets "handle->offset" to
778 * the appropriate value (to make "handle->offset" plus link-layer
779 * header length be a multiple of 4, so that the link-layer payload
780 * will be aligned on a 4-byte boundary when capturing packets).
781 * (If the offset isn't set here, it'll be 0; add code as appropriate
782 * for cases where it shouldn't be 0.)
783 *
784 * Returns -1 if unable to map the type; we print a message and,
785 * if we're using PF_PACKET/SOCK_RAW rather than PF_INET/SOCK_PACKET,
786 * we fall back on using PF_PACKET/SOCK_DGRAM.
787 */
788 static int map_arphrd_to_dlt(pcap_t *handle, int arptype)
789 {
790 switch (arptype) {
791
792 case ARPHRD_ETHER:
793 case ARPHRD_METRICOM:
794 case ARPHRD_LOOPBACK:
795 handle->linktype = DLT_EN10MB;
796 handle->offset = 2;
797 break;
798
799 case ARPHRD_EETHER:
800 handle->linktype = DLT_EN3MB;
801 break;
802
803 case ARPHRD_AX25:
804 handle->linktype = DLT_AX25;
805 break;
806
807 case ARPHRD_PRONET:
808 handle->linktype = DLT_PRONET;
809 break;
810
811 case ARPHRD_CHAOS:
812 handle->linktype = DLT_CHAOS;
813 break;
814
815 #ifndef ARPHRD_IEEE802_TR
816 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
817 #endif
818 case ARPHRD_IEEE802_TR:
819 case ARPHRD_IEEE802:
820 handle->linktype = DLT_IEEE802;
821 handle->offset = 2;
822 break;
823
824 case ARPHRD_ARCNET:
825 handle->linktype = DLT_ARCNET;
826 break;
827
828 case ARPHRD_FDDI:
829 handle->linktype = DLT_FDDI;
830 handle->offset = 3;
831 break;
832
833 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
834 #define ARPHRD_ATM 19
835 #endif
836 case ARPHRD_ATM:
837 handle->linktype = DLT_ATM_CLIP;
838 break;
839
840 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
841 #define ARPHRD_IEEE80211 801
842 #endif
843 case ARPHRD_IEEE80211:
844 handle->linktype = DLT_IEEE802_11;
845 break;
846
847 case ARPHRD_PPP:
848 /*
849 * Some PPP code in the kernel supplies no link-layer
850 * header whatsoever to PF_PACKET sockets; other PPP
851 * code supplies PPP link-layer headers ("syncppp.c");
852 * some PPP code might supply random link-layer
853 * headers (PPP over ISDN - there's code in Ethereal,
854 * for example, to cope with PPP-over-ISDN captures
855 * with which the Ethereal developers have had to cope,
856 * heuristically trying to determine which of the
857 * oddball link-layer headers particular packets have).
858 *
859 * As such, we just punt, and run all PPP interfaces
860 * in cooked mode.
861 */
862 handle->linktype = DLT_LINUX_SLL;
863 break;
864
865 case ARPHRD_HDLC:
866 handle->linktype = DLT_C_HDLC;
867 break;
868
869 /* Not sure if this is correct for all tunnels, but it
870 * works for CIPE */
871 case ARPHRD_TUNNEL:
872 #ifndef ARPHRD_SIT
873 #define ARPHRD_SIT 776 /* From Linux 2.2.14 */
874 #endif
875 case ARPHRD_SIT:
876 case ARPHRD_CSLIP:
877 case ARPHRD_SLIP6:
878 case ARPHRD_CSLIP6:
879 case ARPHRD_ADAPT:
880 case ARPHRD_SLIP:
881 /*
882 * XXX - should some of those be mapped to DLT_LINUX_SLL
883 * instead? Should we just map all of them to DLT_LINUX_SLL?
884 */
885 handle->linktype = DLT_RAW;
886 break;
887
888 case ARPHRD_LOCALTLK:
889 handle->linktype = DLT_LTALK;
890 break;
891
892 default:
893 return -1;
894 }
895 return 0;
896 }
897
898 /* ===== Functions to interface to the newer kernels ================== */
899
900 /*
901 * Try to open a packet socket using the new kernel interface.
902 * Returns 0 on failure.
903 * FIXME: 0 uses to mean success (Sebastian)
904 */
905 static int
906 live_open_new(pcap_t *handle, char *device, int promisc,
907 int to_ms, char *ebuf)
908 {
909 #ifdef HAVE_PF_PACKET_SOCKETS
910 int sock_fd = -1, device_id, arptype;
911 struct packet_mreq mr;
912
913 /* One shot loop used for error handling - bail out with break */
914
915 do {
916 /*
917 * Open a socket with protocol family packet. If a device is
918 * given we try to open it in raw mode otherwise we use
919 * the cooked interface.
920 */
921 sock_fd = device ?
922 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
923 : socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
924
925 if (sock_fd == -1) {
926 snprintf(ebuf, PCAP_ERRBUF_SIZE, "socket: %s",
927 pcap_strerror(errno) );
928 break;
929 }
930
931 /* It seems the kernel supports the new interface. */
932 handle->md.sock_packet = 0;
933
934 /*
935 * Get the interface index of the loopback device.
936 * If the attempt fails, don't fail, just set the
937 * "md.lo_ifindex" to -1.
938 *
939 * XXX - can there be more than one device that loops
940 * packets back, i.e. devices other than "lo"? If so,
941 * we'd need to find them all, and have an array of
942 * indices for them, and check all of them in
943 * "pcap_read_packet()".
944 */
945 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", ebuf);
946
947 /*
948 * Default value for offset to align link-layer payload
949 * on a 4-byte boundary.
950 */
951 handle->offset = 0;
952
953 /*
954 * What kind of frames do we have to deal with? Fall back
955 * to cooked mode if we have an unknown interface type.
956 */
957
958 if (device) {
959 /* Assume for now we don't need cooked mode. */
960 handle->md.cooked = 0;
961
962 arptype = iface_get_arptype(sock_fd, device, ebuf);
963 if (arptype == -1)
964 break;
965 if (map_arphrd_to_dlt(handle, arptype) == -1 ||
966 handle->linktype == DLT_LINUX_SLL ||
967 (handle->linktype == DLT_EN10MB &&
968 (strncmp("isdn", device, 4) == 0 ||
969 strncmp("isdY", device, 4) == 0))) {
970 /*
971 * Unknown interface type (-1), or a
972 * device we explicitly chose to run
973 * in cooked mode (e.g., PPP devices),
974 * or an ISDN device (whose link-layer
975 * type we can only determine by using
976 * APIs that may be different on different
977 * kernels) - reopen in cooked mode.
978 */
979 if (close(sock_fd) == -1) {
980 snprintf(ebuf, PCAP_ERRBUF_SIZE,
981 "close: %s", pcap_strerror(errno));
982 break;
983 }
984 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
985 htons(ETH_P_ALL));
986 if (sock_fd == -1) {
987 snprintf(ebuf, PCAP_ERRBUF_SIZE,
988 "socket: %s", pcap_strerror(errno));
989 break;
990 }
991 handle->md.cooked = 1;
992
993 if (handle->linktype == -1) {
994 /*
995 * Warn that we're falling back on
996 * cooked mode; we may want to
997 * update "map_arphrd_to_dlt()"
998 * to handle the new type.
999 */
1000 fprintf(stderr,
1001 "Warning: arptype %d not "
1002 "supported by libpcap - "
1003 "falling back to cooked "
1004 "socket\n",
1005 arptype);
1006 }
1007 handle->linktype = DLT_LINUX_SLL;
1008 }
1009
1010 device_id = iface_get_id(sock_fd, device, ebuf);
1011 if (device_id == -1)
1012 break;
1013
1014 if (iface_bind(sock_fd, device_id, ebuf) == -1)
1015 break;
1016 } else {
1017 /*
1018 * This is cooked mode.
1019 */
1020 handle->md.cooked = 1;
1021 handle->linktype = DLT_LINUX_SLL;
1022
1023 /*
1024 * XXX - squelch GCC complaints about
1025 * uninitialized variables; if we can't
1026 * select promiscuous mode on all interfaces,
1027 * we should move the code below into the
1028 * "if (device)" branch of the "if" and
1029 * get rid of the next statement.
1030 */
1031 device_id = -1;
1032 }
1033
1034 /* Select promiscuous mode on/off */
1035
1036 #ifdef SOL_PACKET
1037 /*
1038 * Hmm, how can we set promiscuous mode on all interfaces?
1039 * I am not sure if that is possible at all.
1040 */
1041
1042 if (device) {
1043 memset(&mr, 0, sizeof(mr));
1044 mr.mr_ifindex = device_id;
1045 mr.mr_type = promisc ?
1046 PACKET_MR_PROMISC : PACKET_MR_ALLMULTI;
1047 if (setsockopt(sock_fd, SOL_PACKET,
1048 PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == -1)
1049 {
1050 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1051 "setsockopt: %s", pcap_strerror(errno));
1052 break;
1053 }
1054 }
1055 #endif
1056
1057 /* Save the socket FD in the pcap structure */
1058
1059 handle->fd = sock_fd;
1060
1061 return 1;
1062
1063 } while(0);
1064
1065 if (sock_fd != -1)
1066 close(sock_fd);
1067 return 0;
1068 #else
1069 strncpy(ebuf,
1070 "New packet capturing interface not supported by build "
1071 "environment", PCAP_ERRBUF_SIZE);
1072 return 0;
1073 #endif
1074 }
1075
1076 #ifdef HAVE_PF_PACKET_SOCKETS
1077 /*
1078 * Return the index of the given device name. Fill ebuf and return
1079 * -1 on failure.
1080 */
1081 static int
1082 iface_get_id(int fd, const char *device, char *ebuf)
1083 {
1084 struct ifreq ifr;
1085
1086 memset(&ifr, 0, sizeof(ifr));
1087 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1088
1089 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
1090 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1091 "ioctl: %s", pcap_strerror(errno));
1092 return -1;
1093 }
1094
1095 return ifr.ifr_ifindex;
1096 }
1097
1098 /*
1099 * Bind the socket associated with FD to the given device.
1100 */
1101 static int
1102 iface_bind(int fd, int ifindex, char *ebuf)
1103 {
1104 struct sockaddr_ll sll;
1105
1106 memset(&sll, 0, sizeof(sll));
1107 sll.sll_family = AF_PACKET;
1108 sll.sll_ifindex = ifindex;
1109 sll.sll_protocol = htons(ETH_P_ALL);
1110
1111 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
1112 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1113 "bind: %s", pcap_strerror(errno));
1114 return -1;
1115 }
1116
1117 return 0;
1118 }
1119
1120 #endif
1121
1122
1123 /* ===== Functions to interface to the older kernels ================== */
1124
1125 /*
1126 * With older kernels promiscuous mode is kind of interesting because we
1127 * have to reset the interface before exiting. The problem can't really
1128 * be solved without some daemon taking care of managing usage counts.
1129 * If we put the interface into promiscuous mode, we set a flag indicating
1130 * that we must take it out of that mode when the interface is closed,
1131 * and, when closing the interface, if that flag is set we take it out
1132 * of promiscuous mode.
1133 */
1134
1135 /*
1136 * List of pcaps for which we turned promiscuous mode on by hand.
1137 * If there are any such pcaps, we arrange to call "pcap_close_all()"
1138 * when we exit, and have it close all of them to turn promiscuous mode
1139 * off.
1140 */
1141 static struct pcap *pcaps_to_close;
1142
1143 /*
1144 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1145 * be called on exit.
1146 */
1147 static int did_atexit;
1148
1149 static void pcap_close_all(void)
1150 {
1151 struct pcap *handle;
1152
1153 while ((handle = pcaps_to_close) != NULL)
1154 pcap_close(handle);
1155 }
1156
1157 void pcap_close_linux( pcap_t *handle )
1158 {
1159 struct pcap *p, *prevp;
1160 struct ifreq ifr;
1161
1162 if (handle->md.clear_promisc) {
1163 /*
1164 * We put the interface into promiscuous mode; take
1165 * it out of promiscuous mode.
1166 *
1167 * XXX - if somebody else wants it in promiscuous mode,
1168 * this code cannot know that, so it'll take it out
1169 * of promiscuous mode. That's not fixable in 2.0[.x]
1170 * kernels.
1171 */
1172 memset(&ifr, 0, sizeof(ifr));
1173 strncpy(ifr.ifr_name, handle->md.device, sizeof(ifr.ifr_name));
1174 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1175 fprintf(stderr,
1176 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
1177 "Please adjust manually.\n"
1178 "Hint: This can't happen with Linux >= 2.2.0.\n",
1179 strerror(errno));
1180 } else {
1181 if (ifr.ifr_flags & IFF_PROMISC) {
1182 /*
1183 * Promiscuous mode is currently on; turn it
1184 * off.
1185 */
1186 ifr.ifr_flags &= ~IFF_PROMISC;
1187 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1188 fprintf(stderr,
1189 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
1190 "Please adjust manually.\n"
1191 "Hint: This can't happen with Linux >= 2.2.0.\n",
1192 strerror(errno));
1193 }
1194 }
1195 }
1196
1197 /*
1198 * Take this pcap out of the list of pcaps for which we
1199 * have to take the interface out of promiscuous mode.
1200 */
1201 for (p = pcaps_to_close, prevp = NULL; p != NULL;
1202 prevp = p, p = p->md.next) {
1203 if (p == handle) {
1204 /*
1205 * Found it. Remove it from the list.
1206 */
1207 if (prevp == NULL) {
1208 /*
1209 * It was at the head of the list.
1210 */
1211 pcaps_to_close = p->md.next;
1212 } else {
1213 /*
1214 * It was in the middle of the list.
1215 */
1216 prevp->md.next = p->md.next;
1217 }
1218 break;
1219 }
1220 }
1221 }
1222 if (handle->md.device != NULL)
1223 free(handle->md.device);
1224 }
1225
1226 /*
1227 * Try to open a packet socket using the old kernel interface.
1228 * Returns 0 on failure.
1229 * FIXME: 0 uses to mean success (Sebastian)
1230 */
1231 static int
1232 live_open_old(pcap_t *handle, char *device, int promisc,
1233 int to_ms, char *ebuf)
1234 {
1235 int sock_fd = -1, arptype;
1236 struct ifreq ifr;
1237
1238 do {
1239 /* Open the socket */
1240
1241 sock_fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
1242 if (sock_fd == -1) {
1243 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1244 "socket: %s", pcap_strerror(errno));
1245 break;
1246 }
1247
1248 /* It worked - we are using the old interface */
1249 handle->md.sock_packet = 1;
1250
1251 /* ...which means we get the link-layer header. */
1252 handle->md.cooked = 0;
1253
1254 /* Bind to the given device */
1255
1256 if (!device) {
1257 strncpy(ebuf, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
1258 PCAP_ERRBUF_SIZE);
1259 break;
1260 }
1261 if (iface_bind_old(sock_fd, device, ebuf) == -1)
1262 break;
1263
1264 /* Go to promisc mode */
1265 if (promisc) {
1266 memset(&ifr, 0, sizeof(ifr));
1267 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1268 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
1269 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1270 "ioctl: %s", pcap_strerror(errno));
1271 break;
1272 }
1273 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
1274 /*
1275 * Promiscuous mode isn't currently on,
1276 * so turn it on, and remember that
1277 * we should turn it off when the
1278 * pcap_t is closed.
1279 */
1280
1281 /*
1282 * If we haven't already done so, arrange
1283 * to have "pcap_close_all()" called when
1284 * we exit.
1285 */
1286 if (!did_atexit) {
1287 if (atexit(pcap_close_all) == -1) {
1288 /*
1289 * "atexit()" failed; don't
1290 * put the interface in
1291 * promiscuous mode, just
1292 * give up.
1293 */
1294 strncpy(ebuf, "atexit failed",
1295 PCAP_ERRBUF_SIZE);
1296 break;
1297 }
1298 }
1299
1300 ifr.ifr_flags |= IFF_PROMISC;
1301 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
1302 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1303 "ioctl: %s",
1304 pcap_strerror(errno));
1305 break;
1306 }
1307 handle->md.clear_promisc = 1;
1308
1309 /*
1310 * Add this to the list of pcaps
1311 * to close when we exit.
1312 */
1313 handle->md.next = pcaps_to_close;
1314 pcaps_to_close = handle;
1315 }
1316 }
1317
1318 /* All done - fill in the pcap handle */
1319
1320 arptype = iface_get_arptype(sock_fd, device, ebuf);
1321 if (arptype == -1)
1322 break;
1323
1324 /* Save the socket FD in the pcap structure */
1325
1326 handle->fd = sock_fd;
1327
1328 /*
1329 * Default value for offset to align link-layer payload
1330 * on a 4-byte boundary.
1331 */
1332 handle->offset = 0;
1333
1334 /*
1335 * XXX - handle ISDN types here? We can't fall back on
1336 * cooked sockets, so we'd have to figure out from the
1337 * device name what type of link-layer encapsulation
1338 * it's using, and map that to an appropriate DLT_
1339 * value, meaning we'd map "isdnN" devices to DLT_RAW
1340 * (they supply raw IP packets with no link-layer
1341 * header) and "isdY" devices to a new DLT_I4L_IP
1342 * type that has only an Ethernet packet type as
1343 * a link-layer header.
1344 */
1345 if (map_arphrd_to_dlt(handle, arptype) == -1) {
1346 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1347 "interface type of %s not supported", device);
1348 break;
1349 }
1350
1351 return 1;
1352
1353 } while (0);
1354
1355 if (sock_fd != -1)
1356 close(sock_fd);
1357 return 0;
1358 }
1359
1360 /*
1361 * Bind the socket associated with FD to the given device using the
1362 * interface of the old kernels.
1363 */
1364 static int
1365 iface_bind_old(int fd, const char *device, char *ebuf)
1366 {
1367 struct sockaddr saddr;
1368
1369 memset(&saddr, 0, sizeof(saddr));
1370 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
1371 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
1372 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1373 "bind: %s", pcap_strerror(errno));
1374 return -1;
1375 }
1376
1377 return 0;
1378 }
1379
1380
1381 /* ===== System calls available on all supported kernels ============== */
1382
1383 /*
1384 * Query the kernel for the MTU of the given interface.
1385 */
1386 static int
1387 iface_get_mtu(int fd, const char *device, char *ebuf)
1388 {
1389 struct ifreq ifr;
1390
1391 if (!device)
1392 return BIGGER_THAN_ALL_MTUS;
1393
1394 memset(&ifr, 0, sizeof(ifr));
1395 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1396
1397 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
1398 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1399 "ioctl: %s", pcap_strerror(errno));
1400 return -1;
1401 }
1402
1403 return ifr.ifr_mtu;
1404 }
1405
1406 /*
1407 * Get the hardware type of the given interface as ARPHRD_xxx constant.
1408 */
1409 static int
1410 iface_get_arptype(int fd, const char *device, char *ebuf)
1411 {
1412 struct ifreq ifr;
1413
1414 memset(&ifr, 0, sizeof(ifr));
1415 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1416
1417 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
1418 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1419 "ioctl: %s", pcap_strerror(errno));
1420 return -1;
1421 }
1422
1423 return ifr.ifr_hwaddr.sa_family;
1424 }
1425
1426 #ifdef SO_ATTACH_FILTER
1427 static int
1428 fix_program(pcap_t *handle, struct sock_fprog *fcode)
1429 {
1430 size_t prog_size;
1431 register int i;
1432 register struct bpf_insn *p;
1433 struct bpf_insn *f;
1434 int len;
1435
1436 /*
1437 * Make a copy of the filter, and modify that copy if
1438 * necessary.
1439 */
1440 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
1441 len = handle->fcode.bf_len;
1442 f = (struct bpf_insn *)malloc(prog_size);
1443 if (f == NULL) {
1444 snprintf(handle->errbuf, sizeof(handle->errbuf),
1445 "malloc: %s", pcap_strerror(errno));
1446 return -1;
1447 }
1448 memcpy(f, handle->fcode.bf_insns, prog_size);
1449 fcode->len = len;
1450 fcode->filter = (struct sock_filter *) f;
1451
1452 for (i = 0; i < len; ++i) {
1453 p = &f[i];
1454 /*
1455 * What type of instruction is this?
1456 */
1457 switch (BPF_CLASS(p->code)) {
1458
1459 case BPF_RET:
1460 /*
1461 * It's a return instruction; is the snapshot
1462 * length a constant, rather than the contents
1463 * of the accumulator?
1464 */
1465 if (BPF_MODE(p->code) == BPF_K) {
1466 /*
1467 * Yes - if the value to be returned,
1468 * i.e. the snapshot length, is anything
1469 * other than 0, make it 65535, so that
1470 * the packet is truncated by "recvfrom()",
1471 * not by the filter.
1472 *
1473 * XXX - there's nothing we can easily do
1474 * if it's getting the value from the
1475 * accumulator; we'd have to insert
1476 * code to force non-zero values to be
1477 * 65535.
1478 */
1479 if (p->k != 0)
1480 p->k = 65535;
1481 }
1482 break;
1483
1484 case BPF_LD:
1485 case BPF_LDX:
1486 /*
1487 * It's a load instruction; is it loading
1488 * from the packet?
1489 */
1490 switch (BPF_MODE(p->code)) {
1491
1492 case BPF_ABS:
1493 case BPF_IND:
1494 case BPF_MSH:
1495 /*
1496 * Yes; are we in cooked mode?
1497 */
1498 if (handle->md.cooked) {
1499 /*
1500 * Yes, so we need to fix this
1501 * instruction.
1502 */
1503 if (fix_offset(p) < 0) {
1504 /*
1505 * We failed to do so.
1506 * Return 0, so our caller
1507 * knows to punt to userland.
1508 */
1509 return 0;
1510 }
1511 }
1512 break;
1513 }
1514 break;
1515 }
1516 }
1517 return 1; /* we succeeded */
1518 }
1519
1520 static int
1521 fix_offset(struct bpf_insn *p)
1522 {
1523 /*
1524 * What's the offset?
1525 */
1526 if (p->k >= SLL_HDR_LEN) {
1527 /*
1528 * It's within the link-layer payload; that starts at an
1529 * offset of 0, as far as the kernel packet filter is
1530 * concerned, so subtract the length of the link-layer
1531 * header.
1532 */
1533 p->k -= SLL_HDR_LEN;
1534 } else if (p->k == 14) {
1535 /*
1536 * It's the protocol field; map it to the special magic
1537 * kernel offset for that field.
1538 */
1539 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
1540 } else {
1541 /*
1542 * It's within the header, but it's not one of those
1543 * fields; we can't do that in the kernel, so punt
1544 * to userland.
1545 */
1546 return -1;
1547 }
1548 return 0;
1549 }
1550
1551 static int
1552 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
1553 {
1554 int total_filter_on = 0;
1555 int save_mode;
1556 int ret;
1557 int save_errno;
1558 /* setsockopt() barfs unless it get a dummy parameter */
1559 int dummy;
1560
1561 /*
1562 * The socket filter code doesn't discard all packets queued
1563 * up on the socket when the filter is changed; this means
1564 * that packets that don't match the new filter may show up
1565 * after the new filter is put onto the socket, if those
1566 * packets haven't yet been read.
1567 *
1568 * This means, for example, that if you do a tcpdump capture
1569 * with a filter, the first few packets in the capture might
1570 * be packets that wouldn't have passed the filter.
1571 *
1572 * We therefore discard all packets queued up on the socket
1573 * when setting a kernel filter. (This isn't an issue for
1574 * userland filters, as the userland filtering is done after
1575 * packets are queued up.)
1576 *
1577 * To flush those packets, we put the socket in read-only mode,
1578 * and read packets from the socket until there are no more to
1579 * read.
1580 *
1581 * In order to keep that from being an infinite loop - i.e.,
1582 * to keep more packets from arriving while we're draining
1583 * the queue - we put the "total filter", which is a filter
1584 * that rejects all packets, onto the socket before draining
1585 * the queue.
1586 *
1587 * This code deliberately ignores any errors, so that you may
1588 * get bogus packets if an error occurs, rather than having
1589 * the filtering done in userland even if it could have been
1590 * done in the kernel.
1591 */
1592 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
1593 &total_fcode, sizeof(total_fcode)) == 0) {
1594 char drain[1];
1595
1596 /*
1597 * Note that we've put the total socket onto the filter.
1598 */
1599 total_filter_on = 1;
1600
1601 /*
1602 * Save the socket's current mode, and put it in
1603 * non-blocking mode; we drain it by reading packets
1604 * until we get an error (which we assume is a
1605 * "nothing more to be read" error).
1606 */
1607 save_mode = fcntl(handle->fd, F_GETFL, 0);
1608 if (save_mode != -1 &&
1609 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
1610 while (recv(handle->fd, &drain, sizeof drain,
1611 MSG_TRUNC) >= 0)
1612 ;
1613 fcntl(handle->fd, F_SETFL, save_mode);
1614 }
1615 }
1616
1617 /*
1618 * Now attach the new filter.
1619 */
1620 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
1621 fcode, sizeof(*fcode));
1622 if (ret == -1 && total_filter_on) {
1623 /*
1624 * Well, we couldn't set that filter on the socket,
1625 * but we could set the total filter on the socket.
1626 *
1627 * This could, for example, mean that the filter was
1628 * too big to put into the kernel, so we'll have to
1629 * filter in userland; in any case, we'll be doing
1630 * filtering in userland, so we need to remove the
1631 * total filter so we see packets.
1632 */
1633 save_errno = errno;
1634
1635 /*
1636 * XXX - if this fails, we're really screwed;
1637 * we have the total filter on the socket,
1638 * and it won't come off. What do we do then?
1639 */
1640 setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
1641 &dummy, sizeof(dummy));
1642 errno = save_errno;
1643 }
1644 return ret;
1645 }
1646 #endif