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.
26 #include <sys/param.h> /* optionally get BSD define */
27 #include <sys/socket.h>
30 * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
32 * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
33 * at least on *BSD and macOS, it also defines various SIOC ioctls -
34 * we could include <sys/sockio.h>, but if we're already including
35 * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
36 * there's not much point in doing so.
38 * If we have <sys/ioccom.h>, we include it as well, to handle systems
39 * such as Solaris which don't arrange to include <sys/ioccom.h> if you
40 * include <sys/ioctl.h>
42 #include <sys/ioctl.h>
43 #ifdef HAVE_SYS_IOCCOM_H
44 #include <sys/ioccom.h>
46 #include <sys/utsname.h>
48 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
50 * Add support for capturing on FreeBSD usbusN interfaces.
52 static const char usbus_prefix[] = "usbus";
53 #define USBUS_PREFIX_LEN (sizeof(usbus_prefix) - 1)
62 * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
63 * native OS version, as we need "struct bpf_config" from it.
65 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
67 #include <sys/types.h>
70 * Prevent bpf.h from redefining the DLT_ values to their
71 * IFT_ values, as we're going to return the standard libpcap
72 * values, not IBM's non-standard IFT_ values.
79 * If both BIOCROTZBUF and BPF_BUFMODE_ZBUF are defined, we have
82 #if defined(BIOCROTZBUF) && defined(BPF_BUFMODE_ZBUF)
83 #define HAVE_ZEROCOPY_BPF
85 #include <machine/atomic.h>
88 #include <net/if_types.h> /* for IFT_ values */
89 #include <sys/sysconfig.h>
90 #include <sys/device.h>
91 #include <sys/cfgodm.h>
95 #define domakedev makedev64
96 #define getmajor major64
97 #define bpf_hdr bpf_hdr32
99 #define domakedev makedev
100 #define getmajor major
101 #endif /* __64BIT__ */
103 #define BPF_NAME "bpf"
105 #define DRIVER_PATH "/usr/lib/drivers"
106 #define BPF_NODE "/dev/bpf"
107 static int bpfloadedflag = 0;
108 static int odmlockid = 0;
110 static int bpf_load(char *errbuf);
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 * associated 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_non_802_11(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 * In some versions of macOS, we might not even get any of the
230 * 802.11-plus-radio-header DLT_'s defined, even though some
231 * of them are used by various Airport drivers in those versions.
233 #ifndef DLT_PRISM_HEADER
234 #define DLT_PRISM_HEADER 119
236 #ifndef DLT_AIRONET_HEADER
237 #define DLT_AIRONET_HEADER 120
239 #ifndef DLT_IEEE802_11_RADIO
240 #define DLT_IEEE802_11_RADIO 127
242 #ifndef DLT_IEEE802_11_RADIO_AVS
243 #define DLT_IEEE802_11_RADIO_AVS 163
246 static int pcap_can_set_rfmon_bpf(pcap_t *p);
247 static int pcap_activate_bpf(pcap_t *p);
248 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
249 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
250 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
253 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
254 * pb->nonblock so we don't call select(2) if the pcap handle is in non-
258 pcap_getnonblock_bpf(pcap_t *p)
260 #ifdef HAVE_ZEROCOPY_BPF
261 struct pcap_bpf *pb = p->priv;
264 return (pb->nonblock);
266 return (pcap_getnonblock_fd(p));
270 pcap_setnonblock_bpf(pcap_t *p, int nonblock)
272 #ifdef HAVE_ZEROCOPY_BPF
273 struct pcap_bpf *pb = p->priv;
276 pb->nonblock = nonblock;
280 return (pcap_setnonblock_fd(p, nonblock));
283 #ifdef HAVE_ZEROCOPY_BPF
285 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
286 * shared memory buffers.
288 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
289 * and set up p->buffer and cc to reflect one if available. Notice that if
290 * there was no prior buffer, we select zbuf1 as this will be the first
291 * buffer filled for a fresh BPF session.
294 pcap_next_zbuf_shm(pcap_t *p, int *cc)
296 struct pcap_bpf *pb = p->priv;
297 struct bpf_zbuf_header *bzh;
299 if (pb->zbuffer == pb->zbuf2 || pb->zbuffer == NULL) {
300 bzh = (struct bpf_zbuf_header *)pb->zbuf1;
301 if (bzh->bzh_user_gen !=
302 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
304 pb->zbuffer = (u_char *)pb->zbuf1;
305 p->buffer = pb->zbuffer + sizeof(*bzh);
306 *cc = bzh->bzh_kernel_len;
309 } else if (pb->zbuffer == pb->zbuf1) {
310 bzh = (struct bpf_zbuf_header *)pb->zbuf2;
311 if (bzh->bzh_user_gen !=
312 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
314 pb->zbuffer = (u_char *)pb->zbuf2;
315 p->buffer = pb->zbuffer + sizeof(*bzh);
316 *cc = bzh->bzh_kernel_len;
325 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
326 * select() for data or a timeout, and possibly force rotation of the buffer
327 * in the event we time out or are in immediate mode. Invoke the shared
328 * memory check before doing system calls in order to avoid doing avoidable
332 pcap_next_zbuf(pcap_t *p, int *cc)
334 struct pcap_bpf *pb = p->priv;
342 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
344 * Start out by seeing whether anything is waiting by checking the
345 * next shared memory buffer for data.
347 data = pcap_next_zbuf_shm(p, cc);
351 * If a previous sleep was interrupted due to signal delivery, make
352 * sure that the timeout gets adjusted accordingly. This requires
353 * that we analyze when the timeout should be been expired, and
354 * subtract the current time from that. If after this operation,
355 * our timeout is less then or equal to zero, handle it like a
358 tmout = p->opt.timeout;
360 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
361 if (pb->interrupted && p->opt.timeout) {
362 expire = TSTOMILLI(&pb->firstsel) + p->opt.timeout;
363 tmout = expire - TSTOMILLI(&cur);
367 data = pcap_next_zbuf_shm(p, cc);
370 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
371 pcap_fmt_errmsg_for_errno(p->errbuf,
372 PCAP_ERRBUF_SIZE, errno, "BIOCROTZBUF");
375 return (pcap_next_zbuf_shm(p, cc));
379 * No data in the buffer, so must use select() to wait for data or
380 * the next timeout. Note that we only call select if the handle
381 * is in blocking mode.
385 FD_SET(p->fd, &r_set);
387 tv.tv_sec = tmout / 1000;
388 tv.tv_usec = (tmout * 1000) % 1000000;
390 r = select(p->fd + 1, &r_set, NULL, NULL,
391 p->opt.timeout != 0 ? &tv : NULL);
392 if (r < 0 && errno == EINTR) {
393 if (!pb->interrupted && p->opt.timeout) {
399 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
406 * Check again for data, which may exist now that we've either been
407 * woken up as a result of data or timed out. Try the "there's data"
408 * case first since it doesn't require a system call.
410 data = pcap_next_zbuf_shm(p, cc);
414 * Try forcing a buffer rotation to dislodge timed out or immediate
417 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
418 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
419 errno, "BIOCROTZBUF");
422 return (pcap_next_zbuf_shm(p, cc));
426 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
427 * that we know which buffer to use next time around.
430 pcap_ack_zbuf(pcap_t *p)
432 struct pcap_bpf *pb = p->priv;
434 atomic_store_rel_int(&pb->bzh->bzh_user_gen,
435 pb->bzh->bzh_kernel_gen);
440 #endif /* HAVE_ZEROCOPY_BPF */
443 pcap_create_interface(const char *device _U_, char *ebuf)
447 p = PCAP_CREATE_COMMON(ebuf, struct pcap_bpf);
451 p->activate_op = pcap_activate_bpf;
452 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
455 * We claim that we support microsecond and nanosecond time
458 p->tstamp_precision_list = malloc(2 * sizeof(u_int));
459 if (p->tstamp_precision_list == NULL) {
460 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno,
465 p->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
466 p->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
467 p->tstamp_precision_count = 2;
468 #endif /* BIOCSTSTAMP */
473 * On success, returns a file descriptor for a BPF device.
474 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
477 bpf_open(char *errbuf)
480 static const char cloning_device[] = "/dev/bpf";
482 char device[sizeof "/dev/bpf0000000000"];
483 static int no_cloning_bpf = 0;
487 * Load the bpf driver, if it isn't already loaded,
488 * and create the BPF device entries, if they don't
491 if (bpf_load(errbuf) == PCAP_ERROR)
496 * First, unless we've already tried opening /dev/bpf and
497 * gotten ENOENT, try opening /dev/bpf.
498 * If it fails with ENOENT, remember that, so we don't try
499 * again, and try /dev/bpfN.
501 if (!no_cloning_bpf &&
502 (fd = open(cloning_device, O_RDWR)) == -1 &&
503 ((errno != EACCES && errno != ENOENT) ||
504 (fd = open(cloning_device, O_RDONLY)) == -1)) {
505 if (errno != ENOENT) {
506 if (errno == EACCES) {
507 fd = PCAP_ERROR_PERM_DENIED;
508 snprintf(errbuf, PCAP_ERRBUF_SIZE,
509 "Attempt to open %s failed - root privileges may be required",
513 pcap_fmt_errmsg_for_errno(errbuf,
514 PCAP_ERRBUF_SIZE, errno,
515 "(cannot open device) %s", cloning_device);
522 if (no_cloning_bpf) {
524 * We don't have /dev/bpf.
525 * Go through all the /dev/bpfN minors and find one
529 (void)snprintf(device, sizeof(device), "/dev/bpf%u", n++);
531 * Initially try a read/write open (to allow the inject
532 * method to work). If that fails due to permission
533 * issues, fall back to read-only. This allows a
534 * non-root user to be granted specific access to pcap
535 * capabilities via file permissions.
537 * XXX - we should have an API that has a flag that
538 * controls whether to open read-only or read-write,
539 * so that denial of permission to send (or inability
540 * to send, if sending packets isn't supported on
541 * the device in question) can be indicated at open
544 fd = open(device, O_RDWR);
545 if (fd == -1 && errno == EACCES)
546 fd = open(device, O_RDONLY);
547 } while (fd < 0 && errno == EBUSY);
551 * XXX better message for all minors used
560 * /dev/bpf0 doesn't exist, which
561 * means we probably have no BPF
564 snprintf(errbuf, PCAP_ERRBUF_SIZE,
565 "(there are no BPF devices)");
568 * We got EBUSY on at least one
569 * BPF device, so we have BPF
570 * devices, but all the ones
571 * that exist are busy.
573 snprintf(errbuf, PCAP_ERRBUF_SIZE,
574 "(all BPF devices are busy)");
580 * Got EACCES on the last device we tried,
581 * and EBUSY on all devices before that,
584 fd = PCAP_ERROR_PERM_DENIED;
585 snprintf(errbuf, PCAP_ERRBUF_SIZE,
586 "Attempt to open %s failed - root privileges may be required",
592 * Some other problem.
595 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
596 errno, "(cannot open BPF device) %s", device);
605 * Bind a network adapter to a BPF device, given a descriptor for the
606 * BPF device and the name of the network adapter.
608 * Use BIOCSETLIF if available (meaning "on Solaris"), as it supports
609 * longer device names.
611 * If the name is longer than will fit, return PCAP_ERROR_NO_SUCH_DEVICE
612 * before trying to bind the interface, as there cannot be such a device.
614 * If the attempt succeeds, return BPF_BIND_SUCCEEDED.
616 * If the attempt fails:
618 * if it fails with ENXIO, return PCAP_ERROR_NO_SUCH_DEVICE, as
619 * the device doesn't exist;
621 * if it fails with ENETDOWN, return PCAP_ERROR_IFACE_NOT_UP, as
622 * the interface exists but isn't up and the OS doesn't allow
623 * binding to an interface that isn't up;
625 * if it fails with ENOBUFS, return BPF_BIND_BUFFER_TOO_BIG, and
626 * fill in an error message, as the buffer being requested is too
629 * otherwise, return PCAP_ERROR and fill in an error message.
631 #define BPF_BIND_SUCCEEDED 0
632 #define BPF_BIND_BUFFER_TOO_BIG 1
635 bpf_bind(int fd, const char *name, char *errbuf)
641 if (strlen(name) >= sizeof(ifr.lifr_name)) {
642 /* The name is too long, so it can't possibly exist. */
643 return (PCAP_ERROR_NO_SUCH_DEVICE);
645 (void)pcap_strlcpy(ifr.lifr_name, name, sizeof(ifr.lifr_name));
646 status = ioctl(fd, BIOCSETLIF, (caddr_t)&ifr);
650 if (strlen(name) >= sizeof(ifr.ifr_name)) {
651 /* The name is too long, so it can't possibly exist. */
652 return (PCAP_ERROR_NO_SUCH_DEVICE);
654 (void)pcap_strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
655 status = ioctl(fd, BIOCSETIF, (caddr_t)&ifr);
663 * There's no such device.
665 * There's nothing more to say, so clear out the
669 return (PCAP_ERROR_NO_SUCH_DEVICE);
673 * Return a "network down" indication, so that
674 * the application can report that rather than
675 * saying we had a mysterious failure and
676 * suggest that they report a problem to the
677 * libpcap developers.
679 return (PCAP_ERROR_IFACE_NOT_UP);
683 * The buffer size is too big.
684 * Return a special indication so that, if we're
685 * trying to crank the buffer size down, we know
686 * we have to continue; add an error message that
687 * tells the user what needs to be fixed.
689 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
690 errno, "The requested buffer size for %s is too large",
692 return (BPF_BIND_BUFFER_TOO_BIG);
695 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
696 errno, "Binding interface %s to BPF device failed",
701 return (BPF_BIND_SUCCEEDED);
705 * Open and bind to a device; used if we're not actually going to use
706 * the device, but are just testing whether it can be opened, or opening
707 * it to get information about it.
709 * Returns an error code on failure (always negative), and an FD for
710 * the now-bound BPF device on success (always non-negative).
713 bpf_open_and_bind(const char *name, char *errbuf)
719 * First, open a BPF device.
721 fd = bpf_open(errbuf);
723 return (fd); /* fd is the appropriate error code */
726 * Now bind to the device.
728 status = bpf_bind(fd, name, errbuf);
729 if (status != BPF_BIND_SUCCEEDED) {
731 if (status == BPF_BIND_BUFFER_TOO_BIG) {
733 * We didn't specify a buffer size, so
734 * this *really* shouldn't fail because
735 * there's no buffer space. Fail.
750 device_exists(int fd, const char *name, char *errbuf)
755 if (strlen(name) >= sizeof(ifr.ifr_name)) {
756 /* The name is too long, so it can't possibly exist. */
757 return (PCAP_ERROR_NO_SUCH_DEVICE);
759 (void)pcap_strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
760 status = ioctl(fd, SIOCGIFFLAGS, (caddr_t)&ifr);
763 if (errno == ENXIO || errno == EINVAL) {
765 * macOS and *BSD return one of those two
766 * errors if the device doesn't exist.
767 * Don't fill in an error, as this is
768 * an "expected" condition.
770 return (PCAP_ERROR_NO_SUCH_DEVICE);
774 * Some other error - provide a message for it, as
777 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
778 "Can't get interface flags on %s", name);
791 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
793 memset(bdlp, 0, sizeof(*bdlp));
794 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
798 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
799 if (bdlp->bfl_list == NULL) {
800 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
805 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
806 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
807 errno, "BIOCGDLTLIST");
808 free(bdlp->bfl_list);
813 * OK, for real Ethernet devices, add DLT_DOCSIS to the
814 * list, so that an application can let you choose it,
815 * in case you're capturing DOCSIS traffic that a Cisco
816 * Cable Modem Termination System is putting out onto
817 * an Ethernet (it doesn't put an Ethernet header onto
818 * the wire, it puts raw DOCSIS frames out on the wire
819 * inside the low-level Ethernet framing).
821 * A "real Ethernet device" is defined here as a device
822 * that has a link-layer type of DLT_EN10MB and that has
823 * no alternate link-layer types; that's done to exclude
824 * 802.11 interfaces (which might or might not be the
825 * right thing to do, but I suspect it is - Ethernet <->
826 * 802.11 bridges would probably badly mishandle frames
827 * that don't have Ethernet headers).
829 * On Solaris with BPF, Ethernet devices also offer
830 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
831 * treat it as an indication that the device isn't an
834 if (v == DLT_EN10MB) {
836 for (i = 0; i < bdlp->bfl_len; i++) {
837 if (bdlp->bfl_list[i] != DLT_EN10MB
839 && bdlp->bfl_list[i] != DLT_IPNET
848 * We reserved one more slot at the end of
851 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
857 * EINVAL just means "we don't support this ioctl on
858 * this device"; don't treat it as an error.
860 if (errno != EINVAL) {
861 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
862 errno, "BIOCGDLTLIST");
870 #if defined(__APPLE__)
872 pcap_can_set_rfmon_bpf(pcap_t *p)
874 struct utsname osinfo;
877 struct bpf_dltlist bdl;
882 * The joys of monitor mode on Mac OS X/OS X/macOS.
884 * Prior to 10.4, it's not supported at all.
886 * In 10.4, if adapter enN supports monitor mode, there's a
887 * wltN adapter corresponding to it; you open it, instead of
888 * enN, to get monitor mode. You get whatever link-layer
889 * headers it supplies.
891 * In 10.5, and, we assume, later releases, if adapter enN
892 * supports monitor mode, it offers, among its selectable
893 * DLT_ values, values that let you get the 802.11 header;
894 * selecting one of those values puts the adapter into monitor
895 * mode (i.e., you can't get 802.11 headers except in monitor
896 * mode, and you can't get Ethernet headers in monitor mode).
898 if (uname(&osinfo) == -1) {
900 * Can't get the OS version; just say "no".
905 * We assume osinfo.sysname is "Darwin", because
906 * __APPLE__ is defined. We just check the version.
908 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
910 * 10.3 (Darwin 7.x) or earlier.
911 * Monitor mode not supported.
915 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
920 * 10.4 (Darwin 8.x). s/en/wlt/, and check
921 * whether the device exists.
923 if (strncmp(p->opt.device, "en", 2) != 0) {
925 * Not an enN device; no monitor mode.
929 fd = socket(AF_INET, SOCK_DGRAM, 0);
931 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
935 if (pcap_asprintf(&wlt_name, "wlt%s", p->opt.device + 2) == -1) {
936 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
941 status = device_exists(fd, wlt_name, p->errbuf);
945 if (status == PCAP_ERROR_NO_SUCH_DEVICE)
958 * Everything else is 10.5 or later; for those,
959 * we just open the enN device, and check whether
960 * we have any 802.11 devices.
962 * First, open a BPF device.
964 fd = bpf_open(p->errbuf);
966 return (fd); /* fd is the appropriate error code */
969 * Now bind to the device.
971 err = bpf_bind(fd, p->opt.device, p->errbuf);
972 if (err != BPF_BIND_SUCCEEDED) {
974 if (err == BPF_BIND_BUFFER_TOO_BIG) {
976 * We didn't specify a buffer size, so
977 * this *really* shouldn't fail because
978 * there's no buffer space. Fail.
986 * We know the default link type -- now determine all the DLTs
987 * this interface supports. If this fails with EINVAL, it's
988 * not fatal; we just don't get to use the feature later.
989 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
990 * as the default DLT for this adapter.)
992 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
996 if (find_802_11(&bdl) != -1) {
998 * We have an 802.11 DLT, so we can set monitor mode.
1006 #endif /* BIOCGDLTLIST */
1009 #elif defined(HAVE_BSD_IEEE80211)
1011 pcap_can_set_rfmon_bpf(pcap_t *p)
1015 ret = monitor_mode(p, 0);
1016 if (ret == PCAP_ERROR_RFMON_NOTSUP)
1017 return (0); /* not an error, just a "can't do" */
1019 return (1); /* success */
1024 pcap_can_set_rfmon_bpf(pcap_t *p _U_)
1031 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
1036 * "ps_recv" counts packets handed to the filter, not packets
1037 * that passed the filter. This includes packets later dropped
1038 * because we ran out of buffer space.
1040 * "ps_drop" counts packets dropped inside the BPF device
1041 * because we ran out of buffer space. It doesn't count
1042 * packets dropped by the interface driver. It counts
1043 * only packets that passed the filter.
1045 * Both statistics include packets not yet read from the kernel
1046 * by libpcap, and thus not yet seen by the application.
1048 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
1049 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1050 errno, "BIOCGSTATS");
1051 return (PCAP_ERROR);
1054 ps->ps_recv = s.bs_recv;
1055 ps->ps_drop = s.bs_drop;
1061 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
1063 struct pcap_bpf *pb = p->priv;
1066 register u_char *bp, *ep;
1071 #ifdef HAVE_ZEROCOPY_BPF
1077 * Has "pcap_breakloop()" been called?
1079 if (p->break_loop) {
1081 * Yes - clear the flag that indicates that it
1082 * has, and return PCAP_ERROR_BREAK to indicate
1083 * that we were told to break out of the loop.
1086 return (PCAP_ERROR_BREAK);
1091 * When reading without zero-copy from a file descriptor, we
1092 * use a single buffer and return a length of data in the
1093 * buffer. With zero-copy, we update the p->buffer pointer
1094 * to point at whatever underlying buffer contains the next
1095 * data and update cc to reflect the data found in the
1098 #ifdef HAVE_ZEROCOPY_BPF
1100 if (p->buffer != NULL)
1102 i = pcap_next_zbuf(p, &cc);
1106 return (PCAP_ERROR);
1110 cc = (int)read(p->fd, p->buffer, p->bufsize);
1113 /* Don't choke when we get ptraced */
1122 * Sigh. More AIX wonderfulness.
1124 * For some unknown reason the uiomove()
1125 * operation in the bpf kernel extension
1126 * used to copy the buffer into user
1127 * space sometimes returns EFAULT. I have
1128 * no idea why this is the case given that
1129 * a kernel debugger shows the user buffer
1130 * is correct. This problem appears to
1131 * be mostly mitigated by the memset of
1132 * the buffer before it is first used.
1133 * Very strange.... Shaun Clowes
1135 * In any case this means that we shouldn't
1136 * treat EFAULT as a fatal error; as we
1137 * don't have an API for returning
1138 * a "some packets were dropped since
1139 * the last packet you saw" indication,
1140 * we just ignore EFAULT and keep reading.
1148 case ENXIO: /* FreeBSD, DragonFly BSD, and Darwin */
1149 case EIO: /* OpenBSD */
1150 /* NetBSD appears not to return an error in this case */
1152 * The device on which we're capturing
1155 * XXX - we should really return
1156 * an appropriate error for that,
1157 * but pcap_dispatch() etc. aren't
1158 * documented as having error returns
1159 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
1161 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1162 "The interface disappeared");
1163 return (PCAP_ERROR);
1165 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
1167 * Due to a SunOS bug, after 2^31 bytes, the kernel
1168 * file offset overflows and read fails with EINVAL.
1169 * The lseek() to 0 will fix things.
1172 if (lseek(p->fd, 0L, SEEK_CUR) +
1174 (void)lseek(p->fd, 0L, SEEK_SET);
1180 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1182 return (PCAP_ERROR);
1184 bp = (u_char *)p->buffer;
1189 * Loop through each packet.
1191 * This assumes that a single buffer of packets will have
1192 * <= INT_MAX packets, so the packet count doesn't overflow.
1195 #define bhp ((struct bpf_xhdr *)bp)
1197 #define bhp ((struct bpf_hdr *)bp)
1204 register u_int caplen, hdrlen;
1207 * Has "pcap_breakloop()" been called?
1208 * If so, return immediately - if we haven't read any
1209 * packets, clear the flag and return PCAP_ERROR_BREAK
1210 * to indicate that we were told to break out of the loop,
1211 * otherwise leave the flag set, so that the *next* call
1212 * will break out of the loop without having read any
1213 * packets, and return the number of packets we've
1216 if (p->break_loop) {
1218 p->cc = (int)(ep - bp);
1220 * ep is set based on the return value of read(),
1221 * but read() from a BPF device doesn't necessarily
1222 * return a value that's a multiple of the alignment
1223 * value for BPF_WORDALIGN(). However, whenever we
1224 * increment bp, we round up the increment value by
1225 * a value rounded up by BPF_WORDALIGN(), so we
1226 * could increment bp past ep after processing the
1227 * last packet in the buffer.
1229 * We treat ep < bp as an indication that this
1230 * happened, and just set p->cc to 0.
1236 return (PCAP_ERROR_BREAK);
1241 caplen = bhp->bh_caplen;
1242 hdrlen = bhp->bh_hdrlen;
1243 datap = bp + hdrlen;
1245 * Short-circuit evaluation: if using BPF filter
1246 * in kernel, no need to do it now - we already know
1247 * the packet passed the filter.
1250 * Note: the filter code was generated assuming
1251 * that p->fddipad was the amount of padding
1252 * before the header, as that's what's required
1253 * in the kernel, so we run the filter before
1254 * skipping that padding.
1257 if (pb->filtering_in_kernel ||
1258 pcap_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1259 struct pcap_pkthdr pkthdr;
1263 bt.sec = bhp->bh_tstamp.bt_sec;
1264 bt.frac = bhp->bh_tstamp.bt_frac;
1265 if (p->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
1268 bintime2timespec(&bt, &ts);
1269 pkthdr.ts.tv_sec = ts.tv_sec;
1270 pkthdr.ts.tv_usec = ts.tv_nsec;
1274 bintime2timeval(&bt, &tv);
1275 pkthdr.ts.tv_sec = tv.tv_sec;
1276 pkthdr.ts.tv_usec = tv.tv_usec;
1279 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1282 * AIX's BPF returns seconds/nanoseconds time
1283 * stamps, not seconds/microseconds time stamps.
1285 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1287 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1289 #endif /* BIOCSTSTAMP */
1292 pkthdr.caplen = caplen - pad;
1295 if (bhp->bh_datalen > pad)
1296 pkthdr.len = bhp->bh_datalen - pad;
1301 pkthdr.caplen = caplen;
1302 pkthdr.len = bhp->bh_datalen;
1304 (*callback)(user, &pkthdr, datap);
1305 bp += BPF_WORDALIGN(caplen + hdrlen);
1306 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
1308 p->cc = (int)(ep - bp);
1310 * See comment above about p->cc < 0.
1320 bp += BPF_WORDALIGN(caplen + hdrlen);
1329 pcap_inject_bpf(pcap_t *p, const void *buf, int size)
1333 ret = (int)write(p->fd, buf, size);
1335 if (ret == -1 && errno == EAFNOSUPPORT) {
1337 * In some versions of macOS, there's a bug wherein setting
1338 * the BIOCSHDRCMPLT flag causes writes to fail; see, for
1341 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1343 * So, if, on macOS, we get EAFNOSUPPORT from the write, we
1344 * assume it's due to that bug, and turn off that flag
1345 * and try again. If we succeed, it either means that
1346 * somebody applied the fix from that URL, or other patches
1349 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1351 * and are running a Darwin kernel with those fixes, or
1352 * that Apple fixed the problem in some macOS release.
1354 u_int spoof_eth_src = 0;
1356 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1357 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1358 errno, "send: can't turn off BIOCSHDRCMPLT");
1359 return (PCAP_ERROR);
1363 * Now try the write again.
1365 ret = (int)write(p->fd, buf, size);
1367 #endif /* __APPLE__ */
1369 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1371 return (PCAP_ERROR);
1378 bpf_odminit(char *errbuf)
1382 if (odm_initialize() == -1) {
1383 if (odm_err_msg(odmerrno, &errstr) == -1)
1384 errstr = "Unknown error";
1385 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1386 "bpf_load: odm_initialize failed: %s",
1388 return (PCAP_ERROR);
1391 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1392 if (odm_err_msg(odmerrno, &errstr) == -1)
1393 errstr = "Unknown error";
1394 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1395 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1397 (void)odm_terminate();
1398 return (PCAP_ERROR);
1405 bpf_odmcleanup(char *errbuf)
1409 if (odm_unlock(odmlockid) == -1) {
1410 if (errbuf != NULL) {
1411 if (odm_err_msg(odmerrno, &errstr) == -1)
1412 errstr = "Unknown error";
1413 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1414 "bpf_load: odm_unlock failed: %s",
1417 return (PCAP_ERROR);
1420 if (odm_terminate() == -1) {
1421 if (errbuf != NULL) {
1422 if (odm_err_msg(odmerrno, &errstr) == -1)
1423 errstr = "Unknown error";
1424 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1425 "bpf_load: odm_terminate failed: %s",
1428 return (PCAP_ERROR);
1435 bpf_load(char *errbuf)
1439 int numminors, i, rc;
1442 struct bpf_config cfg_bpf;
1443 struct cfg_load cfg_ld;
1444 struct cfg_kmod cfg_km;
1447 * This is very very close to what happens in the real implementation
1448 * but I've fixed some (unlikely) bug situations.
1453 if (bpf_odminit(errbuf) == PCAP_ERROR)
1454 return (PCAP_ERROR);
1456 major = genmajor(BPF_NAME);
1458 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1459 errno, "bpf_load: genmajor failed");
1460 (void)bpf_odmcleanup(NULL);
1461 return (PCAP_ERROR);
1464 minors = getminor(major, &numminors, BPF_NAME);
1466 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1468 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1469 errno, "bpf_load: genminor failed");
1470 (void)bpf_odmcleanup(NULL);
1471 return (PCAP_ERROR);
1475 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1476 return (PCAP_ERROR);
1478 rc = stat(BPF_NODE "0", &sbuf);
1479 if (rc == -1 && errno != ENOENT) {
1480 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1481 errno, "bpf_load: can't stat %s", BPF_NODE "0");
1482 return (PCAP_ERROR);
1485 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1486 for (i = 0; i < BPF_MINORS; i++) {
1487 snprintf(buf, sizeof(buf), "%s%d", BPF_NODE, i);
1489 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1490 pcap_fmt_errmsg_for_errno(errbuf,
1491 PCAP_ERRBUF_SIZE, errno,
1492 "bpf_load: can't mknod %s", buf);
1493 return (PCAP_ERROR);
1498 /* Check if the driver is loaded */
1499 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1500 snprintf(buf, sizeof(buf), "%s/%s", DRIVER_PATH, BPF_NAME);
1502 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1503 (cfg_ld.kmid == 0)) {
1504 /* Driver isn't loaded, load it now */
1505 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1506 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1507 errno, "bpf_load: could not load driver");
1508 return (PCAP_ERROR);
1512 /* Configure the driver */
1513 cfg_km.cmd = CFG_INIT;
1514 cfg_km.kmid = cfg_ld.kmid;
1515 cfg_km.mdilen = sizeof(cfg_bpf);
1516 cfg_km.mdiptr = (void *)&cfg_bpf;
1517 for (i = 0; i < BPF_MINORS; i++) {
1518 cfg_bpf.devno = domakedev(major, i);
1519 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1520 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1521 errno, "bpf_load: could not configure driver");
1522 return (PCAP_ERROR);
1533 * Undo any operations done when opening the device when necessary.
1536 pcap_cleanup_bpf(pcap_t *p)
1538 struct pcap_bpf *pb = p->priv;
1539 #ifdef HAVE_BSD_IEEE80211
1541 struct ifmediareq req;
1545 if (pb->must_do_on_close != 0) {
1547 * There's something we have to do when closing this
1550 #ifdef HAVE_BSD_IEEE80211
1551 if (pb->must_do_on_close & MUST_CLEAR_RFMON) {
1553 * We put the interface into rfmon mode;
1554 * take it out of rfmon mode.
1556 * XXX - if somebody else wants it in rfmon
1557 * mode, this code cannot know that, so it'll take
1558 * it out of rfmon mode.
1560 sock = socket(AF_INET, SOCK_DGRAM, 0);
1563 "Can't restore interface flags (socket() failed: %s).\n"
1564 "Please adjust manually.\n",
1567 memset(&req, 0, sizeof(req));
1568 pcap_strlcpy(req.ifm_name, pb->device,
1569 sizeof(req.ifm_name));
1570 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1572 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1573 "Please adjust manually.\n",
1576 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1578 * Rfmon mode is currently on;
1581 memset(&ifr, 0, sizeof(ifr));
1582 (void)pcap_strlcpy(ifr.ifr_name,
1584 sizeof(ifr.ifr_name));
1586 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1587 if (ioctl(sock, SIOCSIFMEDIA,
1590 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1591 "Please adjust manually.\n",
1599 #endif /* HAVE_BSD_IEEE80211 */
1601 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1603 * Attempt to destroy the usbusN interface that we created.
1605 if (pb->must_do_on_close & MUST_DESTROY_USBUS) {
1606 if (if_nametoindex(pb->device) > 0) {
1609 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1611 pcap_strlcpy(ifr.ifr_name, pb->device,
1612 sizeof(ifr.ifr_name));
1613 ioctl(s, SIOCIFDESTROY, &ifr);
1618 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1620 * Take this pcap out of the list of pcaps for which we
1621 * have to take the interface out of some mode.
1623 pcap_remove_from_pcaps_to_close(p);
1624 pb->must_do_on_close = 0;
1627 #ifdef HAVE_ZEROCOPY_BPF
1630 * Delete the mappings. Note that p->buffer gets
1631 * initialized to one of the mmapped regions in
1632 * this case, so do not try and free it directly;
1633 * null it out so that pcap_cleanup_live_common()
1634 * doesn't try to free it.
1636 if (pb->zbuf1 != MAP_FAILED && pb->zbuf1 != NULL)
1637 (void) munmap(pb->zbuf1, pb->zbufsize);
1638 if (pb->zbuf2 != MAP_FAILED && pb->zbuf2 != NULL)
1639 (void) munmap(pb->zbuf2, pb->zbufsize);
1643 if (pb->device != NULL) {
1647 pcap_cleanup_live_common(p);
1652 check_setif_failure(pcap_t *p, int error)
1657 if (error == PCAP_ERROR_NO_SUCH_DEVICE) {
1659 * No such device exists.
1661 if (p->opt.rfmon && strncmp(p->opt.device, "wlt", 3) == 0) {
1663 * Monitor mode was requested, and we're trying
1664 * to open a "wltN" device. Assume that this
1665 * is 10.4 and that we were asked to open an
1666 * "enN" device; if that device exists, return
1667 * "monitor mode not supported on the device".
1669 fd = socket(AF_INET, SOCK_DGRAM, 0);
1673 if (pcap_asprintf(&en_name, "en%s",
1674 p->opt.device + 3) == -1) {
1676 * We can't find out whether there's
1677 * an underlying "enN" device, so
1678 * just report "no such device".
1680 pcap_fmt_errmsg_for_errno(p->errbuf,
1681 PCAP_ERRBUF_SIZE, errno,
1684 return (PCAP_ERROR_NO_SUCH_DEVICE);
1686 err = device_exists(fd, en_name, p->errbuf);
1689 if (err == PCAP_ERROR_NO_SUCH_DEVICE) {
1691 * The underlying "enN" device
1692 * exists, but there's no
1693 * corresponding "wltN" device;
1694 * that means that the "enN"
1695 * device doesn't support
1696 * monitor mode, probably
1697 * because it's an Ethernet
1698 * device rather than a
1701 err = PCAP_ERROR_RFMON_NOTSUP;
1707 * We can't find out whether there's
1708 * an underlying "enN" device, so
1709 * just report "no such device".
1711 err = PCAP_ERROR_NO_SUCH_DEVICE;
1712 pcap_fmt_errmsg_for_errno(p->errbuf,
1713 errno, PCAP_ERRBUF_SIZE,
1722 return (PCAP_ERROR_NO_SUCH_DEVICE);
1726 * Just return the error status; it's what we want, and, if it's
1727 * PCAP_ERROR, the error string has been filled in.
1733 check_setif_failure(pcap_t *p _U_, int error)
1736 * Just return the error status; it's what we want, and, if it's
1737 * PCAP_ERROR, the error string has been filled in.
1744 * Default capture buffer size.
1745 * 32K isn't very much for modern machines with fast networks; we
1746 * pick .5M, as that's the maximum on at least some systems with BPF.
1748 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1749 * read failures under stress, so we leave it as 32K; yet another
1750 * place where AIX's BPF is broken.
1753 #define DEFAULT_BUFSIZE 32768
1755 #define DEFAULT_BUFSIZE 524288
1759 pcap_activate_bpf(pcap_t *p)
1761 struct pcap_bpf *pb = p->priv;
1763 #ifdef HAVE_BSD_IEEE80211
1767 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1771 struct bpf_version bv;
1774 char *wltdev = NULL;
1777 struct bpf_dltlist bdl;
1778 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1781 #endif /* BIOCGDLTLIST */
1782 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1783 u_int spoof_eth_src = 1;
1786 struct bpf_insn total_insn;
1787 struct bpf_program total_prog;
1788 struct utsname osinfo;
1789 int have_osinfo = 0;
1790 #ifdef HAVE_ZEROCOPY_BPF
1792 u_int bufmode, zbufmax;
1795 fd = bpf_open(p->errbuf);
1803 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1804 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1805 errno, "BIOCVERSION");
1806 status = PCAP_ERROR;
1809 if (bv.bv_major != BPF_MAJOR_VERSION ||
1810 bv.bv_minor < BPF_MINOR_VERSION) {
1811 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1812 "kernel bpf filter out of date");
1813 status = PCAP_ERROR;
1818 * Turn a negative snapshot value (invalid), a snapshot value of
1819 * 0 (unspecified), or a value bigger than the normal maximum
1820 * value, into the maximum allowed value.
1822 * If some application really *needs* a bigger snapshot
1823 * length, we should just increase MAXIMUM_SNAPLEN.
1825 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1826 p->snapshot = MAXIMUM_SNAPLEN;
1828 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1830 * Retrieve the zoneid of the zone we are currently executing in.
1832 if ((ifr.lifr_zoneid = getzoneid()) == -1) {
1833 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1834 errno, "getzoneid()");
1835 status = PCAP_ERROR;
1839 * Check if the given source datalink name has a '/' separated
1840 * zonename prefix string. The zonename prefixed source datalink can
1841 * be used by pcap consumers in the Solaris global zone to capture
1842 * traffic on datalinks in non-global zones. Non-global zones
1843 * do not have access to datalinks outside of their own namespace.
1845 if ((zonesep = strchr(p->opt.device, '/')) != NULL) {
1846 char path_zname[ZONENAME_MAX];
1850 if (ifr.lifr_zoneid != GLOBAL_ZONEID) {
1851 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1852 "zonename/linkname only valid in global zone.");
1853 status = PCAP_ERROR;
1856 znamelen = zonesep - p->opt.device;
1857 (void) pcap_strlcpy(path_zname, p->opt.device, znamelen + 1);
1858 ifr.lifr_zoneid = getzoneidbyname(path_zname);
1859 if (ifr.lifr_zoneid == -1) {
1860 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1861 errno, "getzoneidbyname(%s)", path_zname);
1862 status = PCAP_ERROR;
1865 lnamep = strdup(zonesep + 1);
1866 if (lnamep == NULL) {
1867 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1869 status = PCAP_ERROR;
1872 free(p->opt.device);
1873 p->opt.device = lnamep;
1877 pb->device = strdup(p->opt.device);
1878 if (pb->device == NULL) {
1879 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1881 status = PCAP_ERROR;
1886 * Attempt to find out the version of the OS on which we're running.
1888 if (uname(&osinfo) == 0)
1893 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1894 * of why we check the version number.
1899 * We assume osinfo.sysname is "Darwin", because
1900 * __APPLE__ is defined. We just check the version.
1902 if (osinfo.release[0] < '8' &&
1903 osinfo.release[1] == '.') {
1905 * 10.3 (Darwin 7.x) or earlier.
1907 status = PCAP_ERROR_RFMON_NOTSUP;
1910 if (osinfo.release[0] == '8' &&
1911 osinfo.release[1] == '.') {
1913 * 10.4 (Darwin 8.x). s/en/wlt/
1915 if (strncmp(p->opt.device, "en", 2) != 0) {
1917 * Not an enN device; check
1918 * whether the device even exists.
1920 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1922 status = device_exists(sockfd,
1923 p->opt.device, p->errbuf);
1926 * The device exists,
1933 status = PCAP_ERROR_RFMON_NOTSUP;
1938 * We can't find out whether
1939 * the device exists, so just
1940 * report "no such device".
1942 status = PCAP_ERROR_NO_SUCH_DEVICE;
1943 pcap_fmt_errmsg_for_errno(p->errbuf,
1944 PCAP_ERRBUF_SIZE, errno,
1949 wltdev = malloc(strlen(p->opt.device) + 2);
1950 if (wltdev == NULL) {
1951 pcap_fmt_errmsg_for_errno(p->errbuf,
1952 PCAP_ERRBUF_SIZE, errno,
1954 status = PCAP_ERROR;
1957 strcpy(wltdev, "wlt");
1958 strcat(wltdev, p->opt.device + 2);
1959 free(p->opt.device);
1960 p->opt.device = wltdev;
1963 * Everything else is 10.5 or later; for those,
1964 * we just open the enN device, and set the DLT.
1968 #endif /* __APPLE__ */
1971 * If this is FreeBSD, and the device name begins with "usbus",
1972 * try to create the interface if it's not available.
1974 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1975 if (strncmp(p->opt.device, usbus_prefix, USBUS_PREFIX_LEN) == 0) {
1977 * Do we already have an interface with that name?
1979 if (if_nametoindex(p->opt.device) == 0) {
1981 * No. We need to create it, and, if we
1982 * succeed, remember that we should destroy
1983 * it when the pcap_t is closed.
1989 * Open a socket to use for ioctls to
1990 * create the interface.
1992 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1994 pcap_fmt_errmsg_for_errno(p->errbuf,
1995 PCAP_ERRBUF_SIZE, errno,
1996 "Can't open socket");
1997 status = PCAP_ERROR;
2002 * If we haven't already done so, arrange to have
2003 * "pcap_close_all()" called when we exit.
2005 if (!pcap_do_addexit(p)) {
2007 * "atexit()" failed; don't create the
2008 * interface, just give up.
2010 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2013 status = PCAP_ERROR;
2018 * Create the interface.
2020 pcap_strlcpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
2021 if (ioctl(s, SIOCIFCREATE2, &ifr) < 0) {
2022 if (errno == EINVAL) {
2023 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2024 "Invalid USB bus interface %s",
2027 pcap_fmt_errmsg_for_errno(p->errbuf,
2028 PCAP_ERRBUF_SIZE, errno,
2029 "Can't create interface for %s",
2033 status = PCAP_ERROR;
2038 * Make sure we clean this up when we close.
2040 pb->must_do_on_close |= MUST_DESTROY_USBUS;
2043 * Add this to the list of pcaps to close when we exit.
2045 pcap_add_to_pcaps_to_close(p);
2048 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
2050 #ifdef HAVE_ZEROCOPY_BPF
2052 * If the BPF extension to set buffer mode is present, try setting
2053 * the mode to zero-copy. If that fails, use regular buffering. If
2054 * it succeeds but other setup fails, return an error to the user.
2056 bufmode = BPF_BUFMODE_ZBUF;
2057 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
2059 * We have zerocopy BPF; use it.
2064 * How to pick a buffer size: first, query the maximum buffer
2065 * size supported by zero-copy. This also lets us quickly
2066 * determine whether the kernel generally supports zero-copy.
2067 * Then, if a buffer size was specified, use that, otherwise
2068 * query the default buffer size, which reflects kernel
2069 * policy for a desired default. Round to the nearest page
2072 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
2073 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2074 errno, "BIOCGETZMAX");
2075 status = PCAP_ERROR;
2079 if (p->opt.buffer_size != 0) {
2081 * A buffer size was explicitly specified; use it.
2083 v = p->opt.buffer_size;
2085 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
2086 v < DEFAULT_BUFSIZE)
2087 v = DEFAULT_BUFSIZE;
2090 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
2092 pb->zbufsize = roundup(v, getpagesize());
2093 if (pb->zbufsize > zbufmax)
2094 pb->zbufsize = zbufmax;
2095 pb->zbuf1 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
2097 pb->zbuf2 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
2099 if (pb->zbuf1 == MAP_FAILED || pb->zbuf2 == MAP_FAILED) {
2100 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2102 status = PCAP_ERROR;
2105 memset(&bz, 0, sizeof(bz)); /* bzero() deprecated, replaced with memset() */
2106 bz.bz_bufa = pb->zbuf1;
2107 bz.bz_bufb = pb->zbuf2;
2108 bz.bz_buflen = pb->zbufsize;
2109 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
2110 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2111 errno, "BIOCSETZBUF");
2112 status = PCAP_ERROR;
2115 status = bpf_bind(fd, p->opt.device, ifnamsiz, p->errbuf);
2116 if (status != BPF_BIND_SUCCEEDED) {
2117 if (status == BPF_BIND_BUFFER_TOO_BIG) {
2119 * The requested buffer size
2122 * XXX - should we do the "keep cutting
2123 * the buffer size in half" loop here if
2124 * we're using the default buffer size?
2126 status = PCAP_ERROR;
2130 v = pb->zbufsize - sizeof(struct bpf_zbuf_header);
2135 * We don't have zerocopy BPF.
2136 * Set the buffer size.
2138 if (p->opt.buffer_size != 0) {
2140 * A buffer size was explicitly specified; use it.
2142 if (ioctl(fd, BIOCSBLEN,
2143 (caddr_t)&p->opt.buffer_size) < 0) {
2144 pcap_fmt_errmsg_for_errno(p->errbuf,
2145 PCAP_ERRBUF_SIZE, errno,
2146 "BIOCSBLEN: %s", p->opt.device);
2147 status = PCAP_ERROR;
2152 * Now bind to the device.
2154 status = bpf_bind(fd, p->opt.device, p->errbuf);
2155 if (status != BPF_BIND_SUCCEEDED) {
2156 if (status == BPF_BIND_BUFFER_TOO_BIG) {
2158 * The requested buffer size
2161 status = PCAP_ERROR;
2166 * Special checks on macOS to deal with
2167 * the way monitor mode was done on
2170 status = check_setif_failure(p, status);
2175 * No buffer size was explicitly specified.
2177 * Try finding a good size for the buffer;
2178 * DEFAULT_BUFSIZE may be too big, so keep
2179 * cutting it in half until we find a size
2180 * that works, or run out of sizes to try.
2181 * If the default is larger, don't make it smaller.
2183 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
2184 v < DEFAULT_BUFSIZE)
2185 v = DEFAULT_BUFSIZE;
2186 for ( ; v != 0; v >>= 1) {
2188 * Ignore the return value - this is because the
2189 * call fails on BPF systems that don't have
2190 * kernel malloc. And if the call fails, it's
2191 * no big deal, we just continue to use the
2192 * standard buffer size.
2194 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
2196 status = bpf_bind(fd, p->opt.device, p->errbuf);
2197 if (status == BPF_BIND_SUCCEEDED)
2198 break; /* that size worked; we're done */
2201 * If the attempt failed because the
2202 * buffer was too big, cut the buffer
2203 * size in half and try again.
2207 if (status != BPF_BIND_BUFFER_TOO_BIG) {
2209 * Special checks on macOS to deal
2210 * with the way monitor mode was
2211 * done on 10.4 Tiger.
2213 status = check_setif_failure(p, status);
2219 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2220 "BIOCSBLEN: %s: No buffer size worked",
2222 status = PCAP_ERROR;
2228 /* Get the data link layer type. */
2229 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
2230 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2232 status = PCAP_ERROR;
2238 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
2261 * We don't know what to map this to yet.
2263 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
2265 status = PCAP_ERROR;
2269 #if _BSDI_VERSION - 0 >= 199510
2270 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
2285 case 12: /*DLT_C_HDLC*/
2293 * We know the default link type -- now determine all the DLTs
2294 * this interface supports. If this fails with EINVAL, it's
2295 * not fatal; we just don't get to use the feature later.
2297 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
2298 status = PCAP_ERROR;
2301 p->dlt_count = bdl.bfl_len;
2302 p->dlt_list = bdl.bfl_list;
2306 * Monitor mode fun, continued.
2308 * For 10.5 and, we're assuming, later releases, as noted above,
2309 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
2310 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
2311 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
2314 * Therefore, if the user asked for monitor mode, we filter out
2315 * the DLT_EN10MB value, as you can't get that in monitor mode,
2316 * and, if the user didn't ask for monitor mode, we filter out
2317 * the 802.11 DLT_ values, because selecting those will turn
2318 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
2319 * radio DLT_ value is offered, we try to select that, otherwise
2320 * we try to select DLT_IEEE802_11.
2323 if (PCAP_ISDIGIT((unsigned)osinfo.release[0]) &&
2324 (osinfo.release[0] == '9' ||
2325 PCAP_ISDIGIT((unsigned)osinfo.release[1]))) {
2327 * 10.5 (Darwin 9.x), or later.
2329 new_dlt = find_802_11(&bdl);
2330 if (new_dlt != -1) {
2332 * We have at least one 802.11 DLT_ value,
2333 * so this is an 802.11 interface.
2334 * new_dlt is the best of the 802.11
2335 * DLT_ values in the list.
2339 * Our caller wants monitor mode.
2340 * Purge DLT_EN10MB from the list
2341 * of link-layer types, as selecting
2342 * it will keep monitor mode off.
2344 remove_non_802_11(p);
2347 * If the new mode we want isn't
2348 * the default mode, attempt to
2349 * select the new mode.
2351 if ((u_int)new_dlt != v) {
2352 if (ioctl(p->fd, BIOCSDLT,
2364 * Our caller doesn't want
2365 * monitor mode. Unless this
2366 * is being done by pcap_open_live(),
2367 * purge the 802.11 link-layer types
2368 * from the list, as selecting
2369 * one of them will turn monitor
2378 * The caller requested monitor
2379 * mode, but we have no 802.11
2380 * link-layer types, so they
2383 status = PCAP_ERROR_RFMON_NOTSUP;
2389 #elif defined(HAVE_BSD_IEEE80211)
2391 * *BSD with the new 802.11 ioctls.
2392 * Do we want monitor mode?
2396 * Try to put the interface into monitor mode.
2398 retv = monitor_mode(p, 1);
2408 * We're in monitor mode.
2409 * Try to find the best 802.11 DLT_ value and, if we
2410 * succeed, try to switch to that mode if we're not
2411 * already in that mode.
2413 new_dlt = find_802_11(&bdl);
2414 if (new_dlt != -1) {
2416 * We have at least one 802.11 DLT_ value.
2417 * new_dlt is the best of the 802.11
2418 * DLT_ values in the list.
2420 * If the new mode we want isn't the default mode,
2421 * attempt to select the new mode.
2423 if ((u_int)new_dlt != v) {
2424 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
2426 * We succeeded; make this the
2434 #endif /* various platforms */
2435 #endif /* BIOCGDLTLIST */
2438 * If this is an Ethernet device, and we don't have a DLT_ list,
2439 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
2440 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2441 * do, but there's not much we can do about that without finding
2442 * some other way of determining whether it's an Ethernet or 802.11
2445 if (v == DLT_EN10MB && p->dlt_count == 0) {
2446 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2448 * If that fails, just leave the list empty.
2450 if (p->dlt_list != NULL) {
2451 p->dlt_list[0] = DLT_EN10MB;
2452 p->dlt_list[1] = DLT_DOCSIS;
2458 p->fddipad = PCAP_FDDIPAD;
2464 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2466 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2467 * the link-layer source address isn't forcibly overwritten.
2468 * (Should we ignore errors? Should we do this only if
2469 * we're open for writing?)
2471 * XXX - I seem to remember some packet-sending bug in some
2472 * BSDs - check CVS log for "bpf.c"?
2474 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2475 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2476 errno, "BIOCSHDRCMPLT");
2477 status = PCAP_ERROR;
2482 #ifdef HAVE_ZEROCOPY_BPF
2484 * In zero-copy mode, we just use the timeout in select().
2485 * XXX - what if we're in non-blocking mode and the *application*
2486 * is using select() or poll() or kqueues or....?
2488 if (p->opt.timeout && !pb->zerocopy) {
2490 if (p->opt.timeout) {
2493 * XXX - is this seconds/nanoseconds in AIX?
2494 * (Treating it as such doesn't fix the timeout
2495 * problem described below.)
2497 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2498 * 64-bit userland - it takes, as an argument, a
2499 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2500 * and tv_usec, rather than a "struct timeval".
2502 * If this platform defines "struct BPF_TIMEVAL",
2503 * we check whether the structure size in BIOCSRTIMEOUT
2504 * is that of a "struct timeval" and, if not, we use
2505 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2506 * (That way, if the bug is fixed in a future release,
2507 * we will still do the right thing.)
2510 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2511 struct BPF_TIMEVAL bpf_to;
2513 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2514 bpf_to.tv_sec = p->opt.timeout / 1000;
2515 bpf_to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2516 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2517 pcap_fmt_errmsg_for_errno(p->errbuf,
2518 errno, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT");
2519 status = PCAP_ERROR;
2524 to.tv_sec = p->opt.timeout / 1000;
2525 to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2526 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2527 pcap_fmt_errmsg_for_errno(p->errbuf,
2528 errno, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT");
2529 status = PCAP_ERROR;
2532 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2537 #ifdef BIOCIMMEDIATE
2539 * Darren Reed notes that
2541 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2542 * timeout appears to be ignored and it waits until the buffer
2543 * is filled before returning. The result of not having it
2544 * set is almost worse than useless if your BPF filter
2545 * is reducing things to only a few packets (i.e. one every
2548 * so we always turn BIOCIMMEDIATE mode on if this is AIX.
2550 * For other platforms, we don't turn immediate mode on by default,
2551 * as that would mean we get woken up for every packet, which
2552 * probably isn't what you want for a packet sniffer.
2554 * We set immediate mode if the caller requested it by calling
2555 * pcap_set_immediate() before calling pcap_activate().
2558 if (p->opt.immediate) {
2561 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2562 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2563 errno, "BIOCIMMEDIATE");
2564 status = PCAP_ERROR;
2570 #else /* BIOCIMMEDIATE */
2571 if (p->opt.immediate) {
2573 * We don't support immediate mode. Fail.
2575 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Immediate mode not supported");
2576 status = PCAP_ERROR;
2579 #endif /* BIOCIMMEDIATE */
2581 if (p->opt.promisc) {
2582 /* set promiscuous mode, just warn if it fails */
2583 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2584 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2585 errno, "BIOCPROMISC");
2586 status = PCAP_WARNING_PROMISC_NOTSUP;
2592 if (ioctl(p->fd, BIOCSTSTAMP, &v) < 0) {
2593 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2594 errno, "BIOCSTSTAMP");
2595 status = PCAP_ERROR;
2598 #endif /* BIOCSTSTAMP */
2600 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2601 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2602 errno, "BIOCGBLEN");
2603 status = PCAP_ERROR;
2607 #ifdef HAVE_ZEROCOPY_BPF
2608 if (!pb->zerocopy) {
2610 p->buffer = malloc(p->bufsize);
2611 if (p->buffer == NULL) {
2612 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2614 status = PCAP_ERROR;
2618 /* For some strange reason this seems to prevent the EFAULT
2619 * problems we have experienced from AIX BPF. */
2620 memset(p->buffer, 0x0, p->bufsize);
2622 #ifdef HAVE_ZEROCOPY_BPF
2627 * If there's no filter program installed, there's
2628 * no indication to the kernel of what the snapshot
2629 * length should be, so no snapshotting is done.
2631 * Therefore, when we open the device, we install
2632 * an "accept everything" filter with the specified
2635 total_insn.code = (u_short)(BPF_RET | BPF_K);
2638 total_insn.k = p->snapshot;
2640 total_prog.bf_len = 1;
2641 total_prog.bf_insns = &total_insn;
2642 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2643 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2645 status = PCAP_ERROR;
2650 * On most BPF platforms, either you can do a "select()" or
2651 * "poll()" on a BPF file descriptor and it works correctly,
2652 * or you can do it and it will return "readable" if the
2653 * hold buffer is full but not if the timeout expires *and*
2654 * a non-blocking read will, if the hold buffer is empty
2655 * but the store buffer isn't empty, rotate the buffers
2656 * and return what packets are available.
2658 * In the latter case, the fact that a non-blocking read
2659 * will give you the available packets means you can work
2660 * around the failure of "select()" and "poll()" to wake up
2661 * and return "readable" when the timeout expires by using
2662 * the timeout as the "select()" or "poll()" timeout, putting
2663 * the BPF descriptor into non-blocking mode, and read from
2664 * it regardless of whether "select()" reports it as readable
2667 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2668 * won't wake up and return "readable" if the timer expires
2669 * and non-blocking reads return EWOULDBLOCK if the hold
2670 * buffer is empty, even if the store buffer is non-empty.
2672 * This means the workaround in question won't work.
2674 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2675 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2676 * here". On all other BPF platforms, we set it to the FD for
2677 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2678 * read will, if the hold buffer is empty and the store buffer
2679 * isn't empty, rotate the buffers and return what packets are
2680 * there (and in sufficiently recent versions of OpenBSD
2681 * "select()" and "poll()" should work correctly).
2683 * XXX - what about AIX?
2685 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2688 * We can check what OS this is.
2690 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2691 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2692 strncmp(osinfo.release, "4.4-", 4) == 0)
2693 p->selectable_fd = -1;
2697 p->read_op = pcap_read_bpf;
2698 p->inject_op = pcap_inject_bpf;
2699 p->setfilter_op = pcap_setfilter_bpf;
2700 p->setdirection_op = pcap_setdirection_bpf;
2701 p->set_datalink_op = pcap_set_datalink_bpf;
2702 p->getnonblock_op = pcap_getnonblock_bpf;
2703 p->setnonblock_op = pcap_setnonblock_bpf;
2704 p->stats_op = pcap_stats_bpf;
2705 p->cleanup_op = pcap_cleanup_bpf;
2709 pcap_cleanup_bpf(p);
2714 * Not all interfaces can be bound to by BPF, so try to bind to
2715 * the specified interface; return 0 if we fail with
2716 * PCAP_ERROR_NO_SUCH_DEVICE (which means we got an ENXIO when we tried
2717 * to bind, which means this interface isn't in the list of interfaces
2718 * attached to BPF) and 1 otherwise.
2721 check_bpf_bindable(const char *name)
2724 char errbuf[PCAP_ERRBUF_SIZE];
2727 * On macOS, we don't do this check if the device name begins
2728 * with "wlt"; at least some versions of macOS (actually, it
2729 * was called "Mac OS X" then...) offer monitor mode capturing
2730 * by having a separate "monitor mode" device for each wireless
2731 * adapter, rather than by implementing the ioctls that
2732 * {Free,Net,Open,DragonFly}BSD provide. Opening that device
2733 * puts the adapter into monitor mode, which, at least for
2734 * some adapters, causes them to deassociate from the network
2735 * with which they're associated.
2737 * Instead, we try to open the corresponding "en" device (so
2738 * that we don't end up with, for users without sufficient
2739 * privilege to open capture devices, a list of adapters that
2740 * only includes the wlt devices).
2743 if (strncmp(name, "wlt", 3) == 0) {
2748 * Try to allocate a buffer for the "en"
2751 en_name_len = strlen(name) - 1;
2752 en_name = malloc(en_name_len + 1);
2753 if (en_name == NULL) {
2754 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2758 strcpy(en_name, "en");
2759 strcat(en_name, name + 3);
2760 fd = bpf_open_and_bind(en_name, errbuf);
2763 #endif /* __APPLE */
2764 fd = bpf_open_and_bind(name, errbuf);
2767 * Error - was it PCAP_ERROR_NO_SUCH_DEVICE?
2769 if (fd == PCAP_ERROR_NO_SUCH_DEVICE) {
2771 * Yes, so we can't bind to this because it's
2772 * not something supported by BPF.
2777 * No, so we don't know whether it's supported or not;
2778 * say it is, so that the user can at least try to
2779 * open it and report the error (which is probably
2780 * "you don't have permission to open BPF devices";
2781 * reporting those interfaces means users will ask
2782 * "why am I getting a permissions error when I try
2783 * to capture" rather than "why am I not seeing any
2784 * interfaces", making the underlying problem clearer).
2796 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
2798 get_usb_if_flags(const char *name _U_, bpf_u_int32 *flags _U_, char *errbuf _U_)
2801 * XXX - if there's a way to determine whether there's something
2802 * plugged into a given USB bus, use that to determine whether
2803 * this device is "connected" or not.
2809 finddevs_usb(pcap_if_list_t *devlistp, char *errbuf)
2812 struct dirent *usbitem;
2817 * We might have USB sniffing support, so try looking for USB
2820 * We want to report a usbusN device for each USB bus, but
2821 * usbusN interfaces might, or might not, exist for them -
2822 * we create one if there isn't already one.
2824 * So, instead, we look in /dev/usb for all buses and create
2825 * a "usbusN" device for each one.
2827 usbdir = opendir("/dev/usb");
2828 if (usbdir == NULL) {
2836 * Leave enough room for a 32-bit (10-digit) bus number.
2837 * Yes, that's overkill, but we won't be using
2838 * the buffer very long.
2840 name_max = USBUS_PREFIX_LEN + 10 + 1;
2841 name = malloc(name_max);
2846 while ((usbitem = readdir(usbdir)) != NULL) {
2850 if (strcmp(usbitem->d_name, ".") == 0 ||
2851 strcmp(usbitem->d_name, "..") == 0) {
2857 p = strchr(usbitem->d_name, '.');
2860 busnumlen = p - usbitem->d_name;
2861 memcpy(name, usbus_prefix, USBUS_PREFIX_LEN);
2862 memcpy(name + USBUS_PREFIX_LEN, usbitem->d_name, busnumlen);
2863 *(name + USBUS_PREFIX_LEN + busnumlen) = '\0';
2865 * There's an entry in this directory for every USB device,
2866 * not for every bus; if there's more than one device on
2867 * the bus, there'll be more than one entry for that bus,
2868 * so we need to avoid adding multiple capture devices
2871 if (find_or_add_dev(devlistp, name, PCAP_IF_UP,
2872 get_usb_if_flags, NULL, errbuf) == NULL) {
2875 return (PCAP_ERROR);
2885 * Get additional flags for a device, using SIOCGIFMEDIA.
2889 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
2892 struct ifmediareq req;
2894 sock = socket(AF_INET, SOCK_DGRAM, 0);
2896 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
2897 "Can't create socket to get media information for %s",
2901 memset(&req, 0, sizeof(req));
2902 pcap_strlcpy(req.ifm_name, name, sizeof(req.ifm_name));
2903 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2904 if (errno == EOPNOTSUPP || errno == EINVAL || errno == ENOTTY ||
2905 errno == ENODEV || errno == EPERM
2911 * Not supported, so we can't provide any
2912 * additional information. Assume that
2913 * this means that "connected" vs.
2914 * "disconnected" doesn't apply.
2916 * The ioctl routine for Apple's pktap devices,
2917 * annoyingly, checks for "are you root?" before
2918 * checking whether the ioctl is valid, so it
2919 * returns EPERM, rather than ENOTSUP, for the
2920 * invalid SIOCGIFMEDIA, unless you're root.
2921 * So, just as we do for some ethtool ioctls
2922 * on Linux, which makes the same mistake, we
2923 * also treat EPERM as meaning "not supported".
2925 * And it appears that Apple's llw0 device, which
2926 * appears to be part of the Skywalk subsystem:
2928 * http://newosxbook.com/bonus/vol1ch16.html
2930 * can sometimes return EPWROFF ("Device power
2931 * is off") for that ioctl, so we treat *that*
2932 * as another indication that we can't get a
2933 * connection status. (If it *isn't* "powered
2934 * off", it's reported as a wireless device,
2935 * complete with an active/inactive state.)
2937 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2941 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
2942 "SIOCGIFMEDIA on %s failed", name);
2949 * OK, what type of network is this?
2951 switch (IFM_TYPE(req.ifm_active)) {
2957 *flags |= PCAP_IF_WIRELESS;
2962 * Do we know whether it's connected?
2964 if (req.ifm_status & IFM_AVALID) {
2968 if (req.ifm_status & IFM_ACTIVE) {
2972 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2975 * It's disconnected.
2977 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2984 get_if_flags(const char *name _U_, bpf_u_int32 *flags, char *errbuf _U_)
2987 * Nothing we can do other than mark loopback devices as "the
2988 * connected/disconnected status doesn't apply".
2990 * XXX - on Solaris, can we do what the dladm command does,
2991 * i.e. get a connected/disconnected indication from a kstat?
2992 * (Note that you can also get the link speed, and possibly
2993 * other information, from a kstat as well.)
2995 if (*flags & PCAP_IF_LOOPBACK) {
2997 * Loopback devices aren't wireless, and "connected"/
2998 * "disconnected" doesn't apply to them.
3000 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
3008 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
3011 * Get the list of regular interfaces first.
3013 if (pcap_findalldevs_interfaces(devlistp, errbuf, check_bpf_bindable,
3014 get_if_flags) == -1)
3015 return (-1); /* failure */
3017 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
3018 if (finddevs_usb(devlistp, errbuf) == -1)
3025 #ifdef HAVE_BSD_IEEE80211
3027 monitor_mode(pcap_t *p, int set)
3029 struct pcap_bpf *pb = p->priv;
3031 struct ifmediareq req;
3032 IFM_ULIST_TYPE *media_list;
3037 sock = socket(AF_INET, SOCK_DGRAM, 0);
3039 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3040 errno, "can't open socket");
3041 return (PCAP_ERROR);
3044 memset(&req, 0, sizeof req);
3045 pcap_strlcpy(req.ifm_name, p->opt.device, sizeof req.ifm_name);
3048 * Find out how many media types we have.
3050 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
3052 * Can't get the media types.
3058 * There's no such device.
3060 * There's nothing more to say, so clear the
3063 p->errbuf[0] = '\0';
3065 return (PCAP_ERROR_NO_SUCH_DEVICE);
3069 * Interface doesn't support SIOC{G,S}IFMEDIA.
3072 return (PCAP_ERROR_RFMON_NOTSUP);
3075 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3076 errno, "SIOCGIFMEDIA");
3078 return (PCAP_ERROR);
3081 if (req.ifm_count == 0) {
3086 return (PCAP_ERROR_RFMON_NOTSUP);
3090 * Allocate a buffer to hold all the media types, and
3091 * get the media types.
3093 media_list = malloc(req.ifm_count * sizeof(*media_list));
3094 if (media_list == NULL) {
3095 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3098 return (PCAP_ERROR);
3100 req.ifm_ulist = media_list;
3101 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
3102 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3103 errno, "SIOCGIFMEDIA");
3106 return (PCAP_ERROR);
3110 * Look for an 802.11 "automatic" media type.
3111 * We assume that all 802.11 adapters have that media type,
3112 * and that it will carry the monitor mode supported flag.
3115 for (i = 0; i < req.ifm_count; i++) {
3116 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
3117 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
3118 /* OK, does it do monitor mode? */
3119 if (media_list[i] & IFM_IEEE80211_MONITOR) {
3128 * This adapter doesn't support monitor mode.
3131 return (PCAP_ERROR_RFMON_NOTSUP);
3136 * Don't just check whether we can enable monitor mode,
3137 * do so, if it's not already enabled.
3139 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
3141 * Monitor mode isn't currently on, so turn it on,
3142 * and remember that we should turn it off when the
3147 * If we haven't already done so, arrange to have
3148 * "pcap_close_all()" called when we exit.
3150 if (!pcap_do_addexit(p)) {
3152 * "atexit()" failed; don't put the interface
3153 * in monitor mode, just give up.
3156 return (PCAP_ERROR);
3158 memset(&ifr, 0, sizeof(ifr));
3159 (void)pcap_strlcpy(ifr.ifr_name, p->opt.device,
3160 sizeof(ifr.ifr_name));
3161 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
3162 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
3163 pcap_fmt_errmsg_for_errno(p->errbuf,
3164 PCAP_ERRBUF_SIZE, errno, "SIOCSIFMEDIA");
3166 return (PCAP_ERROR);
3169 pb->must_do_on_close |= MUST_CLEAR_RFMON;
3172 * Add this to the list of pcaps to close when we exit.
3174 pcap_add_to_pcaps_to_close(p);
3179 #endif /* HAVE_BSD_IEEE80211 */
3181 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
3183 * Check whether we have any 802.11 link-layer types; return the best
3184 * of the 802.11 link-layer types if we find one, and return -1
3187 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
3188 * best 802.11 link-layer type; any of the other 802.11-plus-radio
3189 * headers are second-best; 802.11 with no radio information is
3193 find_802_11(struct bpf_dltlist *bdlp)
3199 * Scan the list of DLT_ values, looking for 802.11 values,
3200 * and, if we find any, choose the best of them.
3203 for (i = 0; i < bdlp->bfl_len; i++) {
3204 switch (bdlp->bfl_list[i]) {
3206 case DLT_IEEE802_11:
3208 * 802.11, but no radio.
3210 * Offer this, and select it as the new mode
3211 * unless we've already found an 802.11
3212 * header with radio information.
3215 new_dlt = bdlp->bfl_list[i];
3218 #ifdef DLT_PRISM_HEADER
3219 case DLT_PRISM_HEADER:
3221 #ifdef DLT_AIRONET_HEADER
3222 case DLT_AIRONET_HEADER:
3224 case DLT_IEEE802_11_RADIO_AVS:
3226 * 802.11 with radio, but not radiotap.
3228 * Offer this, and select it as the new mode
3229 * unless we've already found the radiotap DLT_.
3231 if (new_dlt != DLT_IEEE802_11_RADIO)
3232 new_dlt = bdlp->bfl_list[i];
3235 case DLT_IEEE802_11_RADIO:
3237 * 802.11 with radiotap.
3239 * Offer this, and select it as the new mode.
3241 new_dlt = bdlp->bfl_list[i];
3254 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
3256 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
3258 * Remove non-802.11 header types from the list of DLT_ values, as we're in
3259 * monitor mode, and those header types aren't supported in monitor mode.
3262 remove_non_802_11(pcap_t *p)
3267 * Scan the list of DLT_ values and discard non-802.11 ones.
3270 for (i = 0; i < p->dlt_count; i++) {
3271 switch (p->dlt_list[i]) {
3276 * Not 802.11. Don't offer this one.
3282 * Just copy this mode over.
3288 * Copy this DLT_ value to its new position.
3290 p->dlt_list[j] = p->dlt_list[i];
3295 * Set the DLT_ count to the number of entries we copied.
3301 * Remove 802.11 link-layer types from the list of DLT_ values, as
3302 * we're not in monitor mode, and those DLT_ values will switch us
3306 remove_802_11(pcap_t *p)
3311 * Scan the list of DLT_ values and discard 802.11 values.
3314 for (i = 0; i < p->dlt_count; i++) {
3315 switch (p->dlt_list[i]) {
3317 case DLT_IEEE802_11:
3318 #ifdef DLT_PRISM_HEADER
3319 case DLT_PRISM_HEADER:
3321 #ifdef DLT_AIRONET_HEADER
3322 case DLT_AIRONET_HEADER:
3324 case DLT_IEEE802_11_RADIO:
3325 case DLT_IEEE802_11_RADIO_AVS:
3330 * 802.11. Don't offer this one.
3336 * Just copy this mode over.
3342 * Copy this DLT_ value to its new position.
3344 p->dlt_list[j] = p->dlt_list[i];
3349 * Set the DLT_ count to the number of entries we copied.
3353 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
3356 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
3358 struct pcap_bpf *pb = p->priv;
3361 * Free any user-mode filter we might happen to have installed.
3363 pcap_freecode(&p->fcode);
3366 * Try to install the kernel filter.
3368 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
3372 pb->filtering_in_kernel = 1; /* filtering in the kernel */
3375 * Discard any previously-received packets, as they might
3376 * have passed whatever filter was formerly in effect, but
3377 * might not pass this filter (BIOCSETF discards packets
3378 * buffered in the kernel, so you can lose packets in any
3388 * If it failed with EINVAL, that's probably because the program
3389 * is invalid or too big. Validate it ourselves; if we like it
3390 * (we currently allow backward branches, to support protochain),
3391 * run it in userland. (There's no notion of "too big" for
3394 * Otherwise, just give up.
3395 * XXX - if the copy of the program into the kernel failed,
3396 * we will get EINVAL rather than, say, EFAULT on at least
3399 if (errno != EINVAL) {
3400 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3406 * install_bpf_program() validates the program.
3408 * XXX - what if we already have a filter in the kernel?
3410 if (install_bpf_program(p, fp) < 0)
3412 pb->filtering_in_kernel = 0; /* filtering in userland */
3417 * Set direction flag: Which packets do we accept on a forwarding
3418 * single device? IN, OUT or both?
3420 #if defined(BIOCSDIRECTION)
3422 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3425 const char *direction_name;
3428 * FreeBSD and NetBSD.
3434 * Incoming, but not outgoing, so accept only
3437 direction = BPF_D_IN;
3438 direction_name = "\"incoming only\"";
3443 * Outgoing, but not incoming, so accept only
3446 direction = BPF_D_OUT;
3447 direction_name = "\"outgoing only\"";
3452 * Incoming and outgoing, so accept both
3453 * incoming and outgoing packets.
3455 * It's guaranteed, at this point, that d is a valid
3456 * direction value, so we know that this is PCAP_D_INOUT
3457 * if it's not PCAP_D_IN or PCAP_D_OUT.
3459 direction = BPF_D_INOUT;
3460 direction_name = "\"incoming and outgoing\"";
3464 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
3465 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3466 errno, "Cannot set direction to %s", direction_name);
3471 #elif defined(BIOCSDIRFILT)
3473 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3476 const char *direction_name;
3479 * OpenBSD; same functionality, different names, different
3480 * semantics (the flags mean "*don't* capture packets in
3481 * that direction", not "*capture only* packets in that
3488 * Incoming, but not outgoing, so filter out
3491 dirfilt = BPF_DIRECTION_OUT;
3492 direction_name = "\"incoming only\"";
3497 * Outgoing, but not incoming, so filter out
3500 dirfilt = BPF_DIRECTION_IN;
3501 direction_name = "\"outgoing only\"";
3506 * Incoming and outgoing, so don't filter out
3507 * any packets based on direction.
3509 * It's guaranteed, at this point, that d is a valid
3510 * direction value, so we know that this is PCAP_D_INOUT
3511 * if it's not PCAP_D_IN or PCAP_D_OUT.
3514 direction_name = "\"incoming and outgoing\"";
3517 if (ioctl(p->fd, BIOCSDIRFILT, &dirfilt) == -1) {
3518 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3519 errno, "Cannot set direction to %s", direction_name);
3524 #elif defined(BIOCSSEESENT)
3526 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3529 const char *direction_name;
3532 * OS with just BIOCSSEESENT.
3538 * Incoming, but not outgoing, so we don't want to
3539 * see transmitted packets.
3542 direction_name = "\"incoming only\"";
3547 * Outgoing, but not incoming; we can't specify that.
3549 snprintf(p->errbuf, sizeof(p->errbuf),
3550 "Setting direction to \"outgoing only\" is not supported on this device");
3555 * Incoming and outgoing, so we want to see transmitted
3558 * It's guaranteed, at this point, that d is a valid
3559 * direction value, so we know that this is PCAP_D_INOUT
3560 * if it's not PCAP_D_IN or PCAP_D_OUT.
3563 direction_name = "\"incoming and outgoing\"";
3567 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
3568 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3569 errno, "Cannot set direction to %s", direction_name);
3576 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d _U_)
3578 (void) snprintf(p->errbuf, sizeof(p->errbuf),
3579 "Setting direction is not supported on this device");
3586 pcap_set_datalink_bpf(pcap_t *p, int dlt)
3588 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
3589 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3590 errno, "Cannot set DLT %d", dlt);
3597 pcap_set_datalink_bpf(pcap_t *p _U_, int dlt _U_)
3604 * Platform-specific information.
3607 pcap_lib_version(void)
3609 #ifdef HAVE_ZEROCOPY_BPF
3610 return (PCAP_VERSION_STRING " (with zerocopy support)");
3612 return (PCAP_VERSION_STRING);