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