Remove building with NOCRYPTO option
[minix.git] / external / bsd / libpcap / dist / pcap-bpf.c
blob94db4d8829063d7e8b999c9bdb55512d2cae4b4c
1 /* $NetBSD: pcap-bpf.c,v 1.6 2015/03/31 21:39:42 christos Exp $ */
3 /*
4 * Copyright (c) 1993, 1994, 1995, 1996, 1998
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that: (1) source code distributions
9 * retain the above copyright notice and this paragraph in its entirety, (2)
10 * distributions including binary code include the above copyright notice and
11 * this paragraph in its entirety in the documentation or other materials
12 * provided with the distribution, and (3) all advertising materials mentioning
13 * features or use of this software display the following acknowledgement:
14 * ``This product includes software developed by the University of California,
15 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16 * the University nor the names of its contributors may be used to endorse
17 * or promote products derived from this software without specific prior
18 * written permission.
19 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
24 #include <sys/cdefs.h>
25 __RCSID("$NetBSD: pcap-bpf.c,v 1.6 2015/03/31 21:39:42 christos Exp $");
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
31 #include <sys/param.h> /* optionally get BSD define */
32 #ifdef HAVE_ZEROCOPY_BPF
33 #include <sys/mman.h>
34 #endif
35 #include <sys/socket.h>
36 #include <time.h>
38 * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
40 * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
41 * at least on *BSD and Mac OS X, it also defines various SIOC ioctls -
42 * we could include <sys/sockio.h>, but if we're already including
43 * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
44 * there's not much point in doing so.
46 * If we have <sys/ioccom.h>, we include it as well, to handle systems
47 * such as Solaris which don't arrange to include <sys/ioccom.h> if you
48 * include <sys/ioctl.h>
50 #include <sys/ioctl.h>
51 #ifdef HAVE_SYS_IOCCOM_H
52 #include <sys/ioccom.h>
53 #endif
54 #include <sys/utsname.h>
55 #ifdef __NetBSD__
56 #include <paths.h>
57 #endif
59 #ifdef HAVE_ZEROCOPY_BPF
60 #include <machine/atomic.h>
61 #endif
63 #include <net/if.h>
65 #ifdef _AIX
68 * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
69 * native OS version, as we need "struct bpf_config" from it.
71 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
73 #include <sys/types.h>
76 * Prevent bpf.h from redefining the DLT_ values to their
77 * IFT_ values, as we're going to return the standard libpcap
78 * values, not IBM's non-standard IFT_ values.
80 #undef _AIX
81 #include <net/bpf.h>
82 #define _AIX
84 #include <net/if_types.h> /* for IFT_ values */
85 #include <sys/sysconfig.h>
86 #include <sys/device.h>
87 #include <sys/cfgodm.h>
88 #include <cf.h>
90 #ifdef __64BIT__
91 #define domakedev makedev64
92 #define getmajor major64
93 #define bpf_hdr bpf_hdr32
94 #else /* __64BIT__ */
95 #define domakedev makedev
96 #define getmajor major
97 #endif /* __64BIT__ */
99 #define BPF_NAME "bpf"
100 #define BPF_MINORS 4
101 #define DRIVER_PATH "/usr/lib/drivers"
102 #define BPF_NODE "/dev/bpf"
103 static int bpfloadedflag = 0;
104 static int odmlockid = 0;
106 static int bpf_load(char *errbuf);
108 #else /* _AIX */
110 #include <net/bpf.h>
112 #endif /* _AIX */
114 #include <ctype.h>
115 #include <fcntl.h>
116 #include <errno.h>
117 #include <netdb.h>
118 #include <stdio.h>
119 #include <stdlib.h>
120 #include <string.h>
121 #include <unistd.h>
123 #ifdef HAVE_NET_IF_MEDIA_H
124 # include <net/if_media.h>
125 #endif
127 #include "pcap-int.h"
129 #ifdef HAVE_OS_PROTO_H
130 #include "os-proto.h"
131 #endif
134 * Later versions of NetBSD stick padding in front of FDDI frames
135 * to align the IP header on a 4-byte boundary.
137 #if defined(__NetBSD__) && __NetBSD_Version__ > 106000000
138 #define PCAP_FDDIPAD 3
139 #endif
142 * Private data for capturing on BPF devices.
144 struct pcap_bpf {
145 #ifdef PCAP_FDDIPAD
146 int fddipad;
147 #endif
149 #ifdef HAVE_ZEROCOPY_BPF
151 * Zero-copy read buffer -- for zero-copy BPF. 'buffer' above will
152 * alternative between these two actual mmap'd buffers as required.
153 * As there is a header on the front size of the mmap'd buffer, only
154 * some of the buffer is exposed to libpcap as a whole via bufsize;
155 * zbufsize is the true size. zbuffer tracks the current zbuf
156 * assocated with buffer so that it can be used to decide which the
157 * next buffer to read will be.
159 u_char *zbuf1, *zbuf2, *zbuffer;
160 u_int zbufsize;
161 u_int zerocopy;
162 u_int interrupted;
163 struct timespec firstsel;
165 * If there's currently a buffer being actively processed, then it is
166 * referenced here; 'buffer' is also pointed at it, but offset by the
167 * size of the header.
169 struct bpf_zbuf_header *bzh;
170 int nonblock; /* true if in nonblocking mode */
171 #endif /* HAVE_ZEROCOPY_BPF */
173 char *device; /* device name */
174 int filtering_in_kernel; /* using kernel filter */
175 int must_do_on_close; /* stuff we must do when we close */
179 * Stuff to do when we close.
181 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
183 #ifdef BIOCGDLTLIST
184 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
185 #define HAVE_BSD_IEEE80211
186 # endif
188 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
189 static int find_802_11(struct bpf_dltlist *);
191 # ifdef HAVE_BSD_IEEE80211
192 static int monitor_mode(pcap_t *, int);
193 # endif
195 # if defined(__APPLE__)
196 static void remove_en(pcap_t *);
197 static void remove_802_11(pcap_t *);
198 # endif
200 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
202 #endif /* BIOCGDLTLIST */
204 #if defined(sun) && defined(LIFNAMSIZ) && defined(lifr_zoneid)
205 #include <zone.h>
206 #endif
209 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
210 * don't get DLT_DOCSIS defined.
212 #ifndef DLT_DOCSIS
213 #define DLT_DOCSIS 143
214 #endif
217 * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
218 * defined, even though some of them are used by various Airport drivers.
220 #ifndef DLT_PRISM_HEADER
221 #define DLT_PRISM_HEADER 119
222 #endif
223 #ifndef DLT_AIRONET_HEADER
224 #define DLT_AIRONET_HEADER 120
225 #endif
226 #ifndef DLT_IEEE802_11_RADIO
227 #define DLT_IEEE802_11_RADIO 127
228 #endif
229 #ifndef DLT_IEEE802_11_RADIO_AVS
230 #define DLT_IEEE802_11_RADIO_AVS 163
231 #endif
233 static int pcap_can_set_rfmon_bpf(pcap_t *p);
234 static int pcap_activate_bpf(pcap_t *p);
235 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
236 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
237 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
240 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
241 * pb->nonblock so we don't call select(2) if the pcap handle is in non-
242 * blocking mode.
244 static int
245 pcap_getnonblock_bpf(pcap_t *p, char *errbuf)
247 #ifdef HAVE_ZEROCOPY_BPF
248 struct pcap_bpf *pb = p->priv;
250 if (pb->zerocopy)
251 return (pb->nonblock);
252 #endif
253 return (pcap_getnonblock_fd(p, errbuf));
256 static int
257 pcap_setnonblock_bpf(pcap_t *p, int nonblock, char *errbuf)
259 #ifdef HAVE_ZEROCOPY_BPF
260 struct pcap_bpf *pb = p->priv;
262 if (pb->zerocopy) {
263 pb->nonblock = nonblock;
264 return (0);
266 #endif
267 return (pcap_setnonblock_fd(p, nonblock, errbuf));
270 #ifdef HAVE_ZEROCOPY_BPF
272 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
273 * shared memory buffers.
275 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
276 * and set up p->buffer and cc to reflect one if available. Notice that if
277 * there was no prior buffer, we select zbuf1 as this will be the first
278 * buffer filled for a fresh BPF session.
280 static int
281 pcap_next_zbuf_shm(pcap_t *p, int *cc)
283 struct pcap_bpf *pb = p->priv;
284 struct bpf_zbuf_header *bzh;
286 if (pb->zbuffer == pb->zbuf2 || pb->zbuffer == NULL) {
287 bzh = (struct bpf_zbuf_header *)pb->zbuf1;
288 if (bzh->bzh_user_gen !=
289 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
290 pb->bzh = bzh;
291 pb->zbuffer = (u_char *)pb->zbuf1;
292 p->buffer = pb->zbuffer + sizeof(*bzh);
293 *cc = bzh->bzh_kernel_len;
294 return (1);
296 } else if (pb->zbuffer == pb->zbuf1) {
297 bzh = (struct bpf_zbuf_header *)pb->zbuf2;
298 if (bzh->bzh_user_gen !=
299 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
300 pb->bzh = bzh;
301 pb->zbuffer = (u_char *)pb->zbuf2;
302 p->buffer = pb->zbuffer + sizeof(*bzh);
303 *cc = bzh->bzh_kernel_len;
304 return (1);
307 *cc = 0;
308 return (0);
312 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
313 * select() for data or a timeout, and possibly force rotation of the buffer
314 * in the event we time out or are in immediate mode. Invoke the shared
315 * memory check before doing system calls in order to avoid doing avoidable
316 * work.
318 static int
319 pcap_next_zbuf(pcap_t *p, int *cc)
321 struct pcap_bpf *pb = p->priv;
322 struct bpf_zbuf bz;
323 struct timeval tv;
324 struct timespec cur;
325 fd_set r_set;
326 int data, r;
327 int expire, tmout;
329 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
331 * Start out by seeing whether anything is waiting by checking the
332 * next shared memory buffer for data.
334 data = pcap_next_zbuf_shm(p, cc);
335 if (data)
336 return (data);
338 * If a previous sleep was interrupted due to signal delivery, make
339 * sure that the timeout gets adjusted accordingly. This requires
340 * that we analyze when the timeout should be been expired, and
341 * subtract the current time from that. If after this operation,
342 * our timeout is less then or equal to zero, handle it like a
343 * regular timeout.
345 tmout = p->opt.timeout;
346 if (tmout)
347 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
348 if (pb->interrupted && p->opt.timeout) {
349 expire = TSTOMILLI(&pb->firstsel) + p->opt.timeout;
350 tmout = expire - TSTOMILLI(&cur);
351 #undef TSTOMILLI
352 if (tmout <= 0) {
353 pb->interrupted = 0;
354 data = pcap_next_zbuf_shm(p, cc);
355 if (data)
356 return (data);
357 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
358 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
359 "BIOCROTZBUF: %s", strerror(errno));
360 return (PCAP_ERROR);
362 return (pcap_next_zbuf_shm(p, cc));
366 * No data in the buffer, so must use select() to wait for data or
367 * the next timeout. Note that we only call select if the handle
368 * is in blocking mode.
370 if (!pb->nonblock) {
371 FD_ZERO(&r_set);
372 FD_SET(p->fd, &r_set);
373 if (tmout != 0) {
374 tv.tv_sec = tmout / 1000;
375 tv.tv_usec = (tmout * 1000) % 1000000;
377 r = select(p->fd + 1, &r_set, NULL, NULL,
378 p->opt.timeout != 0 ? &tv : NULL);
379 if (r < 0 && errno == EINTR) {
380 if (!pb->interrupted && p->opt.timeout) {
381 pb->interrupted = 1;
382 pb->firstsel = cur;
384 return (0);
385 } else if (r < 0) {
386 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
387 "select: %s", strerror(errno));
388 return (PCAP_ERROR);
391 pb->interrupted = 0;
393 * Check again for data, which may exist now that we've either been
394 * woken up as a result of data or timed out. Try the "there's data"
395 * case first since it doesn't require a system call.
397 data = pcap_next_zbuf_shm(p, cc);
398 if (data)
399 return (data);
401 * Try forcing a buffer rotation to dislodge timed out or immediate
402 * data.
404 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
405 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
406 "BIOCROTZBUF: %s", strerror(errno));
407 return (PCAP_ERROR);
409 return (pcap_next_zbuf_shm(p, cc));
413 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
414 * that we know which buffer to use next time around.
416 static int
417 pcap_ack_zbuf(pcap_t *p)
419 struct pcap_bpf *pb = p->priv;
421 atomic_store_rel_int(&pb->bzh->bzh_user_gen,
422 pb->bzh->bzh_kernel_gen);
423 pb->bzh = NULL;
424 p->buffer = NULL;
425 return (0);
427 #endif /* HAVE_ZEROCOPY_BPF */
429 pcap_t *
430 pcap_create_interface(const char *device, char *ebuf)
432 pcap_t *p;
434 p = pcap_create_common(device, ebuf, sizeof (struct pcap_bpf));
435 if (p == NULL)
436 return (NULL);
438 p->activate_op = pcap_activate_bpf;
439 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
440 return (p);
444 * On success, returns a file descriptor for a BPF device.
445 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
447 static int
448 bpf_open(pcap_t *p)
450 int fd;
451 #ifdef HAVE_CLONING_BPF
452 static const char device[] = "/dev/bpf";
453 #else
454 int n = 0;
455 char device[sizeof "/dev/bpf0000000000"];
456 #endif
458 #ifdef _AIX
460 * Load the bpf driver, if it isn't already loaded,
461 * and create the BPF device entries, if they don't
462 * already exist.
464 if (bpf_load(p->errbuf) == PCAP_ERROR)
465 return (PCAP_ERROR);
466 #endif
468 #ifdef HAVE_CLONING_BPF
469 if ((fd = open(device, O_RDWR)) == -1 &&
470 (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
471 if (errno == EACCES)
472 fd = PCAP_ERROR_PERM_DENIED;
473 else
474 fd = PCAP_ERROR;
475 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
476 "(cannot open device) %s: %s", device, pcap_strerror(errno));
478 #else
480 * Go through all the minors and find one that isn't in use.
482 do {
483 (void)snprintf(device, sizeof(device), "/dev/bpf%d", n++);
485 * Initially try a read/write open (to allow the inject
486 * method to work). If that fails due to permission
487 * issues, fall back to read-only. This allows a
488 * non-root user to be granted specific access to pcap
489 * capabilities via file permissions.
491 * XXX - we should have an API that has a flag that
492 * controls whether to open read-only or read-write,
493 * so that denial of permission to send (or inability
494 * to send, if sending packets isn't supported on
495 * the device in question) can be indicated at open
496 * time.
498 fd = open(device, O_RDWR);
499 if (fd == -1 && errno == EACCES)
500 fd = open(device, O_RDONLY);
501 } while (fd < 0 && errno == EBUSY);
504 * XXX better message for all minors used
506 if (fd < 0) {
507 switch (errno) {
509 case ENOENT:
510 fd = PCAP_ERROR;
511 if (n == 1) {
513 * /dev/bpf0 doesn't exist, which
514 * means we probably have no BPF
515 * devices.
517 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
518 "(there are no BPF devices)");
519 } else {
521 * We got EBUSY on at least one
522 * BPF device, so we have BPF
523 * devices, but all the ones
524 * that exist are busy.
526 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
527 "(all BPF devices are busy)");
529 break;
531 case EACCES:
533 * Got EACCES on the last device we tried,
534 * and EBUSY on all devices before that,
535 * if any.
537 fd = PCAP_ERROR_PERM_DENIED;
538 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
539 "(cannot open BPF device) %s: %s", device,
540 pcap_strerror(errno));
541 break;
543 default:
545 * Some other problem.
547 fd = PCAP_ERROR;
548 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
549 "(cannot open BPF device) %s: %s", device,
550 pcap_strerror(errno));
551 break;
554 #endif
556 return (fd);
559 #ifdef BIOCGDLTLIST
560 static int
561 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
563 memset(bdlp, 0, sizeof(*bdlp));
564 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
565 u_int i;
566 int is_ethernet;
568 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
569 if (bdlp->bfl_list == NULL) {
570 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
571 pcap_strerror(errno));
572 return (PCAP_ERROR);
575 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
576 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
577 "BIOCGDLTLIST: %s", pcap_strerror(errno));
578 free(bdlp->bfl_list);
579 return (PCAP_ERROR);
583 * OK, for real Ethernet devices, add DLT_DOCSIS to the
584 * list, so that an application can let you choose it,
585 * in case you're capturing DOCSIS traffic that a Cisco
586 * Cable Modem Termination System is putting out onto
587 * an Ethernet (it doesn't put an Ethernet header onto
588 * the wire, it puts raw DOCSIS frames out on the wire
589 * inside the low-level Ethernet framing).
591 * A "real Ethernet device" is defined here as a device
592 * that has a link-layer type of DLT_EN10MB and that has
593 * no alternate link-layer types; that's done to exclude
594 * 802.11 interfaces (which might or might not be the
595 * right thing to do, but I suspect it is - Ethernet <->
596 * 802.11 bridges would probably badly mishandle frames
597 * that don't have Ethernet headers).
599 * On Solaris with BPF, Ethernet devices also offer
600 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
601 * treat it as an indication that the device isn't an
602 * Ethernet.
604 if (v == DLT_EN10MB) {
605 is_ethernet = 1;
606 for (i = 0; i < bdlp->bfl_len; i++) {
607 if (bdlp->bfl_list[i] != DLT_EN10MB
608 #ifdef DLT_IPNET
609 && bdlp->bfl_list[i] != DLT_IPNET
610 #endif
612 is_ethernet = 0;
613 break;
616 if (is_ethernet) {
618 * We reserved one more slot at the end of
619 * the list.
621 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
622 bdlp->bfl_len++;
625 } else {
627 * EINVAL just means "we don't support this ioctl on
628 * this device"; don't treat it as an error.
630 if (errno != EINVAL) {
631 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
632 "BIOCGDLTLIST: %s", pcap_strerror(errno));
633 return (PCAP_ERROR);
636 return (0);
638 #endif
640 static int
641 pcap_can_set_rfmon_bpf(pcap_t *p)
643 #if defined(__APPLE__)
644 struct utsname osinfo;
645 struct ifreq ifr;
646 int fd;
647 #ifdef BIOCGDLTLIST
648 struct bpf_dltlist bdl;
649 #endif
652 * The joys of monitor mode on OS X.
654 * Prior to 10.4, it's not supported at all.
656 * In 10.4, if adapter enN supports monitor mode, there's a
657 * wltN adapter corresponding to it; you open it, instead of
658 * enN, to get monitor mode. You get whatever link-layer
659 * headers it supplies.
661 * In 10.5, and, we assume, later releases, if adapter enN
662 * supports monitor mode, it offers, among its selectable
663 * DLT_ values, values that let you get the 802.11 header;
664 * selecting one of those values puts the adapter into monitor
665 * mode (i.e., you can't get 802.11 headers except in monitor
666 * mode, and you can't get Ethernet headers in monitor mode).
668 if (uname(&osinfo) == -1) {
670 * Can't get the OS version; just say "no".
672 return (0);
675 * We assume osinfo.sysname is "Darwin", because
676 * __APPLE__ is defined. We just check the version.
678 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
680 * 10.3 (Darwin 7.x) or earlier.
681 * Monitor mode not supported.
683 return (0);
685 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
687 * 10.4 (Darwin 8.x). s/en/wlt/, and check
688 * whether the device exists.
690 if (strncmp(p->opt.source, "en", 2) != 0) {
692 * Not an enN device; no monitor mode.
694 return (0);
696 fd = socket(AF_INET, SOCK_DGRAM, 0);
697 if (fd == -1) {
698 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
699 "socket: %s", pcap_strerror(errno));
700 return (PCAP_ERROR);
702 strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
703 strlcat(ifr.ifr_name, p->opt.source + 2, sizeof(ifr.ifr_name));
704 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
706 * No such device?
708 close(fd);
709 return (0);
711 close(fd);
712 return (1);
715 #ifdef BIOCGDLTLIST
717 * Everything else is 10.5 or later; for those,
718 * we just open the enN device, and check whether
719 * we have any 802.11 devices.
721 * First, open a BPF device.
723 fd = bpf_open(p);
724 if (fd < 0)
725 return (fd); /* fd is the appropriate error code */
728 * Now bind to the device.
730 (void)strncpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
731 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
732 switch (errno) {
734 case ENXIO:
736 * There's no such device.
738 close(fd);
739 return (PCAP_ERROR_NO_SUCH_DEVICE);
741 case ENETDOWN:
743 * Return a "network down" indication, so that
744 * the application can report that rather than
745 * saying we had a mysterious failure and
746 * suggest that they report a problem to the
747 * libpcap developers.
749 close(fd);
750 return (PCAP_ERROR_IFACE_NOT_UP);
752 default:
753 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
754 "BIOCSETIF: %s: %s",
755 p->opt.source, pcap_strerror(errno));
756 close(fd);
757 return (PCAP_ERROR);
762 * We know the default link type -- now determine all the DLTs
763 * this interface supports. If this fails with EINVAL, it's
764 * not fatal; we just don't get to use the feature later.
765 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
766 * as the default DLT for this adapter.)
768 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
769 close(fd);
770 return (PCAP_ERROR);
772 if (find_802_11(&bdl) != -1) {
774 * We have an 802.11 DLT, so we can set monitor mode.
776 free(bdl.bfl_list);
777 close(fd);
778 return (1);
780 free(bdl.bfl_list);
781 #endif /* BIOCGDLTLIST */
782 return (0);
783 #elif defined(HAVE_BSD_IEEE80211)
784 int ret;
786 ret = monitor_mode(p, 0);
787 if (ret == PCAP_ERROR_RFMON_NOTSUP)
788 return (0); /* not an error, just a "can't do" */
789 if (ret == 0)
790 return (1); /* success */
791 return (ret);
792 #else
793 return (0);
794 #endif
797 static int
798 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
800 struct bpf_stat s;
803 * "ps_recv" counts packets handed to the filter, not packets
804 * that passed the filter. This includes packets later dropped
805 * because we ran out of buffer space.
807 * "ps_drop" counts packets dropped inside the BPF device
808 * because we ran out of buffer space. It doesn't count
809 * packets dropped by the interface driver. It counts
810 * only packets that passed the filter.
812 * Both statistics include packets not yet read from the kernel
813 * by libpcap, and thus not yet seen by the application.
815 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
816 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
817 pcap_strerror(errno));
818 return (PCAP_ERROR);
821 ps->ps_recv = s.bs_recv;
822 ps->ps_drop = s.bs_drop;
823 ps->ps_ifdrop = 0;
824 return (0);
827 static int
828 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
830 struct pcap_bpf *pb = p->priv;
831 int cc;
832 int n = 0;
833 register u_char *bp, *ep;
834 u_char *datap;
835 #ifdef PCAP_FDDIPAD
836 register u_int pad;
837 #endif
838 #ifdef HAVE_ZEROCOPY_BPF
839 int i;
840 #endif
842 again:
844 * Has "pcap_breakloop()" been called?
846 if (p->break_loop) {
848 * Yes - clear the flag that indicates that it
849 * has, and return PCAP_ERROR_BREAK to indicate
850 * that we were told to break out of the loop.
852 p->break_loop = 0;
853 return (PCAP_ERROR_BREAK);
855 cc = p->cc;
856 if (p->cc == 0) {
858 * When reading without zero-copy from a file descriptor, we
859 * use a single buffer and return a length of data in the
860 * buffer. With zero-copy, we update the p->buffer pointer
861 * to point at whatever underlying buffer contains the next
862 * data and update cc to reflect the data found in the
863 * buffer.
865 #ifdef HAVE_ZEROCOPY_BPF
866 if (pb->zerocopy) {
867 if (p->buffer != NULL)
868 pcap_ack_zbuf(p);
869 i = pcap_next_zbuf(p, &cc);
870 if (i == 0)
871 goto again;
872 if (i < 0)
873 return (PCAP_ERROR);
874 } else
875 #endif
877 cc = read(p->fd, (char *)p->buffer, p->bufsize);
879 if (cc < 0) {
880 /* Don't choke when we get ptraced */
881 switch (errno) {
883 case EINTR:
884 goto again;
886 #ifdef _AIX
887 case EFAULT:
889 * Sigh. More AIX wonderfulness.
891 * For some unknown reason the uiomove()
892 * operation in the bpf kernel extension
893 * used to copy the buffer into user
894 * space sometimes returns EFAULT. I have
895 * no idea why this is the case given that
896 * a kernel debugger shows the user buffer
897 * is correct. This problem appears to
898 * be mostly mitigated by the memset of
899 * the buffer before it is first used.
900 * Very strange.... Shaun Clowes
902 * In any case this means that we shouldn't
903 * treat EFAULT as a fatal error; as we
904 * don't have an API for returning
905 * a "some packets were dropped since
906 * the last packet you saw" indication,
907 * we just ignore EFAULT and keep reading.
909 goto again;
910 #endif
912 case EWOULDBLOCK:
913 return (0);
915 case ENXIO:
917 * The device on which we're capturing
918 * went away.
920 * XXX - we should really return
921 * PCAP_ERROR_IFACE_NOT_UP, but
922 * pcap_dispatch() etc. aren't
923 * defined to retur that.
925 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
926 "The interface went down");
927 return (PCAP_ERROR);
929 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
931 * Due to a SunOS bug, after 2^31 bytes, the kernel
932 * file offset overflows and read fails with EINVAL.
933 * The lseek() to 0 will fix things.
935 case EINVAL:
936 if (lseek(p->fd, 0L, SEEK_CUR) +
937 p->bufsize < 0) {
938 (void)lseek(p->fd, 0L, SEEK_SET);
939 goto again;
941 /* fall through */
942 #endif
944 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
945 pcap_strerror(errno));
946 return (PCAP_ERROR);
948 bp = p->buffer;
949 } else
950 bp = p->bp;
953 * Loop through each packet.
955 #define bhp ((struct bpf_hdr *)bp)
956 ep = bp + cc;
957 #ifdef PCAP_FDDIPAD
958 pad = p->fddipad;
959 #endif
960 while (bp < ep) {
961 register u_int caplen, hdrlen;
964 * Has "pcap_breakloop()" been called?
965 * If so, return immediately - if we haven't read any
966 * packets, clear the flag and return PCAP_ERROR_BREAK
967 * to indicate that we were told to break out of the loop,
968 * otherwise leave the flag set, so that the *next* call
969 * will break out of the loop without having read any
970 * packets, and return the number of packets we've
971 * processed so far.
973 if (p->break_loop) {
974 p->bp = bp;
975 p->cc = ep - bp;
977 * ep is set based on the return value of read(),
978 * but read() from a BPF device doesn't necessarily
979 * return a value that's a multiple of the alignment
980 * value for BPF_WORDALIGN(). However, whenever we
981 * increment bp, we round up the increment value by
982 * a value rounded up by BPF_WORDALIGN(), so we
983 * could increment bp past ep after processing the
984 * last packet in the buffer.
986 * We treat ep < bp as an indication that this
987 * happened, and just set p->cc to 0.
989 if (p->cc < 0)
990 p->cc = 0;
991 if (n == 0) {
992 p->break_loop = 0;
993 return (PCAP_ERROR_BREAK);
994 } else
995 return (n);
998 caplen = bhp->bh_caplen;
999 hdrlen = bhp->bh_hdrlen;
1000 datap = bp + hdrlen;
1002 * Short-circuit evaluation: if using BPF filter
1003 * in kernel, no need to do it now - we already know
1004 * the packet passed the filter.
1006 #ifdef PCAP_FDDIPAD
1007 * Note: the filter code was generated assuming
1008 * that p->fddipad was the amount of padding
1009 * before the header, as that's what's required
1010 * in the kernel, so we run the filter before
1011 * skipping that padding.
1012 #endif
1014 if (pb->filtering_in_kernel ||
1015 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1016 struct pcap_pkthdr pkthdr;
1018 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1019 #ifdef _AIX
1021 * AIX's BPF returns seconds/nanoseconds time
1022 * stamps, not seconds/microseconds time stamps.
1024 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1025 #else
1026 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1027 #endif
1028 #ifdef PCAP_FDDIPAD
1029 if (caplen > pad)
1030 pkthdr.caplen = caplen - pad;
1031 else
1032 pkthdr.caplen = 0;
1033 if (bhp->bh_datalen > pad)
1034 pkthdr.len = bhp->bh_datalen - pad;
1035 else
1036 pkthdr.len = 0;
1037 datap += pad;
1038 #else
1039 pkthdr.caplen = caplen;
1040 pkthdr.len = bhp->bh_datalen;
1041 #endif
1042 (*callback)(user, &pkthdr, datap);
1043 bp += BPF_WORDALIGN(caplen + hdrlen);
1044 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
1045 p->bp = bp;
1046 p->cc = ep - bp;
1048 * See comment above about p->cc < 0.
1050 if (p->cc < 0)
1051 p->cc = 0;
1052 return (n);
1054 } else {
1056 * Skip this packet.
1058 bp += BPF_WORDALIGN(caplen + hdrlen);
1061 #undef bhp
1062 p->cc = 0;
1063 return (n);
1066 static int
1067 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1069 int ret;
1071 ret = write(p->fd, buf, size);
1072 #ifdef __APPLE__
1073 if (ret == -1 && errno == EAFNOSUPPORT) {
1075 * In Mac OS X, there's a bug wherein setting the
1076 * BIOCSHDRCMPLT flag causes writes to fail; see,
1077 * for example:
1079 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1081 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
1082 * assume it's due to that bug, and turn off that flag
1083 * and try again. If we succeed, it either means that
1084 * somebody applied the fix from that URL, or other patches
1085 * for that bug from
1087 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1089 * and are running a Darwin kernel with those fixes, or
1090 * that Apple fixed the problem in some OS X release.
1092 u_int spoof_eth_src = 0;
1094 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1095 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1096 "send: can't turn off BIOCSHDRCMPLT: %s",
1097 pcap_strerror(errno));
1098 return (PCAP_ERROR);
1102 * Now try the write again.
1104 ret = write(p->fd, buf, size);
1106 #endif /* __APPLE__ */
1107 if (ret == -1) {
1108 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1109 pcap_strerror(errno));
1110 return (PCAP_ERROR);
1112 return (ret);
1115 #ifdef _AIX
1116 static int
1117 bpf_odminit(char *errbuf)
1119 char *errstr;
1121 if (odm_initialize() == -1) {
1122 if (odm_err_msg(odmerrno, &errstr) == -1)
1123 errstr = "Unknown error";
1124 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1125 "bpf_load: odm_initialize failed: %s",
1126 errstr);
1127 return (PCAP_ERROR);
1130 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1131 if (odm_err_msg(odmerrno, &errstr) == -1)
1132 errstr = "Unknown error";
1133 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1134 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1135 errstr);
1136 (void)odm_terminate();
1137 return (PCAP_ERROR);
1140 return (0);
1143 static int
1144 bpf_odmcleanup(char *errbuf)
1146 char *errstr;
1148 if (odm_unlock(odmlockid) == -1) {
1149 if (errbuf != NULL) {
1150 if (odm_err_msg(odmerrno, &errstr) == -1)
1151 errstr = "Unknown error";
1152 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1153 "bpf_load: odm_unlock failed: %s",
1154 errstr);
1156 return (PCAP_ERROR);
1159 if (odm_terminate() == -1) {
1160 if (errbuf != NULL) {
1161 if (odm_err_msg(odmerrno, &errstr) == -1)
1162 errstr = "Unknown error";
1163 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1164 "bpf_load: odm_terminate failed: %s",
1165 errstr);
1167 return (PCAP_ERROR);
1170 return (0);
1173 static int
1174 bpf_load(char *errbuf)
1176 long major;
1177 int *minors;
1178 int numminors, i, rc;
1179 char buf[1024];
1180 struct stat sbuf;
1181 struct bpf_config cfg_bpf;
1182 struct cfg_load cfg_ld;
1183 struct cfg_kmod cfg_km;
1186 * This is very very close to what happens in the real implementation
1187 * but I've fixed some (unlikely) bug situations.
1189 if (bpfloadedflag)
1190 return (0);
1192 if (bpf_odminit(errbuf) == PCAP_ERROR)
1193 return (PCAP_ERROR);
1195 major = genmajor(BPF_NAME);
1196 if (major == -1) {
1197 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1198 "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1199 (void)bpf_odmcleanup(NULL);
1200 return (PCAP_ERROR);
1203 minors = getminor(major, &numminors, BPF_NAME);
1204 if (!minors) {
1205 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1206 if (!minors) {
1207 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1208 "bpf_load: genminor failed: %s",
1209 pcap_strerror(errno));
1210 (void)bpf_odmcleanup(NULL);
1211 return (PCAP_ERROR);
1215 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1216 return (PCAP_ERROR);
1218 rc = stat(BPF_NODE "0", &sbuf);
1219 if (rc == -1 && errno != ENOENT) {
1220 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1221 "bpf_load: can't stat %s: %s",
1222 BPF_NODE "0", pcap_strerror(errno));
1223 return (PCAP_ERROR);
1226 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1227 for (i = 0; i < BPF_MINORS; i++) {
1228 sprintf(buf, "%s%d", BPF_NODE, i);
1229 unlink(buf);
1230 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1231 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1232 "bpf_load: can't mknod %s: %s",
1233 buf, pcap_strerror(errno));
1234 return (PCAP_ERROR);
1239 /* Check if the driver is loaded */
1240 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1241 cfg_ld.path = buf;
1242 sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1243 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1244 (cfg_ld.kmid == 0)) {
1245 /* Driver isn't loaded, load it now */
1246 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1247 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1248 "bpf_load: could not load driver: %s",
1249 strerror(errno));
1250 return (PCAP_ERROR);
1254 /* Configure the driver */
1255 cfg_km.cmd = CFG_INIT;
1256 cfg_km.kmid = cfg_ld.kmid;
1257 cfg_km.mdilen = sizeof(cfg_bpf);
1258 cfg_km.mdiptr = (void *)&cfg_bpf;
1259 for (i = 0; i < BPF_MINORS; i++) {
1260 cfg_bpf.devno = domakedev(major, i);
1261 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1262 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1263 "bpf_load: could not configure driver: %s",
1264 strerror(errno));
1265 return (PCAP_ERROR);
1269 bpfloadedflag = 1;
1271 return (0);
1273 #endif
1276 * Turn off rfmon mode if necessary.
1278 static void
1279 pcap_cleanup_bpf(pcap_t *p)
1281 struct pcap_bpf *pb = p->priv;
1282 #ifdef HAVE_BSD_IEEE80211
1283 int sock;
1284 struct ifmediareq req;
1285 struct ifreq ifr;
1286 #endif
1288 if (pb->must_do_on_close != 0) {
1290 * There's something we have to do when closing this
1291 * pcap_t.
1293 #ifdef HAVE_BSD_IEEE80211
1294 if (pb->must_do_on_close & MUST_CLEAR_RFMON) {
1296 * We put the interface into rfmon mode;
1297 * take it out of rfmon mode.
1299 * XXX - if somebody else wants it in rfmon
1300 * mode, this code cannot know that, so it'll take
1301 * it out of rfmon mode.
1303 sock = socket(AF_INET, SOCK_DGRAM, 0);
1304 if (sock == -1) {
1305 fprintf(stderr,
1306 "Can't restore interface flags (socket() failed: %s).\n"
1307 "Please adjust manually.\n",
1308 strerror(errno));
1309 } else {
1310 memset(&req, 0, sizeof(req));
1311 strncpy(req.ifm_name, pb->device,
1312 sizeof(req.ifm_name));
1313 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1314 fprintf(stderr,
1315 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1316 "Please adjust manually.\n",
1317 strerror(errno));
1318 } else {
1319 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1321 * Rfmon mode is currently on;
1322 * turn it off.
1324 memset(&ifr, 0, sizeof(ifr));
1325 (void)strncpy(ifr.ifr_name,
1326 pb->device,
1327 sizeof(ifr.ifr_name));
1328 ifr.ifr_media =
1329 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1330 if (ioctl(sock, SIOCSIFMEDIA,
1331 &ifr) == -1) {
1332 fprintf(stderr,
1333 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1334 "Please adjust manually.\n",
1335 strerror(errno));
1339 close(sock);
1342 #endif /* HAVE_BSD_IEEE80211 */
1345 * Take this pcap out of the list of pcaps for which we
1346 * have to take the interface out of some mode.
1348 pcap_remove_from_pcaps_to_close(p);
1349 pb->must_do_on_close = 0;
1352 #ifdef HAVE_ZEROCOPY_BPF
1353 if (pb->zerocopy) {
1355 * Delete the mappings. Note that p->buffer gets
1356 * initialized to one of the mmapped regions in
1357 * this case, so do not try and free it directly;
1358 * null it out so that pcap_cleanup_live_common()
1359 * doesn't try to free it.
1361 if (pb->zbuf1 != MAP_FAILED && pb->zbuf1 != NULL)
1362 (void) munmap(pb->zbuf1, pb->zbufsize);
1363 if (pb->zbuf2 != MAP_FAILED && pb->zbuf2 != NULL)
1364 (void) munmap(pb->zbuf2, pb->zbufsize);
1365 p->buffer = NULL;
1367 #endif
1368 if (pb->device != NULL) {
1369 free(pb->device);
1370 pb->device = NULL;
1372 pcap_cleanup_live_common(p);
1375 static int
1376 check_setif_failure(pcap_t *p, int error)
1378 #ifdef __APPLE__
1379 int fd;
1380 struct ifreq ifr;
1381 int err;
1382 #endif
1384 if (error == ENXIO) {
1386 * No such device exists.
1388 #ifdef __APPLE__
1389 if (p->opt.rfmon && strncmp(p->opt.source, "wlt", 3) == 0) {
1391 * Monitor mode was requested, and we're trying
1392 * to open a "wltN" device. Assume that this
1393 * is 10.4 and that we were asked to open an
1394 * "enN" device; if that device exists, return
1395 * "monitor mode not supported on the device".
1397 fd = socket(AF_INET, SOCK_DGRAM, 0);
1398 if (fd != -1) {
1399 strlcpy(ifr.ifr_name, "en",
1400 sizeof(ifr.ifr_name));
1401 strlcat(ifr.ifr_name, p->opt.source + 3,
1402 sizeof(ifr.ifr_name));
1403 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1405 * We assume this failed because
1406 * the underlying device doesn't
1407 * exist.
1409 err = PCAP_ERROR_NO_SUCH_DEVICE;
1410 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1411 "SIOCGIFFLAGS on %s failed: %s",
1412 ifr.ifr_name, pcap_strerror(errno));
1413 } else {
1415 * The underlying "enN" device
1416 * exists, but there's no
1417 * corresponding "wltN" device;
1418 * that means that the "enN"
1419 * device doesn't support
1420 * monitor mode, probably because
1421 * it's an Ethernet device rather
1422 * than a wireless device.
1424 err = PCAP_ERROR_RFMON_NOTSUP;
1426 close(fd);
1427 } else {
1429 * We can't find out whether there's
1430 * an underlying "enN" device, so
1431 * just report "no such device".
1433 err = PCAP_ERROR_NO_SUCH_DEVICE;
1434 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1435 "socket() failed: %s",
1436 pcap_strerror(errno));
1438 return (err);
1440 #endif
1442 * No such device.
1444 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
1445 pcap_strerror(errno));
1446 return (PCAP_ERROR_NO_SUCH_DEVICE);
1447 } else if (errno == ENETDOWN) {
1449 * Return a "network down" indication, so that
1450 * the application can report that rather than
1451 * saying we had a mysterious failure and
1452 * suggest that they report a problem to the
1453 * libpcap developers.
1455 return (PCAP_ERROR_IFACE_NOT_UP);
1456 } else {
1458 * Some other error; fill in the error string, and
1459 * return PCAP_ERROR.
1461 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1462 p->opt.source, pcap_strerror(errno));
1463 return (PCAP_ERROR);
1468 * Default capture buffer size.
1469 * 32K isn't very much for modern machines with fast networks; we
1470 * pick .5M, as that's the maximum on at least some systems with BPF.
1472 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1473 * read failures under stress, so we leave it as 32K; yet another
1474 * place where AIX's BPF is broken.
1476 #ifdef _AIX
1477 #define DEFAULT_BUFSIZE 32768
1478 #else
1479 #define DEFAULT_BUFSIZE 524288
1480 #endif
1482 static int
1483 pcap_activate_bpf(pcap_t *p)
1485 struct pcap_bpf *pb = p->priv;
1486 int status = 0;
1487 #ifdef HAVE_BSD_IEEE80211
1488 int retv;
1489 #endif
1490 int fd;
1491 #ifdef LIFNAMSIZ
1492 char *zonesep;
1493 struct lifreq ifr;
1494 char *ifrname = ifr.lifr_name;
1495 const size_t ifnamsiz = sizeof(ifr.lifr_name);
1496 #else
1497 struct ifreq ifr;
1498 char *ifrname = ifr.ifr_name;
1499 const size_t ifnamsiz = sizeof(ifr.ifr_name);
1500 #endif
1501 struct bpf_version bv;
1502 #ifdef __APPLE__
1503 int sockfd;
1504 char *wltdev = NULL;
1505 #endif
1506 #ifdef BIOCGDLTLIST
1507 struct bpf_dltlist bdl;
1508 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1509 u_int new_dlt;
1510 #endif
1511 #endif /* BIOCGDLTLIST */
1512 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1513 u_int spoof_eth_src = 1;
1514 #endif
1515 u_int v;
1516 struct bpf_insn total_insn;
1517 struct bpf_program total_prog;
1518 struct utsname osinfo;
1519 int have_osinfo = 0;
1520 #ifdef HAVE_ZEROCOPY_BPF
1521 struct bpf_zbuf bz;
1522 u_int bufmode, zbufmax;
1523 #endif
1525 fd = bpf_open(p);
1526 if (fd < 0) {
1527 status = fd;
1528 goto bad;
1531 p->fd = fd;
1533 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1534 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1535 pcap_strerror(errno));
1536 status = PCAP_ERROR;
1537 goto bad;
1539 if (bv.bv_major != BPF_MAJOR_VERSION ||
1540 bv.bv_minor < BPF_MINOR_VERSION) {
1541 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1542 "kernel bpf filter out of date");
1543 status = PCAP_ERROR;
1544 goto bad;
1547 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1549 * Retrieve the zoneid of the zone we are currently executing in.
1551 if ((ifr.lifr_zoneid = getzoneid()) == -1) {
1552 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "getzoneid(): %s",
1553 pcap_strerror(errno));
1554 status = PCAP_ERROR;
1555 goto bad;
1558 * Check if the given source datalink name has a '/' separated
1559 * zonename prefix string. The zonename prefixed source datalink can
1560 * be used by pcap consumers in the Solaris global zone to capture
1561 * traffic on datalinks in non-global zones. Non-global zones
1562 * do not have access to datalinks outside of their own namespace.
1564 if ((zonesep = strchr(p->opt.source, '/')) != NULL) {
1565 char path_zname[ZONENAME_MAX];
1566 int znamelen;
1567 char *lnamep;
1569 if (ifr.lifr_zoneid != GLOBAL_ZONEID) {
1570 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1571 "zonename/linkname only valid in global zone.");
1572 status = PCAP_ERROR;
1573 goto bad;
1575 znamelen = zonesep - p->opt.source;
1576 (void) strlcpy(path_zname, p->opt.source, znamelen + 1);
1577 ifr.lifr_zoneid = getzoneidbyname(path_zname);
1578 if (ifr.lifr_zoneid == -1) {
1579 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1580 "getzoneidbyname(%s): %s", path_zname,
1581 pcap_strerror(errno));
1582 status = PCAP_ERROR;
1583 goto bad;
1585 lnamep = strdup(zonesep + 1);
1586 free(p->opt.source);
1587 p->opt.source = lnamep;
1589 #endif
1591 pb->device = strdup(p->opt.source);
1592 if (pb->device == NULL) {
1593 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1594 pcap_strerror(errno));
1595 status = PCAP_ERROR;
1596 goto bad;
1600 * Attempt to find out the version of the OS on which we're running.
1602 if (uname(&osinfo) == 0)
1603 have_osinfo = 1;
1605 #ifdef __APPLE__
1607 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1608 * of why we check the version number.
1610 if (p->opt.rfmon) {
1611 if (have_osinfo) {
1613 * We assume osinfo.sysname is "Darwin", because
1614 * __APPLE__ is defined. We just check the version.
1616 if (osinfo.release[0] < '8' &&
1617 osinfo.release[1] == '.') {
1619 * 10.3 (Darwin 7.x) or earlier.
1621 status = PCAP_ERROR_RFMON_NOTSUP;
1622 goto bad;
1624 if (osinfo.release[0] == '8' &&
1625 osinfo.release[1] == '.') {
1627 * 10.4 (Darwin 8.x). s/en/wlt/
1629 if (strncmp(p->opt.source, "en", 2) != 0) {
1631 * Not an enN device; check
1632 * whether the device even exists.
1634 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1635 if (sockfd != -1) {
1636 strlcpy(ifrname,
1637 p->opt.source, ifnamsiz);
1638 if (ioctl(sockfd, SIOCGIFFLAGS,
1639 (char *)&ifr) < 0) {
1641 * We assume this
1642 * failed because
1643 * the underlying
1644 * device doesn't
1645 * exist.
1647 status = PCAP_ERROR_NO_SUCH_DEVICE;
1648 snprintf(p->errbuf,
1649 PCAP_ERRBUF_SIZE,
1650 "SIOCGIFFLAGS failed: %s",
1651 pcap_strerror(errno));
1652 } else
1653 status = PCAP_ERROR_RFMON_NOTSUP;
1654 close(sockfd);
1655 } else {
1657 * We can't find out whether
1658 * the device exists, so just
1659 * report "no such device".
1661 status = PCAP_ERROR_NO_SUCH_DEVICE;
1662 snprintf(p->errbuf,
1663 PCAP_ERRBUF_SIZE,
1664 "socket() failed: %s",
1665 pcap_strerror(errno));
1667 goto bad;
1669 wltdev = malloc(strlen(p->opt.source) + 2);
1670 if (wltdev == NULL) {
1671 (void)snprintf(p->errbuf,
1672 PCAP_ERRBUF_SIZE, "malloc: %s",
1673 pcap_strerror(errno));
1674 status = PCAP_ERROR;
1675 goto bad;
1677 strcpy(wltdev, "wlt");
1678 strcat(wltdev, p->opt.source + 2);
1679 free(p->opt.source);
1680 p->opt.source = wltdev;
1683 * Everything else is 10.5 or later; for those,
1684 * we just open the enN device, and set the DLT.
1688 #endif /* __APPLE__ */
1689 #ifdef HAVE_ZEROCOPY_BPF
1691 * If the BPF extension to set buffer mode is present, try setting
1692 * the mode to zero-copy. If that fails, use regular buffering. If
1693 * it succeeds but other setup fails, return an error to the user.
1695 bufmode = BPF_BUFMODE_ZBUF;
1696 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1698 * We have zerocopy BPF; use it.
1700 pb->zerocopy = 1;
1703 * How to pick a buffer size: first, query the maximum buffer
1704 * size supported by zero-copy. This also lets us quickly
1705 * determine whether the kernel generally supports zero-copy.
1706 * Then, if a buffer size was specified, use that, otherwise
1707 * query the default buffer size, which reflects kernel
1708 * policy for a desired default. Round to the nearest page
1709 * size.
1711 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1712 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1713 pcap_strerror(errno));
1714 status = PCAP_ERROR;
1715 goto bad;
1718 if (p->opt.buffer_size != 0) {
1720 * A buffer size was explicitly specified; use it.
1722 v = p->opt.buffer_size;
1723 } else {
1724 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1725 v < DEFAULT_BUFSIZE)
1726 v = DEFAULT_BUFSIZE;
1728 #ifndef roundup
1729 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
1730 #endif
1731 pb->zbufsize = roundup(v, getpagesize());
1732 if (pb->zbufsize > zbufmax)
1733 pb->zbufsize = zbufmax;
1734 pb->zbuf1 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1735 MAP_ANON, -1, 0);
1736 pb->zbuf2 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1737 MAP_ANON, -1, 0);
1738 if (pb->zbuf1 == MAP_FAILED || pb->zbuf2 == MAP_FAILED) {
1739 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1740 pcap_strerror(errno));
1741 status = PCAP_ERROR;
1742 goto bad;
1744 memset(&bz, 0, sizeof(bz)); /* bzero() deprecated, replaced with memset() */
1745 bz.bz_bufa = pb->zbuf1;
1746 bz.bz_bufb = pb->zbuf2;
1747 bz.bz_buflen = pb->zbufsize;
1748 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1749 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1750 pcap_strerror(errno));
1751 status = PCAP_ERROR;
1752 goto bad;
1754 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1755 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1756 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1757 p->opt.source, pcap_strerror(errno));
1758 status = PCAP_ERROR;
1759 goto bad;
1761 v = pb->zbufsize - sizeof(struct bpf_zbuf_header);
1762 } else
1763 #endif
1766 * We don't have zerocopy BPF.
1767 * Set the buffer size.
1769 if (p->opt.buffer_size != 0) {
1771 * A buffer size was explicitly specified; use it.
1773 if (ioctl(fd, BIOCSBLEN,
1774 (caddr_t)&p->opt.buffer_size) < 0) {
1775 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1776 "BIOCSBLEN: %s: %s", p->opt.source,
1777 pcap_strerror(errno));
1778 status = PCAP_ERROR;
1779 goto bad;
1783 * Now bind to the device.
1785 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1786 #ifdef BIOCSETLIF
1787 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
1788 #else
1789 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
1790 #endif
1792 status = check_setif_failure(p, errno);
1793 goto bad;
1795 } else {
1797 * No buffer size was explicitly specified.
1799 * Try finding a good size for the buffer;
1800 * DEFAULT_BUFSIZE may be too big, so keep
1801 * cutting it in half until we find a size
1802 * that works, or run out of sizes to try.
1803 * If the default is larger, don't make it smaller.
1805 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1806 v < DEFAULT_BUFSIZE)
1807 v = DEFAULT_BUFSIZE;
1808 for ( ; v != 0; v >>= 1) {
1810 * Ignore the return value - this is because the
1811 * call fails on BPF systems that don't have
1812 * kernel malloc. And if the call fails, it's
1813 * no big deal, we just continue to use the
1814 * standard buffer size.
1816 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
1818 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1819 #ifdef BIOCSETLIF
1820 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
1821 #else
1822 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
1823 #endif
1824 break; /* that size worked; we're done */
1826 if (errno != ENOBUFS) {
1827 status = check_setif_failure(p, errno);
1828 goto bad;
1832 if (v == 0) {
1833 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1834 "BIOCSBLEN: %s: No buffer size worked",
1835 p->opt.source);
1836 status = PCAP_ERROR;
1837 goto bad;
1842 /* Get the data link layer type. */
1843 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
1844 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
1845 pcap_strerror(errno));
1846 status = PCAP_ERROR;
1847 goto bad;
1850 #ifdef _AIX
1852 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
1854 switch (v) {
1856 case IFT_ETHER:
1857 case IFT_ISO88023:
1858 v = DLT_EN10MB;
1859 break;
1861 case IFT_FDDI:
1862 v = DLT_FDDI;
1863 break;
1865 case IFT_ISO88025:
1866 v = DLT_IEEE802;
1867 break;
1869 case IFT_LOOP:
1870 v = DLT_NULL;
1871 break;
1873 default:
1875 * We don't know what to map this to yet.
1877 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
1879 status = PCAP_ERROR;
1880 goto bad;
1882 #endif
1883 #if _BSDI_VERSION - 0 >= 199510
1884 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
1885 switch (v) {
1887 case DLT_SLIP:
1888 v = DLT_SLIP_BSDOS;
1889 break;
1891 case DLT_PPP:
1892 v = DLT_PPP_BSDOS;
1893 break;
1895 case 11: /*DLT_FR*/
1896 v = DLT_FRELAY;
1897 break;
1899 case 12: /*DLT_C_HDLC*/
1900 v = DLT_CHDLC;
1901 break;
1903 #endif
1905 #ifdef BIOCGDLTLIST
1907 * We know the default link type -- now determine all the DLTs
1908 * this interface supports. If this fails with EINVAL, it's
1909 * not fatal; we just don't get to use the feature later.
1911 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
1912 status = PCAP_ERROR;
1913 goto bad;
1915 p->dlt_count = bdl.bfl_len;
1916 p->dlt_list = bdl.bfl_list;
1918 #ifdef __APPLE__
1920 * Monitor mode fun, continued.
1922 * For 10.5 and, we're assuming, later releases, as noted above,
1923 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
1924 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
1925 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
1926 * monitor mode on.
1928 * Therefore, if the user asked for monitor mode, we filter out
1929 * the DLT_EN10MB value, as you can't get that in monitor mode,
1930 * and, if the user didn't ask for monitor mode, we filter out
1931 * the 802.11 DLT_ values, because selecting those will turn
1932 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
1933 * radio DLT_ value is offered, we try to select that, otherwise
1934 * we try to select DLT_IEEE802_11.
1936 if (have_osinfo) {
1937 if (isdigit((unsigned)osinfo.release[0]) &&
1938 (osinfo.release[0] == '9' ||
1939 isdigit((unsigned)osinfo.release[1]))) {
1941 * 10.5 (Darwin 9.x), or later.
1943 new_dlt = find_802_11(&bdl);
1944 if (new_dlt != -1) {
1946 * We have at least one 802.11 DLT_ value,
1947 * so this is an 802.11 interface.
1948 * new_dlt is the best of the 802.11
1949 * DLT_ values in the list.
1951 if (p->opt.rfmon) {
1953 * Our caller wants monitor mode.
1954 * Purge DLT_EN10MB from the list
1955 * of link-layer types, as selecting
1956 * it will keep monitor mode off.
1958 remove_en(p);
1961 * If the new mode we want isn't
1962 * the default mode, attempt to
1963 * select the new mode.
1965 if (new_dlt != v) {
1966 if (ioctl(p->fd, BIOCSDLT,
1967 &new_dlt) != -1) {
1969 * We succeeded;
1970 * make this the
1971 * new DLT_ value.
1973 v = new_dlt;
1976 } else {
1978 * Our caller doesn't want
1979 * monitor mode. Unless this
1980 * is being done by pcap_open_live(),
1981 * purge the 802.11 link-layer types
1982 * from the list, as selecting
1983 * one of them will turn monitor
1984 * mode on.
1986 if (!p->oldstyle)
1987 remove_802_11(p);
1989 } else {
1990 if (p->opt.rfmon) {
1992 * The caller requested monitor
1993 * mode, but we have no 802.11
1994 * link-layer types, so they
1995 * can't have it.
1997 status = PCAP_ERROR_RFMON_NOTSUP;
1998 goto bad;
2003 #elif defined(HAVE_BSD_IEEE80211)
2005 * *BSD with the new 802.11 ioctls.
2006 * Do we want monitor mode?
2008 if (p->opt.rfmon) {
2010 * Try to put the interface into monitor mode.
2012 retv = monitor_mode(p, 1);
2013 if (retv != 0) {
2015 * We failed.
2017 status = retv;
2018 goto bad;
2022 * We're in monitor mode.
2023 * Try to find the best 802.11 DLT_ value and, if we
2024 * succeed, try to switch to that mode if we're not
2025 * already in that mode.
2027 new_dlt = find_802_11(&bdl);
2028 if (new_dlt != (unsigned)-1) {
2030 * We have at least one 802.11 DLT_ value.
2031 * new_dlt is the best of the 802.11
2032 * DLT_ values in the list.
2034 * If the new mode we want isn't the default mode,
2035 * attempt to select the new mode.
2037 if (new_dlt != v) {
2038 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
2040 * We succeeded; make this the
2041 * new DLT_ value.
2043 v = new_dlt;
2048 #endif /* various platforms */
2049 #endif /* BIOCGDLTLIST */
2052 * If this is an Ethernet device, and we don't have a DLT_ list,
2053 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
2054 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2055 * do, but there's not much we can do about that without finding
2056 * some other way of determining whether it's an Ethernet or 802.11
2057 * device.)
2059 if (v == DLT_EN10MB && p->dlt_count == 0) {
2060 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2062 * If that fails, just leave the list empty.
2064 if (p->dlt_list != NULL) {
2065 p->dlt_list[0] = DLT_EN10MB;
2066 p->dlt_list[1] = DLT_DOCSIS;
2067 p->dlt_count = 2;
2070 #ifdef PCAP_FDDIPAD
2071 if (v == DLT_FDDI)
2072 p->fddipad = PCAP_FDDIPAD;
2073 else
2074 #endif
2075 p->fddipad = 0;
2076 p->linktype = v;
2078 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2080 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2081 * the link-layer source address isn't forcibly overwritten.
2082 * (Should we ignore errors? Should we do this only if
2083 * we're open for writing?)
2085 * XXX - I seem to remember some packet-sending bug in some
2086 * BSDs - check CVS log for "bpf.c"?
2088 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2089 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2090 "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
2091 status = PCAP_ERROR;
2092 goto bad;
2094 #endif
2095 /* set timeout */
2096 #ifdef HAVE_ZEROCOPY_BPF
2098 * In zero-copy mode, we just use the timeout in select().
2099 * XXX - what if we're in non-blocking mode and the *application*
2100 * is using select() or poll() or kqueues or....?
2102 if (p->opt.timeout && !pb->zerocopy) {
2103 #else
2104 if (p->opt.timeout) {
2105 #endif
2107 * XXX - is this seconds/nanoseconds in AIX?
2108 * (Treating it as such doesn't fix the timeout
2109 * problem described below.)
2111 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2112 * 64-bit userland - it takes, as an argument, a
2113 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2114 * and tv_usec, rather than a "struct timeval".
2116 * If this platform defines "struct BPF_TIMEVAL",
2117 * we check whether the structure size in BIOCSRTIMEOUT
2118 * is that of a "struct timeval" and, if not, we use
2119 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2120 * (That way, if the bug is fixed in a future release,
2121 * we will still do the right thing.)
2123 struct timeval to;
2124 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2125 struct BPF_TIMEVAL bpf_to;
2127 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2128 bpf_to.tv_sec = p->opt.timeout / 1000;
2129 bpf_to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2130 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2131 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2132 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2133 status = PCAP_ERROR;
2134 goto bad;
2136 } else {
2137 #endif
2138 to.tv_sec = p->opt.timeout / 1000;
2139 to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2140 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2141 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2142 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2143 status = PCAP_ERROR;
2144 goto bad;
2146 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2148 #endif
2151 #ifdef BIOCIMMEDIATE
2153 * Darren Reed notes that
2155 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2156 * timeout appears to be ignored and it waits until the buffer
2157 * is filled before returning. The result of not having it
2158 * set is almost worse than useless if your BPF filter
2159 * is reducing things to only a few packets (i.e. one every
2160 * second or so).
2162 * so we always turn BIOCIMMEDIATE mode on if this is AIX.
2164 * For other platforms, we don't turn immediate mode on by default,
2165 * as that would mean we get woken up for every packet, which
2166 * probably isn't what you want for a packet sniffer.
2168 * We set immediate mode if the caller requested it by calling
2169 * pcap_set_immediate() before calling pcap_activate().
2171 #ifndef _AIX
2172 if (p->opt.immediate) {
2173 #endif /* _AIX */
2174 v = 1;
2175 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2176 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2177 "BIOCIMMEDIATE: %s", pcap_strerror(errno));
2178 status = PCAP_ERROR;
2179 goto bad;
2181 #ifndef _AIX
2183 #endif /* _AIX */
2184 #else /* BIOCIMMEDIATE */
2185 if (p->opt.immediate) {
2187 * We don't support immediate mode. Fail.
2189 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Immediate mode not supported");
2190 status = PCAP_ERROR;
2191 goto bad;
2193 #endif /* BIOCIMMEDIATE */
2195 if (p->opt.promisc) {
2196 /* set promiscuous mode, just warn if it fails */
2197 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2198 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
2199 pcap_strerror(errno));
2200 status = PCAP_WARNING_PROMISC_NOTSUP;
2204 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2205 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
2206 pcap_strerror(errno));
2207 status = PCAP_ERROR;
2208 goto bad;
2210 p->bufsize = v;
2211 #ifdef HAVE_ZEROCOPY_BPF
2212 if (!pb->zerocopy) {
2213 #endif
2214 p->buffer = (u_char *)malloc(p->bufsize);
2215 if (p->buffer == NULL) {
2216 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2217 pcap_strerror(errno));
2218 status = PCAP_ERROR;
2219 goto bad;
2221 #ifdef _AIX
2222 /* For some strange reason this seems to prevent the EFAULT
2223 * problems we have experienced from AIX BPF. */
2224 memset(p->buffer, 0x0, p->bufsize);
2225 #endif
2226 #ifdef HAVE_ZEROCOPY_BPF
2228 #endif
2231 * If there's no filter program installed, there's
2232 * no indication to the kernel of what the snapshot
2233 * length should be, so no snapshotting is done.
2235 * Therefore, when we open the device, we install
2236 * an "accept everything" filter with the specified
2237 * snapshot length.
2239 total_insn.code = (u_short)(BPF_RET | BPF_K);
2240 total_insn.jt = 0;
2241 total_insn.jf = 0;
2242 total_insn.k = p->snapshot;
2244 total_prog.bf_len = 1;
2245 total_prog.bf_insns = &total_insn;
2246 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2247 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2248 pcap_strerror(errno));
2249 status = PCAP_ERROR;
2250 goto bad;
2254 * On most BPF platforms, either you can do a "select()" or
2255 * "poll()" on a BPF file descriptor and it works correctly,
2256 * or you can do it and it will return "readable" if the
2257 * hold buffer is full but not if the timeout expires *and*
2258 * a non-blocking read will, if the hold buffer is empty
2259 * but the store buffer isn't empty, rotate the buffers
2260 * and return what packets are available.
2262 * In the latter case, the fact that a non-blocking read
2263 * will give you the available packets means you can work
2264 * around the failure of "select()" and "poll()" to wake up
2265 * and return "readable" when the timeout expires by using
2266 * the timeout as the "select()" or "poll()" timeout, putting
2267 * the BPF descriptor into non-blocking mode, and read from
2268 * it regardless of whether "select()" reports it as readable
2269 * or not.
2271 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2272 * won't wake up and return "readable" if the timer expires
2273 * and non-blocking reads return EWOULDBLOCK if the hold
2274 * buffer is empty, even if the store buffer is non-empty.
2276 * This means the workaround in question won't work.
2278 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2279 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2280 * here". On all other BPF platforms, we set it to the FD for
2281 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2282 * read will, if the hold buffer is empty and the store buffer
2283 * isn't empty, rotate the buffers and return what packets are
2284 * there (and in sufficiently recent versions of OpenBSD
2285 * "select()" and "poll()" should work correctly).
2287 * XXX - what about AIX?
2289 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2290 if (have_osinfo) {
2292 * We can check what OS this is.
2294 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2295 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2296 strncmp(osinfo.release, "4.4-", 4) == 0)
2297 p->selectable_fd = -1;
2301 p->read_op = pcap_read_bpf;
2302 p->inject_op = pcap_inject_bpf;
2303 p->setfilter_op = pcap_setfilter_bpf;
2304 p->setdirection_op = pcap_setdirection_bpf;
2305 p->set_datalink_op = pcap_set_datalink_bpf;
2306 p->getnonblock_op = pcap_getnonblock_bpf;
2307 p->setnonblock_op = pcap_setnonblock_bpf;
2308 p->stats_op = pcap_stats_bpf;
2309 p->cleanup_op = pcap_cleanup_bpf;
2311 return (status);
2312 bad:
2313 pcap_cleanup_bpf(p);
2314 return (status);
2318 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2320 return (0);
2323 #ifdef HAVE_BSD_IEEE80211
2324 static int
2325 monitor_mode(pcap_t *p, int set)
2327 struct pcap_bpf *pb = p->priv;
2328 int sock;
2329 struct ifmediareq req;
2330 int *media_list;
2331 int i;
2332 int can_do;
2333 struct ifreq ifr;
2335 sock = socket(AF_INET, SOCK_DGRAM, 0);
2336 if (sock == -1) {
2337 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2338 pcap_strerror(errno));
2339 return (PCAP_ERROR);
2342 memset(&req, 0, sizeof req);
2343 strncpy(req.ifm_name, p->opt.source, sizeof req.ifm_name);
2346 * Find out how many media types we have.
2348 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2350 * Can't get the media types.
2352 switch (errno) {
2354 case ENXIO:
2356 * There's no such device.
2358 close(sock);
2359 return (PCAP_ERROR_NO_SUCH_DEVICE);
2361 case EINVAL:
2363 * Interface doesn't support SIOC{G,S}IFMEDIA.
2365 close(sock);
2366 return (PCAP_ERROR_RFMON_NOTSUP);
2368 default:
2369 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2370 "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
2371 close(sock);
2372 return (PCAP_ERROR);
2375 if (req.ifm_count == 0) {
2377 * No media types.
2379 close(sock);
2380 return (PCAP_ERROR_RFMON_NOTSUP);
2384 * Allocate a buffer to hold all the media types, and
2385 * get the media types.
2387 media_list = malloc(req.ifm_count * sizeof(int));
2388 if (media_list == NULL) {
2389 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2390 pcap_strerror(errno));
2391 close(sock);
2392 return (PCAP_ERROR);
2394 req.ifm_ulist = media_list;
2395 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2396 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2397 pcap_strerror(errno));
2398 free(media_list);
2399 close(sock);
2400 return (PCAP_ERROR);
2404 * Look for an 802.11 "automatic" media type.
2405 * We assume that all 802.11 adapters have that media type,
2406 * and that it will carry the monitor mode supported flag.
2408 can_do = 0;
2409 for (i = 0; i < req.ifm_count; i++) {
2410 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2411 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2412 /* OK, does it do monitor mode? */
2413 if (media_list[i] & IFM_IEEE80211_MONITOR) {
2414 can_do = 1;
2415 break;
2419 free(media_list);
2420 if (!can_do) {
2422 * This adapter doesn't support monitor mode.
2424 close(sock);
2425 return (PCAP_ERROR_RFMON_NOTSUP);
2428 if (set) {
2430 * Don't just check whether we can enable monitor mode,
2431 * do so, if it's not already enabled.
2433 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2435 * Monitor mode isn't currently on, so turn it on,
2436 * and remember that we should turn it off when the
2437 * pcap_t is closed.
2441 * If we haven't already done so, arrange to have
2442 * "pcap_close_all()" called when we exit.
2444 if (!pcap_do_addexit(p)) {
2446 * "atexit()" failed; don't put the interface
2447 * in monitor mode, just give up.
2449 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2450 "atexit failed");
2451 close(sock);
2452 return (PCAP_ERROR);
2454 memset(&ifr, 0, sizeof(ifr));
2455 (void)strncpy(ifr.ifr_name, p->opt.source,
2456 sizeof(ifr.ifr_name));
2457 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2458 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2459 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2460 "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2461 close(sock);
2462 return (PCAP_ERROR);
2465 pb->must_do_on_close |= MUST_CLEAR_RFMON;
2468 * Add this to the list of pcaps to close when we exit.
2470 pcap_add_to_pcaps_to_close(p);
2473 return (0);
2475 #endif /* HAVE_BSD_IEEE80211 */
2477 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2479 * Check whether we have any 802.11 link-layer types; return the best
2480 * of the 802.11 link-layer types if we find one, and return -1
2481 * otherwise.
2483 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2484 * best 802.11 link-layer type; any of the other 802.11-plus-radio
2485 * headers are second-best; 802.11 with no radio information is
2486 * the least good.
2488 static int
2489 find_802_11(struct bpf_dltlist *bdlp)
2491 int new_dlt;
2492 u_int i;
2495 * Scan the list of DLT_ values, looking for 802.11 values,
2496 * and, if we find any, choose the best of them.
2498 new_dlt = -1;
2499 for (i = 0; i < bdlp->bfl_len; i++) {
2500 switch (bdlp->bfl_list[i]) {
2502 case DLT_IEEE802_11:
2504 * 802.11, but no radio.
2506 * Offer this, and select it as the new mode
2507 * unless we've already found an 802.11
2508 * header with radio information.
2510 if (new_dlt == -1)
2511 new_dlt = bdlp->bfl_list[i];
2512 break;
2514 case DLT_PRISM_HEADER:
2515 case DLT_AIRONET_HEADER:
2516 case DLT_IEEE802_11_RADIO_AVS:
2518 * 802.11 with radio, but not radiotap.
2520 * Offer this, and select it as the new mode
2521 * unless we've already found the radiotap DLT_.
2523 if (new_dlt != DLT_IEEE802_11_RADIO)
2524 new_dlt = bdlp->bfl_list[i];
2525 break;
2527 case DLT_IEEE802_11_RADIO:
2529 * 802.11 with radiotap.
2531 * Offer this, and select it as the new mode.
2533 new_dlt = bdlp->bfl_list[i];
2534 break;
2536 default:
2538 * Not 802.11.
2540 break;
2544 return (new_dlt);
2546 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2548 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
2550 * Remove DLT_EN10MB from the list of DLT_ values, as we're in monitor mode,
2551 * and DLT_EN10MB isn't supported in monitor mode.
2553 static void
2554 remove_en(pcap_t *p)
2556 int i, j;
2559 * Scan the list of DLT_ values and discard DLT_EN10MB.
2561 j = 0;
2562 for (i = 0; i < p->dlt_count; i++) {
2563 switch (p->dlt_list[i]) {
2565 case DLT_EN10MB:
2567 * Don't offer this one.
2569 continue;
2571 default:
2573 * Just copy this mode over.
2575 break;
2579 * Copy this DLT_ value to its new position.
2581 p->dlt_list[j] = p->dlt_list[i];
2582 j++;
2586 * Set the DLT_ count to the number of entries we copied.
2588 p->dlt_count = j;
2592 * Remove 802.11 link-layer types from the list of DLT_ values, as
2593 * we're not in monitor mode, and those DLT_ values will switch us
2594 * to monitor mode.
2596 static void
2597 remove_802_11(pcap_t *p)
2599 int i, j;
2602 * Scan the list of DLT_ values and discard 802.11 values.
2604 j = 0;
2605 for (i = 0; i < p->dlt_count; i++) {
2606 switch (p->dlt_list[i]) {
2608 case DLT_IEEE802_11:
2609 case DLT_PRISM_HEADER:
2610 case DLT_AIRONET_HEADER:
2611 case DLT_IEEE802_11_RADIO:
2612 case DLT_IEEE802_11_RADIO_AVS:
2614 * 802.11. Don't offer this one.
2616 continue;
2618 default:
2620 * Just copy this mode over.
2622 break;
2626 * Copy this DLT_ value to its new position.
2628 p->dlt_list[j] = p->dlt_list[i];
2629 j++;
2633 * Set the DLT_ count to the number of entries we copied.
2635 p->dlt_count = j;
2637 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
2639 static int
2640 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
2642 struct pcap_bpf *pb = p->priv;
2645 * Free any user-mode filter we might happen to have installed.
2647 pcap_freecode(&p->fcode);
2650 * Try to install the kernel filter.
2652 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
2654 * It worked.
2656 pb->filtering_in_kernel = 1; /* filtering in the kernel */
2659 * Discard any previously-received packets, as they might
2660 * have passed whatever filter was formerly in effect, but
2661 * might not pass this filter (BIOCSETF discards packets
2662 * buffered in the kernel, so you can lose packets in any
2663 * case).
2665 p->cc = 0;
2666 return (0);
2670 * We failed.
2672 * If it failed with EINVAL, that's probably because the program
2673 * is invalid or too big. Validate it ourselves; if we like it
2674 * (we currently allow backward branches, to support protochain),
2675 * run it in userland. (There's no notion of "too big" for
2676 * userland.)
2678 * Otherwise, just give up.
2679 * XXX - if the copy of the program into the kernel failed,
2680 * we will get EINVAL rather than, say, EFAULT on at least
2681 * some kernels.
2683 if (errno != EINVAL) {
2684 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2685 pcap_strerror(errno));
2686 return (-1);
2690 * install_bpf_program() validates the program.
2692 * XXX - what if we already have a filter in the kernel?
2694 if (install_bpf_program(p, fp) < 0)
2695 return (-1);
2696 pb->filtering_in_kernel = 0; /* filtering in userland */
2697 return (0);
2701 * Set direction flag: Which packets do we accept on a forwarding
2702 * single device? IN, OUT or both?
2704 static int
2705 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
2707 #if defined(BIOCSDIRECTION)
2708 u_int direction;
2710 direction = (d == PCAP_D_IN) ? BPF_D_IN :
2711 ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
2712 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
2713 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2714 "Cannot set direction to %s: %s",
2715 (d == PCAP_D_IN) ? "PCAP_D_IN" :
2716 ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
2717 strerror(errno));
2718 return (-1);
2720 return (0);
2721 #elif defined(BIOCSSEESENT)
2722 u_int seesent;
2725 * We don't support PCAP_D_OUT.
2727 if (d == PCAP_D_OUT) {
2728 snprintf(p->errbuf, sizeof(p->errbuf),
2729 "Setting direction to PCAP_D_OUT is not supported on BPF");
2730 return -1;
2733 seesent = (d == PCAP_D_INOUT);
2734 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
2735 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2736 "Cannot set direction to %s: %s",
2737 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
2738 strerror(errno));
2739 return (-1);
2741 return (0);
2742 #else
2743 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2744 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
2745 return (-1);
2746 #endif
2749 static int
2750 pcap_set_datalink_bpf(pcap_t *p, int dlt)
2752 #ifdef BIOCSDLT
2753 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
2754 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2755 "Cannot set DLT %d: %s", dlt, strerror(errno));
2756 return (-1);
2758 #endif
2759 return (0);