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