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