hier.7: Document some recently added directories.
[dragonfly.git] / contrib / libpcap / pcap-bpf.c
blob78beb8e99d0af0045444c748622d173c422bdc57
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 #ifdef HAVE_ZEROCOPY_BPF
28 #include <sys/mman.h>
29 #endif
30 #include <sys/socket.h>
31 #include <time.h>
33 * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
35 * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
36 * at least on *BSD and Mac OS X, it also defines various SIOC ioctls -
37 * we could include <sys/sockio.h>, but if we're already including
38 * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
39 * there's not much point in doing so.
41 * If we have <sys/ioccom.h>, we include it as well, to handle systems
42 * such as Solaris which don't arrange to include <sys/ioccom.h> if you
43 * include <sys/ioctl.h>
45 #include <sys/ioctl.h>
46 #ifdef HAVE_SYS_IOCCOM_H
47 #include <sys/ioccom.h>
48 #endif
49 #include <sys/utsname.h>
51 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
53 * Add support for capturing on FreeBSD usbusN interfaces.
55 static const char usbus_prefix[] = "usbus";
56 #define USBUS_PREFIX_LEN (sizeof(usbus_prefix) - 1)
57 #include <dirent.h>
58 #endif
60 #ifdef HAVE_ZEROCOPY_BPF
61 #include <machine/atomic.h>
62 #endif
64 #include <net/if.h>
66 #ifdef _AIX
68 #include <sys/types.h>
71 * Prevent bpf.h from redefining the DLT_ values to their
72 * IFT_ values, as we're going to return the standard libpcap
73 * values, not IBM's non-standard IFT_ values.
75 #undef _AIX
76 #include <net/bpf.h>
77 #define _AIX
79 #include <net/if_types.h> /* for IFT_ values */
80 #include <sys/sysconfig.h>
81 #include <sys/device.h>
82 #include <sys/cfgodm.h>
83 #include <cf.h>
85 #ifdef __64BIT__
86 #define domakedev makedev64
87 #define getmajor major64
88 #define bpf_hdr bpf_hdr32
89 #else /* __64BIT__ */
90 #define domakedev makedev
91 #define getmajor major
92 #endif /* __64BIT__ */
94 #define BPF_NAME "bpf"
95 #define BPF_MINORS 4
96 #define DRIVER_PATH "/usr/lib/drivers"
97 #define BPF_NODE "/dev/bpf"
98 static int bpfloadedflag = 0;
99 static int odmlockid = 0;
101 static int bpf_load(char *errbuf);
103 #else /* _AIX */
105 #include <net/bpf.h>
107 #endif /* _AIX */
109 #include <ctype.h>
110 #include <fcntl.h>
111 #include <errno.h>
112 #include <netdb.h>
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <unistd.h>
118 #ifdef HAVE_NET_IF_MEDIA_H
119 # include <net/if_media.h>
120 #endif
122 #include "pcap-int.h"
124 #ifdef HAVE_OS_PROTO_H
125 #include "os-proto.h"
126 #endif
129 * Later versions of NetBSD stick padding in front of FDDI frames
130 * to align the IP header on a 4-byte boundary.
132 #if defined(__NetBSD__) && __NetBSD_Version__ > 106000000
133 #define PCAP_FDDIPAD 3
134 #endif
137 * Private data for capturing on BPF devices.
139 struct pcap_bpf {
140 #ifdef HAVE_ZEROCOPY_BPF
142 * Zero-copy read buffer -- for zero-copy BPF. 'buffer' above will
143 * alternative between these two actual mmap'd buffers as required.
144 * As there is a header on the front size of the mmap'd buffer, only
145 * some of the buffer is exposed to libpcap as a whole via bufsize;
146 * zbufsize is the true size. zbuffer tracks the current zbuf
147 * assocated with buffer so that it can be used to decide which the
148 * next buffer to read will be.
150 u_char *zbuf1, *zbuf2, *zbuffer;
151 u_int zbufsize;
152 u_int zerocopy;
153 u_int interrupted;
154 struct timespec firstsel;
156 * If there's currently a buffer being actively processed, then it is
157 * referenced here; 'buffer' is also pointed at it, but offset by the
158 * size of the header.
160 struct bpf_zbuf_header *bzh;
161 int nonblock; /* true if in nonblocking mode */
162 #endif /* HAVE_ZEROCOPY_BPF */
164 char *device; /* device name */
165 int filtering_in_kernel; /* using kernel filter */
166 int must_do_on_close; /* stuff we must do when we close */
170 * Stuff to do when we close.
172 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
173 #define MUST_DESTROY_USBUS 0x00000002 /* destroy usbusN interface */
175 #ifdef BIOCGDLTLIST
176 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
177 #define HAVE_BSD_IEEE80211
180 * The ifm_ulist member of a struct ifmediareq is an int * on most systems,
181 * but it's a uint64_t on newer versions of OpenBSD.
183 * We check this by checking whether IFM_GMASK is defined and > 2^32-1.
185 # if defined(IFM_GMASK) && IFM_GMASK > 0xFFFFFFFF
186 # define IFM_ULIST_TYPE uint64_t
187 # else
188 # define IFM_ULIST_TYPE int
189 # endif
190 # endif
192 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
193 static int find_802_11(struct bpf_dltlist *);
195 # ifdef HAVE_BSD_IEEE80211
196 static int monitor_mode(pcap_t *, int);
197 # endif
199 # if defined(__APPLE__)
200 static void remove_en(pcap_t *);
201 static void remove_802_11(pcap_t *);
202 # endif
204 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
206 #endif /* BIOCGDLTLIST */
208 #if defined(sun) && defined(LIFNAMSIZ) && defined(lifr_zoneid)
209 #include <zone.h>
210 #endif
213 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
214 * don't get DLT_DOCSIS defined.
216 #ifndef DLT_DOCSIS
217 #define DLT_DOCSIS 143
218 #endif
221 * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
222 * defined, even though some of them are used by various Airport drivers.
224 #ifndef DLT_PRISM_HEADER
225 #define DLT_PRISM_HEADER 119
226 #endif
227 #ifndef DLT_AIRONET_HEADER
228 #define DLT_AIRONET_HEADER 120
229 #endif
230 #ifndef DLT_IEEE802_11_RADIO
231 #define DLT_IEEE802_11_RADIO 127
232 #endif
233 #ifndef DLT_IEEE802_11_RADIO_AVS
234 #define DLT_IEEE802_11_RADIO_AVS 163
235 #endif
237 static int pcap_can_set_rfmon_bpf(pcap_t *p);
238 static int pcap_activate_bpf(pcap_t *p);
239 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
240 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
241 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
244 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
245 * pb->nonblock so we don't call select(2) if the pcap handle is in non-
246 * blocking mode.
248 static int
249 pcap_getnonblock_bpf(pcap_t *p, char *errbuf)
251 #ifdef HAVE_ZEROCOPY_BPF
252 struct pcap_bpf *pb = p->priv;
254 if (pb->zerocopy)
255 return (pb->nonblock);
256 #endif
257 return (pcap_getnonblock_fd(p, errbuf));
260 static int
261 pcap_setnonblock_bpf(pcap_t *p, int nonblock, char *errbuf)
263 #ifdef HAVE_ZEROCOPY_BPF
264 struct pcap_bpf *pb = p->priv;
266 if (pb->zerocopy) {
267 pb->nonblock = nonblock;
268 return (0);
270 #endif
271 return (pcap_setnonblock_fd(p, nonblock, errbuf));
274 #ifdef HAVE_ZEROCOPY_BPF
276 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
277 * shared memory buffers.
279 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
280 * and set up p->buffer and cc to reflect one if available. Notice that if
281 * there was no prior buffer, we select zbuf1 as this will be the first
282 * buffer filled for a fresh BPF session.
284 static int
285 pcap_next_zbuf_shm(pcap_t *p, int *cc)
287 struct pcap_bpf *pb = p->priv;
288 struct bpf_zbuf_header *bzh;
290 if (pb->zbuffer == pb->zbuf2 || pb->zbuffer == NULL) {
291 bzh = (struct bpf_zbuf_header *)pb->zbuf1;
292 if (bzh->bzh_user_gen !=
293 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
294 pb->bzh = bzh;
295 pb->zbuffer = (u_char *)pb->zbuf1;
296 p->buffer = pb->zbuffer + sizeof(*bzh);
297 *cc = bzh->bzh_kernel_len;
298 return (1);
300 } else if (pb->zbuffer == pb->zbuf1) {
301 bzh = (struct bpf_zbuf_header *)pb->zbuf2;
302 if (bzh->bzh_user_gen !=
303 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
304 pb->bzh = bzh;
305 pb->zbuffer = (u_char *)pb->zbuf2;
306 p->buffer = pb->zbuffer + sizeof(*bzh);
307 *cc = bzh->bzh_kernel_len;
308 return (1);
311 *cc = 0;
312 return (0);
316 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
317 * select() for data or a timeout, and possibly force rotation of the buffer
318 * in the event we time out or are in immediate mode. Invoke the shared
319 * memory check before doing system calls in order to avoid doing avoidable
320 * work.
322 static int
323 pcap_next_zbuf(pcap_t *p, int *cc)
325 struct pcap_bpf *pb = p->priv;
326 struct bpf_zbuf bz;
327 struct timeval tv;
328 struct timespec cur;
329 fd_set r_set;
330 int data, r;
331 int expire, tmout;
333 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
335 * Start out by seeing whether anything is waiting by checking the
336 * next shared memory buffer for data.
338 data = pcap_next_zbuf_shm(p, cc);
339 if (data)
340 return (data);
342 * If a previous sleep was interrupted due to signal delivery, make
343 * sure that the timeout gets adjusted accordingly. This requires
344 * that we analyze when the timeout should be been expired, and
345 * subtract the current time from that. If after this operation,
346 * our timeout is less then or equal to zero, handle it like a
347 * regular timeout.
349 tmout = p->opt.timeout;
350 if (tmout)
351 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
352 if (pb->interrupted && p->opt.timeout) {
353 expire = TSTOMILLI(&pb->firstsel) + p->opt.timeout;
354 tmout = expire - TSTOMILLI(&cur);
355 #undef TSTOMILLI
356 if (tmout <= 0) {
357 pb->interrupted = 0;
358 data = pcap_next_zbuf_shm(p, cc);
359 if (data)
360 return (data);
361 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
362 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
363 "BIOCROTZBUF: %s", strerror(errno));
364 return (PCAP_ERROR);
366 return (pcap_next_zbuf_shm(p, cc));
370 * No data in the buffer, so must use select() to wait for data or
371 * the next timeout. Note that we only call select if the handle
372 * is in blocking mode.
374 if (!pb->nonblock) {
375 FD_ZERO(&r_set);
376 FD_SET(p->fd, &r_set);
377 if (tmout != 0) {
378 tv.tv_sec = tmout / 1000;
379 tv.tv_usec = (tmout * 1000) % 1000000;
381 r = select(p->fd + 1, &r_set, NULL, NULL,
382 p->opt.timeout != 0 ? &tv : NULL);
383 if (r < 0 && errno == EINTR) {
384 if (!pb->interrupted && p->opt.timeout) {
385 pb->interrupted = 1;
386 pb->firstsel = cur;
388 return (0);
389 } else if (r < 0) {
390 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
391 "select: %s", strerror(errno));
392 return (PCAP_ERROR);
395 pb->interrupted = 0;
397 * Check again for data, which may exist now that we've either been
398 * woken up as a result of data or timed out. Try the "there's data"
399 * case first since it doesn't require a system call.
401 data = pcap_next_zbuf_shm(p, cc);
402 if (data)
403 return (data);
405 * Try forcing a buffer rotation to dislodge timed out or immediate
406 * data.
408 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
409 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
410 "BIOCROTZBUF: %s", strerror(errno));
411 return (PCAP_ERROR);
413 return (pcap_next_zbuf_shm(p, cc));
417 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
418 * that we know which buffer to use next time around.
420 static int
421 pcap_ack_zbuf(pcap_t *p)
423 struct pcap_bpf *pb = p->priv;
425 atomic_store_rel_int(&pb->bzh->bzh_user_gen,
426 pb->bzh->bzh_kernel_gen);
427 pb->bzh = NULL;
428 p->buffer = NULL;
429 return (0);
431 #endif /* HAVE_ZEROCOPY_BPF */
433 pcap_t *
434 pcap_create_interface(const char *device _U_, char *ebuf)
436 pcap_t *p;
438 p = pcap_create_common(ebuf, sizeof (struct pcap_bpf));
439 if (p == NULL)
440 return (NULL);
442 p->activate_op = pcap_activate_bpf;
443 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
444 #ifdef BIOCSTSTAMP
446 * We claim that we support microsecond and nanosecond time
447 * stamps.
449 p->tstamp_precision_count = 2;
450 p->tstamp_precision_list = malloc(2 * sizeof(u_int));
451 if (p->tstamp_precision_list == NULL) {
452 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
453 pcap_strerror(errno));
454 free(p);
455 return (NULL);
457 p->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
458 p->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
459 #endif /* BIOCSTSTAMP */
460 return (p);
464 * On success, returns a file descriptor for a BPF device.
465 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
467 static int
468 bpf_open(char *errbuf)
470 int fd;
471 #ifdef HAVE_CLONING_BPF
472 static const char device[] = "/dev/bpf";
473 #else
474 int n = 0;
475 char device[sizeof "/dev/bpf0000000000"];
476 #endif
478 #ifdef _AIX
480 * Load the bpf driver, if it isn't already loaded,
481 * and create the BPF device entries, if they don't
482 * already exist.
484 if (bpf_load(errbuf) == PCAP_ERROR)
485 return (PCAP_ERROR);
486 #endif
488 #ifdef HAVE_CLONING_BPF
489 if ((fd = open(device, O_RDWR)) == -1 &&
490 (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
491 if (errno == EACCES)
492 fd = PCAP_ERROR_PERM_DENIED;
493 else
494 fd = PCAP_ERROR;
495 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
496 "(cannot open device) %s: %s", device, pcap_strerror(errno));
498 #else
500 * Go through all the minors and find one that isn't in use.
502 do {
503 (void)pcap_snprintf(device, sizeof(device), "/dev/bpf%d", n++);
505 * Initially try a read/write open (to allow the inject
506 * method to work). If that fails due to permission
507 * issues, fall back to read-only. This allows a
508 * non-root user to be granted specific access to pcap
509 * capabilities via file permissions.
511 * XXX - we should have an API that has a flag that
512 * controls whether to open read-only or read-write,
513 * so that denial of permission to send (or inability
514 * to send, if sending packets isn't supported on
515 * the device in question) can be indicated at open
516 * time.
518 fd = open(device, O_RDWR);
519 if (fd == -1 && errno == EACCES)
520 fd = open(device, O_RDONLY);
521 } while (fd < 0 && errno == EBUSY);
524 * XXX better message for all minors used
526 if (fd < 0) {
527 switch (errno) {
529 case ENOENT:
530 fd = PCAP_ERROR;
531 if (n == 1) {
533 * /dev/bpf0 doesn't exist, which
534 * means we probably have no BPF
535 * devices.
537 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
538 "(there are no BPF devices)");
539 } else {
541 * We got EBUSY on at least one
542 * BPF device, so we have BPF
543 * devices, but all the ones
544 * that exist are busy.
546 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
547 "(all BPF devices are busy)");
549 break;
551 case EACCES:
553 * Got EACCES on the last device we tried,
554 * and EBUSY on all devices before that,
555 * if any.
557 fd = PCAP_ERROR_PERM_DENIED;
558 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
559 "(cannot open BPF device) %s: %s", device,
560 pcap_strerror(errno));
561 break;
563 default:
565 * Some other problem.
567 fd = PCAP_ERROR;
568 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
569 "(cannot open BPF device) %s: %s", device,
570 pcap_strerror(errno));
571 break;
574 #endif
576 return (fd);
580 * Open and bind to a device; used if we're not actually going to use
581 * the device, but are just testing whether it can be opened, or opening
582 * it to get information about it.
584 * Returns an error code on failure (always negative), and an FD for
585 * the now-bound BPF device on success (always non-negative).
587 static int
588 bpf_open_and_bind(const char *name, char *errbuf)
590 int fd;
591 struct ifreq ifr;
594 * First, open a BPF device.
596 fd = bpf_open(errbuf);
597 if (fd < 0)
598 return (fd); /* fd is the appropriate error code */
601 * Now bind to the device.
603 (void)strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
604 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
605 switch (errno) {
607 case ENXIO:
609 * There's no such device.
611 close(fd);
612 return (PCAP_ERROR_NO_SUCH_DEVICE);
614 case ENETDOWN:
616 * Return a "network down" indication, so that
617 * the application can report that rather than
618 * saying we had a mysterious failure and
619 * suggest that they report a problem to the
620 * libpcap developers.
622 close(fd);
623 return (PCAP_ERROR_IFACE_NOT_UP);
625 default:
626 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
627 "BIOCSETIF: %s: %s", name, pcap_strerror(errno));
628 close(fd);
629 return (PCAP_ERROR);
634 * Success.
636 return (fd);
639 #ifdef BIOCGDLTLIST
640 static int
641 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
643 memset(bdlp, 0, sizeof(*bdlp));
644 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
645 u_int i;
646 int is_ethernet;
648 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
649 if (bdlp->bfl_list == NULL) {
650 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
651 pcap_strerror(errno));
652 return (PCAP_ERROR);
655 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
656 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE,
657 "BIOCGDLTLIST: %s", pcap_strerror(errno));
658 free(bdlp->bfl_list);
659 return (PCAP_ERROR);
663 * OK, for real Ethernet devices, add DLT_DOCSIS to the
664 * list, so that an application can let you choose it,
665 * in case you're capturing DOCSIS traffic that a Cisco
666 * Cable Modem Termination System is putting out onto
667 * an Ethernet (it doesn't put an Ethernet header onto
668 * the wire, it puts raw DOCSIS frames out on the wire
669 * inside the low-level Ethernet framing).
671 * A "real Ethernet device" is defined here as a device
672 * that has a link-layer type of DLT_EN10MB and that has
673 * no alternate link-layer types; that's done to exclude
674 * 802.11 interfaces (which might or might not be the
675 * right thing to do, but I suspect it is - Ethernet <->
676 * 802.11 bridges would probably badly mishandle frames
677 * that don't have Ethernet headers).
679 * On Solaris with BPF, Ethernet devices also offer
680 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
681 * treat it as an indication that the device isn't an
682 * Ethernet.
684 if (v == DLT_EN10MB) {
685 is_ethernet = 1;
686 for (i = 0; i < bdlp->bfl_len; i++) {
687 if (bdlp->bfl_list[i] != DLT_EN10MB
688 #ifdef DLT_IPNET
689 && bdlp->bfl_list[i] != DLT_IPNET
690 #endif
692 is_ethernet = 0;
693 break;
696 if (is_ethernet) {
698 * We reserved one more slot at the end of
699 * the list.
701 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
702 bdlp->bfl_len++;
705 } else {
707 * EINVAL just means "we don't support this ioctl on
708 * this device"; don't treat it as an error.
710 if (errno != EINVAL) {
711 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE,
712 "BIOCGDLTLIST: %s", pcap_strerror(errno));
713 return (PCAP_ERROR);
716 return (0);
718 #endif
720 static int
721 pcap_can_set_rfmon_bpf(pcap_t *p)
723 #if defined(__APPLE__)
724 struct utsname osinfo;
725 struct ifreq ifr;
726 int fd;
727 #ifdef BIOCGDLTLIST
728 struct bpf_dltlist bdl;
729 #endif
732 * The joys of monitor mode on OS X.
734 * Prior to 10.4, it's not supported at all.
736 * In 10.4, if adapter enN supports monitor mode, there's a
737 * wltN adapter corresponding to it; you open it, instead of
738 * enN, to get monitor mode. You get whatever link-layer
739 * headers it supplies.
741 * In 10.5, and, we assume, later releases, if adapter enN
742 * supports monitor mode, it offers, among its selectable
743 * DLT_ values, values that let you get the 802.11 header;
744 * selecting one of those values puts the adapter into monitor
745 * mode (i.e., you can't get 802.11 headers except in monitor
746 * mode, and you can't get Ethernet headers in monitor mode).
748 if (uname(&osinfo) == -1) {
750 * Can't get the OS version; just say "no".
752 return (0);
755 * We assume osinfo.sysname is "Darwin", because
756 * __APPLE__ is defined. We just check the version.
758 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
760 * 10.3 (Darwin 7.x) or earlier.
761 * Monitor mode not supported.
763 return (0);
765 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
767 * 10.4 (Darwin 8.x). s/en/wlt/, and check
768 * whether the device exists.
770 if (strncmp(p->opt.device, "en", 2) != 0) {
772 * Not an enN device; no monitor mode.
774 return (0);
776 fd = socket(AF_INET, SOCK_DGRAM, 0);
777 if (fd == -1) {
778 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
779 "socket: %s", pcap_strerror(errno));
780 return (PCAP_ERROR);
782 strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
783 strlcat(ifr.ifr_name, p->opt.device + 2, sizeof(ifr.ifr_name));
784 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
786 * No such device?
788 close(fd);
789 return (0);
791 close(fd);
792 return (1);
795 #ifdef BIOCGDLTLIST
797 * Everything else is 10.5 or later; for those,
798 * we just open the enN device, and check whether
799 * we have any 802.11 devices.
801 * First, open a BPF device.
803 fd = bpf_open(p->errbuf);
804 if (fd < 0)
805 return (fd); /* fd is the appropriate error code */
808 * Now bind to the device.
810 (void)strncpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
811 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
812 switch (errno) {
814 case ENXIO:
816 * There's no such device.
818 close(fd);
819 return (PCAP_ERROR_NO_SUCH_DEVICE);
821 case ENETDOWN:
823 * Return a "network down" indication, so that
824 * the application can report that rather than
825 * saying we had a mysterious failure and
826 * suggest that they report a problem to the
827 * libpcap developers.
829 close(fd);
830 return (PCAP_ERROR_IFACE_NOT_UP);
832 default:
833 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
834 "BIOCSETIF: %s: %s",
835 p->opt.device, pcap_strerror(errno));
836 close(fd);
837 return (PCAP_ERROR);
842 * We know the default link type -- now determine all the DLTs
843 * this interface supports. If this fails with EINVAL, it's
844 * not fatal; we just don't get to use the feature later.
845 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
846 * as the default DLT for this adapter.)
848 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
849 close(fd);
850 return (PCAP_ERROR);
852 if (find_802_11(&bdl) != -1) {
854 * We have an 802.11 DLT, so we can set monitor mode.
856 free(bdl.bfl_list);
857 close(fd);
858 return (1);
860 free(bdl.bfl_list);
861 close(fd);
862 #endif /* BIOCGDLTLIST */
863 return (0);
864 #elif defined(HAVE_BSD_IEEE80211)
865 int ret;
867 ret = monitor_mode(p, 0);
868 if (ret == PCAP_ERROR_RFMON_NOTSUP)
869 return (0); /* not an error, just a "can't do" */
870 if (ret == 0)
871 return (1); /* success */
872 return (ret);
873 #else
874 return (0);
875 #endif
878 static int
879 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
881 struct bpf_stat s;
884 * "ps_recv" counts packets handed to the filter, not packets
885 * that passed the filter. This includes packets later dropped
886 * because we ran out of buffer space.
888 * "ps_drop" counts packets dropped inside the BPF device
889 * because we ran out of buffer space. It doesn't count
890 * packets dropped by the interface driver. It counts
891 * only packets that passed the filter.
893 * Both statistics include packets not yet read from the kernel
894 * by libpcap, and thus not yet seen by the application.
896 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
897 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
898 pcap_strerror(errno));
899 return (PCAP_ERROR);
902 ps->ps_recv = s.bs_recv;
903 ps->ps_drop = s.bs_drop;
904 ps->ps_ifdrop = 0;
905 return (0);
908 static int
909 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
911 struct pcap_bpf *pb = p->priv;
912 int cc;
913 int n = 0;
914 register u_char *bp, *ep;
915 u_char *datap;
916 #ifdef PCAP_FDDIPAD
917 register u_int pad;
918 #endif
919 #ifdef HAVE_ZEROCOPY_BPF
920 int i;
921 #endif
923 again:
925 * Has "pcap_breakloop()" been called?
927 if (p->break_loop) {
929 * Yes - clear the flag that indicates that it
930 * has, and return PCAP_ERROR_BREAK to indicate
931 * that we were told to break out of the loop.
933 p->break_loop = 0;
934 return (PCAP_ERROR_BREAK);
936 cc = p->cc;
937 if (p->cc == 0) {
939 * When reading without zero-copy from a file descriptor, we
940 * use a single buffer and return a length of data in the
941 * buffer. With zero-copy, we update the p->buffer pointer
942 * to point at whatever underlying buffer contains the next
943 * data and update cc to reflect the data found in the
944 * buffer.
946 #ifdef HAVE_ZEROCOPY_BPF
947 if (pb->zerocopy) {
948 if (p->buffer != NULL)
949 pcap_ack_zbuf(p);
950 i = pcap_next_zbuf(p, &cc);
951 if (i == 0)
952 goto again;
953 if (i < 0)
954 return (PCAP_ERROR);
955 } else
956 #endif
958 cc = read(p->fd, p->buffer, p->bufsize);
960 if (cc < 0) {
961 /* Don't choke when we get ptraced */
962 switch (errno) {
964 case EINTR:
965 goto again;
967 #ifdef _AIX
968 case EFAULT:
970 * Sigh. More AIX wonderfulness.
972 * For some unknown reason the uiomove()
973 * operation in the bpf kernel extension
974 * used to copy the buffer into user
975 * space sometimes returns EFAULT. I have
976 * no idea why this is the case given that
977 * a kernel debugger shows the user buffer
978 * is correct. This problem appears to
979 * be mostly mitigated by the memset of
980 * the buffer before it is first used.
981 * Very strange.... Shaun Clowes
983 * In any case this means that we shouldn't
984 * treat EFAULT as a fatal error; as we
985 * don't have an API for returning
986 * a "some packets were dropped since
987 * the last packet you saw" indication,
988 * we just ignore EFAULT and keep reading.
990 goto again;
991 #endif
993 case EWOULDBLOCK:
994 return (0);
996 case ENXIO:
998 * The device on which we're capturing
999 * went away.
1001 * XXX - we should really return
1002 * PCAP_ERROR_IFACE_NOT_UP, but
1003 * pcap_dispatch() etc. aren't
1004 * defined to retur that.
1006 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1007 "The interface went down");
1008 return (PCAP_ERROR);
1010 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
1012 * Due to a SunOS bug, after 2^31 bytes, the kernel
1013 * file offset overflows and read fails with EINVAL.
1014 * The lseek() to 0 will fix things.
1016 case EINVAL:
1017 if (lseek(p->fd, 0L, SEEK_CUR) +
1018 p->bufsize < 0) {
1019 (void)lseek(p->fd, 0L, SEEK_SET);
1020 goto again;
1022 /* fall through */
1023 #endif
1025 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
1026 pcap_strerror(errno));
1027 return (PCAP_ERROR);
1029 bp = (u_char *)p->buffer;
1030 } else
1031 bp = p->bp;
1034 * Loop through each packet.
1036 #ifdef BIOCSTSTAMP
1037 #define bhp ((struct bpf_xhdr *)bp)
1038 #else
1039 #define bhp ((struct bpf_hdr *)bp)
1040 #endif
1041 ep = bp + cc;
1042 #ifdef PCAP_FDDIPAD
1043 pad = p->fddipad;
1044 #endif
1045 while (bp < ep) {
1046 register u_int caplen, hdrlen;
1049 * Has "pcap_breakloop()" been called?
1050 * If so, return immediately - if we haven't read any
1051 * packets, clear the flag and return PCAP_ERROR_BREAK
1052 * to indicate that we were told to break out of the loop,
1053 * otherwise leave the flag set, so that the *next* call
1054 * will break out of the loop without having read any
1055 * packets, and return the number of packets we've
1056 * processed so far.
1058 if (p->break_loop) {
1059 p->bp = bp;
1060 p->cc = ep - bp;
1062 * ep is set based on the return value of read(),
1063 * but read() from a BPF device doesn't necessarily
1064 * return a value that's a multiple of the alignment
1065 * value for BPF_WORDALIGN(). However, whenever we
1066 * increment bp, we round up the increment value by
1067 * a value rounded up by BPF_WORDALIGN(), so we
1068 * could increment bp past ep after processing the
1069 * last packet in the buffer.
1071 * We treat ep < bp as an indication that this
1072 * happened, and just set p->cc to 0.
1074 if (p->cc < 0)
1075 p->cc = 0;
1076 if (n == 0) {
1077 p->break_loop = 0;
1078 return (PCAP_ERROR_BREAK);
1079 } else
1080 return (n);
1083 caplen = bhp->bh_caplen;
1084 hdrlen = bhp->bh_hdrlen;
1085 datap = bp + hdrlen;
1087 * Short-circuit evaluation: if using BPF filter
1088 * in kernel, no need to do it now - we already know
1089 * the packet passed the filter.
1091 #ifdef PCAP_FDDIPAD
1092 * Note: the filter code was generated assuming
1093 * that p->fddipad was the amount of padding
1094 * before the header, as that's what's required
1095 * in the kernel, so we run the filter before
1096 * skipping that padding.
1097 #endif
1099 if (pb->filtering_in_kernel ||
1100 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1101 struct pcap_pkthdr pkthdr;
1102 #ifdef BIOCSTSTAMP
1103 struct bintime bt;
1105 bt.sec = bhp->bh_tstamp.bt_sec;
1106 bt.frac = bhp->bh_tstamp.bt_frac;
1107 if (p->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
1108 struct timespec ts;
1110 bintime2timespec(&bt, &ts);
1111 pkthdr.ts.tv_sec = ts.tv_sec;
1112 pkthdr.ts.tv_usec = ts.tv_nsec;
1113 } else {
1114 struct timeval tv;
1116 bintime2timeval(&bt, &tv);
1117 pkthdr.ts.tv_sec = tv.tv_sec;
1118 pkthdr.ts.tv_usec = tv.tv_usec;
1120 #else
1121 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1122 #ifdef _AIX
1124 * AIX's BPF returns seconds/nanoseconds time
1125 * stamps, not seconds/microseconds time stamps.
1127 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1128 #else
1129 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1130 #endif
1131 #endif /* BIOCSTSTAMP */
1132 #ifdef PCAP_FDDIPAD
1133 if (caplen > pad)
1134 pkthdr.caplen = caplen - pad;
1135 else
1136 pkthdr.caplen = 0;
1137 if (bhp->bh_datalen > pad)
1138 pkthdr.len = bhp->bh_datalen - pad;
1139 else
1140 pkthdr.len = 0;
1141 datap += pad;
1142 #else
1143 pkthdr.caplen = caplen;
1144 pkthdr.len = bhp->bh_datalen;
1145 #endif
1146 (*callback)(user, &pkthdr, datap);
1147 bp += BPF_WORDALIGN(caplen + hdrlen);
1148 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
1149 p->bp = bp;
1150 p->cc = ep - bp;
1152 * See comment above about p->cc < 0.
1154 if (p->cc < 0)
1155 p->cc = 0;
1156 return (n);
1158 } else {
1160 * Skip this packet.
1162 bp += BPF_WORDALIGN(caplen + hdrlen);
1165 #undef bhp
1166 p->cc = 0;
1167 return (n);
1170 static int
1171 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1173 int ret;
1175 ret = write(p->fd, buf, size);
1176 #ifdef __APPLE__
1177 if (ret == -1 && errno == EAFNOSUPPORT) {
1179 * In Mac OS X, there's a bug wherein setting the
1180 * BIOCSHDRCMPLT flag causes writes to fail; see,
1181 * for example:
1183 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1185 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
1186 * assume it's due to that bug, and turn off that flag
1187 * and try again. If we succeed, it either means that
1188 * somebody applied the fix from that URL, or other patches
1189 * for that bug from
1191 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1193 * and are running a Darwin kernel with those fixes, or
1194 * that Apple fixed the problem in some OS X release.
1196 u_int spoof_eth_src = 0;
1198 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1199 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1200 "send: can't turn off BIOCSHDRCMPLT: %s",
1201 pcap_strerror(errno));
1202 return (PCAP_ERROR);
1206 * Now try the write again.
1208 ret = write(p->fd, buf, size);
1210 #endif /* __APPLE__ */
1211 if (ret == -1) {
1212 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1213 pcap_strerror(errno));
1214 return (PCAP_ERROR);
1216 return (ret);
1219 #ifdef _AIX
1220 static int
1221 bpf_odminit(char *errbuf)
1223 char *errstr;
1225 if (odm_initialize() == -1) {
1226 if (odm_err_msg(odmerrno, &errstr) == -1)
1227 errstr = "Unknown error";
1228 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1229 "bpf_load: odm_initialize failed: %s",
1230 errstr);
1231 return (PCAP_ERROR);
1234 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1235 if (odm_err_msg(odmerrno, &errstr) == -1)
1236 errstr = "Unknown error";
1237 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1238 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1239 errstr);
1240 (void)odm_terminate();
1241 return (PCAP_ERROR);
1244 return (0);
1247 static int
1248 bpf_odmcleanup(char *errbuf)
1250 char *errstr;
1252 if (odm_unlock(odmlockid) == -1) {
1253 if (errbuf != NULL) {
1254 if (odm_err_msg(odmerrno, &errstr) == -1)
1255 errstr = "Unknown error";
1256 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1257 "bpf_load: odm_unlock failed: %s",
1258 errstr);
1260 return (PCAP_ERROR);
1263 if (odm_terminate() == -1) {
1264 if (errbuf != NULL) {
1265 if (odm_err_msg(odmerrno, &errstr) == -1)
1266 errstr = "Unknown error";
1267 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1268 "bpf_load: odm_terminate failed: %s",
1269 errstr);
1271 return (PCAP_ERROR);
1274 return (0);
1277 static int
1278 bpf_load(char *errbuf)
1280 long major;
1281 int *minors;
1282 int numminors, i, rc;
1283 char buf[1024];
1284 struct stat sbuf;
1285 struct bpf_config cfg_bpf;
1286 struct cfg_load cfg_ld;
1287 struct cfg_kmod cfg_km;
1290 * This is very very close to what happens in the real implementation
1291 * but I've fixed some (unlikely) bug situations.
1293 if (bpfloadedflag)
1294 return (0);
1296 if (bpf_odminit(errbuf) == PCAP_ERROR)
1297 return (PCAP_ERROR);
1299 major = genmajor(BPF_NAME);
1300 if (major == -1) {
1301 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1302 "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1303 (void)bpf_odmcleanup(NULL);
1304 return (PCAP_ERROR);
1307 minors = getminor(major, &numminors, BPF_NAME);
1308 if (!minors) {
1309 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1310 if (!minors) {
1311 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1312 "bpf_load: genminor failed: %s",
1313 pcap_strerror(errno));
1314 (void)bpf_odmcleanup(NULL);
1315 return (PCAP_ERROR);
1319 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1320 return (PCAP_ERROR);
1322 rc = stat(BPF_NODE "0", &sbuf);
1323 if (rc == -1 && errno != ENOENT) {
1324 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1325 "bpf_load: can't stat %s: %s",
1326 BPF_NODE "0", pcap_strerror(errno));
1327 return (PCAP_ERROR);
1330 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1331 for (i = 0; i < BPF_MINORS; i++) {
1332 sprintf(buf, "%s%d", BPF_NODE, i);
1333 unlink(buf);
1334 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1335 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1336 "bpf_load: can't mknod %s: %s",
1337 buf, pcap_strerror(errno));
1338 return (PCAP_ERROR);
1343 /* Check if the driver is loaded */
1344 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1345 cfg_ld.path = buf;
1346 sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1347 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1348 (cfg_ld.kmid == 0)) {
1349 /* Driver isn't loaded, load it now */
1350 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1351 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1352 "bpf_load: could not load driver: %s",
1353 strerror(errno));
1354 return (PCAP_ERROR);
1358 /* Configure the driver */
1359 cfg_km.cmd = CFG_INIT;
1360 cfg_km.kmid = cfg_ld.kmid;
1361 cfg_km.mdilen = sizeof(cfg_bpf);
1362 cfg_km.mdiptr = (void *)&cfg_bpf;
1363 for (i = 0; i < BPF_MINORS; i++) {
1364 cfg_bpf.devno = domakedev(major, i);
1365 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1366 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1367 "bpf_load: could not configure driver: %s",
1368 strerror(errno));
1369 return (PCAP_ERROR);
1373 bpfloadedflag = 1;
1375 return (0);
1377 #endif
1380 * Undo any operations done when opening the device when necessary.
1382 static void
1383 pcap_cleanup_bpf(pcap_t *p)
1385 struct pcap_bpf *pb = p->priv;
1386 #ifdef HAVE_BSD_IEEE80211
1387 int sock;
1388 struct ifmediareq req;
1389 struct ifreq ifr;
1390 #endif
1392 if (pb->must_do_on_close != 0) {
1394 * There's something we have to do when closing this
1395 * pcap_t.
1397 #ifdef HAVE_BSD_IEEE80211
1398 if (pb->must_do_on_close & MUST_CLEAR_RFMON) {
1400 * We put the interface into rfmon mode;
1401 * take it out of rfmon mode.
1403 * XXX - if somebody else wants it in rfmon
1404 * mode, this code cannot know that, so it'll take
1405 * it out of rfmon mode.
1407 sock = socket(AF_INET, SOCK_DGRAM, 0);
1408 if (sock == -1) {
1409 fprintf(stderr,
1410 "Can't restore interface flags (socket() failed: %s).\n"
1411 "Please adjust manually.\n",
1412 strerror(errno));
1413 } else {
1414 memset(&req, 0, sizeof(req));
1415 strncpy(req.ifm_name, pb->device,
1416 sizeof(req.ifm_name));
1417 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1418 fprintf(stderr,
1419 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1420 "Please adjust manually.\n",
1421 strerror(errno));
1422 } else {
1423 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1425 * Rfmon mode is currently on;
1426 * turn it off.
1428 memset(&ifr, 0, sizeof(ifr));
1429 (void)strncpy(ifr.ifr_name,
1430 pb->device,
1431 sizeof(ifr.ifr_name));
1432 ifr.ifr_media =
1433 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1434 if (ioctl(sock, SIOCSIFMEDIA,
1435 &ifr) == -1) {
1436 fprintf(stderr,
1437 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1438 "Please adjust manually.\n",
1439 strerror(errno));
1443 close(sock);
1446 #endif /* HAVE_BSD_IEEE80211 */
1448 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1450 * Attempt to destroy the usbusN interface that we created.
1452 if (pb->must_do_on_close & MUST_DESTROY_USBUS) {
1453 if (if_nametoindex(pb->device) > 0) {
1454 int s;
1456 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1457 if (s >= 0) {
1458 strlcpy(ifr.ifr_name, pb->device,
1459 sizeof(ifr.ifr_name));
1460 ioctl(s, SIOCIFDESTROY, &ifr);
1461 close(s);
1465 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1467 * Take this pcap out of the list of pcaps for which we
1468 * have to take the interface out of some mode.
1470 pcap_remove_from_pcaps_to_close(p);
1471 pb->must_do_on_close = 0;
1474 #ifdef HAVE_ZEROCOPY_BPF
1475 if (pb->zerocopy) {
1477 * Delete the mappings. Note that p->buffer gets
1478 * initialized to one of the mmapped regions in
1479 * this case, so do not try and free it directly;
1480 * null it out so that pcap_cleanup_live_common()
1481 * doesn't try to free it.
1483 if (pb->zbuf1 != MAP_FAILED && pb->zbuf1 != NULL)
1484 (void) munmap(pb->zbuf1, pb->zbufsize);
1485 if (pb->zbuf2 != MAP_FAILED && pb->zbuf2 != NULL)
1486 (void) munmap(pb->zbuf2, pb->zbufsize);
1487 p->buffer = NULL;
1489 #endif
1490 if (pb->device != NULL) {
1491 free(pb->device);
1492 pb->device = NULL;
1494 pcap_cleanup_live_common(p);
1497 static int
1498 check_setif_failure(pcap_t *p, int error)
1500 #ifdef __APPLE__
1501 int fd;
1502 struct ifreq ifr;
1503 int err;
1504 #endif
1506 if (error == ENXIO) {
1508 * No such device exists.
1510 #ifdef __APPLE__
1511 if (p->opt.rfmon && strncmp(p->opt.device, "wlt", 3) == 0) {
1513 * Monitor mode was requested, and we're trying
1514 * to open a "wltN" device. Assume that this
1515 * is 10.4 and that we were asked to open an
1516 * "enN" device; if that device exists, return
1517 * "monitor mode not supported on the device".
1519 fd = socket(AF_INET, SOCK_DGRAM, 0);
1520 if (fd != -1) {
1521 strlcpy(ifr.ifr_name, "en",
1522 sizeof(ifr.ifr_name));
1523 strlcat(ifr.ifr_name, p->opt.device + 3,
1524 sizeof(ifr.ifr_name));
1525 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1527 * We assume this failed because
1528 * the underlying device doesn't
1529 * exist.
1531 err = PCAP_ERROR_NO_SUCH_DEVICE;
1532 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1533 "SIOCGIFFLAGS on %s failed: %s",
1534 ifr.ifr_name, pcap_strerror(errno));
1535 } else {
1537 * The underlying "enN" device
1538 * exists, but there's no
1539 * corresponding "wltN" device;
1540 * that means that the "enN"
1541 * device doesn't support
1542 * monitor mode, probably because
1543 * it's an Ethernet device rather
1544 * than a wireless device.
1546 err = PCAP_ERROR_RFMON_NOTSUP;
1548 close(fd);
1549 } else {
1551 * We can't find out whether there's
1552 * an underlying "enN" device, so
1553 * just report "no such device".
1555 err = PCAP_ERROR_NO_SUCH_DEVICE;
1556 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1557 "socket() failed: %s",
1558 pcap_strerror(errno));
1560 return (err);
1562 #endif
1564 * No such device.
1566 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
1567 pcap_strerror(errno));
1568 return (PCAP_ERROR_NO_SUCH_DEVICE);
1569 } else if (errno == ENETDOWN) {
1571 * Return a "network down" indication, so that
1572 * the application can report that rather than
1573 * saying we had a mysterious failure and
1574 * suggest that they report a problem to the
1575 * libpcap developers.
1577 return (PCAP_ERROR_IFACE_NOT_UP);
1578 } else {
1580 * Some other error; fill in the error string, and
1581 * return PCAP_ERROR.
1583 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1584 p->opt.device, pcap_strerror(errno));
1585 return (PCAP_ERROR);
1590 * Default capture buffer size.
1591 * 32K isn't very much for modern machines with fast networks; we
1592 * pick .5M, as that's the maximum on at least some systems with BPF.
1594 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1595 * read failures under stress, so we leave it as 32K; yet another
1596 * place where AIX's BPF is broken.
1598 #ifdef _AIX
1599 #define DEFAULT_BUFSIZE 32768
1600 #else
1601 #define DEFAULT_BUFSIZE 524288
1602 #endif
1604 static int
1605 pcap_activate_bpf(pcap_t *p)
1607 struct pcap_bpf *pb = p->priv;
1608 int status = 0;
1609 #ifdef HAVE_BSD_IEEE80211
1610 int retv;
1611 #endif
1612 int fd;
1613 #ifdef LIFNAMSIZ
1614 char *zonesep;
1615 struct lifreq ifr;
1616 char *ifrname = ifr.lifr_name;
1617 const size_t ifnamsiz = sizeof(ifr.lifr_name);
1618 #else
1619 struct ifreq ifr;
1620 char *ifrname = ifr.ifr_name;
1621 const size_t ifnamsiz = sizeof(ifr.ifr_name);
1622 #endif
1623 struct bpf_version bv;
1624 #ifdef __APPLE__
1625 int sockfd;
1626 char *wltdev = NULL;
1627 #endif
1628 #ifdef BIOCGDLTLIST
1629 struct bpf_dltlist bdl;
1630 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1631 int new_dlt;
1632 #endif
1633 #endif /* BIOCGDLTLIST */
1634 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1635 u_int spoof_eth_src = 1;
1636 #endif
1637 u_int v;
1638 struct bpf_insn total_insn;
1639 struct bpf_program total_prog;
1640 struct utsname osinfo;
1641 int have_osinfo = 0;
1642 #ifdef HAVE_ZEROCOPY_BPF
1643 struct bpf_zbuf bz;
1644 u_int bufmode, zbufmax;
1645 #endif
1647 fd = bpf_open(p->errbuf);
1648 if (fd < 0) {
1649 status = fd;
1650 goto bad;
1653 p->fd = fd;
1655 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1656 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1657 pcap_strerror(errno));
1658 status = PCAP_ERROR;
1659 goto bad;
1661 if (bv.bv_major != BPF_MAJOR_VERSION ||
1662 bv.bv_minor < BPF_MINOR_VERSION) {
1663 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1664 "kernel bpf filter out of date");
1665 status = PCAP_ERROR;
1666 goto bad;
1669 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1671 * Retrieve the zoneid of the zone we are currently executing in.
1673 if ((ifr.lifr_zoneid = getzoneid()) == -1) {
1674 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "getzoneid(): %s",
1675 pcap_strerror(errno));
1676 status = PCAP_ERROR;
1677 goto bad;
1680 * Check if the given source datalink name has a '/' separated
1681 * zonename prefix string. The zonename prefixed source datalink can
1682 * be used by pcap consumers in the Solaris global zone to capture
1683 * traffic on datalinks in non-global zones. Non-global zones
1684 * do not have access to datalinks outside of their own namespace.
1686 if ((zonesep = strchr(p->opt.device, '/')) != NULL) {
1687 char path_zname[ZONENAME_MAX];
1688 int znamelen;
1689 char *lnamep;
1691 if (ifr.lifr_zoneid != GLOBAL_ZONEID) {
1692 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1693 "zonename/linkname only valid in global zone.");
1694 status = PCAP_ERROR;
1695 goto bad;
1697 znamelen = zonesep - p->opt.device;
1698 (void) strlcpy(path_zname, p->opt.device, znamelen + 1);
1699 ifr.lifr_zoneid = getzoneidbyname(path_zname);
1700 if (ifr.lifr_zoneid == -1) {
1701 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1702 "getzoneidbyname(%s): %s", path_zname,
1703 pcap_strerror(errno));
1704 status = PCAP_ERROR;
1705 goto bad;
1707 lnamep = strdup(zonesep + 1);
1708 if (lnamep == NULL) {
1709 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1710 pcap_strerror(errno));
1711 status = PCAP_ERROR;
1712 goto bad;
1714 free(p->opt.device);
1715 p->opt.device = lnamep;
1717 #endif
1719 pb->device = strdup(p->opt.device);
1720 if (pb->device == NULL) {
1721 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1722 pcap_strerror(errno));
1723 status = PCAP_ERROR;
1724 goto bad;
1728 * Attempt to find out the version of the OS on which we're running.
1730 if (uname(&osinfo) == 0)
1731 have_osinfo = 1;
1733 #ifdef __APPLE__
1735 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1736 * of why we check the version number.
1738 if (p->opt.rfmon) {
1739 if (have_osinfo) {
1741 * We assume osinfo.sysname is "Darwin", because
1742 * __APPLE__ is defined. We just check the version.
1744 if (osinfo.release[0] < '8' &&
1745 osinfo.release[1] == '.') {
1747 * 10.3 (Darwin 7.x) or earlier.
1749 status = PCAP_ERROR_RFMON_NOTSUP;
1750 goto bad;
1752 if (osinfo.release[0] == '8' &&
1753 osinfo.release[1] == '.') {
1755 * 10.4 (Darwin 8.x). s/en/wlt/
1757 if (strncmp(p->opt.device, "en", 2) != 0) {
1759 * Not an enN device; check
1760 * whether the device even exists.
1762 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1763 if (sockfd != -1) {
1764 strlcpy(ifrname,
1765 p->opt.device, ifnamsiz);
1766 if (ioctl(sockfd, SIOCGIFFLAGS,
1767 (char *)&ifr) < 0) {
1769 * We assume this
1770 * failed because
1771 * the underlying
1772 * device doesn't
1773 * exist.
1775 status = PCAP_ERROR_NO_SUCH_DEVICE;
1776 pcap_snprintf(p->errbuf,
1777 PCAP_ERRBUF_SIZE,
1778 "SIOCGIFFLAGS failed: %s",
1779 pcap_strerror(errno));
1780 } else
1781 status = PCAP_ERROR_RFMON_NOTSUP;
1782 close(sockfd);
1783 } else {
1785 * We can't find out whether
1786 * the device exists, so just
1787 * report "no such device".
1789 status = PCAP_ERROR_NO_SUCH_DEVICE;
1790 pcap_snprintf(p->errbuf,
1791 PCAP_ERRBUF_SIZE,
1792 "socket() failed: %s",
1793 pcap_strerror(errno));
1795 goto bad;
1797 wltdev = malloc(strlen(p->opt.device) + 2);
1798 if (wltdev == NULL) {
1799 (void)pcap_snprintf(p->errbuf,
1800 PCAP_ERRBUF_SIZE, "malloc: %s",
1801 pcap_strerror(errno));
1802 status = PCAP_ERROR;
1803 goto bad;
1805 strcpy(wltdev, "wlt");
1806 strcat(wltdev, p->opt.device + 2);
1807 free(p->opt.device);
1808 p->opt.device = wltdev;
1811 * Everything else is 10.5 or later; for those,
1812 * we just open the enN device, and set the DLT.
1816 #endif /* __APPLE__ */
1819 * If this is FreeBSD, and the device name begins with "usbus",
1820 * try to create the interface if it's not available.
1822 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1823 if (strncmp(p->opt.device, usbus_prefix, USBUS_PREFIX_LEN) == 0) {
1825 * Do we already have an interface with that name?
1827 if (if_nametoindex(p->opt.device) == 0) {
1829 * No. We need to create it, and, if we
1830 * succeed, remember that we should destroy
1831 * it when the pcap_t is closed.
1833 int s;
1836 * Open a socket to use for ioctls to
1837 * create the interface.
1839 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1840 if (s < 0) {
1841 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1842 "Can't open socket: %s",
1843 pcap_strerror(errno));
1844 status = PCAP_ERROR;
1845 goto bad;
1849 * If we haven't already done so, arrange to have
1850 * "pcap_close_all()" called when we exit.
1852 if (!pcap_do_addexit(p)) {
1854 * "atexit()" failed; don't create the
1855 * interface, just give up.
1857 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1858 "atexit failed");
1859 close(s);
1860 status = PCAP_ERROR;
1861 goto bad;
1865 * Create the interface.
1867 strlcpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
1868 if (ioctl(s, SIOCIFCREATE2, &ifr) < 0) {
1869 if (errno == EINVAL) {
1870 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1871 "Invalid USB bus interface %s",
1872 p->opt.device);
1873 } else {
1874 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1875 "Can't create interface for %s: %s",
1876 p->opt.device, pcap_strerror(errno));
1878 close(s);
1879 status = PCAP_ERROR;
1880 goto bad;
1884 * Make sure we clean this up when we close.
1886 pb->must_do_on_close |= MUST_DESTROY_USBUS;
1889 * Add this to the list of pcaps to close when we exit.
1891 pcap_add_to_pcaps_to_close(p);
1894 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1896 #ifdef HAVE_ZEROCOPY_BPF
1898 * If the BPF extension to set buffer mode is present, try setting
1899 * the mode to zero-copy. If that fails, use regular buffering. If
1900 * it succeeds but other setup fails, return an error to the user.
1902 bufmode = BPF_BUFMODE_ZBUF;
1903 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1905 * We have zerocopy BPF; use it.
1907 pb->zerocopy = 1;
1910 * How to pick a buffer size: first, query the maximum buffer
1911 * size supported by zero-copy. This also lets us quickly
1912 * determine whether the kernel generally supports zero-copy.
1913 * Then, if a buffer size was specified, use that, otherwise
1914 * query the default buffer size, which reflects kernel
1915 * policy for a desired default. Round to the nearest page
1916 * size.
1918 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1919 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1920 pcap_strerror(errno));
1921 status = PCAP_ERROR;
1922 goto bad;
1925 if (p->opt.buffer_size != 0) {
1927 * A buffer size was explicitly specified; use it.
1929 v = p->opt.buffer_size;
1930 } else {
1931 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1932 v < DEFAULT_BUFSIZE)
1933 v = DEFAULT_BUFSIZE;
1935 #ifndef roundup
1936 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
1937 #endif
1938 pb->zbufsize = roundup(v, getpagesize());
1939 if (pb->zbufsize > zbufmax)
1940 pb->zbufsize = zbufmax;
1941 pb->zbuf1 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1942 MAP_ANON, -1, 0);
1943 pb->zbuf2 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1944 MAP_ANON, -1, 0);
1945 if (pb->zbuf1 == MAP_FAILED || pb->zbuf2 == MAP_FAILED) {
1946 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1947 pcap_strerror(errno));
1948 status = PCAP_ERROR;
1949 goto bad;
1951 memset(&bz, 0, sizeof(bz)); /* bzero() deprecated, replaced with memset() */
1952 bz.bz_bufa = pb->zbuf1;
1953 bz.bz_bufb = pb->zbuf2;
1954 bz.bz_buflen = pb->zbufsize;
1955 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1956 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1957 pcap_strerror(errno));
1958 status = PCAP_ERROR;
1959 goto bad;
1961 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
1962 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1963 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1964 p->opt.device, pcap_strerror(errno));
1965 status = PCAP_ERROR;
1966 goto bad;
1968 v = pb->zbufsize - sizeof(struct bpf_zbuf_header);
1969 } else
1970 #endif
1973 * We don't have zerocopy BPF.
1974 * Set the buffer size.
1976 if (p->opt.buffer_size != 0) {
1978 * A buffer size was explicitly specified; use it.
1980 if (ioctl(fd, BIOCSBLEN,
1981 (caddr_t)&p->opt.buffer_size) < 0) {
1982 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1983 "BIOCSBLEN: %s: %s", p->opt.device,
1984 pcap_strerror(errno));
1985 status = PCAP_ERROR;
1986 goto bad;
1990 * Now bind to the device.
1992 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
1993 #ifdef BIOCSETLIF
1994 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
1995 #else
1996 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
1997 #endif
1999 status = check_setif_failure(p, errno);
2000 goto bad;
2002 } else {
2004 * No buffer size was explicitly specified.
2006 * Try finding a good size for the buffer;
2007 * DEFAULT_BUFSIZE may be too big, so keep
2008 * cutting it in half until we find a size
2009 * that works, or run out of sizes to try.
2010 * If the default is larger, don't make it smaller.
2012 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
2013 v < DEFAULT_BUFSIZE)
2014 v = DEFAULT_BUFSIZE;
2015 for ( ; v != 0; v >>= 1) {
2017 * Ignore the return value - this is because the
2018 * call fails on BPF systems that don't have
2019 * kernel malloc. And if the call fails, it's
2020 * no big deal, we just continue to use the
2021 * standard buffer size.
2023 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
2025 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
2026 #ifdef BIOCSETLIF
2027 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
2028 #else
2029 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
2030 #endif
2031 break; /* that size worked; we're done */
2033 if (errno != ENOBUFS) {
2034 status = check_setif_failure(p, errno);
2035 goto bad;
2039 if (v == 0) {
2040 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2041 "BIOCSBLEN: %s: No buffer size worked",
2042 p->opt.device);
2043 status = PCAP_ERROR;
2044 goto bad;
2049 /* Get the data link layer type. */
2050 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
2051 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
2052 pcap_strerror(errno));
2053 status = PCAP_ERROR;
2054 goto bad;
2057 #ifdef _AIX
2059 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
2061 switch (v) {
2063 case IFT_ETHER:
2064 case IFT_ISO88023:
2065 v = DLT_EN10MB;
2066 break;
2068 case IFT_FDDI:
2069 v = DLT_FDDI;
2070 break;
2072 case IFT_ISO88025:
2073 v = DLT_IEEE802;
2074 break;
2076 case IFT_LOOP:
2077 v = DLT_NULL;
2078 break;
2080 default:
2082 * We don't know what to map this to yet.
2084 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
2086 status = PCAP_ERROR;
2087 goto bad;
2089 #endif
2090 #if _BSDI_VERSION - 0 >= 199510
2091 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
2092 switch (v) {
2094 case DLT_SLIP:
2095 v = DLT_SLIP_BSDOS;
2096 break;
2098 case DLT_PPP:
2099 v = DLT_PPP_BSDOS;
2100 break;
2102 case 11: /*DLT_FR*/
2103 v = DLT_FRELAY;
2104 break;
2106 case 12: /*DLT_C_HDLC*/
2107 v = DLT_CHDLC;
2108 break;
2110 #endif
2112 #ifdef BIOCGDLTLIST
2114 * We know the default link type -- now determine all the DLTs
2115 * this interface supports. If this fails with EINVAL, it's
2116 * not fatal; we just don't get to use the feature later.
2118 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
2119 status = PCAP_ERROR;
2120 goto bad;
2122 p->dlt_count = bdl.bfl_len;
2123 p->dlt_list = bdl.bfl_list;
2125 #ifdef __APPLE__
2127 * Monitor mode fun, continued.
2129 * For 10.5 and, we're assuming, later releases, as noted above,
2130 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
2131 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
2132 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
2133 * monitor mode on.
2135 * Therefore, if the user asked for monitor mode, we filter out
2136 * the DLT_EN10MB value, as you can't get that in monitor mode,
2137 * and, if the user didn't ask for monitor mode, we filter out
2138 * the 802.11 DLT_ values, because selecting those will turn
2139 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
2140 * radio DLT_ value is offered, we try to select that, otherwise
2141 * we try to select DLT_IEEE802_11.
2143 if (have_osinfo) {
2144 if (isdigit((unsigned)osinfo.release[0]) &&
2145 (osinfo.release[0] == '9' ||
2146 isdigit((unsigned)osinfo.release[1]))) {
2148 * 10.5 (Darwin 9.x), or later.
2150 new_dlt = find_802_11(&bdl);
2151 if (new_dlt != -1) {
2153 * We have at least one 802.11 DLT_ value,
2154 * so this is an 802.11 interface.
2155 * new_dlt is the best of the 802.11
2156 * DLT_ values in the list.
2158 if (p->opt.rfmon) {
2160 * Our caller wants monitor mode.
2161 * Purge DLT_EN10MB from the list
2162 * of link-layer types, as selecting
2163 * it will keep monitor mode off.
2165 remove_en(p);
2168 * If the new mode we want isn't
2169 * the default mode, attempt to
2170 * select the new mode.
2172 if ((u_int)new_dlt != v) {
2173 if (ioctl(p->fd, BIOCSDLT,
2174 &new_dlt) != -1) {
2176 * We succeeded;
2177 * make this the
2178 * new DLT_ value.
2180 v = new_dlt;
2183 } else {
2185 * Our caller doesn't want
2186 * monitor mode. Unless this
2187 * is being done by pcap_open_live(),
2188 * purge the 802.11 link-layer types
2189 * from the list, as selecting
2190 * one of them will turn monitor
2191 * mode on.
2193 if (!p->oldstyle)
2194 remove_802_11(p);
2196 } else {
2197 if (p->opt.rfmon) {
2199 * The caller requested monitor
2200 * mode, but we have no 802.11
2201 * link-layer types, so they
2202 * can't have it.
2204 status = PCAP_ERROR_RFMON_NOTSUP;
2205 goto bad;
2210 #elif defined(HAVE_BSD_IEEE80211)
2212 * *BSD with the new 802.11 ioctls.
2213 * Do we want monitor mode?
2215 if (p->opt.rfmon) {
2217 * Try to put the interface into monitor mode.
2219 retv = monitor_mode(p, 1);
2220 if (retv != 0) {
2222 * We failed.
2224 status = retv;
2225 goto bad;
2229 * We're in monitor mode.
2230 * Try to find the best 802.11 DLT_ value and, if we
2231 * succeed, try to switch to that mode if we're not
2232 * already in that mode.
2234 new_dlt = find_802_11(&bdl);
2235 if (new_dlt != -1) {
2237 * We have at least one 802.11 DLT_ value.
2238 * new_dlt is the best of the 802.11
2239 * DLT_ values in the list.
2241 * If the new mode we want isn't the default mode,
2242 * attempt to select the new mode.
2244 if ((u_int)new_dlt != v) {
2245 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
2247 * We succeeded; make this the
2248 * new DLT_ value.
2250 v = new_dlt;
2255 #endif /* various platforms */
2256 #endif /* BIOCGDLTLIST */
2259 * If this is an Ethernet device, and we don't have a DLT_ list,
2260 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
2261 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2262 * do, but there's not much we can do about that without finding
2263 * some other way of determining whether it's an Ethernet or 802.11
2264 * device.)
2266 if (v == DLT_EN10MB && p->dlt_count == 0) {
2267 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2269 * If that fails, just leave the list empty.
2271 if (p->dlt_list != NULL) {
2272 p->dlt_list[0] = DLT_EN10MB;
2273 p->dlt_list[1] = DLT_DOCSIS;
2274 p->dlt_count = 2;
2277 #ifdef PCAP_FDDIPAD
2278 if (v == DLT_FDDI)
2279 p->fddipad = PCAP_FDDIPAD;
2280 else
2281 #endif
2282 p->fddipad = 0;
2283 p->linktype = v;
2285 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2287 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2288 * the link-layer source address isn't forcibly overwritten.
2289 * (Should we ignore errors? Should we do this only if
2290 * we're open for writing?)
2292 * XXX - I seem to remember some packet-sending bug in some
2293 * BSDs - check CVS log for "bpf.c"?
2295 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2296 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2297 "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
2298 status = PCAP_ERROR;
2299 goto bad;
2301 #endif
2302 /* set timeout */
2303 #ifdef HAVE_ZEROCOPY_BPF
2305 * In zero-copy mode, we just use the timeout in select().
2306 * XXX - what if we're in non-blocking mode and the *application*
2307 * is using select() or poll() or kqueues or....?
2309 if (p->opt.timeout && !pb->zerocopy) {
2310 #else
2311 if (p->opt.timeout) {
2312 #endif
2314 * XXX - is this seconds/nanoseconds in AIX?
2315 * (Treating it as such doesn't fix the timeout
2316 * problem described below.)
2318 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2319 * 64-bit userland - it takes, as an argument, a
2320 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2321 * and tv_usec, rather than a "struct timeval".
2323 * If this platform defines "struct BPF_TIMEVAL",
2324 * we check whether the structure size in BIOCSRTIMEOUT
2325 * is that of a "struct timeval" and, if not, we use
2326 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2327 * (That way, if the bug is fixed in a future release,
2328 * we will still do the right thing.)
2330 struct timeval to;
2331 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2332 struct BPF_TIMEVAL bpf_to;
2334 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2335 bpf_to.tv_sec = p->opt.timeout / 1000;
2336 bpf_to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2337 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2338 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2339 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2340 status = PCAP_ERROR;
2341 goto bad;
2343 } else {
2344 #endif
2345 to.tv_sec = p->opt.timeout / 1000;
2346 to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2347 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2348 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2349 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2350 status = PCAP_ERROR;
2351 goto bad;
2353 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2355 #endif
2358 #ifdef BIOCIMMEDIATE
2360 * Darren Reed notes that
2362 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2363 * timeout appears to be ignored and it waits until the buffer
2364 * is filled before returning. The result of not having it
2365 * set is almost worse than useless if your BPF filter
2366 * is reducing things to only a few packets (i.e. one every
2367 * second or so).
2369 * so we always turn BIOCIMMEDIATE mode on if this is AIX.
2371 * For other platforms, we don't turn immediate mode on by default,
2372 * as that would mean we get woken up for every packet, which
2373 * probably isn't what you want for a packet sniffer.
2375 * We set immediate mode if the caller requested it by calling
2376 * pcap_set_immediate() before calling pcap_activate().
2378 #ifndef _AIX
2379 if (p->opt.immediate) {
2380 #endif /* _AIX */
2381 v = 1;
2382 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2383 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2384 "BIOCIMMEDIATE: %s", pcap_strerror(errno));
2385 status = PCAP_ERROR;
2386 goto bad;
2388 #ifndef _AIX
2390 #endif /* _AIX */
2391 #else /* BIOCIMMEDIATE */
2392 if (p->opt.immediate) {
2394 * We don't support immediate mode. Fail.
2396 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Immediate mode not supported");
2397 status = PCAP_ERROR;
2398 goto bad;
2400 #endif /* BIOCIMMEDIATE */
2402 if (p->opt.promisc) {
2403 /* set promiscuous mode, just warn if it fails */
2404 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2405 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
2406 pcap_strerror(errno));
2407 status = PCAP_WARNING_PROMISC_NOTSUP;
2411 #ifdef BIOCSTSTAMP
2412 v = BPF_T_BINTIME;
2413 if (ioctl(p->fd, BIOCSTSTAMP, &v) < 0) {
2414 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSTSTAMP: %s",
2415 pcap_strerror(errno));
2416 status = PCAP_ERROR;
2417 goto bad;
2419 #endif /* BIOCSTSTAMP */
2421 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2422 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
2423 pcap_strerror(errno));
2424 status = PCAP_ERROR;
2425 goto bad;
2427 p->bufsize = v;
2428 #ifdef HAVE_ZEROCOPY_BPF
2429 if (!pb->zerocopy) {
2430 #endif
2431 p->buffer = malloc(p->bufsize);
2432 if (p->buffer == NULL) {
2433 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2434 pcap_strerror(errno));
2435 status = PCAP_ERROR;
2436 goto bad;
2438 #ifdef _AIX
2439 /* For some strange reason this seems to prevent the EFAULT
2440 * problems we have experienced from AIX BPF. */
2441 memset(p->buffer, 0x0, p->bufsize);
2442 #endif
2443 #ifdef HAVE_ZEROCOPY_BPF
2445 #endif
2448 * If there's no filter program installed, there's
2449 * no indication to the kernel of what the snapshot
2450 * length should be, so no snapshotting is done.
2452 * Therefore, when we open the device, we install
2453 * an "accept everything" filter with the specified
2454 * snapshot length.
2456 total_insn.code = (u_short)(BPF_RET | BPF_K);
2457 total_insn.jt = 0;
2458 total_insn.jf = 0;
2459 total_insn.k = p->snapshot;
2461 total_prog.bf_len = 1;
2462 total_prog.bf_insns = &total_insn;
2463 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2464 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2465 pcap_strerror(errno));
2466 status = PCAP_ERROR;
2467 goto bad;
2471 * On most BPF platforms, either you can do a "select()" or
2472 * "poll()" on a BPF file descriptor and it works correctly,
2473 * or you can do it and it will return "readable" if the
2474 * hold buffer is full but not if the timeout expires *and*
2475 * a non-blocking read will, if the hold buffer is empty
2476 * but the store buffer isn't empty, rotate the buffers
2477 * and return what packets are available.
2479 * In the latter case, the fact that a non-blocking read
2480 * will give you the available packets means you can work
2481 * around the failure of "select()" and "poll()" to wake up
2482 * and return "readable" when the timeout expires by using
2483 * the timeout as the "select()" or "poll()" timeout, putting
2484 * the BPF descriptor into non-blocking mode, and read from
2485 * it regardless of whether "select()" reports it as readable
2486 * or not.
2488 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2489 * won't wake up and return "readable" if the timer expires
2490 * and non-blocking reads return EWOULDBLOCK if the hold
2491 * buffer is empty, even if the store buffer is non-empty.
2493 * This means the workaround in question won't work.
2495 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2496 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2497 * here". On all other BPF platforms, we set it to the FD for
2498 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2499 * read will, if the hold buffer is empty and the store buffer
2500 * isn't empty, rotate the buffers and return what packets are
2501 * there (and in sufficiently recent versions of OpenBSD
2502 * "select()" and "poll()" should work correctly).
2504 * XXX - what about AIX?
2506 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2507 if (have_osinfo) {
2509 * We can check what OS this is.
2511 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2512 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2513 strncmp(osinfo.release, "4.4-", 4) == 0)
2514 p->selectable_fd = -1;
2518 p->read_op = pcap_read_bpf;
2519 p->inject_op = pcap_inject_bpf;
2520 p->setfilter_op = pcap_setfilter_bpf;
2521 p->setdirection_op = pcap_setdirection_bpf;
2522 p->set_datalink_op = pcap_set_datalink_bpf;
2523 p->getnonblock_op = pcap_getnonblock_bpf;
2524 p->setnonblock_op = pcap_setnonblock_bpf;
2525 p->stats_op = pcap_stats_bpf;
2526 p->cleanup_op = pcap_cleanup_bpf;
2528 return (status);
2529 bad:
2530 pcap_cleanup_bpf(p);
2531 return (status);
2535 * Not all interfaces can be bound to by BPF, so try to bind to
2536 * the specified interface; return 0 if we fail with
2537 * PCAP_ERROR_NO_SUCH_DEVICE (which means we got an ENXIO when we tried
2538 * to bind, which means this interface isn't in the list of interfaces
2539 * attached to BPF) and 1 otherwise.
2541 static int
2542 check_bpf_bindable(const char *name)
2544 int fd;
2545 char errbuf[PCAP_ERRBUF_SIZE];
2547 fd = bpf_open_and_bind(name, errbuf);
2548 if (fd < 0) {
2550 * Error - was it PCAP_ERROR_NO_SUCH_DEVICE?
2552 if (fd == PCAP_ERROR_NO_SUCH_DEVICE) {
2554 * Yes, so we can't bind to this because it's
2555 * not something supported by BPF.
2557 return (0);
2560 * No, so we don't know whether it's supported or not;
2561 * say it is, so that the user can at least try to
2562 * open it and report the error (which is probably
2563 * "you don't have permission to open BPF devices";
2564 * reporting those interfaces means users will ask
2565 * "why am I getting a permissions error when I try
2566 * to capture" rather than "why am I not seeing any
2567 * interfaces", making the underlying problem clearer).
2569 return (1);
2573 * Success.
2575 close(fd);
2576 return (1);
2579 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
2580 static int
2581 finddevs_usb(pcap_if_t **alldevsp, char *errbuf)
2583 DIR *usbdir;
2584 struct dirent *usbitem;
2585 size_t name_max;
2586 char *name;
2589 * We might have USB sniffing support, so try looking for USB
2590 * interfaces.
2592 * We want to report a usbusN device for each USB bus, but
2593 * usbusN interfaces might, or might not, exist for them -
2594 * we create one if there isn't already one.
2596 * So, instead, we look in /dev/usb for all buses and create
2597 * a "usbusN" device for each one.
2599 usbdir = opendir("/dev/usb");
2600 if (usbdir == NULL) {
2602 * Just punt.
2604 return (0);
2608 * Leave enough room for a 32-bit (10-digit) bus number.
2609 * Yes, that's overkill, but we won't be using
2610 * the buffer very long.
2612 name_max = USBUS_PREFIX_LEN + 10 + 1;
2613 name = malloc(name_max);
2614 if (name == NULL) {
2615 closedir(usbdir);
2616 return (0);
2618 while ((usbitem = readdir(usbdir)) != NULL) {
2619 char *p;
2620 size_t busnumlen;
2621 int err;
2623 if (strcmp(usbitem->d_name, ".") == 0 ||
2624 strcmp(usbitem->d_name, "..") == 0) {
2626 * Ignore these.
2628 continue;
2630 p = strchr(usbitem->d_name, '.');
2631 if (p == NULL)
2632 continue;
2633 busnumlen = p - usbitem->d_name;
2634 memcpy(name, usbus_prefix, USBUS_PREFIX_LEN);
2635 memcpy(name + USBUS_PREFIX_LEN, usbitem->d_name, busnumlen);
2636 *(name + USBUS_PREFIX_LEN + busnumlen) = '\0';
2637 err = pcap_add_if(alldevsp, name, PCAP_IF_UP, NULL, errbuf);
2638 if (err != 0) {
2639 free(name);
2640 closedir(usbdir);
2641 return (err);
2644 free(name);
2645 closedir(usbdir);
2646 return (0);
2648 #endif
2651 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2654 * Get the list of regular interfaces first.
2656 if (pcap_findalldevs_interfaces(alldevsp, errbuf, check_bpf_bindable) == -1)
2657 return (-1); /* failure */
2659 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
2660 if (finddevs_usb(alldevsp, errbuf) == -1)
2661 return (-1);
2662 #endif
2664 return (0);
2667 #ifdef HAVE_BSD_IEEE80211
2668 static int
2669 monitor_mode(pcap_t *p, int set)
2671 struct pcap_bpf *pb = p->priv;
2672 int sock;
2673 struct ifmediareq req;
2674 IFM_ULIST_TYPE *media_list;
2675 int i;
2676 int can_do;
2677 struct ifreq ifr;
2679 sock = socket(AF_INET, SOCK_DGRAM, 0);
2680 if (sock == -1) {
2681 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2682 pcap_strerror(errno));
2683 return (PCAP_ERROR);
2686 memset(&req, 0, sizeof req);
2687 strncpy(req.ifm_name, p->opt.device, sizeof req.ifm_name);
2690 * Find out how many media types we have.
2692 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2694 * Can't get the media types.
2696 switch (errno) {
2698 case ENXIO:
2700 * There's no such device.
2702 close(sock);
2703 return (PCAP_ERROR_NO_SUCH_DEVICE);
2705 case EINVAL:
2707 * Interface doesn't support SIOC{G,S}IFMEDIA.
2709 close(sock);
2710 return (PCAP_ERROR_RFMON_NOTSUP);
2712 default:
2713 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2714 "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
2715 close(sock);
2716 return (PCAP_ERROR);
2719 if (req.ifm_count == 0) {
2721 * No media types.
2723 close(sock);
2724 return (PCAP_ERROR_RFMON_NOTSUP);
2728 * Allocate a buffer to hold all the media types, and
2729 * get the media types.
2731 media_list = malloc(req.ifm_count * sizeof(*media_list));
2732 if (media_list == NULL) {
2733 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2734 pcap_strerror(errno));
2735 close(sock);
2736 return (PCAP_ERROR);
2738 req.ifm_ulist = media_list;
2739 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2740 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2741 pcap_strerror(errno));
2742 free(media_list);
2743 close(sock);
2744 return (PCAP_ERROR);
2748 * Look for an 802.11 "automatic" media type.
2749 * We assume that all 802.11 adapters have that media type,
2750 * and that it will carry the monitor mode supported flag.
2752 can_do = 0;
2753 for (i = 0; i < req.ifm_count; i++) {
2754 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2755 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2756 /* OK, does it do monitor mode? */
2757 if (media_list[i] & IFM_IEEE80211_MONITOR) {
2758 can_do = 1;
2759 break;
2763 free(media_list);
2764 if (!can_do) {
2766 * This adapter doesn't support monitor mode.
2768 close(sock);
2769 return (PCAP_ERROR_RFMON_NOTSUP);
2772 if (set) {
2774 * Don't just check whether we can enable monitor mode,
2775 * do so, if it's not already enabled.
2777 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2779 * Monitor mode isn't currently on, so turn it on,
2780 * and remember that we should turn it off when the
2781 * pcap_t is closed.
2785 * If we haven't already done so, arrange to have
2786 * "pcap_close_all()" called when we exit.
2788 if (!pcap_do_addexit(p)) {
2790 * "atexit()" failed; don't put the interface
2791 * in monitor mode, just give up.
2793 close(sock);
2794 return (PCAP_ERROR);
2796 memset(&ifr, 0, sizeof(ifr));
2797 (void)strncpy(ifr.ifr_name, p->opt.device,
2798 sizeof(ifr.ifr_name));
2799 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2800 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2801 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2802 "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2803 close(sock);
2804 return (PCAP_ERROR);
2807 pb->must_do_on_close |= MUST_CLEAR_RFMON;
2810 * Add this to the list of pcaps to close when we exit.
2812 pcap_add_to_pcaps_to_close(p);
2815 return (0);
2817 #endif /* HAVE_BSD_IEEE80211 */
2819 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2821 * Check whether we have any 802.11 link-layer types; return the best
2822 * of the 802.11 link-layer types if we find one, and return -1
2823 * otherwise.
2825 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2826 * best 802.11 link-layer type; any of the other 802.11-plus-radio
2827 * headers are second-best; 802.11 with no radio information is
2828 * the least good.
2830 static int
2831 find_802_11(struct bpf_dltlist *bdlp)
2833 int new_dlt;
2834 u_int i;
2837 * Scan the list of DLT_ values, looking for 802.11 values,
2838 * and, if we find any, choose the best of them.
2840 new_dlt = -1;
2841 for (i = 0; i < bdlp->bfl_len; i++) {
2842 switch (bdlp->bfl_list[i]) {
2844 case DLT_IEEE802_11:
2846 * 802.11, but no radio.
2848 * Offer this, and select it as the new mode
2849 * unless we've already found an 802.11
2850 * header with radio information.
2852 if (new_dlt == -1)
2853 new_dlt = bdlp->bfl_list[i];
2854 break;
2856 case DLT_PRISM_HEADER:
2857 case DLT_AIRONET_HEADER:
2858 case DLT_IEEE802_11_RADIO_AVS:
2860 * 802.11 with radio, but not radiotap.
2862 * Offer this, and select it as the new mode
2863 * unless we've already found the radiotap DLT_.
2865 if (new_dlt != DLT_IEEE802_11_RADIO)
2866 new_dlt = bdlp->bfl_list[i];
2867 break;
2869 case DLT_IEEE802_11_RADIO:
2871 * 802.11 with radiotap.
2873 * Offer this, and select it as the new mode.
2875 new_dlt = bdlp->bfl_list[i];
2876 break;
2878 default:
2880 * Not 802.11.
2882 break;
2886 return (new_dlt);
2888 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2890 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
2892 * Remove DLT_EN10MB from the list of DLT_ values, as we're in monitor mode,
2893 * and DLT_EN10MB isn't supported in monitor mode.
2895 static void
2896 remove_en(pcap_t *p)
2898 int i, j;
2901 * Scan the list of DLT_ values and discard DLT_EN10MB.
2903 j = 0;
2904 for (i = 0; i < p->dlt_count; i++) {
2905 switch (p->dlt_list[i]) {
2907 case DLT_EN10MB:
2909 * Don't offer this one.
2911 continue;
2913 default:
2915 * Just copy this mode over.
2917 break;
2921 * Copy this DLT_ value to its new position.
2923 p->dlt_list[j] = p->dlt_list[i];
2924 j++;
2928 * Set the DLT_ count to the number of entries we copied.
2930 p->dlt_count = j;
2934 * Remove 802.11 link-layer types from the list of DLT_ values, as
2935 * we're not in monitor mode, and those DLT_ values will switch us
2936 * to monitor mode.
2938 static void
2939 remove_802_11(pcap_t *p)
2941 int i, j;
2944 * Scan the list of DLT_ values and discard 802.11 values.
2946 j = 0;
2947 for (i = 0; i < p->dlt_count; i++) {
2948 switch (p->dlt_list[i]) {
2950 case DLT_IEEE802_11:
2951 case DLT_PRISM_HEADER:
2952 case DLT_AIRONET_HEADER:
2953 case DLT_IEEE802_11_RADIO:
2954 case DLT_IEEE802_11_RADIO_AVS:
2956 * 802.11. Don't offer this one.
2958 continue;
2960 default:
2962 * Just copy this mode over.
2964 break;
2968 * Copy this DLT_ value to its new position.
2970 p->dlt_list[j] = p->dlt_list[i];
2971 j++;
2975 * Set the DLT_ count to the number of entries we copied.
2977 p->dlt_count = j;
2979 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
2981 static int
2982 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
2984 struct pcap_bpf *pb = p->priv;
2987 * Free any user-mode filter we might happen to have installed.
2989 pcap_freecode(&p->fcode);
2992 * Try to install the kernel filter.
2994 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
2996 * It worked.
2998 pb->filtering_in_kernel = 1; /* filtering in the kernel */
3001 * Discard any previously-received packets, as they might
3002 * have passed whatever filter was formerly in effect, but
3003 * might not pass this filter (BIOCSETF discards packets
3004 * buffered in the kernel, so you can lose packets in any
3005 * case).
3007 p->cc = 0;
3008 return (0);
3012 * We failed.
3014 * If it failed with EINVAL, that's probably because the program
3015 * is invalid or too big. Validate it ourselves; if we like it
3016 * (we currently allow backward branches, to support protochain),
3017 * run it in userland. (There's no notion of "too big" for
3018 * userland.)
3020 * Otherwise, just give up.
3021 * XXX - if the copy of the program into the kernel failed,
3022 * we will get EINVAL rather than, say, EFAULT on at least
3023 * some kernels.
3025 if (errno != EINVAL) {
3026 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
3027 pcap_strerror(errno));
3028 return (-1);
3032 * install_bpf_program() validates the program.
3034 * XXX - what if we already have a filter in the kernel?
3036 if (install_bpf_program(p, fp) < 0)
3037 return (-1);
3038 pb->filtering_in_kernel = 0; /* filtering in userland */
3039 return (0);
3043 * Set direction flag: Which packets do we accept on a forwarding
3044 * single device? IN, OUT or both?
3046 static int
3047 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3049 #if defined(BIOCSDIRECTION)
3050 u_int direction;
3052 direction = (d == PCAP_D_IN) ? BPF_D_IN :
3053 ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
3054 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
3055 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3056 "Cannot set direction to %s: %s",
3057 (d == PCAP_D_IN) ? "PCAP_D_IN" :
3058 ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
3059 strerror(errno));
3060 return (-1);
3062 return (0);
3063 #elif defined(BIOCSSEESENT)
3064 u_int seesent;
3067 * We don't support PCAP_D_OUT.
3069 if (d == PCAP_D_OUT) {
3070 pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3071 "Setting direction to PCAP_D_OUT is not supported on BPF");
3072 return -1;
3075 seesent = (d == PCAP_D_INOUT);
3076 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
3077 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3078 "Cannot set direction to %s: %s",
3079 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
3080 strerror(errno));
3081 return (-1);
3083 return (0);
3084 #else
3085 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3086 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
3087 return (-1);
3088 #endif
3091 static int
3092 pcap_set_datalink_bpf(pcap_t *p, int dlt)
3094 #ifdef BIOCSDLT
3095 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
3096 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3097 "Cannot set DLT %d: %s", dlt, strerror(errno));
3098 return (-1);
3100 #endif
3101 return (0);