2 * Copyright (c) 1993, 1994, 1995, 1996, 1998
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
24 static const char rcsid[] _U_ =
25 "@(#) $Header: /tcpdump/master/libpcap/pcap-bpf.c,v 1.99.2.17 2008-09-16 18:43:02 guy Exp $ (LBL)";
32 #include <sys/param.h> /* optionally get BSD define */
33 #ifdef HAVE_ZEROCOPY_BPF
37 #include <sys/timeb.h>
38 #include <sys/socket.h>
40 #include <sys/ioctl.h>
41 #include <sys/utsname.h>
43 #ifdef HAVE_ZEROCOPY_BPF
44 #include <machine/atomic.h>
52 * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
53 * native OS version, as we need "struct bpf_config" from it.
55 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
57 #include <sys/types.h>
60 * Prevent bpf.h from redefining the DLT_ values to their
61 * IFT_ values, as we're going to return the standard libpcap
62 * values, not IBM's non-standard IFT_ values.
68 #include <net/if_types.h> /* for IFT_ values */
69 #include <sys/sysconfig.h>
70 #include <sys/device.h>
71 #include <sys/cfgodm.h>
75 #define domakedev makedev64
76 #define getmajor major64
77 #define bpf_hdr bpf_hdr32
79 #define domakedev makedev
80 #define getmajor major
81 #endif /* __64BIT__ */
83 #define BPF_NAME "bpf"
85 #define DRIVER_PATH "/usr/lib/drivers"
86 #define BPF_NODE "/dev/bpf"
87 static int bpfloadedflag = 0;
88 static int odmlockid = 0;
104 #ifdef HAVE_NET_IF_MEDIA_H
105 # include <net/if_media.h>
108 #include "pcap-int.h"
111 #include "pcap-dag.h"
112 #endif /* HAVE_DAG_API */
114 #ifdef HAVE_OS_PROTO_H
115 #include "os-proto.h"
119 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
120 #define HAVE_BSD_IEEE80211
123 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
124 static int find_802_11(struct bpf_dltlist *);
126 # ifdef HAVE_BSD_IEEE80211
127 static int monitor_mode(pcap_t *, int);
130 # if defined(__APPLE__)
131 static void remove_en(pcap_t *);
132 static void remove_802_11(pcap_t *);
135 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
137 #endif /* BIOCGDLTLIST */
140 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
141 * don't get DLT_DOCSIS defined.
144 #define DLT_DOCSIS 143
148 * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
149 * defined, even though some of them are used by various Airport drivers.
151 #ifndef DLT_PRISM_HEADER
152 #define DLT_PRISM_HEADER 119
154 #ifndef DLT_AIRONET_HEADER
155 #define DLT_AIRONET_HEADER 120
157 #ifndef DLT_IEEE802_11_RADIO
158 #define DLT_IEEE802_11_RADIO 127
160 #ifndef DLT_IEEE802_11_RADIO_AVS
161 #define DLT_IEEE802_11_RADIO_AVS 163
164 static int pcap_can_set_rfmon_bpf(pcap_t *p);
165 static int pcap_activate_bpf(pcap_t *p);
166 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
167 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
168 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
170 #ifdef HAVE_ZEROCOPY_BPF
172 * For zerocopy bpf, we need to override the setnonblock/getnonblock routines
173 * so we don't call select(2) if the pcap handle is in non-blocking mode. We
174 * preserve the timeout supplied by pcap_open functions to make sure it
175 * does not get clobbered if the pcap handle moves between blocking and non-
179 pcap_getnonblock_zbuf(pcap_t *p, char *errbuf)
182 * Use a negative value for the timeout to represent that the
183 * pcap handle is in non-blocking mode.
185 return (p->md.timeout < 0);
189 pcap_setnonblock_zbuf(pcap_t *p, int nonblock, char *errbuf)
192 * Map each value to the corresponding 2's complement, to
193 * preserve the timeout value provided with pcap_set_timeout.
194 * (from pcap-linux.c).
197 if (p->md.timeout > 0)
198 p->md.timeout = p->md.timeout * -1 - 1;
200 if (p->md.timeout < 0)
201 p->md.timeout = (p->md.timeout + 1) * -1;
206 * Zero-copy specific close method. Un-map the shared buffers then call
207 * pcap_cleanup_live_common.
210 pcap_cleanup_zbuf(pcap_t *p)
213 * Delete the mappings. Note that p->buffer gets initialized to one
214 * of the mmapped regions in this case, so do not try and free it
215 * directly; null it out so that pcap_cleanup_live_common() doesn't
218 if (p->md.zbuf1 != MAP_FAILED && p->md.zbuf1 != NULL)
219 (void) munmap(p->md.zbuf1, p->md.zbufsize);
220 if (p->md.zbuf2 != MAP_FAILED && p->md.zbuf2 != NULL)
221 (void) munmap(p->md.zbuf2, p->md.zbufsize);
223 pcap_cleanup_live_common(p);
227 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
228 * shared memory buffers.
230 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
231 * and set up p->buffer and cc to reflect one if available. Notice that if
232 * there was no prior buffer, we select zbuf1 as this will be the first
233 * buffer filled for a fresh BPF session.
236 pcap_next_zbuf_shm(pcap_t *p, int *cc)
238 struct bpf_zbuf_header *bzh;
240 if (p->md.zbuffer == p->md.zbuf2 || p->md.zbuffer == NULL) {
241 bzh = (struct bpf_zbuf_header *)p->md.zbuf1;
242 if (bzh->bzh_user_gen !=
243 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
245 p->md.zbuffer = (u_char *)p->md.zbuf1;
246 p->buffer = p->md.zbuffer + sizeof(*bzh);
247 *cc = bzh->bzh_kernel_len;
250 } else if (p->md.zbuffer == p->md.zbuf1) {
251 bzh = (struct bpf_zbuf_header *)p->md.zbuf2;
252 if (bzh->bzh_user_gen !=
253 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
255 p->md.zbuffer = (u_char *)p->md.zbuf2;
256 p->buffer = p->md.zbuffer + sizeof(*bzh);
257 *cc = bzh->bzh_kernel_len;
266 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
267 * select() for data or a timeout, and possibly force rotation of the buffer
268 * in the event we time out or are in immediate mode. Invoke the shared
269 * memory check before doing system calls in order to avoid doing avoidable
273 pcap_next_zbuf(pcap_t *p, int *cc)
282 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
284 * Start out by seeing whether anything is waiting by checking the
285 * next shared memory buffer for data.
287 data = pcap_next_zbuf_shm(p, cc);
291 * If a previous sleep was interrupted due to signal delivery, make
292 * sure that the timeout gets adjusted accordingly. This requires
293 * that we analyze when the timeout should be been expired, and
294 * subtract the current time from that. If after this operation,
295 * our timeout is less then or equal to zero, handle it like a
298 tmout = p->md.timeout;
300 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
301 if (p->md.interrupted && p->md.timeout) {
302 expire = TSTOMILLI(&p->md.firstsel) + p->md.timeout;
303 tmout = expire - TSTOMILLI(&cur);
306 p->md.interrupted = 0;
307 data = pcap_next_zbuf_shm(p, cc);
310 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
311 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
312 "BIOCROTZBUF: %s", strerror(errno));
315 return (pcap_next_zbuf_shm(p, cc));
319 * No data in the buffer, so must use select() to wait for data or
320 * the next timeout. Note that we only call select if the handle
321 * is in blocking mode.
323 if (p->md.timeout >= 0) {
325 FD_SET(p->fd, &r_set);
327 tv.tv_sec = tmout / 1000;
328 tv.tv_usec = (tmout * 1000) % 1000000;
330 r = select(p->fd + 1, &r_set, NULL, NULL,
331 p->md.timeout != 0 ? &tv : NULL);
332 if (r < 0 && errno == EINTR) {
333 if (!p->md.interrupted && p->md.timeout) {
334 p->md.interrupted = 1;
335 p->md.firstsel = cur;
339 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
340 "select: %s", strerror(errno));
344 p->md.interrupted = 0;
346 * Check again for data, which may exist now that we've either been
347 * woken up as a result of data or timed out. Try the "there's data"
348 * case first since it doesn't require a system call.
350 data = pcap_next_zbuf_shm(p, cc);
354 * Try forcing a buffer rotation to dislodge timed out or immediate
357 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
358 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
359 "BIOCROTZBUF: %s", strerror(errno));
362 return (pcap_next_zbuf_shm(p, cc));
366 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
367 * that we know which buffer to use next time around.
370 pcap_ack_zbuf(pcap_t *p)
373 atomic_store_rel_int(&p->md.bzh->bzh_user_gen,
374 p->md.bzh->bzh_kernel_gen);
382 pcap_create(const char *device, char *ebuf)
387 if (strstr(device, "dag"))
388 return (dag_create(device, ebuf));
389 #endif /* HAVE_DAG_API */
391 p = pcap_create_common(device, ebuf);
395 p->activate_op = pcap_activate_bpf;
396 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
404 #ifdef HAVE_CLONING_BPF
405 static const char device[] = "/dev/bpf";
408 char device[sizeof "/dev/bpf0000000000"];
413 * Load the bpf driver, if it isn't already loaded,
414 * and create the BPF device entries, if they don't
417 if (bpf_load(p->errbuf) == PCAP_ERROR)
421 #ifdef HAVE_CLONING_BPF
422 if ((fd = open(device, O_RDWR)) == -1 &&
423 (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
425 fd = PCAP_ERROR_PERM_DENIED;
428 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
429 "(cannot open device) %s: %s", device, pcap_strerror(errno));
433 * Go through all the minors and find one that isn't in use.
436 (void)snprintf(device, sizeof(device), "/dev/bpf%d", n++);
438 * Initially try a read/write open (to allow the inject
439 * method to work). If that fails due to permission
440 * issues, fall back to read-only. This allows a
441 * non-root user to be granted specific access to pcap
442 * capabilities via file permissions.
444 * XXX - we should have an API that has a flag that
445 * controls whether to open read-only or read-write,
446 * so that denial of permission to send (or inability
447 * to send, if sending packets isn't supported on
448 * the device in question) can be indicated at open
451 fd = open(device, O_RDWR);
452 if (fd == -1 && errno == EACCES)
453 fd = open(device, O_RDONLY);
454 } while (fd < 0 && errno == EBUSY);
457 * XXX better message for all minors used
461 fd = PCAP_ERROR_PERM_DENIED;
464 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "(no devices found) %s: %s",
465 device, pcap_strerror(errno));
474 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
476 memset(bdlp, 0, sizeof(*bdlp));
477 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
481 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
482 if (bdlp->bfl_list == NULL) {
483 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
484 pcap_strerror(errno));
488 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
489 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
490 "BIOCGDLTLIST: %s", pcap_strerror(errno));
491 free(bdlp->bfl_list);
496 * OK, for real Ethernet devices, add DLT_DOCSIS to the
497 * list, so that an application can let you choose it,
498 * in case you're capturing DOCSIS traffic that a Cisco
499 * Cable Modem Termination System is putting out onto
500 * an Ethernet (it doesn't put an Ethernet header onto
501 * the wire, it puts raw DOCSIS frames out on the wire
502 * inside the low-level Ethernet framing).
504 * A "real Ethernet device" is defined here as a device
505 * that has a link-layer type of DLT_EN10MB and that has
506 * no alternate link-layer types; that's done to exclude
507 * 802.11 interfaces (which might or might not be the
508 * right thing to do, but I suspect it is - Ethernet <->
509 * 802.11 bridges would probably badly mishandle frames
510 * that don't have Ethernet headers).
512 if (v == DLT_EN10MB) {
514 for (i = 0; i < bdlp->bfl_len; i++) {
515 if (bdlp->bfl_list[i] != DLT_EN10MB) {
522 * We reserved one more slot at the end of
525 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
531 * EINVAL just means "we don't support this ioctl on
532 * this device"; don't treat it as an error.
534 if (errno != EINVAL) {
535 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
536 "BIOCGDLTLIST: %s", pcap_strerror(errno));
545 pcap_can_set_rfmon_bpf(pcap_t *p)
547 #if defined(__APPLE__)
548 struct utsname osinfo;
552 struct bpf_dltlist bdl;
556 * The joys of monitor mode on OS X.
558 * Prior to 10.4, it's not supported at all.
560 * In 10.4, if adapter enN supports monitor mode, there's a
561 * wltN adapter corresponding to it; you open it, instead of
562 * enN, to get monitor mode. You get whatever link-layer
563 * headers it supplies.
565 * In 10.5, and, we assume, later releases, if adapter enN
566 * supports monitor mode, it offers, among its selectable
567 * DLT_ values, values that let you get the 802.11 header;
568 * selecting one of those values puts the adapter into monitor
569 * mode (i.e., you can't get 802.11 headers except in monitor
570 * mode, and you can't get Ethernet headers in monitor mode).
572 if (uname(&osinfo) == -1) {
574 * Can't get the OS version; just say "no".
579 * We assume osinfo.sysname is "Darwin", because
580 * __APPLE__ is defined. We just check the version.
582 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
584 * 10.3 (Darwin 7.x) or earlier.
585 * Monitor mode not supported.
589 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
591 * 10.4 (Darwin 8.x). s/en/wlt/, and check
592 * whether the device exists.
594 if (strncmp(p->opt.source, "en", 2) != 0) {
596 * Not an enN device; no monitor mode.
600 fd = socket(AF_INET, SOCK_DGRAM, 0);
602 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
603 "socket: %s", pcap_strerror(errno));
606 strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
607 strlcat(ifr.ifr_name, p->opt.source + 2, sizeof(ifr.ifr_name));
608 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
621 * Everything else is 10.5 or later; for those,
622 * we just open the enN device, and check whether
623 * we have any 802.11 devices.
625 * First, open a BPF device.
632 * Now bind to the device.
634 (void)strncpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
635 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
636 if (errno == ENETDOWN) {
638 * Return a "network down" indication, so that
639 * the application can report that rather than
640 * saying we had a mysterious failure and
641 * suggest that they report a problem to the
642 * libpcap developers.
645 return (PCAP_ERROR_IFACE_NOT_UP);
647 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
649 p->opt.source, pcap_strerror(errno));
656 * We know the default link type -- now determine all the DLTs
657 * this interface supports. If this fails with EINVAL, it's
658 * not fatal; we just don't get to use the feature later.
659 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
660 * as the default DLT for this adapter.)
662 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
666 if (find_802_11(&bdl) != -1) {
668 * We have an 802.11 DLT, so we can set monitor mode.
675 #endif /* BIOCGDLTLIST */
677 #elif defined(HAVE_BSD_IEEE80211)
680 ret = monitor_mode(p, 0);
681 if (ret == PCAP_ERROR_RFMON_NOTSUP)
682 return (0); /* not an error, just a "can't do" */
684 return (1); /* success */
692 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
697 * "ps_recv" counts packets handed to the filter, not packets
698 * that passed the filter. This includes packets later dropped
699 * because we ran out of buffer space.
701 * "ps_drop" counts packets dropped inside the BPF device
702 * because we ran out of buffer space. It doesn't count
703 * packets dropped by the interface driver. It counts
704 * only packets that passed the filter.
706 * Both statistics include packets not yet read from the kernel
707 * by libpcap, and thus not yet seen by the application.
709 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
710 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
711 pcap_strerror(errno));
715 ps->ps_recv = s.bs_recv;
716 ps->ps_drop = s.bs_drop;
721 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
725 register u_char *bp, *ep;
730 #ifdef HAVE_ZEROCOPY_BPF
736 * Has "pcap_breakloop()" been called?
740 * Yes - clear the flag that indicates that it
741 * has, and return PCAP_ERROR_BREAK to indicate
742 * that we were told to break out of the loop.
745 return (PCAP_ERROR_BREAK);
750 * When reading without zero-copy from a file descriptor, we
751 * use a single buffer and return a length of data in the
752 * buffer. With zero-copy, we update the p->buffer pointer
753 * to point at whatever underlying buffer contains the next
754 * data and update cc to reflect the data found in the
757 #ifdef HAVE_ZEROCOPY_BPF
758 if (p->md.zerocopy) {
759 if (p->buffer != NULL)
761 i = pcap_next_zbuf(p, &cc);
769 cc = read(p->fd, (char *)p->buffer, p->bufsize);
772 /* Don't choke when we get ptraced */
781 * Sigh. More AIX wonderfulness.
783 * For some unknown reason the uiomove()
784 * operation in the bpf kernel extension
785 * used to copy the buffer into user
786 * space sometimes returns EFAULT. I have
787 * no idea why this is the case given that
788 * a kernel debugger shows the user buffer
789 * is correct. This problem appears to
790 * be mostly mitigated by the memset of
791 * the buffer before it is first used.
792 * Very strange.... Shaun Clowes
794 * In any case this means that we shouldn't
795 * treat EFAULT as a fatal error; as we
796 * don't have an API for returning
797 * a "some packets were dropped since
798 * the last packet you saw" indication,
799 * we just ignore EFAULT and keep reading.
806 #if defined(sun) && !defined(BSD)
808 * Due to a SunOS bug, after 2^31 bytes, the kernel
809 * file offset overflows and read fails with EINVAL.
810 * The lseek() to 0 will fix things.
813 if (lseek(p->fd, 0L, SEEK_CUR) +
815 (void)lseek(p->fd, 0L, SEEK_SET);
821 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
822 pcap_strerror(errno));
830 * Loop through each packet.
832 #define bhp ((struct bpf_hdr *)bp)
838 register int caplen, hdrlen;
841 * Has "pcap_breakloop()" been called?
842 * If so, return immediately - if we haven't read any
843 * packets, clear the flag and return PCAP_ERROR_BREAK
844 * to indicate that we were told to break out of the loop,
845 * otherwise leave the flag set, so that the *next* call
846 * will break out of the loop without having read any
847 * packets, and return the number of packets we've
853 return (PCAP_ERROR_BREAK);
861 caplen = bhp->bh_caplen;
862 hdrlen = bhp->bh_hdrlen;
865 * Short-circuit evaluation: if using BPF filter
866 * in kernel, no need to do it now - we already know
867 * the packet passed the filter.
870 * Note: the filter code was generated assuming
871 * that p->fddipad was the amount of padding
872 * before the header, as that's what's required
873 * in the kernel, so we run the filter before
874 * skipping that padding.
878 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
879 struct pcap_pkthdr pkthdr;
881 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
884 * AIX's BPF returns seconds/nanoseconds time
885 * stamps, not seconds/microseconds time stamps.
887 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
889 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
893 pkthdr.caplen = caplen - pad;
896 if (bhp->bh_datalen > pad)
897 pkthdr.len = bhp->bh_datalen - pad;
902 pkthdr.caplen = caplen;
903 pkthdr.len = bhp->bh_datalen;
905 (*callback)(user, &pkthdr, datap);
906 bp += BPF_WORDALIGN(caplen + hdrlen);
907 if (++n >= cnt && cnt > 0) {
916 bp += BPF_WORDALIGN(caplen + hdrlen);
925 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
929 ret = write(p->fd, buf, size);
931 if (ret == -1 && errno == EAFNOSUPPORT) {
933 * In Mac OS X, there's a bug wherein setting the
934 * BIOCSHDRCMPLT flag causes writes to fail; see,
937 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
939 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
940 * assume it's due to that bug, and turn off that flag
941 * and try again. If we succeed, it either means that
942 * somebody applied the fix from that URL, or other patches
945 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
947 * and are running a Darwin kernel with those fixes, or
948 * that Apple fixed the problem in some OS X release.
950 u_int spoof_eth_src = 0;
952 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
953 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
954 "send: can't turn off BIOCSHDRCMPLT: %s",
955 pcap_strerror(errno));
960 * Now try the write again.
962 ret = write(p->fd, buf, size);
964 #endif /* __APPLE__ */
966 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
967 pcap_strerror(errno));
975 bpf_odminit(char *errbuf)
979 if (odm_initialize() == -1) {
980 if (odm_err_msg(odmerrno, &errstr) == -1)
981 errstr = "Unknown error";
982 snprintf(errbuf, PCAP_ERRBUF_SIZE,
983 "bpf_load: odm_initialize failed: %s",
988 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
989 if (odm_err_msg(odmerrno, &errstr) == -1)
990 errstr = "Unknown error";
991 snprintf(errbuf, PCAP_ERRBUF_SIZE,
992 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1001 bpf_odmcleanup(char *errbuf)
1005 if (odm_unlock(odmlockid) == -1) {
1006 if (odm_err_msg(odmerrno, &errstr) == -1)
1007 errstr = "Unknown error";
1008 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1009 "bpf_load: odm_unlock failed: %s",
1011 return (PCAP_ERROR);
1014 if (odm_terminate() == -1) {
1015 if (odm_err_msg(odmerrno, &errstr) == -1)
1016 errstr = "Unknown error";
1017 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1018 "bpf_load: odm_terminate failed: %s",
1020 return (PCAP_ERROR);
1027 bpf_load(char *errbuf)
1031 int numminors, i, rc;
1034 struct bpf_config cfg_bpf;
1035 struct cfg_load cfg_ld;
1036 struct cfg_kmod cfg_km;
1039 * This is very very close to what happens in the real implementation
1040 * but I've fixed some (unlikely) bug situations.
1045 if (bpf_odminit(errbuf) == PCAP_ERROR)
1046 return (PCAP_ERROR);
1048 major = genmajor(BPF_NAME);
1050 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1051 "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1052 return (PCAP_ERROR);
1055 minors = getminor(major, &numminors, BPF_NAME);
1057 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1059 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1060 "bpf_load: genminor failed: %s",
1061 pcap_strerror(errno));
1062 return (PCAP_ERROR);
1066 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1067 return (PCAP_ERROR);
1069 rc = stat(BPF_NODE "0", &sbuf);
1070 if (rc == -1 && errno != ENOENT) {
1071 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1072 "bpf_load: can't stat %s: %s",
1073 BPF_NODE "0", pcap_strerror(errno));
1074 return (PCAP_ERROR);
1077 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1078 for (i = 0; i < BPF_MINORS; i++) {
1079 sprintf(buf, "%s%d", BPF_NODE, i);
1081 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1082 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1083 "bpf_load: can't mknod %s: %s",
1084 buf, pcap_strerror(errno));
1085 return (PCAP_ERROR);
1090 /* Check if the driver is loaded */
1091 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1093 sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1094 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1095 (cfg_ld.kmid == 0)) {
1096 /* Driver isn't loaded, load it now */
1097 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1098 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1099 "bpf_load: could not load driver: %s",
1101 return (PCAP_ERROR);
1105 /* Configure the driver */
1106 cfg_km.cmd = CFG_INIT;
1107 cfg_km.kmid = cfg_ld.kmid;
1108 cfg_km.mdilen = sizeof(cfg_bpf);
1109 cfg_km.mdiptr = (void *)&cfg_bpf;
1110 for (i = 0; i < BPF_MINORS; i++) {
1111 cfg_bpf.devno = domakedev(major, i);
1112 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1113 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1114 "bpf_load: could not configure driver: %s",
1116 return (PCAP_ERROR);
1127 * Turn off rfmon mode if necessary.
1130 pcap_cleanup_bpf(pcap_t *p)
1132 #ifdef HAVE_BSD_IEEE80211
1134 struct ifmediareq req;
1138 if (p->md.must_clear != 0) {
1140 * There's something we have to do when closing this
1143 #ifdef HAVE_BSD_IEEE80211
1144 if (p->md.must_clear & MUST_CLEAR_RFMON) {
1146 * We put the interface into rfmon mode;
1147 * take it out of rfmon mode.
1149 * XXX - if somebody else wants it in rfmon
1150 * mode, this code cannot know that, so it'll take
1151 * it out of rfmon mode.
1153 sock = socket(AF_INET, SOCK_DGRAM, 0);
1156 "Can't restore interface flags (socket() failed: %s).\n"
1157 "Please adjust manually.\n",
1160 memset(&req, 0, sizeof(req));
1161 strncpy(req.ifm_name, p->md.device,
1162 sizeof(req.ifm_name));
1163 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1165 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1166 "Please adjust manually.\n",
1169 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1171 * Rfmon mode is currently on;
1174 memset(&ifr, 0, sizeof(ifr));
1175 (void)strncpy(ifr.ifr_name,
1177 sizeof(ifr.ifr_name));
1179 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1180 if (ioctl(sock, SIOCSIFMEDIA,
1183 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1184 "Please adjust manually.\n",
1192 #endif /* HAVE_BSD_IEEE80211 */
1195 * Take this pcap out of the list of pcaps for which we
1196 * have to take the interface out of some mode.
1198 pcap_remove_from_pcaps_to_close(p);
1199 p->md.must_clear = 0;
1202 #ifdef HAVE_ZEROCOPY_BPF
1204 * In zero-copy mode, p->buffer is just a pointer into one of the two
1205 * memory-mapped buffers, so no need to free it.
1207 if (p->md.zerocopy) {
1208 if (p->md.zbuf1 != MAP_FAILED && p->md.zbuf1 != NULL)
1209 munmap(p->md.zbuf1, p->md.zbufsize);
1210 if (p->md.zbuf2 != MAP_FAILED && p->md.zbuf2 != NULL)
1211 munmap(p->md.zbuf2, p->md.zbufsize);
1214 if (p->md.device != NULL) {
1216 p->md.device = NULL;
1218 pcap_cleanup_live_common(p);
1222 check_setif_failure(pcap_t *p, int error)
1230 if (error == ENXIO) {
1232 * No such device exists.
1235 if (p->opt.rfmon && strncmp(p->opt.source, "wlt", 3) == 0) {
1237 * Monitor mode was requested, and we're trying
1238 * to open a "wltN" device. Assume that this
1239 * is 10.4 and that we were asked to open an
1240 * "enN" device; if that device exists, return
1241 * "monitor mode not supported on the device".
1243 fd = socket(AF_INET, SOCK_DGRAM, 0);
1245 strlcpy(ifr.ifr_name, "en",
1246 sizeof(ifr.ifr_name));
1247 strlcat(ifr.ifr_name, p->opt.source + 3,
1248 sizeof(ifr.ifr_name));
1249 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1251 * We assume this failed because
1252 * the underlying device doesn't
1255 err = PCAP_ERROR_NO_SUCH_DEVICE;
1256 strcpy(p->errbuf, "");
1259 * The underlying "enN" device
1260 * exists, but there's no
1261 * corresponding "wltN" device;
1262 * that means that the "enN"
1263 * device doesn't support
1264 * monitor mode, probably because
1265 * it's an Ethernet device rather
1266 * than a wireless device.
1268 err = PCAP_ERROR_RFMON_NOTSUP;
1273 * We can't find out whether there's
1274 * an underlying "enN" device, so
1275 * just report "no such device".
1277 err = PCAP_ERROR_NO_SUCH_DEVICE;
1278 strcpy(p->errbuf, "");
1286 strcpy(p->errbuf, "");
1287 return (PCAP_ERROR_NO_SUCH_DEVICE);
1288 } else if (errno == ENETDOWN) {
1290 * Return a "network down" indication, so that
1291 * the application can report that rather than
1292 * saying we had a mysterious failure and
1293 * suggest that they report a problem to the
1294 * libpcap developers.
1296 return (PCAP_ERROR_IFACE_NOT_UP);
1299 * Some other error; fill in the error string, and
1300 * return PCAP_ERROR.
1302 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1303 p->opt.source, pcap_strerror(errno));
1304 return (PCAP_ERROR);
1309 pcap_activate_bpf(pcap_t *p)
1314 struct bpf_version bv;
1317 char *wltdev = NULL;
1320 struct bpf_dltlist bdl;
1321 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1324 #endif /* BIOCGDLTLIST */
1325 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1326 u_int spoof_eth_src = 1;
1329 struct bpf_insn total_insn;
1330 struct bpf_program total_prog;
1331 struct utsname osinfo;
1334 if (strstr(device, "dag")) {
1335 return dag_open_live(device, snaplen, promisc, to_ms, ebuf);
1337 #endif /* HAVE_DAG_API */
1340 memset(&bdl, 0, sizeof(bdl));
1341 int have_osinfo = 0;
1342 #ifdef HAVE_ZEROCOPY_BPF
1344 u_int bufmode, zbufmax;
1355 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1356 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1357 pcap_strerror(errno));
1358 status = PCAP_ERROR;
1361 if (bv.bv_major != BPF_MAJOR_VERSION ||
1362 bv.bv_minor < BPF_MINOR_VERSION) {
1363 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1364 "kernel bpf filter out of date");
1365 status = PCAP_ERROR;
1369 p->md.device = strdup(p->opt.source);
1370 if (p->md.device == NULL) {
1371 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1372 pcap_strerror(errno));
1373 status = PCAP_ERROR;
1378 * Try finding a good size for the buffer; 32768 may be too
1379 * big, so keep cutting it in half until we find a size
1380 * that works, or run out of sizes to try. If the default
1381 * is larger, don't make it smaller.
1383 * XXX - there should be a user-accessible hook to set the
1384 * initial buffer size.
1385 * Attempt to find out the version of the OS on which we're running.
1387 if (uname(&osinfo) == 0)
1392 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1393 * of why we check the version number.
1398 * We assume osinfo.sysname is "Darwin", because
1399 * __APPLE__ is defined. We just check the version.
1401 if (osinfo.release[0] < '8' &&
1402 osinfo.release[1] == '.') {
1404 * 10.3 (Darwin 7.x) or earlier.
1406 status = PCAP_ERROR_RFMON_NOTSUP;
1409 if (osinfo.release[0] == '8' &&
1410 osinfo.release[1] == '.') {
1412 * 10.4 (Darwin 8.x). s/en/wlt/
1414 if (strncmp(p->opt.source, "en", 2) != 0) {
1416 * Not an enN device; check
1417 * whether the device even exists.
1419 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1421 strlcpy(ifr.ifr_name,
1423 sizeof(ifr.ifr_name));
1424 if (ioctl(sockfd, SIOCGIFFLAGS,
1425 (char *)&ifr) < 0) {
1433 status = PCAP_ERROR_NO_SUCH_DEVICE;
1434 strcpy(p->errbuf, "");
1436 status = PCAP_ERROR_RFMON_NOTSUP;
1440 * We can't find out whether
1441 * the device exists, so just
1442 * report "no such device".
1444 status = PCAP_ERROR_NO_SUCH_DEVICE;
1445 strcpy(p->errbuf, "");
1449 wltdev = malloc(strlen(p->opt.source) + 2);
1450 if (wltdev == NULL) {
1451 (void)snprintf(p->errbuf,
1452 PCAP_ERRBUF_SIZE, "malloc: %s",
1453 pcap_strerror(errno));
1454 status = PCAP_ERROR;
1457 strcpy(wltdev, "wlt");
1458 strcat(wltdev, p->opt.source + 2);
1459 free(p->opt.source);
1460 p->opt.source = wltdev;
1463 * Everything else is 10.5 or later; for those,
1464 * we just open the enN device, and set the DLT.
1468 #endif /* __APPLE__ */
1469 #ifdef HAVE_ZEROCOPY_BPF
1471 * If the BPF extension to set buffer mode is present, try setting
1472 * the mode to zero-copy. If that fails, use regular buffering. If
1473 * it succeeds but other setup fails, return an error to the user.
1475 bufmode = BPF_BUFMODE_ZBUF;
1476 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1478 * We have zerocopy BPF; use it.
1483 * Set the cleanup and set/get nonblocking mode ops
1484 * as appropriate for zero-copy mode.
1486 p->cleanup_op = pcap_cleanup_zbuf;
1487 p->setnonblock_op = pcap_setnonblock_zbuf;
1488 p->getnonblock_op = pcap_getnonblock_zbuf;
1491 * How to pick a buffer size: first, query the maximum buffer
1492 * size supported by zero-copy. This also lets us quickly
1493 * determine whether the kernel generally supports zero-copy.
1494 * Then, if a buffer size was specified, use that, otherwise
1495 * query the default buffer size, which reflects kernel
1496 * policy for a desired default. Round to the nearest page
1499 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1500 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1501 pcap_strerror(errno));
1505 if (p->opt.buffer_size != 0) {
1507 * A buffer size was explicitly specified; use it.
1509 v = p->opt.buffer_size;
1511 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1516 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
1518 p->md.zbufsize = roundup(v, getpagesize());
1519 if (p->md.zbufsize > zbufmax)
1520 p->md.zbufsize = zbufmax;
1521 p->md.zbuf1 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1523 p->md.zbuf2 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1525 if (p->md.zbuf1 == MAP_FAILED || p->md.zbuf2 == MAP_FAILED) {
1526 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1527 pcap_strerror(errno));
1530 bzero(&bz, sizeof(bz));
1531 bz.bz_bufa = p->md.zbuf1;
1532 bz.bz_bufb = p->md.zbuf2;
1533 bz.bz_buflen = p->md.zbufsize;
1534 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1535 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1536 pcap_strerror(errno));
1539 (void)strncpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
1540 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1541 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1542 p->opt.source, pcap_strerror(errno));
1545 v = p->md.zbufsize - sizeof(struct bpf_zbuf_header);
1550 * We don't have zerocopy BPF.
1551 * Set the buffer size.
1553 if (p->opt.buffer_size != 0) {
1555 * A buffer size was explicitly specified; use it.
1557 if (ioctl(fd, BIOCSBLEN,
1558 (caddr_t)&p->opt.buffer_size) < 0) {
1559 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1560 "BIOCSBLEN: %s: %s", p->opt.source,
1561 pcap_strerror(errno));
1562 status = PCAP_ERROR;
1567 * Now bind to the device.
1569 (void)strncpy(ifr.ifr_name, p->opt.source,
1570 sizeof(ifr.ifr_name));
1571 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1572 status = check_setif_failure(p, errno);
1577 * No buffer size was explicitly specified.
1579 * Try finding a good size for the buffer; 32768 may
1580 * be too big, so keep cutting it in half until we
1581 * find a size that works, or run out of sizes to try.
1582 * If the default is larger, don't make it smaller.
1584 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1587 for ( ; v != 0; v >>= 1) {
1589 * Ignore the return value - this is because the
1590 * call fails on BPF systems that don't have
1591 * kernel malloc. And if the call fails, it's
1592 * no big deal, we just continue to use the
1593 * standard buffer size.
1595 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
1597 (void)strncpy(ifr.ifr_name, p->opt.source,
1598 sizeof(ifr.ifr_name));
1599 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
1600 break; /* that size worked; we're done */
1602 if (errno != ENOBUFS) {
1603 status = check_setif_failure(p, errno);
1609 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1610 "BIOCSBLEN: %s: No buffer size worked",
1612 status = PCAP_ERROR;
1619 /* Get the data link layer type. */
1620 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
1621 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
1622 pcap_strerror(errno));
1623 status = PCAP_ERROR;
1629 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
1652 * We don't know what to map this to yet.
1654 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
1656 status = PCAP_ERROR;
1660 #if _BSDI_VERSION - 0 >= 199510
1661 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
1676 case 12: /*DLT_C_HDLC*/
1684 * We know the default link type -- now determine all the DLTs
1685 * this interface supports. If this fails with EINVAL, it's
1686 * not fatal; we just don't get to use the feature later.
1688 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
1689 status = PCAP_ERROR;
1692 p->dlt_count = bdl.bfl_len;
1693 p->dlt_list = bdl.bfl_list;
1697 * Monitor mode fun, continued.
1699 * For 10.5 and, we're assuming, later releases, as noted above,
1700 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
1701 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
1702 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
1705 * Therefore, if the user asked for monitor mode, we filter out
1706 * the DLT_EN10MB value, as you can't get that in monitor mode,
1707 * and, if the user didn't ask for monitor mode, we filter out
1708 * the 802.11 DLT_ values, because selecting those will turn
1709 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
1710 * radio DLT_ value is offered, we try to select that, otherwise
1711 * we try to select DLT_IEEE802_11.
1714 if (isdigit((unsigned)osinfo.release[0]) &&
1715 (osinfo.release[0] == '9' ||
1716 isdigit((unsigned)osinfo.release[1]))) {
1718 * 10.5 (Darwin 9.x), or later.
1720 new_dlt = find_802_11(&bdl);
1721 if (new_dlt != -1) {
1723 * We have at least one 802.11 DLT_ value,
1724 * so this is an 802.11 interface.
1725 * new_dlt is the best of the 802.11
1726 * DLT_ values in the list.
1730 * Our caller wants monitor mode.
1731 * Purge DLT_EN10MB from the list
1732 * of link-layer types, as selecting
1733 * it will keep monitor mode off.
1738 * If the new mode we want isn't
1739 * the default mode, attempt to
1740 * select the new mode.
1743 if (ioctl(p->fd, BIOCSDLT,
1755 * Our caller doesn't want
1756 * monitor mode. Unless this
1757 * is being done by pcap_open_live(),
1758 * purge the 802.11 link-layer types
1759 * from the list, as selecting
1760 * one of them will turn monitor
1769 * The caller requested monitor
1770 * mode, but we have no 802.11
1771 * link-layer types, so they
1774 status = PCAP_ERROR_RFMON_NOTSUP;
1780 #elif defined(HAVE_BSD_IEEE80211)
1782 * *BSD with the new 802.11 ioctls.
1783 * Do we want monitor mode?
1787 * Try to put the interface into monitor mode.
1789 status = monitor_mode(p, 1);
1798 * We're in monitor mode.
1799 * Try to find the best 802.11 DLT_ value and, if we
1800 * succeed, try to switch to that mode if we're not
1801 * already in that mode.
1803 new_dlt = find_802_11(&bdl);
1804 if (new_dlt != -1) {
1806 * We have at least one 802.11 DLT_ value.
1807 * new_dlt is the best of the 802.11
1808 * DLT_ values in the list.
1810 * If the new mode we want isn't the default mode,
1811 * attempt to select the new mode.
1814 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
1816 * We succeeded; make this the
1824 #endif /* various platforms */
1825 #endif /* BIOCGDLTLIST */
1828 * If this is an Ethernet device, and we don't have a DLT_ list,
1829 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
1830 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
1831 * do, but there's not much we can do about that without finding
1832 * some other way of determining whether it's an Ethernet or 802.11
1835 if (v == DLT_EN10MB && p->dlt_count == 0) {
1836 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1838 * If that fails, just leave the list empty.
1840 if (p->dlt_list != NULL) {
1841 p->dlt_list[0] = DLT_EN10MB;
1842 p->dlt_list[1] = DLT_DOCSIS;
1848 p->fddipad = PCAP_FDDIPAD;
1854 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1856 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
1857 * the link-layer source address isn't forcibly overwritten.
1858 * (Should we ignore errors? Should we do this only if
1859 * we're open for writing?)
1861 * XXX - I seem to remember some packet-sending bug in some
1862 * BSDs - check CVS log for "bpf.c"?
1864 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1865 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1866 "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
1867 status = PCAP_ERROR;
1872 #ifdef HAVE_ZEROCOPY_BPF
1873 if (p->md.timeout != 0 && !p->md.zerocopy) {
1875 if (p->md.timeout) {
1878 * XXX - is this seconds/nanoseconds in AIX?
1879 * (Treating it as such doesn't fix the timeout
1880 * problem described below.)
1883 to.tv_sec = p->md.timeout / 1000;
1884 to.tv_usec = (p->md.timeout * 1000) % 1000000;
1885 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
1886 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT: %s",
1887 pcap_strerror(errno));
1888 status = PCAP_ERROR;
1894 #ifdef BIOCIMMEDIATE
1896 * Darren Reed notes that
1898 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
1899 * timeout appears to be ignored and it waits until the buffer
1900 * is filled before returning. The result of not having it
1901 * set is almost worse than useless if your BPF filter
1902 * is reducing things to only a few packets (i.e. one every
1905 * so we turn BIOCIMMEDIATE mode on if this is AIX.
1907 * We don't turn it on for other platforms, as that means we
1908 * get woken up for every packet, which may not be what we want;
1909 * in the Winter 1993 USENIX paper on BPF, they say:
1911 * Since a process might want to look at every packet on a
1912 * network and the time between packets can be only a few
1913 * microseconds, it is not possible to do a read system call
1914 * per packet and BPF must collect the data from several
1915 * packets and return it as a unit when the monitoring
1916 * application does a read.
1918 * which I infer is the reason for the timeout - it means we
1919 * wait that amount of time, in the hopes that more packets
1920 * will arrive and we'll get them all with one read.
1922 * Setting BIOCIMMEDIATE mode on FreeBSD (and probably other
1923 * BSDs) causes the timeout to be ignored.
1925 * On the other hand, some platforms (e.g., Linux) don't support
1926 * timeouts, they just hand stuff to you as soon as it arrives;
1927 * if that doesn't cause a problem on those platforms, it may
1928 * be OK to have BIOCIMMEDIATE mode on BSD as well.
1930 * (Note, though, that applications may depend on the read
1931 * completing, even if no packets have arrived, when the timeout
1932 * expires, e.g. GUI applications that have to check for input
1933 * while waiting for packets to arrive; a non-zero timeout
1934 * prevents "select()" from working right on FreeBSD and
1935 * possibly other BSDs, as the timer doesn't start until a
1936 * "read()" is done, so the timer isn't in effect if the
1937 * application is blocked on a "select()", and the "select()"
1938 * doesn't get woken up for a BPF device until the buffer
1942 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
1943 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCIMMEDIATE: %s",
1944 pcap_strerror(errno));
1945 status = PCAP_ERROR;
1948 #endif /* BIOCIMMEDIATE */
1951 if (p->opt.promisc) {
1952 /* set promiscuous mode, just warn if it fails */
1953 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
1954 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
1955 pcap_strerror(errno));
1956 status = PCAP_WARNING_PROMISC_NOTSUP;
1960 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
1961 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
1962 pcap_strerror(errno));
1963 status = PCAP_ERROR;
1967 #ifdef HAVE_ZEROCOPY_BPF
1968 if (!p->md.zerocopy) {
1970 p->buffer = (u_char *)malloc(p->bufsize);
1971 if (p->buffer == NULL) {
1972 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
1973 pcap_strerror(errno));
1974 status = PCAP_ERROR;
1978 /* For some strange reason this seems to prevent the EFAULT
1979 * problems we have experienced from AIX BPF. */
1980 memset(p->buffer, 0x0, p->bufsize);
1982 #ifdef HAVE_ZEROCOPY_BPF
1987 * If there's no filter program installed, there's
1988 * no indication to the kernel of what the snapshot
1989 * length should be, so no snapshotting is done.
1991 * Therefore, when we open the device, we install
1992 * an "accept everything" filter with the specified
1995 total_insn.code = (u_short)(BPF_RET | BPF_K);
1998 total_insn.k = p->snapshot;
2000 total_prog.bf_len = 1;
2001 total_prog.bf_insns = &total_insn;
2002 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2003 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2004 pcap_strerror(errno));
2005 status = PCAP_ERROR;
2010 * On most BPF platforms, either you can do a "select()" or
2011 * "poll()" on a BPF file descriptor and it works correctly,
2012 * or you can do it and it will return "readable" if the
2013 * hold buffer is full but not if the timeout expires *and*
2014 * a non-blocking read will, if the hold buffer is empty
2015 * but the store buffer isn't empty, rotate the buffers
2016 * and return what packets are available.
2018 * In the latter case, the fact that a non-blocking read
2019 * will give you the available packets means you can work
2020 * around the failure of "select()" and "poll()" to wake up
2021 * and return "readable" when the timeout expires by using
2022 * the timeout as the "select()" or "poll()" timeout, putting
2023 * the BPF descriptor into non-blocking mode, and read from
2024 * it regardless of whether "select()" reports it as readable
2027 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2028 * won't wake up and return "readable" if the timer expires
2029 * and non-blocking reads return EWOULDBLOCK if the hold
2030 * buffer is empty, even if the store buffer is non-empty.
2032 * This means the workaround in question won't work.
2034 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2035 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2036 * here". On all other BPF platforms, we set it to the FD for
2037 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2038 * read will, if the hold buffer is empty and the store buffer
2039 * isn't empty, rotate the buffers and return what packets are
2040 * there (and in sufficiently recent versions of OpenBSD
2041 * "select()" and "poll()" should work correctly).
2043 * XXX - what about AIX?
2045 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2048 * We can check what OS this is.
2050 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2051 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2052 strncmp(osinfo.release, "4.4-", 4) == 0)
2053 p->selectable_fd = -1;
2057 p->read_op = pcap_read_bpf;
2058 p->inject_op = pcap_inject_bpf;
2059 p->setfilter_op = pcap_setfilter_bpf;
2060 p->setdirection_op = pcap_setdirection_bpf;
2061 p->set_datalink_op = pcap_set_datalink_bpf;
2062 p->getnonblock_op = pcap_getnonblock_fd;
2063 p->setnonblock_op = pcap_setnonblock_fd;
2064 p->stats_op = pcap_stats_bpf;
2065 p->cleanup_op = pcap_cleanup_bpf;
2069 pcap_cleanup_bpf(p);
2074 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2077 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
2079 #endif /* HAVE_DAG_API */
2084 #ifdef HAVE_BSD_IEEE80211
2086 monitor_mode(pcap_t *p, int set)
2089 struct ifmediareq req;
2095 sock = socket(AF_INET, SOCK_DGRAM, 0);
2097 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2098 pcap_strerror(errno));
2099 return (PCAP_ERROR);
2102 memset(&req, 0, sizeof req);
2103 strncpy(req.ifm_name, p->opt.source, sizeof req.ifm_name);
2106 * Find out how many media types we have.
2108 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2110 * Can't get the media types.
2112 if (errno == EINVAL) {
2114 * Interface doesn't support SIOC{G,S}IFMEDIA.
2117 return (PCAP_ERROR_RFMON_NOTSUP);
2119 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA 1: %s",
2120 pcap_strerror(errno));
2122 return (PCAP_ERROR);
2124 if (req.ifm_count == 0) {
2129 return (PCAP_ERROR_RFMON_NOTSUP);
2133 * Allocate a buffer to hold all the media types, and
2134 * get the media types.
2136 media_list = malloc(req.ifm_count * sizeof(int));
2137 if (media_list == NULL) {
2138 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2139 pcap_strerror(errno));
2141 return (PCAP_ERROR);
2143 req.ifm_ulist = media_list;
2144 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2145 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2146 pcap_strerror(errno));
2149 return (PCAP_ERROR);
2153 * Look for an 802.11 "automatic" media type.
2154 * We assume that all 802.11 adapters have that media type,
2155 * and that it will carry the monitor mode supported flag.
2158 for (i = 0; i < req.ifm_count; i++) {
2159 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2160 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2161 /* OK, does it do monitor mode? */
2162 if (media_list[i] & IFM_IEEE80211_MONITOR) {
2171 * This adapter doesn't support monitor mode.
2174 return (PCAP_ERROR_RFMON_NOTSUP);
2179 * Don't just check whether we can enable monitor mode,
2180 * do so, if it's not already enabled.
2182 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2184 * Monitor mode isn't currently on, so turn it on,
2185 * and remember that we should turn it off when the
2190 * If we haven't already done so, arrange to have
2191 * "pcap_close_all()" called when we exit.
2193 if (!pcap_do_addexit(p)) {
2195 * "atexit()" failed; don't put the interface
2196 * in monitor mode, just give up.
2198 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2201 return (PCAP_ERROR);
2203 memset(&ifr, 0, sizeof(ifr));
2204 (void)strncpy(ifr.ifr_name, p->opt.source,
2205 sizeof(ifr.ifr_name));
2206 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2207 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2208 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2209 "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2211 return (PCAP_ERROR);
2214 p->md.must_clear |= MUST_CLEAR_RFMON;
2217 * Add this to the list of pcaps to close when we exit.
2219 pcap_add_to_pcaps_to_close(p);
2224 #endif /* HAVE_BSD_IEEE80211 */
2226 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2228 * Check whether we have any 802.11 link-layer types; return the best
2229 * of the 802.11 link-layer types if we find one, and return -1
2232 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2233 * best 802.11 link-layer type; any of the other 802.11-plus-radio
2234 * headers are second-best; 802.11 with no radio information is
2238 find_802_11(struct bpf_dltlist *bdlp)
2244 * Scan the list of DLT_ values, looking for 802.11 values,
2245 * and, if we find any, choose the best of them.
2248 for (i = 0; i < bdlp->bfl_len; i++) {
2249 switch (bdlp->bfl_list[i]) {
2251 case DLT_IEEE802_11:
2253 * 802.11, but no radio.
2255 * Offer this, and select it as the new mode
2256 * unless we've already found an 802.11
2257 * header with radio information.
2260 new_dlt = bdlp->bfl_list[i];
2263 case DLT_PRISM_HEADER:
2264 case DLT_AIRONET_HEADER:
2265 case DLT_IEEE802_11_RADIO_AVS:
2267 * 802.11 with radio, but not radiotap.
2269 * Offer this, and select it as the new mode
2270 * unless we've already found the radiotap DLT_.
2272 if (new_dlt != DLT_IEEE802_11_RADIO)
2273 new_dlt = bdlp->bfl_list[i];
2276 case DLT_IEEE802_11_RADIO:
2278 * 802.11 with radiotap.
2280 * Offer this, and select it as the new mode.
2282 new_dlt = bdlp->bfl_list[i];
2295 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2297 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
2299 * Remove DLT_EN10MB from the list of DLT_ values.
2302 remove_en(pcap_t *p)
2307 * Scan the list of DLT_ values and discard DLT_EN10MB.
2310 for (i = 0; i < p->dlt_count; i++) {
2311 switch (p->dlt_list[i]) {
2315 * Don't offer this one.
2321 * Just copy this mode over.
2327 * Copy this DLT_ value to its new position.
2329 p->dlt_list[j] = p->dlt_list[i];
2334 * Set the DLT_ count to the number of entries we copied.
2340 * Remove DLT_EN10MB from the list of DLT_ values, and look for the
2341 * best 802.11 link-layer type in that list and return it.
2342 * Radiotap is better than anything else; 802.11 with any other radio
2343 * header is better than 802.11 with no radio header.
2346 remove_802_11(pcap_t *p)
2351 * Scan the list of DLT_ values and discard 802.11 values.
2354 for (i = 0; i < p->dlt_count; i++) {
2355 switch (p->dlt_list[i]) {
2357 case DLT_IEEE802_11:
2358 case DLT_PRISM_HEADER:
2359 case DLT_AIRONET_HEADER:
2360 case DLT_IEEE802_11_RADIO:
2361 case DLT_IEEE802_11_RADIO_AVS:
2363 * 802.11. Don't offer this one.
2369 * Just copy this mode over.
2375 * Copy this DLT_ value to its new position.
2377 p->dlt_list[j] = p->dlt_list[i];
2382 * Set the DLT_ count to the number of entries we copied.
2386 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
2389 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
2392 * Free any user-mode filter we might happen to have installed.
2394 pcap_freecode(&p->fcode);
2397 * Try to install the kernel filter.
2399 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
2403 p->md.use_bpf = 1; /* filtering in the kernel */
2406 * Discard any previously-received packets, as they might
2407 * have passed whatever filter was formerly in effect, but
2408 * might not pass this filter (BIOCSETF discards packets
2409 * buffered in the kernel, so you can lose packets in any
2419 * If it failed with EINVAL, that's probably because the program
2420 * is invalid or too big. Validate it ourselves; if we like it
2421 * (we currently allow backward branches, to support protochain),
2422 * run it in userland. (There's no notion of "too big" for
2425 * Otherwise, just give up.
2426 * XXX - if the copy of the program into the kernel failed,
2427 * we will get EINVAL rather than, say, EFAULT on at least
2430 if (errno != EINVAL) {
2431 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2432 pcap_strerror(errno));
2437 * install_bpf_program() validates the program.
2439 * XXX - what if we already have a filter in the kernel?
2441 if (install_bpf_program(p, fp) < 0)
2443 p->md.use_bpf = 0; /* filtering in userland */
2448 * Set direction flag: Which packets do we accept on a forwarding
2449 * single device? IN, OUT or both?
2452 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
2454 #if defined(BIOCSDIRECTION)
2457 direction = (d == PCAP_D_IN) ? BPF_D_IN :
2458 ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
2459 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
2460 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2461 "Cannot set direction to %s: %s",
2462 (d == PCAP_D_IN) ? "PCAP_D_IN" :
2463 ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
2468 #elif defined(BIOCSSEESENT)
2472 * We don't support PCAP_D_OUT.
2474 if (d == PCAP_D_OUT) {
2475 snprintf(p->errbuf, sizeof(p->errbuf),
2476 "Setting direction to PCAP_D_OUT is not supported on BPF");
2480 seesent = (d == PCAP_D_INOUT);
2481 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
2482 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2483 "Cannot set direction to %s: %s",
2484 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
2490 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2491 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
2497 pcap_set_datalink_bpf(pcap_t *p, int dlt)
2500 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
2501 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2502 "Cannot set DLT %d: %s", dlt, strerror(errno));