Updates to Tomato RAF including NGINX && PHP
[tomato.git] / release / src / router / libpcap / pcap-bpf.c
blobdf5849cf2b8fdd430e9ba82928d6d88b28c14d06
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.
21 #ifndef lint
22 static const char rcsid[] _U_ =
23 "@(#) $Header: /tcpdump/master/libpcap/pcap-bpf.c,v 1.116 2008-09-16 18:42:29 guy Exp $ (LBL)";
24 #endif
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
30 #include <sys/param.h> /* optionally get BSD define */
31 #ifdef HAVE_ZEROCOPY_BPF
32 #include <sys/mman.h>
33 #endif
34 #include <sys/socket.h>
35 #include <time.h>
37 * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
39 * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
40 * at least on *BSD and Mac OS X, it also defines various SIOC ioctls -
41 * we could include <sys/sockio.h>, but if we're already including
42 * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
43 * there's not much point in doing so.
45 * If we have <sys/ioccom.h>, we include it as well, to handle systems
46 * such as Solaris which don't arrange to include <sys/ioccom.h> if you
47 * include <sys/ioctl.h>
49 #include <sys/ioctl.h>
50 #ifdef HAVE_SYS_IOCCOM_H
51 #include <sys/ioccom.h>
52 #endif
53 #include <sys/utsname.h>
55 #ifdef HAVE_ZEROCOPY_BPF
56 #include <machine/atomic.h>
57 #endif
59 #include <net/if.h>
61 #ifdef _AIX
64 * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
65 * native OS version, as we need "struct bpf_config" from it.
67 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
69 #include <sys/types.h>
72 * Prevent bpf.h from redefining the DLT_ values to their
73 * IFT_ values, as we're going to return the standard libpcap
74 * values, not IBM's non-standard IFT_ values.
76 #undef _AIX
77 #include <net/bpf.h>
78 #define _AIX
80 #include <net/if_types.h> /* for IFT_ values */
81 #include <sys/sysconfig.h>
82 #include <sys/device.h>
83 #include <sys/cfgodm.h>
84 #include <cf.h>
86 #ifdef __64BIT__
87 #define domakedev makedev64
88 #define getmajor major64
89 #define bpf_hdr bpf_hdr32
90 #else /* __64BIT__ */
91 #define domakedev makedev
92 #define getmajor major
93 #endif /* __64BIT__ */
95 #define BPF_NAME "bpf"
96 #define BPF_MINORS 4
97 #define DRIVER_PATH "/usr/lib/drivers"
98 #define BPF_NODE "/dev/bpf"
99 static int bpfloadedflag = 0;
100 static int odmlockid = 0;
102 static int bpf_load(char *errbuf);
104 #else /* _AIX */
106 #include <net/bpf.h>
108 #endif /* _AIX */
110 #include <ctype.h>
111 #include <fcntl.h>
112 #include <errno.h>
113 #include <netdb.h>
114 #include <stdio.h>
115 #include <stdlib.h>
116 #include <string.h>
117 #include <unistd.h>
119 #ifdef HAVE_NET_IF_MEDIA_H
120 # include <net/if_media.h>
121 #endif
123 #include "pcap-int.h"
125 #ifdef HAVE_DAG_API
126 #include "pcap-dag.h"
127 #endif /* HAVE_DAG_API */
129 #ifdef HAVE_SNF_API
130 #include "pcap-snf.h"
131 #endif /* HAVE_SNF_API */
133 #ifdef HAVE_OS_PROTO_H
134 #include "os-proto.h"
135 #endif
137 #ifdef HAVE_REMOTE
138 #include <pcap-remote.h>
139 #endif /* HAVE_REMOTE */
141 #ifdef BIOCGDLTLIST
142 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
143 #define HAVE_BSD_IEEE80211
144 # endif
146 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
147 static int find_802_11(struct bpf_dltlist *);
149 # ifdef HAVE_BSD_IEEE80211
150 static int monitor_mode(pcap_t *, int);
151 # endif
153 # if defined(__APPLE__)
154 static void remove_en(pcap_t *);
155 static void remove_802_11(pcap_t *);
156 # endif
158 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
160 #endif /* BIOCGDLTLIST */
162 #if defined(sun) && defined(LIFNAMSIZ) && defined(lifr_zoneid)
163 #include <zone.h>
164 #endif
167 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
168 * don't get DLT_DOCSIS defined.
170 #ifndef DLT_DOCSIS
171 #define DLT_DOCSIS 143
172 #endif
175 * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
176 * defined, even though some of them are used by various Airport drivers.
178 #ifndef DLT_PRISM_HEADER
179 #define DLT_PRISM_HEADER 119
180 #endif
181 #ifndef DLT_AIRONET_HEADER
182 #define DLT_AIRONET_HEADER 120
183 #endif
184 #ifndef DLT_IEEE802_11_RADIO
185 #define DLT_IEEE802_11_RADIO 127
186 #endif
187 #ifndef DLT_IEEE802_11_RADIO_AVS
188 #define DLT_IEEE802_11_RADIO_AVS 163
189 #endif
191 static int pcap_can_set_rfmon_bpf(pcap_t *p);
192 static int pcap_activate_bpf(pcap_t *p);
193 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
194 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
195 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
198 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
199 * p->md.timeout so we don't call select(2) if the pcap handle is in non-
200 * blocking mode. We preserve the timeout supplied by pcap_open functions
201 * to make sure it does not get clobbered if the pcap handle moves between
202 * blocking and non-blocking mode.
204 static int
205 pcap_getnonblock_bpf(pcap_t *p, char *errbuf)
207 #ifdef HAVE_ZEROCOPY_BPF
208 if (p->md.zerocopy) {
210 * Use a negative value for the timeout to represent that the
211 * pcap handle is in non-blocking mode.
213 return (p->md.timeout < 0);
215 #endif
216 return (pcap_getnonblock_fd(p, errbuf));
219 static int
220 pcap_setnonblock_bpf(pcap_t *p, int nonblock, char *errbuf)
222 #ifdef HAVE_ZEROCOPY_BPF
223 if (p->md.zerocopy) {
225 * Map each value to the corresponding 2's complement, to
226 * preserve the timeout value provided with pcap_set_timeout.
227 * (from pcap-linux.c).
229 if (nonblock) {
230 if (p->md.timeout >= 0) {
232 * Timeout is non-negative, so we're not
233 * currently in non-blocking mode; set it
234 * to the 2's complement, to make it
235 * negative, as an indication that we're
236 * in non-blocking mode.
238 p->md.timeout = p->md.timeout * -1 - 1;
240 } else {
241 if (p->md.timeout < 0) {
243 * Timeout is negative, so we're currently
244 * in blocking mode; reverse the previous
245 * operation, to make the timeout non-negative
246 * again.
248 p->md.timeout = (p->md.timeout + 1) * -1;
251 return (0);
253 #endif
254 return (pcap_setnonblock_fd(p, nonblock, errbuf));
257 #ifdef HAVE_ZEROCOPY_BPF
259 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
260 * shared memory buffers.
262 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
263 * and set up p->buffer and cc to reflect one if available. Notice that if
264 * there was no prior buffer, we select zbuf1 as this will be the first
265 * buffer filled for a fresh BPF session.
267 static int
268 pcap_next_zbuf_shm(pcap_t *p, int *cc)
270 struct bpf_zbuf_header *bzh;
272 if (p->md.zbuffer == p->md.zbuf2 || p->md.zbuffer == NULL) {
273 bzh = (struct bpf_zbuf_header *)p->md.zbuf1;
274 if (bzh->bzh_user_gen !=
275 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
276 p->md.bzh = bzh;
277 p->md.zbuffer = (u_char *)p->md.zbuf1;
278 p->buffer = p->md.zbuffer + sizeof(*bzh);
279 *cc = bzh->bzh_kernel_len;
280 return (1);
282 } else if (p->md.zbuffer == p->md.zbuf1) {
283 bzh = (struct bpf_zbuf_header *)p->md.zbuf2;
284 if (bzh->bzh_user_gen !=
285 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
286 p->md.bzh = bzh;
287 p->md.zbuffer = (u_char *)p->md.zbuf2;
288 p->buffer = p->md.zbuffer + sizeof(*bzh);
289 *cc = bzh->bzh_kernel_len;
290 return (1);
293 *cc = 0;
294 return (0);
298 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
299 * select() for data or a timeout, and possibly force rotation of the buffer
300 * in the event we time out or are in immediate mode. Invoke the shared
301 * memory check before doing system calls in order to avoid doing avoidable
302 * work.
304 static int
305 pcap_next_zbuf(pcap_t *p, int *cc)
307 struct bpf_zbuf bz;
308 struct timeval tv;
309 struct timespec cur;
310 fd_set r_set;
311 int data, r;
312 int expire, tmout;
314 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
316 * Start out by seeing whether anything is waiting by checking the
317 * next shared memory buffer for data.
319 data = pcap_next_zbuf_shm(p, cc);
320 if (data)
321 return (data);
323 * If a previous sleep was interrupted due to signal delivery, make
324 * sure that the timeout gets adjusted accordingly. This requires
325 * that we analyze when the timeout should be been expired, and
326 * subtract the current time from that. If after this operation,
327 * our timeout is less then or equal to zero, handle it like a
328 * regular timeout.
330 tmout = p->md.timeout;
331 if (tmout)
332 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
333 if (p->md.interrupted && p->md.timeout) {
334 expire = TSTOMILLI(&p->md.firstsel) + p->md.timeout;
335 tmout = expire - TSTOMILLI(&cur);
336 #undef TSTOMILLI
337 if (tmout <= 0) {
338 p->md.interrupted = 0;
339 data = pcap_next_zbuf_shm(p, cc);
340 if (data)
341 return (data);
342 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
343 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
344 "BIOCROTZBUF: %s", strerror(errno));
345 return (PCAP_ERROR);
347 return (pcap_next_zbuf_shm(p, cc));
351 * No data in the buffer, so must use select() to wait for data or
352 * the next timeout. Note that we only call select if the handle
353 * is in blocking mode.
355 if (p->md.timeout >= 0) {
356 FD_ZERO(&r_set);
357 FD_SET(p->fd, &r_set);
358 if (tmout != 0) {
359 tv.tv_sec = tmout / 1000;
360 tv.tv_usec = (tmout * 1000) % 1000000;
362 r = select(p->fd + 1, &r_set, NULL, NULL,
363 p->md.timeout != 0 ? &tv : NULL);
364 if (r < 0 && errno == EINTR) {
365 if (!p->md.interrupted && p->md.timeout) {
366 p->md.interrupted = 1;
367 p->md.firstsel = cur;
369 return (0);
370 } else if (r < 0) {
371 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
372 "select: %s", strerror(errno));
373 return (PCAP_ERROR);
376 p->md.interrupted = 0;
378 * Check again for data, which may exist now that we've either been
379 * woken up as a result of data or timed out. Try the "there's data"
380 * case first since it doesn't require a system call.
382 data = pcap_next_zbuf_shm(p, cc);
383 if (data)
384 return (data);
386 * Try forcing a buffer rotation to dislodge timed out or immediate
387 * data.
389 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
390 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
391 "BIOCROTZBUF: %s", strerror(errno));
392 return (PCAP_ERROR);
394 return (pcap_next_zbuf_shm(p, cc));
398 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
399 * that we know which buffer to use next time around.
401 static int
402 pcap_ack_zbuf(pcap_t *p)
405 atomic_store_rel_int(&p->md.bzh->bzh_user_gen,
406 p->md.bzh->bzh_kernel_gen);
407 p->md.bzh = NULL;
408 p->buffer = NULL;
409 return (0);
411 #endif /* HAVE_ZEROCOPY_BPF */
413 pcap_t *
414 pcap_create(const char *device, char *ebuf)
416 pcap_t *p;
418 #ifdef HAVE_REMOTE
420 Retrofit; we have to make older applications compatible with the remote capture
421 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
422 Obviously, we cannot exploit all the new features; for instance, we cannot
423 send authentication, we cannot use a UDP data connection, and so on.
426 char host[PCAP_BUF_SIZE + 1];
427 char port[PCAP_BUF_SIZE + 1];
428 char name[PCAP_BUF_SIZE + 1];
429 int srctype;
431 if (pcap_parsesrcstr(device, &srctype, host, port, name, ebuf) )
432 return NULL;
434 if (srctype == PCAP_SRC_IFREMOTE)
436 p= pcap_opensource_remote(device, NULL, ebuf);
438 if (p == NULL)
439 return NULL;
441 p->snapshot= snaplen;
442 p->timeout= to_ms;
443 p->rmt_flags= (promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0;
445 return p;
448 if (srctype == PCAP_SRC_IFLOCAL)
451 * If it starts with rpcap://, cut down the string
453 if (strncmp(p->opt.source, PCAP_SRC_IF_STRING, strlen(PCAP_SRC_IF_STRING)) == 0)
455 size_t len = strlen(p->opt.source) - strlen(PCAP_SRC_IF_STRING) + 1;
456 char *new_string;
458 * allocate a new string and free the old one
460 if (len > 0)
462 new_string = (char*)malloc(len);
463 if (new_string != NULL)
465 char *tmp;
466 strcpy(new_string, p->opt.source + strlen(PCAP_SRC_IF_STRING));
467 tmp = p->opt.source;
468 p->opt.source = new_string;
469 free(tmp);
475 #endif /* HAVE_REMOTE */
477 #ifdef HAVE_DAG_API
478 if (strstr(device, "dag"))
479 return (dag_create(device, ebuf));
480 #endif /* HAVE_DAG_API */
481 #ifdef HAVE_SNF_API
482 if (strstr(device, "snf"))
483 return (snf_create(device, ebuf));
484 #endif /* HAVE_SNF_API */
486 p = pcap_create_common(device, ebuf);
487 if (p == NULL)
488 return (NULL);
490 p->activate_op = pcap_activate_bpf;
491 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
492 return (p);
496 * On success, returns a file descriptor for a BPF device.
497 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
499 static int
500 bpf_open(pcap_t *p)
502 int fd;
503 #ifdef HAVE_CLONING_BPF
504 static const char device[] = "/dev/bpf";
505 #else
506 int n = 0;
507 char device[sizeof "/dev/bpf0000000000"];
508 #endif
510 #ifdef _AIX
512 * Load the bpf driver, if it isn't already loaded,
513 * and create the BPF device entries, if they don't
514 * already exist.
516 if (bpf_load(p->errbuf) == PCAP_ERROR)
517 return (PCAP_ERROR);
518 #endif
520 #ifdef HAVE_CLONING_BPF
521 if ((fd = open(device, O_RDWR)) == -1 &&
522 (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
523 if (errno == EACCES)
524 fd = PCAP_ERROR_PERM_DENIED;
525 else
526 fd = PCAP_ERROR;
527 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
528 "(cannot open device) %s: %s", device, pcap_strerror(errno));
530 #else
532 * Go through all the minors and find one that isn't in use.
534 do {
535 (void)snprintf(device, sizeof(device), "/dev/bpf%d", n++);
537 * Initially try a read/write open (to allow the inject
538 * method to work). If that fails due to permission
539 * issues, fall back to read-only. This allows a
540 * non-root user to be granted specific access to pcap
541 * capabilities via file permissions.
543 * XXX - we should have an API that has a flag that
544 * controls whether to open read-only or read-write,
545 * so that denial of permission to send (or inability
546 * to send, if sending packets isn't supported on
547 * the device in question) can be indicated at open
548 * time.
550 fd = open(device, O_RDWR);
551 if (fd == -1 && errno == EACCES)
552 fd = open(device, O_RDONLY);
553 } while (fd < 0 && errno == EBUSY);
556 * XXX better message for all minors used
558 if (fd < 0) {
559 switch (errno) {
561 case ENOENT:
562 fd = PCAP_ERROR;
563 if (n == 1) {
565 * /dev/bpf0 doesn't exist, which
566 * means we probably have no BPF
567 * devices.
569 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
570 "(there are no BPF devices)");
571 } else {
573 * We got EBUSY on at least one
574 * BPF device, so we have BPF
575 * devices, but all the ones
576 * that exist are busy.
578 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
579 "(all BPF devices are busy)");
581 break;
583 case EACCES:
585 * Got EACCES on the last device we tried,
586 * and EBUSY on all devices before that,
587 * if any.
589 fd = PCAP_ERROR_PERM_DENIED;
590 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
591 "(cannot open BPF device) %s: %s", device,
592 pcap_strerror(errno));
593 break;
595 default:
597 * Some other problem.
599 fd = PCAP_ERROR;
600 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
601 "(cannot open BPF device) %s: %s", device,
602 pcap_strerror(errno));
603 break;
606 #endif
608 return (fd);
611 #ifdef BIOCGDLTLIST
612 static int
613 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
615 memset(bdlp, 0, sizeof(*bdlp));
616 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
617 u_int i;
618 int is_ethernet;
620 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
621 if (bdlp->bfl_list == NULL) {
622 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
623 pcap_strerror(errno));
624 return (PCAP_ERROR);
627 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
628 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
629 "BIOCGDLTLIST: %s", pcap_strerror(errno));
630 free(bdlp->bfl_list);
631 return (PCAP_ERROR);
635 * OK, for real Ethernet devices, add DLT_DOCSIS to the
636 * list, so that an application can let you choose it,
637 * in case you're capturing DOCSIS traffic that a Cisco
638 * Cable Modem Termination System is putting out onto
639 * an Ethernet (it doesn't put an Ethernet header onto
640 * the wire, it puts raw DOCSIS frames out on the wire
641 * inside the low-level Ethernet framing).
643 * A "real Ethernet device" is defined here as a device
644 * that has a link-layer type of DLT_EN10MB and that has
645 * no alternate link-layer types; that's done to exclude
646 * 802.11 interfaces (which might or might not be the
647 * right thing to do, but I suspect it is - Ethernet <->
648 * 802.11 bridges would probably badly mishandle frames
649 * that don't have Ethernet headers).
651 * On Solaris with BPF, Ethernet devices also offer
652 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
653 * treat it as an indication that the device isn't an
654 * Ethernet.
656 if (v == DLT_EN10MB) {
657 is_ethernet = 1;
658 for (i = 0; i < bdlp->bfl_len; i++) {
659 if (bdlp->bfl_list[i] != DLT_EN10MB
660 #ifdef DLT_IPNET
661 && bdlp->bfl_list[i] != DLT_IPNET
662 #endif
664 is_ethernet = 0;
665 break;
668 if (is_ethernet) {
670 * We reserved one more slot at the end of
671 * the list.
673 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
674 bdlp->bfl_len++;
677 } else {
679 * EINVAL just means "we don't support this ioctl on
680 * this device"; don't treat it as an error.
682 if (errno != EINVAL) {
683 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
684 "BIOCGDLTLIST: %s", pcap_strerror(errno));
685 return (PCAP_ERROR);
688 return (0);
690 #endif
692 static int
693 pcap_can_set_rfmon_bpf(pcap_t *p)
695 #if defined(__APPLE__)
696 struct utsname osinfo;
697 struct ifreq ifr;
698 int fd;
699 #ifdef BIOCGDLTLIST
700 struct bpf_dltlist bdl;
701 #endif
704 * The joys of monitor mode on OS X.
706 * Prior to 10.4, it's not supported at all.
708 * In 10.4, if adapter enN supports monitor mode, there's a
709 * wltN adapter corresponding to it; you open it, instead of
710 * enN, to get monitor mode. You get whatever link-layer
711 * headers it supplies.
713 * In 10.5, and, we assume, later releases, if adapter enN
714 * supports monitor mode, it offers, among its selectable
715 * DLT_ values, values that let you get the 802.11 header;
716 * selecting one of those values puts the adapter into monitor
717 * mode (i.e., you can't get 802.11 headers except in monitor
718 * mode, and you can't get Ethernet headers in monitor mode).
720 if (uname(&osinfo) == -1) {
722 * Can't get the OS version; just say "no".
724 return (0);
727 * We assume osinfo.sysname is "Darwin", because
728 * __APPLE__ is defined. We just check the version.
730 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
732 * 10.3 (Darwin 7.x) or earlier.
733 * Monitor mode not supported.
735 return (0);
737 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
739 * 10.4 (Darwin 8.x). s/en/wlt/, and check
740 * whether the device exists.
742 if (strncmp(p->opt.source, "en", 2) != 0) {
744 * Not an enN device; no monitor mode.
746 return (0);
748 fd = socket(AF_INET, SOCK_DGRAM, 0);
749 if (fd == -1) {
750 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
751 "socket: %s", pcap_strerror(errno));
752 return (PCAP_ERROR);
754 strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
755 strlcat(ifr.ifr_name, p->opt.source + 2, sizeof(ifr.ifr_name));
756 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
758 * No such device?
760 close(fd);
761 return (0);
763 close(fd);
764 return (1);
767 #ifdef BIOCGDLTLIST
769 * Everything else is 10.5 or later; for those,
770 * we just open the enN device, and check whether
771 * we have any 802.11 devices.
773 * First, open a BPF device.
775 fd = bpf_open(p);
776 if (fd < 0)
777 return (fd); /* fd is the appropriate error code */
780 * Now bind to the device.
782 (void)strncpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
783 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
784 switch (errno) {
786 case ENXIO:
788 * There's no such device.
790 close(fd);
791 return (PCAP_ERROR_NO_SUCH_DEVICE);
793 case ENETDOWN:
795 * Return a "network down" indication, so that
796 * the application can report that rather than
797 * saying we had a mysterious failure and
798 * suggest that they report a problem to the
799 * libpcap developers.
801 close(fd);
802 return (PCAP_ERROR_IFACE_NOT_UP);
804 default:
805 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
806 "BIOCSETIF: %s: %s",
807 p->opt.source, pcap_strerror(errno));
808 close(fd);
809 return (PCAP_ERROR);
814 * We know the default link type -- now determine all the DLTs
815 * this interface supports. If this fails with EINVAL, it's
816 * not fatal; we just don't get to use the feature later.
817 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
818 * as the default DLT for this adapter.)
820 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
821 close(fd);
822 return (PCAP_ERROR);
824 if (find_802_11(&bdl) != -1) {
826 * We have an 802.11 DLT, so we can set monitor mode.
828 free(bdl.bfl_list);
829 close(fd);
830 return (1);
832 free(bdl.bfl_list);
833 #endif /* BIOCGDLTLIST */
834 return (0);
835 #elif defined(HAVE_BSD_IEEE80211)
836 int ret;
838 ret = monitor_mode(p, 0);
839 if (ret == PCAP_ERROR_RFMON_NOTSUP)
840 return (0); /* not an error, just a "can't do" */
841 if (ret == 0)
842 return (1); /* success */
843 return (ret);
844 #else
845 return (0);
846 #endif
849 static int
850 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
852 struct bpf_stat s;
855 * "ps_recv" counts packets handed to the filter, not packets
856 * that passed the filter. This includes packets later dropped
857 * because we ran out of buffer space.
859 * "ps_drop" counts packets dropped inside the BPF device
860 * because we ran out of buffer space. It doesn't count
861 * packets dropped by the interface driver. It counts
862 * only packets that passed the filter.
864 * Both statistics include packets not yet read from the kernel
865 * by libpcap, and thus not yet seen by the application.
867 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
868 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
869 pcap_strerror(errno));
870 return (PCAP_ERROR);
873 ps->ps_recv = s.bs_recv;
874 ps->ps_drop = s.bs_drop;
875 ps->ps_ifdrop = 0;
876 return (0);
879 static int
880 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
882 int cc;
883 int n = 0;
884 register u_char *bp, *ep;
885 u_char *datap;
886 #ifdef PCAP_FDDIPAD
887 register int pad;
888 #endif
889 #ifdef HAVE_ZEROCOPY_BPF
890 int i;
891 #endif
893 again:
895 * Has "pcap_breakloop()" been called?
897 if (p->break_loop) {
899 * Yes - clear the flag that indicates that it
900 * has, and return PCAP_ERROR_BREAK to indicate
901 * that we were told to break out of the loop.
903 p->break_loop = 0;
904 return (PCAP_ERROR_BREAK);
906 cc = p->cc;
907 if (p->cc == 0) {
909 * When reading without zero-copy from a file descriptor, we
910 * use a single buffer and return a length of data in the
911 * buffer. With zero-copy, we update the p->buffer pointer
912 * to point at whatever underlying buffer contains the next
913 * data and update cc to reflect the data found in the
914 * buffer.
916 #ifdef HAVE_ZEROCOPY_BPF
917 if (p->md.zerocopy) {
918 if (p->buffer != NULL)
919 pcap_ack_zbuf(p);
920 i = pcap_next_zbuf(p, &cc);
921 if (i == 0)
922 goto again;
923 if (i < 0)
924 return (PCAP_ERROR);
925 } else
926 #endif
928 cc = read(p->fd, (char *)p->buffer, p->bufsize);
930 if (cc < 0) {
931 /* Don't choke when we get ptraced */
932 switch (errno) {
934 case EINTR:
935 goto again;
937 #ifdef _AIX
938 case EFAULT:
940 * Sigh. More AIX wonderfulness.
942 * For some unknown reason the uiomove()
943 * operation in the bpf kernel extension
944 * used to copy the buffer into user
945 * space sometimes returns EFAULT. I have
946 * no idea why this is the case given that
947 * a kernel debugger shows the user buffer
948 * is correct. This problem appears to
949 * be mostly mitigated by the memset of
950 * the buffer before it is first used.
951 * Very strange.... Shaun Clowes
953 * In any case this means that we shouldn't
954 * treat EFAULT as a fatal error; as we
955 * don't have an API for returning
956 * a "some packets were dropped since
957 * the last packet you saw" indication,
958 * we just ignore EFAULT and keep reading.
960 goto again;
961 #endif
963 case EWOULDBLOCK:
964 return (0);
966 case ENXIO:
968 * The device on which we're capturing
969 * went away.
971 * XXX - we should really return
972 * PCAP_ERROR_IFACE_NOT_UP, but
973 * pcap_dispatch() etc. aren't
974 * defined to retur that.
976 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
977 "The interface went down");
978 return (PCAP_ERROR);
980 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
982 * Due to a SunOS bug, after 2^31 bytes, the kernel
983 * file offset overflows and read fails with EINVAL.
984 * The lseek() to 0 will fix things.
986 case EINVAL:
987 if (lseek(p->fd, 0L, SEEK_CUR) +
988 p->bufsize < 0) {
989 (void)lseek(p->fd, 0L, SEEK_SET);
990 goto again;
992 /* fall through */
993 #endif
995 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
996 pcap_strerror(errno));
997 return (PCAP_ERROR);
999 bp = p->buffer;
1000 } else
1001 bp = p->bp;
1004 * Loop through each packet.
1006 #define bhp ((struct bpf_hdr *)bp)
1007 ep = bp + cc;
1008 #ifdef PCAP_FDDIPAD
1009 pad = p->fddipad;
1010 #endif
1011 while (bp < ep) {
1012 register int caplen, hdrlen;
1015 * Has "pcap_breakloop()" been called?
1016 * If so, return immediately - if we haven't read any
1017 * packets, clear the flag and return PCAP_ERROR_BREAK
1018 * to indicate that we were told to break out of the loop,
1019 * otherwise leave the flag set, so that the *next* call
1020 * will break out of the loop without having read any
1021 * packets, and return the number of packets we've
1022 * processed so far.
1024 if (p->break_loop) {
1025 p->bp = bp;
1026 p->cc = ep - bp;
1028 * ep is set based on the return value of read(),
1029 * but read() from a BPF device doesn't necessarily
1030 * return a value that's a multiple of the alignment
1031 * value for BPF_WORDALIGN(). However, whenever we
1032 * increment bp, we round up the increment value by
1033 * a value rounded up by BPF_WORDALIGN(), so we
1034 * could increment bp past ep after processing the
1035 * last packet in the buffer.
1037 * We treat ep < bp as an indication that this
1038 * happened, and just set p->cc to 0.
1040 if (p->cc < 0)
1041 p->cc = 0;
1042 if (n == 0) {
1043 p->break_loop = 0;
1044 return (PCAP_ERROR_BREAK);
1045 } else
1046 return (n);
1049 caplen = bhp->bh_caplen;
1050 hdrlen = bhp->bh_hdrlen;
1051 datap = bp + hdrlen;
1053 * Short-circuit evaluation: if using BPF filter
1054 * in kernel, no need to do it now - we already know
1055 * the packet passed the filter.
1057 #ifdef PCAP_FDDIPAD
1058 * Note: the filter code was generated assuming
1059 * that p->fddipad was the amount of padding
1060 * before the header, as that's what's required
1061 * in the kernel, so we run the filter before
1062 * skipping that padding.
1063 #endif
1065 if (p->md.use_bpf ||
1066 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1067 struct pcap_pkthdr pkthdr;
1069 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1070 #ifdef _AIX
1072 * AIX's BPF returns seconds/nanoseconds time
1073 * stamps, not seconds/microseconds time stamps.
1075 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1076 #else
1077 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1078 #endif
1079 #ifdef PCAP_FDDIPAD
1080 if (caplen > pad)
1081 pkthdr.caplen = caplen - pad;
1082 else
1083 pkthdr.caplen = 0;
1084 if (bhp->bh_datalen > pad)
1085 pkthdr.len = bhp->bh_datalen - pad;
1086 else
1087 pkthdr.len = 0;
1088 datap += pad;
1089 #else
1090 pkthdr.caplen = caplen;
1091 pkthdr.len = bhp->bh_datalen;
1092 #endif
1093 (*callback)(user, &pkthdr, datap);
1094 bp += BPF_WORDALIGN(caplen + hdrlen);
1095 if (++n >= cnt && cnt > 0) {
1096 p->bp = bp;
1097 p->cc = ep - bp;
1099 * See comment above about p->cc < 0.
1101 if (p->cc < 0)
1102 p->cc = 0;
1103 return (n);
1105 } else {
1107 * Skip this packet.
1109 bp += BPF_WORDALIGN(caplen + hdrlen);
1112 #undef bhp
1113 p->cc = 0;
1114 return (n);
1117 static int
1118 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1120 int ret;
1122 ret = write(p->fd, buf, size);
1123 #ifdef __APPLE__
1124 if (ret == -1 && errno == EAFNOSUPPORT) {
1126 * In Mac OS X, there's a bug wherein setting the
1127 * BIOCSHDRCMPLT flag causes writes to fail; see,
1128 * for example:
1130 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1132 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
1133 * assume it's due to that bug, and turn off that flag
1134 * and try again. If we succeed, it either means that
1135 * somebody applied the fix from that URL, or other patches
1136 * for that bug from
1138 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1140 * and are running a Darwin kernel with those fixes, or
1141 * that Apple fixed the problem in some OS X release.
1143 u_int spoof_eth_src = 0;
1145 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1146 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1147 "send: can't turn off BIOCSHDRCMPLT: %s",
1148 pcap_strerror(errno));
1149 return (PCAP_ERROR);
1153 * Now try the write again.
1155 ret = write(p->fd, buf, size);
1157 #endif /* __APPLE__ */
1158 if (ret == -1) {
1159 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1160 pcap_strerror(errno));
1161 return (PCAP_ERROR);
1163 return (ret);
1166 #ifdef _AIX
1167 static int
1168 bpf_odminit(char *errbuf)
1170 char *errstr;
1172 if (odm_initialize() == -1) {
1173 if (odm_err_msg(odmerrno, &errstr) == -1)
1174 errstr = "Unknown error";
1175 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1176 "bpf_load: odm_initialize failed: %s",
1177 errstr);
1178 return (PCAP_ERROR);
1181 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1182 if (odm_err_msg(odmerrno, &errstr) == -1)
1183 errstr = "Unknown error";
1184 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1185 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1186 errstr);
1187 (void)odm_terminate();
1188 return (PCAP_ERROR);
1191 return (0);
1194 static int
1195 bpf_odmcleanup(char *errbuf)
1197 char *errstr;
1199 if (odm_unlock(odmlockid) == -1) {
1200 if (errbuf != NULL) {
1201 if (odm_err_msg(odmerrno, &errstr) == -1)
1202 errstr = "Unknown error";
1203 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1204 "bpf_load: odm_unlock failed: %s",
1205 errstr);
1207 return (PCAP_ERROR);
1210 if (odm_terminate() == -1) {
1211 if (errbuf != NULL) {
1212 if (odm_err_msg(odmerrno, &errstr) == -1)
1213 errstr = "Unknown error";
1214 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1215 "bpf_load: odm_terminate failed: %s",
1216 errstr);
1218 return (PCAP_ERROR);
1221 return (0);
1224 static int
1225 bpf_load(char *errbuf)
1227 long major;
1228 int *minors;
1229 int numminors, i, rc;
1230 char buf[1024];
1231 struct stat sbuf;
1232 struct bpf_config cfg_bpf;
1233 struct cfg_load cfg_ld;
1234 struct cfg_kmod cfg_km;
1237 * This is very very close to what happens in the real implementation
1238 * but I've fixed some (unlikely) bug situations.
1240 if (bpfloadedflag)
1241 return (0);
1243 if (bpf_odminit(errbuf) == PCAP_ERROR)
1244 return (PCAP_ERROR);
1246 major = genmajor(BPF_NAME);
1247 if (major == -1) {
1248 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1249 "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1250 (void)bpf_odmcleanup(NULL);
1251 return (PCAP_ERROR);
1254 minors = getminor(major, &numminors, BPF_NAME);
1255 if (!minors) {
1256 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1257 if (!minors) {
1258 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1259 "bpf_load: genminor failed: %s",
1260 pcap_strerror(errno));
1261 (void)bpf_odmcleanup(NULL);
1262 return (PCAP_ERROR);
1266 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1267 return (PCAP_ERROR);
1269 rc = stat(BPF_NODE "0", &sbuf);
1270 if (rc == -1 && errno != ENOENT) {
1271 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1272 "bpf_load: can't stat %s: %s",
1273 BPF_NODE "0", pcap_strerror(errno));
1274 return (PCAP_ERROR);
1277 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1278 for (i = 0; i < BPF_MINORS; i++) {
1279 sprintf(buf, "%s%d", BPF_NODE, i);
1280 unlink(buf);
1281 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1282 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1283 "bpf_load: can't mknod %s: %s",
1284 buf, pcap_strerror(errno));
1285 return (PCAP_ERROR);
1290 /* Check if the driver is loaded */
1291 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1292 cfg_ld.path = buf;
1293 sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1294 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1295 (cfg_ld.kmid == 0)) {
1296 /* Driver isn't loaded, load it now */
1297 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1298 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1299 "bpf_load: could not load driver: %s",
1300 strerror(errno));
1301 return (PCAP_ERROR);
1305 /* Configure the driver */
1306 cfg_km.cmd = CFG_INIT;
1307 cfg_km.kmid = cfg_ld.kmid;
1308 cfg_km.mdilen = sizeof(cfg_bpf);
1309 cfg_km.mdiptr = (void *)&cfg_bpf;
1310 for (i = 0; i < BPF_MINORS; i++) {
1311 cfg_bpf.devno = domakedev(major, i);
1312 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1313 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1314 "bpf_load: could not configure driver: %s",
1315 strerror(errno));
1316 return (PCAP_ERROR);
1320 bpfloadedflag = 1;
1322 return (0);
1324 #endif
1327 * Turn off rfmon mode if necessary.
1329 static void
1330 pcap_cleanup_bpf(pcap_t *p)
1332 #ifdef HAVE_BSD_IEEE80211
1333 int sock;
1334 struct ifmediareq req;
1335 struct ifreq ifr;
1336 #endif
1338 if (p->md.must_do_on_close != 0) {
1340 * There's something we have to do when closing this
1341 * pcap_t.
1343 #ifdef HAVE_BSD_IEEE80211
1344 if (p->md.must_do_on_close & MUST_CLEAR_RFMON) {
1346 * We put the interface into rfmon mode;
1347 * take it out of rfmon mode.
1349 * XXX - if somebody else wants it in rfmon
1350 * mode, this code cannot know that, so it'll take
1351 * it out of rfmon mode.
1353 sock = socket(AF_INET, SOCK_DGRAM, 0);
1354 if (sock == -1) {
1355 fprintf(stderr,
1356 "Can't restore interface flags (socket() failed: %s).\n"
1357 "Please adjust manually.\n",
1358 strerror(errno));
1359 } else {
1360 memset(&req, 0, sizeof(req));
1361 strncpy(req.ifm_name, p->md.device,
1362 sizeof(req.ifm_name));
1363 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1364 fprintf(stderr,
1365 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1366 "Please adjust manually.\n",
1367 strerror(errno));
1368 } else {
1369 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1371 * Rfmon mode is currently on;
1372 * turn it off.
1374 memset(&ifr, 0, sizeof(ifr));
1375 (void)strncpy(ifr.ifr_name,
1376 p->md.device,
1377 sizeof(ifr.ifr_name));
1378 ifr.ifr_media =
1379 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1380 if (ioctl(sock, SIOCSIFMEDIA,
1381 &ifr) == -1) {
1382 fprintf(stderr,
1383 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1384 "Please adjust manually.\n",
1385 strerror(errno));
1389 close(sock);
1392 #endif /* HAVE_BSD_IEEE80211 */
1395 * Take this pcap out of the list of pcaps for which we
1396 * have to take the interface out of some mode.
1398 pcap_remove_from_pcaps_to_close(p);
1399 p->md.must_do_on_close = 0;
1402 #ifdef HAVE_ZEROCOPY_BPF
1403 if (p->md.zerocopy) {
1405 * Delete the mappings. Note that p->buffer gets
1406 * initialized to one of the mmapped regions in
1407 * this case, so do not try and free it directly;
1408 * null it out so that pcap_cleanup_live_common()
1409 * doesn't try to free it.
1411 if (p->md.zbuf1 != MAP_FAILED && p->md.zbuf1 != NULL)
1412 (void) munmap(p->md.zbuf1, p->md.zbufsize);
1413 if (p->md.zbuf2 != MAP_FAILED && p->md.zbuf2 != NULL)
1414 (void) munmap(p->md.zbuf2, p->md.zbufsize);
1415 p->buffer = NULL;
1417 #endif
1418 if (p->md.device != NULL) {
1419 free(p->md.device);
1420 p->md.device = NULL;
1422 pcap_cleanup_live_common(p);
1425 static int
1426 check_setif_failure(pcap_t *p, int error)
1428 #ifdef __APPLE__
1429 int fd;
1430 struct ifreq ifr;
1431 int err;
1432 #endif
1434 if (error == ENXIO) {
1436 * No such device exists.
1438 #ifdef __APPLE__
1439 if (p->opt.rfmon && strncmp(p->opt.source, "wlt", 3) == 0) {
1441 * Monitor mode was requested, and we're trying
1442 * to open a "wltN" device. Assume that this
1443 * is 10.4 and that we were asked to open an
1444 * "enN" device; if that device exists, return
1445 * "monitor mode not supported on the device".
1447 fd = socket(AF_INET, SOCK_DGRAM, 0);
1448 if (fd != -1) {
1449 strlcpy(ifr.ifr_name, "en",
1450 sizeof(ifr.ifr_name));
1451 strlcat(ifr.ifr_name, p->opt.source + 3,
1452 sizeof(ifr.ifr_name));
1453 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1455 * We assume this failed because
1456 * the underlying device doesn't
1457 * exist.
1459 err = PCAP_ERROR_NO_SUCH_DEVICE;
1460 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1461 "SIOCGIFFLAGS on %s failed: %s",
1462 ifr.ifr_name, pcap_strerror(errno));
1463 } else {
1465 * The underlying "enN" device
1466 * exists, but there's no
1467 * corresponding "wltN" device;
1468 * that means that the "enN"
1469 * device doesn't support
1470 * monitor mode, probably because
1471 * it's an Ethernet device rather
1472 * than a wireless device.
1474 err = PCAP_ERROR_RFMON_NOTSUP;
1476 close(fd);
1477 } else {
1479 * We can't find out whether there's
1480 * an underlying "enN" device, so
1481 * just report "no such device".
1483 err = PCAP_ERROR_NO_SUCH_DEVICE;
1484 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1485 "socket() failed: %s",
1486 pcap_strerror(errno));
1488 return (err);
1490 #endif
1492 * No such device.
1494 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
1495 pcap_strerror(errno));
1496 return (PCAP_ERROR_NO_SUCH_DEVICE);
1497 } else if (errno == ENETDOWN) {
1499 * Return a "network down" indication, so that
1500 * the application can report that rather than
1501 * saying we had a mysterious failure and
1502 * suggest that they report a problem to the
1503 * libpcap developers.
1505 return (PCAP_ERROR_IFACE_NOT_UP);
1506 } else {
1508 * Some other error; fill in the error string, and
1509 * return PCAP_ERROR.
1511 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1512 p->opt.source, pcap_strerror(errno));
1513 return (PCAP_ERROR);
1518 * Default capture buffer size.
1519 * 32K isn't very much for modern machines with fast networks; we
1520 * pick .5M, as that's the maximum on at least some systems with BPF.
1522 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1523 * read failures under stress, so we leave it as 32K; yet another
1524 * place where AIX's BPF is broken.
1526 #ifdef _AIX
1527 #define DEFAULT_BUFSIZE 32768
1528 #else
1529 #define DEFAULT_BUFSIZE 524288
1530 #endif
1532 static int
1533 pcap_activate_bpf(pcap_t *p)
1535 int status = 0;
1536 int fd;
1537 #ifdef LIFNAMSIZ
1538 char *zonesep;
1539 struct lifreq ifr;
1540 char *ifrname = ifr.lifr_name;
1541 const size_t ifnamsiz = sizeof(ifr.lifr_name);
1542 #else
1543 struct ifreq ifr;
1544 char *ifrname = ifr.ifr_name;
1545 const size_t ifnamsiz = sizeof(ifr.ifr_name);
1546 #endif
1547 struct bpf_version bv;
1548 #ifdef __APPLE__
1549 int sockfd;
1550 char *wltdev = NULL;
1551 #endif
1552 #ifdef BIOCGDLTLIST
1553 struct bpf_dltlist bdl;
1554 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1555 int new_dlt;
1556 #endif
1557 #endif /* BIOCGDLTLIST */
1558 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1559 u_int spoof_eth_src = 1;
1560 #endif
1561 u_int v;
1562 struct bpf_insn total_insn;
1563 struct bpf_program total_prog;
1564 struct utsname osinfo;
1565 int have_osinfo = 0;
1566 #ifdef HAVE_ZEROCOPY_BPF
1567 struct bpf_zbuf bz;
1568 u_int bufmode, zbufmax;
1569 #endif
1571 fd = bpf_open(p);
1572 if (fd < 0) {
1573 status = fd;
1574 goto bad;
1577 p->fd = fd;
1579 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1580 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1581 pcap_strerror(errno));
1582 status = PCAP_ERROR;
1583 goto bad;
1585 if (bv.bv_major != BPF_MAJOR_VERSION ||
1586 bv.bv_minor < BPF_MINOR_VERSION) {
1587 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1588 "kernel bpf filter out of date");
1589 status = PCAP_ERROR;
1590 goto bad;
1593 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1595 * Check if the given source network device has a '/' separated
1596 * zonename prefix string. The zonename prefixed source device
1597 * can be used by libpcap consumers to capture network traffic
1598 * in non-global zones from the global zone on Solaris 11 and
1599 * above. If the zonename prefix is present then we strip the
1600 * prefix and pass the zone ID as part of lifr_zoneid.
1602 if ((zonesep = strchr(p->opt.source, '/')) != NULL) {
1603 char zonename[ZONENAME_MAX];
1604 int znamelen;
1605 char *lnamep;
1607 znamelen = zonesep - p->opt.source;
1608 (void) strlcpy(zonename, p->opt.source, znamelen + 1);
1609 lnamep = strdup(zonesep + 1);
1610 ifr.lifr_zoneid = getzoneidbyname(zonename);
1611 free(p->opt.source);
1612 p->opt.source = lnamep;
1614 #endif
1616 p->md.device = strdup(p->opt.source);
1617 if (p->md.device == NULL) {
1618 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1619 pcap_strerror(errno));
1620 status = PCAP_ERROR;
1621 goto bad;
1625 * Attempt to find out the version of the OS on which we're running.
1627 if (uname(&osinfo) == 0)
1628 have_osinfo = 1;
1630 #ifdef __APPLE__
1632 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1633 * of why we check the version number.
1635 if (p->opt.rfmon) {
1636 if (have_osinfo) {
1638 * We assume osinfo.sysname is "Darwin", because
1639 * __APPLE__ is defined. We just check the version.
1641 if (osinfo.release[0] < '8' &&
1642 osinfo.release[1] == '.') {
1644 * 10.3 (Darwin 7.x) or earlier.
1646 status = PCAP_ERROR_RFMON_NOTSUP;
1647 goto bad;
1649 if (osinfo.release[0] == '8' &&
1650 osinfo.release[1] == '.') {
1652 * 10.4 (Darwin 8.x). s/en/wlt/
1654 if (strncmp(p->opt.source, "en", 2) != 0) {
1656 * Not an enN device; check
1657 * whether the device even exists.
1659 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1660 if (sockfd != -1) {
1661 strlcpy(ifrname,
1662 p->opt.source, ifnamsiz);
1663 if (ioctl(sockfd, SIOCGIFFLAGS,
1664 (char *)&ifr) < 0) {
1666 * We assume this
1667 * failed because
1668 * the underlying
1669 * device doesn't
1670 * exist.
1672 status = PCAP_ERROR_NO_SUCH_DEVICE;
1673 snprintf(p->errbuf,
1674 PCAP_ERRBUF_SIZE,
1675 "SIOCGIFFLAGS failed: %s",
1676 pcap_strerror(errno));
1677 } else
1678 status = PCAP_ERROR_RFMON_NOTSUP;
1679 close(sockfd);
1680 } else {
1682 * We can't find out whether
1683 * the device exists, so just
1684 * report "no such device".
1686 status = PCAP_ERROR_NO_SUCH_DEVICE;
1687 snprintf(p->errbuf,
1688 PCAP_ERRBUF_SIZE,
1689 "socket() failed: %s",
1690 pcap_strerror(errno));
1692 goto bad;
1694 wltdev = malloc(strlen(p->opt.source) + 2);
1695 if (wltdev == NULL) {
1696 (void)snprintf(p->errbuf,
1697 PCAP_ERRBUF_SIZE, "malloc: %s",
1698 pcap_strerror(errno));
1699 status = PCAP_ERROR;
1700 goto bad;
1702 strcpy(wltdev, "wlt");
1703 strcat(wltdev, p->opt.source + 2);
1704 free(p->opt.source);
1705 p->opt.source = wltdev;
1708 * Everything else is 10.5 or later; for those,
1709 * we just open the enN device, and set the DLT.
1713 #endif /* __APPLE__ */
1714 #ifdef HAVE_ZEROCOPY_BPF
1716 * If the BPF extension to set buffer mode is present, try setting
1717 * the mode to zero-copy. If that fails, use regular buffering. If
1718 * it succeeds but other setup fails, return an error to the user.
1720 bufmode = BPF_BUFMODE_ZBUF;
1721 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1723 * We have zerocopy BPF; use it.
1725 p->md.zerocopy = 1;
1728 * How to pick a buffer size: first, query the maximum buffer
1729 * size supported by zero-copy. This also lets us quickly
1730 * determine whether the kernel generally supports zero-copy.
1731 * Then, if a buffer size was specified, use that, otherwise
1732 * query the default buffer size, which reflects kernel
1733 * policy for a desired default. Round to the nearest page
1734 * size.
1736 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1737 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1738 pcap_strerror(errno));
1739 goto bad;
1742 if (p->opt.buffer_size != 0) {
1744 * A buffer size was explicitly specified; use it.
1746 v = p->opt.buffer_size;
1747 } else {
1748 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1749 v < DEFAULT_BUFSIZE)
1750 v = DEFAULT_BUFSIZE;
1752 #ifndef roundup
1753 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
1754 #endif
1755 p->md.zbufsize = roundup(v, getpagesize());
1756 if (p->md.zbufsize > zbufmax)
1757 p->md.zbufsize = zbufmax;
1758 p->md.zbuf1 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1759 MAP_ANON, -1, 0);
1760 p->md.zbuf2 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1761 MAP_ANON, -1, 0);
1762 if (p->md.zbuf1 == MAP_FAILED || p->md.zbuf2 == MAP_FAILED) {
1763 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1764 pcap_strerror(errno));
1765 goto bad;
1767 bzero(&bz, sizeof(bz));
1768 bz.bz_bufa = p->md.zbuf1;
1769 bz.bz_bufb = p->md.zbuf2;
1770 bz.bz_buflen = p->md.zbufsize;
1771 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1772 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1773 pcap_strerror(errno));
1774 goto bad;
1776 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1777 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1778 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1779 p->opt.source, pcap_strerror(errno));
1780 goto bad;
1782 v = p->md.zbufsize - sizeof(struct bpf_zbuf_header);
1783 } else
1784 #endif
1787 * We don't have zerocopy BPF.
1788 * Set the buffer size.
1790 if (p->opt.buffer_size != 0) {
1792 * A buffer size was explicitly specified; use it.
1794 if (ioctl(fd, BIOCSBLEN,
1795 (caddr_t)&p->opt.buffer_size) < 0) {
1796 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1797 "BIOCSBLEN: %s: %s", p->opt.source,
1798 pcap_strerror(errno));
1799 status = PCAP_ERROR;
1800 goto bad;
1804 * Now bind to the device.
1806 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1807 #ifdef BIOCSETLIF
1808 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
1809 #else
1810 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
1811 #endif
1813 status = check_setif_failure(p, errno);
1814 goto bad;
1816 } else {
1818 * No buffer size was explicitly specified.
1820 * Try finding a good size for the buffer;
1821 * DEFAULT_BUFSIZE may be too big, so keep
1822 * cutting it in half until we find a size
1823 * that works, or run out of sizes to try.
1824 * If the default is larger, don't make it smaller.
1826 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1827 v < DEFAULT_BUFSIZE)
1828 v = DEFAULT_BUFSIZE;
1829 for ( ; v != 0; v >>= 1) {
1831 * Ignore the return value - this is because the
1832 * call fails on BPF systems that don't have
1833 * kernel malloc. And if the call fails, it's
1834 * no big deal, we just continue to use the
1835 * standard buffer size.
1837 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
1839 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1840 #ifdef BIOCSETLIF
1841 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
1842 #else
1843 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
1844 #endif
1845 break; /* that size worked; we're done */
1847 if (errno != ENOBUFS) {
1848 status = check_setif_failure(p, errno);
1849 goto bad;
1853 if (v == 0) {
1854 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1855 "BIOCSBLEN: %s: No buffer size worked",
1856 p->opt.source);
1857 status = PCAP_ERROR;
1858 goto bad;
1863 /* Get the data link layer type. */
1864 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
1865 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
1866 pcap_strerror(errno));
1867 status = PCAP_ERROR;
1868 goto bad;
1871 #ifdef _AIX
1873 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
1875 switch (v) {
1877 case IFT_ETHER:
1878 case IFT_ISO88023:
1879 v = DLT_EN10MB;
1880 break;
1882 case IFT_FDDI:
1883 v = DLT_FDDI;
1884 break;
1886 case IFT_ISO88025:
1887 v = DLT_IEEE802;
1888 break;
1890 case IFT_LOOP:
1891 v = DLT_NULL;
1892 break;
1894 default:
1896 * We don't know what to map this to yet.
1898 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
1900 status = PCAP_ERROR;
1901 goto bad;
1903 #endif
1904 #if _BSDI_VERSION - 0 >= 199510
1905 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
1906 switch (v) {
1908 case DLT_SLIP:
1909 v = DLT_SLIP_BSDOS;
1910 break;
1912 case DLT_PPP:
1913 v = DLT_PPP_BSDOS;
1914 break;
1916 case 11: /*DLT_FR*/
1917 v = DLT_FRELAY;
1918 break;
1920 case 12: /*DLT_C_HDLC*/
1921 v = DLT_CHDLC;
1922 break;
1924 #endif
1926 #ifdef BIOCGDLTLIST
1928 * We know the default link type -- now determine all the DLTs
1929 * this interface supports. If this fails with EINVAL, it's
1930 * not fatal; we just don't get to use the feature later.
1932 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
1933 status = PCAP_ERROR;
1934 goto bad;
1936 p->dlt_count = bdl.bfl_len;
1937 p->dlt_list = bdl.bfl_list;
1939 #ifdef __APPLE__
1941 * Monitor mode fun, continued.
1943 * For 10.5 and, we're assuming, later releases, as noted above,
1944 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
1945 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
1946 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
1947 * monitor mode on.
1949 * Therefore, if the user asked for monitor mode, we filter out
1950 * the DLT_EN10MB value, as you can't get that in monitor mode,
1951 * and, if the user didn't ask for monitor mode, we filter out
1952 * the 802.11 DLT_ values, because selecting those will turn
1953 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
1954 * radio DLT_ value is offered, we try to select that, otherwise
1955 * we try to select DLT_IEEE802_11.
1957 if (have_osinfo) {
1958 if (isdigit((unsigned)osinfo.release[0]) &&
1959 (osinfo.release[0] == '9' ||
1960 isdigit((unsigned)osinfo.release[1]))) {
1962 * 10.5 (Darwin 9.x), or later.
1964 new_dlt = find_802_11(&bdl);
1965 if (new_dlt != -1) {
1967 * We have at least one 802.11 DLT_ value,
1968 * so this is an 802.11 interface.
1969 * new_dlt is the best of the 802.11
1970 * DLT_ values in the list.
1972 if (p->opt.rfmon) {
1974 * Our caller wants monitor mode.
1975 * Purge DLT_EN10MB from the list
1976 * of link-layer types, as selecting
1977 * it will keep monitor mode off.
1979 remove_en(p);
1982 * If the new mode we want isn't
1983 * the default mode, attempt to
1984 * select the new mode.
1986 if (new_dlt != v) {
1987 if (ioctl(p->fd, BIOCSDLT,
1988 &new_dlt) != -1) {
1990 * We succeeded;
1991 * make this the
1992 * new DLT_ value.
1994 v = new_dlt;
1997 } else {
1999 * Our caller doesn't want
2000 * monitor mode. Unless this
2001 * is being done by pcap_open_live(),
2002 * purge the 802.11 link-layer types
2003 * from the list, as selecting
2004 * one of them will turn monitor
2005 * mode on.
2007 if (!p->oldstyle)
2008 remove_802_11(p);
2010 } else {
2011 if (p->opt.rfmon) {
2013 * The caller requested monitor
2014 * mode, but we have no 802.11
2015 * link-layer types, so they
2016 * can't have it.
2018 status = PCAP_ERROR_RFMON_NOTSUP;
2019 goto bad;
2024 #elif defined(HAVE_BSD_IEEE80211)
2026 * *BSD with the new 802.11 ioctls.
2027 * Do we want monitor mode?
2029 if (p->opt.rfmon) {
2031 * Try to put the interface into monitor mode.
2033 status = monitor_mode(p, 1);
2034 if (status != 0) {
2036 * We failed.
2038 goto bad;
2042 * We're in monitor mode.
2043 * Try to find the best 802.11 DLT_ value and, if we
2044 * succeed, try to switch to that mode if we're not
2045 * already in that mode.
2047 new_dlt = find_802_11(&bdl);
2048 if (new_dlt != -1) {
2050 * We have at least one 802.11 DLT_ value.
2051 * new_dlt is the best of the 802.11
2052 * DLT_ values in the list.
2054 * If the new mode we want isn't the default mode,
2055 * attempt to select the new mode.
2057 if (new_dlt != v) {
2058 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
2060 * We succeeded; make this the
2061 * new DLT_ value.
2063 v = new_dlt;
2068 #endif /* various platforms */
2069 #endif /* BIOCGDLTLIST */
2072 * If this is an Ethernet device, and we don't have a DLT_ list,
2073 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
2074 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2075 * do, but there's not much we can do about that without finding
2076 * some other way of determining whether it's an Ethernet or 802.11
2077 * device.)
2079 if (v == DLT_EN10MB && p->dlt_count == 0) {
2080 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2082 * If that fails, just leave the list empty.
2084 if (p->dlt_list != NULL) {
2085 p->dlt_list[0] = DLT_EN10MB;
2086 p->dlt_list[1] = DLT_DOCSIS;
2087 p->dlt_count = 2;
2090 #ifdef PCAP_FDDIPAD
2091 if (v == DLT_FDDI)
2092 p->fddipad = PCAP_FDDIPAD;
2093 else
2094 p->fddipad = 0;
2095 #endif
2096 p->linktype = v;
2098 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2100 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2101 * the link-layer source address isn't forcibly overwritten.
2102 * (Should we ignore errors? Should we do this only if
2103 * we're open for writing?)
2105 * XXX - I seem to remember some packet-sending bug in some
2106 * BSDs - check CVS log for "bpf.c"?
2108 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2109 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2110 "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
2111 status = PCAP_ERROR;
2112 goto bad;
2114 #endif
2115 /* set timeout */
2116 #ifdef HAVE_ZEROCOPY_BPF
2117 if (p->md.timeout != 0 && !p->md.zerocopy) {
2118 #else
2119 if (p->md.timeout) {
2120 #endif
2122 * XXX - is this seconds/nanoseconds in AIX?
2123 * (Treating it as such doesn't fix the timeout
2124 * problem described below.)
2126 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2127 * 64-bit userland - it takes, as an argument, a
2128 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2129 * and tv_usec, rather than a "struct timeval".
2131 * If this platform defines "struct BPF_TIMEVAL",
2132 * we check whether the structure size in BIOCSRTIMEOUT
2133 * is that of a "struct timeval" and, if not, we use
2134 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2135 * (That way, if the bug is fixed in a future release,
2136 * we will still do the right thing.)
2138 struct timeval to;
2139 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2140 struct BPF_TIMEVAL bpf_to;
2142 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2143 bpf_to.tv_sec = p->md.timeout / 1000;
2144 bpf_to.tv_usec = (p->md.timeout * 1000) % 1000000;
2145 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2146 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2147 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2148 status = PCAP_ERROR;
2149 goto bad;
2151 } else {
2152 #endif
2153 to.tv_sec = p->md.timeout / 1000;
2154 to.tv_usec = (p->md.timeout * 1000) % 1000000;
2155 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2156 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2157 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2158 status = PCAP_ERROR;
2159 goto bad;
2161 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2163 #endif
2166 #ifdef _AIX
2167 #ifdef BIOCIMMEDIATE
2169 * Darren Reed notes that
2171 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2172 * timeout appears to be ignored and it waits until the buffer
2173 * is filled before returning. The result of not having it
2174 * set is almost worse than useless if your BPF filter
2175 * is reducing things to only a few packets (i.e. one every
2176 * second or so).
2178 * so we turn BIOCIMMEDIATE mode on if this is AIX.
2180 * We don't turn it on for other platforms, as that means we
2181 * get woken up for every packet, which may not be what we want;
2182 * in the Winter 1993 USENIX paper on BPF, they say:
2184 * Since a process might want to look at every packet on a
2185 * network and the time between packets can be only a few
2186 * microseconds, it is not possible to do a read system call
2187 * per packet and BPF must collect the data from several
2188 * packets and return it as a unit when the monitoring
2189 * application does a read.
2191 * which I infer is the reason for the timeout - it means we
2192 * wait that amount of time, in the hopes that more packets
2193 * will arrive and we'll get them all with one read.
2195 * Setting BIOCIMMEDIATE mode on FreeBSD (and probably other
2196 * BSDs) causes the timeout to be ignored.
2198 * On the other hand, some platforms (e.g., Linux) don't support
2199 * timeouts, they just hand stuff to you as soon as it arrives;
2200 * if that doesn't cause a problem on those platforms, it may
2201 * be OK to have BIOCIMMEDIATE mode on BSD as well.
2203 * (Note, though, that applications may depend on the read
2204 * completing, even if no packets have arrived, when the timeout
2205 * expires, e.g. GUI applications that have to check for input
2206 * while waiting for packets to arrive; a non-zero timeout
2207 * prevents "select()" from working right on FreeBSD and
2208 * possibly other BSDs, as the timer doesn't start until a
2209 * "read()" is done, so the timer isn't in effect if the
2210 * application is blocked on a "select()", and the "select()"
2211 * doesn't get woken up for a BPF device until the buffer
2212 * fills up.)
2214 v = 1;
2215 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2216 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCIMMEDIATE: %s",
2217 pcap_strerror(errno));
2218 status = PCAP_ERROR;
2219 goto bad;
2221 #endif /* BIOCIMMEDIATE */
2222 #endif /* _AIX */
2224 if (p->opt.promisc) {
2225 /* set promiscuous mode, just warn if it fails */
2226 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2227 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
2228 pcap_strerror(errno));
2229 status = PCAP_WARNING_PROMISC_NOTSUP;
2233 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2234 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
2235 pcap_strerror(errno));
2236 status = PCAP_ERROR;
2237 goto bad;
2239 p->bufsize = v;
2240 #ifdef HAVE_ZEROCOPY_BPF
2241 if (!p->md.zerocopy) {
2242 #endif
2243 p->buffer = (u_char *)malloc(p->bufsize);
2244 if (p->buffer == NULL) {
2245 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2246 pcap_strerror(errno));
2247 status = PCAP_ERROR;
2248 goto bad;
2250 #ifdef _AIX
2251 /* For some strange reason this seems to prevent the EFAULT
2252 * problems we have experienced from AIX BPF. */
2253 memset(p->buffer, 0x0, p->bufsize);
2254 #endif
2255 #ifdef HAVE_ZEROCOPY_BPF
2257 #endif
2260 * If there's no filter program installed, there's
2261 * no indication to the kernel of what the snapshot
2262 * length should be, so no snapshotting is done.
2264 * Therefore, when we open the device, we install
2265 * an "accept everything" filter with the specified
2266 * snapshot length.
2268 total_insn.code = (u_short)(BPF_RET | BPF_K);
2269 total_insn.jt = 0;
2270 total_insn.jf = 0;
2271 total_insn.k = p->snapshot;
2273 total_prog.bf_len = 1;
2274 total_prog.bf_insns = &total_insn;
2275 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2276 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2277 pcap_strerror(errno));
2278 status = PCAP_ERROR;
2279 goto bad;
2283 * On most BPF platforms, either you can do a "select()" or
2284 * "poll()" on a BPF file descriptor and it works correctly,
2285 * or you can do it and it will return "readable" if the
2286 * hold buffer is full but not if the timeout expires *and*
2287 * a non-blocking read will, if the hold buffer is empty
2288 * but the store buffer isn't empty, rotate the buffers
2289 * and return what packets are available.
2291 * In the latter case, the fact that a non-blocking read
2292 * will give you the available packets means you can work
2293 * around the failure of "select()" and "poll()" to wake up
2294 * and return "readable" when the timeout expires by using
2295 * the timeout as the "select()" or "poll()" timeout, putting
2296 * the BPF descriptor into non-blocking mode, and read from
2297 * it regardless of whether "select()" reports it as readable
2298 * or not.
2300 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2301 * won't wake up and return "readable" if the timer expires
2302 * and non-blocking reads return EWOULDBLOCK if the hold
2303 * buffer is empty, even if the store buffer is non-empty.
2305 * This means the workaround in question won't work.
2307 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2308 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2309 * here". On all other BPF platforms, we set it to the FD for
2310 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2311 * read will, if the hold buffer is empty and the store buffer
2312 * isn't empty, rotate the buffers and return what packets are
2313 * there (and in sufficiently recent versions of OpenBSD
2314 * "select()" and "poll()" should work correctly).
2316 * XXX - what about AIX?
2318 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2319 if (have_osinfo) {
2321 * We can check what OS this is.
2323 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2324 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2325 strncmp(osinfo.release, "4.4-", 4) == 0)
2326 p->selectable_fd = -1;
2330 p->read_op = pcap_read_bpf;
2331 p->inject_op = pcap_inject_bpf;
2332 p->setfilter_op = pcap_setfilter_bpf;
2333 p->setdirection_op = pcap_setdirection_bpf;
2334 p->set_datalink_op = pcap_set_datalink_bpf;
2335 p->getnonblock_op = pcap_getnonblock_bpf;
2336 p->setnonblock_op = pcap_setnonblock_bpf;
2337 p->stats_op = pcap_stats_bpf;
2338 p->cleanup_op = pcap_cleanup_bpf;
2340 return (status);
2341 bad:
2342 pcap_cleanup_bpf(p);
2343 return (status);
2347 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2349 #ifdef HAVE_DAG_API
2350 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
2351 return (-1);
2352 #endif /* HAVE_DAG_API */
2353 #ifdef HAVE_SNF_API
2354 if (snf_platform_finddevs(alldevsp, errbuf) < 0)
2355 return (-1);
2356 #endif /* HAVE_SNF_API */
2358 return (0);
2361 #ifdef HAVE_BSD_IEEE80211
2362 static int
2363 monitor_mode(pcap_t *p, int set)
2365 int sock;
2366 struct ifmediareq req;
2367 int *media_list;
2368 int i;
2369 int can_do;
2370 struct ifreq ifr;
2372 sock = socket(AF_INET, SOCK_DGRAM, 0);
2373 if (sock == -1) {
2374 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2375 pcap_strerror(errno));
2376 return (PCAP_ERROR);
2379 memset(&req, 0, sizeof req);
2380 strncpy(req.ifm_name, p->opt.source, sizeof req.ifm_name);
2383 * Find out how many media types we have.
2385 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2387 * Can't get the media types.
2389 switch (errno) {
2391 case ENXIO:
2393 * There's no such device.
2395 close(sock);
2396 return (PCAP_ERROR_NO_SUCH_DEVICE);
2398 case EINVAL:
2400 * Interface doesn't support SIOC{G,S}IFMEDIA.
2402 close(sock);
2403 return (PCAP_ERROR_RFMON_NOTSUP);
2405 default:
2406 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2407 "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
2408 close(sock);
2409 return (PCAP_ERROR);
2412 if (req.ifm_count == 0) {
2414 * No media types.
2416 close(sock);
2417 return (PCAP_ERROR_RFMON_NOTSUP);
2421 * Allocate a buffer to hold all the media types, and
2422 * get the media types.
2424 media_list = malloc(req.ifm_count * sizeof(int));
2425 if (media_list == NULL) {
2426 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2427 pcap_strerror(errno));
2428 close(sock);
2429 return (PCAP_ERROR);
2431 req.ifm_ulist = media_list;
2432 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2433 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2434 pcap_strerror(errno));
2435 free(media_list);
2436 close(sock);
2437 return (PCAP_ERROR);
2441 * Look for an 802.11 "automatic" media type.
2442 * We assume that all 802.11 adapters have that media type,
2443 * and that it will carry the monitor mode supported flag.
2445 can_do = 0;
2446 for (i = 0; i < req.ifm_count; i++) {
2447 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2448 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2449 /* OK, does it do monitor mode? */
2450 if (media_list[i] & IFM_IEEE80211_MONITOR) {
2451 can_do = 1;
2452 break;
2456 free(media_list);
2457 if (!can_do) {
2459 * This adapter doesn't support monitor mode.
2461 close(sock);
2462 return (PCAP_ERROR_RFMON_NOTSUP);
2465 if (set) {
2467 * Don't just check whether we can enable monitor mode,
2468 * do so, if it's not already enabled.
2470 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2472 * Monitor mode isn't currently on, so turn it on,
2473 * and remember that we should turn it off when the
2474 * pcap_t is closed.
2478 * If we haven't already done so, arrange to have
2479 * "pcap_close_all()" called when we exit.
2481 if (!pcap_do_addexit(p)) {
2483 * "atexit()" failed; don't put the interface
2484 * in monitor mode, just give up.
2486 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2487 "atexit failed");
2488 close(sock);
2489 return (PCAP_ERROR);
2491 memset(&ifr, 0, sizeof(ifr));
2492 (void)strncpy(ifr.ifr_name, p->opt.source,
2493 sizeof(ifr.ifr_name));
2494 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2495 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2496 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2497 "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2498 close(sock);
2499 return (PCAP_ERROR);
2502 p->md.must_do_on_close |= MUST_CLEAR_RFMON;
2505 * Add this to the list of pcaps to close when we exit.
2507 pcap_add_to_pcaps_to_close(p);
2510 return (0);
2512 #endif /* HAVE_BSD_IEEE80211 */
2514 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2516 * Check whether we have any 802.11 link-layer types; return the best
2517 * of the 802.11 link-layer types if we find one, and return -1
2518 * otherwise.
2520 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2521 * best 802.11 link-layer type; any of the other 802.11-plus-radio
2522 * headers are second-best; 802.11 with no radio information is
2523 * the least good.
2525 static int
2526 find_802_11(struct bpf_dltlist *bdlp)
2528 int new_dlt;
2529 int i;
2532 * Scan the list of DLT_ values, looking for 802.11 values,
2533 * and, if we find any, choose the best of them.
2535 new_dlt = -1;
2536 for (i = 0; i < bdlp->bfl_len; i++) {
2537 switch (bdlp->bfl_list[i]) {
2539 case DLT_IEEE802_11:
2541 * 802.11, but no radio.
2543 * Offer this, and select it as the new mode
2544 * unless we've already found an 802.11
2545 * header with radio information.
2547 if (new_dlt == -1)
2548 new_dlt = bdlp->bfl_list[i];
2549 break;
2551 case DLT_PRISM_HEADER:
2552 case DLT_AIRONET_HEADER:
2553 case DLT_IEEE802_11_RADIO_AVS:
2555 * 802.11 with radio, but not radiotap.
2557 * Offer this, and select it as the new mode
2558 * unless we've already found the radiotap DLT_.
2560 if (new_dlt != DLT_IEEE802_11_RADIO)
2561 new_dlt = bdlp->bfl_list[i];
2562 break;
2564 case DLT_IEEE802_11_RADIO:
2566 * 802.11 with radiotap.
2568 * Offer this, and select it as the new mode.
2570 new_dlt = bdlp->bfl_list[i];
2571 break;
2573 default:
2575 * Not 802.11.
2577 break;
2581 return (new_dlt);
2583 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2585 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
2587 * Remove DLT_EN10MB from the list of DLT_ values, as we're in monitor mode,
2588 * and DLT_EN10MB isn't supported in monitor mode.
2590 static void
2591 remove_en(pcap_t *p)
2593 int i, j;
2596 * Scan the list of DLT_ values and discard DLT_EN10MB.
2598 j = 0;
2599 for (i = 0; i < p->dlt_count; i++) {
2600 switch (p->dlt_list[i]) {
2602 case DLT_EN10MB:
2604 * Don't offer this one.
2606 continue;
2608 default:
2610 * Just copy this mode over.
2612 break;
2616 * Copy this DLT_ value to its new position.
2618 p->dlt_list[j] = p->dlt_list[i];
2619 j++;
2623 * Set the DLT_ count to the number of entries we copied.
2625 p->dlt_count = j;
2629 * Remove 802.11 link-layer types from the list of DLT_ values, as
2630 * we're not in monitor mode, and those DLT_ values will switch us
2631 * to monitor mode.
2633 static void
2634 remove_802_11(pcap_t *p)
2636 int i, j;
2639 * Scan the list of DLT_ values and discard 802.11 values.
2641 j = 0;
2642 for (i = 0; i < p->dlt_count; i++) {
2643 switch (p->dlt_list[i]) {
2645 case DLT_IEEE802_11:
2646 case DLT_PRISM_HEADER:
2647 case DLT_AIRONET_HEADER:
2648 case DLT_IEEE802_11_RADIO:
2649 case DLT_IEEE802_11_RADIO_AVS:
2651 * 802.11. Don't offer this one.
2653 continue;
2655 default:
2657 * Just copy this mode over.
2659 break;
2663 * Copy this DLT_ value to its new position.
2665 p->dlt_list[j] = p->dlt_list[i];
2666 j++;
2670 * Set the DLT_ count to the number of entries we copied.
2672 p->dlt_count = j;
2674 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
2676 static int
2677 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
2680 * Free any user-mode filter we might happen to have installed.
2682 pcap_freecode(&p->fcode);
2685 * Try to install the kernel filter.
2687 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
2689 * It worked.
2691 p->md.use_bpf = 1; /* filtering in the kernel */
2694 * Discard any previously-received packets, as they might
2695 * have passed whatever filter was formerly in effect, but
2696 * might not pass this filter (BIOCSETF discards packets
2697 * buffered in the kernel, so you can lose packets in any
2698 * case).
2700 p->cc = 0;
2701 return (0);
2705 * We failed.
2707 * If it failed with EINVAL, that's probably because the program
2708 * is invalid or too big. Validate it ourselves; if we like it
2709 * (we currently allow backward branches, to support protochain),
2710 * run it in userland. (There's no notion of "too big" for
2711 * userland.)
2713 * Otherwise, just give up.
2714 * XXX - if the copy of the program into the kernel failed,
2715 * we will get EINVAL rather than, say, EFAULT on at least
2716 * some kernels.
2718 if (errno != EINVAL) {
2719 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2720 pcap_strerror(errno));
2721 return (-1);
2725 * install_bpf_program() validates the program.
2727 * XXX - what if we already have a filter in the kernel?
2729 if (install_bpf_program(p, fp) < 0)
2730 return (-1);
2731 p->md.use_bpf = 0; /* filtering in userland */
2732 return (0);
2736 * Set direction flag: Which packets do we accept on a forwarding
2737 * single device? IN, OUT or both?
2739 static int
2740 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
2742 #if defined(BIOCSDIRECTION)
2743 u_int direction;
2745 direction = (d == PCAP_D_IN) ? BPF_D_IN :
2746 ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
2747 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
2748 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2749 "Cannot set direction to %s: %s",
2750 (d == PCAP_D_IN) ? "PCAP_D_IN" :
2751 ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
2752 strerror(errno));
2753 return (-1);
2755 return (0);
2756 #elif defined(BIOCSSEESENT)
2757 u_int seesent;
2760 * We don't support PCAP_D_OUT.
2762 if (d == PCAP_D_OUT) {
2763 snprintf(p->errbuf, sizeof(p->errbuf),
2764 "Setting direction to PCAP_D_OUT is not supported on BPF");
2765 return -1;
2768 seesent = (d == PCAP_D_INOUT);
2769 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
2770 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2771 "Cannot set direction to %s: %s",
2772 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
2773 strerror(errno));
2774 return (-1);
2776 return (0);
2777 #else
2778 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2779 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
2780 return (-1);
2781 #endif
2784 static int
2785 pcap_set_datalink_bpf(pcap_t *p, int dlt)
2787 #ifdef BIOCSDLT
2788 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
2789 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2790 "Cannot set DLT %d: %s", dlt, strerror(errno));
2791 return (-1);
2793 #endif
2794 return (0);