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