Merge commit 'e4768a3447c8320148c66b297c2acb00217f575d'
[unleashed.git] / contrib / libpcap / pcap-bpf.c
blobb765904d7cab4a8809f9996b9ea16eacffaaa7a3
1 /*
2 * Copyright (c) 1993, 1994, 1995, 1996, 1998
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
16 * written permission.
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
26 #include <sys/param.h> /* optionally get BSD define */
27 #ifdef HAVE_ZEROCOPY_BPF
28 #include <sys/mman.h>
29 #endif
30 #include <sys/socket.h>
31 #include <time.h>
33 * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
35 * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
36 * at least on *BSD and Mac OS X, it also defines various SIOC ioctls -
37 * we could include <sys/sockio.h>, but if we're already including
38 * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
39 * there's not much point in doing so.
41 * If we have <sys/ioccom.h>, we include it as well, to handle systems
42 * such as Solaris which don't arrange to include <sys/ioccom.h> if you
43 * include <sys/ioctl.h>
45 #include <sys/ioctl.h>
46 #ifdef HAVE_SYS_IOCCOM_H
47 #include <sys/ioccom.h>
48 #endif
49 #include <sys/utsname.h>
51 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
53 * Add support for capturing on FreeBSD usbusN interfaces.
55 static const char usbus_prefix[] = "usbus";
56 #define USBUS_PREFIX_LEN (sizeof(usbus_prefix) - 1)
57 #include <dirent.h>
58 #endif
60 #ifdef HAVE_ZEROCOPY_BPF
61 #include <machine/atomic.h>
62 #endif
64 #include <net/if.h>
66 #ifdef _AIX
69 * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
70 * native OS version, as we need "struct bpf_config" from it.
72 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
74 #include <sys/types.h>
77 * Prevent bpf.h from redefining the DLT_ values to their
78 * IFT_ values, as we're going to return the standard libpcap
79 * values, not IBM's non-standard IFT_ values.
81 #undef _AIX
82 #include <net/bpf.h>
83 #define _AIX
85 #include <net/if_types.h> /* for IFT_ values */
86 #include <sys/sysconfig.h>
87 #include <sys/device.h>
88 #include <sys/cfgodm.h>
89 #include <cf.h>
91 #ifdef __64BIT__
92 #define domakedev makedev64
93 #define getmajor major64
94 #define bpf_hdr bpf_hdr32
95 #else /* __64BIT__ */
96 #define domakedev makedev
97 #define getmajor major
98 #endif /* __64BIT__ */
100 #define BPF_NAME "bpf"
101 #define BPF_MINORS 4
102 #define DRIVER_PATH "/usr/lib/drivers"
103 #define BPF_NODE "/dev/bpf"
104 static int bpfloadedflag = 0;
105 static int odmlockid = 0;
107 static int bpf_load(char *errbuf);
109 #else /* _AIX */
111 #include <net/bpf.h>
113 #endif /* _AIX */
115 #include <ctype.h>
116 #include <fcntl.h>
117 #include <errno.h>
118 #include <netdb.h>
119 #include <stdio.h>
120 #include <stdlib.h>
121 #include <string.h>
122 #include <unistd.h>
124 #ifdef HAVE_NET_IF_MEDIA_H
125 # include <net/if_media.h>
126 #endif
128 #include "pcap-int.h"
130 #ifdef HAVE_OS_PROTO_H
131 #include "os-proto.h"
132 #endif
135 * Later versions of NetBSD stick padding in front of FDDI frames
136 * to align the IP header on a 4-byte boundary.
138 #if defined(__NetBSD__) && __NetBSD_Version__ > 106000000
139 #define PCAP_FDDIPAD 3
140 #endif
143 * Private data for capturing on BPF devices.
145 struct pcap_bpf {
146 #ifdef HAVE_ZEROCOPY_BPF
148 * Zero-copy read buffer -- for zero-copy BPF. 'buffer' above will
149 * alternative between these two actual mmap'd buffers as required.
150 * As there is a header on the front size of the mmap'd buffer, only
151 * some of the buffer is exposed to libpcap as a whole via bufsize;
152 * zbufsize is the true size. zbuffer tracks the current zbuf
153 * assocated with buffer so that it can be used to decide which the
154 * next buffer to read will be.
156 u_char *zbuf1, *zbuf2, *zbuffer;
157 u_int zbufsize;
158 u_int zerocopy;
159 u_int interrupted;
160 struct timespec firstsel;
162 * If there's currently a buffer being actively processed, then it is
163 * referenced here; 'buffer' is also pointed at it, but offset by the
164 * size of the header.
166 struct bpf_zbuf_header *bzh;
167 int nonblock; /* true if in nonblocking mode */
168 #endif /* HAVE_ZEROCOPY_BPF */
170 char *device; /* device name */
171 int filtering_in_kernel; /* using kernel filter */
172 int must_do_on_close; /* stuff we must do when we close */
176 * Stuff to do when we close.
178 #define MUST_CLEAR_RFMON 0x00000001 /* clear rfmon (monitor) mode */
179 #define MUST_DESTROY_USBUS 0x00000002 /* destroy usbusN interface */
181 #ifdef BIOCGDLTLIST
182 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
183 #define HAVE_BSD_IEEE80211
186 * The ifm_ulist member of a struct ifmediareq is an int * on most systems,
187 * but it's a uint64_t on newer versions of OpenBSD.
189 * We check this by checking whether IFM_GMASK is defined and > 2^32-1.
191 # if defined(IFM_GMASK) && IFM_GMASK > 0xFFFFFFFF
192 # define IFM_ULIST_TYPE uint64_t
193 # else
194 # define IFM_ULIST_TYPE int
195 # endif
196 # endif
198 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
199 static int find_802_11(struct bpf_dltlist *);
201 # ifdef HAVE_BSD_IEEE80211
202 static int monitor_mode(pcap_t *, int);
203 # endif
205 # if defined(__APPLE__)
206 static void remove_en(pcap_t *);
207 static void remove_802_11(pcap_t *);
208 # endif
210 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
212 #endif /* BIOCGDLTLIST */
214 #if defined(sun) && defined(LIFNAMSIZ) && defined(lifr_zoneid)
215 #include <zone.h>
216 #endif
219 * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
220 * don't get DLT_DOCSIS defined.
222 #ifndef DLT_DOCSIS
223 #define DLT_DOCSIS 143
224 #endif
227 * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
228 * defined, even though some of them are used by various Airport drivers.
230 #ifndef DLT_PRISM_HEADER
231 #define DLT_PRISM_HEADER 119
232 #endif
233 #ifndef DLT_AIRONET_HEADER
234 #define DLT_AIRONET_HEADER 120
235 #endif
236 #ifndef DLT_IEEE802_11_RADIO
237 #define DLT_IEEE802_11_RADIO 127
238 #endif
239 #ifndef DLT_IEEE802_11_RADIO_AVS
240 #define DLT_IEEE802_11_RADIO_AVS 163
241 #endif
243 static int pcap_can_set_rfmon_bpf(pcap_t *p);
244 static int pcap_activate_bpf(pcap_t *p);
245 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
246 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
247 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
250 * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
251 * pb->nonblock so we don't call select(2) if the pcap handle is in non-
252 * blocking mode.
254 static int
255 pcap_getnonblock_bpf(pcap_t *p, char *errbuf)
257 #ifdef HAVE_ZEROCOPY_BPF
258 struct pcap_bpf *pb = p->priv;
260 if (pb->zerocopy)
261 return (pb->nonblock);
262 #endif
263 return (pcap_getnonblock_fd(p, errbuf));
266 static int
267 pcap_setnonblock_bpf(pcap_t *p, int nonblock, char *errbuf)
269 #ifdef HAVE_ZEROCOPY_BPF
270 struct pcap_bpf *pb = p->priv;
272 if (pb->zerocopy) {
273 pb->nonblock = nonblock;
274 return (0);
276 #endif
277 return (pcap_setnonblock_fd(p, nonblock, errbuf));
280 #ifdef HAVE_ZEROCOPY_BPF
282 * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
283 * shared memory buffers.
285 * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
286 * and set up p->buffer and cc to reflect one if available. Notice that if
287 * there was no prior buffer, we select zbuf1 as this will be the first
288 * buffer filled for a fresh BPF session.
290 static int
291 pcap_next_zbuf_shm(pcap_t *p, int *cc)
293 struct pcap_bpf *pb = p->priv;
294 struct bpf_zbuf_header *bzh;
296 if (pb->zbuffer == pb->zbuf2 || pb->zbuffer == NULL) {
297 bzh = (struct bpf_zbuf_header *)pb->zbuf1;
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->zbuf1;
302 p->buffer = pb->zbuffer + sizeof(*bzh);
303 *cc = bzh->bzh_kernel_len;
304 return (1);
306 } else if (pb->zbuffer == pb->zbuf1) {
307 bzh = (struct bpf_zbuf_header *)pb->zbuf2;
308 if (bzh->bzh_user_gen !=
309 atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
310 pb->bzh = bzh;
311 pb->zbuffer = (u_char *)pb->zbuf2;
312 p->buffer = pb->zbuffer + sizeof(*bzh);
313 *cc = bzh->bzh_kernel_len;
314 return (1);
317 *cc = 0;
318 return (0);
322 * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
323 * select() for data or a timeout, and possibly force rotation of the buffer
324 * in the event we time out or are in immediate mode. Invoke the shared
325 * memory check before doing system calls in order to avoid doing avoidable
326 * work.
328 static int
329 pcap_next_zbuf(pcap_t *p, int *cc)
331 struct pcap_bpf *pb = p->priv;
332 struct bpf_zbuf bz;
333 struct timeval tv;
334 struct timespec cur;
335 fd_set r_set;
336 int data, r;
337 int expire, tmout;
339 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
341 * Start out by seeing whether anything is waiting by checking the
342 * next shared memory buffer for data.
344 data = pcap_next_zbuf_shm(p, cc);
345 if (data)
346 return (data);
348 * If a previous sleep was interrupted due to signal delivery, make
349 * sure that the timeout gets adjusted accordingly. This requires
350 * that we analyze when the timeout should be been expired, and
351 * subtract the current time from that. If after this operation,
352 * our timeout is less then or equal to zero, handle it like a
353 * regular timeout.
355 tmout = p->opt.timeout;
356 if (tmout)
357 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
358 if (pb->interrupted && p->opt.timeout) {
359 expire = TSTOMILLI(&pb->firstsel) + p->opt.timeout;
360 tmout = expire - TSTOMILLI(&cur);
361 #undef TSTOMILLI
362 if (tmout <= 0) {
363 pb->interrupted = 0;
364 data = pcap_next_zbuf_shm(p, cc);
365 if (data)
366 return (data);
367 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
368 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
369 "BIOCROTZBUF: %s", strerror(errno));
370 return (PCAP_ERROR);
372 return (pcap_next_zbuf_shm(p, cc));
376 * No data in the buffer, so must use select() to wait for data or
377 * the next timeout. Note that we only call select if the handle
378 * is in blocking mode.
380 if (!pb->nonblock) {
381 FD_ZERO(&r_set);
382 FD_SET(p->fd, &r_set);
383 if (tmout != 0) {
384 tv.tv_sec = tmout / 1000;
385 tv.tv_usec = (tmout * 1000) % 1000000;
387 r = select(p->fd + 1, &r_set, NULL, NULL,
388 p->opt.timeout != 0 ? &tv : NULL);
389 if (r < 0 && errno == EINTR) {
390 if (!pb->interrupted && p->opt.timeout) {
391 pb->interrupted = 1;
392 pb->firstsel = cur;
394 return (0);
395 } else if (r < 0) {
396 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
397 "select: %s", strerror(errno));
398 return (PCAP_ERROR);
401 pb->interrupted = 0;
403 * Check again for data, which may exist now that we've either been
404 * woken up as a result of data or timed out. Try the "there's data"
405 * case first since it doesn't require a system call.
407 data = pcap_next_zbuf_shm(p, cc);
408 if (data)
409 return (data);
411 * Try forcing a buffer rotation to dislodge timed out or immediate
412 * data.
414 if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
415 (void) pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
416 "BIOCROTZBUF: %s", strerror(errno));
417 return (PCAP_ERROR);
419 return (pcap_next_zbuf_shm(p, cc));
423 * Notify kernel that we are done with the buffer. We don't reset zbuffer so
424 * that we know which buffer to use next time around.
426 static int
427 pcap_ack_zbuf(pcap_t *p)
429 struct pcap_bpf *pb = p->priv;
431 atomic_store_rel_int(&pb->bzh->bzh_user_gen,
432 pb->bzh->bzh_kernel_gen);
433 pb->bzh = NULL;
434 p->buffer = NULL;
435 return (0);
437 #endif /* HAVE_ZEROCOPY_BPF */
439 pcap_t *
440 pcap_create_interface(const char *device _U_, char *ebuf)
442 pcap_t *p;
444 p = pcap_create_common(ebuf, sizeof (struct pcap_bpf));
445 if (p == NULL)
446 return (NULL);
448 p->activate_op = pcap_activate_bpf;
449 p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
450 #ifdef BIOCSTSTAMP
452 * We claim that we support microsecond and nanosecond time
453 * stamps.
455 p->tstamp_precision_count = 2;
456 p->tstamp_precision_list = malloc(2 * sizeof(u_int));
457 if (p->tstamp_precision_list == NULL) {
458 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
459 pcap_strerror(errno));
460 free(p);
461 return (NULL);
463 p->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
464 p->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
465 #endif /* BIOCSTSTAMP */
466 return (p);
470 * On success, returns a file descriptor for a BPF device.
471 * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
473 static int
474 bpf_open(char *errbuf)
476 int fd;
477 #ifdef HAVE_CLONING_BPF
478 static const char device[] = "/dev/bpf";
479 #else
480 int n = 0;
481 char device[sizeof "/dev/bpf0000000000"];
482 #endif
484 #ifdef _AIX
486 * Load the bpf driver, if it isn't already loaded,
487 * and create the BPF device entries, if they don't
488 * already exist.
490 if (bpf_load(errbuf) == PCAP_ERROR)
491 return (PCAP_ERROR);
492 #endif
494 #ifdef HAVE_CLONING_BPF
495 if ((fd = open(device, O_RDWR)) == -1 &&
496 (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
497 if (errno == EACCES)
498 fd = PCAP_ERROR_PERM_DENIED;
499 else
500 fd = PCAP_ERROR;
501 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
502 "(cannot open device) %s: %s", device, pcap_strerror(errno));
504 #else
506 * Go through all the minors and find one that isn't in use.
508 do {
509 (void)pcap_snprintf(device, sizeof(device), "/dev/bpf%d", n++);
511 * Initially try a read/write open (to allow the inject
512 * method to work). If that fails due to permission
513 * issues, fall back to read-only. This allows a
514 * non-root user to be granted specific access to pcap
515 * capabilities via file permissions.
517 * XXX - we should have an API that has a flag that
518 * controls whether to open read-only or read-write,
519 * so that denial of permission to send (or inability
520 * to send, if sending packets isn't supported on
521 * the device in question) can be indicated at open
522 * time.
524 fd = open(device, O_RDWR);
525 if (fd == -1 && errno == EACCES)
526 fd = open(device, O_RDONLY);
527 } while (fd < 0 && errno == EBUSY);
530 * XXX better message for all minors used
532 if (fd < 0) {
533 switch (errno) {
535 case ENOENT:
536 fd = PCAP_ERROR;
537 if (n == 1) {
539 * /dev/bpf0 doesn't exist, which
540 * means we probably have no BPF
541 * devices.
543 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
544 "(there are no BPF devices)");
545 } else {
547 * We got EBUSY on at least one
548 * BPF device, so we have BPF
549 * devices, but all the ones
550 * that exist are busy.
552 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
553 "(all BPF devices are busy)");
555 break;
557 case EACCES:
559 * Got EACCES on the last device we tried,
560 * and EBUSY on all devices before that,
561 * if any.
563 fd = PCAP_ERROR_PERM_DENIED;
564 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
565 "(cannot open BPF device) %s: %s", device,
566 pcap_strerror(errno));
567 break;
569 default:
571 * Some other problem.
573 fd = PCAP_ERROR;
574 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
575 "(cannot open BPF device) %s: %s", device,
576 pcap_strerror(errno));
577 break;
580 #endif
582 return (fd);
586 * Open and bind to a device; used if we're not actually going to use
587 * the device, but are just testing whether it can be opened, or opening
588 * it to get information about it.
590 * Returns an error code on failure (always negative), and an FD for
591 * the now-bound BPF device on success (always non-negative).
593 static int
594 bpf_open_and_bind(const char *name, char *errbuf)
596 int fd;
597 struct ifreq ifr;
600 * First, open a BPF device.
602 fd = bpf_open(errbuf);
603 if (fd < 0)
604 return (fd); /* fd is the appropriate error code */
607 * Now bind to the device.
609 (void)strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
610 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
611 switch (errno) {
613 case ENXIO:
615 * There's no such device.
617 close(fd);
618 return (PCAP_ERROR_NO_SUCH_DEVICE);
620 case ENETDOWN:
622 * Return a "network down" indication, so that
623 * the application can report that rather than
624 * saying we had a mysterious failure and
625 * suggest that they report a problem to the
626 * libpcap developers.
628 close(fd);
629 return (PCAP_ERROR_IFACE_NOT_UP);
631 default:
632 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
633 "BIOCSETIF: %s: %s", name, pcap_strerror(errno));
634 close(fd);
635 return (PCAP_ERROR);
640 * Success.
642 return (fd);
645 #ifdef BIOCGDLTLIST
646 static int
647 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
649 memset(bdlp, 0, sizeof(*bdlp));
650 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
651 u_int i;
652 int is_ethernet;
654 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
655 if (bdlp->bfl_list == NULL) {
656 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
657 pcap_strerror(errno));
658 return (PCAP_ERROR);
661 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
662 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE,
663 "BIOCGDLTLIST: %s", pcap_strerror(errno));
664 free(bdlp->bfl_list);
665 return (PCAP_ERROR);
669 * OK, for real Ethernet devices, add DLT_DOCSIS to the
670 * list, so that an application can let you choose it,
671 * in case you're capturing DOCSIS traffic that a Cisco
672 * Cable Modem Termination System is putting out onto
673 * an Ethernet (it doesn't put an Ethernet header onto
674 * the wire, it puts raw DOCSIS frames out on the wire
675 * inside the low-level Ethernet framing).
677 * A "real Ethernet device" is defined here as a device
678 * that has a link-layer type of DLT_EN10MB and that has
679 * no alternate link-layer types; that's done to exclude
680 * 802.11 interfaces (which might or might not be the
681 * right thing to do, but I suspect it is - Ethernet <->
682 * 802.11 bridges would probably badly mishandle frames
683 * that don't have Ethernet headers).
685 * On Solaris with BPF, Ethernet devices also offer
686 * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
687 * treat it as an indication that the device isn't an
688 * Ethernet.
690 if (v == DLT_EN10MB) {
691 is_ethernet = 1;
692 for (i = 0; i < bdlp->bfl_len; i++) {
693 if (bdlp->bfl_list[i] != DLT_EN10MB
694 #ifdef DLT_IPNET
695 && bdlp->bfl_list[i] != DLT_IPNET
696 #endif
698 is_ethernet = 0;
699 break;
702 if (is_ethernet) {
704 * We reserved one more slot at the end of
705 * the list.
707 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
708 bdlp->bfl_len++;
711 } else {
713 * EINVAL just means "we don't support this ioctl on
714 * this device"; don't treat it as an error.
716 if (errno != EINVAL) {
717 (void)pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE,
718 "BIOCGDLTLIST: %s", pcap_strerror(errno));
719 return (PCAP_ERROR);
722 return (0);
724 #endif
726 static int
727 pcap_can_set_rfmon_bpf(pcap_t *p)
729 #if defined(__APPLE__)
730 struct utsname osinfo;
731 struct ifreq ifr;
732 int fd;
733 #ifdef BIOCGDLTLIST
734 struct bpf_dltlist bdl;
735 #endif
738 * The joys of monitor mode on OS X.
740 * Prior to 10.4, it's not supported at all.
742 * In 10.4, if adapter enN supports monitor mode, there's a
743 * wltN adapter corresponding to it; you open it, instead of
744 * enN, to get monitor mode. You get whatever link-layer
745 * headers it supplies.
747 * In 10.5, and, we assume, later releases, if adapter enN
748 * supports monitor mode, it offers, among its selectable
749 * DLT_ values, values that let you get the 802.11 header;
750 * selecting one of those values puts the adapter into monitor
751 * mode (i.e., you can't get 802.11 headers except in monitor
752 * mode, and you can't get Ethernet headers in monitor mode).
754 if (uname(&osinfo) == -1) {
756 * Can't get the OS version; just say "no".
758 return (0);
761 * We assume osinfo.sysname is "Darwin", because
762 * __APPLE__ is defined. We just check the version.
764 if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
766 * 10.3 (Darwin 7.x) or earlier.
767 * Monitor mode not supported.
769 return (0);
771 if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
773 * 10.4 (Darwin 8.x). s/en/wlt/, and check
774 * whether the device exists.
776 if (strncmp(p->opt.device, "en", 2) != 0) {
778 * Not an enN device; no monitor mode.
780 return (0);
782 fd = socket(AF_INET, SOCK_DGRAM, 0);
783 if (fd == -1) {
784 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
785 "socket: %s", pcap_strerror(errno));
786 return (PCAP_ERROR);
788 strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
789 strlcat(ifr.ifr_name, p->opt.device + 2, sizeof(ifr.ifr_name));
790 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
792 * No such device?
794 close(fd);
795 return (0);
797 close(fd);
798 return (1);
801 #ifdef BIOCGDLTLIST
803 * Everything else is 10.5 or later; for those,
804 * we just open the enN device, and check whether
805 * we have any 802.11 devices.
807 * First, open a BPF device.
809 fd = bpf_open(p->errbuf);
810 if (fd < 0)
811 return (fd); /* fd is the appropriate error code */
814 * Now bind to the device.
816 (void)strncpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
817 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
818 switch (errno) {
820 case ENXIO:
822 * There's no such device.
824 close(fd);
825 return (PCAP_ERROR_NO_SUCH_DEVICE);
827 case ENETDOWN:
829 * Return a "network down" indication, so that
830 * the application can report that rather than
831 * saying we had a mysterious failure and
832 * suggest that they report a problem to the
833 * libpcap developers.
835 close(fd);
836 return (PCAP_ERROR_IFACE_NOT_UP);
838 default:
839 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
840 "BIOCSETIF: %s: %s",
841 p->opt.device, pcap_strerror(errno));
842 close(fd);
843 return (PCAP_ERROR);
848 * We know the default link type -- now determine all the DLTs
849 * this interface supports. If this fails with EINVAL, it's
850 * not fatal; we just don't get to use the feature later.
851 * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
852 * as the default DLT for this adapter.)
854 if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
855 close(fd);
856 return (PCAP_ERROR);
858 if (find_802_11(&bdl) != -1) {
860 * We have an 802.11 DLT, so we can set monitor mode.
862 free(bdl.bfl_list);
863 close(fd);
864 return (1);
866 free(bdl.bfl_list);
867 close(fd);
868 #endif /* BIOCGDLTLIST */
869 return (0);
870 #elif defined(HAVE_BSD_IEEE80211)
871 int ret;
873 ret = monitor_mode(p, 0);
874 if (ret == PCAP_ERROR_RFMON_NOTSUP)
875 return (0); /* not an error, just a "can't do" */
876 if (ret == 0)
877 return (1); /* success */
878 return (ret);
879 #else
880 return (0);
881 #endif
884 static int
885 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
887 struct bpf_stat s;
890 * "ps_recv" counts packets handed to the filter, not packets
891 * that passed the filter. This includes packets later dropped
892 * because we ran out of buffer space.
894 * "ps_drop" counts packets dropped inside the BPF device
895 * because we ran out of buffer space. It doesn't count
896 * packets dropped by the interface driver. It counts
897 * only packets that passed the filter.
899 * Both statistics include packets not yet read from the kernel
900 * by libpcap, and thus not yet seen by the application.
902 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
903 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
904 pcap_strerror(errno));
905 return (PCAP_ERROR);
908 ps->ps_recv = s.bs_recv;
909 ps->ps_drop = s.bs_drop;
910 ps->ps_ifdrop = 0;
911 return (0);
914 static int
915 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
917 struct pcap_bpf *pb = p->priv;
918 int cc;
919 int n = 0;
920 register u_char *bp, *ep;
921 u_char *datap;
922 #ifdef PCAP_FDDIPAD
923 register u_int pad;
924 #endif
925 #ifdef HAVE_ZEROCOPY_BPF
926 int i;
927 #endif
929 again:
931 * Has "pcap_breakloop()" been called?
933 if (p->break_loop) {
935 * Yes - clear the flag that indicates that it
936 * has, and return PCAP_ERROR_BREAK to indicate
937 * that we were told to break out of the loop.
939 p->break_loop = 0;
940 return (PCAP_ERROR_BREAK);
942 cc = p->cc;
943 if (p->cc == 0) {
945 * When reading without zero-copy from a file descriptor, we
946 * use a single buffer and return a length of data in the
947 * buffer. With zero-copy, we update the p->buffer pointer
948 * to point at whatever underlying buffer contains the next
949 * data and update cc to reflect the data found in the
950 * buffer.
952 #ifdef HAVE_ZEROCOPY_BPF
953 if (pb->zerocopy) {
954 if (p->buffer != NULL)
955 pcap_ack_zbuf(p);
956 i = pcap_next_zbuf(p, &cc);
957 if (i == 0)
958 goto again;
959 if (i < 0)
960 return (PCAP_ERROR);
961 } else
962 #endif
964 cc = read(p->fd, p->buffer, p->bufsize);
966 if (cc < 0) {
967 /* Don't choke when we get ptraced */
968 switch (errno) {
970 case EINTR:
971 goto again;
973 #ifdef _AIX
974 case EFAULT:
976 * Sigh. More AIX wonderfulness.
978 * For some unknown reason the uiomove()
979 * operation in the bpf kernel extension
980 * used to copy the buffer into user
981 * space sometimes returns EFAULT. I have
982 * no idea why this is the case given that
983 * a kernel debugger shows the user buffer
984 * is correct. This problem appears to
985 * be mostly mitigated by the memset of
986 * the buffer before it is first used.
987 * Very strange.... Shaun Clowes
989 * In any case this means that we shouldn't
990 * treat EFAULT as a fatal error; as we
991 * don't have an API for returning
992 * a "some packets were dropped since
993 * the last packet you saw" indication,
994 * we just ignore EFAULT and keep reading.
996 goto again;
997 #endif
999 case EWOULDBLOCK:
1000 return (0);
1002 case ENXIO:
1004 * The device on which we're capturing
1005 * went away.
1007 * XXX - we should really return
1008 * PCAP_ERROR_IFACE_NOT_UP, but
1009 * pcap_dispatch() etc. aren't
1010 * defined to retur that.
1012 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1013 "The interface went down");
1014 return (PCAP_ERROR);
1016 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
1018 * Due to a SunOS bug, after 2^31 bytes, the kernel
1019 * file offset overflows and read fails with EINVAL.
1020 * The lseek() to 0 will fix things.
1022 case EINVAL:
1023 if (lseek(p->fd, 0L, SEEK_CUR) +
1024 p->bufsize < 0) {
1025 (void)lseek(p->fd, 0L, SEEK_SET);
1026 goto again;
1028 /* fall through */
1029 #endif
1031 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
1032 pcap_strerror(errno));
1033 return (PCAP_ERROR);
1035 bp = (u_char *)p->buffer;
1036 } else
1037 bp = p->bp;
1040 * Loop through each packet.
1042 #ifdef BIOCSTSTAMP
1043 #define bhp ((struct bpf_xhdr *)bp)
1044 #else
1045 #define bhp ((struct bpf_hdr *)bp)
1046 #endif
1047 ep = bp + cc;
1048 #ifdef PCAP_FDDIPAD
1049 pad = p->fddipad;
1050 #endif
1051 while (bp < ep) {
1052 register u_int caplen, hdrlen;
1055 * Has "pcap_breakloop()" been called?
1056 * If so, return immediately - if we haven't read any
1057 * packets, clear the flag and return PCAP_ERROR_BREAK
1058 * to indicate that we were told to break out of the loop,
1059 * otherwise leave the flag set, so that the *next* call
1060 * will break out of the loop without having read any
1061 * packets, and return the number of packets we've
1062 * processed so far.
1064 if (p->break_loop) {
1065 p->bp = bp;
1066 p->cc = ep - bp;
1068 * ep is set based on the return value of read(),
1069 * but read() from a BPF device doesn't necessarily
1070 * return a value that's a multiple of the alignment
1071 * value for BPF_WORDALIGN(). However, whenever we
1072 * increment bp, we round up the increment value by
1073 * a value rounded up by BPF_WORDALIGN(), so we
1074 * could increment bp past ep after processing the
1075 * last packet in the buffer.
1077 * We treat ep < bp as an indication that this
1078 * happened, and just set p->cc to 0.
1080 if (p->cc < 0)
1081 p->cc = 0;
1082 if (n == 0) {
1083 p->break_loop = 0;
1084 return (PCAP_ERROR_BREAK);
1085 } else
1086 return (n);
1089 caplen = bhp->bh_caplen;
1090 hdrlen = bhp->bh_hdrlen;
1091 datap = bp + hdrlen;
1093 * Short-circuit evaluation: if using BPF filter
1094 * in kernel, no need to do it now - we already know
1095 * the packet passed the filter.
1097 #ifdef PCAP_FDDIPAD
1098 * Note: the filter code was generated assuming
1099 * that p->fddipad was the amount of padding
1100 * before the header, as that's what's required
1101 * in the kernel, so we run the filter before
1102 * skipping that padding.
1103 #endif
1105 if (pb->filtering_in_kernel ||
1106 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1107 struct pcap_pkthdr pkthdr;
1108 #ifdef BIOCSTSTAMP
1109 struct bintime bt;
1111 bt.sec = bhp->bh_tstamp.bt_sec;
1112 bt.frac = bhp->bh_tstamp.bt_frac;
1113 if (p->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
1114 struct timespec ts;
1116 bintime2timespec(&bt, &ts);
1117 pkthdr.ts.tv_sec = ts.tv_sec;
1118 pkthdr.ts.tv_usec = ts.tv_nsec;
1119 } else {
1120 struct timeval tv;
1122 bintime2timeval(&bt, &tv);
1123 pkthdr.ts.tv_sec = tv.tv_sec;
1124 pkthdr.ts.tv_usec = tv.tv_usec;
1126 #else
1127 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1128 #ifdef _AIX
1130 * AIX's BPF returns seconds/nanoseconds time
1131 * stamps, not seconds/microseconds time stamps.
1133 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1134 #else
1135 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1136 #endif
1137 #endif /* BIOCSTSTAMP */
1138 #ifdef PCAP_FDDIPAD
1139 if (caplen > pad)
1140 pkthdr.caplen = caplen - pad;
1141 else
1142 pkthdr.caplen = 0;
1143 if (bhp->bh_datalen > pad)
1144 pkthdr.len = bhp->bh_datalen - pad;
1145 else
1146 pkthdr.len = 0;
1147 datap += pad;
1148 #else
1149 pkthdr.caplen = caplen;
1150 pkthdr.len = bhp->bh_datalen;
1151 #endif
1152 (*callback)(user, &pkthdr, datap);
1153 bp += BPF_WORDALIGN(caplen + hdrlen);
1154 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
1155 p->bp = bp;
1156 p->cc = ep - bp;
1158 * See comment above about p->cc < 0.
1160 if (p->cc < 0)
1161 p->cc = 0;
1162 return (n);
1164 } else {
1166 * Skip this packet.
1168 bp += BPF_WORDALIGN(caplen + hdrlen);
1171 #undef bhp
1172 p->cc = 0;
1173 return (n);
1176 static int
1177 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1179 int ret;
1181 ret = write(p->fd, buf, size);
1182 #ifdef __APPLE__
1183 if (ret == -1 && errno == EAFNOSUPPORT) {
1185 * In Mac OS X, there's a bug wherein setting the
1186 * BIOCSHDRCMPLT flag causes writes to fail; see,
1187 * for example:
1189 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1191 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
1192 * assume it's due to that bug, and turn off that flag
1193 * and try again. If we succeed, it either means that
1194 * somebody applied the fix from that URL, or other patches
1195 * for that bug from
1197 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1199 * and are running a Darwin kernel with those fixes, or
1200 * that Apple fixed the problem in some OS X release.
1202 u_int spoof_eth_src = 0;
1204 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1205 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1206 "send: can't turn off BIOCSHDRCMPLT: %s",
1207 pcap_strerror(errno));
1208 return (PCAP_ERROR);
1212 * Now try the write again.
1214 ret = write(p->fd, buf, size);
1216 #endif /* __APPLE__ */
1217 if (ret == -1) {
1218 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1219 pcap_strerror(errno));
1220 return (PCAP_ERROR);
1222 return (ret);
1225 #ifdef _AIX
1226 static int
1227 bpf_odminit(char *errbuf)
1229 char *errstr;
1231 if (odm_initialize() == -1) {
1232 if (odm_err_msg(odmerrno, &errstr) == -1)
1233 errstr = "Unknown error";
1234 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1235 "bpf_load: odm_initialize failed: %s",
1236 errstr);
1237 return (PCAP_ERROR);
1240 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1241 if (odm_err_msg(odmerrno, &errstr) == -1)
1242 errstr = "Unknown error";
1243 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1244 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1245 errstr);
1246 (void)odm_terminate();
1247 return (PCAP_ERROR);
1250 return (0);
1253 static int
1254 bpf_odmcleanup(char *errbuf)
1256 char *errstr;
1258 if (odm_unlock(odmlockid) == -1) {
1259 if (errbuf != NULL) {
1260 if (odm_err_msg(odmerrno, &errstr) == -1)
1261 errstr = "Unknown error";
1262 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1263 "bpf_load: odm_unlock failed: %s",
1264 errstr);
1266 return (PCAP_ERROR);
1269 if (odm_terminate() == -1) {
1270 if (errbuf != NULL) {
1271 if (odm_err_msg(odmerrno, &errstr) == -1)
1272 errstr = "Unknown error";
1273 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1274 "bpf_load: odm_terminate failed: %s",
1275 errstr);
1277 return (PCAP_ERROR);
1280 return (0);
1283 static int
1284 bpf_load(char *errbuf)
1286 long major;
1287 int *minors;
1288 int numminors, i, rc;
1289 char buf[1024];
1290 struct stat sbuf;
1291 struct bpf_config cfg_bpf;
1292 struct cfg_load cfg_ld;
1293 struct cfg_kmod cfg_km;
1296 * This is very very close to what happens in the real implementation
1297 * but I've fixed some (unlikely) bug situations.
1299 if (bpfloadedflag)
1300 return (0);
1302 if (bpf_odminit(errbuf) == PCAP_ERROR)
1303 return (PCAP_ERROR);
1305 major = genmajor(BPF_NAME);
1306 if (major == -1) {
1307 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1308 "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1309 (void)bpf_odmcleanup(NULL);
1310 return (PCAP_ERROR);
1313 minors = getminor(major, &numminors, BPF_NAME);
1314 if (!minors) {
1315 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1316 if (!minors) {
1317 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1318 "bpf_load: genminor failed: %s",
1319 pcap_strerror(errno));
1320 (void)bpf_odmcleanup(NULL);
1321 return (PCAP_ERROR);
1325 if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1326 return (PCAP_ERROR);
1328 rc = stat(BPF_NODE "0", &sbuf);
1329 if (rc == -1 && errno != ENOENT) {
1330 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1331 "bpf_load: can't stat %s: %s",
1332 BPF_NODE "0", pcap_strerror(errno));
1333 return (PCAP_ERROR);
1336 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1337 for (i = 0; i < BPF_MINORS; i++) {
1338 sprintf(buf, "%s%d", BPF_NODE, i);
1339 unlink(buf);
1340 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1341 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1342 "bpf_load: can't mknod %s: %s",
1343 buf, pcap_strerror(errno));
1344 return (PCAP_ERROR);
1349 /* Check if the driver is loaded */
1350 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1351 cfg_ld.path = buf;
1352 sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1353 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1354 (cfg_ld.kmid == 0)) {
1355 /* Driver isn't loaded, load it now */
1356 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1357 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1358 "bpf_load: could not load driver: %s",
1359 strerror(errno));
1360 return (PCAP_ERROR);
1364 /* Configure the driver */
1365 cfg_km.cmd = CFG_INIT;
1366 cfg_km.kmid = cfg_ld.kmid;
1367 cfg_km.mdilen = sizeof(cfg_bpf);
1368 cfg_km.mdiptr = (void *)&cfg_bpf;
1369 for (i = 0; i < BPF_MINORS; i++) {
1370 cfg_bpf.devno = domakedev(major, i);
1371 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1372 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1373 "bpf_load: could not configure driver: %s",
1374 strerror(errno));
1375 return (PCAP_ERROR);
1379 bpfloadedflag = 1;
1381 return (0);
1383 #endif
1386 * Undo any operations done when opening the device when necessary.
1388 static void
1389 pcap_cleanup_bpf(pcap_t *p)
1391 struct pcap_bpf *pb = p->priv;
1392 #ifdef HAVE_BSD_IEEE80211
1393 int sock;
1394 struct ifmediareq req;
1395 struct ifreq ifr;
1396 #endif
1398 if (pb->must_do_on_close != 0) {
1400 * There's something we have to do when closing this
1401 * pcap_t.
1403 #ifdef HAVE_BSD_IEEE80211
1404 if (pb->must_do_on_close & MUST_CLEAR_RFMON) {
1406 * We put the interface into rfmon mode;
1407 * take it out of rfmon mode.
1409 * XXX - if somebody else wants it in rfmon
1410 * mode, this code cannot know that, so it'll take
1411 * it out of rfmon mode.
1413 sock = socket(AF_INET, SOCK_DGRAM, 0);
1414 if (sock == -1) {
1415 fprintf(stderr,
1416 "Can't restore interface flags (socket() failed: %s).\n"
1417 "Please adjust manually.\n",
1418 strerror(errno));
1419 } else {
1420 memset(&req, 0, sizeof(req));
1421 strncpy(req.ifm_name, pb->device,
1422 sizeof(req.ifm_name));
1423 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1424 fprintf(stderr,
1425 "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1426 "Please adjust manually.\n",
1427 strerror(errno));
1428 } else {
1429 if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1431 * Rfmon mode is currently on;
1432 * turn it off.
1434 memset(&ifr, 0, sizeof(ifr));
1435 (void)strncpy(ifr.ifr_name,
1436 pb->device,
1437 sizeof(ifr.ifr_name));
1438 ifr.ifr_media =
1439 req.ifm_current & ~IFM_IEEE80211_MONITOR;
1440 if (ioctl(sock, SIOCSIFMEDIA,
1441 &ifr) == -1) {
1442 fprintf(stderr,
1443 "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1444 "Please adjust manually.\n",
1445 strerror(errno));
1449 close(sock);
1452 #endif /* HAVE_BSD_IEEE80211 */
1454 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1456 * Attempt to destroy the usbusN interface that we created.
1458 if (pb->must_do_on_close & MUST_DESTROY_USBUS) {
1459 if (if_nametoindex(pb->device) > 0) {
1460 int s;
1462 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1463 if (s >= 0) {
1464 strlcpy(ifr.ifr_name, pb->device,
1465 sizeof(ifr.ifr_name));
1466 ioctl(s, SIOCIFDESTROY, &ifr);
1467 close(s);
1471 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1473 * Take this pcap out of the list of pcaps for which we
1474 * have to take the interface out of some mode.
1476 pcap_remove_from_pcaps_to_close(p);
1477 pb->must_do_on_close = 0;
1480 #ifdef HAVE_ZEROCOPY_BPF
1481 if (pb->zerocopy) {
1483 * Delete the mappings. Note that p->buffer gets
1484 * initialized to one of the mmapped regions in
1485 * this case, so do not try and free it directly;
1486 * null it out so that pcap_cleanup_live_common()
1487 * doesn't try to free it.
1489 if (pb->zbuf1 != MAP_FAILED && pb->zbuf1 != NULL)
1490 (void) munmap(pb->zbuf1, pb->zbufsize);
1491 if (pb->zbuf2 != MAP_FAILED && pb->zbuf2 != NULL)
1492 (void) munmap(pb->zbuf2, pb->zbufsize);
1493 p->buffer = NULL;
1495 #endif
1496 if (pb->device != NULL) {
1497 free(pb->device);
1498 pb->device = NULL;
1500 pcap_cleanup_live_common(p);
1503 static int
1504 check_setif_failure(pcap_t *p, int error)
1506 #ifdef __APPLE__
1507 int fd;
1508 struct ifreq ifr;
1509 int err;
1510 #endif
1512 if (error == ENXIO) {
1514 * No such device exists.
1516 #ifdef __APPLE__
1517 if (p->opt.rfmon && strncmp(p->opt.device, "wlt", 3) == 0) {
1519 * Monitor mode was requested, and we're trying
1520 * to open a "wltN" device. Assume that this
1521 * is 10.4 and that we were asked to open an
1522 * "enN" device; if that device exists, return
1523 * "monitor mode not supported on the device".
1525 fd = socket(AF_INET, SOCK_DGRAM, 0);
1526 if (fd != -1) {
1527 strlcpy(ifr.ifr_name, "en",
1528 sizeof(ifr.ifr_name));
1529 strlcat(ifr.ifr_name, p->opt.device + 3,
1530 sizeof(ifr.ifr_name));
1531 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1533 * We assume this failed because
1534 * the underlying device doesn't
1535 * exist.
1537 err = PCAP_ERROR_NO_SUCH_DEVICE;
1538 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1539 "SIOCGIFFLAGS on %s failed: %s",
1540 ifr.ifr_name, pcap_strerror(errno));
1541 } else {
1543 * The underlying "enN" device
1544 * exists, but there's no
1545 * corresponding "wltN" device;
1546 * that means that the "enN"
1547 * device doesn't support
1548 * monitor mode, probably because
1549 * it's an Ethernet device rather
1550 * than a wireless device.
1552 err = PCAP_ERROR_RFMON_NOTSUP;
1554 close(fd);
1555 } else {
1557 * We can't find out whether there's
1558 * an underlying "enN" device, so
1559 * just report "no such device".
1561 err = PCAP_ERROR_NO_SUCH_DEVICE;
1562 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1563 "socket() failed: %s",
1564 pcap_strerror(errno));
1566 return (err);
1568 #endif
1570 * No such device.
1572 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
1573 pcap_strerror(errno));
1574 return (PCAP_ERROR_NO_SUCH_DEVICE);
1575 } else if (errno == ENETDOWN) {
1577 * Return a "network down" indication, so that
1578 * the application can report that rather than
1579 * saying we had a mysterious failure and
1580 * suggest that they report a problem to the
1581 * libpcap developers.
1583 return (PCAP_ERROR_IFACE_NOT_UP);
1584 } else {
1586 * Some other error; fill in the error string, and
1587 * return PCAP_ERROR.
1589 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1590 p->opt.device, pcap_strerror(errno));
1591 return (PCAP_ERROR);
1596 * Default capture buffer size.
1597 * 32K isn't very much for modern machines with fast networks; we
1598 * pick .5M, as that's the maximum on at least some systems with BPF.
1600 * However, on AIX 3.5, the larger buffer sized caused unrecoverable
1601 * read failures under stress, so we leave it as 32K; yet another
1602 * place where AIX's BPF is broken.
1604 #ifdef _AIX
1605 #define DEFAULT_BUFSIZE 32768
1606 #else
1607 #define DEFAULT_BUFSIZE 524288
1608 #endif
1610 static int
1611 pcap_activate_bpf(pcap_t *p)
1613 struct pcap_bpf *pb = p->priv;
1614 int status = 0;
1615 #ifdef HAVE_BSD_IEEE80211
1616 int retv;
1617 #endif
1618 int fd;
1619 #ifdef LIFNAMSIZ
1620 char *zonesep;
1621 struct lifreq ifr;
1622 char *ifrname = ifr.lifr_name;
1623 const size_t ifnamsiz = sizeof(ifr.lifr_name);
1624 #else
1625 struct ifreq ifr;
1626 char *ifrname = ifr.ifr_name;
1627 const size_t ifnamsiz = sizeof(ifr.ifr_name);
1628 #endif
1629 struct bpf_version bv;
1630 #ifdef __APPLE__
1631 int sockfd;
1632 char *wltdev = NULL;
1633 #endif
1634 #ifdef BIOCGDLTLIST
1635 struct bpf_dltlist bdl;
1636 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1637 int new_dlt;
1638 #endif
1639 #endif /* BIOCGDLTLIST */
1640 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1641 u_int spoof_eth_src = 1;
1642 #endif
1643 u_int v;
1644 struct bpf_insn total_insn;
1645 struct bpf_program total_prog;
1646 struct utsname osinfo;
1647 int have_osinfo = 0;
1648 #ifdef HAVE_ZEROCOPY_BPF
1649 struct bpf_zbuf bz;
1650 u_int bufmode, zbufmax;
1651 #endif
1653 fd = bpf_open(p->errbuf);
1654 if (fd < 0) {
1655 status = fd;
1656 goto bad;
1659 p->fd = fd;
1661 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1662 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1663 pcap_strerror(errno));
1664 status = PCAP_ERROR;
1665 goto bad;
1667 if (bv.bv_major != BPF_MAJOR_VERSION ||
1668 bv.bv_minor < BPF_MINOR_VERSION) {
1669 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1670 "kernel bpf filter out of date");
1671 status = PCAP_ERROR;
1672 goto bad;
1675 #if defined(LIFNAMSIZ) && defined(ZONENAME_MAX) && defined(lifr_zoneid)
1677 * Retrieve the zoneid of the zone we are currently executing in.
1679 if ((ifr.lifr_zoneid = getzoneid()) == -1) {
1680 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "getzoneid(): %s",
1681 pcap_strerror(errno));
1682 status = PCAP_ERROR;
1683 goto bad;
1686 * Check if the given source datalink name has a '/' separated
1687 * zonename prefix string. The zonename prefixed source datalink can
1688 * be used by pcap consumers in the Solaris global zone to capture
1689 * traffic on datalinks in non-global zones. Non-global zones
1690 * do not have access to datalinks outside of their own namespace.
1692 if ((zonesep = strchr(p->opt.device, '/')) != NULL) {
1693 char path_zname[ZONENAME_MAX];
1694 int znamelen;
1695 char *lnamep;
1697 if (ifr.lifr_zoneid != GLOBAL_ZONEID) {
1698 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1699 "zonename/linkname only valid in global zone.");
1700 status = PCAP_ERROR;
1701 goto bad;
1703 znamelen = zonesep - p->opt.device;
1704 (void) strlcpy(path_zname, p->opt.device, znamelen + 1);
1705 ifr.lifr_zoneid = getzoneidbyname(path_zname);
1706 if (ifr.lifr_zoneid == -1) {
1707 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1708 "getzoneidbyname(%s): %s", path_zname,
1709 pcap_strerror(errno));
1710 status = PCAP_ERROR;
1711 goto bad;
1713 lnamep = strdup(zonesep + 1);
1714 if (lnamep == NULL) {
1715 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1716 pcap_strerror(errno));
1717 status = PCAP_ERROR;
1718 goto bad;
1720 free(p->opt.device);
1721 p->opt.device = lnamep;
1723 #endif
1725 pb->device = strdup(p->opt.device);
1726 if (pb->device == NULL) {
1727 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1728 pcap_strerror(errno));
1729 status = PCAP_ERROR;
1730 goto bad;
1734 * Attempt to find out the version of the OS on which we're running.
1736 if (uname(&osinfo) == 0)
1737 have_osinfo = 1;
1739 #ifdef __APPLE__
1741 * See comment in pcap_can_set_rfmon_bpf() for an explanation
1742 * of why we check the version number.
1744 if (p->opt.rfmon) {
1745 if (have_osinfo) {
1747 * We assume osinfo.sysname is "Darwin", because
1748 * __APPLE__ is defined. We just check the version.
1750 if (osinfo.release[0] < '8' &&
1751 osinfo.release[1] == '.') {
1753 * 10.3 (Darwin 7.x) or earlier.
1755 status = PCAP_ERROR_RFMON_NOTSUP;
1756 goto bad;
1758 if (osinfo.release[0] == '8' &&
1759 osinfo.release[1] == '.') {
1761 * 10.4 (Darwin 8.x). s/en/wlt/
1763 if (strncmp(p->opt.device, "en", 2) != 0) {
1765 * Not an enN device; check
1766 * whether the device even exists.
1768 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1769 if (sockfd != -1) {
1770 strlcpy(ifrname,
1771 p->opt.device, ifnamsiz);
1772 if (ioctl(sockfd, SIOCGIFFLAGS,
1773 (char *)&ifr) < 0) {
1775 * We assume this
1776 * failed because
1777 * the underlying
1778 * device doesn't
1779 * exist.
1781 status = PCAP_ERROR_NO_SUCH_DEVICE;
1782 pcap_snprintf(p->errbuf,
1783 PCAP_ERRBUF_SIZE,
1784 "SIOCGIFFLAGS failed: %s",
1785 pcap_strerror(errno));
1786 } else
1787 status = PCAP_ERROR_RFMON_NOTSUP;
1788 close(sockfd);
1789 } else {
1791 * We can't find out whether
1792 * the device exists, so just
1793 * report "no such device".
1795 status = PCAP_ERROR_NO_SUCH_DEVICE;
1796 pcap_snprintf(p->errbuf,
1797 PCAP_ERRBUF_SIZE,
1798 "socket() failed: %s",
1799 pcap_strerror(errno));
1801 goto bad;
1803 wltdev = malloc(strlen(p->opt.device) + 2);
1804 if (wltdev == NULL) {
1805 (void)pcap_snprintf(p->errbuf,
1806 PCAP_ERRBUF_SIZE, "malloc: %s",
1807 pcap_strerror(errno));
1808 status = PCAP_ERROR;
1809 goto bad;
1811 strcpy(wltdev, "wlt");
1812 strcat(wltdev, p->opt.device + 2);
1813 free(p->opt.device);
1814 p->opt.device = wltdev;
1817 * Everything else is 10.5 or later; for those,
1818 * we just open the enN device, and set the DLT.
1822 #endif /* __APPLE__ */
1825 * If this is FreeBSD, and the device name begins with "usbus",
1826 * try to create the interface if it's not available.
1828 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
1829 if (strncmp(p->opt.device, usbus_prefix, USBUS_PREFIX_LEN) == 0) {
1831 * Do we already have an interface with that name?
1833 if (if_nametoindex(p->opt.device) == 0) {
1835 * No. We need to create it, and, if we
1836 * succeed, remember that we should destroy
1837 * it when the pcap_t is closed.
1839 int s;
1842 * Open a socket to use for ioctls to
1843 * create the interface.
1845 s = socket(AF_LOCAL, SOCK_DGRAM, 0);
1846 if (s < 0) {
1847 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1848 "Can't open socket: %s",
1849 pcap_strerror(errno));
1850 status = PCAP_ERROR;
1851 goto bad;
1855 * If we haven't already done so, arrange to have
1856 * "pcap_close_all()" called when we exit.
1858 if (!pcap_do_addexit(p)) {
1860 * "atexit()" failed; don't create the
1861 * interface, just give up.
1863 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1864 "atexit failed");
1865 close(s);
1866 status = PCAP_ERROR;
1867 goto bad;
1871 * Create the interface.
1873 strlcpy(ifr.ifr_name, p->opt.device, sizeof(ifr.ifr_name));
1874 if (ioctl(s, SIOCIFCREATE2, &ifr) < 0) {
1875 if (errno == EINVAL) {
1876 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1877 "Invalid USB bus interface %s",
1878 p->opt.device);
1879 } else {
1880 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1881 "Can't create interface for %s: %s",
1882 p->opt.device, pcap_strerror(errno));
1884 close(s);
1885 status = PCAP_ERROR;
1886 goto bad;
1890 * Make sure we clean this up when we close.
1892 pb->must_do_on_close |= MUST_DESTROY_USBUS;
1895 * Add this to the list of pcaps to close when we exit.
1897 pcap_add_to_pcaps_to_close(p);
1900 #endif /* defined(__FreeBSD__) && defined(SIOCIFCREATE2) */
1902 #ifdef HAVE_ZEROCOPY_BPF
1904 * If the BPF extension to set buffer mode is present, try setting
1905 * the mode to zero-copy. If that fails, use regular buffering. If
1906 * it succeeds but other setup fails, return an error to the user.
1908 bufmode = BPF_BUFMODE_ZBUF;
1909 if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1911 * We have zerocopy BPF; use it.
1913 pb->zerocopy = 1;
1916 * How to pick a buffer size: first, query the maximum buffer
1917 * size supported by zero-copy. This also lets us quickly
1918 * determine whether the kernel generally supports zero-copy.
1919 * Then, if a buffer size was specified, use that, otherwise
1920 * query the default buffer size, which reflects kernel
1921 * policy for a desired default. Round to the nearest page
1922 * size.
1924 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1925 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1926 pcap_strerror(errno));
1927 status = PCAP_ERROR;
1928 goto bad;
1931 if (p->opt.buffer_size != 0) {
1933 * A buffer size was explicitly specified; use it.
1935 v = p->opt.buffer_size;
1936 } else {
1937 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1938 v < DEFAULT_BUFSIZE)
1939 v = DEFAULT_BUFSIZE;
1941 #ifndef roundup
1942 #define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */
1943 #endif
1944 pb->zbufsize = roundup(v, getpagesize());
1945 if (pb->zbufsize > zbufmax)
1946 pb->zbufsize = zbufmax;
1947 pb->zbuf1 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1948 MAP_ANON, -1, 0);
1949 pb->zbuf2 = mmap(NULL, pb->zbufsize, PROT_READ | PROT_WRITE,
1950 MAP_ANON, -1, 0);
1951 if (pb->zbuf1 == MAP_FAILED || pb->zbuf2 == MAP_FAILED) {
1952 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1953 pcap_strerror(errno));
1954 status = PCAP_ERROR;
1955 goto bad;
1957 memset(&bz, 0, sizeof(bz)); /* bzero() deprecated, replaced with memset() */
1958 bz.bz_bufa = pb->zbuf1;
1959 bz.bz_bufb = pb->zbuf2;
1960 bz.bz_buflen = pb->zbufsize;
1961 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1962 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1963 pcap_strerror(errno));
1964 status = PCAP_ERROR;
1965 goto bad;
1967 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
1968 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1969 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1970 p->opt.device, pcap_strerror(errno));
1971 status = PCAP_ERROR;
1972 goto bad;
1974 v = pb->zbufsize - sizeof(struct bpf_zbuf_header);
1975 } else
1976 #endif
1979 * We don't have zerocopy BPF.
1980 * Set the buffer size.
1982 if (p->opt.buffer_size != 0) {
1984 * A buffer size was explicitly specified; use it.
1986 if (ioctl(fd, BIOCSBLEN,
1987 (caddr_t)&p->opt.buffer_size) < 0) {
1988 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1989 "BIOCSBLEN: %s: %s", p->opt.device,
1990 pcap_strerror(errno));
1991 status = PCAP_ERROR;
1992 goto bad;
1996 * Now bind to the device.
1998 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
1999 #ifdef BIOCSETLIF
2000 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
2001 #else
2002 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
2003 #endif
2005 status = check_setif_failure(p, errno);
2006 goto bad;
2008 } else {
2010 * No buffer size was explicitly specified.
2012 * Try finding a good size for the buffer;
2013 * DEFAULT_BUFSIZE may be too big, so keep
2014 * cutting it in half until we find a size
2015 * that works, or run out of sizes to try.
2016 * If the default is larger, don't make it smaller.
2018 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
2019 v < DEFAULT_BUFSIZE)
2020 v = DEFAULT_BUFSIZE;
2021 for ( ; v != 0; v >>= 1) {
2023 * Ignore the return value - this is because the
2024 * call fails on BPF systems that don't have
2025 * kernel malloc. And if the call fails, it's
2026 * no big deal, we just continue to use the
2027 * standard buffer size.
2029 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
2031 (void)strncpy(ifrname, p->opt.device, ifnamsiz);
2032 #ifdef BIOCSETLIF
2033 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
2034 #else
2035 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
2036 #endif
2037 break; /* that size worked; we're done */
2039 if (errno != ENOBUFS) {
2040 status = check_setif_failure(p, errno);
2041 goto bad;
2045 if (v == 0) {
2046 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2047 "BIOCSBLEN: %s: No buffer size worked",
2048 p->opt.device);
2049 status = PCAP_ERROR;
2050 goto bad;
2055 /* Get the data link layer type. */
2056 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
2057 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
2058 pcap_strerror(errno));
2059 status = PCAP_ERROR;
2060 goto bad;
2063 #ifdef _AIX
2065 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
2067 switch (v) {
2069 case IFT_ETHER:
2070 case IFT_ISO88023:
2071 v = DLT_EN10MB;
2072 break;
2074 case IFT_FDDI:
2075 v = DLT_FDDI;
2076 break;
2078 case IFT_ISO88025:
2079 v = DLT_IEEE802;
2080 break;
2082 case IFT_LOOP:
2083 v = DLT_NULL;
2084 break;
2086 default:
2088 * We don't know what to map this to yet.
2090 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
2092 status = PCAP_ERROR;
2093 goto bad;
2095 #endif
2096 #if _BSDI_VERSION - 0 >= 199510
2097 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
2098 switch (v) {
2100 case DLT_SLIP:
2101 v = DLT_SLIP_BSDOS;
2102 break;
2104 case DLT_PPP:
2105 v = DLT_PPP_BSDOS;
2106 break;
2108 case 11: /*DLT_FR*/
2109 v = DLT_FRELAY;
2110 break;
2112 case 12: /*DLT_C_HDLC*/
2113 v = DLT_CHDLC;
2114 break;
2116 #endif
2118 #ifdef BIOCGDLTLIST
2120 * We know the default link type -- now determine all the DLTs
2121 * this interface supports. If this fails with EINVAL, it's
2122 * not fatal; we just don't get to use the feature later.
2124 if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
2125 status = PCAP_ERROR;
2126 goto bad;
2128 p->dlt_count = bdl.bfl_len;
2129 p->dlt_list = bdl.bfl_list;
2131 #ifdef __APPLE__
2133 * Monitor mode fun, continued.
2135 * For 10.5 and, we're assuming, later releases, as noted above,
2136 * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
2137 * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
2138 * DLT_ value. Choosing one of the 802.11 DLT_ values will turn
2139 * monitor mode on.
2141 * Therefore, if the user asked for monitor mode, we filter out
2142 * the DLT_EN10MB value, as you can't get that in monitor mode,
2143 * and, if the user didn't ask for monitor mode, we filter out
2144 * the 802.11 DLT_ values, because selecting those will turn
2145 * monitor mode on. Then, for monitor mode, if an 802.11-plus-
2146 * radio DLT_ value is offered, we try to select that, otherwise
2147 * we try to select DLT_IEEE802_11.
2149 if (have_osinfo) {
2150 if (isdigit((unsigned)osinfo.release[0]) &&
2151 (osinfo.release[0] == '9' ||
2152 isdigit((unsigned)osinfo.release[1]))) {
2154 * 10.5 (Darwin 9.x), or later.
2156 new_dlt = find_802_11(&bdl);
2157 if (new_dlt != -1) {
2159 * We have at least one 802.11 DLT_ value,
2160 * so this is an 802.11 interface.
2161 * new_dlt is the best of the 802.11
2162 * DLT_ values in the list.
2164 if (p->opt.rfmon) {
2166 * Our caller wants monitor mode.
2167 * Purge DLT_EN10MB from the list
2168 * of link-layer types, as selecting
2169 * it will keep monitor mode off.
2171 remove_en(p);
2174 * If the new mode we want isn't
2175 * the default mode, attempt to
2176 * select the new mode.
2178 if ((u_int)new_dlt != v) {
2179 if (ioctl(p->fd, BIOCSDLT,
2180 &new_dlt) != -1) {
2182 * We succeeded;
2183 * make this the
2184 * new DLT_ value.
2186 v = new_dlt;
2189 } else {
2191 * Our caller doesn't want
2192 * monitor mode. Unless this
2193 * is being done by pcap_open_live(),
2194 * purge the 802.11 link-layer types
2195 * from the list, as selecting
2196 * one of them will turn monitor
2197 * mode on.
2199 if (!p->oldstyle)
2200 remove_802_11(p);
2202 } else {
2203 if (p->opt.rfmon) {
2205 * The caller requested monitor
2206 * mode, but we have no 802.11
2207 * link-layer types, so they
2208 * can't have it.
2210 status = PCAP_ERROR_RFMON_NOTSUP;
2211 goto bad;
2216 #elif defined(HAVE_BSD_IEEE80211)
2218 * *BSD with the new 802.11 ioctls.
2219 * Do we want monitor mode?
2221 if (p->opt.rfmon) {
2223 * Try to put the interface into monitor mode.
2225 retv = monitor_mode(p, 1);
2226 if (retv != 0) {
2228 * We failed.
2230 status = retv;
2231 goto bad;
2235 * We're in monitor mode.
2236 * Try to find the best 802.11 DLT_ value and, if we
2237 * succeed, try to switch to that mode if we're not
2238 * already in that mode.
2240 new_dlt = find_802_11(&bdl);
2241 if (new_dlt != -1) {
2243 * We have at least one 802.11 DLT_ value.
2244 * new_dlt is the best of the 802.11
2245 * DLT_ values in the list.
2247 * If the new mode we want isn't the default mode,
2248 * attempt to select the new mode.
2250 if ((u_int)new_dlt != v) {
2251 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
2253 * We succeeded; make this the
2254 * new DLT_ value.
2256 v = new_dlt;
2261 #endif /* various platforms */
2262 #endif /* BIOCGDLTLIST */
2265 * If this is an Ethernet device, and we don't have a DLT_ list,
2266 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
2267 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
2268 * do, but there's not much we can do about that without finding
2269 * some other way of determining whether it's an Ethernet or 802.11
2270 * device.)
2272 if (v == DLT_EN10MB && p->dlt_count == 0) {
2273 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2275 * If that fails, just leave the list empty.
2277 if (p->dlt_list != NULL) {
2278 p->dlt_list[0] = DLT_EN10MB;
2279 p->dlt_list[1] = DLT_DOCSIS;
2280 p->dlt_count = 2;
2283 #ifdef PCAP_FDDIPAD
2284 if (v == DLT_FDDI)
2285 p->fddipad = PCAP_FDDIPAD;
2286 else
2287 #endif
2288 p->fddipad = 0;
2289 p->linktype = v;
2291 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2293 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2294 * the link-layer source address isn't forcibly overwritten.
2295 * (Should we ignore errors? Should we do this only if
2296 * we're open for writing?)
2298 * XXX - I seem to remember some packet-sending bug in some
2299 * BSDs - check CVS log for "bpf.c"?
2301 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2302 (void)pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2303 "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
2304 status = PCAP_ERROR;
2305 goto bad;
2307 #endif
2308 /* set timeout */
2309 #ifdef HAVE_ZEROCOPY_BPF
2311 * In zero-copy mode, we just use the timeout in select().
2312 * XXX - what if we're in non-blocking mode and the *application*
2313 * is using select() or poll() or kqueues or....?
2315 if (p->opt.timeout && !pb->zerocopy) {
2316 #else
2317 if (p->opt.timeout) {
2318 #endif
2320 * XXX - is this seconds/nanoseconds in AIX?
2321 * (Treating it as such doesn't fix the timeout
2322 * problem described below.)
2324 * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2325 * 64-bit userland - it takes, as an argument, a
2326 * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2327 * and tv_usec, rather than a "struct timeval".
2329 * If this platform defines "struct BPF_TIMEVAL",
2330 * we check whether the structure size in BIOCSRTIMEOUT
2331 * is that of a "struct timeval" and, if not, we use
2332 * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2333 * (That way, if the bug is fixed in a future release,
2334 * we will still do the right thing.)
2336 struct timeval to;
2337 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2338 struct BPF_TIMEVAL bpf_to;
2340 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2341 bpf_to.tv_sec = p->opt.timeout / 1000;
2342 bpf_to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2343 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2344 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2345 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2346 status = PCAP_ERROR;
2347 goto bad;
2349 } else {
2350 #endif
2351 to.tv_sec = p->opt.timeout / 1000;
2352 to.tv_usec = (p->opt.timeout * 1000) % 1000000;
2353 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2354 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2355 "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2356 status = PCAP_ERROR;
2357 goto bad;
2359 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2361 #endif
2364 #ifdef BIOCIMMEDIATE
2366 * Darren Reed notes that
2368 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2369 * timeout appears to be ignored and it waits until the buffer
2370 * is filled before returning. The result of not having it
2371 * set is almost worse than useless if your BPF filter
2372 * is reducing things to only a few packets (i.e. one every
2373 * second or so).
2375 * so we always turn BIOCIMMEDIATE mode on if this is AIX.
2377 * For other platforms, we don't turn immediate mode on by default,
2378 * as that would mean we get woken up for every packet, which
2379 * probably isn't what you want for a packet sniffer.
2381 * We set immediate mode if the caller requested it by calling
2382 * pcap_set_immediate() before calling pcap_activate().
2384 #ifndef _AIX
2385 if (p->opt.immediate) {
2386 #endif /* _AIX */
2387 v = 1;
2388 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2389 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2390 "BIOCIMMEDIATE: %s", pcap_strerror(errno));
2391 status = PCAP_ERROR;
2392 goto bad;
2394 #ifndef _AIX
2396 #endif /* _AIX */
2397 #else /* BIOCIMMEDIATE */
2398 if (p->opt.immediate) {
2400 * We don't support immediate mode. Fail.
2402 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Immediate mode not supported");
2403 status = PCAP_ERROR;
2404 goto bad;
2406 #endif /* BIOCIMMEDIATE */
2408 if (p->opt.promisc) {
2409 /* set promiscuous mode, just warn if it fails */
2410 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2411 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
2412 pcap_strerror(errno));
2413 status = PCAP_WARNING_PROMISC_NOTSUP;
2417 #ifdef BIOCSTSTAMP
2418 v = BPF_T_BINTIME;
2419 if (ioctl(p->fd, BIOCSTSTAMP, &v) < 0) {
2420 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSTSTAMP: %s",
2421 pcap_strerror(errno));
2422 status = PCAP_ERROR;
2423 goto bad;
2425 #endif /* BIOCSTSTAMP */
2427 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2428 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
2429 pcap_strerror(errno));
2430 status = PCAP_ERROR;
2431 goto bad;
2433 p->bufsize = v;
2434 #ifdef HAVE_ZEROCOPY_BPF
2435 if (!pb->zerocopy) {
2436 #endif
2437 p->buffer = malloc(p->bufsize);
2438 if (p->buffer == NULL) {
2439 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2440 pcap_strerror(errno));
2441 status = PCAP_ERROR;
2442 goto bad;
2444 #ifdef _AIX
2445 /* For some strange reason this seems to prevent the EFAULT
2446 * problems we have experienced from AIX BPF. */
2447 memset(p->buffer, 0x0, p->bufsize);
2448 #endif
2449 #ifdef HAVE_ZEROCOPY_BPF
2451 #endif
2454 * If there's no filter program installed, there's
2455 * no indication to the kernel of what the snapshot
2456 * length should be, so no snapshotting is done.
2458 * Therefore, when we open the device, we install
2459 * an "accept everything" filter with the specified
2460 * snapshot length.
2462 total_insn.code = (u_short)(BPF_RET | BPF_K);
2463 total_insn.jt = 0;
2464 total_insn.jf = 0;
2465 total_insn.k = p->snapshot;
2467 total_prog.bf_len = 1;
2468 total_prog.bf_insns = &total_insn;
2469 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2470 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2471 pcap_strerror(errno));
2472 status = PCAP_ERROR;
2473 goto bad;
2477 * On most BPF platforms, either you can do a "select()" or
2478 * "poll()" on a BPF file descriptor and it works correctly,
2479 * or you can do it and it will return "readable" if the
2480 * hold buffer is full but not if the timeout expires *and*
2481 * a non-blocking read will, if the hold buffer is empty
2482 * but the store buffer isn't empty, rotate the buffers
2483 * and return what packets are available.
2485 * In the latter case, the fact that a non-blocking read
2486 * will give you the available packets means you can work
2487 * around the failure of "select()" and "poll()" to wake up
2488 * and return "readable" when the timeout expires by using
2489 * the timeout as the "select()" or "poll()" timeout, putting
2490 * the BPF descriptor into non-blocking mode, and read from
2491 * it regardless of whether "select()" reports it as readable
2492 * or not.
2494 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2495 * won't wake up and return "readable" if the timer expires
2496 * and non-blocking reads return EWOULDBLOCK if the hold
2497 * buffer is empty, even if the store buffer is non-empty.
2499 * This means the workaround in question won't work.
2501 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2502 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2503 * here". On all other BPF platforms, we set it to the FD for
2504 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2505 * read will, if the hold buffer is empty and the store buffer
2506 * isn't empty, rotate the buffers and return what packets are
2507 * there (and in sufficiently recent versions of OpenBSD
2508 * "select()" and "poll()" should work correctly).
2510 * XXX - what about AIX?
2512 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
2513 if (have_osinfo) {
2515 * We can check what OS this is.
2517 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2518 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2519 strncmp(osinfo.release, "4.4-", 4) == 0)
2520 p->selectable_fd = -1;
2524 p->read_op = pcap_read_bpf;
2525 p->inject_op = pcap_inject_bpf;
2526 p->setfilter_op = pcap_setfilter_bpf;
2527 p->setdirection_op = pcap_setdirection_bpf;
2528 p->set_datalink_op = pcap_set_datalink_bpf;
2529 p->getnonblock_op = pcap_getnonblock_bpf;
2530 p->setnonblock_op = pcap_setnonblock_bpf;
2531 p->stats_op = pcap_stats_bpf;
2532 p->cleanup_op = pcap_cleanup_bpf;
2534 return (status);
2535 bad:
2536 pcap_cleanup_bpf(p);
2537 return (status);
2541 * Not all interfaces can be bound to by BPF, so try to bind to
2542 * the specified interface; return 0 if we fail with
2543 * PCAP_ERROR_NO_SUCH_DEVICE (which means we got an ENXIO when we tried
2544 * to bind, which means this interface isn't in the list of interfaces
2545 * attached to BPF) and 1 otherwise.
2547 static int
2548 check_bpf_bindable(const char *name)
2550 int fd;
2551 char errbuf[PCAP_ERRBUF_SIZE];
2553 fd = bpf_open_and_bind(name, errbuf);
2554 if (fd < 0) {
2556 * Error - was it PCAP_ERROR_NO_SUCH_DEVICE?
2558 if (fd == PCAP_ERROR_NO_SUCH_DEVICE) {
2560 * Yes, so we can't bind to this because it's
2561 * not something supported by BPF.
2563 return (0);
2566 * No, so we don't know whether it's supported or not;
2567 * say it is, so that the user can at least try to
2568 * open it and report the error (which is probably
2569 * "you don't have permission to open BPF devices";
2570 * reporting those interfaces means users will ask
2571 * "why am I getting a permissions error when I try
2572 * to capture" rather than "why am I not seeing any
2573 * interfaces", making the underlying problem clearer).
2575 return (1);
2579 * Success.
2581 close(fd);
2582 return (1);
2585 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
2586 static int
2587 finddevs_usb(pcap_if_t **alldevsp, char *errbuf)
2589 DIR *usbdir;
2590 struct dirent *usbitem;
2591 size_t name_max;
2592 char *name;
2595 * We might have USB sniffing support, so try looking for USB
2596 * interfaces.
2598 * We want to report a usbusN device for each USB bus, but
2599 * usbusN interfaces might, or might not, exist for them -
2600 * we create one if there isn't already one.
2602 * So, instead, we look in /dev/usb for all buses and create
2603 * a "usbusN" device for each one.
2605 usbdir = opendir("/dev/usb");
2606 if (usbdir == NULL) {
2608 * Just punt.
2610 return (0);
2614 * Leave enough room for a 32-bit (10-digit) bus number.
2615 * Yes, that's overkill, but we won't be using
2616 * the buffer very long.
2618 name_max = USBUS_PREFIX_LEN + 10 + 1;
2619 name = malloc(name_max);
2620 if (name == NULL) {
2621 closedir(usbdir);
2622 return (0);
2624 while ((usbitem = readdir(usbdir)) != NULL) {
2625 char *p;
2626 size_t busnumlen;
2627 int err;
2629 if (strcmp(usbitem->d_name, ".") == 0 ||
2630 strcmp(usbitem->d_name, "..") == 0) {
2632 * Ignore these.
2634 continue;
2636 p = strchr(usbitem->d_name, '.');
2637 if (p == NULL)
2638 continue;
2639 busnumlen = p - usbitem->d_name;
2640 memcpy(name, usbus_prefix, USBUS_PREFIX_LEN);
2641 memcpy(name + USBUS_PREFIX_LEN, usbitem->d_name, busnumlen);
2642 *(name + USBUS_PREFIX_LEN + busnumlen) = '\0';
2643 err = pcap_add_if(alldevsp, name, PCAP_IF_UP, NULL, errbuf);
2644 if (err != 0) {
2645 free(name);
2646 closedir(usbdir);
2647 return (err);
2650 free(name);
2651 closedir(usbdir);
2652 return (0);
2654 #endif
2657 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2660 * Get the list of regular interfaces first.
2662 if (pcap_findalldevs_interfaces(alldevsp, errbuf, check_bpf_bindable) == -1)
2663 return (-1); /* failure */
2665 #if defined(__FreeBSD__) && defined(SIOCIFCREATE2)
2666 if (finddevs_usb(alldevsp, errbuf) == -1)
2667 return (-1);
2668 #endif
2670 return (0);
2673 #ifdef HAVE_BSD_IEEE80211
2674 static int
2675 monitor_mode(pcap_t *p, int set)
2677 struct pcap_bpf *pb = p->priv;
2678 int sock;
2679 struct ifmediareq req;
2680 IFM_ULIST_TYPE *media_list;
2681 int i;
2682 int can_do;
2683 struct ifreq ifr;
2685 sock = socket(AF_INET, SOCK_DGRAM, 0);
2686 if (sock == -1) {
2687 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2688 pcap_strerror(errno));
2689 return (PCAP_ERROR);
2692 memset(&req, 0, sizeof req);
2693 strncpy(req.ifm_name, p->opt.device, sizeof req.ifm_name);
2696 * Find out how many media types we have.
2698 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2700 * Can't get the media types.
2702 switch (errno) {
2704 case ENXIO:
2706 * There's no such device.
2708 close(sock);
2709 return (PCAP_ERROR_NO_SUCH_DEVICE);
2711 case EINVAL:
2713 * Interface doesn't support SIOC{G,S}IFMEDIA.
2715 close(sock);
2716 return (PCAP_ERROR_RFMON_NOTSUP);
2718 default:
2719 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2720 "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
2721 close(sock);
2722 return (PCAP_ERROR);
2725 if (req.ifm_count == 0) {
2727 * No media types.
2729 close(sock);
2730 return (PCAP_ERROR_RFMON_NOTSUP);
2734 * Allocate a buffer to hold all the media types, and
2735 * get the media types.
2737 media_list = malloc(req.ifm_count * sizeof(*media_list));
2738 if (media_list == NULL) {
2739 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2740 pcap_strerror(errno));
2741 close(sock);
2742 return (PCAP_ERROR);
2744 req.ifm_ulist = media_list;
2745 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2746 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2747 pcap_strerror(errno));
2748 free(media_list);
2749 close(sock);
2750 return (PCAP_ERROR);
2754 * Look for an 802.11 "automatic" media type.
2755 * We assume that all 802.11 adapters have that media type,
2756 * and that it will carry the monitor mode supported flag.
2758 can_do = 0;
2759 for (i = 0; i < req.ifm_count; i++) {
2760 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2761 && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2762 /* OK, does it do monitor mode? */
2763 if (media_list[i] & IFM_IEEE80211_MONITOR) {
2764 can_do = 1;
2765 break;
2769 free(media_list);
2770 if (!can_do) {
2772 * This adapter doesn't support monitor mode.
2774 close(sock);
2775 return (PCAP_ERROR_RFMON_NOTSUP);
2778 if (set) {
2780 * Don't just check whether we can enable monitor mode,
2781 * do so, if it's not already enabled.
2783 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2785 * Monitor mode isn't currently on, so turn it on,
2786 * and remember that we should turn it off when the
2787 * pcap_t is closed.
2791 * If we haven't already done so, arrange to have
2792 * "pcap_close_all()" called when we exit.
2794 if (!pcap_do_addexit(p)) {
2796 * "atexit()" failed; don't put the interface
2797 * in monitor mode, just give up.
2799 close(sock);
2800 return (PCAP_ERROR);
2802 memset(&ifr, 0, sizeof(ifr));
2803 (void)strncpy(ifr.ifr_name, p->opt.device,
2804 sizeof(ifr.ifr_name));
2805 ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2806 if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2807 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2808 "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2809 close(sock);
2810 return (PCAP_ERROR);
2813 pb->must_do_on_close |= MUST_CLEAR_RFMON;
2816 * Add this to the list of pcaps to close when we exit.
2818 pcap_add_to_pcaps_to_close(p);
2821 return (0);
2823 #endif /* HAVE_BSD_IEEE80211 */
2825 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2827 * Check whether we have any 802.11 link-layer types; return the best
2828 * of the 802.11 link-layer types if we find one, and return -1
2829 * otherwise.
2831 * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2832 * best 802.11 link-layer type; any of the other 802.11-plus-radio
2833 * headers are second-best; 802.11 with no radio information is
2834 * the least good.
2836 static int
2837 find_802_11(struct bpf_dltlist *bdlp)
2839 int new_dlt;
2840 u_int i;
2843 * Scan the list of DLT_ values, looking for 802.11 values,
2844 * and, if we find any, choose the best of them.
2846 new_dlt = -1;
2847 for (i = 0; i < bdlp->bfl_len; i++) {
2848 switch (bdlp->bfl_list[i]) {
2850 case DLT_IEEE802_11:
2852 * 802.11, but no radio.
2854 * Offer this, and select it as the new mode
2855 * unless we've already found an 802.11
2856 * header with radio information.
2858 if (new_dlt == -1)
2859 new_dlt = bdlp->bfl_list[i];
2860 break;
2862 case DLT_PRISM_HEADER:
2863 case DLT_AIRONET_HEADER:
2864 case DLT_IEEE802_11_RADIO_AVS:
2866 * 802.11 with radio, but not radiotap.
2868 * Offer this, and select it as the new mode
2869 * unless we've already found the radiotap DLT_.
2871 if (new_dlt != DLT_IEEE802_11_RADIO)
2872 new_dlt = bdlp->bfl_list[i];
2873 break;
2875 case DLT_IEEE802_11_RADIO:
2877 * 802.11 with radiotap.
2879 * Offer this, and select it as the new mode.
2881 new_dlt = bdlp->bfl_list[i];
2882 break;
2884 default:
2886 * Not 802.11.
2888 break;
2892 return (new_dlt);
2894 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2896 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
2898 * Remove DLT_EN10MB from the list of DLT_ values, as we're in monitor mode,
2899 * and DLT_EN10MB isn't supported in monitor mode.
2901 static void
2902 remove_en(pcap_t *p)
2904 int i, j;
2907 * Scan the list of DLT_ values and discard DLT_EN10MB.
2909 j = 0;
2910 for (i = 0; i < p->dlt_count; i++) {
2911 switch (p->dlt_list[i]) {
2913 case DLT_EN10MB:
2915 * Don't offer this one.
2917 continue;
2919 default:
2921 * Just copy this mode over.
2923 break;
2927 * Copy this DLT_ value to its new position.
2929 p->dlt_list[j] = p->dlt_list[i];
2930 j++;
2934 * Set the DLT_ count to the number of entries we copied.
2936 p->dlt_count = j;
2940 * Remove 802.11 link-layer types from the list of DLT_ values, as
2941 * we're not in monitor mode, and those DLT_ values will switch us
2942 * to monitor mode.
2944 static void
2945 remove_802_11(pcap_t *p)
2947 int i, j;
2950 * Scan the list of DLT_ values and discard 802.11 values.
2952 j = 0;
2953 for (i = 0; i < p->dlt_count; i++) {
2954 switch (p->dlt_list[i]) {
2956 case DLT_IEEE802_11:
2957 case DLT_PRISM_HEADER:
2958 case DLT_AIRONET_HEADER:
2959 case DLT_IEEE802_11_RADIO:
2960 case DLT_IEEE802_11_RADIO_AVS:
2962 * 802.11. Don't offer this one.
2964 continue;
2966 default:
2968 * Just copy this mode over.
2970 break;
2974 * Copy this DLT_ value to its new position.
2976 p->dlt_list[j] = p->dlt_list[i];
2977 j++;
2981 * Set the DLT_ count to the number of entries we copied.
2983 p->dlt_count = j;
2985 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
2987 static int
2988 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
2990 struct pcap_bpf *pb = p->priv;
2993 * Free any user-mode filter we might happen to have installed.
2995 pcap_freecode(&p->fcode);
2998 * Try to install the kernel filter.
3000 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
3002 * It worked.
3004 pb->filtering_in_kernel = 1; /* filtering in the kernel */
3007 * Discard any previously-received packets, as they might
3008 * have passed whatever filter was formerly in effect, but
3009 * might not pass this filter (BIOCSETF discards packets
3010 * buffered in the kernel, so you can lose packets in any
3011 * case).
3013 p->cc = 0;
3014 return (0);
3018 * We failed.
3020 * If it failed with EINVAL, that's probably because the program
3021 * is invalid or too big. Validate it ourselves; if we like it
3022 * (we currently allow backward branches, to support protochain),
3023 * run it in userland. (There's no notion of "too big" for
3024 * userland.)
3026 * Otherwise, just give up.
3027 * XXX - if the copy of the program into the kernel failed,
3028 * we will get EINVAL rather than, say, EFAULT on at least
3029 * some kernels.
3031 if (errno != EINVAL) {
3032 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
3033 pcap_strerror(errno));
3034 return (-1);
3038 * install_bpf_program() validates the program.
3040 * XXX - what if we already have a filter in the kernel?
3042 if (install_bpf_program(p, fp) < 0)
3043 return (-1);
3044 pb->filtering_in_kernel = 0; /* filtering in userland */
3045 return (0);
3049 * Set direction flag: Which packets do we accept on a forwarding
3050 * single device? IN, OUT or both?
3052 static int
3053 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
3055 #if defined(BIOCSDIRECTION)
3056 u_int direction;
3058 direction = (d == PCAP_D_IN) ? BPF_D_IN :
3059 ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
3060 if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
3061 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3062 "Cannot set direction to %s: %s",
3063 (d == PCAP_D_IN) ? "PCAP_D_IN" :
3064 ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
3065 strerror(errno));
3066 return (-1);
3068 return (0);
3069 #elif defined(BIOCSSEESENT)
3070 u_int seesent;
3073 * We don't support PCAP_D_OUT.
3075 if (d == PCAP_D_OUT) {
3076 pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3077 "Setting direction to PCAP_D_OUT is not supported on BPF");
3078 return -1;
3081 seesent = (d == PCAP_D_INOUT);
3082 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
3083 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3084 "Cannot set direction to %s: %s",
3085 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
3086 strerror(errno));
3087 return (-1);
3089 return (0);
3090 #else
3091 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3092 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
3093 return (-1);
3094 #endif
3097 static int
3098 pcap_set_datalink_bpf(pcap_t *p, int dlt)
3100 #ifdef BIOCSDLT
3101 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
3102 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
3103 "Cannot set DLT %d: %s", dlt, strerror(errno));
3104 return (-1);
3106 #endif
3107 return (0);