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