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