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