add winpcap 4.0.2 from url http://www.winpcap.org/
[natblaster.git] / winpcap / wpcap / libpcap / pcap-bpf.c
blob56c3db7c2c46c80d1d00747285039fc07b3c9bfd
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.86.2.9 2006/01/22 05:28:34 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 #include <sys/time.h>
32 #include <sys/timeb.h>
33 #include <sys/socket.h>
34 #include <sys/file.h>
35 #include <sys/ioctl.h>
36 #include <sys/utsname.h>
38 #include <net/if.h>
40 #ifdef _AIX
43 * Make "pcap.h" not include "pcap-bpf.h"; we are going to include the
44 * native OS version, as we need "struct bpf_config" from it.
46 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
48 #include <sys/types.h>
51 * Prevent bpf.h from redefining the DLT_ values to their
52 * IFT_ values, as we're going to return the standard libpcap
53 * values, not IBM's non-standard IFT_ values.
55 #undef _AIX
56 #include <net/bpf.h>
57 #define _AIX
59 #include <net/if_types.h> /* for IFT_ values */
60 #include <sys/sysconfig.h>
61 #include <sys/device.h>
62 #include <sys/cfgodm.h>
63 #include <cf.h>
65 #ifdef __64BIT__
66 #define domakedev makedev64
67 #define getmajor major64
68 #define bpf_hdr bpf_hdr32
69 #else /* __64BIT__ */
70 #define domakedev makedev
71 #define getmajor major
72 #endif /* __64BIT__ */
74 #define BPF_NAME "bpf"
75 #define BPF_MINORS 4
76 #define DRIVER_PATH "/usr/lib/drivers"
77 #define BPF_NODE "/dev/bpf"
78 static int bpfloadedflag = 0;
79 static int odmlockid = 0;
81 #else /* _AIX */
83 #include <net/bpf.h>
85 #endif /* _AIX */
87 #include <ctype.h>
88 #include <errno.h>
89 #include <netdb.h>
90 #include <stdio.h>
91 #include <stdlib.h>
92 #include <string.h>
93 #include <unistd.h>
95 #include "pcap-int.h"
97 #ifdef HAVE_DAG_API
98 #include "pcap-dag.h"
99 #endif /* HAVE_DAG_API */
101 #ifdef HAVE_OS_PROTO_H
102 #include "os-proto.h"
103 #endif
105 #ifdef HAVE_REMOTE
106 #include <pcap-remote.h>
107 #endif /* HAVE_REMOTE */
109 #include "gencode.h" /* for "no_optimize" */
111 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
112 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
113 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
115 static int
116 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
118 struct bpf_stat s;
121 * "ps_recv" counts packets handed to the filter, not packets
122 * that passed the filter. This includes packets later dropped
123 * because we ran out of buffer space.
125 * "ps_drop" counts packets dropped inside the BPF device
126 * because we ran out of buffer space. It doesn't count
127 * packets dropped by the interface driver. It counts
128 * only packets that passed the filter.
130 * Both statistics include packets not yet read from the kernel
131 * by libpcap, and thus not yet seen by the application.
133 if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
134 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
135 pcap_strerror(errno));
136 return (-1);
139 ps->ps_recv = s.bs_recv;
140 ps->ps_drop = s.bs_drop;
141 return (0);
144 static int
145 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
147 int cc;
148 int n = 0;
149 register u_char *bp, *ep;
150 u_char *datap;
151 struct bpf_insn *fcode;
152 #ifdef PCAP_FDDIPAD
153 register int pad;
154 #endif
156 fcode = p->md.use_bpf ? NULL : p->fcode.bf_insns;
157 again:
159 * Has "pcap_breakloop()" been called?
161 if (p->break_loop) {
163 * Yes - clear the flag that indicates that it
164 * has, and return -2 to indicate that we were
165 * told to break out of the loop.
167 p->break_loop = 0;
168 return (-2);
170 cc = p->cc;
171 if (p->cc == 0) {
172 cc = read(p->fd, (char *)p->buffer, p->bufsize);
173 if (cc < 0) {
174 /* Don't choke when we get ptraced */
175 switch (errno) {
177 case EINTR:
178 goto again;
180 #ifdef _AIX
181 case EFAULT:
183 * Sigh. More AIX wonderfulness.
185 * For some unknown reason the uiomove()
186 * operation in the bpf kernel extension
187 * used to copy the buffer into user
188 * space sometimes returns EFAULT. I have
189 * no idea why this is the case given that
190 * a kernel debugger shows the user buffer
191 * is correct. This problem appears to
192 * be mostly mitigated by the memset of
193 * the buffer before it is first used.
194 * Very strange.... Shaun Clowes
196 * In any case this means that we shouldn't
197 * treat EFAULT as a fatal error; as we
198 * don't have an API for returning
199 * a "some packets were dropped since
200 * the last packet you saw" indication,
201 * we just ignore EFAULT and keep reading.
203 goto again;
204 #endif
206 case EWOULDBLOCK:
207 return (0);
208 #if defined(sun) && !defined(BSD)
210 * Due to a SunOS bug, after 2^31 bytes, the kernel
211 * file offset overflows and read fails with EINVAL.
212 * The lseek() to 0 will fix things.
214 case EINVAL:
215 if (lseek(p->fd, 0L, SEEK_CUR) +
216 p->bufsize < 0) {
217 (void)lseek(p->fd, 0L, SEEK_SET);
218 goto again;
220 /* fall through */
221 #endif
223 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
224 pcap_strerror(errno));
225 return (-1);
227 bp = p->buffer;
228 } else
229 bp = p->bp;
232 * Loop through each packet.
234 #define bhp ((struct bpf_hdr *)bp)
235 ep = bp + cc;
236 #ifdef PCAP_FDDIPAD
237 pad = p->fddipad;
238 #endif
239 while (bp < ep) {
240 register int caplen, hdrlen;
243 * Has "pcap_breakloop()" been called?
244 * If so, return immediately - if we haven't read any
245 * packets, clear the flag and return -2 to indicate
246 * that we were told to break out of the loop, otherwise
247 * leave the flag set, so that the *next* call will break
248 * out of the loop without having read any packets, and
249 * return the number of packets we've processed so far.
251 if (p->break_loop) {
252 if (n == 0) {
253 p->break_loop = 0;
254 return (-2);
255 } else {
256 p->bp = bp;
257 p->cc = ep - bp;
258 return (n);
262 caplen = bhp->bh_caplen;
263 hdrlen = bhp->bh_hdrlen;
264 datap = bp + hdrlen;
266 * Short-circuit evaluation: if using BPF filter
267 * in kernel, no need to do it now.
269 #ifdef PCAP_FDDIPAD
270 * Note: the filter code was generated assuming
271 * that p->fddipad was the amount of padding
272 * before the header, as that's what's required
273 * in the kernel, so we run the filter before
274 * skipping that padding.
275 #endif
277 if (fcode == NULL ||
278 bpf_filter(fcode, datap, bhp->bh_datalen, caplen)) {
279 struct pcap_pkthdr pkthdr;
281 pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
282 #ifdef _AIX
284 * AIX's BPF returns seconds/nanoseconds time
285 * stamps, not seconds/microseconds time stamps.
287 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
288 #else
289 pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
290 #endif
291 #ifdef PCAP_FDDIPAD
292 if (caplen > pad)
293 pkthdr.caplen = caplen - pad;
294 else
295 pkthdr.caplen = 0;
296 if (bhp->bh_datalen > pad)
297 pkthdr.len = bhp->bh_datalen - pad;
298 else
299 pkthdr.len = 0;
300 datap += pad;
301 #else
302 pkthdr.caplen = caplen;
303 pkthdr.len = bhp->bh_datalen;
304 #endif
305 (*callback)(user, &pkthdr, datap);
306 bp += BPF_WORDALIGN(caplen + hdrlen);
307 if (++n >= cnt && cnt > 0) {
308 p->bp = bp;
309 p->cc = ep - bp;
310 return (n);
312 } else {
314 * Skip this packet.
316 bp += BPF_WORDALIGN(caplen + hdrlen);
319 #undef bhp
320 p->cc = 0;
321 return (n);
324 static int
325 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
327 int ret;
329 ret = write(p->fd, buf, size);
330 #ifdef __APPLE__
331 if (ret == -1 && errno == EAFNOSUPPORT) {
333 * In Mac OS X, there's a bug wherein setting the
334 * BIOCSHDRCMPLT flag causes writes to fail; see,
335 * for example:
337 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
339 * So, if, on OS X, we get EAFNOSUPPORT from the write, we
340 * assume it's due to that bug, and turn off that flag
341 * and try again. If we succeed, it either means that
342 * somebody applied the fix from that URL, or other patches
343 * for that bug from
345 * http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
347 * and are running a Darwin kernel with those fixes, or
348 * that Apple fixed the problem in some OS X release.
350 u_int spoof_eth_src = 0;
352 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
353 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
354 "send: can't turn off BIOCSHDRCMPLT: %s",
355 pcap_strerror(errno));
356 return (-1);
360 * Now try the write again.
362 ret = write(p->fd, buf, size);
364 #endif /* __APPLE__ */
365 if (ret == -1) {
366 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
367 pcap_strerror(errno));
368 return (-1);
370 return (ret);
373 #ifdef _AIX
374 static int
375 bpf_odminit(char *errbuf)
377 char *errstr;
379 if (odm_initialize() == -1) {
380 if (odm_err_msg(odmerrno, &errstr) == -1)
381 errstr = "Unknown error";
382 snprintf(errbuf, PCAP_ERRBUF_SIZE,
383 "bpf_load: odm_initialize failed: %s",
384 errstr);
385 return (-1);
388 if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
389 if (odm_err_msg(odmerrno, &errstr) == -1)
390 errstr = "Unknown error";
391 snprintf(errbuf, PCAP_ERRBUF_SIZE,
392 "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
393 errstr);
394 return (-1);
397 return (0);
400 static int
401 bpf_odmcleanup(char *errbuf)
403 char *errstr;
405 if (odm_unlock(odmlockid) == -1) {
406 if (odm_err_msg(odmerrno, &errstr) == -1)
407 errstr = "Unknown error";
408 snprintf(errbuf, PCAP_ERRBUF_SIZE,
409 "bpf_load: odm_unlock failed: %s",
410 errstr);
411 return (-1);
414 if (odm_terminate() == -1) {
415 if (odm_err_msg(odmerrno, &errstr) == -1)
416 errstr = "Unknown error";
417 snprintf(errbuf, PCAP_ERRBUF_SIZE,
418 "bpf_load: odm_terminate failed: %s",
419 errstr);
420 return (-1);
423 return (0);
426 static int
427 bpf_load(char *errbuf)
429 long major;
430 int *minors;
431 int numminors, i, rc;
432 char buf[1024];
433 struct stat sbuf;
434 struct bpf_config cfg_bpf;
435 struct cfg_load cfg_ld;
436 struct cfg_kmod cfg_km;
439 * This is very very close to what happens in the real implementation
440 * but I've fixed some (unlikely) bug situations.
442 if (bpfloadedflag)
443 return (0);
445 if (bpf_odminit(errbuf) != 0)
446 return (-1);
448 major = genmajor(BPF_NAME);
449 if (major == -1) {
450 snprintf(errbuf, PCAP_ERRBUF_SIZE,
451 "bpf_load: genmajor failed: %s", pcap_strerror(errno));
452 return (-1);
455 minors = getminor(major, &numminors, BPF_NAME);
456 if (!minors) {
457 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
458 if (!minors) {
459 snprintf(errbuf, PCAP_ERRBUF_SIZE,
460 "bpf_load: genminor failed: %s",
461 pcap_strerror(errno));
462 return (-1);
466 if (bpf_odmcleanup(errbuf))
467 return (-1);
469 rc = stat(BPF_NODE "0", &sbuf);
470 if (rc == -1 && errno != ENOENT) {
471 snprintf(errbuf, PCAP_ERRBUF_SIZE,
472 "bpf_load: can't stat %s: %s",
473 BPF_NODE "0", pcap_strerror(errno));
474 return (-1);
477 if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
478 for (i = 0; i < BPF_MINORS; i++) {
479 sprintf(buf, "%s%d", BPF_NODE, i);
480 unlink(buf);
481 if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
482 snprintf(errbuf, PCAP_ERRBUF_SIZE,
483 "bpf_load: can't mknod %s: %s",
484 buf, pcap_strerror(errno));
485 return (-1);
490 /* Check if the driver is loaded */
491 memset(&cfg_ld, 0x0, sizeof(cfg_ld));
492 cfg_ld.path = buf;
493 sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
494 if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
495 (cfg_ld.kmid == 0)) {
496 /* Driver isn't loaded, load it now */
497 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
498 snprintf(errbuf, PCAP_ERRBUF_SIZE,
499 "bpf_load: could not load driver: %s",
500 strerror(errno));
501 return (-1);
505 /* Configure the driver */
506 cfg_km.cmd = CFG_INIT;
507 cfg_km.kmid = cfg_ld.kmid;
508 cfg_km.mdilen = sizeof(cfg_bpf);
509 cfg_km.mdiptr = (void *)&cfg_bpf;
510 for (i = 0; i < BPF_MINORS; i++) {
511 cfg_bpf.devno = domakedev(major, i);
512 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
513 snprintf(errbuf, PCAP_ERRBUF_SIZE,
514 "bpf_load: could not configure driver: %s",
515 strerror(errno));
516 return (-1);
520 bpfloadedflag = 1;
522 return (0);
524 #endif
526 static inline int
527 bpf_open(pcap_t *p, char *errbuf)
529 int fd;
530 int n = 0;
531 char device[sizeof "/dev/bpf0000000000"];
533 #ifdef _AIX
535 * Load the bpf driver, if it isn't already loaded,
536 * and create the BPF device entries, if they don't
537 * already exist.
539 if (bpf_load(errbuf) == -1)
540 return (-1);
541 #endif
544 * Go through all the minors and find one that isn't in use.
546 do {
547 (void)snprintf(device, sizeof(device), "/dev/bpf%d", n++);
549 * Initially try a read/write open (to allow the inject
550 * method to work). If that fails due to permission
551 * issues, fall back to read-only. This allows a
552 * non-root user to be granted specific access to pcap
553 * capabilities via file permissions.
555 * XXX - we should have an API that has a flag that
556 * controls whether to open read-only or read-write,
557 * so that denial of permission to send (or inability
558 * to send, if sending packets isn't supported on
559 * the device in question) can be indicated at open
560 * time.
562 fd = open(device, O_RDWR);
563 if (fd == -1 && errno == EACCES)
564 fd = open(device, O_RDONLY);
565 } while (fd < 0 && errno == EBUSY);
568 * XXX better message for all minors used
570 if (fd < 0)
571 snprintf(errbuf, PCAP_ERRBUF_SIZE, "(no devices found) %s: %s",
572 device, pcap_strerror(errno));
574 return (fd);
578 * We include the OS's <net/bpf.h>, not our "pcap-bpf.h", so we probably
579 * don't get DLT_DOCSIS defined.
581 #ifndef DLT_DOCSIS
582 #define DLT_DOCSIS 143
583 #endif
585 pcap_t *
586 pcap_open_live(const char *device, int snaplen, int promisc, int to_ms,
587 char *ebuf)
589 int fd;
590 struct ifreq ifr;
591 struct bpf_version bv;
592 #ifdef BIOCGDLTLIST
593 struct bpf_dltlist bdl;
594 #endif
595 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
596 u_int spoof_eth_src = 1;
597 #endif
598 u_int v;
599 pcap_t *p;
600 struct bpf_insn total_insn;
601 struct bpf_program total_prog;
602 struct utsname osinfo;
604 #ifdef HAVE_REMOTE
606 Retrofit; we have to make older applications compatible with the remote capture
607 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
608 Obviously, we cannot exploit all the new features; for instance, we cannot
609 send authentication, we cannot use a UDP data connection, and so on.
612 char host[PCAP_BUF_SIZE + 1];
613 char port[PCAP_BUF_SIZE + 1];
614 char name[PCAP_BUF_SIZE + 1];
615 int srctype;
617 if (pcap_parsesrcstr(device, &srctype, host, port, name, ebuf) )
618 return NULL;
620 if (srctype == PCAP_SRC_IFREMOTE)
622 p= pcap_opensource_remote(device, NULL, ebuf);
624 if (p == NULL)
625 return NULL;
627 p->snapshot= snaplen;
628 p->timeout= to_ms;
629 p->rmt_flags= (promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0;
631 return p;
633 #endif /* HAVE_REMOTE */
635 #ifdef HAVE_DAG_API
636 if (strstr(device, "dag")) {
637 return dag_open_live(device, snaplen, promisc, to_ms, ebuf);
639 #endif /* HAVE_DAG_API */
641 #ifdef BIOCGDLTLIST
642 memset(&bdl, 0, sizeof(bdl));
643 #endif
645 p = (pcap_t *)malloc(sizeof(*p));
646 if (p == NULL) {
647 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
648 pcap_strerror(errno));
649 return (NULL);
651 memset(p, 0, sizeof(*p));
652 fd = bpf_open(p, ebuf);
653 if (fd < 0)
654 goto bad;
656 p->fd = fd;
657 p->snapshot = snaplen;
659 if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
660 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
661 pcap_strerror(errno));
662 goto bad;
664 if (bv.bv_major != BPF_MAJOR_VERSION ||
665 bv.bv_minor < BPF_MINOR_VERSION) {
666 snprintf(ebuf, PCAP_ERRBUF_SIZE,
667 "kernel bpf filter out of date");
668 goto bad;
672 * Try finding a good size for the buffer; 32768 may be too
673 * big, so keep cutting it in half until we find a size
674 * that works, or run out of sizes to try. If the default
675 * is larger, don't make it smaller.
677 * XXX - there should be a user-accessible hook to set the
678 * initial buffer size.
680 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) || v < 32768)
681 v = 32768;
682 for ( ; v != 0; v >>= 1) {
683 /* Ignore the return value - this is because the call fails
684 * on BPF systems that don't have kernel malloc. And if
685 * the call fails, it's no big deal, we just continue to
686 * use the standard buffer size.
688 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
690 (void)strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
691 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
692 break; /* that size worked; we're done */
694 if (errno != ENOBUFS) {
695 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
696 device, pcap_strerror(errno));
697 goto bad;
701 if (v == 0) {
702 snprintf(ebuf, PCAP_ERRBUF_SIZE,
703 "BIOCSBLEN: %s: No buffer size worked", device);
704 goto bad;
707 /* Get the data link layer type. */
708 if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
709 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
710 pcap_strerror(errno));
711 goto bad;
713 #ifdef _AIX
715 * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
717 switch (v) {
719 case IFT_ETHER:
720 case IFT_ISO88023:
721 v = DLT_EN10MB;
722 break;
724 case IFT_FDDI:
725 v = DLT_FDDI;
726 break;
728 case IFT_ISO88025:
729 v = DLT_IEEE802;
730 break;
732 case IFT_LOOP:
733 v = DLT_NULL;
734 break;
736 default:
738 * We don't know what to map this to yet.
740 snprintf(ebuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
742 goto bad;
744 #endif
745 #if _BSDI_VERSION - 0 >= 199510
746 /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
747 switch (v) {
749 case DLT_SLIP:
750 v = DLT_SLIP_BSDOS;
751 break;
753 case DLT_PPP:
754 v = DLT_PPP_BSDOS;
755 break;
757 case 11: /*DLT_FR*/
758 v = DLT_FRELAY;
759 break;
761 case 12: /*DLT_C_HDLC*/
762 v = DLT_CHDLC;
763 break;
765 #endif
766 #ifdef PCAP_FDDIPAD
767 if (v == DLT_FDDI)
768 p->fddipad = PCAP_FDDIPAD;
769 else
770 p->fddipad = 0;
771 #endif
772 p->linktype = v;
774 #ifdef BIOCGDLTLIST
776 * We know the default link type -- now determine all the DLTs
777 * this interface supports. If this fails with EINVAL, it's
778 * not fatal; we just don't get to use the feature later.
780 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)&bdl) == 0) {
781 u_int i;
782 int is_ethernet;
784 bdl.bfl_list = (u_int *) malloc(sizeof(u_int) * (bdl.bfl_len + 1));
785 if (bdl.bfl_list == NULL) {
786 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
787 pcap_strerror(errno));
788 goto bad;
791 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)&bdl) < 0) {
792 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
793 "BIOCGDLTLIST: %s", pcap_strerror(errno));
794 free(bdl.bfl_list);
795 goto bad;
799 * OK, for real Ethernet devices, add DLT_DOCSIS to the
800 * list, so that an application can let you choose it,
801 * in case you're capturing DOCSIS traffic that a Cisco
802 * Cable Modem Termination System is putting out onto
803 * an Ethernet (it doesn't put an Ethernet header onto
804 * the wire, it puts raw DOCSIS frames out on the wire
805 * inside the low-level Ethernet framing).
807 * A "real Ethernet device" is defined here as a device
808 * that has a link-layer type of DLT_EN10MB and that has
809 * no alternate link-layer types; that's done to exclude
810 * 802.11 interfaces (which might or might not be the
811 * right thing to do, but I suspect it is - Ethernet <->
812 * 802.11 bridges would probably badly mishandle frames
813 * that don't have Ethernet headers).
815 if (p->linktype == DLT_EN10MB) {
816 is_ethernet = 1;
817 for (i = 0; i < bdl.bfl_len; i++) {
818 if (bdl.bfl_list[i] != DLT_EN10MB) {
819 is_ethernet = 0;
820 break;
823 if (is_ethernet) {
825 * We reserved one more slot at the end of
826 * the list.
828 bdl.bfl_list[bdl.bfl_len] = DLT_DOCSIS;
829 bdl.bfl_len++;
832 p->dlt_count = bdl.bfl_len;
833 p->dlt_list = bdl.bfl_list;
834 } else {
835 if (errno != EINVAL) {
836 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
837 "BIOCGDLTLIST: %s", pcap_strerror(errno));
838 goto bad;
841 #endif
844 * If this is an Ethernet device, and we don't have a DLT_ list,
845 * give it a list with DLT_EN10MB and DLT_DOCSIS. (That'd give
846 * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
847 * do, but there's not much we can do about that without finding
848 * some other way of determining whether it's an Ethernet or 802.11
849 * device.)
851 if (p->linktype == DLT_EN10MB && p->dlt_count == 0) {
852 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
854 * If that fails, just leave the list empty.
856 if (p->dlt_list != NULL) {
857 p->dlt_list[0] = DLT_EN10MB;
858 p->dlt_list[1] = DLT_DOCSIS;
859 p->dlt_count = 2;
863 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
865 * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
866 * the link-layer source address isn't forcibly overwritten.
867 * (Should we ignore errors? Should we do this only if
868 * we're open for writing?)
870 * XXX - I seem to remember some packet-sending bug in some
871 * BSDs - check CVS log for "bpf.c"?
873 if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
874 (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
875 "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
876 goto bad;
878 #endif
879 /* set timeout */
880 if (to_ms != 0) {
882 * XXX - is this seconds/nanoseconds in AIX?
883 * (Treating it as such doesn't fix the timeout
884 * problem described below.)
886 struct timeval to;
887 to.tv_sec = to_ms / 1000;
888 to.tv_usec = (to_ms * 1000) % 1000000;
889 if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
890 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSRTIMEOUT: %s",
891 pcap_strerror(errno));
892 goto bad;
896 #ifdef _AIX
897 #ifdef BIOCIMMEDIATE
899 * Darren Reed notes that
901 * On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
902 * timeout appears to be ignored and it waits until the buffer
903 * is filled before returning. The result of not having it
904 * set is almost worse than useless if your BPF filter
905 * is reducing things to only a few packets (i.e. one every
906 * second or so).
908 * so we turn BIOCIMMEDIATE mode on if this is AIX.
910 * We don't turn it on for other platforms, as that means we
911 * get woken up for every packet, which may not be what we want;
912 * in the Winter 1993 USENIX paper on BPF, they say:
914 * Since a process might want to look at every packet on a
915 * network and the time between packets can be only a few
916 * microseconds, it is not possible to do a read system call
917 * per packet and BPF must collect the data from several
918 * packets and return it as a unit when the monitoring
919 * application does a read.
921 * which I infer is the reason for the timeout - it means we
922 * wait that amount of time, in the hopes that more packets
923 * will arrive and we'll get them all with one read.
925 * Setting BIOCIMMEDIATE mode on FreeBSD (and probably other
926 * BSDs) causes the timeout to be ignored.
928 * On the other hand, some platforms (e.g., Linux) don't support
929 * timeouts, they just hand stuff to you as soon as it arrives;
930 * if that doesn't cause a problem on those platforms, it may
931 * be OK to have BIOCIMMEDIATE mode on BSD as well.
933 * (Note, though, that applications may depend on the read
934 * completing, even if no packets have arrived, when the timeout
935 * expires, e.g. GUI applications that have to check for input
936 * while waiting for packets to arrive; a non-zero timeout
937 * prevents "select()" from working right on FreeBSD and
938 * possibly other BSDs, as the timer doesn't start until a
939 * "read()" is done, so the timer isn't in effect if the
940 * application is blocked on a "select()", and the "select()"
941 * doesn't get woken up for a BPF device until the buffer
942 * fills up.)
944 v = 1;
945 if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
946 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCIMMEDIATE: %s",
947 pcap_strerror(errno));
948 goto bad;
950 #endif /* BIOCIMMEDIATE */
951 #endif /* _AIX */
953 if (promisc) {
954 /* set promiscuous mode, okay if it fails */
955 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
956 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
957 pcap_strerror(errno));
961 if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
962 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
963 pcap_strerror(errno));
964 goto bad;
966 p->bufsize = v;
967 p->buffer = (u_char *)malloc(p->bufsize);
968 if (p->buffer == NULL) {
969 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
970 pcap_strerror(errno));
971 goto bad;
973 #ifdef _AIX
974 /* For some strange reason this seems to prevent the EFAULT
975 * problems we have experienced from AIX BPF. */
976 memset(p->buffer, 0x0, p->bufsize);
977 #endif
980 * If there's no filter program installed, there's
981 * no indication to the kernel of what the snapshot
982 * length should be, so no snapshotting is done.
984 * Therefore, when we open the device, we install
985 * an "accept everything" filter with the specified
986 * snapshot length.
988 total_insn.code = (u_short)(BPF_RET | BPF_K);
989 total_insn.jt = 0;
990 total_insn.jf = 0;
991 total_insn.k = snaplen;
993 total_prog.bf_len = 1;
994 total_prog.bf_insns = &total_insn;
995 if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
996 snprintf(ebuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
997 pcap_strerror(errno));
998 goto bad;
1002 * On most BPF platforms, either you can do a "select()" or
1003 * "poll()" on a BPF file descriptor and it works correctly,
1004 * or you can do it and it will return "readable" if the
1005 * hold buffer is full but not if the timeout expires *and*
1006 * a non-blocking read will, if the hold buffer is empty
1007 * but the store buffer isn't empty, rotate the buffers
1008 * and return what packets are available.
1010 * In the latter case, the fact that a non-blocking read
1011 * will give you the available packets means you can work
1012 * around the failure of "select()" and "poll()" to wake up
1013 * and return "readable" when the timeout expires by using
1014 * the timeout as the "select()" or "poll()" timeout, putting
1015 * the BPF descriptor into non-blocking mode, and read from
1016 * it regardless of whether "select()" reports it as readable
1017 * or not.
1019 * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
1020 * won't wake up and return "readable" if the timer expires
1021 * and non-blocking reads return EWOULDBLOCK if the hold
1022 * buffer is empty, even if the store buffer is non-empty.
1024 * This means the workaround in question won't work.
1026 * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
1027 * to -1, which means "sorry, you can't use 'select()' or 'poll()'
1028 * here". On all other BPF platforms, we set it to the FD for
1029 * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
1030 * read will, if the hold buffer is empty and the store buffer
1031 * isn't empty, rotate the buffers and return what packets are
1032 * there (and in sufficiently recent versions of OpenBSD
1033 * "select()" and "poll()" should work correctly).
1035 * XXX - what about AIX?
1037 p->selectable_fd = p->fd; /* assume select() works until we know otherwise */
1038 if (uname(&osinfo) == 0) {
1040 * We can check what OS this is.
1042 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
1043 if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
1044 strncmp(osinfo.release, "4.4-", 4) == 0)
1045 p->selectable_fd = -1;
1049 p->read_op = pcap_read_bpf;
1050 p->inject_op = pcap_inject_bpf;
1051 p->setfilter_op = pcap_setfilter_bpf;
1052 p->setdirection_op = pcap_setdirection_bpf;
1053 p->set_datalink_op = pcap_set_datalink_bpf;
1054 p->getnonblock_op = pcap_getnonblock_fd;
1055 p->setnonblock_op = pcap_setnonblock_fd;
1056 p->stats_op = pcap_stats_bpf;
1057 p->close_op = pcap_close_common;
1059 return (p);
1060 bad:
1061 (void)close(fd);
1062 if (p->dlt_list != NULL)
1063 free(p->dlt_list);
1064 free(p);
1065 return (NULL);
1069 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
1071 #ifdef HAVE_DAG_API
1072 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
1073 return (-1);
1074 #endif /* HAVE_DAG_API */
1076 return (0);
1079 static int
1080 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
1083 * It looks that BPF code generated by gen_protochain() is not
1084 * compatible with some of kernel BPF code (for example BSD/OS 3.1).
1085 * Take a safer side for now.
1087 if (no_optimize) {
1089 * XXX - what if we already have a filter in the kernel?
1091 if (install_bpf_program(p, fp) < 0)
1092 return (-1);
1093 p->md.use_bpf = 0; /* filtering in userland */
1094 return (0);
1098 * Free any user-mode filter we might happen to have installed.
1100 pcap_freecode(&p->fcode);
1103 * Try to install the kernel filter.
1105 if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) < 0) {
1106 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
1107 pcap_strerror(errno));
1108 return (-1);
1110 p->md.use_bpf = 1; /* filtering in the kernel */
1113 * Discard any previously-received packets, as they might have
1114 * passed whatever filter was formerly in effect, but might
1115 * not pass this filter (BIOCSETF discards packets buffered
1116 * in the kernel, so you can lose packets in any case).
1118 p->cc = 0;
1119 return (0);
1123 * Set direction flag: Which packets do we accept on a forwarding
1124 * single device? IN, OUT or both?
1126 static int
1127 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
1129 #ifdef BIOCSSEESENT
1130 u_int seesent;
1131 #endif
1134 * We don't support PCAP_D_OUT.
1136 if (d == PCAP_D_OUT) {
1137 snprintf(p->errbuf, sizeof(p->errbuf),
1138 "Setting direction to PCAP_D_OUT is not supported on BPF");
1139 return -1;
1141 #ifdef BIOCSSEESENT
1142 seesent = (d == PCAP_D_INOUT);
1143 if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
1144 (void) snprintf(p->errbuf, sizeof(p->errbuf),
1145 "Cannot set direction to %s: %s",
1146 (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
1147 strerror(errno));
1148 return (-1);
1150 return (0);
1151 #else
1152 (void) snprintf(p->errbuf, sizeof(p->errbuf),
1153 "This system doesn't support BIOCSSEESENT, so the direction can't be set");
1154 return (-1);
1155 #endif
1158 static int
1159 pcap_set_datalink_bpf(pcap_t *p, int dlt)
1161 #ifdef BIOCSDLT
1162 if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
1163 (void) snprintf(p->errbuf, sizeof(p->errbuf),
1164 "Cannot set DLT %d: %s", dlt, strerror(errno));
1165 return (-1);
1167 #endif
1168 return (0);