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