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