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.
28 #include <sys/param.h> /* optionally get BSD define */
29 #ifdef HAVE_ZEROCOPY_BPF
32 #include <sys/socket.h>
35 * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
37 * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
38 * at least on *BSD and Mac OS X, it also defines various SIOC ioctls -
39 * we could include <sys/sockio.h>, but if we're already including
40 * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
41 * there's not much point in doing so.
43 * If we have <sys/ioccom.h>, we include it as well, to handle systems
44 * such as Solaris which don't arrange to include <sys/ioccom.h> if you
45 * include <sys/ioctl.h>
47 #include <sys/ioctl.h>
48 #ifdef HAVE_SYS_IOCCOM_H
49 #include <sys/ioccom.h>
51 #include <sys/utsname.h>
53 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
55 * Add support for capturing on FreeBSD usbusN interfaces.
57 static const char usbus_prefix[] = "usbus";
58 #define USBUS_PREFIX_LEN (sizeof(usbus_prefix) - 1)
62 #ifdef HAVE_ZEROCOPY_BPF
63 #include <machine/atomic.h>
71 * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
72 * native OS version, as we need "struct bpf_config" from it.
74 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
76 #include <sys/types.h>
79 * Prevent bpf.h from redefining the DLT_ values to their
80 * IFT_ values, as we're going to return the standard libpcap
81 * values, not IBM's non-standard IFT_ values.
87 #include <net/if_types.h> /* for IFT_ values */
88 #include <sys/sysconfig.h>
89 #include <sys/device.h>
90 #include <sys/cfgodm.h>
94 #define domakedev makedev64
95 #define getmajor major64
96 #define bpf_hdr bpf_hdr32
98 #define domakedev makedev
99 #define getmajor major
100 #endif /* __64BIT__ */
102 #define BPF_NAME "bpf"
104 #define DRIVER_PATH "/usr/lib/drivers"
105 #define BPF_NODE "/dev/bpf"
106 static int bpfloadedflag = 0;
107 static int odmlockid = 0;
109 static int bpf_load(char *errbuf);
126 #ifdef HAVE_NET_IF_MEDIA_H
127 # include <net/if_media.h>
130 #include "pcap-int.h"
132 #ifdef HAVE_OS_PROTO_H
133 #include "os-proto.h"
137 * Later versions of NetBSD stick padding in front of FDDI frames
138 * to align the IP header on a 4-byte boundary.
140 #if defined(__NetBSD__) && __NetBSD_Version__ > 106000000
141 #define PCAP_FDDIPAD 3
145 * Private data for capturing on BPF devices.
148 #ifdef HAVE_ZEROCOPY_BPF
150 * Zero-copy read buffer -- for zero-copy BPF. 'buffer' above will
151 * alternative between these two actual mmap'd buffers as required.
152 * As there is a header on the front size of the mmap'd buffer, only
153 * some of the buffer is exposed to libpcap as a whole via bufsize;
154 * zbufsize is the true size. zbuffer tracks the current zbuf
155 * assocated with buffer so that it can be used to decide which the
156 * next buffer to read will be.
158 u_char *zbuf1, *zbuf2, *zbuffer;
162 struct timespec firstsel;
164 * If there's currently a buffer being actively processed, then it is
165 * referenced here; 'buffer' is also pointed at it, but offset by the
166 * size of the header.
168 struct bpf_zbuf_header *bzh;
169 int nonblock; /* true if in nonblocking mode */
170 #endif /* HAVE_ZEROCOPY_BPF */
172 char *device; /* device name */
173 int filtering_in_kernel; /* using kernel filter */
174 int must_do_on_close; /* stuff we must do when we close */
178 * Stuff to do when we close.
180 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
181 #define MUST_DESTROY_USBUS 0x00000002 /* destroy usbusN interface */
184 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
185 #define HAVE_BSD_IEEE80211
188 * The ifm_ulist member of a struct ifmediareq is an int * on most systems,
189 * but it's a uint64_t on newer versions of OpenBSD.
191 * We check this by checking whether IFM_GMASK is defined and > 2^32-1.
193 # if defined(IFM_GMASK) && IFM_GMASK > 0xFFFFFFFF
194 # define IFM_ULIST_TYPE uint64_t
196 # define IFM_ULIST_TYPE int
200 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
201 static int find_802_11(struct bpf_dltlist *);
203 # ifdef HAVE_BSD_IEEE80211
204 static int monitor_mode(pcap_t *, int);
207 # if defined(__APPLE__)
208 static void remove_en(pcap_t *);
209 static void remove_802_11(pcap_t *);
212 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
214 #endif /* BIOCGDLTLIST */
216 #if defined(sun) && defined(LIFNAMSIZ) && defined(lifr_zoneid)
221 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
222 * don't get DLT_DOCSIS defined.
225 #define DLT_DOCSIS 143
229 * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
230 * defined, even though some of them are used by various Airport drivers.
232 #ifndef DLT_PRISM_HEADER
233 #define DLT_PRISM_HEADER 119
235 #ifndef DLT_AIRONET_HEADER
236 #define DLT_AIRONET_HEADER 120
238 #ifndef DLT_IEEE802_11_RADIO
239 #define DLT_IEEE802_11_RADIO 127
241 #ifndef DLT_IEEE802_11_RADIO_AVS
242 #define DLT_IEEE802_11_RADIO_AVS 163
245 static int pcap_can_set_rfmon_bpf(pcap_t *p);
246 static int pcap_activate_bpf(pcap_t *p);
247 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
248 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
249 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
252 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
253 * pb->nonblock so we don't call select(2) if the pcap handle is in non-
257 pcap_getnonblock_bpf(pcap_t *p, char *errbuf)
259 #ifdef HAVE_ZEROCOPY_BPF
260 struct pcap_bpf *pb = p->priv;
263 return (pb->nonblock);
265 return (pcap_getnonblock_fd(p, errbuf));
269 pcap_setnonblock_bpf(pcap_t *p, int nonblock, char *errbuf)
271 #ifdef HAVE_ZEROCOPY_BPF
272 struct pcap_bpf *pb = p->priv;
275 pb->nonblock = nonblock;
279 return (pcap_setnonblock_fd(p, nonblock, errbuf));
282 #ifdef HAVE_ZEROCOPY_BPF
284 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
285 * shared memory buffers.
287 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
288 * and set up p->buffer and cc to reflect one if available. Notice that if
289 * there was no prior buffer, we select zbuf1 as this will be the first
290 * buffer filled for a fresh BPF session.
293 pcap_next_zbuf_shm(pcap_t *p, int *cc)
295 struct pcap_bpf *pb = p->priv;
296 struct bpf_zbuf_header *bzh;
298 if (pb->zbuffer == pb->zbuf2 || pb->zbuffer == NULL) {
299 bzh = (struct bpf_zbuf_header *)pb->zbuf1;
300 if (bzh->bzh_user_gen !=
301 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
303 pb->zbuffer = (u_char *)pb->zbuf1;
304 p->buffer = pb->zbuffer + sizeof(*bzh);
305 *cc = bzh->bzh_kernel_len;
308 } else if (pb->zbuffer == pb->zbuf1) {
309 bzh = (struct bpf_zbuf_header *)pb->zbuf2;
310 if (bzh->bzh_user_gen !=
311 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
313 pb->zbuffer = (u_char *)pb->zbuf2;
314 p->buffer = pb->zbuffer + sizeof(*bzh);
315 *cc = bzh->bzh_kernel_len;
324 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
325 * select() for data or a timeout, and possibly force rotation of the buffer
326 * in the event we time out or are in immediate mode. Invoke the shared
327 * memory check before doing system calls in order to avoid doing avoidable
331 pcap_next_zbuf(pcap_t *p, int *cc)
333 struct pcap_bpf *pb = p->priv;
341 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
343 * Start out by seeing whether anything is waiting by checking the
344 * next shared memory buffer for data.
346 data = pcap_next_zbuf_shm(p, cc);
350 * If a previous sleep was interrupted due to signal delivery, make
351 * sure that the timeout gets adjusted accordingly. This requires
352 * that we analyze when the timeout should be been expired, and
353 * subtract the current time from that. If after this operation,
354 * our timeout is less then or equal to zero, handle it like a
357 tmout = p->opt.timeout;
359 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
360 if (pb->interrupted && p->opt.timeout) {
361 expire = TSTOMILLI(&pb->firstsel) + p->opt.timeout;
362 tmout = expire - TSTOMILLI(&cur);
366 data = pcap_next_zbuf_shm(p, cc);
369 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
370 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
371 "BIOCROTZBUF: %s", strerror(errno));
374 return (pcap_next_zbuf_shm(p, cc));
378 * No data in the buffer, so must use select() to wait for data or
379 * the next timeout. Note that we only call select if the handle
380 * is in blocking mode.
384 FD_SET(p->fd, &r_set);
386 tv.tv_sec = tmout / 1000;
387 tv.tv_usec = (tmout * 1000) % 1000000;
389 r = select(p->fd + 1, &r_set, NULL, NULL,
390 p->opt.timeout != 0 ? &tv : NULL);
391 if (r < 0 && errno == EINTR) {
392 if (!pb->interrupted && p->opt.timeout) {
398 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
399 "select: %s", strerror(errno));
405 * Check again for data, which may exist now that we've either been
406 * woken up as a result of data or timed out. Try the "there's data"
407 * case first since it doesn't require a system call.
409 data = pcap_next_zbuf_shm(p, cc);
413 * Try forcing a buffer rotation to dislodge timed out or immediate
416 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
417 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
418 "BIOCROTZBUF: %s", strerror(errno));
421 return (pcap_next_zbuf_shm(p, cc));
425 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
426 * that we know which buffer to use next time around.
429 pcap_ack_zbuf(pcap_t *p)
431 struct pcap_bpf *pb = p->priv;
433 atomic_store_rel_int(&pb->bzh->bzh_user_gen,
434 pb->bzh->bzh_kernel_gen);
439 #endif /* HAVE_ZEROCOPY_BPF */
442 pcap_create_interface(const char *device _U_, char *ebuf)
446 p = pcap_create_common(ebuf, sizeof (struct pcap_bpf));
450 p->activate_op = pcap_activate_bpf;
451 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
454 * We claim that we support microsecond and nanosecond time
457 p->tstamp_precision_count = 2;
458 p->tstamp_precision_list = malloc(2 * sizeof(u_int));
459 if (p->tstamp_precision_list == NULL) {
460 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
461 pcap_strerror(errno));
465 p->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
466 p->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
467 #endif /* BIOCSTSTAMP */
472 * On success, returns a file descriptor for a BPF device.
473 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
476 bpf_open(char *errbuf)
479 #ifdef HAVE_CLONING_BPF
480 static const char device[] = "/dev/bpf";
483 char device[sizeof "/dev/bpf0000000000"];
488 * Load the bpf driver, if it isn't already loaded,
489 * and create the BPF device entries, if they don't
492 if (bpf_load(errbuf) == PCAP_ERROR)
496 #ifdef HAVE_CLONING_BPF
497 if ((fd = open(device, O_RDWR)) == -1 &&
498 (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
500 fd = PCAP_ERROR_PERM_DENIED;
503 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
504 "(cannot open device) %s: %s", device, pcap_strerror(errno));
508 * Go through all the minors and find one that isn't in use.
511 (void)pcap_snprintf(device, sizeof(device), "/dev/bpf%d", n++);
513 * Initially try a read/write open (to allow the inject
514 * method to work). If that fails due to permission
515 * issues, fall back to read-only. This allows a
516 * non-root user to be granted specific access to pcap
517 * capabilities via file permissions.
519 * XXX - we should have an API that has a flag that
520 * controls whether to open read-only or read-write,
521 * so that denial of permission to send (or inability
522 * to send, if sending packets isn't supported on
523 * the device in question) can be indicated at open
526 fd = open(device, O_RDWR);
527 if (fd == -1 && errno == EACCES)
528 fd = open(device, O_RDONLY);
529 } while (fd < 0 && errno == EBUSY);
532 * XXX better message for all minors used
541 * /dev/bpf0 doesn't exist, which
542 * means we probably have no BPF
545 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
546 "(there are no BPF devices)");
549 * We got EBUSY on at least one
550 * BPF device, so we have BPF
551 * devices, but all the ones
552 * that exist are busy.
554 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
555 "(all BPF devices are busy)");
561 * Got EACCES on the last device we tried,
562 * and EBUSY on all devices before that,
565 fd = PCAP_ERROR_PERM_DENIED;
566 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
567 "(cannot open BPF device) %s: %s", device,
568 pcap_strerror(errno));
573 * Some other problem.
576 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
577 "(cannot open BPF device) %s: %s", device,
578 pcap_strerror(errno));
588 * Open and bind to a device; used if we're not actually going to use
589 * the device, but are just testing whether it can be opened, or opening
590 * it to get information about it.
592 * Returns an error code on failure (always negative), and an FD for
593 * the now-bound BPF device on success (always non-negative).
596 bpf_open_and_bind(const char *name, char *errbuf)
602 * First, open a BPF device.
604 fd = bpf_open(errbuf);
606 return (fd); /* fd is the appropriate error code */
609 * Now bind to the device.
611 (void)strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
612 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
617 * There's no such device.
620 return (PCAP_ERROR_NO_SUCH_DEVICE);
624 * Return a "network down" indication, so that
625 * the application can report that rather than
626 * saying we had a mysterious failure and
627 * suggest that they report a problem to the
628 * libpcap developers.
631 return (PCAP_ERROR_IFACE_NOT_UP);
634 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
635 "BIOCSETIF: %s: %s", name, pcap_strerror(errno));
649 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
651 memset(bdlp, 0, sizeof(*bdlp));
652 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
656 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
657 if (bdlp->bfl_list == NULL) {
658 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
659 pcap_strerror(errno));
663 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
664 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE,
665 "BIOCGDLTLIST: %s", pcap_strerror(errno));
666 free(bdlp->bfl_list);
671 * OK, for real Ethernet devices, add DLT_DOCSIS to the
672 * list, so that an application can let you choose it,
673 * in case you're capturing DOCSIS traffic that a Cisco
674 * Cable Modem Termination System is putting out onto
675 * an Ethernet (it doesn't put an Ethernet header onto
676 * the wire, it puts raw DOCSIS frames out on the wire
677 * inside the low-level Ethernet framing).
679 * A "real Ethernet device" is defined here as a device
680 * that has a link-layer type of DLT_EN10MB and that has
681 * no alternate link-layer types; that's done to exclude
682 * 802.11 interfaces (which might or might not be the
683 * right thing to do, but I suspect it is - Ethernet <->
684 * 802.11 bridges would probably badly mishandle frames
685 * that don't have Ethernet headers).
687 * On Solaris with BPF, Ethernet devices also offer
688 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
689 * treat it as an indication that the device isn't an
692 if (v == DLT_EN10MB) {
694 for (i = 0; i < bdlp->bfl_len; i++) {
695 if (bdlp->bfl_list[i] != DLT_EN10MB
697 && bdlp->bfl_list[i] != DLT_IPNET
706 * We reserved one more slot at the end of
709 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
715 * EINVAL just means "we don't support this ioctl on
716 * this device"; don't treat it as an error.
718 if (errno != EINVAL) {
719 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE,
720 "BIOCGDLTLIST: %s", pcap_strerror(errno));
729 pcap_can_set_rfmon_bpf(pcap_t *p)
731 #if defined(__APPLE__)
732 struct utsname osinfo;
736 struct bpf_dltlist bdl;
740 * The joys of monitor mode on OS X.
742 * Prior to 10.4, it's not supported at all.
744 * In 10.4, if adapter enN supports monitor mode, there's a
745 * wltN adapter corresponding to it; you open it, instead of
746 * enN, to get monitor mode. You get whatever link-layer
747 * headers it supplies.
749 * In 10.5, and, we assume, later releases, if adapter enN
750 * supports monitor mode, it offers, among its selectable
751 * DLT_ values, values that let you get the 802.11 header;
752 * selecting one of those values puts the adapter into monitor
753 * mode (i.e., you can't get 802.11 headers except in monitor
754 * mode, and you can't get Ethernet headers in monitor mode).
756 if (uname(&osinfo) == -1) {
758 * Can't get the OS version; just say "no".
763 * We assume osinfo.sysname is "Darwin", because
764 * __APPLE__ is defined. We just check the version.
766 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
768 * 10.3 (Darwin 7.x) or earlier.
769 * Monitor mode not supported.
773 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
775 * 10.4 (Darwin 8.x). s/en/wlt/, and check
776 * whether the device exists.
778 if (strncmp(p->opt.device, "en", 2) != 0) {
780 * Not an enN device; no monitor mode.
784 fd = socket(AF_INET, SOCK_DGRAM, 0);
786 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
787 "socket: %s", pcap_strerror(errno));
790 strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
791 strlcat(ifr.ifr_name, p->opt.device + 2, sizeof(ifr.ifr_name));
792 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
805 * Everything else is 10.5 or later; for those,
806 * we just open the enN device, and check whether
807 * we have any 802.11 devices.
809 * First, open a BPF device.
811 fd = bpf_open(p->errbuf);
813 return (fd); /* fd is the appropriate error code */
816 * Now bind to the device.
818 (void)strncpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
819 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
824 * There's no such device.
827 return (PCAP_ERROR_NO_SUCH_DEVICE);
831 * Return a "network down" indication, so that
832 * the application can report that rather than
833 * saying we had a mysterious failure and
834 * suggest that they report a problem to the
835 * libpcap developers.
838 return (PCAP_ERROR_IFACE_NOT_UP);
841 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
843 p->opt.device, pcap_strerror(errno));
850 * We know the default link type -- now determine all the DLTs
851 * this interface supports. If this fails with EINVAL, it's
852 * not fatal; we just don't get to use the feature later.
853 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
854 * as the default DLT for this adapter.)
856 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
860 if (find_802_11(&bdl) != -1) {
862 * We have an 802.11 DLT, so we can set monitor mode.
870 #endif /* BIOCGDLTLIST */
872 #elif defined(HAVE_BSD_IEEE80211)
875 ret = monitor_mode(p, 0);
876 if (ret == PCAP_ERROR_RFMON_NOTSUP)
877 return (0); /* not an error, just a "can't do" */
879 return (1); /* success */
887 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
892 * "ps_recv" counts packets handed to the filter, not packets
893 * that passed the filter. This includes packets later dropped
894 * because we ran out of buffer space.
896 * "ps_drop" counts packets dropped inside the BPF device
897 * because we ran out of buffer space. It doesn't count
898 * packets dropped by the interface driver. It counts
899 * only packets that passed the filter.
901 * Both statistics include packets not yet read from the kernel
902 * by libpcap, and thus not yet seen by the application.
904 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
905 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
906 pcap_strerror(errno));
910 ps->ps_recv = s.bs_recv;
911 ps->ps_drop = s.bs_drop;
917 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
919 struct pcap_bpf *pb = p->priv;
922 register u_char *bp, *ep;
927 #ifdef HAVE_ZEROCOPY_BPF
933 * Has "pcap_breakloop()" been called?
937 * Yes - clear the flag that indicates that it
938 * has, and return PCAP_ERROR_BREAK to indicate
939 * that we were told to break out of the loop.
942 return (PCAP_ERROR_BREAK);
947 * When reading without zero-copy from a file descriptor, we
948 * use a single buffer and return a length of data in the
949 * buffer. With zero-copy, we update the p->buffer pointer
950 * to point at whatever underlying buffer contains the next
951 * data and update cc to reflect the data found in the
954 #ifdef HAVE_ZEROCOPY_BPF
956 if (p->buffer != NULL)
958 i = pcap_next_zbuf(p, &cc);
966 cc = read(p->fd, p->buffer, p->bufsize);
969 /* Don't choke when we get ptraced */
978 * Sigh. More AIX wonderfulness.
980 * For some unknown reason the uiomove()
981 * operation in the bpf kernel extension
982 * used to copy the buffer into user
983 * space sometimes returns EFAULT. I have
984 * no idea why this is the case given that
985 * a kernel debugger shows the user buffer
986 * is correct. This problem appears to
987 * be mostly mitigated by the memset of
988 * the buffer before it is first used.
989 * Very strange.... Shaun Clowes
991 * In any case this means that we shouldn't
992 * treat EFAULT as a fatal error; as we
993 * don't have an API for returning
994 * a "some packets were dropped since
995 * the last packet you saw" indication,
996 * we just ignore EFAULT and keep reading.
1006 * The device on which we're capturing
1009 * XXX - we should really return
1010 * PCAP_ERROR_IFACE_NOT_UP, but
1011 * pcap_dispatch() etc. aren't
1012 * defined to retur that.
1014 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1015 "The interface went down");
1016 return (PCAP_ERROR);
1018 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
1020 * Due to a SunOS bug, after 2^31 bytes, the kernel
1021 * file offset overflows and read fails with EINVAL.
1022 * The lseek() to 0 will fix things.
1025 if (lseek(p->fd, 0L, SEEK_CUR) +
1027 (void)lseek(p->fd, 0L, SEEK_SET);
1033 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
1034 pcap_strerror(errno));
1035 return (PCAP_ERROR);
1037 bp = (u_char *)p->buffer;
1042 * Loop through each packet.
1045 #define bhp ((struct bpf_xhdr *)bp)
1047 #define bhp ((struct bpf_hdr *)bp)
1054 register u_int caplen, hdrlen;
1057 * Has "pcap_breakloop()" been called?
1058 * If so, return immediately - if we haven't read any
1059 * packets, clear the flag and return PCAP_ERROR_BREAK
1060 * to indicate that we were told to break out of the loop,
1061 * otherwise leave the flag set, so that the *next* call
1062 * will break out of the loop without having read any
1063 * packets, and return the number of packets we've
1066 if (p->break_loop) {
1070 * ep is set based on the return value of read(),
1071 * but read() from a BPF device doesn't necessarily
1072 * return a value that's a multiple of the alignment
1073 * value for BPF_WORDALIGN(). However, whenever we
1074 * increment bp, we round up the increment value by
1075 * a value rounded up by BPF_WORDALIGN(), so we
1076 * could increment bp past ep after processing the
1077 * last packet in the buffer.
1079 * We treat ep < bp as an indication that this
1080 * happened, and just set p->cc to 0.
1086 return (PCAP_ERROR_BREAK);
1091 caplen = bhp->bh_caplen;
1092 hdrlen = bhp->bh_hdrlen;
1093 datap = bp + hdrlen;
1095 * Short-circuit evaluation: if using BPF filter
1096 * in kernel, no need to do it now - we already know
1097 * the packet passed the filter.
1100 * Note: the filter code was generated assuming
1101 * that p->fddipad was the amount of padding
1102 * before the header, as that's what's required
1103 * in the kernel, so we run the filter before
1104 * skipping that padding.
1107 if (pb->filtering_in_kernel ||
1108 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1109 struct pcap_pkthdr pkthdr;
1113 bt.sec = bhp->bh_tstamp.bt_sec;
1114 bt.frac = bhp->bh_tstamp.bt_frac;
1115 if (p->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
1118 bintime2timespec(&bt, &ts);
1119 pkthdr.ts.tv_sec = ts.tv_sec;
1120 pkthdr.ts.tv_usec = ts.tv_nsec;
1124 bintime2timeval(&bt, &tv);
1125 pkthdr.ts.tv_sec = tv.tv_sec;
1126 pkthdr.ts.tv_usec = tv.tv_usec;
1129 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1132 * AIX's BPF returns seconds/nanoseconds time
1133 * stamps, not seconds/microseconds time stamps.
1135 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1137 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1139 #endif /* BIOCSTSTAMP */
1142 pkthdr.caplen = caplen - pad;
1145 if (bhp->bh_datalen > pad)
1146 pkthdr.len = bhp->bh_datalen - pad;
1151 pkthdr.caplen = caplen;
1152 pkthdr.len = bhp->bh_datalen;
1154 (*callback)(user, &pkthdr, datap);
1155 bp += BPF_WORDALIGN(caplen + hdrlen);
1156 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
1160 * See comment above about p->cc < 0.
1170 bp += BPF_WORDALIGN(caplen + hdrlen);
1179 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1183 ret = write(p->fd, buf, size);
1185 if (ret == -1 && errno == EAFNOSUPPORT) {
1187 * In Mac OS X, there's a bug wherein setting the
1188 * BIOCSHDRCMPLT flag causes writes to fail; see,
1191 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1193 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
1194 * assume it's due to that bug, and turn off that flag
1195 * and try again. If we succeed, it either means that
1196 * somebody applied the fix from that URL, or other patches
1199 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1201 * and are running a Darwin kernel with those fixes, or
1202 * that Apple fixed the problem in some OS X release.
1204 u_int spoof_eth_src = 0;
1206 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1207 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1208 "send: can't turn off BIOCSHDRCMPLT: %s",
1209 pcap_strerror(errno));
1210 return (PCAP_ERROR);
1214 * Now try the write again.
1216 ret = write(p->fd, buf, size);
1218 #endif /* __APPLE__ */
1220 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1221 pcap_strerror(errno));
1222 return (PCAP_ERROR);
1229 bpf_odminit(char *errbuf)
1233 if (odm_initialize() == -1) {
1234 if (odm_err_msg(odmerrno, &errstr) == -1)
1235 errstr = "Unknown error";
1236 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1237 "bpf_load: odm_initialize failed: %s",
1239 return (PCAP_ERROR);
1242 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1243 if (odm_err_msg(odmerrno, &errstr) == -1)
1244 errstr = "Unknown error";
1245 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1246 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1248 (void)odm_terminate();
1249 return (PCAP_ERROR);
1256 bpf_odmcleanup(char *errbuf)
1260 if (odm_unlock(odmlockid) == -1) {
1261 if (errbuf != NULL) {
1262 if (odm_err_msg(odmerrno, &errstr) == -1)
1263 errstr = "Unknown error";
1264 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1265 "bpf_load: odm_unlock failed: %s",
1268 return (PCAP_ERROR);
1271 if (odm_terminate() == -1) {
1272 if (errbuf != NULL) {
1273 if (odm_err_msg(odmerrno, &errstr) == -1)
1274 errstr = "Unknown error";
1275 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1276 "bpf_load: odm_terminate failed: %s",
1279 return (PCAP_ERROR);
1286 bpf_load(char *errbuf)
1290 int numminors, i, rc;
1293 struct bpf_config cfg_bpf;
1294 struct cfg_load cfg_ld;
1295 struct cfg_kmod cfg_km;
1298 * This is very very close to what happens in the real implementation
1299 * but I've fixed some (unlikely) bug situations.
1304 if (bpf_odminit(errbuf) == PCAP_ERROR)
1305 return (PCAP_ERROR);
1307 major = genmajor(BPF_NAME);
1309 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1310 "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1311 (void)bpf_odmcleanup(NULL);
1312 return (PCAP_ERROR);
1315 minors = getminor(major, &numminors, BPF_NAME);
1317 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1319 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1320 "bpf_load: genminor failed: %s",
1321 pcap_strerror(errno));
1322 (void)bpf_odmcleanup(NULL);
1323 return (PCAP_ERROR);
1327 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1328 return (PCAP_ERROR);
1330 rc = stat(BPF_NODE "0", &sbuf);
1331 if (rc == -1 && errno != ENOENT) {
1332 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1333 "bpf_load: can't stat %s: %s",
1334 BPF_NODE "0", pcap_strerror(errno));
1335 return (PCAP_ERROR);
1338 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1339 for (i = 0; i < BPF_MINORS; i++) {
1340 sprintf(buf, "%s%d", BPF_NODE, i);
1342 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1343 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1344 "bpf_load: can't mknod %s: %s",
1345 buf, pcap_strerror(errno));
1346 return (PCAP_ERROR);
1351 /* Check if the driver is loaded */
1352 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1354 sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1355 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1356 (cfg_ld.kmid == 0)) {
1357 /* Driver isn't loaded, load it now */
1358 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1359 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1360 "bpf_load: could not load driver: %s",
1362 return (PCAP_ERROR);
1366 /* Configure the driver */
1367 cfg_km.cmd = CFG_INIT;
1368 cfg_km.kmid = cfg_ld.kmid;
1369 cfg_km.mdilen = sizeof(cfg_bpf);
1370 cfg_km.mdiptr = (void *)&cfg_bpf;
1371 for (i = 0; i < BPF_MINORS; i++) {
1372 cfg_bpf.devno = domakedev(major, i);
1373 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1374 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1375 "bpf_load: could not configure driver: %s",
1377 return (PCAP_ERROR);
1388 * Undo any operations done when opening the device when necessary.
1391 pcap_cleanup_bpf(pcap_t *p)
1393 struct pcap_bpf *pb = p->priv;
1394 #ifdef HAVE_BSD_IEEE80211
1396 struct ifmediareq req;
1400 if (pb->must_do_on_close != 0) {
1402 * There's something we have to do when closing this
1405 #ifdef HAVE_BSD_IEEE80211
1406 if (pb->must_do_on_close & MUST_CLEAR_RFMON) {
1408 * We put the interface into rfmon mode;
1409 * take it out of rfmon mode.
1411 * XXX - if somebody else wants it in rfmon
1412 * mode, this code cannot know that, so it'll take
1413 * it out of rfmon mode.
1415 sock = socket(AF_INET, SOCK_DGRAM, 0);
1418 "Can't restore interface flags (socket() failed: %s).\n"
1419 "Please adjust manually.\n",
1422 memset(&req, 0, sizeof(req));
1423 strncpy(req.ifm_name, pb->device,
1424 sizeof(req.ifm_name));
1425 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1427 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1428 "Please adjust manually.\n",
1431 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1433 * Rfmon mode is currently on;
1436 memset(&ifr, 0, sizeof(ifr));
1437 (void)strncpy(ifr.ifr_name,
1439 sizeof(ifr.ifr_name));
1441 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1442 if (ioctl(sock, SIOCSIFMEDIA,
1445 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1446 "Please adjust manually.\n",
1454 #endif /* HAVE_BSD_IEEE80211 */
1456 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1458 * Attempt to destroy the usbusN interface that we created.
1460 if (pb->must_do_on_close & MUST_DESTROY_USBUS) {
1461 if (if_nametoindex(pb->device) > 0) {
1464 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1466 strlcpy(ifr.ifr_name, pb->device,
1467 sizeof(ifr.ifr_name));
1468 ioctl(s, SIOCIFDESTROY, &ifr);
1473 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1475 * Take this pcap out of the list of pcaps for which we
1476 * have to take the interface out of some mode.
1478 pcap_remove_from_pcaps_to_close(p);
1479 pb->must_do_on_close = 0;
1482 #ifdef HAVE_ZEROCOPY_BPF
1485 * Delete the mappings. Note that p->buffer gets
1486 * initialized to one of the mmapped regions in
1487 * this case, so do not try and free it directly;
1488 * null it out so that pcap_cleanup_live_common()
1489 * doesn't try to free it.
1491 if (pb->zbuf1 != MAP_FAILED && pb->zbuf1 != NULL)
1492 (void) munmap(pb->zbuf1, pb->zbufsize);
1493 if (pb->zbuf2 != MAP_FAILED && pb->zbuf2 != NULL)
1494 (void) munmap(pb->zbuf2, pb->zbufsize);
1499 if (pb->device != NULL) {
1503 pcap_cleanup_live_common(p);
1507 check_setif_failure(pcap_t *p, int error)
1515 if (error == ENXIO) {
1517 * No such device exists.
1520 if (p->opt.rfmon && strncmp(p->opt.device, "wlt", 3) == 0) {
1522 * Monitor mode was requested, and we're trying
1523 * to open a "wltN" device. Assume that this
1524 * is 10.4 and that we were asked to open an
1525 * "enN" device; if that device exists, return
1526 * "monitor mode not supported on the device".
1528 fd = socket(AF_INET, SOCK_DGRAM, 0);
1530 strlcpy(ifr.ifr_name, "en",
1531 sizeof(ifr.ifr_name));
1532 strlcat(ifr.ifr_name, p->opt.device + 3,
1533 sizeof(ifr.ifr_name));
1534 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1536 * We assume this failed because
1537 * the underlying device doesn't
1540 err = PCAP_ERROR_NO_SUCH_DEVICE;
1541 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1542 "SIOCGIFFLAGS on %s failed: %s",
1543 ifr.ifr_name, pcap_strerror(errno));
1546 * The underlying "enN" device
1547 * exists, but there's no
1548 * corresponding "wltN" device;
1549 * that means that the "enN"
1550 * device doesn't support
1551 * monitor mode, probably because
1552 * it's an Ethernet device rather
1553 * than a wireless device.
1555 err = PCAP_ERROR_RFMON_NOTSUP;
1560 * We can't find out whether there's
1561 * an underlying "enN" device, so
1562 * just report "no such device".
1564 err = PCAP_ERROR_NO_SUCH_DEVICE;
1565 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1566 "socket() failed: %s",
1567 pcap_strerror(errno));
1575 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
1576 pcap_strerror(errno));
1577 return (PCAP_ERROR_NO_SUCH_DEVICE);
1578 } else if (errno == ENETDOWN) {
1580 * Return a "network down" indication, so that
1581 * the application can report that rather than
1582 * saying we had a mysterious failure and
1583 * suggest that they report a problem to the
1584 * libpcap developers.
1586 return (PCAP_ERROR_IFACE_NOT_UP);
1589 * Some other error; fill in the error string, and
1590 * return PCAP_ERROR.
1592 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1593 p->opt.device, pcap_strerror(errno));
1594 return (PCAP_ERROR);
1599 * Default capture buffer size.
1600 * 32K isn't very much for modern machines with fast networks; we
1601 * pick .5M, as that's the maximum on at least some systems with BPF.
1603 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1604 * read failures under stress, so we leave it as 32K; yet another
1605 * place where AIX's BPF is broken.
1608 #define DEFAULT_BUFSIZE 32768
1610 #define DEFAULT_BUFSIZE 524288
1614 pcap_activate_bpf(pcap_t *p)
1616 struct pcap_bpf *pb = p->priv;
1618 #ifdef HAVE_BSD_IEEE80211
1625 char *ifrname = ifr.lifr_name;
1626 const size_t ifnamsiz = sizeof(ifr.lifr_name);
1629 char *ifrname = ifr.ifr_name;
1630 const size_t ifnamsiz = sizeof(ifr.ifr_name);
1632 struct bpf_version bv;
1635 char *wltdev = NULL;
1638 struct bpf_dltlist bdl;
1639 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1642 #endif /* BIOCGDLTLIST */
1643 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1644 u_int spoof_eth_src = 1;
1647 struct bpf_insn total_insn;
1648 struct bpf_program total_prog;
1649 struct utsname osinfo;
1652 if (strstr(device, "dag")) {
1653 return dag_open_live(device, snaplen, promisc, to_ms, ebuf);
1655 #endif /* HAVE_DAG_API */
1658 memset(&bdl, 0, sizeof(bdl));
1659 int have_osinfo = 0;
1660 #ifdef HAVE_ZEROCOPY_BPF
1662 u_int bufmode, zbufmax;
1665 fd = bpf_open(p->errbuf);
1673 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1674 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1675 pcap_strerror(errno));
1676 status = PCAP_ERROR;
1679 if (bv.bv_major != BPF_MAJOR_VERSION ||
1680 bv.bv_minor < BPF_MINOR_VERSION) {
1681 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1682 "kernel bpf filter out of date");
1683 status = PCAP_ERROR;
1687 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1689 * Retrieve the zoneid of the zone we are currently executing in.
1691 if ((ifr.lifr_zoneid = getzoneid()) == -1) {
1692 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "getzoneid(): %s",
1693 pcap_strerror(errno));
1694 status = PCAP_ERROR;
1698 * Check if the given source datalink name has a '/' separated
1699 * zonename prefix string. The zonename prefixed source datalink can
1700 * be used by pcap consumers in the Solaris global zone to capture
1701 * traffic on datalinks in non-global zones. Non-global zones
1702 * do not have access to datalinks outside of their own namespace.
1704 if ((zonesep = strchr(p->opt.device, '/')) != NULL) {
1705 char path_zname[ZONENAME_MAX];
1709 if (ifr.lifr_zoneid != GLOBAL_ZONEID) {
1710 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1711 "zonename/linkname only valid in global zone.");
1712 status = PCAP_ERROR;
1715 znamelen = zonesep - p->opt.device;
1716 (void) strlcpy(path_zname, p->opt.device, znamelen + 1);
1717 ifr.lifr_zoneid = getzoneidbyname(path_zname);
1718 if (ifr.lifr_zoneid == -1) {
1719 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1720 "getzoneidbyname(%s): %s", path_zname,
1721 pcap_strerror(errno));
1722 status = PCAP_ERROR;
1725 lnamep = strdup(zonesep + 1);
1726 if (lnamep == NULL) {
1727 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1728 pcap_strerror(errno));
1729 status = PCAP_ERROR;
1732 free(p->opt.device);
1733 p->opt.device = lnamep;
1737 pb->device = strdup(p->opt.device);
1738 if (pb->device == NULL) {
1739 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1740 pcap_strerror(errno));
1741 status = PCAP_ERROR;
1746 * Try finding a good size for the buffer; 32768 may be too
1747 * big, so keep cutting it in half until we find a size
1748 * that works, or run out of sizes to try. If the default
1749 * is larger, don't make it smaller.
1751 * XXX - there should be a user-accessible hook to set the
1752 * initial buffer size.
1753 * Attempt to find out the version of the OS on which we're running.
1755 if (uname(&osinfo) == 0)
1760 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1761 * of why we check the version number.
1766 * We assume osinfo.sysname is "Darwin", because
1767 * __APPLE__ is defined. We just check the version.
1769 if (osinfo.release[0] < '8' &&
1770 osinfo.release[1] == '.') {
1772 * 10.3 (Darwin 7.x) or earlier.
1774 status = PCAP_ERROR_RFMON_NOTSUP;
1777 if (osinfo.release[0] == '8' &&
1778 osinfo.release[1] == '.') {
1780 * 10.4 (Darwin 8.x). s/en/wlt/
1782 if (strncmp(p->opt.device, "en", 2) != 0) {
1784 * Not an enN device; check
1785 * whether the device even exists.
1787 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1790 p->opt.device, ifnamsiz);
1791 if (ioctl(sockfd, SIOCGIFFLAGS,
1792 (char *)&ifr) < 0) {
1800 status = PCAP_ERROR_NO_SUCH_DEVICE;
1801 pcap_snprintf(p->errbuf,
1803 "SIOCGIFFLAGS failed: %s",
1804 pcap_strerror(errno));
1806 status = PCAP_ERROR_RFMON_NOTSUP;
1810 * We can't find out whether
1811 * the device exists, so just
1812 * report "no such device".
1814 status = PCAP_ERROR_NO_SUCH_DEVICE;
1815 pcap_snprintf(p->errbuf,
1817 "socket() failed: %s",
1818 pcap_strerror(errno));
1822 wltdev = malloc(strlen(p->opt.device) + 2);
1823 if (wltdev == NULL) {
1824 (void)pcap_snprintf(p->errbuf,
1825 PCAP_ERRBUF_SIZE, "malloc: %s",
1826 pcap_strerror(errno));
1827 status = PCAP_ERROR;
1830 strcpy(wltdev, "wlt");
1831 strcat(wltdev, p->opt.device + 2);
1832 free(p->opt.device);
1833 p->opt.device = wltdev;
1836 * Everything else is 10.5 or later; for those,
1837 * we just open the enN device, and set the DLT.
1841 #endif /* __APPLE__ */
1844 * If this is FreeBSD, and the device name begins with "usbus",
1845 * try to create the interface if it's not available.
1847 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1848 if (strncmp(p->opt.device, usbus_prefix, USBUS_PREFIX_LEN) == 0) {
1850 * Do we already have an interface with that name?
1852 if (if_nametoindex(p->opt.device) == 0) {
1854 * No. We need to create it, and, if we
1855 * succeed, remember that we should destroy
1856 * it when the pcap_t is closed.
1861 * Open a socket to use for ioctls to
1862 * create the interface.
1864 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1866 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1867 "Can't open socket: %s",
1868 pcap_strerror(errno));
1869 status = PCAP_ERROR;
1874 * If we haven't already done so, arrange to have
1875 * "pcap_close_all()" called when we exit.
1877 if (!pcap_do_addexit(p)) {
1879 * "atexit()" failed; don't create the
1880 * interface, just give up.
1882 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1885 status = PCAP_ERROR;
1890 * Create the interface.
1892 strlcpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
1893 if (ioctl(s, SIOCIFCREATE2, &ifr) < 0) {
1894 if (errno == EINVAL) {
1895 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1896 "Invalid USB bus interface %s",
1899 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1900 "Can't create interface for %s: %s",
1901 p->opt.device, pcap_strerror(errno));
1904 status = PCAP_ERROR;
1909 * Make sure we clean this up when we close.
1911 pb->must_do_on_close |= MUST_DESTROY_USBUS;
1914 * Add this to the list of pcaps to close when we exit.
1916 pcap_add_to_pcaps_to_close(p);
1919 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1921 #ifdef HAVE_ZEROCOPY_BPF
1923 * If the BPF extension to set buffer mode is present, try setting
1924 * the mode to zero-copy. If that fails, use regular buffering. If
1925 * it succeeds but other setup fails, return an error to the user.
1927 bufmode = BPF_BUFMODE_ZBUF;
1928 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1930 * We have zerocopy BPF; use it.
1935 * How to pick a buffer size: first, query the maximum buffer
1936 * size supported by zero-copy. This also lets us quickly
1937 * determine whether the kernel generally supports zero-copy.
1938 * Then, if a buffer size was specified, use that, otherwise
1939 * query the default buffer size, which reflects kernel
1940 * policy for a desired default. Round to the nearest page
1943 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1944 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1945 pcap_strerror(errno));
1946 status = PCAP_ERROR;
1950 if (p->opt.buffer_size != 0) {
1952 * A buffer size was explicitly specified; use it.
1954 v = p->opt.buffer_size;
1956 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1957 v < DEFAULT_BUFSIZE)
1958 v = DEFAULT_BUFSIZE;
1961 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
1963 pb->zbufsize = roundup(v, getpagesize());
1964 if (pb->zbufsize > zbufmax)
1965 pb->zbufsize = zbufmax;
1966 pb->zbuf1 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1968 pb->zbuf2 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1970 if (pb->zbuf1 == MAP_FAILED || pb->zbuf2 == MAP_FAILED) {
1971 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1972 pcap_strerror(errno));
1973 status = PCAP_ERROR;
1976 memset(&bz, 0, sizeof(bz)); /* bzero() deprecated, replaced with memset() */
1977 bz.bz_bufa = pb->zbuf1;
1978 bz.bz_bufb = pb->zbuf2;
1979 bz.bz_buflen = pb->zbufsize;
1980 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1981 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1982 pcap_strerror(errno));
1983 status = PCAP_ERROR;
1986 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
1987 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1988 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1989 p->opt.device, pcap_strerror(errno));
1990 status = PCAP_ERROR;
1993 v = pb->zbufsize - sizeof(struct bpf_zbuf_header);
1998 * We don't have zerocopy BPF.
1999 * Set the buffer size.
2001 if (p->opt.buffer_size != 0) {
2003 * A buffer size was explicitly specified; use it.
2005 if (ioctl(fd, BIOCSBLEN,
2006 (caddr_t)&p->opt.buffer_size) < 0) {
2007 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2008 "BIOCSBLEN: %s: %s", p->opt.device,
2009 pcap_strerror(errno));
2010 status = PCAP_ERROR;
2015 * Now bind to the device.
2017 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
2019 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
2021 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
2024 status = check_setif_failure(p, errno);
2029 * No buffer size was explicitly specified.
2031 * Try finding a good size for the buffer;
2032 * DEFAULT_BUFSIZE may be too big, so keep
2033 * cutting it in half until we find a size
2034 * that works, or run out of sizes to try.
2035 * If the default is larger, don't make it smaller.
2037 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
2038 v < DEFAULT_BUFSIZE)
2039 v = DEFAULT_BUFSIZE;
2040 for ( ; v != 0; v >>= 1) {
2042 * Ignore the return value - this is because the
2043 * call fails on BPF systems that don't have
2044 * kernel malloc. And if the call fails, it's
2045 * no big deal, we just continue to use the
2046 * standard buffer size.
2048 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
2050 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
2052 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
2054 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
2056 break; /* that size worked; we're done */
2058 if (errno != ENOBUFS) {
2059 status = check_setif_failure(p, errno);
2065 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2066 "BIOCSBLEN: %s: No buffer size worked",
2068 status = PCAP_ERROR;
2075 /* Get the data link layer type. */
2076 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
2077 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
2078 pcap_strerror(errno));
2079 status = PCAP_ERROR;
2085 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
2108 * We don't know what to map this to yet.
2110 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
2112 status = PCAP_ERROR;
2116 #if _BSDI_VERSION - 0 >= 199510
2117 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
2132 case 12: /*DLT_C_HDLC*/
2140 * We know the default link type -- now determine all the DLTs
2141 * this interface supports. If this fails with EINVAL, it's
2142 * not fatal; we just don't get to use the feature later.
2144 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
2145 status = PCAP_ERROR;
2148 p->dlt_count = bdl.bfl_len;
2149 p->dlt_list = bdl.bfl_list;
2153 * Monitor mode fun, continued.
2155 * For 10.5 and, we're assuming, later releases, as noted above,
2156 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
2157 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
2158 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
2161 * Therefore, if the user asked for monitor mode, we filter out
2162 * the DLT_EN10MB value, as you can't get that in monitor mode,
2163 * and, if the user didn't ask for monitor mode, we filter out
2164 * the 802.11 DLT_ values, because selecting those will turn
2165 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
2166 * radio DLT_ value is offered, we try to select that, otherwise
2167 * we try to select DLT_IEEE802_11.
2170 if (isdigit((unsigned)osinfo.release[0]) &&
2171 (osinfo.release[0] == '9' ||
2172 isdigit((unsigned)osinfo.release[1]))) {
2174 * 10.5 (Darwin 9.x), or later.
2176 new_dlt = find_802_11(&bdl);
2177 if (new_dlt != -1) {
2179 * We have at least one 802.11 DLT_ value,
2180 * so this is an 802.11 interface.
2181 * new_dlt is the best of the 802.11
2182 * DLT_ values in the list.
2186 * Our caller wants monitor mode.
2187 * Purge DLT_EN10MB from the list
2188 * of link-layer types, as selecting
2189 * it will keep monitor mode off.
2194 * If the new mode we want isn't
2195 * the default mode, attempt to
2196 * select the new mode.
2198 if ((u_int)new_dlt != v) {
2199 if (ioctl(p->fd, BIOCSDLT,
2211 * Our caller doesn't want
2212 * monitor mode. Unless this
2213 * is being done by pcap_open_live(),
2214 * purge the 802.11 link-layer types
2215 * from the list, as selecting
2216 * one of them will turn monitor
2225 * The caller requested monitor
2226 * mode, but we have no 802.11
2227 * link-layer types, so they
2230 status = PCAP_ERROR_RFMON_NOTSUP;
2236 #elif defined(HAVE_BSD_IEEE80211)
2238 * *BSD with the new 802.11 ioctls.
2239 * Do we want monitor mode?
2243 * Try to put the interface into monitor mode.
2245 retv = monitor_mode(p, 1);
2255 * We're in monitor mode.
2256 * Try to find the best 802.11 DLT_ value and, if we
2257 * succeed, try to switch to that mode if we're not
2258 * already in that mode.
2260 new_dlt = find_802_11(&bdl);
2261 if (new_dlt != -1) {
2263 * We have at least one 802.11 DLT_ value.
2264 * new_dlt is the best of the 802.11
2265 * DLT_ values in the list.
2267 * If the new mode we want isn't the default mode,
2268 * attempt to select the new mode.
2270 if ((u_int)new_dlt != v) {
2271 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
2273 * We succeeded; make this the
2281 #endif /* various platforms */
2282 #endif /* BIOCGDLTLIST */
2285 * If this is an Ethernet device, and we don't have a DLT_ list,
2286 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
2287 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2288 * do, but there's not much we can do about that without finding
2289 * some other way of determining whether it's an Ethernet or 802.11
2292 if (v == DLT_EN10MB && p->dlt_count == 0) {
2293 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2295 * If that fails, just leave the list empty.
2297 if (p->dlt_list != NULL) {
2298 p->dlt_list[0] = DLT_EN10MB;
2299 p->dlt_list[1] = DLT_DOCSIS;
2305 p->fddipad = PCAP_FDDIPAD;
2311 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2313 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2314 * the link-layer source address isn't forcibly overwritten.
2315 * (Should we ignore errors? Should we do this only if
2316 * we're open for writing?)
2318 * XXX - I seem to remember some packet-sending bug in some
2319 * BSDs - check CVS log for "bpf.c"?
2321 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2322 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2323 "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
2324 status = PCAP_ERROR;
2329 #ifdef HAVE_ZEROCOPY_BPF
2331 * In zero-copy mode, we just use the timeout in select().
2332 * XXX - what if we're in non-blocking mode and the *application*
2333 * is using select() or poll() or kqueues or....?
2335 if (p->opt.timeout && !pb->zerocopy) {
2337 if (p->opt.timeout) {
2340 * XXX - is this seconds/nanoseconds in AIX?
2341 * (Treating it as such doesn't fix the timeout
2342 * problem described below.)
2344 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2345 * 64-bit userland - it takes, as an argument, a
2346 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2347 * and tv_usec, rather than a "struct timeval".
2349 * If this platform defines "struct BPF_TIMEVAL",
2350 * we check whether the structure size in BIOCSRTIMEOUT
2351 * is that of a "struct timeval" and, if not, we use
2352 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2353 * (That way, if the bug is fixed in a future release,
2354 * we will still do the right thing.)
2357 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2358 struct BPF_TIMEVAL bpf_to;
2360 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2361 bpf_to.tv_sec = p->opt.timeout / 1000;
2362 bpf_to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2363 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2364 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2365 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2366 status = PCAP_ERROR;
2371 to.tv_sec = p->opt.timeout / 1000;
2372 to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2373 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2374 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2375 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2376 status = PCAP_ERROR;
2379 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2384 #ifdef BIOCIMMEDIATE
2386 * Darren Reed notes that
2388 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2389 * timeout appears to be ignored and it waits until the buffer
2390 * is filled before returning. The result of not having it
2391 * set is almost worse than useless if your BPF filter
2392 * is reducing things to only a few packets (i.e. one every
2395 * so we always turn BIOCIMMEDIATE mode on if this is AIX.
2397 * For other platforms, we don't turn immediate mode on by default,
2398 * as that would mean we get woken up for every packet, which
2399 * probably isn't what you want for a packet sniffer.
2401 * We set immediate mode if the caller requested it by calling
2402 * pcap_set_immediate() before calling pcap_activate().
2405 if (p->opt.immediate) {
2408 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2409 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2410 "BIOCIMMEDIATE: %s", pcap_strerror(errno));
2411 status = PCAP_ERROR;
2417 #else /* BIOCIMMEDIATE */
2418 if (p->opt.immediate) {
2420 * We don't support immediate mode. Fail.
2422 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Immediate mode not supported");
2423 status = PCAP_ERROR;
2426 #endif /* BIOCIMMEDIATE */
2428 if (p->opt.promisc) {
2429 /* set promiscuous mode, just warn if it fails */
2430 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2431 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
2432 pcap_strerror(errno));
2433 status = PCAP_WARNING_PROMISC_NOTSUP;
2439 if (ioctl(p->fd, BIOCSTSTAMP, &v) < 0) {
2440 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSTSTAMP: %s",
2441 pcap_strerror(errno));
2442 status = PCAP_ERROR;
2445 #endif /* BIOCSTSTAMP */
2447 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2448 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
2449 pcap_strerror(errno));
2450 status = PCAP_ERROR;
2454 #ifdef HAVE_ZEROCOPY_BPF
2455 if (!pb->zerocopy) {
2457 p->buffer = malloc(p->bufsize);
2458 if (p->buffer == NULL) {
2459 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2460 pcap_strerror(errno));
2461 status = PCAP_ERROR;
2465 /* For some strange reason this seems to prevent the EFAULT
2466 * problems we have experienced from AIX BPF. */
2467 memset(p->buffer, 0x0, p->bufsize);
2469 #ifdef HAVE_ZEROCOPY_BPF
2474 * If there's no filter program installed, there's
2475 * no indication to the kernel of what the snapshot
2476 * length should be, so no snapshotting is done.
2478 * Therefore, when we open the device, we install
2479 * an "accept everything" filter with the specified
2482 total_insn.code = (u_short)(BPF_RET | BPF_K);
2485 total_insn.k = p->snapshot;
2487 total_prog.bf_len = 1;
2488 total_prog.bf_insns = &total_insn;
2489 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2490 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2491 pcap_strerror(errno));
2492 status = PCAP_ERROR;
2497 * On most BPF platforms, either you can do a "select()" or
2498 * "poll()" on a BPF file descriptor and it works correctly,
2499 * or you can do it and it will return "readable" if the
2500 * hold buffer is full but not if the timeout expires *and*
2501 * a non-blocking read will, if the hold buffer is empty
2502 * but the store buffer isn't empty, rotate the buffers
2503 * and return what packets are available.
2505 * In the latter case, the fact that a non-blocking read
2506 * will give you the available packets means you can work
2507 * around the failure of "select()" and "poll()" to wake up
2508 * and return "readable" when the timeout expires by using
2509 * the timeout as the "select()" or "poll()" timeout, putting
2510 * the BPF descriptor into non-blocking mode, and read from
2511 * it regardless of whether "select()" reports it as readable
2514 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2515 * won't wake up and return "readable" if the timer expires
2516 * and non-blocking reads return EWOULDBLOCK if the hold
2517 * buffer is empty, even if the store buffer is non-empty.
2519 * This means the workaround in question won't work.
2521 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2522 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2523 * here". On all other BPF platforms, we set it to the FD for
2524 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2525 * read will, if the hold buffer is empty and the store buffer
2526 * isn't empty, rotate the buffers and return what packets are
2527 * there (and in sufficiently recent versions of OpenBSD
2528 * "select()" and "poll()" should work correctly).
2530 * XXX - what about AIX?
2532 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2535 * We can check what OS this is.
2537 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2538 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2539 strncmp(osinfo.release, "4.4-", 4) == 0)
2540 p->selectable_fd = -1;
2544 p->read_op = pcap_read_bpf;
2545 p->inject_op = pcap_inject_bpf;
2546 p->setfilter_op = pcap_setfilter_bpf;
2547 p->setdirection_op = pcap_setdirection_bpf;
2548 p->set_datalink_op = pcap_set_datalink_bpf;
2549 p->getnonblock_op = pcap_getnonblock_bpf;
2550 p->setnonblock_op = pcap_setnonblock_bpf;
2551 p->stats_op = pcap_stats_bpf;
2552 p->cleanup_op = pcap_cleanup_bpf;
2556 pcap_cleanup_bpf(p);
2561 * Not all interfaces can be bound to by BPF, so try to bind to
2562 * the specified interface; return 0 if we fail with
2563 * PCAP_ERROR_NO_SUCH_DEVICE (which means we got an ENXIO when we tried
2564 * to bind, which means this interface isn't in the list of interfaces
2565 * attached to BPF) and 1 otherwise.
2568 check_bpf_bindable(const char *name)
2571 char errbuf[PCAP_ERRBUF_SIZE];
2573 fd = bpf_open_and_bind(name, errbuf);
2576 * Error - was it PCAP_ERROR_NO_SUCH_DEVICE?
2578 if (fd == PCAP_ERROR_NO_SUCH_DEVICE) {
2580 * Yes, so we can't bind to this because it's
2581 * not something supported by BPF.
2586 * No, so we don't know whether it's supported or not;
2587 * say it is, so that the user can at least try to
2588 * open it and report the error (which is probably
2589 * "you don't have permission to open BPF devices";
2590 * reporting those interfaces means users will ask
2591 * "why am I getting a permissions error when I try
2592 * to capture" rather than "why am I not seeing any
2593 * interfaces", making the underlying problem clearer).
2605 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
2607 finddevs_usb(pcap_if_t **alldevsp, char *errbuf)
2610 struct dirent *usbitem;
2615 * We might have USB sniffing support, so try looking for USB
2618 * We want to report a usbusN device for each USB bus, but
2619 * usbusN interfaces might, or might not, exist for them -
2620 * we create one if there isn't already one.
2622 * So, instead, we look in /dev/usb for all buses and create
2623 * a "usbusN" device for each one.
2625 usbdir = opendir("/dev/usb");
2626 if (usbdir == NULL) {
2634 * Leave enough room for a 32-bit (10-digit) bus number.
2635 * Yes, that's overkill, but we won't be using
2636 * the buffer very long.
2638 name_max = USBUS_PREFIX_LEN + 10 + 1;
2639 name = malloc(name_max);
2644 while ((usbitem = readdir(usbdir)) != NULL) {
2649 if (strcmp(usbitem->d_name, ".") == 0 ||
2650 strcmp(usbitem->d_name, "..") == 0) {
2656 p = strchr(usbitem->d_name, '.');
2659 busnumlen = p - usbitem->d_name;
2660 memcpy(name, usbus_prefix, USBUS_PREFIX_LEN);
2661 memcpy(name + USBUS_PREFIX_LEN, usbitem->d_name, busnumlen);
2662 *(name + USBUS_PREFIX_LEN + busnumlen) = '\0';
2663 err = pcap_add_if(alldevsp, name, PCAP_IF_UP, NULL, errbuf);
2677 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2680 * Get the list of regular interfaces first.
2682 if (pcap_findalldevs_interfaces(alldevsp, errbuf, check_bpf_bindable) == -1)
2683 return (-1); /* failure */
2685 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
2686 if (finddevs_usb(alldevsp, errbuf) == -1)
2693 #ifdef HAVE_BSD_IEEE80211
2695 monitor_mode(pcap_t *p, int set)
2697 struct pcap_bpf *pb = p->priv;
2699 struct ifmediareq req;
2700 IFM_ULIST_TYPE *media_list;
2705 sock = socket(AF_INET, SOCK_DGRAM, 0);
2707 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2708 pcap_strerror(errno));
2709 return (PCAP_ERROR);
2712 memset(&req, 0, sizeof req);
2713 strncpy(req.ifm_name, p->opt.device, sizeof req.ifm_name);
2716 * Find out how many media types we have.
2718 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2720 * Can't get the media types.
2726 * There's no such device.
2729 return (PCAP_ERROR_NO_SUCH_DEVICE);
2733 * Interface doesn't support SIOC{G,S}IFMEDIA.
2736 return (PCAP_ERROR_RFMON_NOTSUP);
2739 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2740 "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
2742 return (PCAP_ERROR);
2745 if (req.ifm_count == 0) {
2750 return (PCAP_ERROR_RFMON_NOTSUP);
2754 * Allocate a buffer to hold all the media types, and
2755 * get the media types.
2757 media_list = malloc(req.ifm_count * sizeof(*media_list));
2758 if (media_list == NULL) {
2759 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2760 pcap_strerror(errno));
2762 return (PCAP_ERROR);
2764 req.ifm_ulist = media_list;
2765 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2766 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2767 pcap_strerror(errno));
2770 return (PCAP_ERROR);
2774 * Look for an 802.11 "automatic" media type.
2775 * We assume that all 802.11 adapters have that media type,
2776 * and that it will carry the monitor mode supported flag.
2779 for (i = 0; i < req.ifm_count; i++) {
2780 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2781 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2782 /* OK, does it do monitor mode? */
2783 if (media_list[i] & IFM_IEEE80211_MONITOR) {
2792 * This adapter doesn't support monitor mode.
2795 return (PCAP_ERROR_RFMON_NOTSUP);
2800 * Don't just check whether we can enable monitor mode,
2801 * do so, if it's not already enabled.
2803 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2805 * Monitor mode isn't currently on, so turn it on,
2806 * and remember that we should turn it off when the
2811 * If we haven't already done so, arrange to have
2812 * "pcap_close_all()" called when we exit.
2814 if (!pcap_do_addexit(p)) {
2816 * "atexit()" failed; don't put the interface
2817 * in monitor mode, just give up.
2820 return (PCAP_ERROR);
2822 memset(&ifr, 0, sizeof(ifr));
2823 (void)strncpy(ifr.ifr_name, p->opt.device,
2824 sizeof(ifr.ifr_name));
2825 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2826 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2827 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2828 "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2830 return (PCAP_ERROR);
2833 pb->must_do_on_close |= MUST_CLEAR_RFMON;
2836 * Add this to the list of pcaps to close when we exit.
2838 pcap_add_to_pcaps_to_close(p);
2843 #endif /* HAVE_BSD_IEEE80211 */
2845 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2847 * Check whether we have any 802.11 link-layer types; return the best
2848 * of the 802.11 link-layer types if we find one, and return -1
2851 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2852 * best 802.11 link-layer type; any of the other 802.11-plus-radio
2853 * headers are second-best; 802.11 with no radio information is
2857 find_802_11(struct bpf_dltlist *bdlp)
2863 * Scan the list of DLT_ values, looking for 802.11 values,
2864 * and, if we find any, choose the best of them.
2867 for (i = 0; i < bdlp->bfl_len; i++) {
2868 switch (bdlp->bfl_list[i]) {
2870 case DLT_IEEE802_11:
2872 * 802.11, but no radio.
2874 * Offer this, and select it as the new mode
2875 * unless we've already found an 802.11
2876 * header with radio information.
2879 new_dlt = bdlp->bfl_list[i];
2882 case DLT_PRISM_HEADER:
2883 case DLT_AIRONET_HEADER:
2884 case DLT_IEEE802_11_RADIO_AVS:
2886 * 802.11 with radio, but not radiotap.
2888 * Offer this, and select it as the new mode
2889 * unless we've already found the radiotap DLT_.
2891 if (new_dlt != DLT_IEEE802_11_RADIO)
2892 new_dlt = bdlp->bfl_list[i];
2895 case DLT_IEEE802_11_RADIO:
2897 * 802.11 with radiotap.
2899 * Offer this, and select it as the new mode.
2901 new_dlt = bdlp->bfl_list[i];
2914 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2916 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
2918 * Remove DLT_EN10MB from the list of DLT_ values, as we're in monitor mode,
2919 * and DLT_EN10MB isn't supported in monitor mode.
2922 remove_en(pcap_t *p)
2927 * Scan the list of DLT_ values and discard DLT_EN10MB.
2930 for (i = 0; i < p->dlt_count; i++) {
2931 switch (p->dlt_list[i]) {
2935 * Don't offer this one.
2941 * Just copy this mode over.
2947 * Copy this DLT_ value to its new position.
2949 p->dlt_list[j] = p->dlt_list[i];
2954 * Set the DLT_ count to the number of entries we copied.
2960 * Remove 802.11 link-layer types from the list of DLT_ values, as
2961 * we're not in monitor mode, and those DLT_ values will switch us
2965 remove_802_11(pcap_t *p)
2970 * Scan the list of DLT_ values and discard 802.11 values.
2973 for (i = 0; i < p->dlt_count; i++) {
2974 switch (p->dlt_list[i]) {
2976 case DLT_IEEE802_11:
2977 case DLT_PRISM_HEADER:
2978 case DLT_AIRONET_HEADER:
2979 case DLT_IEEE802_11_RADIO:
2980 case DLT_IEEE802_11_RADIO_AVS:
2982 * 802.11. Don't offer this one.
2988 * Just copy this mode over.
2994 * Copy this DLT_ value to its new position.
2996 p->dlt_list[j] = p->dlt_list[i];
3001 * Set the DLT_ count to the number of entries we copied.
3005 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
3008 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
3010 struct pcap_bpf *pb = p->priv;
3013 * Free any user-mode filter we might happen to have installed.
3015 pcap_freecode(&p->fcode);
3018 * Try to install the kernel filter.
3020 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
3024 pb->filtering_in_kernel = 1; /* filtering in the kernel */
3027 * Discard any previously-received packets, as they might
3028 * have passed whatever filter was formerly in effect, but
3029 * might not pass this filter (BIOCSETF discards packets
3030 * buffered in the kernel, so you can lose packets in any
3040 * If it failed with EINVAL, that's probably because the program
3041 * is invalid or too big. Validate it ourselves; if we like it
3042 * (we currently allow backward branches, to support protochain),
3043 * run it in userland. (There's no notion of "too big" for
3046 * Otherwise, just give up.
3047 * XXX - if the copy of the program into the kernel failed,
3048 * we will get EINVAL rather than, say, EFAULT on at least
3051 if (errno != EINVAL) {
3052 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
3053 pcap_strerror(errno));
3058 * install_bpf_program() validates the program.
3060 * XXX - what if we already have a filter in the kernel?
3062 if (install_bpf_program(p, fp) < 0)
3064 pb->filtering_in_kernel = 0; /* filtering in userland */
3069 * Set direction flag: Which packets do we accept on a forwarding
3070 * single device? IN, OUT or both?
3073 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3075 #if defined(BIOCSDIRECTION)
3078 direction = (d == PCAP_D_IN) ? BPF_D_IN :
3079 ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
3080 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
3081 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3082 "Cannot set direction to %s: %s",
3083 (d == PCAP_D_IN) ? "PCAP_D_IN" :
3084 ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
3089 #elif defined(BIOCSSEESENT)
3093 * We don't support PCAP_D_OUT.
3095 if (d == PCAP_D_OUT) {
3096 pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3097 "Setting direction to PCAP_D_OUT is not supported on BPF");
3101 seesent = (d == PCAP_D_INOUT);
3102 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
3103 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3104 "Cannot set direction to %s: %s",
3105 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
3111 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3112 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
3118 pcap_set_datalink_bpf(pcap_t *p, int dlt)
3121 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
3122 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3123 "Cannot set DLT %d: %s", dlt, strerror(errno));