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