kernel: avoid possible sysctl integer overflow in acpi_thinkpad(4)
[dragonfly.git] / contrib / libpcap / pcap-bpf.c
blob8162398dcd605cec3e49e3015cdf527bca0dd8e2
1 /*
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
16 * written permission.
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.
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
26 #include <sys/param.h> /* optionally get BSD define */
27 #include <sys/socket.h>
28 #include <time.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>
45 #endif
46 #include <sys/utsname.h>
48 #if (defined(__FreeBSD__) || defined(__DragonFly__)) && 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)
54 #include <dirent.h>
55 #endif
57 #include <net/if.h>
59 #ifdef _AIX
61 #include <sys/types.h>
64 * Prevent bpf.h from redefining the DLT_ values to their
65 * IFT_ values, as we're going to return the standard libpcap
66 * values, not IBM's non-standard IFT_ values.
68 #undef _AIX
69 #include <net/bpf.h>
70 #define _AIX
73 * If both BIOCROTZBUF and BPF_BUFMODE_ZBUF are defined, we have
74 * zero-copy BPF.
76 #if defined(BIOCROTZBUF) && defined(BPF_BUFMODE_ZBUF)
77 #define HAVE_ZEROCOPY_BPF
78 #include <sys/mman.h>
79 #include <machine/atomic.h>
80 #endif
82 #include <net/if_types.h> /* for IFT_ values */
83 #include <sys/sysconfig.h>
84 #include <sys/device.h>
85 #include <sys/cfgodm.h>
86 #include <cf.h>
88 #ifdef __64BIT__
89 #define domakedev makedev64
90 #define getmajor major64
91 #define bpf_hdr bpf_hdr32
92 #else /* __64BIT__ */
93 #define domakedev makedev
94 #define getmajor major
95 #endif /* __64BIT__ */
97 #define BPF_NAME "bpf"
98 #define BPF_MINORS 4
99 #define DRIVER_PATH "/usr/lib/drivers"
100 #define BPF_NODE "/dev/bpf"
101 static int bpfloadedflag = 0;
102 static int odmlockid = 0;
104 static int bpf_load(char *errbuf);
106 #else /* _AIX */
108 #include <net/bpf.h>
110 #endif /* _AIX */
112 #include <ctype.h>
113 #include <fcntl.h>
114 #include <errno.h>
115 #include <netdb.h>
116 #include <stdio.h>
117 #include <stdlib.h>
118 #include <string.h>
119 #include <unistd.h>
121 #ifdef SIOCGIFMEDIA
122 # include <net/if_media.h>
123 #endif
125 #include "pcap-int.h"
127 #ifdef HAVE_OS_PROTO_H
128 #include "os-proto.h"
129 #endif
132 * Later versions of NetBSD stick padding in front of FDDI frames
133 * to align the IP header on a 4-byte boundary.
135 #if defined(__NetBSD__) && __NetBSD_Version__ > 106000000
136 #define PCAP_FDDIPAD 3
137 #endif
140 * Private data for capturing on BPF devices.
142 struct pcap_bpf {
143 #ifdef HAVE_ZEROCOPY_BPF
145 * Zero-copy read buffer -- for zero-copy BPF. 'buffer' above will
146 * alternative between these two actual mmap'd buffers as required.
147 * As there is a header on the front size of the mmap'd buffer, only
148 * some of the buffer is exposed to libpcap as a whole via bufsize;
149 * zbufsize is the true size. zbuffer tracks the current zbuf
150 * assocated with buffer so that it can be used to decide which the
151 * next buffer to read will be.
153 u_char *zbuf1, *zbuf2, *zbuffer;
154 u_int zbufsize;
155 u_int zerocopy;
156 u_int interrupted;
157 struct timespec firstsel;
159 * If there's currently a buffer being actively processed, then it is
160 * referenced here; 'buffer' is also pointed at it, but offset by the
161 * size of the header.
163 struct bpf_zbuf_header *bzh;
164 int nonblock; /* true if in nonblocking mode */
165 #endif /* HAVE_ZEROCOPY_BPF */
167 char *device; /* device name */
168 int filtering_in_kernel; /* using kernel filter */
169 int must_do_on_close; /* stuff we must do when we close */
173 * Stuff to do when we close.
175 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
176 #define MUST_DESTROY_USBUS 0x00000002 /* destroy usbusN interface */
178 #ifdef BIOCGDLTLIST
179 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
180 #define HAVE_BSD_IEEE80211
183 * The ifm_ulist member of a struct ifmediareq is an int * on most systems,
184 * but it's a uint64_t on newer versions of OpenBSD.
186 * We check this by checking whether IFM_GMASK is defined and > 2^32-1.
188 # if defined(IFM_GMASK) && IFM_GMASK > 0xFFFFFFFF
189 # define IFM_ULIST_TYPE uint64_t
190 # else
191 # define IFM_ULIST_TYPE int
192 # endif
193 # endif
195 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
196 static int find_802_11(struct bpf_dltlist *);
198 # ifdef HAVE_BSD_IEEE80211
199 static int monitor_mode(pcap_t *, int);
200 # endif
202 # if defined(__APPLE__)
203 static void remove_non_802_11(pcap_t *);
204 static void remove_802_11(pcap_t *);
205 # endif
207 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
209 #endif /* BIOCGDLTLIST */
211 #if defined(sun) && defined(LIFNAMSIZ) && defined(lifr_zoneid)
212 #include <zone.h>
213 #endif
216 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
217 * don't get DLT_DOCSIS defined.
219 #ifndef DLT_DOCSIS
220 #define DLT_DOCSIS 143
221 #endif
224 * In some versions of macOS, we might not even get any of the
225 * 802.11-plus-radio-header DLT_'s defined, even though some
226 * of them are used by various Airport drivers in those versions.
228 #ifndef DLT_PRISM_HEADER
229 #define DLT_PRISM_HEADER 119
230 #endif
231 #ifndef DLT_AIRONET_HEADER
232 #define DLT_AIRONET_HEADER 120
233 #endif
234 #ifndef DLT_IEEE802_11_RADIO
235 #define DLT_IEEE802_11_RADIO 127
236 #endif
237 #ifndef DLT_IEEE802_11_RADIO_AVS
238 #define DLT_IEEE802_11_RADIO_AVS 163
239 #endif
241 static int pcap_can_set_rfmon_bpf(pcap_t *p);
242 static int pcap_activate_bpf(pcap_t *p);
243 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
244 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
245 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
248 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
249 * pb->nonblock so we don't call select(2) if the pcap handle is in non-
250 * blocking mode.
252 static int
253 pcap_getnonblock_bpf(pcap_t *p)
255 #ifdef HAVE_ZEROCOPY_BPF
256 struct pcap_bpf *pb = p->priv;
258 if (pb->zerocopy)
259 return (pb->nonblock);
260 #endif
261 return (pcap_getnonblock_fd(p));
264 static int
265 pcap_setnonblock_bpf(pcap_t *p, int nonblock)
267 #ifdef HAVE_ZEROCOPY_BPF
268 struct pcap_bpf *pb = p->priv;
270 if (pb->zerocopy) {
271 pb->nonblock = nonblock;
272 return (0);
274 #endif
275 return (pcap_setnonblock_fd(p, nonblock));
278 #ifdef HAVE_ZEROCOPY_BPF
280 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
281 * shared memory buffers.
283 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
284 * and set up p->buffer and cc to reflect one if available. Notice that if
285 * there was no prior buffer, we select zbuf1 as this will be the first
286 * buffer filled for a fresh BPF session.
288 static int
289 pcap_next_zbuf_shm(pcap_t *p, int *cc)
291 struct pcap_bpf *pb = p->priv;
292 struct bpf_zbuf_header *bzh;
294 if (pb->zbuffer == pb->zbuf2 || pb->zbuffer == NULL) {
295 bzh = (struct bpf_zbuf_header *)pb->zbuf1;
296 if (bzh->bzh_user_gen !=
297 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
298 pb->bzh = bzh;
299 pb->zbuffer = (u_char *)pb->zbuf1;
300 p->buffer = pb->zbuffer + sizeof(*bzh);
301 *cc = bzh->bzh_kernel_len;
302 return (1);
304 } else if (pb->zbuffer == pb->zbuf1) {
305 bzh = (struct bpf_zbuf_header *)pb->zbuf2;
306 if (bzh->bzh_user_gen !=
307 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
308 pb->bzh = bzh;
309 pb->zbuffer = (u_char *)pb->zbuf2;
310 p->buffer = pb->zbuffer + sizeof(*bzh);
311 *cc = bzh->bzh_kernel_len;
312 return (1);
315 *cc = 0;
316 return (0);
320 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
321 * select() for data or a timeout, and possibly force rotation of the buffer
322 * in the event we time out or are in immediate mode. Invoke the shared
323 * memory check before doing system calls in order to avoid doing avoidable
324 * work.
326 static int
327 pcap_next_zbuf(pcap_t *p, int *cc)
329 struct pcap_bpf *pb = p->priv;
330 struct bpf_zbuf bz;
331 struct timeval tv;
332 struct timespec cur;
333 fd_set r_set;
334 int data, r;
335 int expire, tmout;
337 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
339 * Start out by seeing whether anything is waiting by checking the
340 * next shared memory buffer for data.
342 data = pcap_next_zbuf_shm(p, cc);
343 if (data)
344 return (data);
346 * If a previous sleep was interrupted due to signal delivery, make
347 * sure that the timeout gets adjusted accordingly. This requires
348 * that we analyze when the timeout should be been expired, and
349 * subtract the current time from that. If after this operation,
350 * our timeout is less then or equal to zero, handle it like a
351 * regular timeout.
353 tmout = p->opt.timeout;
354 if (tmout)
355 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
356 if (pb->interrupted && p->opt.timeout) {
357 expire = TSTOMILLI(&pb->firstsel) + p->opt.timeout;
358 tmout = expire - TSTOMILLI(&cur);
359 #undef TSTOMILLI
360 if (tmout <= 0) {
361 pb->interrupted = 0;
362 data = pcap_next_zbuf_shm(p, cc);
363 if (data)
364 return (data);
365 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
366 pcap_fmt_errmsg_for_errno(p->errbuf,
367 PCAP_ERRBUF_SIZE, errno, "BIOCROTZBUF");
368 return (PCAP_ERROR);
370 return (pcap_next_zbuf_shm(p, cc));
374 * No data in the buffer, so must use select() to wait for data or
375 * the next timeout. Note that we only call select if the handle
376 * is in blocking mode.
378 if (!pb->nonblock) {
379 FD_ZERO(&r_set);
380 FD_SET(p->fd, &r_set);
381 if (tmout != 0) {
382 tv.tv_sec = tmout / 1000;
383 tv.tv_usec = (tmout * 1000) % 1000000;
385 r = select(p->fd + 1, &r_set, NULL, NULL,
386 p->opt.timeout != 0 ? &tv : NULL);
387 if (r < 0 && errno == EINTR) {
388 if (!pb->interrupted && p->opt.timeout) {
389 pb->interrupted = 1;
390 pb->firstsel = cur;
392 return (0);
393 } else if (r < 0) {
394 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
395 errno, "select");
396 return (PCAP_ERROR);
399 pb->interrupted = 0;
401 * Check again for data, which may exist now that we've either been
402 * woken up as a result of data or timed out. Try the "there's data"
403 * case first since it doesn't require a system call.
405 data = pcap_next_zbuf_shm(p, cc);
406 if (data)
407 return (data);
409 * Try forcing a buffer rotation to dislodge timed out or immediate
410 * data.
412 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
413 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
414 errno, "BIOCROTZBUF");
415 return (PCAP_ERROR);
417 return (pcap_next_zbuf_shm(p, cc));
421 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
422 * that we know which buffer to use next time around.
424 static int
425 pcap_ack_zbuf(pcap_t *p)
427 struct pcap_bpf *pb = p->priv;
429 atomic_store_rel_int(&pb->bzh->bzh_user_gen,
430 pb->bzh->bzh_kernel_gen);
431 pb->bzh = NULL;
432 p->buffer = NULL;
433 return (0);
435 #endif /* HAVE_ZEROCOPY_BPF */
437 pcap_t *
438 pcap_create_interface(const char *device _U_, char *ebuf)
440 pcap_t *p;
442 p = pcap_create_common(ebuf, sizeof (struct pcap_bpf));
443 if (p == NULL)
444 return (NULL);
446 p->activate_op = pcap_activate_bpf;
447 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
448 #ifdef BIOCSTSTAMP
450 * We claim that we support microsecond and nanosecond time
451 * stamps.
453 p->tstamp_precision_count = 2;
454 p->tstamp_precision_list = malloc(2 * sizeof(u_int));
455 if (p->tstamp_precision_list == NULL) {
456 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno,
457 "malloc");
458 free(p);
459 return (NULL);
461 p->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
462 p->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
463 #endif /* BIOCSTSTAMP */
464 return (p);
468 * On success, returns a file descriptor for a BPF device.
469 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
471 static int
472 bpf_open(char *errbuf)
474 int fd = -1;
475 static const char cloning_device[] = "/dev/bpf";
476 int n = 0;
477 char device[sizeof "/dev/bpf0000000000"];
478 static int no_cloning_bpf = 0;
480 #ifdef _AIX
482 * Load the bpf driver, if it isn't already loaded,
483 * and create the BPF device entries, if they don't
484 * already exist.
486 if (bpf_load(errbuf) == PCAP_ERROR)
487 return (PCAP_ERROR);
488 #endif
491 * First, unless we've already tried opening /dev/bpf and
492 * gotten ENOENT, try opening /dev/bpf.
493 * If it fails with ENOENT, remember that, so we don't try
494 * again, and try /dev/bpfN.
496 if (!no_cloning_bpf &&
497 (fd = open(cloning_device, O_RDWR)) == -1 &&
498 ((errno != EACCES && errno != ENOENT) ||
499 (fd = open(cloning_device, O_RDONLY)) == -1)) {
500 if (errno != ENOENT) {
501 if (errno == EACCES)
502 fd = PCAP_ERROR_PERM_DENIED;
503 else
504 fd = PCAP_ERROR;
505 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
506 errno, "(cannot open device) %s", cloning_device);
507 return (fd);
509 no_cloning_bpf = 1;
512 if (no_cloning_bpf) {
514 * We don't have /dev/bpf.
515 * Go through all the /dev/bpfN minors and find one
516 * that isn't in use.
518 do {
519 (void)pcap_snprintf(device, sizeof(device), "/dev/bpf%d", n++);
521 * Initially try a read/write open (to allow the inject
522 * method to work). If that fails due to permission
523 * issues, fall back to read-only. This allows a
524 * non-root user to be granted specific access to pcap
525 * capabilities via file permissions.
527 * XXX - we should have an API that has a flag that
528 * controls whether to open read-only or read-write,
529 * so that denial of permission to send (or inability
530 * to send, if sending packets isn't supported on
531 * the device in question) can be indicated at open
532 * time.
534 fd = open(device, O_RDWR);
535 if (fd == -1 && errno == EACCES)
536 fd = open(device, O_RDONLY);
537 } while (fd < 0 && errno == EBUSY);
541 * XXX better message for all minors used
543 if (fd < 0) {
544 switch (errno) {
546 case ENOENT:
547 fd = PCAP_ERROR;
548 if (n == 1) {
550 * /dev/bpf0 doesn't exist, which
551 * means we probably have no BPF
552 * devices.
554 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
555 "(there are no BPF devices)");
556 } else {
558 * We got EBUSY on at least one
559 * BPF device, so we have BPF
560 * devices, but all the ones
561 * that exist are busy.
563 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
564 "(all BPF devices are busy)");
566 break;
568 case EACCES:
570 * Got EACCES on the last device we tried,
571 * and EBUSY on all devices before that,
572 * if any.
574 fd = PCAP_ERROR_PERM_DENIED;
575 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
576 errno, "(cannot open BPF device) %s", device);
577 break;
579 default:
581 * Some other problem.
583 fd = PCAP_ERROR;
584 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
585 errno, "(cannot open BPF device) %s", device);
586 break;
590 return (fd);
594 * Open and bind to a device; used if we're not actually going to use
595 * the device, but are just testing whether it can be opened, or opening
596 * it to get information about it.
598 * Returns an error code on failure (always negative), and an FD for
599 * the now-bound BPF device on success (always non-negative).
601 static int
602 bpf_open_and_bind(const char *name, char *errbuf)
604 int fd;
605 struct ifreq ifr;
608 * First, open a BPF device.
610 fd = bpf_open(errbuf);
611 if (fd < 0)
612 return (fd); /* fd is the appropriate error code */
615 * Now bind to the device.
617 (void)strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
618 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
619 switch (errno) {
621 case ENXIO:
623 * There's no such device.
625 close(fd);
626 return (PCAP_ERROR_NO_SUCH_DEVICE);
628 case ENETDOWN:
630 * Return a "network down" indication, so that
631 * the application can report that rather than
632 * saying we had a mysterious failure and
633 * suggest that they report a problem to the
634 * libpcap developers.
636 close(fd);
637 return (PCAP_ERROR_IFACE_NOT_UP);
639 default:
640 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
641 errno, "BIOCSETIF: %s", name);
642 close(fd);
643 return (PCAP_ERROR);
648 * Success.
650 return (fd);
653 #ifdef BIOCGDLTLIST
654 static int
655 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
657 memset(bdlp, 0, sizeof(*bdlp));
658 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
659 u_int i;
660 int is_ethernet;
662 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
663 if (bdlp->bfl_list == NULL) {
664 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
665 errno, "malloc");
666 return (PCAP_ERROR);
669 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
670 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
671 errno, "BIOCGDLTLIST");
672 free(bdlp->bfl_list);
673 return (PCAP_ERROR);
677 * OK, for real Ethernet devices, add DLT_DOCSIS to the
678 * list, so that an application can let you choose it,
679 * in case you're capturing DOCSIS traffic that a Cisco
680 * Cable Modem Termination System is putting out onto
681 * an Ethernet (it doesn't put an Ethernet header onto
682 * the wire, it puts raw DOCSIS frames out on the wire
683 * inside the low-level Ethernet framing).
685 * A "real Ethernet device" is defined here as a device
686 * that has a link-layer type of DLT_EN10MB and that has
687 * no alternate link-layer types; that's done to exclude
688 * 802.11 interfaces (which might or might not be the
689 * right thing to do, but I suspect it is - Ethernet <->
690 * 802.11 bridges would probably badly mishandle frames
691 * that don't have Ethernet headers).
693 * On Solaris with BPF, Ethernet devices also offer
694 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
695 * treat it as an indication that the device isn't an
696 * Ethernet.
698 if (v == DLT_EN10MB) {
699 is_ethernet = 1;
700 for (i = 0; i < bdlp->bfl_len; i++) {
701 if (bdlp->bfl_list[i] != DLT_EN10MB
702 #ifdef DLT_IPNET
703 && bdlp->bfl_list[i] != DLT_IPNET
704 #endif
706 is_ethernet = 0;
707 break;
710 if (is_ethernet) {
712 * We reserved one more slot at the end of
713 * the list.
715 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
716 bdlp->bfl_len++;
719 } else {
721 * EINVAL just means "we don't support this ioctl on
722 * this device"; don't treat it as an error.
724 if (errno != EINVAL) {
725 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
726 errno, "BIOCGDLTLIST");
727 return (PCAP_ERROR);
730 return (0);
732 #endif
734 #if defined(__APPLE__)
735 static int
736 pcap_can_set_rfmon_bpf(pcap_t *p)
738 struct utsname osinfo;
739 struct ifreq ifr;
740 int fd;
741 #ifdef BIOCGDLTLIST
742 struct bpf_dltlist bdl;
743 #endif
746 * The joys of monitor mode on Mac OS X/OS X/macOS.
748 * Prior to 10.4, it's not supported at all.
750 * In 10.4, if adapter enN supports monitor mode, there's a
751 * wltN adapter corresponding to it; you open it, instead of
752 * enN, to get monitor mode. You get whatever link-layer
753 * headers it supplies.
755 * In 10.5, and, we assume, later releases, if adapter enN
756 * supports monitor mode, it offers, among its selectable
757 * DLT_ values, values that let you get the 802.11 header;
758 * selecting one of those values puts the adapter into monitor
759 * mode (i.e., you can't get 802.11 headers except in monitor
760 * mode, and you can't get Ethernet headers in monitor mode).
762 if (uname(&osinfo) == -1) {
764 * Can't get the OS version; just say "no".
766 return (0);
769 * We assume osinfo.sysname is "Darwin", because
770 * __APPLE__ is defined. We just check the version.
772 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
774 * 10.3 (Darwin 7.x) or earlier.
775 * Monitor mode not supported.
777 return (0);
779 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
781 * 10.4 (Darwin 8.x). s/en/wlt/, and check
782 * whether the device exists.
784 if (strncmp(p->opt.device, "en", 2) != 0) {
786 * Not an enN device; no monitor mode.
788 return (0);
790 fd = socket(AF_INET, SOCK_DGRAM, 0);
791 if (fd == -1) {
792 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
793 errno, "socket");
794 return (PCAP_ERROR);
796 pcap_strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
797 pcap_strlcat(ifr.ifr_name, p->opt.device + 2, sizeof(ifr.ifr_name));
798 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
800 * No such device?
802 close(fd);
803 return (0);
805 close(fd);
806 return (1);
809 #ifdef BIOCGDLTLIST
811 * Everything else is 10.5 or later; for those,
812 * we just open the enN device, and check whether
813 * we have any 802.11 devices.
815 * First, open a BPF device.
817 fd = bpf_open(p->errbuf);
818 if (fd < 0)
819 return (fd); /* fd is the appropriate error code */
822 * Now bind to the device.
824 (void)strncpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
825 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
826 switch (errno) {
828 case ENXIO:
830 * There's no such device.
832 close(fd);
833 return (PCAP_ERROR_NO_SUCH_DEVICE);
835 case ENETDOWN:
837 * Return a "network down" indication, so that
838 * the application can report that rather than
839 * saying we had a mysterious failure and
840 * suggest that they report a problem to the
841 * libpcap developers.
843 close(fd);
844 return (PCAP_ERROR_IFACE_NOT_UP);
846 default:
847 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
848 errno, "BIOCSETIF: %s", p->opt.device);
849 close(fd);
850 return (PCAP_ERROR);
855 * We know the default link type -- now determine all the DLTs
856 * this interface supports. If this fails with EINVAL, it's
857 * not fatal; we just don't get to use the feature later.
858 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
859 * as the default DLT for this adapter.)
861 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
862 close(fd);
863 return (PCAP_ERROR);
865 if (find_802_11(&bdl) != -1) {
867 * We have an 802.11 DLT, so we can set monitor mode.
869 free(bdl.bfl_list);
870 close(fd);
871 return (1);
873 free(bdl.bfl_list);
874 close(fd);
875 #endif /* BIOCGDLTLIST */
876 return (0);
878 #elif defined(HAVE_BSD_IEEE80211)
879 static int
880 pcap_can_set_rfmon_bpf(pcap_t *p)
882 int ret;
884 ret = monitor_mode(p, 0);
885 if (ret == PCAP_ERROR_RFMON_NOTSUP)
886 return (0); /* not an error, just a "can't do" */
887 if (ret == 0)
888 return (1); /* success */
889 return (ret);
891 #else
892 static int
893 pcap_can_set_rfmon_bpf(pcap_t *p _U_)
895 return (0);
897 #endif
899 static int
900 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
902 struct bpf_stat s;
905 * "ps_recv" counts packets handed to the filter, not packets
906 * that passed the filter. This includes packets later dropped
907 * because we ran out of buffer space.
909 * "ps_drop" counts packets dropped inside the BPF device
910 * because we ran out of buffer space. It doesn't count
911 * packets dropped by the interface driver. It counts
912 * only packets that passed the filter.
914 * Both statistics include packets not yet read from the kernel
915 * by libpcap, and thus not yet seen by the application.
917 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
918 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
919 errno, "BIOCGSTATS");
920 return (PCAP_ERROR);
923 ps->ps_recv = s.bs_recv;
924 ps->ps_drop = s.bs_drop;
925 ps->ps_ifdrop = 0;
926 return (0);
929 static int
930 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
932 struct pcap_bpf *pb = p->priv;
933 int cc;
934 int n = 0;
935 register u_char *bp, *ep;
936 u_char *datap;
937 #ifdef PCAP_FDDIPAD
938 register u_int pad;
939 #endif
940 #ifdef HAVE_ZEROCOPY_BPF
941 int i;
942 #endif
944 again:
946 * Has "pcap_breakloop()" been called?
948 if (p->break_loop) {
950 * Yes - clear the flag that indicates that it
951 * has, and return PCAP_ERROR_BREAK to indicate
952 * that we were told to break out of the loop.
954 p->break_loop = 0;
955 return (PCAP_ERROR_BREAK);
957 cc = p->cc;
958 if (p->cc == 0) {
960 * When reading without zero-copy from a file descriptor, we
961 * use a single buffer and return a length of data in the
962 * buffer. With zero-copy, we update the p->buffer pointer
963 * to point at whatever underlying buffer contains the next
964 * data and update cc to reflect the data found in the
965 * buffer.
967 #ifdef HAVE_ZEROCOPY_BPF
968 if (pb->zerocopy) {
969 if (p->buffer != NULL)
970 pcap_ack_zbuf(p);
971 i = pcap_next_zbuf(p, &cc);
972 if (i == 0)
973 goto again;
974 if (i < 0)
975 return (PCAP_ERROR);
976 } else
977 #endif
979 cc = read(p->fd, p->buffer, p->bufsize);
981 if (cc < 0) {
982 /* Don't choke when we get ptraced */
983 switch (errno) {
985 case EINTR:
986 goto again;
988 #ifdef _AIX
989 case EFAULT:
991 * Sigh. More AIX wonderfulness.
993 * For some unknown reason the uiomove()
994 * operation in the bpf kernel extension
995 * used to copy the buffer into user
996 * space sometimes returns EFAULT. I have
997 * no idea why this is the case given that
998 * a kernel debugger shows the user buffer
999 * is correct. This problem appears to
1000 * be mostly mitigated by the memset of
1001 * the buffer before it is first used.
1002 * Very strange.... Shaun Clowes
1004 * In any case this means that we shouldn't
1005 * treat EFAULT as a fatal error; as we
1006 * don't have an API for returning
1007 * a "some packets were dropped since
1008 * the last packet you saw" indication,
1009 * we just ignore EFAULT and keep reading.
1011 goto again;
1012 #endif
1014 case EWOULDBLOCK:
1015 return (0);
1017 case ENXIO: /* FreeBSD, DragonFly BSD, and Darwin */
1018 case EIO: /* OpenBSD */
1019 /* NetBSD appears not to return an error in this case */
1021 * The device on which we're capturing
1022 * went away.
1024 * XXX - we should really return
1025 * an appropriate error for that,
1026 * but pcap_dispatch() etc. aren't
1027 * documented as having error returns
1028 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
1030 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1031 "The interface disappeared");
1032 return (PCAP_ERROR);
1034 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
1036 * Due to a SunOS bug, after 2^31 bytes, the kernel
1037 * file offset overflows and read fails with EINVAL.
1038 * The lseek() to 0 will fix things.
1040 case EINVAL:
1041 if (lseek(p->fd, 0L, SEEK_CUR) +
1042 p->bufsize < 0) {
1043 (void)lseek(p->fd, 0L, SEEK_SET);
1044 goto again;
1046 /* fall through */
1047 #endif
1049 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1050 errno, "read");
1051 return (PCAP_ERROR);
1053 bp = (u_char *)p->buffer;
1054 } else
1055 bp = p->bp;
1058 * Loop through each packet.
1060 #ifdef BIOCSTSTAMP
1061 #define bhp ((struct bpf_xhdr *)bp)
1062 #else
1063 #define bhp ((struct bpf_hdr *)bp)
1064 #endif
1065 ep = bp + cc;
1066 #ifdef PCAP_FDDIPAD
1067 pad = p->fddipad;
1068 #endif
1069 while (bp < ep) {
1070 register u_int caplen, hdrlen;
1073 * Has "pcap_breakloop()" been called?
1074 * If so, return immediately - if we haven't read any
1075 * packets, clear the flag and return PCAP_ERROR_BREAK
1076 * to indicate that we were told to break out of the loop,
1077 * otherwise leave the flag set, so that the *next* call
1078 * will break out of the loop without having read any
1079 * packets, and return the number of packets we've
1080 * processed so far.
1082 if (p->break_loop) {
1083 p->bp = bp;
1084 p->cc = ep - bp;
1086 * ep is set based on the return value of read(),
1087 * but read() from a BPF device doesn't necessarily
1088 * return a value that's a multiple of the alignment
1089 * value for BPF_WORDALIGN(). However, whenever we
1090 * increment bp, we round up the increment value by
1091 * a value rounded up by BPF_WORDALIGN(), so we
1092 * could increment bp past ep after processing the
1093 * last packet in the buffer.
1095 * We treat ep < bp as an indication that this
1096 * happened, and just set p->cc to 0.
1098 if (p->cc < 0)
1099 p->cc = 0;
1100 if (n == 0) {
1101 p->break_loop = 0;
1102 return (PCAP_ERROR_BREAK);
1103 } else
1104 return (n);
1107 caplen = bhp->bh_caplen;
1108 hdrlen = bhp->bh_hdrlen;
1109 datap = bp + hdrlen;
1111 * Short-circuit evaluation: if using BPF filter
1112 * in kernel, no need to do it now - we already know
1113 * the packet passed the filter.
1115 #ifdef PCAP_FDDIPAD
1116 * Note: the filter code was generated assuming
1117 * that p->fddipad was the amount of padding
1118 * before the header, as that's what's required
1119 * in the kernel, so we run the filter before
1120 * skipping that padding.
1121 #endif
1123 if (pb->filtering_in_kernel ||
1124 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1125 struct pcap_pkthdr pkthdr;
1126 #ifdef BIOCSTSTAMP
1127 struct bintime bt;
1129 bt.sec = bhp->bh_tstamp.bt_sec;
1130 bt.frac = bhp->bh_tstamp.bt_frac;
1131 if (p->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
1132 struct timespec ts;
1134 bintime2timespec(&bt, &ts);
1135 pkthdr.ts.tv_sec = ts.tv_sec;
1136 pkthdr.ts.tv_usec = ts.tv_nsec;
1137 } else {
1138 struct timeval tv;
1140 bintime2timeval(&bt, &tv);
1141 pkthdr.ts.tv_sec = tv.tv_sec;
1142 pkthdr.ts.tv_usec = tv.tv_usec;
1144 #else
1145 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1146 #ifdef _AIX
1148 * AIX's BPF returns seconds/nanoseconds time
1149 * stamps, not seconds/microseconds time stamps.
1151 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1152 #else
1153 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1154 #endif
1155 #endif /* BIOCSTSTAMP */
1156 #ifdef PCAP_FDDIPAD
1157 if (caplen > pad)
1158 pkthdr.caplen = caplen - pad;
1159 else
1160 pkthdr.caplen = 0;
1161 if (bhp->bh_datalen > pad)
1162 pkthdr.len = bhp->bh_datalen - pad;
1163 else
1164 pkthdr.len = 0;
1165 datap += pad;
1166 #else
1167 pkthdr.caplen = caplen;
1168 pkthdr.len = bhp->bh_datalen;
1169 #endif
1170 (*callback)(user, &pkthdr, datap);
1171 bp += BPF_WORDALIGN(caplen + hdrlen);
1172 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
1173 p->bp = bp;
1174 p->cc = ep - bp;
1176 * See comment above about p->cc < 0.
1178 if (p->cc < 0)
1179 p->cc = 0;
1180 return (n);
1182 } else {
1184 * Skip this packet.
1186 bp += BPF_WORDALIGN(caplen + hdrlen);
1189 #undef bhp
1190 p->cc = 0;
1191 return (n);
1194 static int
1195 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1197 int ret;
1199 ret = write(p->fd, buf, size);
1200 #ifdef __APPLE__
1201 if (ret == -1 && errno == EAFNOSUPPORT) {
1203 * In some versions of macOS, there's a bug wherein setting
1204 * the BIOCSHDRCMPLT flag causes writes to fail; see, for
1205 * example:
1207 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1209 * So, if, on macOS, we get EAFNOSUPPORT from the write, we
1210 * assume it's due to that bug, and turn off that flag
1211 * and try again. If we succeed, it either means that
1212 * somebody applied the fix from that URL, or other patches
1213 * for that bug from
1215 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1217 * and are running a Darwin kernel with those fixes, or
1218 * that Apple fixed the problem in some macOS release.
1220 u_int spoof_eth_src = 0;
1222 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1223 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1224 errno, "send: can't turn off BIOCSHDRCMPLT");
1225 return (PCAP_ERROR);
1229 * Now try the write again.
1231 ret = write(p->fd, buf, size);
1233 #endif /* __APPLE__ */
1234 if (ret == -1) {
1235 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1236 errno, "send");
1237 return (PCAP_ERROR);
1239 return (ret);
1242 #ifdef _AIX
1243 static int
1244 bpf_odminit(char *errbuf)
1246 char *errstr;
1248 if (odm_initialize() == -1) {
1249 if (odm_err_msg(odmerrno, &errstr) == -1)
1250 errstr = "Unknown error";
1251 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1252 "bpf_load: odm_initialize failed: %s",
1253 errstr);
1254 return (PCAP_ERROR);
1257 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1258 if (odm_err_msg(odmerrno, &errstr) == -1)
1259 errstr = "Unknown error";
1260 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1261 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1262 errstr);
1263 (void)odm_terminate();
1264 return (PCAP_ERROR);
1267 return (0);
1270 static int
1271 bpf_odmcleanup(char *errbuf)
1273 char *errstr;
1275 if (odm_unlock(odmlockid) == -1) {
1276 if (errbuf != NULL) {
1277 if (odm_err_msg(odmerrno, &errstr) == -1)
1278 errstr = "Unknown error";
1279 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1280 "bpf_load: odm_unlock failed: %s",
1281 errstr);
1283 return (PCAP_ERROR);
1286 if (odm_terminate() == -1) {
1287 if (errbuf != NULL) {
1288 if (odm_err_msg(odmerrno, &errstr) == -1)
1289 errstr = "Unknown error";
1290 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1291 "bpf_load: odm_terminate failed: %s",
1292 errstr);
1294 return (PCAP_ERROR);
1297 return (0);
1300 static int
1301 bpf_load(char *errbuf)
1303 long major;
1304 int *minors;
1305 int numminors, i, rc;
1306 char buf[1024];
1307 struct stat sbuf;
1308 struct bpf_config cfg_bpf;
1309 struct cfg_load cfg_ld;
1310 struct cfg_kmod cfg_km;
1313 * This is very very close to what happens in the real implementation
1314 * but I've fixed some (unlikely) bug situations.
1316 if (bpfloadedflag)
1317 return (0);
1319 if (bpf_odminit(errbuf) == PCAP_ERROR)
1320 return (PCAP_ERROR);
1322 major = genmajor(BPF_NAME);
1323 if (major == -1) {
1324 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1325 errno, "bpf_load: genmajor failed");
1326 (void)bpf_odmcleanup(NULL);
1327 return (PCAP_ERROR);
1330 minors = getminor(major, &numminors, BPF_NAME);
1331 if (!minors) {
1332 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1333 if (!minors) {
1334 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1335 errno, "bpf_load: genminor failed");
1336 (void)bpf_odmcleanup(NULL);
1337 return (PCAP_ERROR);
1341 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1342 return (PCAP_ERROR);
1344 rc = stat(BPF_NODE "0", &sbuf);
1345 if (rc == -1 && errno != ENOENT) {
1346 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1347 errno, "bpf_load: can't stat %s", BPF_NODE "0");
1348 return (PCAP_ERROR);
1351 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1352 for (i = 0; i < BPF_MINORS; i++) {
1353 pcap_snprintf(buf, sizeof(buf), "%s%d", BPF_NODE, i);
1354 unlink(buf);
1355 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1356 pcap_fmt_errmsg_for_errno(errbuf,
1357 PCAP_ERRBUF_SIZE, errno,
1358 "bpf_load: can't mknod %s", buf);
1359 return (PCAP_ERROR);
1364 /* Check if the driver is loaded */
1365 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1366 pcap_snprintf(buf, sizeof(buf), "%s/%s", DRIVER_PATH, BPF_NAME);
1367 cfg_ld.path = buf;
1368 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1369 (cfg_ld.kmid == 0)) {
1370 /* Driver isn't loaded, load it now */
1371 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1372 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1373 errno, "bpf_load: could not load driver");
1374 return (PCAP_ERROR);
1378 /* Configure the driver */
1379 cfg_km.cmd = CFG_INIT;
1380 cfg_km.kmid = cfg_ld.kmid;
1381 cfg_km.mdilen = sizeof(cfg_bpf);
1382 cfg_km.mdiptr = (void *)&cfg_bpf;
1383 for (i = 0; i < BPF_MINORS; i++) {
1384 cfg_bpf.devno = domakedev(major, i);
1385 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1386 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1387 errno, "bpf_load: could not configure driver");
1388 return (PCAP_ERROR);
1392 bpfloadedflag = 1;
1394 return (0);
1396 #endif
1399 * Undo any operations done when opening the device when necessary.
1401 static void
1402 pcap_cleanup_bpf(pcap_t *p)
1404 struct pcap_bpf *pb = p->priv;
1405 #ifdef HAVE_BSD_IEEE80211
1406 int sock;
1407 struct ifmediareq req;
1408 struct ifreq ifr;
1409 #endif
1411 if (pb->must_do_on_close != 0) {
1413 * There's something we have to do when closing this
1414 * pcap_t.
1416 #ifdef HAVE_BSD_IEEE80211
1417 if (pb->must_do_on_close & MUST_CLEAR_RFMON) {
1419 * We put the interface into rfmon mode;
1420 * take it out of rfmon mode.
1422 * XXX - if somebody else wants it in rfmon
1423 * mode, this code cannot know that, so it'll take
1424 * it out of rfmon mode.
1426 sock = socket(AF_INET, SOCK_DGRAM, 0);
1427 if (sock == -1) {
1428 fprintf(stderr,
1429 "Can't restore interface flags (socket() failed: %s).\n"
1430 "Please adjust manually.\n",
1431 strerror(errno));
1432 } else {
1433 memset(&req, 0, sizeof(req));
1434 strncpy(req.ifm_name, pb->device,
1435 sizeof(req.ifm_name));
1436 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1437 fprintf(stderr,
1438 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1439 "Please adjust manually.\n",
1440 strerror(errno));
1441 } else {
1442 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1444 * Rfmon mode is currently on;
1445 * turn it off.
1447 memset(&ifr, 0, sizeof(ifr));
1448 (void)strncpy(ifr.ifr_name,
1449 pb->device,
1450 sizeof(ifr.ifr_name));
1451 ifr.ifr_media =
1452 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1453 if (ioctl(sock, SIOCSIFMEDIA,
1454 &ifr) == -1) {
1455 fprintf(stderr,
1456 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1457 "Please adjust manually.\n",
1458 strerror(errno));
1462 close(sock);
1465 #endif /* HAVE_BSD_IEEE80211 */
1467 #if (defined(__FreeBSD__) || defined(__DragonFly__)) && defined(SIOCIFCREATE2)
1469 * Attempt to destroy the usbusN interface that we created.
1471 if (pb->must_do_on_close & MUST_DESTROY_USBUS) {
1472 if (if_nametoindex(pb->device) > 0) {
1473 int s;
1475 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1476 if (s >= 0) {
1477 pcap_strlcpy(ifr.ifr_name, pb->device,
1478 sizeof(ifr.ifr_name));
1479 ioctl(s, SIOCIFDESTROY, &ifr);
1480 close(s);
1484 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1486 * Take this pcap out of the list of pcaps for which we
1487 * have to take the interface out of some mode.
1489 pcap_remove_from_pcaps_to_close(p);
1490 pb->must_do_on_close = 0;
1493 #ifdef HAVE_ZEROCOPY_BPF
1494 if (pb->zerocopy) {
1496 * Delete the mappings. Note that p->buffer gets
1497 * initialized to one of the mmapped regions in
1498 * this case, so do not try and free it directly;
1499 * null it out so that pcap_cleanup_live_common()
1500 * doesn't try to free it.
1502 if (pb->zbuf1 != MAP_FAILED && pb->zbuf1 != NULL)
1503 (void) munmap(pb->zbuf1, pb->zbufsize);
1504 if (pb->zbuf2 != MAP_FAILED && pb->zbuf2 != NULL)
1505 (void) munmap(pb->zbuf2, pb->zbufsize);
1506 p->buffer = NULL;
1508 #endif
1509 if (pb->device != NULL) {
1510 free(pb->device);
1511 pb->device = NULL;
1513 pcap_cleanup_live_common(p);
1516 static int
1517 check_setif_failure(pcap_t *p, int error)
1519 #ifdef __APPLE__
1520 int fd;
1521 struct ifreq ifr;
1522 int err;
1523 #endif
1525 if (error == ENXIO) {
1527 * No such device exists.
1529 #ifdef __APPLE__
1530 if (p->opt.rfmon && strncmp(p->opt.device, "wlt", 3) == 0) {
1532 * Monitor mode was requested, and we're trying
1533 * to open a "wltN" device. Assume that this
1534 * is 10.4 and that we were asked to open an
1535 * "enN" device; if that device exists, return
1536 * "monitor mode not supported on the device".
1538 fd = socket(AF_INET, SOCK_DGRAM, 0);
1539 if (fd != -1) {
1540 pcap_strlcpy(ifr.ifr_name, "en",
1541 sizeof(ifr.ifr_name));
1542 pcap_strlcat(ifr.ifr_name, p->opt.device + 3,
1543 sizeof(ifr.ifr_name));
1544 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1546 * We assume this failed because
1547 * the underlying device doesn't
1548 * exist.
1550 err = PCAP_ERROR_NO_SUCH_DEVICE;
1551 pcap_fmt_errmsg_for_errno(p->errbuf,
1552 PCAP_ERRBUF_SIZE, errno,
1553 "SIOCGIFFLAGS on %s failed",
1554 ifr.ifr_name);
1555 } else {
1557 * The underlying "enN" device
1558 * exists, but there's no
1559 * corresponding "wltN" device;
1560 * that means that the "enN"
1561 * device doesn't support
1562 * monitor mode, probably because
1563 * it's an Ethernet device rather
1564 * than a wireless device.
1566 err = PCAP_ERROR_RFMON_NOTSUP;
1568 close(fd);
1569 } else {
1571 * We can't find out whether there's
1572 * an underlying "enN" device, so
1573 * just report "no such device".
1575 err = PCAP_ERROR_NO_SUCH_DEVICE;
1576 pcap_fmt_errmsg_for_errno(p->errbuf,
1577 errno, PCAP_ERRBUF_SIZE,
1578 "socket() failed");
1580 return (err);
1582 #endif
1584 * No such device.
1586 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1587 errno, "BIOCSETIF failed");
1588 return (PCAP_ERROR_NO_SUCH_DEVICE);
1589 } else if (errno == ENETDOWN) {
1591 * Return a "network down" indication, so that
1592 * the application can report that rather than
1593 * saying we had a mysterious failure and
1594 * suggest that they report a problem to the
1595 * libpcap developers.
1597 return (PCAP_ERROR_IFACE_NOT_UP);
1598 } else {
1600 * Some other error; fill in the error string, and
1601 * return PCAP_ERROR.
1603 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1604 errno, "BIOCSETIF: %s", p->opt.device);
1605 return (PCAP_ERROR);
1610 * Default capture buffer size.
1611 * 32K isn't very much for modern machines with fast networks; we
1612 * pick .5M, as that's the maximum on at least some systems with BPF.
1614 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1615 * read failures under stress, so we leave it as 32K; yet another
1616 * place where AIX's BPF is broken.
1618 #ifdef _AIX
1619 #define DEFAULT_BUFSIZE 32768
1620 #else
1621 #define DEFAULT_BUFSIZE 524288
1622 #endif
1624 static int
1625 pcap_activate_bpf(pcap_t *p)
1627 struct pcap_bpf *pb = p->priv;
1628 int status = 0;
1629 #ifdef HAVE_BSD_IEEE80211
1630 int retv;
1631 #endif
1632 int fd;
1633 #ifdef LIFNAMSIZ
1634 char *zonesep;
1635 struct lifreq ifr;
1636 char *ifrname = ifr.lifr_name;
1637 const size_t ifnamsiz = sizeof(ifr.lifr_name);
1638 #else
1639 struct ifreq ifr;
1640 char *ifrname = ifr.ifr_name;
1641 const size_t ifnamsiz = sizeof(ifr.ifr_name);
1642 #endif
1643 struct bpf_version bv;
1644 #ifdef __APPLE__
1645 int sockfd;
1646 char *wltdev = NULL;
1647 #endif
1648 #ifdef BIOCGDLTLIST
1649 struct bpf_dltlist bdl;
1650 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1651 int new_dlt;
1652 #endif
1653 #endif /* BIOCGDLTLIST */
1654 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1655 u_int spoof_eth_src = 1;
1656 #endif
1657 u_int v;
1658 struct bpf_insn total_insn;
1659 struct bpf_program total_prog;
1660 struct utsname osinfo;
1661 int have_osinfo = 0;
1662 #ifdef HAVE_ZEROCOPY_BPF
1663 struct bpf_zbuf bz;
1664 u_int bufmode, zbufmax;
1665 #endif
1667 fd = bpf_open(p->errbuf);
1668 if (fd < 0) {
1669 status = fd;
1670 goto bad;
1673 p->fd = fd;
1675 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1676 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1677 errno, "BIOCVERSION");
1678 status = PCAP_ERROR;
1679 goto bad;
1681 if (bv.bv_major != BPF_MAJOR_VERSION ||
1682 bv.bv_minor < BPF_MINOR_VERSION) {
1683 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1684 "kernel bpf filter out of date");
1685 status = PCAP_ERROR;
1686 goto bad;
1690 * Turn a negative snapshot value (invalid), a snapshot value of
1691 * 0 (unspecified), or a value bigger than the normal maximum
1692 * value, into the maximum allowed value.
1694 * If some application really *needs* a bigger snapshot
1695 * length, we should just increase MAXIMUM_SNAPLEN.
1697 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1698 p->snapshot = MAXIMUM_SNAPLEN;
1700 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1702 * Retrieve the zoneid of the zone we are currently executing in.
1704 if ((ifr.lifr_zoneid = getzoneid()) == -1) {
1705 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1706 errno, "getzoneid()");
1707 status = PCAP_ERROR;
1708 goto bad;
1711 * Check if the given source datalink name has a '/' separated
1712 * zonename prefix string. The zonename prefixed source datalink can
1713 * be used by pcap consumers in the Solaris global zone to capture
1714 * traffic on datalinks in non-global zones. Non-global zones
1715 * do not have access to datalinks outside of their own namespace.
1717 if ((zonesep = strchr(p->opt.device, '/')) != NULL) {
1718 char path_zname[ZONENAME_MAX];
1719 int znamelen;
1720 char *lnamep;
1722 if (ifr.lifr_zoneid != GLOBAL_ZONEID) {
1723 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1724 "zonename/linkname only valid in global zone.");
1725 status = PCAP_ERROR;
1726 goto bad;
1728 znamelen = zonesep - p->opt.device;
1729 (void) pcap_strlcpy(path_zname, p->opt.device, znamelen + 1);
1730 ifr.lifr_zoneid = getzoneidbyname(path_zname);
1731 if (ifr.lifr_zoneid == -1) {
1732 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1733 errno, "getzoneidbyname(%s)", path_zname);
1734 status = PCAP_ERROR;
1735 goto bad;
1737 lnamep = strdup(zonesep + 1);
1738 if (lnamep == NULL) {
1739 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1740 errno, "strdup");
1741 status = PCAP_ERROR;
1742 goto bad;
1744 free(p->opt.device);
1745 p->opt.device = lnamep;
1747 #endif
1749 pb->device = strdup(p->opt.device);
1750 if (pb->device == NULL) {
1751 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1752 errno, "strdup");
1753 status = PCAP_ERROR;
1754 goto bad;
1758 * Attempt to find out the version of the OS on which we're running.
1760 if (uname(&osinfo) == 0)
1761 have_osinfo = 1;
1763 #ifdef __APPLE__
1765 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1766 * of why we check the version number.
1768 if (p->opt.rfmon) {
1769 if (have_osinfo) {
1771 * We assume osinfo.sysname is "Darwin", because
1772 * __APPLE__ is defined. We just check the version.
1774 if (osinfo.release[0] < '8' &&
1775 osinfo.release[1] == '.') {
1777 * 10.3 (Darwin 7.x) or earlier.
1779 status = PCAP_ERROR_RFMON_NOTSUP;
1780 goto bad;
1782 if (osinfo.release[0] == '8' &&
1783 osinfo.release[1] == '.') {
1785 * 10.4 (Darwin 8.x). s/en/wlt/
1787 if (strncmp(p->opt.device, "en", 2) != 0) {
1789 * Not an enN device; check
1790 * whether the device even exists.
1792 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1793 if (sockfd != -1) {
1794 pcap_strlcpy(ifrname,
1795 p->opt.device, ifnamsiz);
1796 if (ioctl(sockfd, SIOCGIFFLAGS,
1797 (char *)&ifr) < 0) {
1799 * We assume this
1800 * failed because
1801 * the underlying
1802 * device doesn't
1803 * exist.
1805 status = PCAP_ERROR_NO_SUCH_DEVICE;
1806 pcap_fmt_errmsg_for_errno(p->errbuf,
1807 PCAP_ERRBUF_SIZE,
1808 errno,
1809 "SIOCGIFFLAGS failed");
1810 } else
1811 status = PCAP_ERROR_RFMON_NOTSUP;
1812 close(sockfd);
1813 } else {
1815 * We can't find out whether
1816 * the device exists, so just
1817 * report "no such device".
1819 status = PCAP_ERROR_NO_SUCH_DEVICE;
1820 pcap_fmt_errmsg_for_errno(p->errbuf,
1821 PCAP_ERRBUF_SIZE, errno,
1822 "socket() failed");
1824 goto bad;
1826 wltdev = malloc(strlen(p->opt.device) + 2);
1827 if (wltdev == NULL) {
1828 pcap_fmt_errmsg_for_errno(p->errbuf,
1829 PCAP_ERRBUF_SIZE, errno,
1830 "malloc");
1831 status = PCAP_ERROR;
1832 goto bad;
1834 strcpy(wltdev, "wlt");
1835 strcat(wltdev, p->opt.device + 2);
1836 free(p->opt.device);
1837 p->opt.device = wltdev;
1840 * Everything else is 10.5 or later; for those,
1841 * we just open the enN device, and set the DLT.
1845 #endif /* __APPLE__ */
1848 * If this is FreeBSD, and the device name begins with "usbus",
1849 * try to create the interface if it's not available.
1851 #if (defined(__FreeBSD__) || defined(__DragonFly__)) && defined(SIOCIFCREATE2)
1852 if (strncmp(p->opt.device, usbus_prefix, USBUS_PREFIX_LEN) == 0) {
1854 * Do we already have an interface with that name?
1856 if (if_nametoindex(p->opt.device) == 0) {
1858 * No. We need to create it, and, if we
1859 * succeed, remember that we should destroy
1860 * it when the pcap_t is closed.
1862 int s;
1865 * Open a socket to use for ioctls to
1866 * create the interface.
1868 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1869 if (s < 0) {
1870 pcap_fmt_errmsg_for_errno(p->errbuf,
1871 PCAP_ERRBUF_SIZE, errno,
1872 "Can't open socket");
1873 status = PCAP_ERROR;
1874 goto bad;
1878 * If we haven't already done so, arrange to have
1879 * "pcap_close_all()" called when we exit.
1881 if (!pcap_do_addexit(p)) {
1883 * "atexit()" failed; don't create the
1884 * interface, just give up.
1886 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1887 "atexit failed");
1888 close(s);
1889 status = PCAP_ERROR;
1890 goto bad;
1894 * Create the interface.
1896 pcap_strlcpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
1897 if (ioctl(s, SIOCIFCREATE2, &ifr) < 0) {
1898 if (errno == EINVAL) {
1899 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1900 "Invalid USB bus interface %s",
1901 p->opt.device);
1902 } else {
1903 pcap_fmt_errmsg_for_errno(p->errbuf,
1904 PCAP_ERRBUF_SIZE, errno,
1905 "Can't create interface for %s",
1906 p->opt.device);
1908 close(s);
1909 status = PCAP_ERROR;
1910 goto bad;
1914 * Make sure we clean this up when we close.
1916 pb->must_do_on_close |= MUST_DESTROY_USBUS;
1919 * Add this to the list of pcaps to close when we exit.
1921 pcap_add_to_pcaps_to_close(p);
1924 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1926 #ifdef HAVE_ZEROCOPY_BPF
1928 * If the BPF extension to set buffer mode is present, try setting
1929 * the mode to zero-copy. If that fails, use regular buffering. If
1930 * it succeeds but other setup fails, return an error to the user.
1932 bufmode = BPF_BUFMODE_ZBUF;
1933 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1935 * We have zerocopy BPF; use it.
1937 pb->zerocopy = 1;
1940 * How to pick a buffer size: first, query the maximum buffer
1941 * size supported by zero-copy. This also lets us quickly
1942 * determine whether the kernel generally supports zero-copy.
1943 * Then, if a buffer size was specified, use that, otherwise
1944 * query the default buffer size, which reflects kernel
1945 * policy for a desired default. Round to the nearest page
1946 * size.
1948 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1949 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1950 errno, "BIOCGETZMAX");
1951 status = PCAP_ERROR;
1952 goto bad;
1955 if (p->opt.buffer_size != 0) {
1957 * A buffer size was explicitly specified; use it.
1959 v = p->opt.buffer_size;
1960 } else {
1961 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1962 v < DEFAULT_BUFSIZE)
1963 v = DEFAULT_BUFSIZE;
1965 #ifndef roundup
1966 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
1967 #endif
1968 pb->zbufsize = roundup(v, getpagesize());
1969 if (pb->zbufsize > zbufmax)
1970 pb->zbufsize = zbufmax;
1971 pb->zbuf1 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1972 MAP_ANON, -1, 0);
1973 pb->zbuf2 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1974 MAP_ANON, -1, 0);
1975 if (pb->zbuf1 == MAP_FAILED || pb->zbuf2 == MAP_FAILED) {
1976 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1977 errno, "mmap");
1978 status = PCAP_ERROR;
1979 goto bad;
1981 memset(&bz, 0, sizeof(bz)); /* bzero() deprecated, replaced with memset() */
1982 bz.bz_bufa = pb->zbuf1;
1983 bz.bz_bufb = pb->zbuf2;
1984 bz.bz_buflen = pb->zbufsize;
1985 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1986 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1987 errno, "BIOCSETZBUF");
1988 status = PCAP_ERROR;
1989 goto bad;
1991 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
1992 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1993 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1994 errno, "BIOCSETIF: %s", p->opt.device);
1995 status = PCAP_ERROR;
1996 goto bad;
1998 v = pb->zbufsize - sizeof(struct bpf_zbuf_header);
1999 } else
2000 #endif
2003 * We don't have zerocopy BPF.
2004 * Set the buffer size.
2006 if (p->opt.buffer_size != 0) {
2008 * A buffer size was explicitly specified; use it.
2010 if (ioctl(fd, BIOCSBLEN,
2011 (caddr_t)&p->opt.buffer_size) < 0) {
2012 pcap_fmt_errmsg_for_errno(p->errbuf,
2013 PCAP_ERRBUF_SIZE, errno,
2014 "BIOCSBLEN: %s", p->opt.device);
2015 status = PCAP_ERROR;
2016 goto bad;
2020 * Now bind to the device.
2022 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
2023 #ifdef BIOCSETLIF
2024 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
2025 #else
2026 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
2027 #endif
2029 status = check_setif_failure(p, errno);
2030 goto bad;
2032 } else {
2034 * No buffer size was explicitly specified.
2036 * Try finding a good size for the buffer;
2037 * DEFAULT_BUFSIZE may be too big, so keep
2038 * cutting it in half until we find a size
2039 * that works, or run out of sizes to try.
2040 * If the default is larger, don't make it smaller.
2042 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
2043 v < DEFAULT_BUFSIZE)
2044 v = DEFAULT_BUFSIZE;
2045 for ( ; v != 0; v >>= 1) {
2047 * Ignore the return value - this is because the
2048 * call fails on BPF systems that don't have
2049 * kernel malloc. And if the call fails, it's
2050 * no big deal, we just continue to use the
2051 * standard buffer size.
2053 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
2055 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
2056 #ifdef BIOCSETLIF
2057 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
2058 #else
2059 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
2060 #endif
2061 break; /* that size worked; we're done */
2063 if (errno != ENOBUFS) {
2064 status = check_setif_failure(p, errno);
2065 goto bad;
2069 if (v == 0) {
2070 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2071 "BIOCSBLEN: %s: No buffer size worked",
2072 p->opt.device);
2073 status = PCAP_ERROR;
2074 goto bad;
2079 /* Get the data link layer type. */
2080 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
2081 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2082 errno, "BIOCGDLT");
2083 status = PCAP_ERROR;
2084 goto bad;
2087 #ifdef _AIX
2089 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
2091 switch (v) {
2093 case IFT_ETHER:
2094 case IFT_ISO88023:
2095 v = DLT_EN10MB;
2096 break;
2098 case IFT_FDDI:
2099 v = DLT_FDDI;
2100 break;
2102 case IFT_ISO88025:
2103 v = DLT_IEEE802;
2104 break;
2106 case IFT_LOOP:
2107 v = DLT_NULL;
2108 break;
2110 default:
2112 * We don't know what to map this to yet.
2114 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
2116 status = PCAP_ERROR;
2117 goto bad;
2119 #endif
2120 #if _BSDI_VERSION - 0 >= 199510
2121 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
2122 switch (v) {
2124 case DLT_SLIP:
2125 v = DLT_SLIP_BSDOS;
2126 break;
2128 case DLT_PPP:
2129 v = DLT_PPP_BSDOS;
2130 break;
2132 case 11: /*DLT_FR*/
2133 v = DLT_FRELAY;
2134 break;
2136 case 12: /*DLT_C_HDLC*/
2137 v = DLT_CHDLC;
2138 break;
2140 #endif
2142 #ifdef BIOCGDLTLIST
2144 * We know the default link type -- now determine all the DLTs
2145 * this interface supports. If this fails with EINVAL, it's
2146 * not fatal; we just don't get to use the feature later.
2148 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
2149 status = PCAP_ERROR;
2150 goto bad;
2152 p->dlt_count = bdl.bfl_len;
2153 p->dlt_list = bdl.bfl_list;
2155 #ifdef __APPLE__
2157 * Monitor mode fun, continued.
2159 * For 10.5 and, we're assuming, later releases, as noted above,
2160 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
2161 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
2162 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
2163 * monitor mode on.
2165 * Therefore, if the user asked for monitor mode, we filter out
2166 * the DLT_EN10MB value, as you can't get that in monitor mode,
2167 * and, if the user didn't ask for monitor mode, we filter out
2168 * the 802.11 DLT_ values, because selecting those will turn
2169 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
2170 * radio DLT_ value is offered, we try to select that, otherwise
2171 * we try to select DLT_IEEE802_11.
2173 if (have_osinfo) {
2174 if (isdigit((unsigned)osinfo.release[0]) &&
2175 (osinfo.release[0] == '9' ||
2176 isdigit((unsigned)osinfo.release[1]))) {
2178 * 10.5 (Darwin 9.x), or later.
2180 new_dlt = find_802_11(&bdl);
2181 if (new_dlt != -1) {
2183 * We have at least one 802.11 DLT_ value,
2184 * so this is an 802.11 interface.
2185 * new_dlt is the best of the 802.11
2186 * DLT_ values in the list.
2188 if (p->opt.rfmon) {
2190 * Our caller wants monitor mode.
2191 * Purge DLT_EN10MB from the list
2192 * of link-layer types, as selecting
2193 * it will keep monitor mode off.
2195 remove_non_802_11(p);
2198 * If the new mode we want isn't
2199 * the default mode, attempt to
2200 * select the new mode.
2202 if ((u_int)new_dlt != v) {
2203 if (ioctl(p->fd, BIOCSDLT,
2204 &new_dlt) != -1) {
2206 * We succeeded;
2207 * make this the
2208 * new DLT_ value.
2210 v = new_dlt;
2213 } else {
2215 * Our caller doesn't want
2216 * monitor mode. Unless this
2217 * is being done by pcap_open_live(),
2218 * purge the 802.11 link-layer types
2219 * from the list, as selecting
2220 * one of them will turn monitor
2221 * mode on.
2223 if (!p->oldstyle)
2224 remove_802_11(p);
2226 } else {
2227 if (p->opt.rfmon) {
2229 * The caller requested monitor
2230 * mode, but we have no 802.11
2231 * link-layer types, so they
2232 * can't have it.
2234 status = PCAP_ERROR_RFMON_NOTSUP;
2235 goto bad;
2240 #elif defined(HAVE_BSD_IEEE80211)
2242 * *BSD with the new 802.11 ioctls.
2243 * Do we want monitor mode?
2245 if (p->opt.rfmon) {
2247 * Try to put the interface into monitor mode.
2249 retv = monitor_mode(p, 1);
2250 if (retv != 0) {
2252 * We failed.
2254 status = retv;
2255 goto bad;
2259 * We're in monitor mode.
2260 * Try to find the best 802.11 DLT_ value and, if we
2261 * succeed, try to switch to that mode if we're not
2262 * already in that mode.
2264 new_dlt = find_802_11(&bdl);
2265 if (new_dlt != -1) {
2267 * We have at least one 802.11 DLT_ value.
2268 * new_dlt is the best of the 802.11
2269 * DLT_ values in the list.
2271 * If the new mode we want isn't the default mode,
2272 * attempt to select the new mode.
2274 if ((u_int)new_dlt != v) {
2275 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
2277 * We succeeded; make this the
2278 * new DLT_ value.
2280 v = new_dlt;
2285 #endif /* various platforms */
2286 #endif /* BIOCGDLTLIST */
2289 * If this is an Ethernet device, and we don't have a DLT_ list,
2290 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
2291 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2292 * do, but there's not much we can do about that without finding
2293 * some other way of determining whether it's an Ethernet or 802.11
2294 * device.)
2296 if (v == DLT_EN10MB && p->dlt_count == 0) {
2297 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2299 * If that fails, just leave the list empty.
2301 if (p->dlt_list != NULL) {
2302 p->dlt_list[0] = DLT_EN10MB;
2303 p->dlt_list[1] = DLT_DOCSIS;
2304 p->dlt_count = 2;
2307 #ifdef PCAP_FDDIPAD
2308 if (v == DLT_FDDI)
2309 p->fddipad = PCAP_FDDIPAD;
2310 else
2311 #endif
2312 p->fddipad = 0;
2313 p->linktype = v;
2315 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2317 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2318 * the link-layer source address isn't forcibly overwritten.
2319 * (Should we ignore errors? Should we do this only if
2320 * we're open for writing?)
2322 * XXX - I seem to remember some packet-sending bug in some
2323 * BSDs - check CVS log for "bpf.c"?
2325 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2326 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2327 errno, "BIOCSHDRCMPLT");
2328 status = PCAP_ERROR;
2329 goto bad;
2331 #endif
2332 /* set timeout */
2333 #ifdef HAVE_ZEROCOPY_BPF
2335 * In zero-copy mode, we just use the timeout in select().
2336 * XXX - what if we're in non-blocking mode and the *application*
2337 * is using select() or poll() or kqueues or....?
2339 if (p->opt.timeout && !pb->zerocopy) {
2340 #else
2341 if (p->opt.timeout) {
2342 #endif
2344 * XXX - is this seconds/nanoseconds in AIX?
2345 * (Treating it as such doesn't fix the timeout
2346 * problem described below.)
2348 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2349 * 64-bit userland - it takes, as an argument, a
2350 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2351 * and tv_usec, rather than a "struct timeval".
2353 * If this platform defines "struct BPF_TIMEVAL",
2354 * we check whether the structure size in BIOCSRTIMEOUT
2355 * is that of a "struct timeval" and, if not, we use
2356 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2357 * (That way, if the bug is fixed in a future release,
2358 * we will still do the right thing.)
2360 struct timeval to;
2361 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2362 struct BPF_TIMEVAL bpf_to;
2364 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2365 bpf_to.tv_sec = p->opt.timeout / 1000;
2366 bpf_to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2367 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2368 pcap_fmt_errmsg_for_errno(p->errbuf,
2369 errno, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT");
2370 status = PCAP_ERROR;
2371 goto bad;
2373 } else {
2374 #endif
2375 to.tv_sec = p->opt.timeout / 1000;
2376 to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2377 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2378 pcap_fmt_errmsg_for_errno(p->errbuf,
2379 errno, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT");
2380 status = PCAP_ERROR;
2381 goto bad;
2383 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2385 #endif
2388 #ifdef BIOCIMMEDIATE
2390 * Darren Reed notes that
2392 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2393 * timeout appears to be ignored and it waits until the buffer
2394 * is filled before returning. The result of not having it
2395 * set is almost worse than useless if your BPF filter
2396 * is reducing things to only a few packets (i.e. one every
2397 * second or so).
2399 * so we always turn BIOCIMMEDIATE mode on if this is AIX.
2401 * For other platforms, we don't turn immediate mode on by default,
2402 * as that would mean we get woken up for every packet, which
2403 * probably isn't what you want for a packet sniffer.
2405 * We set immediate mode if the caller requested it by calling
2406 * pcap_set_immediate() before calling pcap_activate().
2408 #ifndef _AIX
2409 if (p->opt.immediate) {
2410 #endif /* _AIX */
2411 v = 1;
2412 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2413 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2414 errno, "BIOCIMMEDIATE");
2415 status = PCAP_ERROR;
2416 goto bad;
2418 #ifndef _AIX
2420 #endif /* _AIX */
2421 #else /* BIOCIMMEDIATE */
2422 if (p->opt.immediate) {
2424 * We don't support immediate mode. Fail.
2426 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Immediate mode not supported");
2427 status = PCAP_ERROR;
2428 goto bad;
2430 #endif /* BIOCIMMEDIATE */
2432 if (p->opt.promisc) {
2433 /* set promiscuous mode, just warn if it fails */
2434 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2435 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2436 errno, "BIOCPROMISC");
2437 status = PCAP_WARNING_PROMISC_NOTSUP;
2441 #ifdef BIOCSTSTAMP
2442 v = BPF_T_BINTIME;
2443 if (ioctl(p->fd, BIOCSTSTAMP, &v) < 0) {
2444 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2445 errno, "BIOCSTSTAMP");
2446 status = PCAP_ERROR;
2447 goto bad;
2449 #endif /* BIOCSTSTAMP */
2451 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2452 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2453 errno, "BIOCGBLEN");
2454 status = PCAP_ERROR;
2455 goto bad;
2457 p->bufsize = v;
2458 #ifdef HAVE_ZEROCOPY_BPF
2459 if (!pb->zerocopy) {
2460 #endif
2461 p->buffer = malloc(p->bufsize);
2462 if (p->buffer == NULL) {
2463 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2464 errno, "malloc");
2465 status = PCAP_ERROR;
2466 goto bad;
2468 #ifdef _AIX
2469 /* For some strange reason this seems to prevent the EFAULT
2470 * problems we have experienced from AIX BPF. */
2471 memset(p->buffer, 0x0, p->bufsize);
2472 #endif
2473 #ifdef HAVE_ZEROCOPY_BPF
2475 #endif
2478 * If there's no filter program installed, there's
2479 * no indication to the kernel of what the snapshot
2480 * length should be, so no snapshotting is done.
2482 * Therefore, when we open the device, we install
2483 * an "accept everything" filter with the specified
2484 * snapshot length.
2486 total_insn.code = (u_short)(BPF_RET | BPF_K);
2487 total_insn.jt = 0;
2488 total_insn.jf = 0;
2489 total_insn.k = p->snapshot;
2491 total_prog.bf_len = 1;
2492 total_prog.bf_insns = &total_insn;
2493 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2494 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2495 errno, "BIOCSETF");
2496 status = PCAP_ERROR;
2497 goto bad;
2501 * On most BPF platforms, either you can do a "select()" or
2502 * "poll()" on a BPF file descriptor and it works correctly,
2503 * or you can do it and it will return "readable" if the
2504 * hold buffer is full but not if the timeout expires *and*
2505 * a non-blocking read will, if the hold buffer is empty
2506 * but the store buffer isn't empty, rotate the buffers
2507 * and return what packets are available.
2509 * In the latter case, the fact that a non-blocking read
2510 * will give you the available packets means you can work
2511 * around the failure of "select()" and "poll()" to wake up
2512 * and return "readable" when the timeout expires by using
2513 * the timeout as the "select()" or "poll()" timeout, putting
2514 * the BPF descriptor into non-blocking mode, and read from
2515 * it regardless of whether "select()" reports it as readable
2516 * or not.
2518 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2519 * won't wake up and return "readable" if the timer expires
2520 * and non-blocking reads return EWOULDBLOCK if the hold
2521 * buffer is empty, even if the store buffer is non-empty.
2523 * This means the workaround in question won't work.
2525 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2526 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2527 * here". On all other BPF platforms, we set it to the FD for
2528 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2529 * read will, if the hold buffer is empty and the store buffer
2530 * isn't empty, rotate the buffers and return what packets are
2531 * there (and in sufficiently recent versions of OpenBSD
2532 * "select()" and "poll()" should work correctly).
2534 * XXX - what about AIX?
2536 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2537 if (have_osinfo) {
2539 * We can check what OS this is.
2541 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2542 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2543 strncmp(osinfo.release, "4.4-", 4) == 0)
2544 p->selectable_fd = -1;
2548 p->read_op = pcap_read_bpf;
2549 p->inject_op = pcap_inject_bpf;
2550 p->setfilter_op = pcap_setfilter_bpf;
2551 p->setdirection_op = pcap_setdirection_bpf;
2552 p->set_datalink_op = pcap_set_datalink_bpf;
2553 p->getnonblock_op = pcap_getnonblock_bpf;
2554 p->setnonblock_op = pcap_setnonblock_bpf;
2555 p->stats_op = pcap_stats_bpf;
2556 p->cleanup_op = pcap_cleanup_bpf;
2558 return (status);
2559 bad:
2560 pcap_cleanup_bpf(p);
2561 return (status);
2565 * Not all interfaces can be bound to by BPF, so try to bind to
2566 * the specified interface; return 0 if we fail with
2567 * PCAP_ERROR_NO_SUCH_DEVICE (which means we got an ENXIO when we tried
2568 * to bind, which means this interface isn't in the list of interfaces
2569 * attached to BPF) and 1 otherwise.
2571 static int
2572 check_bpf_bindable(const char *name)
2574 int fd;
2575 char errbuf[PCAP_ERRBUF_SIZE];
2578 * On macOS, we don't do this check if the device name begins
2579 * with "wlt"; at least some versions of macOS (actually, it
2580 * was called "Mac OS X" then...) offer monitor mode capturing
2581 * by having a separate "monitor mode" device for each wireless
2582 * adapter, rather than by implementing the ioctls that
2583 * {Free,Net,Open,DragonFly}BSD provide. Opening that device
2584 * puts the adapter into monitor mode, which, at least for
2585 * some adapters, causes them to deassociate from the network
2586 * with which they're associated.
2588 * Instead, we try to open the corresponding "en" device (so
2589 * that we don't end up with, for users without sufficient
2590 * privilege to open capture devices, a list of adapters that
2591 * only includes the wlt devices).
2593 #ifdef __APPLE__
2594 if (strncmp(name, "wlt", 3) == 0) {
2595 char *en_name;
2596 size_t en_name_len;
2599 * Try to allocate a buffer for the "en"
2600 * device's name.
2602 en_name_len = strlen(name) - 1;
2603 en_name = malloc(en_name_len + 1);
2604 if (en_name == NULL) {
2605 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2606 errno, "malloc");
2607 return (-1);
2609 strcpy(en_name, "en");
2610 strcat(en_name, name + 3);
2611 fd = bpf_open_and_bind(en_name, errbuf);
2612 free(en_name);
2613 } else
2614 #endif /* __APPLE */
2615 fd = bpf_open_and_bind(name, errbuf);
2616 if (fd < 0) {
2618 * Error - was it PCAP_ERROR_NO_SUCH_DEVICE?
2620 if (fd == PCAP_ERROR_NO_SUCH_DEVICE) {
2622 * Yes, so we can't bind to this because it's
2623 * not something supported by BPF.
2625 return (0);
2628 * No, so we don't know whether it's supported or not;
2629 * say it is, so that the user can at least try to
2630 * open it and report the error (which is probably
2631 * "you don't have permission to open BPF devices";
2632 * reporting those interfaces means users will ask
2633 * "why am I getting a permissions error when I try
2634 * to capture" rather than "why am I not seeing any
2635 * interfaces", making the underlying problem clearer).
2637 return (1);
2641 * Success.
2643 close(fd);
2644 return (1);
2647 #if (defined(__FreeBSD__) || defined(__DragonFly__)) && defined(SIOCIFCREATE2)
2648 static int
2649 get_usb_if_flags(const char *name _U_, bpf_u_int32 *flags _U_, char *errbuf _U_)
2652 * XXX - if there's a way to determine whether there's something
2653 * plugged into a given USB bus, use that to determine whether
2654 * this device is "connected" or not.
2656 return (0);
2659 static int
2660 finddevs_usb(pcap_if_list_t *devlistp, char *errbuf)
2662 DIR *usbdir;
2663 struct dirent *usbitem;
2664 size_t name_max;
2665 char *name;
2668 * We might have USB sniffing support, so try looking for USB
2669 * interfaces.
2671 * We want to report a usbusN device for each USB bus, but
2672 * usbusN interfaces might, or might not, exist for them -
2673 * we create one if there isn't already one.
2675 * So, instead, we look in /dev/usb for all buses and create
2676 * a "usbusN" device for each one.
2678 usbdir = opendir("/dev/usb");
2679 if (usbdir == NULL) {
2681 * Just punt.
2683 return (0);
2687 * Leave enough room for a 32-bit (10-digit) bus number.
2688 * Yes, that's overkill, but we won't be using
2689 * the buffer very long.
2691 name_max = USBUS_PREFIX_LEN + 10 + 1;
2692 name = malloc(name_max);
2693 if (name == NULL) {
2694 closedir(usbdir);
2695 return (0);
2697 while ((usbitem = readdir(usbdir)) != NULL) {
2698 char *p;
2699 size_t busnumlen;
2701 if (strcmp(usbitem->d_name, ".") == 0 ||
2702 strcmp(usbitem->d_name, "..") == 0) {
2704 * Ignore these.
2706 continue;
2708 p = strchr(usbitem->d_name, '.');
2709 if (p == NULL)
2710 continue;
2711 busnumlen = p - usbitem->d_name;
2712 memcpy(name, usbus_prefix, USBUS_PREFIX_LEN);
2713 memcpy(name + USBUS_PREFIX_LEN, usbitem->d_name, busnumlen);
2714 *(name + USBUS_PREFIX_LEN + busnumlen) = '\0';
2716 * There's an entry in this directory for every USB device,
2717 * not for every bus; if there's more than one device on
2718 * the bus, there'll be more than one entry for that bus,
2719 * so we need to avoid adding multiple capture devices
2720 * for each bus.
2722 if (find_or_add_dev(devlistp, name, PCAP_IF_UP,
2723 get_usb_if_flags, NULL, errbuf) == NULL) {
2724 free(name);
2725 closedir(usbdir);
2726 return (PCAP_ERROR);
2729 free(name);
2730 closedir(usbdir);
2731 return (0);
2733 #endif
2736 * Get additional flags for a device, using SIOCGIFMEDIA.
2738 #ifdef SIOCGIFMEDIA
2739 static int
2740 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
2742 int sock;
2743 struct ifmediareq req;
2745 sock = socket(AF_INET, SOCK_DGRAM, 0);
2746 if (sock == -1) {
2747 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
2748 "Can't create socket to get media information for %s",
2749 name);
2750 return (-1);
2752 memset(&req, 0, sizeof(req));
2753 strncpy(req.ifm_name, name, sizeof(req.ifm_name));
2754 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2755 if (errno == EOPNOTSUPP || errno == EINVAL || errno == ENOTTY ||
2756 errno == ENODEV || errno == EPERM) {
2758 * Not supported, so we can't provide any
2759 * additional information. Assume that
2760 * this means that "connected" vs.
2761 * "disconnected" doesn't apply.
2763 * The ioctl routine for Apple's pktap devices,
2764 * annoyingly, checks for "are you root?" before
2765 * checking whether the ioctl is valid, so it
2766 * returns EPERM, rather than ENOTSUP, for the
2767 * invalid SIOCGIFMEDIA, unless you're root.
2768 * So, just as we do for some ethtool ioctls
2769 * on Linux, which makes the same mistake, we
2770 * also treat EPERM as meaning "not supported".
2772 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2773 close(sock);
2774 return (0);
2776 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
2777 "SIOCGIFMEDIA on %s failed", name);
2778 close(sock);
2779 return (-1);
2781 close(sock);
2784 * OK, what type of network is this?
2786 switch (IFM_TYPE(req.ifm_active)) {
2788 case IFM_IEEE80211:
2790 * Wireless.
2792 *flags |= PCAP_IF_WIRELESS;
2793 break;
2797 * Do we know whether it's connected?
2799 if (req.ifm_status & IFM_AVALID) {
2801 * Yes.
2803 if (req.ifm_status & IFM_ACTIVE) {
2805 * It's connected.
2807 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2808 } else {
2810 * It's disconnected.
2812 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2815 return (0);
2817 #else
2818 static int
2819 get_if_flags(const char *name _U_, bpf_u_int32 *flags _U_, char *errbuf _U_)
2822 * Nothing we can do other than mark loopback devices as "the
2823 * connected/disconnected status doesn't apply".
2825 * XXX - on Solaris, can we do what the dladm command does,
2826 * i.e. get a connected/disconnected indication from a kstat?
2827 * (Note that you can also get the link speed, and possibly
2828 * other information, from a kstat as well.)
2830 if (*flags & PCAP_IF_LOOPBACK) {
2832 * Loopback devices aren't wireless, and "connected"/
2833 * "disconnected" doesn't apply to them.
2835 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2836 return (0);
2838 return (0);
2840 #endif
2843 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2846 * Get the list of regular interfaces first.
2848 if (pcap_findalldevs_interfaces(devlistp, errbuf, check_bpf_bindable,
2849 get_if_flags) == -1)
2850 return (-1); /* failure */
2852 #if (defined(__FreeBSD__) || defined(__DragonFly__)) && defined(SIOCIFCREATE2)
2853 if (finddevs_usb(devlistp, errbuf) == -1)
2854 return (-1);
2855 #endif
2857 return (0);
2860 #ifdef HAVE_BSD_IEEE80211
2861 static int
2862 monitor_mode(pcap_t *p, int set)
2864 struct pcap_bpf *pb = p->priv;
2865 int sock;
2866 struct ifmediareq req;
2867 IFM_ULIST_TYPE *media_list;
2868 int i;
2869 int can_do;
2870 struct ifreq ifr;
2872 sock = socket(AF_INET, SOCK_DGRAM, 0);
2873 if (sock == -1) {
2874 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2875 errno, "can't open socket");
2876 return (PCAP_ERROR);
2879 memset(&req, 0, sizeof req);
2880 strncpy(req.ifm_name, p->opt.device, sizeof req.ifm_name);
2883 * Find out how many media types we have.
2885 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2887 * Can't get the media types.
2889 switch (errno) {
2891 case ENXIO:
2893 * There's no such device.
2895 close(sock);
2896 return (PCAP_ERROR_NO_SUCH_DEVICE);
2898 case EINVAL:
2900 * Interface doesn't support SIOC{G,S}IFMEDIA.
2902 close(sock);
2903 return (PCAP_ERROR_RFMON_NOTSUP);
2905 default:
2906 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2907 errno, "SIOCGIFMEDIA");
2908 close(sock);
2909 return (PCAP_ERROR);
2912 if (req.ifm_count == 0) {
2914 * No media types.
2916 close(sock);
2917 return (PCAP_ERROR_RFMON_NOTSUP);
2921 * Allocate a buffer to hold all the media types, and
2922 * get the media types.
2924 media_list = malloc(req.ifm_count * sizeof(*media_list));
2925 if (media_list == NULL) {
2926 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2927 errno, "malloc");
2928 close(sock);
2929 return (PCAP_ERROR);
2931 req.ifm_ulist = media_list;
2932 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2933 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
2934 errno, "SIOCGIFMEDIA");
2935 free(media_list);
2936 close(sock);
2937 return (PCAP_ERROR);
2941 * Look for an 802.11 "automatic" media type.
2942 * We assume that all 802.11 adapters have that media type,
2943 * and that it will carry the monitor mode supported flag.
2945 can_do = 0;
2946 for (i = 0; i < req.ifm_count; i++) {
2947 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2948 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2949 /* OK, does it do monitor mode? */
2950 if (media_list[i] & IFM_IEEE80211_MONITOR) {
2951 can_do = 1;
2952 break;
2956 free(media_list);
2957 if (!can_do) {
2959 * This adapter doesn't support monitor mode.
2961 close(sock);
2962 return (PCAP_ERROR_RFMON_NOTSUP);
2965 if (set) {
2967 * Don't just check whether we can enable monitor mode,
2968 * do so, if it's not already enabled.
2970 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2972 * Monitor mode isn't currently on, so turn it on,
2973 * and remember that we should turn it off when the
2974 * pcap_t is closed.
2978 * If we haven't already done so, arrange to have
2979 * "pcap_close_all()" called when we exit.
2981 if (!pcap_do_addexit(p)) {
2983 * "atexit()" failed; don't put the interface
2984 * in monitor mode, just give up.
2986 close(sock);
2987 return (PCAP_ERROR);
2989 memset(&ifr, 0, sizeof(ifr));
2990 (void)strncpy(ifr.ifr_name, p->opt.device,
2991 sizeof(ifr.ifr_name));
2992 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2993 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2994 pcap_fmt_errmsg_for_errno(p->errbuf,
2995 PCAP_ERRBUF_SIZE, errno, "SIOCSIFMEDIA");
2996 close(sock);
2997 return (PCAP_ERROR);
3000 pb->must_do_on_close |= MUST_CLEAR_RFMON;
3003 * Add this to the list of pcaps to close when we exit.
3005 pcap_add_to_pcaps_to_close(p);
3008 return (0);
3010 #endif /* HAVE_BSD_IEEE80211 */
3012 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
3014 * Check whether we have any 802.11 link-layer types; return the best
3015 * of the 802.11 link-layer types if we find one, and return -1
3016 * otherwise.
3018 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
3019 * best 802.11 link-layer type; any of the other 802.11-plus-radio
3020 * headers are second-best; 802.11 with no radio information is
3021 * the least good.
3023 static int
3024 find_802_11(struct bpf_dltlist *bdlp)
3026 int new_dlt;
3027 u_int i;
3030 * Scan the list of DLT_ values, looking for 802.11 values,
3031 * and, if we find any, choose the best of them.
3033 new_dlt = -1;
3034 for (i = 0; i < bdlp->bfl_len; i++) {
3035 switch (bdlp->bfl_list[i]) {
3037 case DLT_IEEE802_11:
3039 * 802.11, but no radio.
3041 * Offer this, and select it as the new mode
3042 * unless we've already found an 802.11
3043 * header with radio information.
3045 if (new_dlt == -1)
3046 new_dlt = bdlp->bfl_list[i];
3047 break;
3049 #ifdef DLT_PRISM_HEADER
3050 case DLT_PRISM_HEADER:
3051 #endif
3052 #ifdef DLT_AIRONET_HEADER
3053 case DLT_AIRONET_HEADER:
3054 #endif
3055 case DLT_IEEE802_11_RADIO_AVS:
3057 * 802.11 with radio, but not radiotap.
3059 * Offer this, and select it as the new mode
3060 * unless we've already found the radiotap DLT_.
3062 if (new_dlt != DLT_IEEE802_11_RADIO)
3063 new_dlt = bdlp->bfl_list[i];
3064 break;
3066 case DLT_IEEE802_11_RADIO:
3068 * 802.11 with radiotap.
3070 * Offer this, and select it as the new mode.
3072 new_dlt = bdlp->bfl_list[i];
3073 break;
3075 default:
3077 * Not 802.11.
3079 break;
3083 return (new_dlt);
3085 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
3087 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
3089 * Remove non-802.11 header types from the list of DLT_ values, as we're in
3090 * monitor mode, and those header types aren't supported in monitor mode.
3092 static void
3093 remove_non_802_11(pcap_t *p)
3095 int i, j;
3098 * Scan the list of DLT_ values and discard non-802.11 ones.
3100 j = 0;
3101 for (i = 0; i < p->dlt_count; i++) {
3102 switch (p->dlt_list[i]) {
3104 case DLT_EN10MB:
3105 case DLT_RAW:
3107 * Not 802.11. Don't offer this one.
3109 continue;
3111 default:
3113 * Just copy this mode over.
3115 break;
3119 * Copy this DLT_ value to its new position.
3121 p->dlt_list[j] = p->dlt_list[i];
3122 j++;
3126 * Set the DLT_ count to the number of entries we copied.
3128 p->dlt_count = j;
3132 * Remove 802.11 link-layer types from the list of DLT_ values, as
3133 * we're not in monitor mode, and those DLT_ values will switch us
3134 * to monitor mode.
3136 static void
3137 remove_802_11(pcap_t *p)
3139 int i, j;
3142 * Scan the list of DLT_ values and discard 802.11 values.
3144 j = 0;
3145 for (i = 0; i < p->dlt_count; i++) {
3146 switch (p->dlt_list[i]) {
3148 case DLT_IEEE802_11:
3149 #ifdef DLT_PRISM_HEADER
3150 case DLT_PRISM_HEADER:
3151 #endif
3152 #ifdef DLT_AIRONET_HEADER
3153 case DLT_AIRONET_HEADER:
3154 #endif
3155 case DLT_IEEE802_11_RADIO:
3156 case DLT_IEEE802_11_RADIO_AVS:
3157 #ifdef DLT_PPI
3158 case DLT_PPI:
3159 #endif
3161 * 802.11. Don't offer this one.
3163 continue;
3165 default:
3167 * Just copy this mode over.
3169 break;
3173 * Copy this DLT_ value to its new position.
3175 p->dlt_list[j] = p->dlt_list[i];
3176 j++;
3180 * Set the DLT_ count to the number of entries we copied.
3182 p->dlt_count = j;
3184 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
3186 static int
3187 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
3189 struct pcap_bpf *pb = p->priv;
3192 * Free any user-mode filter we might happen to have installed.
3194 pcap_freecode(&p->fcode);
3197 * Try to install the kernel filter.
3199 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
3201 * It worked.
3203 pb->filtering_in_kernel = 1; /* filtering in the kernel */
3206 * Discard any previously-received packets, as they might
3207 * have passed whatever filter was formerly in effect, but
3208 * might not pass this filter (BIOCSETF discards packets
3209 * buffered in the kernel, so you can lose packets in any
3210 * case).
3212 p->cc = 0;
3213 return (0);
3217 * We failed.
3219 * If it failed with EINVAL, that's probably because the program
3220 * is invalid or too big. Validate it ourselves; if we like it
3221 * (we currently allow backward branches, to support protochain),
3222 * run it in userland. (There's no notion of "too big" for
3223 * userland.)
3225 * Otherwise, just give up.
3226 * XXX - if the copy of the program into the kernel failed,
3227 * we will get EINVAL rather than, say, EFAULT on at least
3228 * some kernels.
3230 if (errno != EINVAL) {
3231 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3232 errno, "BIOCSETF");
3233 return (-1);
3237 * install_bpf_program() validates the program.
3239 * XXX - what if we already have a filter in the kernel?
3241 if (install_bpf_program(p, fp) < 0)
3242 return (-1);
3243 pb->filtering_in_kernel = 0; /* filtering in userland */
3244 return (0);
3248 * Set direction flag: Which packets do we accept on a forwarding
3249 * single device? IN, OUT or both?
3251 #if defined(BIOCSDIRECTION)
3252 static int
3253 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3255 u_int direction;
3257 direction = (d == PCAP_D_IN) ? BPF_D_IN :
3258 ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
3259 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
3260 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3261 errno, "Cannot set direction to %s",
3262 (d == PCAP_D_IN) ? "PCAP_D_IN" :
3263 ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"));
3264 return (-1);
3266 return (0);
3268 #elif defined(BIOCSSEESENT)
3269 static int
3270 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3272 u_int seesent;
3275 * We don't support PCAP_D_OUT.
3277 if (d == PCAP_D_OUT) {
3278 pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3279 "Setting direction to PCAP_D_OUT is not supported on BPF");
3280 return -1;
3283 seesent = (d == PCAP_D_INOUT);
3284 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
3285 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3286 errno, "Cannot set direction to %s",
3287 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN");
3288 return (-1);
3290 return (0);
3292 #else
3293 static int
3294 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d _U_)
3296 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3297 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
3298 return (-1);
3300 #endif
3302 #ifdef BIOCSDLT
3303 static int
3304 pcap_set_datalink_bpf(pcap_t *p, int dlt)
3306 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
3307 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3308 errno, "Cannot set DLT %d", dlt);
3309 return (-1);
3311 return (0);
3313 #else
3314 static int
3315 pcap_set_datalink_bpf(pcap_t *p _U_, int dlt _U_)
3317 return (0);
3319 #endif
3322 * Platform-specific information.
3324 const char *
3325 pcap_lib_version(void)
3327 #ifdef HAVE_ZEROCOPY_BPF
3328 return (PCAP_VERSION_STRING " (with zerocopy support)");
3329 #else
3330 return (PCAP_VERSION_STRING);
3331 #endif