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