]> The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
From Paolo Abeni: support for a memory-mapped capture buffer.
[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 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
29 *
30 * based on previous works of:
31 * Simon Patarin <patarin@cs.unibo.it>
32 * Phil Wood <cpw@lanl.gov>
33 */
34
35 #ifndef lint
36 static const char rcsid[] _U_ =
37 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.132 2008-01-05 22:32:31 guy Exp $ (LBL)";
38 #endif
39
40 /*
41 * Known problems with 2.0[.x] kernels:
42 *
43 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
44 * if we use PF_PACKET, we can filter out the transmitted version
45 * of the packet by using data in the "sockaddr_ll" returned by
46 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
47 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
48 * "sockaddr_pkt" which doesn't give us enough information to let
49 * us do that.
50 *
51 * - We have to set the interface's IFF_PROMISC flag ourselves, if
52 * we're to run in promiscuous mode, which means we have to turn
53 * it off ourselves when we're done; the kernel doesn't keep track
54 * of how many sockets are listening promiscuously, which means
55 * it won't get turned off automatically when no sockets are
56 * listening promiscuously. We catch "pcap_close()" and, for
57 * interfaces we put into promiscuous mode, take them out of
58 * promiscuous mode - which isn't necessarily the right thing to
59 * do, if another socket also requested promiscuous mode between
60 * the time when we opened the socket and the time when we close
61 * the socket.
62 *
63 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
64 * return the amount of data that you could have read, rather than
65 * the amount that was returned, so we can't just allocate a buffer
66 * whose size is the snapshot length and pass the snapshot length
67 * as the byte count, and also pass MSG_TRUNC, so that the return
68 * value tells us how long the packet was on the wire.
69 *
70 * This means that, if we want to get the actual size of the packet,
71 * so we can return it in the "len" field of the packet header,
72 * we have to read the entire packet, not just the part that fits
73 * within the snapshot length, and thus waste CPU time copying data
74 * from the kernel that our caller won't see.
75 *
76 * We have to get the actual size, and supply it in "len", because
77 * otherwise, the IP dissector in tcpdump, for example, will complain
78 * about "truncated-ip", as the packet will appear to have been
79 * shorter, on the wire, than the IP header said it should have been.
80 */
81
82
83 #ifdef HAVE_CONFIG_H
84 #include "config.h"
85 #endif
86
87 #include "pcap-int.h"
88 #include "pcap/sll.h"
89
90 #ifdef HAVE_DAG_API
91 #include "pcap-dag.h"
92 #endif /* HAVE_DAG_API */
93
94 #ifdef HAVE_SEPTEL_API
95 #include "pcap-septel.h"
96 #endif /* HAVE_SEPTEL_API */
97
98 #ifdef PCAP_SUPPORT_USB
99 #include "pcap-usb-linux.h"
100 #endif
101
102 #ifdef PCAP_SUPPORT_BT
103 #include "pcap-bt-linux.h"
104 #endif
105
106 #ifdef SITA
107 #include "pcap-sita.h"
108 #endif
109
110 #include <errno.h>
111 #include <stdlib.h>
112 #include <unistd.h>
113 #include <fcntl.h>
114 #include <string.h>
115 #include <sys/socket.h>
116 #include <sys/ioctl.h>
117 #include <sys/utsname.h>
118 #include <sys/mman.h>
119 #include <net/if.h>
120 #include <netinet/in.h>
121 #include <linux/if_ether.h>
122 #include <net/if_arp.h>
123 #include <poll.h>
124
125 /*
126 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
127 * sockets rather than SOCK_PACKET sockets.
128 *
129 * To use them, we include <linux/if_packet.h> rather than
130 * <netpacket/packet.h>; we do so because
131 *
132 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
133 * later kernels and libc5, and don't provide a <netpacket/packet.h>
134 * file;
135 *
136 * not all versions of glibc2 have a <netpacket/packet.h> file
137 * that defines stuff needed for some of the 2.4-or-later-kernel
138 * features, so if the system has a 2.4 or later kernel, we
139 * still can't use those features.
140 *
141 * We're already including a number of other <linux/XXX.h> headers, and
142 * this code is Linux-specific (no other OS has PF_PACKET sockets as
143 * a raw packet capture mechanism), so it's not as if you gain any
144 * useful portability by using <netpacket/packet.h>
145 *
146 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
147 * isn't defined? It only defines one data structure in 2.0.x, so
148 * it shouldn't cause any problems.
149 */
150 #ifdef PF_PACKET
151 # include <linux/if_packet.h>
152
153 /*
154 * On at least some Linux distributions (for example, Red Hat 5.2),
155 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
156 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
157 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
158 * the PACKET_xxx stuff.
159 *
160 * So we check whether PACKET_HOST is defined, and assume that we have
161 * PF_PACKET sockets only if it is defined.
162 */
163 # ifdef PACKET_HOST
164 # define HAVE_PF_PACKET_SOCKETS
165 # endif /* PACKET_HOST */
166
167
168 /* check for memory mapped access avaibility. We assume every needed
169 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
170 * uses many ring related structs and macros */
171 # ifdef TPACKET_HDRLEN
172 # define HAVE_PACKET_RING
173 # endif /* TPACKET_HDRLEN */
174 #endif /* PF_PACKET */
175
176 #ifdef SO_ATTACH_FILTER
177 #include <linux/types.h>
178 #include <linux/filter.h>
179 #endif
180
181 #ifndef __GLIBC__
182 typedef int socklen_t;
183 #endif
184
185 #ifndef MSG_TRUNC
186 /*
187 * This is being compiled on a system that lacks MSG_TRUNC; define it
188 * with the value it has in the 2.2 and later kernels, so that, on
189 * those kernels, when we pass it in the flags argument to "recvfrom()"
190 * we're passing the right value and thus get the MSG_TRUNC behavior
191 * we want. (We don't get that behavior on 2.0[.x] kernels, because
192 * they didn't support MSG_TRUNC.)
193 */
194 #define MSG_TRUNC 0x20
195 #endif
196
197 #ifndef SOL_PACKET
198 /*
199 * This is being compiled on a system that lacks SOL_PACKET; define it
200 * with the value it has in the 2.2 and later kernels, so that we can
201 * set promiscuous mode in the good modern way rather than the old
202 * 2.0-kernel crappy way.
203 */
204 #define SOL_PACKET 263
205 #endif
206
207 #define MAX_LINKHEADER_SIZE 256
208
209 /*
210 * When capturing on all interfaces we use this as the buffer size.
211 * Should be bigger then all MTUs that occur in real life.
212 * 64kB should be enough for now.
213 */
214 #define BIGGER_THAN_ALL_MTUS (64*1024)
215
216 /*
217 * Prototypes for internal functions
218 */
219 static void map_arphrd_to_dlt(pcap_t *, int, int);
220 static short int map_packet_type_to_sll_type(short int);
221 static int live_open_old(pcap_t *, const char *, int, int, char *);
222 static int live_open_new(pcap_t *, const char *, int, int, char *);
223 static int live_open_mmap(pcap_t *, char *);
224 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
225 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
226 static int pcap_inject_linux(pcap_t *, const void *, size_t);
227 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
228 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
229 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
230 static void pcap_close_linux(pcap_t *);
231
232 #ifdef HAVE_PACKET_RING
233 #define RING_GET_FRAME(h) (((struct tpacket_hdr**)h->buffer)[handle->offset])
234
235 static void destroy_ring(pcap_t *handle);
236 static int create_ring(pcap_t* handle, unsigned size, char* errmsg);
237 static void pcap_close_linux_mmap(pcap_t *);
238 static int pcap_read_linux_mmap(pcap_t *, int, pcap_handler , u_char *);
239 static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
240 static int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
241 static int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
242 #endif
243
244 /*
245 * Wrap some ioctl calls
246 */
247 #ifdef HAVE_PF_PACKET_SOCKETS
248 static int iface_get_id(int fd, const char *device, char *ebuf);
249 #endif
250 static int iface_get_mtu(int fd, const char *device, char *ebuf);
251 static int iface_get_arptype(int fd, const char *device, char *ebuf);
252 #ifdef HAVE_PF_PACKET_SOCKETS
253 static int iface_bind(int fd, int ifindex, char *ebuf);
254 #endif
255 static int iface_bind_old(int fd, const char *device, char *ebuf);
256
257 #ifdef SO_ATTACH_FILTER
258 static int fix_program(pcap_t *handle, struct sock_fprog *fcode);
259 static int fix_offset(struct bpf_insn *p);
260 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
261 static int reset_kernel_filter(pcap_t *handle);
262
263 static struct sock_filter total_insn
264 = BPF_STMT(BPF_RET | BPF_K, 0);
265 static struct sock_fprog total_fcode
266 = { 1, &total_insn };
267 #endif
268
269 /*
270 * Get a handle for a live capture from the given device. You can
271 * pass NULL as device to get all packages (without link level
272 * information of course). If you pass 1 as promisc the interface
273 * will be set to promiscous mode (XXX: I think this usage should
274 * be deprecated and functions be added to select that later allow
275 * modification of that values -- Torsten).
276 *
277 * See also pcap(3).
278 */
279 pcap_t *
280 pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
281 char *ebuf)
282 {
283 pcap_t *handle;
284 int mtu;
285 int err;
286 int live_open_ok = 0;
287 struct utsname utsname;
288
289 #ifdef HAVE_DAG_API
290 if (strstr(device, "dag")) {
291 return dag_open_live(device, snaplen, promisc, to_ms, ebuf);
292 }
293 #endif /* HAVE_DAG_API */
294
295 #ifdef HAVE_SEPTEL_API
296 if (strstr(device, "septel")) {
297 return septel_open_live(device, snaplen, promisc, to_ms, ebuf);
298 }
299 #endif /* HAVE_SEPTEL_API */
300
301 #ifdef PCAP_SUPPORT_BT
302 if (strstr(device, "bluetooth")) {
303 return bt_open_live(device, snaplen, promisc, to_ms, ebuf);
304 }
305 #endif
306
307 #ifdef PCAP_SUPPORT_USB
308 if (strstr(device, "usb")) {
309 return usb_open_live(device, snaplen, promisc, to_ms, ebuf);
310 }
311 #endif
312
313 /* Allocate a handle for this session. */
314
315 handle = malloc(sizeof(*handle));
316 if (handle == NULL) {
317 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
318 pcap_strerror(errno));
319 return NULL;
320 }
321
322 /* Initialize some components of the pcap structure. */
323
324 memset(handle, 0, sizeof(*handle));
325 handle->snapshot = snaplen;
326 handle->md.timeout = to_ms;
327
328 handle->inject_op = pcap_inject_linux;
329 handle->setfilter_op = pcap_setfilter_linux;
330 handle->setdirection_op = pcap_setdirection_linux;
331 handle->set_datalink_op = NULL; /* can't change data link type */
332 handle->getnonblock_op = pcap_getnonblock_fd;
333 handle->setnonblock_op = pcap_setnonblock_fd;
334 handle->close_op = pcap_close_linux;
335
336 #ifdef SITA
337 handle->read_op = pcap_read_acn;
338 handle->stats_op = pcap_stats_acn;
339 #else
340 handle->read_op = pcap_read_linux;
341 handle->stats_op = pcap_stats_linux;
342 #endif
343
344 /*
345 * NULL and "any" are special devices which give us the hint to
346 * monitor all devices.
347 */
348 if (!device || strcmp(device, "any") == 0) {
349 device = NULL;
350 handle->md.device = strdup("any");
351 if (promisc) {
352 promisc = 0;
353 /* Just a warning. */
354 snprintf(ebuf, PCAP_ERRBUF_SIZE,
355 "Promiscuous mode not supported on the \"any\" device");
356 }
357
358 } else
359 handle->md.device = strdup(device);
360
361 if (handle->md.device == NULL) {
362 snprintf(ebuf, PCAP_ERRBUF_SIZE, "strdup: %s",
363 pcap_strerror(errno) );
364 free(handle);
365 return NULL;
366 }
367
368 /*
369 * Current Linux kernels use the protocol family PF_PACKET to
370 * allow direct access to all packets on the network while
371 * older kernels had a special socket type SOCK_PACKET to
372 * implement this feature.
373 * While this old implementation is kind of obsolete we need
374 * to be compatible with older kernels for a while so we are
375 * trying both methods with the newer method preferred.
376 */
377
378 #ifdef SITA
379 live_open_ok = acn_open_live((unsigned char *)device, ebuf, &handle->linktype);
380 handle->md.clear_promisc = promisc;
381 handle->fd = live_open_ok;
382 handle->bufsize = handle->snapshot;
383 #else
384 if ((err = live_open_new(handle, device, promisc, to_ms, ebuf)) == 1) {
385 live_open_ok = 1;
386 if (live_open_mmap(handle, ebuf) == 1)
387 return handle;
388 }
389 else if (err == 0) {
390 /* Non-fatal error; try old way */
391 if (live_open_old(handle, device, promisc, to_ms, ebuf))
392 live_open_ok = 1;
393 }
394 #endif
395 if (!live_open_ok) {
396 /*
397 * Both methods to open the packet socket failed. Tidy
398 * up and report our failure (ebuf is expected to be
399 * set by the functions above).
400 */
401
402 if (handle->md.device != NULL)
403 free(handle->md.device);
404 free(handle);
405 return NULL;
406 }
407
408 #ifndef SITA
409 /*
410 * Compute the buffer size.
411 *
412 * If we're using SOCK_PACKET, this might be a 2.0[.x] kernel,
413 * and might require special handling - check.
414 */
415 if (handle->md.sock_packet && (uname(&utsname) < 0 ||
416 strncmp(utsname.release, "2.0", 3) == 0)) {
417 /*
418 * We're using a SOCK_PACKET structure, and either
419 * we couldn't find out what kernel release this is,
420 * or it's a 2.0[.x] kernel.
421 *
422 * In the 2.0[.x] kernel, a "recvfrom()" on
423 * a SOCK_PACKET socket, with MSG_TRUNC set, will
424 * return the number of bytes read, so if we pass
425 * a length based on the snapshot length, it'll
426 * return the number of bytes from the packet
427 * copied to userland, not the actual length
428 * of the packet.
429 *
430 * This means that, for example, the IP dissector
431 * in tcpdump will get handed a packet length less
432 * than the length in the IP header, and will
433 * complain about "truncated-ip".
434 *
435 * So we don't bother trying to copy from the
436 * kernel only the bytes in which we're interested,
437 * but instead copy them all, just as the older
438 * versions of libpcap for Linux did.
439 *
440 * The buffer therefore needs to be big enough to
441 * hold the largest packet we can get from this
442 * device. Unfortunately, we can't get the MRU
443 * of the network; we can only get the MTU. The
444 * MTU may be too small, in which case a packet larger
445 * than the buffer size will be truncated *and* we
446 * won't get the actual packet size.
447 *
448 * However, if the snapshot length is larger than
449 * the buffer size based on the MTU, we use the
450 * snapshot length as the buffer size, instead;
451 * this means that with a sufficiently large snapshot
452 * length we won't artificially truncate packets
453 * to the MTU-based size.
454 *
455 * This mess just one of many problems with packet
456 * capture on 2.0[.x] kernels; you really want a
457 * 2.2[.x] or later kernel if you want packet capture
458 * to work well.
459 */
460 mtu = iface_get_mtu(handle->fd, device, ebuf);
461 if (mtu == -1) {
462 pcap_close_linux(handle);
463 free(handle);
464 return NULL;
465 }
466 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
467 if (handle->bufsize < handle->snapshot)
468 handle->bufsize = handle->snapshot;
469 } else {
470 /*
471 * This is a 2.2[.x] or later kernel (we know that
472 * either because we're not using a SOCK_PACKET
473 * socket - PF_PACKET is supported only in 2.2
474 * and later kernels - or because we checked the
475 * kernel version).
476 *
477 * We can safely pass "recvfrom()" a byte count
478 * based on the snapshot length.
479 *
480 * If we're in cooked mode, make the snapshot length
481 * large enough to hold a "cooked mode" header plus
482 * 1 byte of packet data (so we don't pass a byte
483 * count of 0 to "recvfrom()").
484 */
485 if (handle->md.cooked) {
486 if (handle->snapshot < SLL_HDR_LEN + 1)
487 handle->snapshot = SLL_HDR_LEN + 1;
488 }
489 handle->bufsize = handle->snapshot;
490 }
491 #endif
492
493 /* Allocate the buffer */
494
495 handle->buffer = malloc(handle->bufsize + handle->offset);
496 if (!handle->buffer) {
497 snprintf(ebuf, PCAP_ERRBUF_SIZE,
498 "malloc: %s", pcap_strerror(errno));
499 pcap_close_linux(handle);
500 free(handle);
501 return NULL;
502 }
503
504 /*
505 * "handle->fd" is a socket, so "select()" and "poll()"
506 * should work on it.
507 */
508 handle->selectable_fd = handle->fd;
509
510 return handle;
511 }
512
513 /*
514 * Read at most max_packets from the capture stream and call the callback
515 * for each of them. Returns the number of packets handled or -1 if an
516 * error occured.
517 */
518 static int
519 pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
520 {
521 /*
522 * Currently, on Linux only one packet is delivered per read,
523 * so we don't loop.
524 */
525 return pcap_read_packet(handle, callback, user);
526 }
527
528 /*
529 * Read a packet from the socket calling the handler provided by
530 * the user. Returns the number of packets received or -1 if an
531 * error occured.
532 */
533 static int
534 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
535 {
536 u_char *bp;
537 int offset;
538 #ifdef HAVE_PF_PACKET_SOCKETS
539 struct sockaddr_ll from;
540 struct sll_header *hdrp;
541 #else
542 struct sockaddr from;
543 #endif
544 socklen_t fromlen;
545 int packet_len, caplen;
546 struct pcap_pkthdr pcap_header;
547
548 #ifdef HAVE_PF_PACKET_SOCKETS
549 /*
550 * If this is a cooked device, leave extra room for a
551 * fake packet header.
552 */
553 if (handle->md.cooked)
554 offset = SLL_HDR_LEN;
555 else
556 offset = 0;
557 #else
558 /*
559 * This system doesn't have PF_PACKET sockets, so it doesn't
560 * support cooked devices.
561 */
562 offset = 0;
563 #endif
564
565 /* Receive a single packet from the kernel */
566
567 bp = handle->buffer + handle->offset;
568 do {
569 /*
570 * Has "pcap_breakloop()" been called?
571 */
572 if (handle->break_loop) {
573 /*
574 * Yes - clear the flag that indicates that it
575 * has, and return -2 as an indication that we
576 * were told to break out of the loop.
577 */
578 handle->break_loop = 0;
579 return -2;
580 }
581 fromlen = sizeof(from);
582 packet_len = recvfrom(
583 handle->fd, bp + offset,
584 handle->bufsize - offset, MSG_TRUNC,
585 (struct sockaddr *) &from, &fromlen);
586 } while (packet_len == -1 && errno == EINTR);
587
588 /* Check if an error occured */
589
590 if (packet_len == -1) {
591 if (errno == EAGAIN)
592 return 0; /* no packet there */
593 else {
594 snprintf(handle->errbuf, sizeof(handle->errbuf),
595 "recvfrom: %s", pcap_strerror(errno));
596 return -1;
597 }
598 }
599
600 #ifdef HAVE_PF_PACKET_SOCKETS
601 if (!handle->md.sock_packet) {
602 /*
603 * Unfortunately, there is a window between socket() and
604 * bind() where the kernel may queue packets from any
605 * interface. If we're bound to a particular interface,
606 * discard packets not from that interface.
607 *
608 * (If socket filters are supported, we could do the
609 * same thing we do when changing the filter; however,
610 * that won't handle packet sockets without socket
611 * filter support, and it's a bit more complicated.
612 * It would save some instructions per packet, however.)
613 */
614 if (handle->md.ifindex != -1 &&
615 from.sll_ifindex != handle->md.ifindex)
616 return 0;
617
618 /*
619 * Do checks based on packet direction.
620 * We can only do this if we're using PF_PACKET; the
621 * address returned for SOCK_PACKET is a "sockaddr_pkt"
622 * which lacks the relevant packet type information.
623 */
624 if (from.sll_pkttype == PACKET_OUTGOING) {
625 /*
626 * Outgoing packet.
627 * If this is from the loopback device, reject it;
628 * we'll see the packet as an incoming packet as well,
629 * and we don't want to see it twice.
630 */
631 if (from.sll_ifindex == handle->md.lo_ifindex)
632 return 0;
633
634 /*
635 * If the user only wants incoming packets, reject it.
636 */
637 if (handle->direction == PCAP_D_IN)
638 return 0;
639 } else {
640 /*
641 * Incoming packet.
642 * If the user only wants outgoing packets, reject it.
643 */
644 if (handle->direction == PCAP_D_OUT)
645 return 0;
646 }
647 }
648 #endif
649
650 #ifdef HAVE_PF_PACKET_SOCKETS
651 /*
652 * If this is a cooked device, fill in the fake packet header.
653 */
654 if (handle->md.cooked) {
655 /*
656 * Add the length of the fake header to the length
657 * of packet data we read.
658 */
659 packet_len += SLL_HDR_LEN;
660
661 hdrp = (struct sll_header *)bp;
662 hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
663 hdrp->sll_hatype = htons(from.sll_hatype);
664 hdrp->sll_halen = htons(from.sll_halen);
665 memcpy(hdrp->sll_addr, from.sll_addr,
666 (from.sll_halen > SLL_ADDRLEN) ?
667 SLL_ADDRLEN :
668 from.sll_halen);
669 hdrp->sll_protocol = from.sll_protocol;
670 }
671 #endif
672
673 /*
674 * XXX: According to the kernel source we should get the real
675 * packet len if calling recvfrom with MSG_TRUNC set. It does
676 * not seem to work here :(, but it is supported by this code
677 * anyway.
678 * To be honest the code RELIES on that feature so this is really
679 * broken with 2.2.x kernels.
680 * I spend a day to figure out what's going on and I found out
681 * that the following is happening:
682 *
683 * The packet comes from a random interface and the packet_rcv
684 * hook is called with a clone of the packet. That code inserts
685 * the packet into the receive queue of the packet socket.
686 * If a filter is attached to that socket that filter is run
687 * first - and there lies the problem. The default filter always
688 * cuts the packet at the snaplen:
689 *
690 * # tcpdump -d
691 * (000) ret #68
692 *
693 * So the packet filter cuts down the packet. The recvfrom call
694 * says "hey, it's only 68 bytes, it fits into the buffer" with
695 * the result that we don't get the real packet length. This
696 * is valid at least until kernel 2.2.17pre6.
697 *
698 * We currently handle this by making a copy of the filter
699 * program, fixing all "ret" instructions with non-zero
700 * operands to have an operand of 65535 so that the filter
701 * doesn't truncate the packet, and supplying that modified
702 * filter to the kernel.
703 */
704
705 caplen = packet_len;
706 if (caplen > handle->snapshot)
707 caplen = handle->snapshot;
708
709 /* Run the packet filter if not using kernel filter */
710 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
711 if (bpf_filter(handle->fcode.bf_insns, bp,
712 packet_len, caplen) == 0)
713 {
714 /* rejected by filter */
715 return 0;
716 }
717 }
718
719 /* Fill in our own header data */
720
721 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
722 snprintf(handle->errbuf, sizeof(handle->errbuf),
723 "SIOCGSTAMP: %s", pcap_strerror(errno));
724 return -1;
725 }
726 pcap_header.caplen = caplen;
727 pcap_header.len = packet_len;
728
729 /*
730 * Count the packet.
731 *
732 * Arguably, we should count them before we check the filter,
733 * as on many other platforms "ps_recv" counts packets
734 * handed to the filter rather than packets that passed
735 * the filter, but if filtering is done in the kernel, we
736 * can't get a count of packets that passed the filter,
737 * and that would mean the meaning of "ps_recv" wouldn't
738 * be the same on all Linux systems.
739 *
740 * XXX - it's not the same on all systems in any case;
741 * ideally, we should have a "get the statistics" call
742 * that supplies more counts and indicates which of them
743 * it supplies, so that we supply a count of packets
744 * handed to the filter only on platforms where that
745 * information is available.
746 *
747 * We count them here even if we can get the packet count
748 * from the kernel, as we can only determine at run time
749 * whether we'll be able to get it from the kernel (if
750 * HAVE_TPACKET_STATS isn't defined, we can't get it from
751 * the kernel, but if it is defined, the library might
752 * have been built with a 2.4 or later kernel, but we
753 * might be running on a 2.2[.x] kernel without Alexey
754 * Kuznetzov's turbopacket patches, and thus the kernel
755 * might not be able to supply those statistics). We
756 * could, I guess, try, when opening the socket, to get
757 * the statistics, and if we can not increment the count
758 * here, but it's not clear that always incrementing
759 * the count is more expensive than always testing a flag
760 * in memory.
761 *
762 * We keep the count in "md.packets_read", and use that for
763 * "ps_recv" if we can't get the statistics from the kernel.
764 * We do that because, if we *can* get the statistics from
765 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
766 * as running counts, as reading the statistics from the
767 * kernel resets the kernel statistics, and if we directly
768 * increment "md.stat.ps_recv" here, that means it will
769 * count packets *twice* on systems where we can get kernel
770 * statistics - once here, and once in pcap_stats_linux().
771 */
772 handle->md.packets_read++;
773
774 /* Call the user supplied callback function */
775 callback(userdata, &pcap_header, bp);
776
777 return 1;
778 }
779
780 static int
781 pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
782 {
783 int ret;
784
785 #ifdef HAVE_PF_PACKET_SOCKETS
786 if (!handle->md.sock_packet) {
787 /* PF_PACKET socket */
788 if (handle->md.ifindex == -1) {
789 /*
790 * We don't support sending on the "any" device.
791 */
792 strlcpy(handle->errbuf,
793 "Sending packets isn't supported on the \"any\" device",
794 PCAP_ERRBUF_SIZE);
795 return (-1);
796 }
797
798 if (handle->md.cooked) {
799 /*
800 * We don't support sending on the "any" device.
801 *
802 * XXX - how do you send on a bound cooked-mode
803 * socket?
804 * Is a "sendto()" required there?
805 */
806 strlcpy(handle->errbuf,
807 "Sending packets isn't supported in cooked mode",
808 PCAP_ERRBUF_SIZE);
809 return (-1);
810 }
811 }
812 #endif
813
814 ret = send(handle->fd, buf, size, 0);
815 if (ret == -1) {
816 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
817 pcap_strerror(errno));
818 return (-1);
819 }
820 return (ret);
821 }
822
823 /*
824 * Get the statistics for the given packet capture handle.
825 * Reports the number of dropped packets iff the kernel supports
826 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
827 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
828 * patches); otherwise, that information isn't available, and we lie
829 * and report 0 as the count of dropped packets.
830 */
831 static int
832 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
833 {
834 #ifdef HAVE_TPACKET_STATS
835 struct tpacket_stats kstats;
836 socklen_t len = sizeof (struct tpacket_stats);
837 #endif
838
839 #ifdef HAVE_TPACKET_STATS
840 /*
841 * Try to get the packet counts from the kernel.
842 */
843 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
844 &kstats, &len) > -1) {
845 /*
846 * On systems where the PACKET_STATISTICS "getsockopt()"
847 * argument is supported on PF_PACKET sockets:
848 *
849 * "ps_recv" counts only packets that *passed* the
850 * filter, not packets that didn't pass the filter.
851 * This includes packets later dropped because we
852 * ran out of buffer space.
853 *
854 * "ps_drop" counts packets dropped because we ran
855 * out of buffer space. It doesn't count packets
856 * dropped by the interface driver. It counts only
857 * packets that passed the filter.
858 *
859 * Both statistics include packets not yet read from
860 * the kernel by libpcap, and thus not yet seen by
861 * the application.
862 *
863 * In "linux/net/packet/af_packet.c", at least in the
864 * 2.4.9 kernel, "tp_packets" is incremented for every
865 * packet that passes the packet filter *and* is
866 * successfully queued on the socket; "tp_drops" is
867 * incremented for every packet dropped because there's
868 * not enough free space in the socket buffer.
869 *
870 * When the statistics are returned for a PACKET_STATISTICS
871 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
872 * so that "tp_packets" counts all packets handed to
873 * the PF_PACKET socket, including packets dropped because
874 * there wasn't room on the socket buffer - but not
875 * including packets that didn't pass the filter.
876 *
877 * In the BSD BPF, the count of received packets is
878 * incremented for every packet handed to BPF, regardless
879 * of whether it passed the filter.
880 *
881 * We can't make "pcap_stats()" work the same on both
882 * platforms, but the best approximation is to return
883 * "tp_packets" as the count of packets and "tp_drops"
884 * as the count of drops.
885 *
886 * Keep a running total because each call to
887 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
888 * resets the counters to zero.
889 */
890 handle->md.stat.ps_recv += kstats.tp_packets;
891 handle->md.stat.ps_drop += kstats.tp_drops;
892 *stats = handle->md.stat;
893 return 0;
894 }
895 else
896 {
897 /*
898 * If the error was EOPNOTSUPP, fall through, so that
899 * if you build the library on a system with
900 * "struct tpacket_stats" and run it on a system
901 * that doesn't, it works as it does if the library
902 * is built on a system without "struct tpacket_stats".
903 */
904 if (errno != EOPNOTSUPP) {
905 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
906 "pcap_stats: %s", pcap_strerror(errno));
907 return -1;
908 }
909 }
910 #endif
911 /*
912 * On systems where the PACKET_STATISTICS "getsockopt()" argument
913 * is not supported on PF_PACKET sockets:
914 *
915 * "ps_recv" counts only packets that *passed* the filter,
916 * not packets that didn't pass the filter. It does not
917 * count packets dropped because we ran out of buffer
918 * space.
919 *
920 * "ps_drop" is not supported.
921 *
922 * "ps_recv" doesn't include packets not yet read from
923 * the kernel by libpcap.
924 *
925 * We maintain the count of packets processed by libpcap in
926 * "md.packets_read", for reasons described in the comment
927 * at the end of pcap_read_packet(). We have no idea how many
928 * packets were dropped.
929 */
930 stats->ps_recv = handle->md.packets_read;
931 stats->ps_drop = 0;
932 return 0;
933 }
934
935 /*
936 * Description string for the "any" device.
937 */
938 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
939
940 int
941 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
942 {
943 if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
944 return (-1);
945
946 #ifdef HAVE_DAG_API
947 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
948 return (-1);
949 #endif /* HAVE_DAG_API */
950
951 #ifdef HAVE_SEPTEL_API
952 if (septel_platform_finddevs(alldevsp, errbuf) < 0)
953 return (-1);
954 #endif /* HAVE_SEPTEL_API */
955
956 #ifdef PCAP_SUPPORT_BT
957 if (bt_platform_finddevs(alldevsp, errbuf) < 0)
958 return (-1);
959 #endif
960
961 #ifdef PCAP_SUPPORT_USB
962 if (usb_platform_finddevs(alldevsp, errbuf) < 0)
963 return (-1);
964 #endif
965
966 return (0);
967 }
968
969 /*
970 * Attach the given BPF code to the packet capture device.
971 */
972 static int
973 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
974 {
975 #ifdef SO_ATTACH_FILTER
976 struct sock_fprog fcode;
977 int can_filter_in_kernel;
978 int err = 0;
979 #endif
980
981 if (!handle)
982 return -1;
983 if (!filter) {
984 strncpy(handle->errbuf, "setfilter: No filter specified",
985 sizeof(handle->errbuf));
986 return -1;
987 }
988
989 #ifdef SITA
990 return acn_setfilter(handle->fd, filter);
991 #else
992 /* Make our private copy of the filter */
993
994 if (install_bpf_program(handle, filter) < 0)
995 /* install_bpf_program() filled in errbuf */
996 return -1;
997
998 /*
999 * Run user level packet filter by default. Will be overriden if
1000 * installing a kernel filter succeeds.
1001 */
1002 handle->md.use_bpf = 0;
1003
1004 /* Install kernel level filter if possible */
1005
1006 #ifdef SO_ATTACH_FILTER
1007 #ifdef USHRT_MAX
1008 if (handle->fcode.bf_len > USHRT_MAX) {
1009 /*
1010 * fcode.len is an unsigned short for current kernel.
1011 * I have yet to see BPF-Code with that much
1012 * instructions but still it is possible. So for the
1013 * sake of correctness I added this check.
1014 */
1015 fprintf(stderr, "Warning: Filter too complex for kernel\n");
1016 fcode.len = 0;
1017 fcode.filter = NULL;
1018 can_filter_in_kernel = 0;
1019 } else
1020 #endif /* USHRT_MAX */
1021 {
1022 /*
1023 * Oh joy, the Linux kernel uses struct sock_fprog instead
1024 * of struct bpf_program and of course the length field is
1025 * of different size. Pointed out by Sebastian
1026 *
1027 * Oh, and we also need to fix it up so that all "ret"
1028 * instructions with non-zero operands have 65535 as the
1029 * operand, and so that, if we're in cooked mode, all
1030 * memory-reference instructions use special magic offsets
1031 * in references to the link-layer header and assume that
1032 * the link-layer payload begins at 0; "fix_program()"
1033 * will do that.
1034 */
1035 switch (fix_program(handle, &fcode)) {
1036
1037 case -1:
1038 default:
1039 /*
1040 * Fatal error; just quit.
1041 * (The "default" case shouldn't happen; we
1042 * return -1 for that reason.)
1043 */
1044 return -1;
1045
1046 case 0:
1047 /*
1048 * The program performed checks that we can't make
1049 * work in the kernel.
1050 */
1051 can_filter_in_kernel = 0;
1052 break;
1053
1054 case 1:
1055 /*
1056 * We have a filter that'll work in the kernel.
1057 */
1058 can_filter_in_kernel = 1;
1059 break;
1060 }
1061 }
1062
1063 if (can_filter_in_kernel) {
1064 if ((err = set_kernel_filter(handle, &fcode)) == 0)
1065 {
1066 /* Installation succeded - using kernel filter. */
1067 handle->md.use_bpf = 1;
1068 }
1069 else if (err == -1) /* Non-fatal error */
1070 {
1071 /*
1072 * Print a warning if we weren't able to install
1073 * the filter for a reason other than "this kernel
1074 * isn't configured to support socket filters.
1075 */
1076 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
1077 fprintf(stderr,
1078 "Warning: Kernel filter failed: %s\n",
1079 pcap_strerror(errno));
1080 }
1081 }
1082 }
1083
1084 /*
1085 * If we're not using the kernel filter, get rid of any kernel
1086 * filter that might've been there before, e.g. because the
1087 * previous filter could work in the kernel, or because some other
1088 * code attached a filter to the socket by some means other than
1089 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1090 * filter out packets that would pass the new userland filter.
1091 */
1092 if (!handle->md.use_bpf)
1093 reset_kernel_filter(handle);
1094
1095 /*
1096 * Free up the copy of the filter that was made by "fix_program()".
1097 */
1098 if (fcode.filter != NULL)
1099 free(fcode.filter);
1100
1101 if (err == -2)
1102 /* Fatal error */
1103 return -1;
1104 #endif /* SO_ATTACH_FILTER */
1105
1106 return 0;
1107 #endif /* SITA */
1108 }
1109
1110 /*
1111 * Set direction flag: Which packets do we accept on a forwarding
1112 * single device? IN, OUT or both?
1113 */
1114 static int
1115 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
1116 {
1117 #ifdef HAVE_PF_PACKET_SOCKETS
1118 if (!handle->md.sock_packet) {
1119 handle->direction = d;
1120 return 0;
1121 }
1122 #endif
1123 /*
1124 * We're not using PF_PACKET sockets, so we can't determine
1125 * the direction of the packet.
1126 */
1127 snprintf(handle->errbuf, sizeof(handle->errbuf),
1128 "Setting direction is not supported on SOCK_PACKET sockets");
1129 return -1;
1130 }
1131
1132
1133 /*
1134 * Map the PACKET_ value to a LINUX_SLL_ value; we
1135 * want the same numerical value to be used in
1136 * the link-layer header even if the numerical values
1137 * for the PACKET_ #defines change, so that programs
1138 * that look at the packet type field will always be
1139 * able to handle DLT_LINUX_SLL captures.
1140 */
1141 static short int
1142 map_packet_type_to_sll_type(short int sll_pkttype)
1143 {
1144 switch (sll_pkttype) {
1145
1146 case PACKET_HOST:
1147 return htons(LINUX_SLL_HOST);
1148
1149 case PACKET_BROADCAST:
1150 return htons(LINUX_SLL_BROADCAST);
1151
1152 case PACKET_MULTICAST:
1153 return htons(LINUX_SLL_MULTICAST);
1154
1155 case PACKET_OTHERHOST:
1156 return htons(LINUX_SLL_OTHERHOST);
1157
1158 case PACKET_OUTGOING:
1159 return htons(LINUX_SLL_OUTGOING);
1160
1161 default:
1162 return -1;
1163 }
1164 }
1165
1166 /*
1167 * Linux uses the ARP hardware type to identify the type of an
1168 * interface. pcap uses the DLT_xxx constants for this. This
1169 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1170 * constant, as arguments, and sets "handle->linktype" to the
1171 * appropriate DLT_XXX constant and sets "handle->offset" to
1172 * the appropriate value (to make "handle->offset" plus link-layer
1173 * header length be a multiple of 4, so that the link-layer payload
1174 * will be aligned on a 4-byte boundary when capturing packets).
1175 * (If the offset isn't set here, it'll be 0; add code as appropriate
1176 * for cases where it shouldn't be 0.)
1177 *
1178 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1179 * in cooked mode; otherwise, we can't use cooked mode, so we have
1180 * to pick some type that works in raw mode, or fail.
1181 *
1182 * Sets the link type to -1 if unable to map the type.
1183 */
1184 static void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
1185 {
1186 switch (arptype) {
1187
1188 case ARPHRD_ETHER:
1189 /*
1190 * This is (presumably) a real Ethernet capture; give it a
1191 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1192 * that an application can let you choose it, in case you're
1193 * capturing DOCSIS traffic that a Cisco Cable Modem
1194 * Termination System is putting out onto an Ethernet (it
1195 * doesn't put an Ethernet header onto the wire, it puts raw
1196 * DOCSIS frames out on the wire inside the low-level
1197 * Ethernet framing).
1198 *
1199 * XXX - are there any sorts of "fake Ethernet" that have
1200 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1201 * a Cisco CMTS won't put traffic onto it or get traffic
1202 * bridged onto it? ISDN is handled in "live_open_new()",
1203 * as we fall back on cooked mode there; are there any
1204 * others?
1205 */
1206 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1207 /*
1208 * If that fails, just leave the list empty.
1209 */
1210 if (handle->dlt_list != NULL) {
1211 handle->dlt_list[0] = DLT_EN10MB;
1212 handle->dlt_list[1] = DLT_DOCSIS;
1213 handle->dlt_count = 2;
1214 }
1215 /* FALLTHROUGH */
1216
1217 case ARPHRD_METRICOM:
1218 case ARPHRD_LOOPBACK:
1219 handle->linktype = DLT_EN10MB;
1220 handle->offset = 2;
1221 break;
1222
1223 case ARPHRD_EETHER:
1224 handle->linktype = DLT_EN3MB;
1225 break;
1226
1227 case ARPHRD_AX25:
1228 handle->linktype = DLT_AX25_KISS;
1229 break;
1230
1231 case ARPHRD_PRONET:
1232 handle->linktype = DLT_PRONET;
1233 break;
1234
1235 case ARPHRD_CHAOS:
1236 handle->linktype = DLT_CHAOS;
1237 break;
1238
1239 #ifndef ARPHRD_IEEE802_TR
1240 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1241 #endif
1242 case ARPHRD_IEEE802_TR:
1243 case ARPHRD_IEEE802:
1244 handle->linktype = DLT_IEEE802;
1245 handle->offset = 2;
1246 break;
1247
1248 case ARPHRD_ARCNET:
1249 handle->linktype = DLT_ARCNET_LINUX;
1250 break;
1251
1252 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1253 #define ARPHRD_FDDI 774
1254 #endif
1255 case ARPHRD_FDDI:
1256 handle->linktype = DLT_FDDI;
1257 handle->offset = 3;
1258 break;
1259
1260 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1261 #define ARPHRD_ATM 19
1262 #endif
1263 case ARPHRD_ATM:
1264 /*
1265 * The Classical IP implementation in ATM for Linux
1266 * supports both what RFC 1483 calls "LLC Encapsulation",
1267 * in which each packet has an LLC header, possibly
1268 * with a SNAP header as well, prepended to it, and
1269 * what RFC 1483 calls "VC Based Multiplexing", in which
1270 * different virtual circuits carry different network
1271 * layer protocols, and no header is prepended to packets.
1272 *
1273 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1274 * you can't use the ARPHRD_ type to find out whether
1275 * captured packets will have an LLC header, and,
1276 * while there's a socket ioctl to *set* the encapsulation
1277 * type, there's no ioctl to *get* the encapsulation type.
1278 *
1279 * This means that
1280 *
1281 * programs that dissect Linux Classical IP frames
1282 * would have to check for an LLC header and,
1283 * depending on whether they see one or not, dissect
1284 * the frame as LLC-encapsulated or as raw IP (I
1285 * don't know whether there's any traffic other than
1286 * IP that would show up on the socket, or whether
1287 * there's any support for IPv6 in the Linux
1288 * Classical IP code);
1289 *
1290 * filter expressions would have to compile into
1291 * code that checks for an LLC header and does
1292 * the right thing.
1293 *
1294 * Both of those are a nuisance - and, at least on systems
1295 * that support PF_PACKET sockets, we don't have to put
1296 * up with those nuisances; instead, we can just capture
1297 * in cooked mode. That's what we'll do, if we can.
1298 * Otherwise, we'll just fail.
1299 */
1300 if (cooked_ok)
1301 handle->linktype = DLT_LINUX_SLL;
1302 else
1303 handle->linktype = -1;
1304 break;
1305
1306 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1307 #define ARPHRD_IEEE80211 801
1308 #endif
1309 case ARPHRD_IEEE80211:
1310 handle->linktype = DLT_IEEE802_11;
1311 break;
1312
1313 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1314 #define ARPHRD_IEEE80211_PRISM 802
1315 #endif
1316 case ARPHRD_IEEE80211_PRISM:
1317 handle->linktype = DLT_PRISM_HEADER;
1318 break;
1319
1320 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1321 #define ARPHRD_IEEE80211_RADIOTAP 803
1322 #endif
1323 case ARPHRD_IEEE80211_RADIOTAP:
1324 handle->linktype = DLT_IEEE802_11_RADIO;
1325 break;
1326
1327 case ARPHRD_PPP:
1328 /*
1329 * Some PPP code in the kernel supplies no link-layer
1330 * header whatsoever to PF_PACKET sockets; other PPP
1331 * code supplies PPP link-layer headers ("syncppp.c");
1332 * some PPP code might supply random link-layer
1333 * headers (PPP over ISDN - there's code in Ethereal,
1334 * for example, to cope with PPP-over-ISDN captures
1335 * with which the Ethereal developers have had to cope,
1336 * heuristically trying to determine which of the
1337 * oddball link-layer headers particular packets have).
1338 *
1339 * As such, we just punt, and run all PPP interfaces
1340 * in cooked mode, if we can; otherwise, we just treat
1341 * it as DLT_RAW, for now - if somebody needs to capture,
1342 * on a 2.0[.x] kernel, on PPP devices that supply a
1343 * link-layer header, they'll have to add code here to
1344 * map to the appropriate DLT_ type (possibly adding a
1345 * new DLT_ type, if necessary).
1346 */
1347 if (cooked_ok)
1348 handle->linktype = DLT_LINUX_SLL;
1349 else {
1350 /*
1351 * XXX - handle ISDN types here? We can't fall
1352 * back on cooked sockets, so we'd have to
1353 * figure out from the device name what type of
1354 * link-layer encapsulation it's using, and map
1355 * that to an appropriate DLT_ value, meaning
1356 * we'd map "isdnN" devices to DLT_RAW (they
1357 * supply raw IP packets with no link-layer
1358 * header) and "isdY" devices to a new DLT_I4L_IP
1359 * type that has only an Ethernet packet type as
1360 * a link-layer header.
1361 *
1362 * But sometimes we seem to get random crap
1363 * in the link-layer header when capturing on
1364 * ISDN devices....
1365 */
1366 handle->linktype = DLT_RAW;
1367 }
1368 break;
1369
1370 #ifndef ARPHRD_CISCO
1371 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1372 #endif
1373 case ARPHRD_CISCO:
1374 handle->linktype = DLT_C_HDLC;
1375 break;
1376
1377 /* Not sure if this is correct for all tunnels, but it
1378 * works for CIPE */
1379 case ARPHRD_TUNNEL:
1380 #ifndef ARPHRD_SIT
1381 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1382 #endif
1383 case ARPHRD_SIT:
1384 case ARPHRD_CSLIP:
1385 case ARPHRD_SLIP6:
1386 case ARPHRD_CSLIP6:
1387 case ARPHRD_ADAPT:
1388 case ARPHRD_SLIP:
1389 #ifndef ARPHRD_RAWHDLC
1390 #define ARPHRD_RAWHDLC 518
1391 #endif
1392 case ARPHRD_RAWHDLC:
1393 #ifndef ARPHRD_DLCI
1394 #define ARPHRD_DLCI 15
1395 #endif
1396 case ARPHRD_DLCI:
1397 /*
1398 * XXX - should some of those be mapped to DLT_LINUX_SLL
1399 * instead? Should we just map all of them to DLT_LINUX_SLL?
1400 */
1401 handle->linktype = DLT_RAW;
1402 break;
1403
1404 #ifndef ARPHRD_FRAD
1405 #define ARPHRD_FRAD 770
1406 #endif
1407 case ARPHRD_FRAD:
1408 handle->linktype = DLT_FRELAY;
1409 break;
1410
1411 case ARPHRD_LOCALTLK:
1412 handle->linktype = DLT_LTALK;
1413 break;
1414
1415 #ifndef ARPHRD_FCPP
1416 #define ARPHRD_FCPP 784
1417 #endif
1418 case ARPHRD_FCPP:
1419 #ifndef ARPHRD_FCAL
1420 #define ARPHRD_FCAL 785
1421 #endif
1422 case ARPHRD_FCAL:
1423 #ifndef ARPHRD_FCPL
1424 #define ARPHRD_FCPL 786
1425 #endif
1426 case ARPHRD_FCPL:
1427 #ifndef ARPHRD_FCFABRIC
1428 #define ARPHRD_FCFABRIC 787
1429 #endif
1430 case ARPHRD_FCFABRIC:
1431 /*
1432 * We assume that those all mean RFC 2625 IP-over-
1433 * Fibre Channel, with the RFC 2625 header at
1434 * the beginning of the packet.
1435 */
1436 handle->linktype = DLT_IP_OVER_FC;
1437 break;
1438
1439 #ifndef ARPHRD_IRDA
1440 #define ARPHRD_IRDA 783
1441 #endif
1442 case ARPHRD_IRDA:
1443 /* Don't expect IP packet out of this interfaces... */
1444 handle->linktype = DLT_LINUX_IRDA;
1445 /* We need to save packet direction for IrDA decoding,
1446 * so let's use "Linux-cooked" mode. Jean II */
1447 //handle->md.cooked = 1;
1448 break;
1449
1450 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1451 * is needed, please report it to <daniele@orlandi.com> */
1452 #ifndef ARPHRD_LAPD
1453 #define ARPHRD_LAPD 8445
1454 #endif
1455 case ARPHRD_LAPD:
1456 /* Don't expect IP packet out of this interfaces... */
1457 handle->linktype = DLT_LINUX_LAPD;
1458 break;
1459
1460 default:
1461 handle->linktype = -1;
1462 break;
1463 }
1464 }
1465
1466 /* ===== Functions to interface to the newer kernels ================== */
1467
1468 /*
1469 * Try to open a packet socket using the new kernel interface.
1470 * Returns 0 on failure.
1471 * FIXME: 0 uses to mean success (Sebastian)
1472 */
1473 static int
1474 live_open_new(pcap_t *handle, const char *device, int promisc,
1475 int to_ms, char *ebuf)
1476 {
1477 #ifdef HAVE_PF_PACKET_SOCKETS
1478 int sock_fd = -1, arptype;
1479 int err;
1480 int fatal_err = 0;
1481 struct packet_mreq mr;
1482
1483 /* One shot loop used for error handling - bail out with break */
1484
1485 do {
1486 /*
1487 * Open a socket with protocol family packet. If a device is
1488 * given we try to open it in raw mode otherwise we use
1489 * the cooked interface.
1490 */
1491 sock_fd = device ?
1492 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
1493 : socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
1494
1495 if (sock_fd == -1) {
1496 snprintf(ebuf, PCAP_ERRBUF_SIZE, "socket: %s",
1497 pcap_strerror(errno) );
1498 break;
1499 }
1500
1501 /* It seems the kernel supports the new interface. */
1502 handle->md.sock_packet = 0;
1503
1504 /*
1505 * Get the interface index of the loopback device.
1506 * If the attempt fails, don't fail, just set the
1507 * "md.lo_ifindex" to -1.
1508 *
1509 * XXX - can there be more than one device that loops
1510 * packets back, i.e. devices other than "lo"? If so,
1511 * we'd need to find them all, and have an array of
1512 * indices for them, and check all of them in
1513 * "pcap_read_packet()".
1514 */
1515 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", ebuf);
1516
1517 /*
1518 * Default value for offset to align link-layer payload
1519 * on a 4-byte boundary.
1520 */
1521 handle->offset = 0;
1522
1523 /*
1524 * What kind of frames do we have to deal with? Fall back
1525 * to cooked mode if we have an unknown interface type.
1526 */
1527
1528 if (device) {
1529 /* Assume for now we don't need cooked mode. */
1530 handle->md.cooked = 0;
1531
1532 arptype = iface_get_arptype(sock_fd, device, ebuf);
1533 if (arptype == -1) {
1534 fatal_err = 1;
1535 break;
1536 }
1537 map_arphrd_to_dlt(handle, arptype, 1);
1538 if (handle->linktype == -1 ||
1539 handle->linktype == DLT_LINUX_SLL ||
1540 handle->linktype == DLT_LINUX_IRDA ||
1541 handle->linktype == DLT_LINUX_LAPD ||
1542 (handle->linktype == DLT_EN10MB &&
1543 (strncmp("isdn", device, 4) == 0 ||
1544 strncmp("isdY", device, 4) == 0))) {
1545 /*
1546 * Unknown interface type (-1), or a
1547 * device we explicitly chose to run
1548 * in cooked mode (e.g., PPP devices),
1549 * or an ISDN device (whose link-layer
1550 * type we can only determine by using
1551 * APIs that may be different on different
1552 * kernels) - reopen in cooked mode.
1553 */
1554 if (close(sock_fd) == -1) {
1555 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1556 "close: %s", pcap_strerror(errno));
1557 break;
1558 }
1559 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
1560 htons(ETH_P_ALL));
1561 if (sock_fd == -1) {
1562 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1563 "socket: %s", pcap_strerror(errno));
1564 break;
1565 }
1566 handle->md.cooked = 1;
1567
1568 /*
1569 * Get rid of any link-layer type list
1570 * we allocated - this only supports cooked
1571 * capture.
1572 */
1573 if (handle->dlt_list != NULL) {
1574 free(handle->dlt_list);
1575 handle->dlt_list = NULL;
1576 handle->dlt_count = 0;
1577 }
1578
1579 if (handle->linktype == -1) {
1580 /*
1581 * Warn that we're falling back on
1582 * cooked mode; we may want to
1583 * update "map_arphrd_to_dlt()"
1584 * to handle the new type.
1585 */
1586 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1587 "arptype %d not "
1588 "supported by libpcap - "
1589 "falling back to cooked "
1590 "socket",
1591 arptype);
1592 }
1593 /* IrDA capture is not a real "cooked" capture,
1594 * it's IrLAP frames, not IP packets. */
1595 if (handle->linktype != DLT_LINUX_IRDA &&
1596 handle->linktype != DLT_LINUX_LAPD)
1597 handle->linktype = DLT_LINUX_SLL;
1598 }
1599
1600 handle->md.ifindex = iface_get_id(sock_fd, device, ebuf);
1601 if (handle->md.ifindex == -1)
1602 break;
1603
1604 if ((err = iface_bind(sock_fd, handle->md.ifindex,
1605 ebuf)) < 0) {
1606 if (err == -2)
1607 fatal_err = 1;
1608 break;
1609 }
1610 } else {
1611 /*
1612 * This is cooked mode.
1613 */
1614 handle->md.cooked = 1;
1615 handle->linktype = DLT_LINUX_SLL;
1616
1617 /*
1618 * We're not bound to a device.
1619 * XXX - true? Or true only if we're using
1620 * the "any" device?
1621 * For now, we're using this as an indication
1622 * that we can't transmit; stop doing that only
1623 * if we figure out how to transmit in cooked
1624 * mode.
1625 */
1626 handle->md.ifindex = -1;
1627 }
1628
1629 /*
1630 * Select promiscuous mode on if "promisc" is set.
1631 *
1632 * Do not turn allmulti mode on if we don't select
1633 * promiscuous mode - on some devices (e.g., Orinoco
1634 * wireless interfaces), allmulti mode isn't supported
1635 * and the driver implements it by turning promiscuous
1636 * mode on, and that screws up the operation of the
1637 * card as a normal networking interface, and on no
1638 * other platform I know of does starting a non-
1639 * promiscuous capture affect which multicast packets
1640 * are received by the interface.
1641 */
1642
1643 /*
1644 * Hmm, how can we set promiscuous mode on all interfaces?
1645 * I am not sure if that is possible at all.
1646 */
1647
1648 if (device && promisc) {
1649 memset(&mr, 0, sizeof(mr));
1650 mr.mr_ifindex = handle->md.ifindex;
1651 mr.mr_type = PACKET_MR_PROMISC;
1652 if (setsockopt(sock_fd, SOL_PACKET,
1653 PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == -1)
1654 {
1655 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1656 "setsockopt: %s", pcap_strerror(errno));
1657 break;
1658 }
1659 }
1660
1661 /* Save the socket FD in the pcap structure */
1662
1663 handle->fd = sock_fd;
1664
1665 return 1;
1666
1667 } while(0);
1668
1669 if (sock_fd != -1)
1670 close(sock_fd);
1671
1672 if (fatal_err) {
1673 /*
1674 * Get rid of any link-layer type list we allocated.
1675 */
1676 if (handle->dlt_list != NULL)
1677 free(handle->dlt_list);
1678 return -2;
1679 } else
1680 return 0;
1681 #else
1682 strncpy(ebuf,
1683 "New packet capturing interface not supported by build "
1684 "environment", PCAP_ERRBUF_SIZE);
1685 return 0;
1686 #endif
1687 }
1688
1689 static int
1690 live_open_mmap(pcap_t* handle, char* errmsg)
1691 {
1692 #ifdef HAVE_PACKET_RING
1693 /* by default request 4M for the ring buffer */
1694 int ret = create_ring(handle, 4*1024*1024, errmsg);
1695 if (ret == 0)
1696 return ret;
1697
1698 /* override some defaults and inherit the other fields from
1699 * open_live_new
1700 * handle->offset is used to get the current position into the rx ring
1701 * handle->cc is used to store the ring size */
1702 handle->read_op = pcap_read_linux_mmap;
1703 handle->close_op = pcap_close_linux_mmap;
1704 handle->setfilter_op = pcap_setfilter_linux_mmap;
1705 handle->setnonblock_op = pcap_setnonblock_mmap;
1706 handle->getnonblock_op = pcap_getnonblock_mmap;
1707 handle->selectable_fd = handle->fd;
1708 return 1;
1709 #else /* HAVE_PACKET_RING */
1710 return 0;
1711 #endif /* HAVE_PACKET_RING */
1712 }
1713
1714 #ifdef HAVE_PACKET_RING
1715
1716 static void
1717 compute_ring_block(int frame_size, unsigned *block_size, unsigned *frames_per_block)
1718 {
1719 /* compute the minumum block size that will handle this frame.
1720 * The block has to be page size aligned.
1721 * The max block size allowed by the kernel is arch-dependent and
1722 * it's not explicitly checked here. */
1723 *block_size = getpagesize();
1724 while (*block_size < frame_size)
1725 *block_size <<= 1;
1726
1727 *frames_per_block = *block_size/frame_size;
1728 }
1729
1730 static int
1731 create_ring(pcap_t* handle, unsigned size, char* errmsg)
1732 {
1733 unsigned i, j, ringsize, frames_per_block;
1734 struct tpacket_req req;
1735
1736 /* Note that with large snapshot (say 64K) only a few frames
1737 * will be available in the ring even with pretty large ring size
1738 * (and a lot of memory will be unused).
1739 * The snap len should be carefully chosen to achive best
1740 * performance */
1741 req.tp_frame_size = TPACKET_ALIGN(handle->snapshot+TPACKET_HDRLEN);
1742 req.tp_frame_nr = size/req.tp_frame_size;
1743 compute_ring_block(req.tp_frame_size, &req.tp_block_size, &frames_per_block);
1744 req.tp_block_nr = req.tp_frame_nr / frames_per_block;
1745
1746 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
1747 req.tp_frame_nr = req.tp_block_nr * frames_per_block;
1748
1749 /* ask the kernel to create the ring */
1750 retry:
1751 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
1752 (void *) &req, sizeof(req))) {
1753 /* try to reduce requested ring size to prevent memory failure */
1754 if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
1755 req.tp_frame_nr >>= 1;
1756 req.tp_block_nr = req.tp_frame_nr/frames_per_block;
1757 goto retry;
1758 }
1759 snprintf(errmsg, PCAP_ERRBUF_SIZE, "can't create rx ring on "
1760 "packet socket %d: %d-%s", handle->fd, errno,
1761 pcap_strerror(errno));
1762 return 0;
1763 }
1764
1765 /* memory map the rx ring */
1766 ringsize = req.tp_block_nr * req.tp_block_size;
1767 handle->bp = mmap(0, ringsize, PROT_READ| PROT_WRITE, MAP_SHARED,
1768 handle->fd, 0);
1769 if (handle->bp == MAP_FAILED) {
1770 snprintf(errmsg, PCAP_ERRBUF_SIZE, "can't mmap rx ring: %d-%s",
1771 errno, pcap_strerror(errno));
1772
1773 /* clear the allocated ring on error*/
1774 destroy_ring(handle);
1775 return 0;
1776 }
1777
1778 /* allocate a ring for each frame header pointer*/
1779 handle->cc = req.tp_frame_nr;
1780 handle->buffer = malloc(handle->cc * sizeof(struct tpacket_hdr*));
1781 if (!handle->buffer) {
1782 destroy_ring(handle);
1783 return 0;
1784 }
1785
1786 /* fill the header ring with proper frame ptr*/
1787 handle->offset = 0;
1788 for (i=0; i<req.tp_block_nr; ++i) {
1789 u_char *base = &handle->bp[i*req.tp_block_size];
1790 for (j=0; j<frames_per_block; ++j, ++handle->offset) {
1791 RING_GET_FRAME(handle) = (struct tpacket_hdr*) base;
1792 base += req.tp_frame_size;
1793 }
1794 }
1795
1796 handle->bufsize = req.tp_frame_size;
1797 handle->offset = 0;
1798 return 1;
1799 }
1800
1801 /* free all ring related resources*/
1802 static void
1803 destroy_ring(pcap_t *handle)
1804 {
1805 /* tell the kernel to destroy the ring*/
1806 struct tpacket_req req;
1807 memset(&req, 0, sizeof(req));
1808 setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
1809 (void *) &req, sizeof(req));
1810
1811 /* if ring is mapped, unmap it*/
1812 if (handle->bp) {
1813 /* need to re-compute the ring size */
1814 unsigned frames_per_block, block_size;
1815 compute_ring_block(handle->bufsize, &block_size, &frames_per_block);
1816
1817 /* do not perform sanity check here: we can't recover any error */
1818 munmap(handle->bp, block_size * handle->cc / frames_per_block);
1819 handle->bp = 0;
1820 }
1821
1822 /* if the header ring is allocated, clear it*/
1823 if (handle->buffer) {
1824 free(handle->buffer);
1825 handle->buffer = 0;
1826 }
1827 }
1828
1829 static void
1830 pcap_close_linux_mmap( pcap_t *handle )
1831 {
1832 destroy_ring(handle);
1833 pcap_close_linux(handle);
1834 }
1835
1836
1837 int
1838 pcap_getnonblock_mmap(pcap_t *p, char *errbuf)
1839 {
1840 /* use negative value of timeout to indicate non blocking ops */
1841 return (p->md.timeout<0);
1842 }
1843
1844 int
1845 pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
1846 {
1847 /* map each value to the corresponding 2's complement, to
1848 * preserve the timeout value provided with pcap_open_live */
1849 if (nonblock) {
1850 if (p->md.timeout > 0)
1851 p->md.timeout = p->md.timeout*-1 - 1;
1852 } else
1853 if (p->md.timeout < 0)
1854 p->md.timeout = (p->md.timeout+1)*-1;
1855 return 0;
1856 }
1857
1858 static int
1859 pcap_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback,
1860 u_char *user)
1861 {
1862 int pkts = 0;
1863
1864 /* wait for frames availability.*/
1865 if ((handle->md.timeout >= 0) && !(RING_GET_FRAME(handle)->tp_status)) {
1866 struct pollfd pollinfo;
1867 int ret;
1868
1869 pollinfo.fd = handle->fd;
1870 pollinfo.events = POLLIN;
1871
1872 do {
1873 /* poll() requires a negative timeout to wait forever */
1874 ret = poll(&pollinfo, 1, (handle->md.timeout > 0)?
1875 handle->md.timeout: -1);
1876 if ((ret < 0) && (errno != EINTR)) {
1877 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1878 "can't poll on packet socket fd %d: %d-%s",
1879 handle->fd, errno, pcap_strerror(errno));
1880 return -1;
1881 }
1882 /* check for break loop condition on interrupted syscall*/
1883 if (handle->break_loop) {
1884 handle->break_loop = 0;
1885 return -2;
1886 }
1887 } while (ret < 0);
1888 }
1889
1890 /* negative values of max_packets are used to require all
1891 * packets available in the ring */
1892 while ((pkts < max_packets) || (max_packets <0)) {
1893 int run_bpf;
1894 struct sockaddr_ll *sll;
1895 struct pcap_pkthdr pcaphdr;
1896 unsigned char *bp;
1897 struct tpacket_hdr* thdr = RING_GET_FRAME(handle);
1898 if (thdr->tp_status == TP_STATUS_KERNEL)
1899 break;
1900
1901 /* perform sanity check on internal offset. */
1902 if (thdr->tp_mac+thdr->tp_snaplen > handle->bufsize) {
1903 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1904 "corrupted frame on kernel ring mac "
1905 "offset %d + caplen %d > frame len %d\n",
1906 thdr->tp_mac, thdr->tp_snaplen, handle->bufsize);
1907 return -1;
1908 }
1909
1910 /* run filter on received packet
1911 * If the kernel filtering is enabled we need to run the
1912 * filter until all the frames present into the ring
1913 * at filter creation time are processed.
1914 * In such case md.use_bpf is used as a counter for the
1915 * packet we need to filter.
1916 * Note: alternatively it could be possible to stop applying
1917 * the filter when the ring became empty, but it can possibly
1918 * happen a lot later... */
1919 bp = (unsigned char*)thdr + thdr->tp_mac;
1920 run_bpf = (!handle->md.use_bpf) ||
1921 ((handle->md.use_bpf>1) && handle->md.use_bpf--);
1922 if (run_bpf && handle->fcode.bf_insns &&
1923 (bpf_filter(handle->fcode.bf_insns, bp,
1924 thdr->tp_len, thdr->tp_snaplen) == 0))
1925 goto skip;
1926
1927 /* check direction and interface index */
1928 sll = (void*)thdr + TPACKET_ALIGN(sizeof(*thdr));
1929 if ((sll->sll_ifindex == handle->md.lo_ifindex) &&
1930 (sll->sll_pkttype == PACKET_OUTGOING))
1931 goto skip;
1932
1933 /* get required packet info from ring header */
1934 pcaphdr.ts.tv_sec = thdr->tp_sec;
1935 pcaphdr.ts.tv_usec = thdr->tp_usec;
1936 pcaphdr.caplen = thdr->tp_snaplen;
1937 pcaphdr.len = thdr->tp_len;
1938
1939 /* if required build in place the sll header*/
1940 if (handle->md.cooked) {
1941 struct sll_header *hdrp = (struct sll_header *)((char *)bp - sizeof(struct sll_header));
1942
1943 hdrp->sll_pkttype = map_packet_type_to_sll_type(
1944 sll->sll_pkttype);
1945 hdrp->sll_hatype = htons(sll->sll_hatype);
1946 hdrp->sll_halen = htons(sll->sll_halen);
1947 memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
1948 hdrp->sll_protocol = sll->sll_protocol;
1949
1950 /* update packet len */
1951 pcaphdr.caplen += SLL_HDR_LEN;
1952 pcaphdr.len += SLL_HDR_LEN;
1953 }
1954
1955 /* pass the packet to the user */
1956 pkts++;
1957 callback(user, &pcaphdr, bp);
1958 handle->md.packets_read++;
1959
1960 skip:
1961 /* next packet */
1962 thdr->tp_status = TP_STATUS_KERNEL;
1963 if (++handle->offset >= handle->cc)
1964 handle->offset = 0;
1965
1966 /* check for break loop condition*/
1967 if (handle->break_loop) {
1968 handle->break_loop = 0;
1969 return -2;
1970 }
1971 }
1972 return pkts;
1973 }
1974
1975 static int
1976 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
1977 {
1978 int n, offset;
1979 int ret = pcap_setfilter_linux(handle, filter);
1980 if (ret < 0)
1981 return ret;
1982
1983 /* if the kernel filter is enabled, we need to apply the filter on
1984 * all packets present into the ring. Get an upper bound of their number
1985 */
1986 if (!handle->md.use_bpf)
1987 return ret;
1988
1989 /* walk the ring backward and count the free slot */
1990 offset = handle->offset;
1991 if (--handle->offset < 0)
1992 handle->offset = handle->cc - 1;
1993 for (n=0; n < handle->cc; ++n) {
1994 if (--handle->offset < 0)
1995 handle->offset = handle->cc - 1;
1996 if (RING_GET_FRAME(handle)->tp_status != TP_STATUS_KERNEL)
1997 break;
1998 }
1999
2000 /* be careful to not change current ring position */
2001 handle->offset = offset;
2002
2003 /* store the number of packets currently present in the ring */
2004 handle->md.use_bpf = 1 + (handle->cc - n);
2005 return ret;
2006 }
2007
2008 #endif /* HAVE_PACKET_RING */
2009
2010
2011 #ifdef HAVE_PF_PACKET_SOCKETS
2012 /*
2013 * Return the index of the given device name. Fill ebuf and return
2014 * -1 on failure.
2015 */
2016 static int
2017 iface_get_id(int fd, const char *device, char *ebuf)
2018 {
2019 struct ifreq ifr;
2020
2021 memset(&ifr, 0, sizeof(ifr));
2022 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
2023
2024 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
2025 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2026 "SIOCGIFINDEX: %s", pcap_strerror(errno));
2027 return -1;
2028 }
2029
2030 return ifr.ifr_ifindex;
2031 }
2032
2033 /*
2034 * Bind the socket associated with FD to the given device.
2035 */
2036 static int
2037 iface_bind(int fd, int ifindex, char *ebuf)
2038 {
2039 struct sockaddr_ll sll;
2040 int err;
2041 socklen_t errlen = sizeof(err);
2042
2043 memset(&sll, 0, sizeof(sll));
2044 sll.sll_family = AF_PACKET;
2045 sll.sll_ifindex = ifindex;
2046 sll.sll_protocol = htons(ETH_P_ALL);
2047
2048 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
2049 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2050 "bind: %s", pcap_strerror(errno));
2051 return -1;
2052 }
2053
2054 /* Any pending errors, e.g., network is down? */
2055
2056 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
2057 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2058 "getsockopt: %s", pcap_strerror(errno));
2059 return -2;
2060 }
2061
2062 if (err > 0) {
2063 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2064 "bind: %s", pcap_strerror(err));
2065 return -2;
2066 }
2067
2068 return 0;
2069 }
2070
2071 #endif
2072
2073
2074 /* ===== Functions to interface to the older kernels ================== */
2075
2076 /*
2077 * With older kernels promiscuous mode is kind of interesting because we
2078 * have to reset the interface before exiting. The problem can't really
2079 * be solved without some daemon taking care of managing usage counts.
2080 * If we put the interface into promiscuous mode, we set a flag indicating
2081 * that we must take it out of that mode when the interface is closed,
2082 * and, when closing the interface, if that flag is set we take it out
2083 * of promiscuous mode.
2084 */
2085
2086 /*
2087 * List of pcaps for which we turned promiscuous mode on by hand.
2088 * If there are any such pcaps, we arrange to call "pcap_close_all()"
2089 * when we exit, and have it close all of them to turn promiscuous mode
2090 * off.
2091 */
2092 static struct pcap *pcaps_to_close;
2093
2094 /*
2095 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
2096 * be called on exit.
2097 */
2098 static int did_atexit;
2099
2100 static void pcap_close_all(void)
2101 {
2102 struct pcap *handle;
2103
2104 while ((handle = pcaps_to_close) != NULL)
2105 pcap_close(handle);
2106 }
2107
2108 static void pcap_close_linux( pcap_t *handle )
2109 {
2110 #ifdef SITA
2111 pcap_close_acn(handle);
2112 #else
2113 struct pcap *p, *prevp;
2114 struct ifreq ifr;
2115
2116 if (handle->md.clear_promisc) {
2117 /*
2118 * We put the interface into promiscuous mode; take
2119 * it out of promiscuous mode.
2120 *
2121 * XXX - if somebody else wants it in promiscuous mode,
2122 * this code cannot know that, so it'll take it out
2123 * of promiscuous mode. That's not fixable in 2.0[.x]
2124 * kernels.
2125 */
2126 memset(&ifr, 0, sizeof(ifr));
2127 strncpy(ifr.ifr_name, handle->md.device, sizeof(ifr.ifr_name));
2128 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
2129 fprintf(stderr,
2130 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
2131 "Please adjust manually.\n"
2132 "Hint: This can't happen with Linux >= 2.2.0.\n",
2133 strerror(errno));
2134 } else {
2135 if (ifr.ifr_flags & IFF_PROMISC) {
2136 /*
2137 * Promiscuous mode is currently on; turn it
2138 * off.
2139 */
2140 ifr.ifr_flags &= ~IFF_PROMISC;
2141 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
2142 fprintf(stderr,
2143 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
2144 "Please adjust manually.\n"
2145 "Hint: This can't happen with Linux >= 2.2.0.\n",
2146 strerror(errno));
2147 }
2148 }
2149 }
2150
2151 /*
2152 * Take this pcap out of the list of pcaps for which we
2153 * have to take the interface out of promiscuous mode.
2154 */
2155 for (p = pcaps_to_close, prevp = NULL; p != NULL;
2156 prevp = p, p = p->md.next) {
2157 if (p == handle) {
2158 /*
2159 * Found it. Remove it from the list.
2160 */
2161 if (prevp == NULL) {
2162 /*
2163 * It was at the head of the list.
2164 */
2165 pcaps_to_close = p->md.next;
2166 } else {
2167 /*
2168 * It was in the middle of the list.
2169 */
2170 prevp->md.next = p->md.next;
2171 }
2172 break;
2173 }
2174 }
2175 }
2176
2177 if (handle->md.device != NULL)
2178 free(handle->md.device);
2179 handle->md.device = NULL;
2180 pcap_close_common(handle);
2181 #endif /* SITA */
2182 }
2183
2184 /*
2185 * Try to open a packet socket using the old kernel interface.
2186 * Returns 0 on failure.
2187 * FIXME: 0 uses to mean success (Sebastian)
2188 */
2189 static int
2190 live_open_old(pcap_t *handle, const char *device, int promisc,
2191 int to_ms, char *ebuf)
2192 {
2193 int arptype;
2194 struct ifreq ifr;
2195
2196 do {
2197 /* Open the socket */
2198
2199 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
2200 if (handle->fd == -1) {
2201 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2202 "socket: %s", pcap_strerror(errno));
2203 break;
2204 }
2205
2206 /* It worked - we are using the old interface */
2207 handle->md.sock_packet = 1;
2208
2209 /* ...which means we get the link-layer header. */
2210 handle->md.cooked = 0;
2211
2212 /* Bind to the given device */
2213
2214 if (!device) {
2215 strncpy(ebuf, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
2216 PCAP_ERRBUF_SIZE);
2217 break;
2218 }
2219 if (iface_bind_old(handle->fd, device, ebuf) == -1)
2220 break;
2221
2222 /*
2223 * Try to get the link-layer type.
2224 */
2225 arptype = iface_get_arptype(handle->fd, device, ebuf);
2226 if (arptype == -1)
2227 break;
2228
2229 /*
2230 * Try to find the DLT_ type corresponding to that
2231 * link-layer type.
2232 */
2233 map_arphrd_to_dlt(handle, arptype, 0);
2234 if (handle->linktype == -1) {
2235 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2236 "unknown arptype %d", arptype);
2237 break;
2238 }
2239
2240 /* Go to promisc mode if requested */
2241
2242 if (promisc) {
2243 memset(&ifr, 0, sizeof(ifr));
2244 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
2245 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
2246 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2247 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
2248 break;
2249 }
2250 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
2251 /*
2252 * Promiscuous mode isn't currently on,
2253 * so turn it on, and remember that
2254 * we should turn it off when the
2255 * pcap_t is closed.
2256 */
2257
2258 /*
2259 * If we haven't already done so, arrange
2260 * to have "pcap_close_all()" called when
2261 * we exit.
2262 */
2263 if (!did_atexit) {
2264 if (atexit(pcap_close_all) == -1) {
2265 /*
2266 * "atexit()" failed; don't
2267 * put the interface in
2268 * promiscuous mode, just
2269 * give up.
2270 */
2271 strncpy(ebuf, "atexit failed",
2272 PCAP_ERRBUF_SIZE);
2273 break;
2274 }
2275 did_atexit = 1;
2276 }
2277
2278 ifr.ifr_flags |= IFF_PROMISC;
2279 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
2280 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2281 "SIOCSIFFLAGS: %s",
2282 pcap_strerror(errno));
2283 break;
2284 }
2285 handle->md.clear_promisc = 1;
2286
2287 /*
2288 * Add this to the list of pcaps
2289 * to close when we exit.
2290 */
2291 handle->md.next = pcaps_to_close;
2292 pcaps_to_close = handle;
2293 }
2294 }
2295
2296 /*
2297 * Default value for offset to align link-layer payload
2298 * on a 4-byte boundary.
2299 */
2300 handle->offset = 0;
2301
2302 return 1;
2303
2304 } while (0);
2305
2306 pcap_close_linux(handle);
2307 return 0;
2308 }
2309
2310 /*
2311 * Bind the socket associated with FD to the given device using the
2312 * interface of the old kernels.
2313 */
2314 static int
2315 iface_bind_old(int fd, const char *device, char *ebuf)
2316 {
2317 struct sockaddr saddr;
2318 int err;
2319 socklen_t errlen = sizeof(err);
2320
2321 memset(&saddr, 0, sizeof(saddr));
2322 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
2323 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
2324 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2325 "bind: %s", pcap_strerror(errno));
2326 return -1;
2327 }
2328
2329 /* Any pending errors, e.g., network is down? */
2330
2331 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
2332 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2333 "getsockopt: %s", pcap_strerror(errno));
2334 return -1;
2335 }
2336
2337 if (err > 0) {
2338 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2339 "bind: %s", pcap_strerror(err));
2340 return -1;
2341 }
2342
2343 return 0;
2344 }
2345
2346
2347 /* ===== System calls available on all supported kernels ============== */
2348
2349 /*
2350 * Query the kernel for the MTU of the given interface.
2351 */
2352 static int
2353 iface_get_mtu(int fd, const char *device, char *ebuf)
2354 {
2355 struct ifreq ifr;
2356
2357 if (!device)
2358 return BIGGER_THAN_ALL_MTUS;
2359
2360 memset(&ifr, 0, sizeof(ifr));
2361 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
2362
2363 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
2364 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2365 "SIOCGIFMTU: %s", pcap_strerror(errno));
2366 return -1;
2367 }
2368
2369 return ifr.ifr_mtu;
2370 }
2371
2372 /*
2373 * Get the hardware type of the given interface as ARPHRD_xxx constant.
2374 */
2375 static int
2376 iface_get_arptype(int fd, const char *device, char *ebuf)
2377 {
2378 struct ifreq ifr;
2379
2380 memset(&ifr, 0, sizeof(ifr));
2381 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
2382
2383 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
2384 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2385 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
2386 return -1;
2387 }
2388
2389 return ifr.ifr_hwaddr.sa_family;
2390 }
2391
2392 #ifdef SO_ATTACH_FILTER
2393 static int
2394 fix_program(pcap_t *handle, struct sock_fprog *fcode)
2395 {
2396 size_t prog_size;
2397 register int i;
2398 register struct bpf_insn *p;
2399 struct bpf_insn *f;
2400 int len;
2401
2402 /*
2403 * Make a copy of the filter, and modify that copy if
2404 * necessary.
2405 */
2406 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
2407 len = handle->fcode.bf_len;
2408 f = (struct bpf_insn *)malloc(prog_size);
2409 if (f == NULL) {
2410 snprintf(handle->errbuf, sizeof(handle->errbuf),
2411 "malloc: %s", pcap_strerror(errno));
2412 return -1;
2413 }
2414 memcpy(f, handle->fcode.bf_insns, prog_size);
2415 fcode->len = len;
2416 fcode->filter = (struct sock_filter *) f;
2417
2418 for (i = 0; i < len; ++i) {
2419 p = &f[i];
2420 /*
2421 * What type of instruction is this?
2422 */
2423 switch (BPF_CLASS(p->code)) {
2424
2425 case BPF_RET:
2426 /*
2427 * It's a return instruction; is the snapshot
2428 * length a constant, rather than the contents
2429 * of the accumulator?
2430 */
2431 if (BPF_MODE(p->code) == BPF_K) {
2432 /*
2433 * Yes - if the value to be returned,
2434 * i.e. the snapshot length, is anything
2435 * other than 0, make it 65535, so that
2436 * the packet is truncated by "recvfrom()",
2437 * not by the filter.
2438 *
2439 * XXX - there's nothing we can easily do
2440 * if it's getting the value from the
2441 * accumulator; we'd have to insert
2442 * code to force non-zero values to be
2443 * 65535.
2444 */
2445 if (p->k != 0)
2446 p->k = 65535;
2447 }
2448 break;
2449
2450 case BPF_LD:
2451 case BPF_LDX:
2452 /*
2453 * It's a load instruction; is it loading
2454 * from the packet?
2455 */
2456 switch (BPF_MODE(p->code)) {
2457
2458 case BPF_ABS:
2459 case BPF_IND:
2460 case BPF_MSH:
2461 /*
2462 * Yes; are we in cooked mode?
2463 */
2464 if (handle->md.cooked) {
2465 /*
2466 * Yes, so we need to fix this
2467 * instruction.
2468 */
2469 if (fix_offset(p) < 0) {
2470 /*
2471 * We failed to do so.
2472 * Return 0, so our caller
2473 * knows to punt to userland.
2474 */
2475 return 0;
2476 }
2477 }
2478 break;
2479 }
2480 break;
2481 }
2482 }
2483 return 1; /* we succeeded */
2484 }
2485
2486 static int
2487 fix_offset(struct bpf_insn *p)
2488 {
2489 /*
2490 * What's the offset?
2491 */
2492 if (p->k >= SLL_HDR_LEN) {
2493 /*
2494 * It's within the link-layer payload; that starts at an
2495 * offset of 0, as far as the kernel packet filter is
2496 * concerned, so subtract the length of the link-layer
2497 * header.
2498 */
2499 p->k -= SLL_HDR_LEN;
2500 } else if (p->k == 14) {
2501 /*
2502 * It's the protocol field; map it to the special magic
2503 * kernel offset for that field.
2504 */
2505 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
2506 } else {
2507 /*
2508 * It's within the header, but it's not one of those
2509 * fields; we can't do that in the kernel, so punt
2510 * to userland.
2511 */
2512 return -1;
2513 }
2514 return 0;
2515 }
2516
2517 static int
2518 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
2519 {
2520 int total_filter_on = 0;
2521 int save_mode;
2522 int ret;
2523 int save_errno;
2524
2525 /*
2526 * The socket filter code doesn't discard all packets queued
2527 * up on the socket when the filter is changed; this means
2528 * that packets that don't match the new filter may show up
2529 * after the new filter is put onto the socket, if those
2530 * packets haven't yet been read.
2531 *
2532 * This means, for example, that if you do a tcpdump capture
2533 * with a filter, the first few packets in the capture might
2534 * be packets that wouldn't have passed the filter.
2535 *
2536 * We therefore discard all packets queued up on the socket
2537 * when setting a kernel filter. (This isn't an issue for
2538 * userland filters, as the userland filtering is done after
2539 * packets are queued up.)
2540 *
2541 * To flush those packets, we put the socket in read-only mode,
2542 * and read packets from the socket until there are no more to
2543 * read.
2544 *
2545 * In order to keep that from being an infinite loop - i.e.,
2546 * to keep more packets from arriving while we're draining
2547 * the queue - we put the "total filter", which is a filter
2548 * that rejects all packets, onto the socket before draining
2549 * the queue.
2550 *
2551 * This code deliberately ignores any errors, so that you may
2552 * get bogus packets if an error occurs, rather than having
2553 * the filtering done in userland even if it could have been
2554 * done in the kernel.
2555 */
2556 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
2557 &total_fcode, sizeof(total_fcode)) == 0) {
2558 char drain[1];
2559
2560 /*
2561 * Note that we've put the total filter onto the socket.
2562 */
2563 total_filter_on = 1;
2564
2565 /*
2566 * Save the socket's current mode, and put it in
2567 * non-blocking mode; we drain it by reading packets
2568 * until we get an error (which is normally a
2569 * "nothing more to be read" error).
2570 */
2571 save_mode = fcntl(handle->fd, F_GETFL, 0);
2572 if (save_mode != -1 &&
2573 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
2574 while (recv(handle->fd, &drain, sizeof drain,
2575 MSG_TRUNC) >= 0)
2576 ;
2577 save_errno = errno;
2578 fcntl(handle->fd, F_SETFL, save_mode);
2579 if (save_errno != EAGAIN) {
2580 /* Fatal error */
2581 reset_kernel_filter(handle);
2582 snprintf(handle->errbuf, sizeof(handle->errbuf),
2583 "recv: %s", pcap_strerror(save_errno));
2584 return -2;
2585 }
2586 }
2587 }
2588
2589 /*
2590 * Now attach the new filter.
2591 */
2592 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
2593 fcode, sizeof(*fcode));
2594 if (ret == -1 && total_filter_on) {
2595 /*
2596 * Well, we couldn't set that filter on the socket,
2597 * but we could set the total filter on the socket.
2598 *
2599 * This could, for example, mean that the filter was
2600 * too big to put into the kernel, so we'll have to
2601 * filter in userland; in any case, we'll be doing
2602 * filtering in userland, so we need to remove the
2603 * total filter so we see packets.
2604 */
2605 save_errno = errno;
2606
2607 /*
2608 * XXX - if this fails, we're really screwed;
2609 * we have the total filter on the socket,
2610 * and it won't come off. What do we do then?
2611 */
2612 reset_kernel_filter(handle);
2613
2614 errno = save_errno;
2615 }
2616 return ret;
2617 }
2618
2619 static int
2620 reset_kernel_filter(pcap_t *handle)
2621 {
2622 /*
2623 * setsockopt() barfs unless it get a dummy parameter.
2624 * valgrind whines unless the value is initialized,
2625 * as it has no idea that setsockopt() ignores its
2626 * parameter.
2627 */
2628 int dummy = 0;
2629
2630 return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
2631 &dummy, sizeof(dummy));
2632 }
2633 #endif