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