]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - contrib/libpcap/pcap-bpf.c
MFC r238935,238960:
[FreeBSD/releng/9.1.git] / contrib / libpcap / pcap-bpf.c
1 /*
2  * Copyright (c) 1993, 1994, 1995, 1996, 1998
3  *      The Regents of the University of California.  All rights reserved.
4  *
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.
20  *
21  * $FreeBSD$
22  */
23 #ifndef lint
24 static const char rcsid[] _U_ =
25     "@(#) $Header: /tcpdump/master/libpcap/pcap-bpf.c,v 1.116 2008-09-16 18:42:29 guy Exp $ (LBL)";
26 #endif
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #include <sys/param.h>                  /* optionally get BSD define */
33 #ifdef HAVE_ZEROCOPY_BPF
34 #include <sys/mman.h>
35 #endif
36 #include <sys/socket.h>
37 #include <time.h>
38 /*
39  * <net/bpf.h> defines ioctls, but doesn't include <sys/ioccom.h>.
40  *
41  * We include <sys/ioctl.h> as it might be necessary to declare ioctl();
42  * at least on *BSD and Mac OS X, it also defines various SIOC ioctls -
43  * we could include <sys/sockio.h>, but if we're already including
44  * <sys/ioctl.h>, which includes <sys/sockio.h> on those platforms,
45  * there's not much point in doing so.
46  *
47  * If we have <sys/ioccom.h>, we include it as well, to handle systems
48  * such as Solaris which don't arrange to include <sys/ioccom.h> if you
49  * include <sys/ioctl.h>
50  */
51 #include <sys/ioctl.h>
52 #ifdef HAVE_SYS_IOCCOM_H
53 #include <sys/ioccom.h>
54 #endif
55 #include <sys/utsname.h>
56
57 #ifdef HAVE_ZEROCOPY_BPF
58 #include <machine/atomic.h>
59 #endif
60
61 #include <net/if.h>
62
63 #ifdef _AIX
64
65 /*
66  * Make "pcap.h" not include "pcap/bpf.h"; we are going to include the
67  * native OS version, as we need "struct bpf_config" from it.
68  */
69 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
70
71 #include <sys/types.h>
72
73 /*
74  * Prevent bpf.h from redefining the DLT_ values to their
75  * IFT_ values, as we're going to return the standard libpcap
76  * values, not IBM's non-standard IFT_ values.
77  */
78 #undef _AIX
79 #include <net/bpf.h>
80 #define _AIX
81
82 #include <net/if_types.h>               /* for IFT_ values */
83 #include <sys/sysconfig.h>
84 #include <sys/device.h>
85 #include <sys/cfgodm.h>
86 #include <cf.h>
87
88 #ifdef __64BIT__
89 #define domakedev makedev64
90 #define getmajor major64
91 #define bpf_hdr bpf_hdr32
92 #else /* __64BIT__ */
93 #define domakedev makedev
94 #define getmajor major
95 #endif /* __64BIT__ */
96
97 #define BPF_NAME "bpf"
98 #define BPF_MINORS 4
99 #define DRIVER_PATH "/usr/lib/drivers"
100 #define BPF_NODE "/dev/bpf"
101 static int bpfloadedflag = 0;
102 static int odmlockid = 0;
103
104 static int bpf_load(char *errbuf);
105
106 #else /* _AIX */
107
108 #include <net/bpf.h>
109
110 #endif /* _AIX */
111
112 #include <ctype.h>
113 #include <fcntl.h>
114 #include <errno.h>
115 #include <netdb.h>
116 #include <stdio.h>
117 #include <stdlib.h>
118 #include <string.h>
119 #include <unistd.h>
120
121 #ifdef HAVE_NET_IF_MEDIA_H
122 # include <net/if_media.h>
123 #endif
124
125 #include "pcap-int.h"
126
127 #ifdef HAVE_DAG_API
128 #include "pcap-dag.h"
129 #endif /* HAVE_DAG_API */
130
131 #ifdef HAVE_SNF_API
132 #include "pcap-snf.h"
133 #endif /* HAVE_SNF_API */
134
135 #ifdef HAVE_OS_PROTO_H
136 #include "os-proto.h"
137 #endif
138
139 #ifdef BIOCGDLTLIST
140 # if (defined(HAVE_NET_IF_MEDIA_H) && defined(IFM_IEEE80211)) && !defined(__APPLE__)
141 #define HAVE_BSD_IEEE80211
142 # endif
143
144 # if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
145 static int find_802_11(struct bpf_dltlist *);
146
147 #  ifdef HAVE_BSD_IEEE80211
148 static int monitor_mode(pcap_t *, int);
149 #  endif
150
151 #  if defined(__APPLE__)
152 static void remove_en(pcap_t *);
153 static void remove_802_11(pcap_t *);
154 #  endif
155
156 # endif /* defined(__APPLE__) || defined(HAVE_BSD_IEEE80211) */
157
158 #endif /* BIOCGDLTLIST */
159
160 /*
161  * We include the OS's <net/bpf.h>, not our "pcap/bpf.h", so we probably
162  * don't get DLT_DOCSIS defined.
163  */
164 #ifndef DLT_DOCSIS
165 #define DLT_DOCSIS      143
166 #endif
167
168 /*
169  * On OS X, we don't even get any of the 802.11-plus-radio-header DLT_'s
170  * defined, even though some of them are used by various Airport drivers.
171  */
172 #ifndef DLT_PRISM_HEADER
173 #define DLT_PRISM_HEADER        119
174 #endif
175 #ifndef DLT_AIRONET_HEADER
176 #define DLT_AIRONET_HEADER      120
177 #endif
178 #ifndef DLT_IEEE802_11_RADIO
179 #define DLT_IEEE802_11_RADIO    127
180 #endif
181 #ifndef DLT_IEEE802_11_RADIO_AVS
182 #define DLT_IEEE802_11_RADIO_AVS 163
183 #endif
184
185 static int pcap_can_set_rfmon_bpf(pcap_t *p);
186 static int pcap_activate_bpf(pcap_t *p);
187 static int pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp);
188 static int pcap_setdirection_bpf(pcap_t *, pcap_direction_t);
189 static int pcap_set_datalink_bpf(pcap_t *p, int dlt);
190
191 /*
192  * For zerocopy bpf, the setnonblock/getnonblock routines need to modify
193  * p->md.timeout so we don't call select(2) if the pcap handle is in non-
194  * blocking mode.  We preserve the timeout supplied by pcap_open functions
195  * to make sure it does not get clobbered if the pcap handle moves between
196  * blocking and non-blocking mode.
197  */
198 static int
199 pcap_getnonblock_bpf(pcap_t *p, char *errbuf)
200
201 #ifdef HAVE_ZEROCOPY_BPF
202         if (p->md.zerocopy) {
203                 /*
204                  * Use a negative value for the timeout to represent that the
205                  * pcap handle is in non-blocking mode.
206                  */
207                 return (p->md.timeout < 0);
208         }
209 #endif
210         return (pcap_getnonblock_fd(p, errbuf));
211 }
212
213 static int
214 pcap_setnonblock_bpf(pcap_t *p, int nonblock, char *errbuf)
215 {   
216 #ifdef HAVE_ZEROCOPY_BPF
217         if (p->md.zerocopy) {
218                 /*
219                  * Map each value to the corresponding 2's complement, to
220                  * preserve the timeout value provided with pcap_set_timeout.
221                  * (from pcap-linux.c).
222                  */
223                 if (nonblock) {
224                         if (p->md.timeout >= 0) {
225                                 /*
226                                  * Timeout is non-negative, so we're not
227                                  * currently in non-blocking mode; set it
228                                  * to the 2's complement, to make it
229                                  * negative, as an indication that we're
230                                  * in non-blocking mode.
231                                  */
232                                 p->md.timeout = p->md.timeout * -1 - 1;
233                         }
234                 } else {
235                         if (p->md.timeout < 0) {
236                                 /*
237                                  * Timeout is negative, so we're currently
238                                  * in blocking mode; reverse the previous
239                                  * operation, to make the timeout non-negative
240                                  * again.
241                                  */
242                                 p->md.timeout = (p->md.timeout + 1) * -1;
243                         }
244                 }
245                 return (0);
246         }
247 #endif
248         return (pcap_setnonblock_fd(p, nonblock, errbuf));
249 }
250
251 #ifdef HAVE_ZEROCOPY_BPF
252 /*
253  * Zero-copy BPF buffer routines to check for and acknowledge BPF data in
254  * shared memory buffers.
255  *
256  * pcap_next_zbuf_shm(): Check for a newly available shared memory buffer,
257  * and set up p->buffer and cc to reflect one if available.  Notice that if
258  * there was no prior buffer, we select zbuf1 as this will be the first
259  * buffer filled for a fresh BPF session.
260  */
261 static int
262 pcap_next_zbuf_shm(pcap_t *p, int *cc)
263 {
264         struct bpf_zbuf_header *bzh;
265
266         if (p->md.zbuffer == p->md.zbuf2 || p->md.zbuffer == NULL) {
267                 bzh = (struct bpf_zbuf_header *)p->md.zbuf1;
268                 if (bzh->bzh_user_gen !=
269                     atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
270                         p->md.bzh = bzh;
271                         p->md.zbuffer = (u_char *)p->md.zbuf1;
272                         p->buffer = p->md.zbuffer + sizeof(*bzh);
273                         *cc = bzh->bzh_kernel_len;
274                         return (1);
275                 }
276         } else if (p->md.zbuffer == p->md.zbuf1) {
277                 bzh = (struct bpf_zbuf_header *)p->md.zbuf2;
278                 if (bzh->bzh_user_gen !=
279                     atomic_load_acq_int(&bzh->bzh_kernel_gen)) {
280                         p->md.bzh = bzh;
281                         p->md.zbuffer = (u_char *)p->md.zbuf2;
282                         p->buffer = p->md.zbuffer + sizeof(*bzh);
283                         *cc = bzh->bzh_kernel_len;
284                         return (1);
285                 }
286         }
287         *cc = 0;
288         return (0);
289 }
290
291 /*
292  * pcap_next_zbuf() -- Similar to pcap_next_zbuf_shm(), except wait using
293  * select() for data or a timeout, and possibly force rotation of the buffer
294  * in the event we time out or are in immediate mode.  Invoke the shared
295  * memory check before doing system calls in order to avoid doing avoidable
296  * work.
297  */
298 static int
299 pcap_next_zbuf(pcap_t *p, int *cc)
300 {
301         struct bpf_zbuf bz;
302         struct timeval tv;
303         struct timespec cur;
304         fd_set r_set;
305         int data, r;
306         int expire, tmout;
307
308 #define TSTOMILLI(ts) (((ts)->tv_sec * 1000) + ((ts)->tv_nsec / 1000000))
309         /*
310          * Start out by seeing whether anything is waiting by checking the
311          * next shared memory buffer for data.
312          */
313         data = pcap_next_zbuf_shm(p, cc);
314         if (data)
315                 return (data);
316         /*
317          * If a previous sleep was interrupted due to signal delivery, make
318          * sure that the timeout gets adjusted accordingly.  This requires
319          * that we analyze when the timeout should be been expired, and
320          * subtract the current time from that.  If after this operation,
321          * our timeout is less then or equal to zero, handle it like a
322          * regular timeout.
323          */
324         tmout = p->md.timeout;
325         if (tmout)
326                 (void) clock_gettime(CLOCK_MONOTONIC, &cur);
327         if (p->md.interrupted && p->md.timeout) {
328                 expire = TSTOMILLI(&p->md.firstsel) + p->md.timeout;
329                 tmout = expire - TSTOMILLI(&cur);
330 #undef TSTOMILLI
331                 if (tmout <= 0) {
332                         p->md.interrupted = 0;
333                         data = pcap_next_zbuf_shm(p, cc);
334                         if (data)
335                                 return (data);
336                         if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
337                                 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
338                                     "BIOCROTZBUF: %s", strerror(errno));
339                                 return (PCAP_ERROR);
340                         }
341                         return (pcap_next_zbuf_shm(p, cc));
342                 }
343         }
344         /*
345          * No data in the buffer, so must use select() to wait for data or
346          * the next timeout.  Note that we only call select if the handle
347          * is in blocking mode.
348          */
349         if (p->md.timeout >= 0) {
350                 FD_ZERO(&r_set);
351                 FD_SET(p->fd, &r_set);
352                 if (tmout != 0) {
353                         tv.tv_sec = tmout / 1000;
354                         tv.tv_usec = (tmout * 1000) % 1000000;
355                 }
356                 r = select(p->fd + 1, &r_set, NULL, NULL,
357                     p->md.timeout != 0 ? &tv : NULL);
358                 if (r < 0 && errno == EINTR) {
359                         if (!p->md.interrupted && p->md.timeout) {
360                                 p->md.interrupted = 1;
361                                 p->md.firstsel = cur;
362                         }
363                         return (0);
364                 } else if (r < 0) {
365                         (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
366                             "select: %s", strerror(errno));
367                         return (PCAP_ERROR);
368                 }
369         }
370         p->md.interrupted = 0;
371         /*
372          * Check again for data, which may exist now that we've either been
373          * woken up as a result of data or timed out.  Try the "there's data"
374          * case first since it doesn't require a system call.
375          */
376         data = pcap_next_zbuf_shm(p, cc);
377         if (data)
378                 return (data);
379         /*
380          * Try forcing a buffer rotation to dislodge timed out or immediate
381          * data.
382          */
383         if (ioctl(p->fd, BIOCROTZBUF, &bz) < 0) {
384                 (void) snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
385                     "BIOCROTZBUF: %s", strerror(errno));
386                 return (PCAP_ERROR);
387         }
388         return (pcap_next_zbuf_shm(p, cc));
389 }
390
391 /*
392  * Notify kernel that we are done with the buffer.  We don't reset zbuffer so
393  * that we know which buffer to use next time around.
394  */
395 static int
396 pcap_ack_zbuf(pcap_t *p)
397 {
398
399         atomic_store_rel_int(&p->md.bzh->bzh_user_gen,
400             p->md.bzh->bzh_kernel_gen);
401         p->md.bzh = NULL;
402         p->buffer = NULL;
403         return (0);
404 }
405 #endif /* HAVE_ZEROCOPY_BPF */
406
407 pcap_t *
408 pcap_create(const char *device, char *ebuf)
409 {
410         pcap_t *p;
411
412 #ifdef HAVE_DAG_API
413         if (strstr(device, "dag"))
414                 return (dag_create(device, ebuf));
415 #endif /* HAVE_DAG_API */
416 #ifdef HAVE_SNF_API
417         if (strstr(device, "snf"))
418                 return (snf_create(device, ebuf));
419 #endif /* HAVE_SNF_API */
420
421         p = pcap_create_common(device, ebuf);
422         if (p == NULL)
423                 return (NULL);
424
425         p->activate_op = pcap_activate_bpf;
426         p->can_set_rfmon_op = pcap_can_set_rfmon_bpf;
427         return (p);
428 }
429
430 /*
431  * On success, returns a file descriptor for a BPF device.
432  * On failure, returns a PCAP_ERROR_ value, and sets p->errbuf.
433  */
434 static int
435 bpf_open(pcap_t *p)
436 {
437         int fd;
438 #ifdef HAVE_CLONING_BPF
439         static const char device[] = "/dev/bpf";
440 #else
441         int n = 0;
442         char device[sizeof "/dev/bpf0000000000"];
443 #endif
444
445 #ifdef _AIX
446         /*
447          * Load the bpf driver, if it isn't already loaded,
448          * and create the BPF device entries, if they don't
449          * already exist.
450          */
451         if (bpf_load(p->errbuf) == PCAP_ERROR)
452                 return (PCAP_ERROR);
453 #endif
454
455 #ifdef HAVE_CLONING_BPF
456         if ((fd = open(device, O_RDWR)) == -1 &&
457             (errno != EACCES || (fd = open(device, O_RDONLY)) == -1)) {
458                 if (errno == EACCES)
459                         fd = PCAP_ERROR_PERM_DENIED;
460                 else
461                         fd = PCAP_ERROR;
462                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
463                   "(cannot open device) %s: %s", device, pcap_strerror(errno));
464         }
465 #else
466         /*
467          * Go through all the minors and find one that isn't in use.
468          */
469         do {
470                 (void)snprintf(device, sizeof(device), "/dev/bpf%d", n++);
471                 /*
472                  * Initially try a read/write open (to allow the inject
473                  * method to work).  If that fails due to permission
474                  * issues, fall back to read-only.  This allows a
475                  * non-root user to be granted specific access to pcap
476                  * capabilities via file permissions.
477                  *
478                  * XXX - we should have an API that has a flag that
479                  * controls whether to open read-only or read-write,
480                  * so that denial of permission to send (or inability
481                  * to send, if sending packets isn't supported on
482                  * the device in question) can be indicated at open
483                  * time.
484                  */
485                 fd = open(device, O_RDWR);
486                 if (fd == -1 && errno == EACCES)
487                         fd = open(device, O_RDONLY);
488         } while (fd < 0 && errno == EBUSY);
489
490         /*
491          * XXX better message for all minors used
492          */
493         if (fd < 0) {
494                 switch (errno) {
495
496                 case ENOENT:
497                         fd = PCAP_ERROR;
498                         if (n == 1) {
499                                 /*
500                                  * /dev/bpf0 doesn't exist, which
501                                  * means we probably have no BPF
502                                  * devices.
503                                  */
504                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
505                                     "(there are no BPF devices)");
506                         } else {
507                                 /*
508                                  * We got EBUSY on at least one
509                                  * BPF device, so we have BPF
510                                  * devices, but all the ones
511                                  * that exist are busy.
512                                  */
513                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
514                                     "(all BPF devices are busy)");
515                         }
516                         break;
517
518                 case EACCES:
519                         /*
520                          * Got EACCES on the last device we tried,
521                          * and EBUSY on all devices before that,
522                          * if any.
523                          */
524                         fd = PCAP_ERROR_PERM_DENIED;
525                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
526                             "(cannot open BPF device) %s: %s", device,
527                             pcap_strerror(errno));
528                         break;
529
530                 default:
531                         /*
532                          * Some other problem.
533                          */
534                         fd = PCAP_ERROR;
535                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
536                             "(cannot open BPF device) %s: %s", device,
537                             pcap_strerror(errno));
538                         break;
539                 }
540         }
541 #endif
542
543         return (fd);
544 }
545
546 #ifdef BIOCGDLTLIST
547 static int
548 get_dlt_list(int fd, int v, struct bpf_dltlist *bdlp, char *ebuf)
549 {
550         memset(bdlp, 0, sizeof(*bdlp));
551         if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) == 0) {
552                 u_int i;
553                 int is_ethernet;
554
555                 bdlp->bfl_list = (u_int *) malloc(sizeof(u_int) * (bdlp->bfl_len + 1));
556                 if (bdlp->bfl_list == NULL) {
557                         (void)snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
558                             pcap_strerror(errno));
559                         return (PCAP_ERROR);
560                 }
561
562                 if (ioctl(fd, BIOCGDLTLIST, (caddr_t)bdlp) < 0) {
563                         (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
564                             "BIOCGDLTLIST: %s", pcap_strerror(errno));
565                         free(bdlp->bfl_list);
566                         return (PCAP_ERROR);
567                 }
568
569                 /*
570                  * OK, for real Ethernet devices, add DLT_DOCSIS to the
571                  * list, so that an application can let you choose it,
572                  * in case you're capturing DOCSIS traffic that a Cisco
573                  * Cable Modem Termination System is putting out onto
574                  * an Ethernet (it doesn't put an Ethernet header onto
575                  * the wire, it puts raw DOCSIS frames out on the wire
576                  * inside the low-level Ethernet framing).
577                  *
578                  * A "real Ethernet device" is defined here as a device
579                  * that has a link-layer type of DLT_EN10MB and that has
580                  * no alternate link-layer types; that's done to exclude
581                  * 802.11 interfaces (which might or might not be the
582                  * right thing to do, but I suspect it is - Ethernet <->
583                  * 802.11 bridges would probably badly mishandle frames
584                  * that don't have Ethernet headers).
585                  *
586                  * On Solaris with BPF, Ethernet devices also offer
587                  * DLT_IPNET, so we, if DLT_IPNET is defined, we don't
588                  * treat it as an indication that the device isn't an
589                  * Ethernet.
590                  */
591                 if (v == DLT_EN10MB) {
592                         is_ethernet = 1;
593                         for (i = 0; i < bdlp->bfl_len; i++) {
594                                 if (bdlp->bfl_list[i] != DLT_EN10MB
595 #ifdef DLT_IPNET
596                                     && bdlp->bfl_list[i] != DLT_IPNET
597 #endif
598                                     ) {
599                                         is_ethernet = 0;
600                                         break;
601                                 }
602                         }
603                         if (is_ethernet) {
604                                 /*
605                                  * We reserved one more slot at the end of
606                                  * the list.
607                                  */
608                                 bdlp->bfl_list[bdlp->bfl_len] = DLT_DOCSIS;
609                                 bdlp->bfl_len++;
610                         }
611                 }
612         } else {
613                 /*
614                  * EINVAL just means "we don't support this ioctl on
615                  * this device"; don't treat it as an error.
616                  */
617                 if (errno != EINVAL) {
618                         (void)snprintf(ebuf, PCAP_ERRBUF_SIZE,
619                             "BIOCGDLTLIST: %s", pcap_strerror(errno));
620                         return (PCAP_ERROR);
621                 }
622         }
623         return (0);
624 }
625 #endif
626
627 static int
628 pcap_can_set_rfmon_bpf(pcap_t *p)
629 {
630 #if defined(__APPLE__)
631         struct utsname osinfo;
632         struct ifreq ifr;
633         int fd;
634 #ifdef BIOCGDLTLIST
635         struct bpf_dltlist bdl;
636 #endif
637
638         /*
639          * The joys of monitor mode on OS X.
640          *
641          * Prior to 10.4, it's not supported at all.
642          *
643          * In 10.4, if adapter enN supports monitor mode, there's a
644          * wltN adapter corresponding to it; you open it, instead of
645          * enN, to get monitor mode.  You get whatever link-layer
646          * headers it supplies.
647          *
648          * In 10.5, and, we assume, later releases, if adapter enN
649          * supports monitor mode, it offers, among its selectable
650          * DLT_ values, values that let you get the 802.11 header;
651          * selecting one of those values puts the adapter into monitor
652          * mode (i.e., you can't get 802.11 headers except in monitor
653          * mode, and you can't get Ethernet headers in monitor mode).
654          */
655         if (uname(&osinfo) == -1) {
656                 /*
657                  * Can't get the OS version; just say "no".
658                  */
659                 return (0);
660         }
661         /*
662          * We assume osinfo.sysname is "Darwin", because
663          * __APPLE__ is defined.  We just check the version.
664          */
665         if (osinfo.release[0] < '8' && osinfo.release[1] == '.') {
666                 /*
667                  * 10.3 (Darwin 7.x) or earlier.
668                  * Monitor mode not supported.
669                  */
670                 return (0);
671         }
672         if (osinfo.release[0] == '8' && osinfo.release[1] == '.') {
673                 /*
674                  * 10.4 (Darwin 8.x).  s/en/wlt/, and check
675                  * whether the device exists.
676                  */
677                 if (strncmp(p->opt.source, "en", 2) != 0) {
678                         /*
679                          * Not an enN device; no monitor mode.
680                          */
681                         return (0);
682                 }
683                 fd = socket(AF_INET, SOCK_DGRAM, 0);
684                 if (fd == -1) {
685                         (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
686                             "socket: %s", pcap_strerror(errno));
687                         return (PCAP_ERROR);
688                 }
689                 strlcpy(ifr.ifr_name, "wlt", sizeof(ifr.ifr_name));
690                 strlcat(ifr.ifr_name, p->opt.source + 2, sizeof(ifr.ifr_name));
691                 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
692                         /*
693                          * No such device?
694                          */
695                         close(fd);
696                         return (0);
697                 }
698                 close(fd);
699                 return (1);
700         }
701
702 #ifdef BIOCGDLTLIST
703         /*
704          * Everything else is 10.5 or later; for those,
705          * we just open the enN device, and check whether
706          * we have any 802.11 devices.
707          *
708          * First, open a BPF device.
709          */
710         fd = bpf_open(p);
711         if (fd < 0)
712                 return (fd);    /* fd is the appropriate error code */
713
714         /*
715          * Now bind to the device.
716          */
717         (void)strncpy(ifr.ifr_name, p->opt.source, sizeof(ifr.ifr_name));
718         if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
719                 switch (errno) {
720
721                 case ENXIO:
722                         /*
723                          * There's no such device.
724                          */
725                         close(fd);
726                         return (PCAP_ERROR_NO_SUCH_DEVICE);
727
728                 case ENETDOWN:
729                         /*
730                          * Return a "network down" indication, so that
731                          * the application can report that rather than
732                          * saying we had a mysterious failure and
733                          * suggest that they report a problem to the
734                          * libpcap developers.
735                          */
736                         close(fd);
737                         return (PCAP_ERROR_IFACE_NOT_UP);
738
739                 default:
740                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
741                             "BIOCSETIF: %s: %s",
742                             p->opt.source, pcap_strerror(errno));
743                         close(fd);
744                         return (PCAP_ERROR);
745                 }
746         }
747
748         /*
749          * We know the default link type -- now determine all the DLTs
750          * this interface supports.  If this fails with EINVAL, it's
751          * not fatal; we just don't get to use the feature later.
752          * (We don't care about DLT_DOCSIS, so we pass DLT_NULL
753          * as the default DLT for this adapter.)
754          */
755         if (get_dlt_list(fd, DLT_NULL, &bdl, p->errbuf) == PCAP_ERROR) {
756                 close(fd);
757                 return (PCAP_ERROR);
758         }
759         if (find_802_11(&bdl) != -1) {
760                 /*
761                  * We have an 802.11 DLT, so we can set monitor mode.
762                  */
763                 free(bdl.bfl_list);
764                 close(fd);
765                 return (1);
766         }
767         free(bdl.bfl_list);
768 #endif /* BIOCGDLTLIST */
769         return (0);
770 #elif defined(HAVE_BSD_IEEE80211)
771         int ret;
772
773         ret = monitor_mode(p, 0);
774         if (ret == PCAP_ERROR_RFMON_NOTSUP)
775                 return (0);     /* not an error, just a "can't do" */
776         if (ret == 0)
777                 return (1);     /* success */
778         return (ret);
779 #else
780         return (0);
781 #endif
782 }
783
784 static int
785 pcap_stats_bpf(pcap_t *p, struct pcap_stat *ps)
786 {
787         struct bpf_stat s;
788
789         /*
790          * "ps_recv" counts packets handed to the filter, not packets
791          * that passed the filter.  This includes packets later dropped
792          * because we ran out of buffer space.
793          *
794          * "ps_drop" counts packets dropped inside the BPF device
795          * because we ran out of buffer space.  It doesn't count
796          * packets dropped by the interface driver.  It counts
797          * only packets that passed the filter.
798          *
799          * Both statistics include packets not yet read from the kernel
800          * by libpcap, and thus not yet seen by the application.
801          */
802         if (ioctl(p->fd, BIOCGSTATS, (caddr_t)&s) < 0) {
803                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGSTATS: %s",
804                     pcap_strerror(errno));
805                 return (PCAP_ERROR);
806         }
807
808         ps->ps_recv = s.bs_recv;
809         ps->ps_drop = s.bs_drop;
810         ps->ps_ifdrop = 0;
811         return (0);
812 }
813
814 static int
815 pcap_read_bpf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
816 {
817         int cc;
818         int n = 0;
819         register u_char *bp, *ep;
820         u_char *datap;
821 #ifdef PCAP_FDDIPAD
822         register int pad;
823 #endif
824 #ifdef HAVE_ZEROCOPY_BPF
825         int i;
826 #endif
827
828  again:
829         /*
830          * Has "pcap_breakloop()" been called?
831          */
832         if (p->break_loop) {
833                 /*
834                  * Yes - clear the flag that indicates that it
835                  * has, and return PCAP_ERROR_BREAK to indicate
836                  * that we were told to break out of the loop.
837                  */
838                 p->break_loop = 0;
839                 return (PCAP_ERROR_BREAK);
840         }
841         cc = p->cc;
842         if (p->cc == 0) {
843                 /*
844                  * When reading without zero-copy from a file descriptor, we
845                  * use a single buffer and return a length of data in the
846                  * buffer.  With zero-copy, we update the p->buffer pointer
847                  * to point at whatever underlying buffer contains the next
848                  * data and update cc to reflect the data found in the
849                  * buffer.
850                  */
851 #ifdef HAVE_ZEROCOPY_BPF
852                 if (p->md.zerocopy) {
853                         if (p->buffer != NULL)
854                                 pcap_ack_zbuf(p);
855                         i = pcap_next_zbuf(p, &cc);
856                         if (i == 0)
857                                 goto again;
858                         if (i < 0)
859                                 return (PCAP_ERROR);
860                 } else
861 #endif
862                 {
863                         cc = read(p->fd, (char *)p->buffer, p->bufsize);
864                 }
865                 if (cc < 0) {
866                         /* Don't choke when we get ptraced */
867                         switch (errno) {
868
869                         case EINTR:
870                                 goto again;
871
872 #ifdef _AIX
873                         case EFAULT:
874                                 /*
875                                  * Sigh.  More AIX wonderfulness.
876                                  *
877                                  * For some unknown reason the uiomove()
878                                  * operation in the bpf kernel extension
879                                  * used to copy the buffer into user
880                                  * space sometimes returns EFAULT. I have
881                                  * no idea why this is the case given that
882                                  * a kernel debugger shows the user buffer
883                                  * is correct. This problem appears to
884                                  * be mostly mitigated by the memset of
885                                  * the buffer before it is first used.
886                                  * Very strange.... Shaun Clowes
887                                  *
888                                  * In any case this means that we shouldn't
889                                  * treat EFAULT as a fatal error; as we
890                                  * don't have an API for returning
891                                  * a "some packets were dropped since
892                                  * the last packet you saw" indication,
893                                  * we just ignore EFAULT and keep reading.
894                                  */
895                                 goto again;
896 #endif
897
898                         case EWOULDBLOCK:
899                                 return (0);
900
901                         case ENXIO:
902                                 /*
903                                  * The device on which we're capturing
904                                  * went away.
905                                  *
906                                  * XXX - we should really return
907                                  * PCAP_ERROR_IFACE_NOT_UP, but
908                                  * pcap_dispatch() etc. aren't
909                                  * defined to retur that.
910                                  */
911                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
912                                     "The interface went down");
913                                 return (PCAP_ERROR);
914
915 #if defined(sun) && !defined(BSD) && !defined(__svr4__) && !defined(__SVR4)
916                         /*
917                          * Due to a SunOS bug, after 2^31 bytes, the kernel
918                          * file offset overflows and read fails with EINVAL.
919                          * The lseek() to 0 will fix things.
920                          */
921                         case EINVAL:
922                                 if (lseek(p->fd, 0L, SEEK_CUR) +
923                                     p->bufsize < 0) {
924                                         (void)lseek(p->fd, 0L, SEEK_SET);
925                                         goto again;
926                                 }
927                                 /* fall through */
928 #endif
929                         }
930                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read: %s",
931                             pcap_strerror(errno));
932                         return (PCAP_ERROR);
933                 }
934                 bp = p->buffer;
935         } else
936                 bp = p->bp;
937
938         /*
939          * Loop through each packet.
940          */
941 #define bhp ((struct bpf_hdr *)bp)
942         ep = bp + cc;
943 #ifdef PCAP_FDDIPAD
944         pad = p->fddipad;
945 #endif
946         while (bp < ep) {
947                 register int caplen, hdrlen;
948
949                 /*
950                  * Has "pcap_breakloop()" been called?
951                  * If so, return immediately - if we haven't read any
952                  * packets, clear the flag and return PCAP_ERROR_BREAK
953                  * to indicate that we were told to break out of the loop,
954                  * otherwise leave the flag set, so that the *next* call
955                  * will break out of the loop without having read any
956                  * packets, and return the number of packets we've
957                  * processed so far.
958                  */
959                 if (p->break_loop) {
960                         p->bp = bp;
961                         p->cc = ep - bp;
962                         /*
963                          * ep is set based on the return value of read(),
964                          * but read() from a BPF device doesn't necessarily
965                          * return a value that's a multiple of the alignment
966                          * value for BPF_WORDALIGN().  However, whenever we
967                          * increment bp, we round up the increment value by
968                          * a value rounded up by BPF_WORDALIGN(), so we
969                          * could increment bp past ep after processing the
970                          * last packet in the buffer.
971                          *
972                          * We treat ep < bp as an indication that this
973                          * happened, and just set p->cc to 0.
974                          */
975                         if (p->cc < 0)
976                                 p->cc = 0;
977                         if (n == 0) {
978                                 p->break_loop = 0;
979                                 return (PCAP_ERROR_BREAK);
980                         } else
981                                 return (n);
982                 }
983
984                 caplen = bhp->bh_caplen;
985                 hdrlen = bhp->bh_hdrlen;
986                 datap = bp + hdrlen;
987                 /*
988                  * Short-circuit evaluation: if using BPF filter
989                  * in kernel, no need to do it now - we already know
990                  * the packet passed the filter.
991                  *
992 #ifdef PCAP_FDDIPAD
993                  * Note: the filter code was generated assuming
994                  * that p->fddipad was the amount of padding
995                  * before the header, as that's what's required
996                  * in the kernel, so we run the filter before
997                  * skipping that padding.
998 #endif
999                  */
1000                 if (p->md.use_bpf ||
1001                     bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
1002                         struct pcap_pkthdr pkthdr;
1003
1004                         pkthdr.ts.tv_sec = bhp->bh_tstamp.tv_sec;
1005 #ifdef _AIX
1006                         /*
1007                          * AIX's BPF returns seconds/nanoseconds time
1008                          * stamps, not seconds/microseconds time stamps.
1009                          */
1010                         pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec/1000;
1011 #else
1012                         pkthdr.ts.tv_usec = bhp->bh_tstamp.tv_usec;
1013 #endif
1014 #ifdef PCAP_FDDIPAD
1015                         if (caplen > pad)
1016                                 pkthdr.caplen = caplen - pad;
1017                         else
1018                                 pkthdr.caplen = 0;
1019                         if (bhp->bh_datalen > pad)
1020                                 pkthdr.len = bhp->bh_datalen - pad;
1021                         else
1022                                 pkthdr.len = 0;
1023                         datap += pad;
1024 #else
1025                         pkthdr.caplen = caplen;
1026                         pkthdr.len = bhp->bh_datalen;
1027 #endif
1028                         (*callback)(user, &pkthdr, datap);
1029                         bp += BPF_WORDALIGN(caplen + hdrlen);
1030                         if (++n >= cnt && cnt > 0) {
1031                                 p->bp = bp;
1032                                 p->cc = ep - bp;
1033                                 /*
1034                                  * See comment above about p->cc < 0.
1035                                  */
1036                                 if (p->cc < 0)
1037                                         p->cc = 0;
1038                                 return (n);
1039                         }
1040                 } else {
1041                         /*
1042                          * Skip this packet.
1043                          */
1044                         bp += BPF_WORDALIGN(caplen + hdrlen);
1045                 }
1046         }
1047 #undef bhp
1048         p->cc = 0;
1049         return (n);
1050 }
1051
1052 static int
1053 pcap_inject_bpf(pcap_t *p, const void *buf, size_t size)
1054 {
1055         int ret;
1056
1057         ret = write(p->fd, buf, size);
1058 #ifdef __APPLE__
1059         if (ret == -1 && errno == EAFNOSUPPORT) {
1060                 /*
1061                  * In Mac OS X, there's a bug wherein setting the
1062                  * BIOCSHDRCMPLT flag causes writes to fail; see,
1063                  * for example:
1064                  *
1065                  *      http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/BIOCSHDRCMPLT-10.3.3.patch
1066                  *
1067                  * So, if, on OS X, we get EAFNOSUPPORT from the write, we
1068                  * assume it's due to that bug, and turn off that flag
1069                  * and try again.  If we succeed, it either means that
1070                  * somebody applied the fix from that URL, or other patches
1071                  * for that bug from
1072                  *
1073                  *      http://cerberus.sourcefire.com/~jeff/archives/patches/macosx/
1074                  *
1075                  * and are running a Darwin kernel with those fixes, or
1076                  * that Apple fixed the problem in some OS X release.
1077                  */
1078                 u_int spoof_eth_src = 0;
1079
1080                 if (ioctl(p->fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
1081                         (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1082                             "send: can't turn off BIOCSHDRCMPLT: %s",
1083                             pcap_strerror(errno));
1084                         return (PCAP_ERROR);
1085                 }
1086
1087                 /*
1088                  * Now try the write again.
1089                  */
1090                 ret = write(p->fd, buf, size);
1091         }
1092 #endif /* __APPLE__ */
1093         if (ret == -1) {
1094                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1095                     pcap_strerror(errno));
1096                 return (PCAP_ERROR);
1097         }
1098         return (ret);
1099 }
1100
1101 #ifdef _AIX
1102 static int
1103 bpf_odminit(char *errbuf)
1104 {
1105         char *errstr;
1106
1107         if (odm_initialize() == -1) {
1108                 if (odm_err_msg(odmerrno, &errstr) == -1)
1109                         errstr = "Unknown error";
1110                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1111                     "bpf_load: odm_initialize failed: %s",
1112                     errstr);
1113                 return (PCAP_ERROR);
1114         }
1115
1116         if ((odmlockid = odm_lock("/etc/objrepos/config_lock", ODM_WAIT)) == -1) {
1117                 if (odm_err_msg(odmerrno, &errstr) == -1)
1118                         errstr = "Unknown error";
1119                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1120                     "bpf_load: odm_lock of /etc/objrepos/config_lock failed: %s",
1121                     errstr);
1122                 (void)odm_terminate();
1123                 return (PCAP_ERROR);
1124         }
1125
1126         return (0);
1127 }
1128
1129 static int
1130 bpf_odmcleanup(char *errbuf)
1131 {
1132         char *errstr;
1133
1134         if (odm_unlock(odmlockid) == -1) {
1135                 if (errbuf != NULL) {
1136                         if (odm_err_msg(odmerrno, &errstr) == -1)
1137                                 errstr = "Unknown error";
1138                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1139                             "bpf_load: odm_unlock failed: %s",
1140                             errstr);
1141                 }
1142                 return (PCAP_ERROR);
1143         }
1144
1145         if (odm_terminate() == -1) {
1146                 if (errbuf != NULL) {
1147                         if (odm_err_msg(odmerrno, &errstr) == -1)
1148                                 errstr = "Unknown error";
1149                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1150                             "bpf_load: odm_terminate failed: %s",
1151                             errstr);
1152                 }
1153                 return (PCAP_ERROR);
1154         }
1155
1156         return (0);
1157 }
1158
1159 static int
1160 bpf_load(char *errbuf)
1161 {
1162         long major;
1163         int *minors;
1164         int numminors, i, rc;
1165         char buf[1024];
1166         struct stat sbuf;
1167         struct bpf_config cfg_bpf;
1168         struct cfg_load cfg_ld;
1169         struct cfg_kmod cfg_km;
1170
1171         /*
1172          * This is very very close to what happens in the real implementation
1173          * but I've fixed some (unlikely) bug situations.
1174          */
1175         if (bpfloadedflag)
1176                 return (0);
1177
1178         if (bpf_odminit(errbuf) == PCAP_ERROR)
1179                 return (PCAP_ERROR);
1180
1181         major = genmajor(BPF_NAME);
1182         if (major == -1) {
1183                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1184                     "bpf_load: genmajor failed: %s", pcap_strerror(errno));
1185                 (void)bpf_odmcleanup(NULL);
1186                 return (PCAP_ERROR);
1187         }
1188
1189         minors = getminor(major, &numminors, BPF_NAME);
1190         if (!minors) {
1191                 minors = genminor("bpf", major, 0, BPF_MINORS, 1, 1);
1192                 if (!minors) {
1193                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1194                             "bpf_load: genminor failed: %s",
1195                             pcap_strerror(errno));
1196                         (void)bpf_odmcleanup(NULL);
1197                         return (PCAP_ERROR);
1198                 }
1199         }
1200
1201         if (bpf_odmcleanup(errbuf) == PCAP_ERROR)
1202                 return (PCAP_ERROR);
1203
1204         rc = stat(BPF_NODE "0", &sbuf);
1205         if (rc == -1 && errno != ENOENT) {
1206                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1207                     "bpf_load: can't stat %s: %s",
1208                     BPF_NODE "0", pcap_strerror(errno));
1209                 return (PCAP_ERROR);
1210         }
1211
1212         if (rc == -1 || getmajor(sbuf.st_rdev) != major) {
1213                 for (i = 0; i < BPF_MINORS; i++) {
1214                         sprintf(buf, "%s%d", BPF_NODE, i);
1215                         unlink(buf);
1216                         if (mknod(buf, S_IRUSR | S_IFCHR, domakedev(major, i)) == -1) {
1217                                 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1218                                     "bpf_load: can't mknod %s: %s",
1219                                     buf, pcap_strerror(errno));
1220                                 return (PCAP_ERROR);
1221                         }
1222                 }
1223         }
1224
1225         /* Check if the driver is loaded */
1226         memset(&cfg_ld, 0x0, sizeof(cfg_ld));
1227         cfg_ld.path = buf;
1228         sprintf(cfg_ld.path, "%s/%s", DRIVER_PATH, BPF_NAME);
1229         if ((sysconfig(SYS_QUERYLOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) ||
1230             (cfg_ld.kmid == 0)) {
1231                 /* Driver isn't loaded, load it now */
1232                 if (sysconfig(SYS_SINGLELOAD, (void *)&cfg_ld, sizeof(cfg_ld)) == -1) {
1233                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1234                             "bpf_load: could not load driver: %s",
1235                             strerror(errno));
1236                         return (PCAP_ERROR);
1237                 }
1238         }
1239
1240         /* Configure the driver */
1241         cfg_km.cmd = CFG_INIT;
1242         cfg_km.kmid = cfg_ld.kmid;
1243         cfg_km.mdilen = sizeof(cfg_bpf);
1244         cfg_km.mdiptr = (void *)&cfg_bpf;
1245         for (i = 0; i < BPF_MINORS; i++) {
1246                 cfg_bpf.devno = domakedev(major, i);
1247                 if (sysconfig(SYS_CFGKMOD, (void *)&cfg_km, sizeof(cfg_km)) == -1) {
1248                         snprintf(errbuf, PCAP_ERRBUF_SIZE,
1249                             "bpf_load: could not configure driver: %s",
1250                             strerror(errno));
1251                         return (PCAP_ERROR);
1252                 }
1253         }
1254
1255         bpfloadedflag = 1;
1256
1257         return (0);
1258 }
1259 #endif
1260
1261 /*
1262  * Turn off rfmon mode if necessary.
1263  */
1264 static void
1265 pcap_cleanup_bpf(pcap_t *p)
1266 {
1267 #ifdef HAVE_BSD_IEEE80211
1268         int sock;
1269         struct ifmediareq req;
1270         struct ifreq ifr;
1271 #endif
1272
1273         if (p->md.must_do_on_close != 0) {
1274                 /*
1275                  * There's something we have to do when closing this
1276                  * pcap_t.
1277                  */
1278 #ifdef HAVE_BSD_IEEE80211
1279                 if (p->md.must_do_on_close & MUST_CLEAR_RFMON) {
1280                         /*
1281                          * We put the interface into rfmon mode;
1282                          * take it out of rfmon mode.
1283                          *
1284                          * XXX - if somebody else wants it in rfmon
1285                          * mode, this code cannot know that, so it'll take
1286                          * it out of rfmon mode.
1287                          */
1288                         sock = socket(AF_INET, SOCK_DGRAM, 0);
1289                         if (sock == -1) {
1290                                 fprintf(stderr,
1291                                     "Can't restore interface flags (socket() failed: %s).\n"
1292                                     "Please adjust manually.\n",
1293                                     strerror(errno));
1294                         } else {
1295                                 memset(&req, 0, sizeof(req));
1296                                 strncpy(req.ifm_name, p->md.device,
1297                                     sizeof(req.ifm_name));
1298                                 if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
1299                                         fprintf(stderr,
1300                                             "Can't restore interface flags (SIOCGIFMEDIA failed: %s).\n"
1301                                             "Please adjust manually.\n",
1302                                             strerror(errno));
1303                                 } else {
1304                                         if (req.ifm_current & IFM_IEEE80211_MONITOR) {
1305                                                 /*
1306                                                  * Rfmon mode is currently on;
1307                                                  * turn it off.
1308                                                  */
1309                                                 memset(&ifr, 0, sizeof(ifr));
1310                                                 (void)strncpy(ifr.ifr_name,
1311                                                     p->md.device,
1312                                                     sizeof(ifr.ifr_name));
1313                                                 ifr.ifr_media =
1314                                                     req.ifm_current & ~IFM_IEEE80211_MONITOR;
1315                                                 if (ioctl(sock, SIOCSIFMEDIA,
1316                                                     &ifr) == -1) {
1317                                                         fprintf(stderr,
1318                                                             "Can't restore interface flags (SIOCSIFMEDIA failed: %s).\n"
1319                                                             "Please adjust manually.\n",
1320                                                             strerror(errno));
1321                                                 }
1322                                         }
1323                                 }
1324                                 close(sock);
1325                         }
1326                 }
1327 #endif /* HAVE_BSD_IEEE80211 */
1328
1329                 /*
1330                  * Take this pcap out of the list of pcaps for which we
1331                  * have to take the interface out of some mode.
1332                  */
1333                 pcap_remove_from_pcaps_to_close(p);
1334                 p->md.must_do_on_close = 0;
1335         }
1336
1337 #ifdef HAVE_ZEROCOPY_BPF
1338         if (p->md.zerocopy) {
1339                 /*
1340                  * Delete the mappings.  Note that p->buffer gets
1341                  * initialized to one of the mmapped regions in
1342                  * this case, so do not try and free it directly;
1343                  * null it out so that pcap_cleanup_live_common()
1344                  * doesn't try to free it.
1345                  */
1346                 if (p->md.zbuf1 != MAP_FAILED && p->md.zbuf1 != NULL)
1347                         (void) munmap(p->md.zbuf1, p->md.zbufsize);
1348                 if (p->md.zbuf2 != MAP_FAILED && p->md.zbuf2 != NULL)
1349                         (void) munmap(p->md.zbuf2, p->md.zbufsize);
1350                 p->buffer = NULL;
1351                 p->buffer = NULL;
1352         }
1353 #endif
1354         if (p->md.device != NULL) {
1355                 free(p->md.device);
1356                 p->md.device = NULL;
1357         }
1358         pcap_cleanup_live_common(p);
1359 }
1360
1361 static int
1362 check_setif_failure(pcap_t *p, int error)
1363 {
1364 #ifdef __APPLE__
1365         int fd;
1366         struct ifreq ifr;
1367         int err;
1368 #endif
1369
1370         if (error == ENXIO) {
1371                 /*
1372                  * No such device exists.
1373                  */
1374 #ifdef __APPLE__
1375                 if (p->opt.rfmon && strncmp(p->opt.source, "wlt", 3) == 0) {
1376                         /*
1377                          * Monitor mode was requested, and we're trying
1378                          * to open a "wltN" device.  Assume that this
1379                          * is 10.4 and that we were asked to open an
1380                          * "enN" device; if that device exists, return
1381                          * "monitor mode not supported on the device".
1382                          */
1383                         fd = socket(AF_INET, SOCK_DGRAM, 0);
1384                         if (fd != -1) {
1385                                 strlcpy(ifr.ifr_name, "en",
1386                                     sizeof(ifr.ifr_name));
1387                                 strlcat(ifr.ifr_name, p->opt.source + 3,
1388                                     sizeof(ifr.ifr_name));
1389                                 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifr) < 0) {
1390                                         /*
1391                                          * We assume this failed because
1392                                          * the underlying device doesn't
1393                                          * exist.
1394                                          */
1395                                         err = PCAP_ERROR_NO_SUCH_DEVICE;
1396                                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1397                                             "SIOCGIFFLAGS on %s failed: %s",
1398                                             ifr.ifr_name, pcap_strerror(errno));
1399                                 } else {
1400                                         /*
1401                                          * The underlying "enN" device
1402                                          * exists, but there's no
1403                                          * corresponding "wltN" device;
1404                                          * that means that the "enN"
1405                                          * device doesn't support
1406                                          * monitor mode, probably because
1407                                          * it's an Ethernet device rather
1408                                          * than a wireless device.
1409                                          */
1410                                         err = PCAP_ERROR_RFMON_NOTSUP;
1411                                 }
1412                                 close(fd);
1413                         } else {
1414                                 /*
1415                                  * We can't find out whether there's
1416                                  * an underlying "enN" device, so
1417                                  * just report "no such device".
1418                                  */
1419                                 err = PCAP_ERROR_NO_SUCH_DEVICE;
1420                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1421                                     "socket() failed: %s",
1422                                     pcap_strerror(errno));
1423                         }
1424                         return (err);
1425                 }
1426 #endif
1427                 /*
1428                  * No such device.
1429                  */
1430                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF failed: %s",
1431                     pcap_strerror(errno));
1432                 return (PCAP_ERROR_NO_SUCH_DEVICE);
1433         } else if (errno == ENETDOWN) {
1434                 /*
1435                  * Return a "network down" indication, so that
1436                  * the application can report that rather than
1437                  * saying we had a mysterious failure and
1438                  * suggest that they report a problem to the
1439                  * libpcap developers.
1440                  */
1441                 return (PCAP_ERROR_IFACE_NOT_UP);
1442         } else {
1443                 /*
1444                  * Some other error; fill in the error string, and
1445                  * return PCAP_ERROR.
1446                  */
1447                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1448                     p->opt.source, pcap_strerror(errno));
1449                 return (PCAP_ERROR);
1450         }
1451 }
1452
1453 /*
1454  * Default capture buffer size.
1455  * 32K isn't very much for modern machines with fast networks; we
1456  * pick .5M, as that's the maximum on at least some systems with BPF.
1457  */
1458 #define DEFAULT_BUFSIZE 524288
1459
1460 static int
1461 pcap_activate_bpf(pcap_t *p)
1462 {
1463         int status = 0;
1464         int fd;
1465 #ifdef LIFNAMSIZ
1466         struct lifreq ifr;
1467         char *ifrname = ifr.lifr_name;
1468         const size_t ifnamsiz = sizeof(ifr.lifr_name);
1469 #else
1470         struct ifreq ifr;
1471         char *ifrname = ifr.ifr_name;
1472         const size_t ifnamsiz = sizeof(ifr.ifr_name);
1473 #endif
1474         struct bpf_version bv;
1475 #ifdef __APPLE__
1476         int sockfd;
1477         char *wltdev = NULL;
1478 #endif
1479 #ifdef BIOCGDLTLIST
1480         struct bpf_dltlist bdl;
1481 #if defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)
1482         int new_dlt;
1483 #endif
1484 #endif /* BIOCGDLTLIST */
1485 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
1486         u_int spoof_eth_src = 1;
1487 #endif
1488         u_int v;
1489         struct bpf_insn total_insn;
1490         struct bpf_program total_prog;
1491         struct utsname osinfo;
1492
1493 #ifdef HAVE_DAG_API
1494         if (strstr(device, "dag")) {
1495                 return dag_open_live(device, snaplen, promisc, to_ms, ebuf);
1496         }
1497 #endif /* HAVE_DAG_API */
1498
1499 #ifdef BIOCGDLTLIST
1500         memset(&bdl, 0, sizeof(bdl));
1501         int have_osinfo = 0;
1502 #ifdef HAVE_ZEROCOPY_BPF
1503         struct bpf_zbuf bz;
1504         u_int bufmode, zbufmax;
1505 #endif
1506
1507         fd = bpf_open(p);
1508         if (fd < 0) {
1509                 status = fd;
1510                 goto bad;
1511         }
1512
1513         p->fd = fd;
1514
1515         if (ioctl(fd, BIOCVERSION, (caddr_t)&bv) < 0) {
1516                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCVERSION: %s",
1517                     pcap_strerror(errno));
1518                 status = PCAP_ERROR;
1519                 goto bad;
1520         }
1521         if (bv.bv_major != BPF_MAJOR_VERSION ||
1522             bv.bv_minor < BPF_MINOR_VERSION) {
1523                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1524                     "kernel bpf filter out of date");
1525                 status = PCAP_ERROR;
1526                 goto bad;
1527         }
1528
1529         p->md.device = strdup(p->opt.source);
1530         if (p->md.device == NULL) {
1531                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
1532                      pcap_strerror(errno));
1533                 status = PCAP_ERROR;
1534                 goto bad;
1535         }
1536
1537         /*
1538          * Try finding a good size for the buffer; 32768 may be too
1539          * big, so keep cutting it in half until we find a size
1540          * that works, or run out of sizes to try.  If the default
1541          * is larger, don't make it smaller.
1542          *
1543          * XXX - there should be a user-accessible hook to set the
1544          * initial buffer size.
1545          * Attempt to find out the version of the OS on which we're running.
1546          */
1547         if (uname(&osinfo) == 0)
1548                 have_osinfo = 1;
1549
1550 #ifdef __APPLE__
1551         /*
1552          * See comment in pcap_can_set_rfmon_bpf() for an explanation
1553          * of why we check the version number.
1554          */
1555         if (p->opt.rfmon) {
1556                 if (have_osinfo) {
1557                         /*
1558                          * We assume osinfo.sysname is "Darwin", because
1559                          * __APPLE__ is defined.  We just check the version.
1560                          */
1561                         if (osinfo.release[0] < '8' &&
1562                             osinfo.release[1] == '.') {
1563                                 /*
1564                                  * 10.3 (Darwin 7.x) or earlier.
1565                                  */
1566                                 status = PCAP_ERROR_RFMON_NOTSUP;
1567                                 goto bad;
1568                         }
1569                         if (osinfo.release[0] == '8' &&
1570                             osinfo.release[1] == '.') {
1571                                 /*
1572                                  * 10.4 (Darwin 8.x).  s/en/wlt/
1573                                  */
1574                                 if (strncmp(p->opt.source, "en", 2) != 0) {
1575                                         /*
1576                                          * Not an enN device; check
1577                                          * whether the device even exists.
1578                                          */
1579                                         sockfd = socket(AF_INET, SOCK_DGRAM, 0);
1580                                         if (sockfd != -1) {
1581                                                 strlcpy(ifrname,
1582                                                     p->opt.source, ifnamsiz);
1583                                                 if (ioctl(sockfd, SIOCGIFFLAGS,
1584                                                     (char *)&ifr) < 0) {
1585                                                         /*
1586                                                          * We assume this
1587                                                          * failed because
1588                                                          * the underlying
1589                                                          * device doesn't
1590                                                          * exist.
1591                                                          */
1592                                                         status = PCAP_ERROR_NO_SUCH_DEVICE;
1593                                                         snprintf(p->errbuf,
1594                                                             PCAP_ERRBUF_SIZE,
1595                                                             "SIOCGIFFLAGS failed: %s",
1596                                                             pcap_strerror(errno));
1597                                                 } else
1598                                                         status = PCAP_ERROR_RFMON_NOTSUP;
1599                                                 close(sockfd);
1600                                         } else {
1601                                                 /*
1602                                                  * We can't find out whether
1603                                                  * the device exists, so just
1604                                                  * report "no such device".
1605                                                  */
1606                                                 status = PCAP_ERROR_NO_SUCH_DEVICE;
1607                                                 snprintf(p->errbuf,
1608                                                     PCAP_ERRBUF_SIZE,
1609                                                     "socket() failed: %s",
1610                                                     pcap_strerror(errno));
1611                                         }
1612                                         goto bad;
1613                                 }
1614                                 wltdev = malloc(strlen(p->opt.source) + 2);
1615                                 if (wltdev == NULL) {
1616                                         (void)snprintf(p->errbuf,
1617                                             PCAP_ERRBUF_SIZE, "malloc: %s",
1618                                             pcap_strerror(errno));
1619                                         status = PCAP_ERROR;
1620                                         goto bad;
1621                                 }
1622                                 strcpy(wltdev, "wlt");
1623                                 strcat(wltdev, p->opt.source + 2);
1624                                 free(p->opt.source);
1625                                 p->opt.source = wltdev;
1626                         }
1627                         /*
1628                          * Everything else is 10.5 or later; for those,
1629                          * we just open the enN device, and set the DLT.
1630                          */
1631                 }
1632         }
1633 #endif /* __APPLE__ */
1634 #ifdef HAVE_ZEROCOPY_BPF
1635         /*
1636          * If the BPF extension to set buffer mode is present, try setting
1637          * the mode to zero-copy.  If that fails, use regular buffering.  If
1638          * it succeeds but other setup fails, return an error to the user.
1639          */
1640         bufmode = BPF_BUFMODE_ZBUF;
1641         if (ioctl(fd, BIOCSETBUFMODE, (caddr_t)&bufmode) == 0) {
1642                 /*
1643                  * We have zerocopy BPF; use it.
1644                  */
1645                 p->md.zerocopy = 1;
1646
1647                 /*
1648                  * How to pick a buffer size: first, query the maximum buffer
1649                  * size supported by zero-copy.  This also lets us quickly
1650                  * determine whether the kernel generally supports zero-copy.
1651                  * Then, if a buffer size was specified, use that, otherwise
1652                  * query the default buffer size, which reflects kernel
1653                  * policy for a desired default.  Round to the nearest page
1654                  * size.
1655                  */
1656                 if (ioctl(fd, BIOCGETZMAX, (caddr_t)&zbufmax) < 0) {
1657                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGETZMAX: %s",
1658                             pcap_strerror(errno));
1659                         goto bad;
1660                 }
1661
1662                 if (p->opt.buffer_size != 0) {
1663                         /*
1664                          * A buffer size was explicitly specified; use it.
1665                          */
1666                         v = p->opt.buffer_size;
1667                 } else {
1668                         if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1669                             v < DEFAULT_BUFSIZE)
1670                                 v = DEFAULT_BUFSIZE;
1671                 }
1672 #ifndef roundup
1673 #define roundup(x, y)   ((((x)+((y)-1))/(y))*(y))  /* to any y */
1674 #endif
1675                 p->md.zbufsize = roundup(v, getpagesize());
1676                 if (p->md.zbufsize > zbufmax)
1677                         p->md.zbufsize = zbufmax;
1678                 p->md.zbuf1 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1679                     MAP_ANON, -1, 0);
1680                 p->md.zbuf2 = mmap(NULL, p->md.zbufsize, PROT_READ | PROT_WRITE,
1681                     MAP_ANON, -1, 0);
1682                 if (p->md.zbuf1 == MAP_FAILED || p->md.zbuf2 == MAP_FAILED) {
1683                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "mmap: %s",
1684                             pcap_strerror(errno));
1685                         goto bad;
1686                 }
1687                 bzero(&bz, sizeof(bz));
1688                 bz.bz_bufa = p->md.zbuf1;
1689                 bz.bz_bufb = p->md.zbuf2;
1690                 bz.bz_buflen = p->md.zbufsize;
1691                 if (ioctl(fd, BIOCSETZBUF, (caddr_t)&bz) < 0) {
1692                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETZBUF: %s",
1693                             pcap_strerror(errno));
1694                         goto bad;
1695                 }
1696                 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1697                 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0) {
1698                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETIF: %s: %s",
1699                             p->opt.source, pcap_strerror(errno));
1700                         goto bad;
1701                 }
1702                 v = p->md.zbufsize - sizeof(struct bpf_zbuf_header);
1703         } else
1704 #endif
1705         {
1706                 /*
1707                  * We don't have zerocopy BPF.
1708                  * Set the buffer size.
1709                  */
1710                 if (p->opt.buffer_size != 0) {
1711                         /*
1712                          * A buffer size was explicitly specified; use it.
1713                          */
1714                         if (ioctl(fd, BIOCSBLEN,
1715                             (caddr_t)&p->opt.buffer_size) < 0) {
1716                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1717                                     "BIOCSBLEN: %s: %s", p->opt.source,
1718                                     pcap_strerror(errno));
1719                                 status = PCAP_ERROR;
1720                                 goto bad;
1721                         }
1722
1723                         /*
1724                          * Now bind to the device.
1725                          */
1726                         (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1727 #ifdef BIOCSETLIF
1728                         if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) < 0)
1729 #else
1730                         if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) < 0)
1731 #endif
1732                         {
1733                                 status = check_setif_failure(p, errno);
1734                                 goto bad;
1735                         }
1736                 } else {
1737                         /*
1738                          * No buffer size was explicitly specified.
1739                          *
1740                          * Try finding a good size for the buffer;
1741                          * DEFAULT_BUFSIZE may be too big, so keep
1742                          * cutting it in half until we find a size
1743                          * that works, or run out of sizes to try.
1744                          * If the default is larger, don't make it smaller.
1745                          */
1746                         if ((ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) ||
1747                             v < DEFAULT_BUFSIZE)
1748                                 v = DEFAULT_BUFSIZE;
1749                         for ( ; v != 0; v >>= 1) {
1750                                 /*
1751                                  * Ignore the return value - this is because the
1752                                  * call fails on BPF systems that don't have
1753                                  * kernel malloc.  And if the call fails, it's
1754                                  * no big deal, we just continue to use the
1755                                  * standard buffer size.
1756                                  */
1757                                 (void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
1758
1759                                 (void)strncpy(ifrname, p->opt.source, ifnamsiz);
1760 #ifdef BIOCSETLIF
1761                                 if (ioctl(fd, BIOCSETLIF, (caddr_t)&ifr) >= 0)
1762 #else
1763                                 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
1764 #endif
1765                                         break;  /* that size worked; we're done */
1766
1767                                 if (errno != ENOBUFS) {
1768                                         status = check_setif_failure(p, errno);
1769                                         goto bad;
1770                                 }
1771                         }
1772
1773                         if (v == 0) {
1774                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1775                                     "BIOCSBLEN: %s: No buffer size worked",
1776                                     p->opt.source);
1777                                 status = PCAP_ERROR;
1778                                 goto bad;
1779                         }
1780                 }
1781         }
1782 #endif
1783
1784         /* Get the data link layer type. */
1785         if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
1786                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGDLT: %s",
1787                     pcap_strerror(errno));
1788                 status = PCAP_ERROR;
1789                 goto bad;
1790         }
1791
1792 #ifdef _AIX
1793         /*
1794          * AIX's BPF returns IFF_ types, not DLT_ types, in BIOCGDLT.
1795          */
1796         switch (v) {
1797
1798         case IFT_ETHER:
1799         case IFT_ISO88023:
1800                 v = DLT_EN10MB;
1801                 break;
1802
1803         case IFT_FDDI:
1804                 v = DLT_FDDI;
1805                 break;
1806
1807         case IFT_ISO88025:
1808                 v = DLT_IEEE802;
1809                 break;
1810
1811         case IFT_LOOP:
1812                 v = DLT_NULL;
1813                 break;
1814
1815         default:
1816                 /*
1817                  * We don't know what to map this to yet.
1818                  */
1819                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown interface type %u",
1820                     v);
1821                 status = PCAP_ERROR;
1822                 goto bad;
1823         }
1824 #endif
1825 #if _BSDI_VERSION - 0 >= 199510
1826         /* The SLIP and PPP link layer header changed in BSD/OS 2.1 */
1827         switch (v) {
1828
1829         case DLT_SLIP:
1830                 v = DLT_SLIP_BSDOS;
1831                 break;
1832
1833         case DLT_PPP:
1834                 v = DLT_PPP_BSDOS;
1835                 break;
1836
1837         case 11:        /*DLT_FR*/
1838                 v = DLT_FRELAY;
1839                 break;
1840
1841         case 12:        /*DLT_C_HDLC*/
1842                 v = DLT_CHDLC;
1843                 break;
1844         }
1845 #endif
1846
1847 #ifdef BIOCGDLTLIST
1848         /*
1849          * We know the default link type -- now determine all the DLTs
1850          * this interface supports.  If this fails with EINVAL, it's
1851          * not fatal; we just don't get to use the feature later.
1852          */
1853         if (get_dlt_list(fd, v, &bdl, p->errbuf) == -1) {
1854                 status = PCAP_ERROR;
1855                 goto bad;
1856         }
1857         p->dlt_count = bdl.bfl_len;
1858         p->dlt_list = bdl.bfl_list;
1859
1860 #ifdef __APPLE__
1861         /*
1862          * Monitor mode fun, continued.
1863          *
1864          * For 10.5 and, we're assuming, later releases, as noted above,
1865          * 802.1 adapters that support monitor mode offer both DLT_EN10MB,
1866          * DLT_IEEE802_11, and possibly some 802.11-plus-radio-information
1867          * DLT_ value.  Choosing one of the 802.11 DLT_ values will turn
1868          * monitor mode on.
1869          *
1870          * Therefore, if the user asked for monitor mode, we filter out
1871          * the DLT_EN10MB value, as you can't get that in monitor mode,
1872          * and, if the user didn't ask for monitor mode, we filter out
1873          * the 802.11 DLT_ values, because selecting those will turn
1874          * monitor mode on.  Then, for monitor mode, if an 802.11-plus-
1875          * radio DLT_ value is offered, we try to select that, otherwise
1876          * we try to select DLT_IEEE802_11.
1877          */
1878         if (have_osinfo) {
1879                 if (isdigit((unsigned)osinfo.release[0]) &&
1880                      (osinfo.release[0] == '9' ||
1881                      isdigit((unsigned)osinfo.release[1]))) {
1882                         /*
1883                          * 10.5 (Darwin 9.x), or later.
1884                          */
1885                         new_dlt = find_802_11(&bdl);
1886                         if (new_dlt != -1) {
1887                                 /*
1888                                  * We have at least one 802.11 DLT_ value,
1889                                  * so this is an 802.11 interface.
1890                                  * new_dlt is the best of the 802.11
1891                                  * DLT_ values in the list.
1892                                  */
1893                                 if (p->opt.rfmon) {
1894                                         /*
1895                                          * Our caller wants monitor mode.
1896                                          * Purge DLT_EN10MB from the list
1897                                          * of link-layer types, as selecting
1898                                          * it will keep monitor mode off.
1899                                          */
1900                                         remove_en(p);
1901
1902                                         /*
1903                                          * If the new mode we want isn't
1904                                          * the default mode, attempt to
1905                                          * select the new mode.
1906                                          */
1907                                         if (new_dlt != v) {
1908                                                 if (ioctl(p->fd, BIOCSDLT,
1909                                                     &new_dlt) != -1) {
1910                                                         /*
1911                                                          * We succeeded;
1912                                                          * make this the
1913                                                          * new DLT_ value.
1914                                                          */
1915                                                         v = new_dlt;
1916                                                 }
1917                                         }
1918                                 } else {
1919                                         /*
1920                                          * Our caller doesn't want
1921                                          * monitor mode.  Unless this
1922                                          * is being done by pcap_open_live(),
1923                                          * purge the 802.11 link-layer types
1924                                          * from the list, as selecting
1925                                          * one of them will turn monitor
1926                                          * mode on.
1927                                          */
1928                                         if (!p->oldstyle)
1929                                                 remove_802_11(p);
1930                                 }
1931                         } else {
1932                                 if (p->opt.rfmon) {
1933                                         /*
1934                                          * The caller requested monitor
1935                                          * mode, but we have no 802.11
1936                                          * link-layer types, so they
1937                                          * can't have it.
1938                                          */
1939                                         status = PCAP_ERROR_RFMON_NOTSUP;
1940                                         goto bad;
1941                                 }
1942                         }
1943                 }
1944         }
1945 #elif defined(HAVE_BSD_IEEE80211)
1946         /*
1947          * *BSD with the new 802.11 ioctls.
1948          * Do we want monitor mode?
1949          */
1950         if (p->opt.rfmon) {
1951                 /*
1952                  * Try to put the interface into monitor mode.
1953                  */
1954                 status = monitor_mode(p, 1);
1955                 if (status != 0) {
1956                         /*
1957                          * We failed.
1958                          */
1959                         goto bad;
1960                 }
1961
1962                 /*
1963                  * We're in monitor mode.
1964                  * Try to find the best 802.11 DLT_ value and, if we
1965                  * succeed, try to switch to that mode if we're not
1966                  * already in that mode.
1967                  */
1968                 new_dlt = find_802_11(&bdl);
1969                 if (new_dlt != -1) {
1970                         /*
1971                          * We have at least one 802.11 DLT_ value.
1972                          * new_dlt is the best of the 802.11
1973                          * DLT_ values in the list.
1974                          *
1975                          * If the new mode we want isn't the default mode,
1976                          * attempt to select the new mode.
1977                          */
1978                         if (new_dlt != v) {
1979                                 if (ioctl(p->fd, BIOCSDLT, &new_dlt) != -1) {
1980                                         /*
1981                                          * We succeeded; make this the
1982                                          * new DLT_ value.
1983                                          */
1984                                         v = new_dlt;
1985                                 }
1986                         }
1987                 }
1988         }
1989 #endif /* various platforms */
1990 #endif /* BIOCGDLTLIST */
1991
1992         /*
1993          * If this is an Ethernet device, and we don't have a DLT_ list,
1994          * give it a list with DLT_EN10MB and DLT_DOCSIS.  (That'd give
1995          * 802.11 interfaces DLT_DOCSIS, which isn't the right thing to
1996          * do, but there's not much we can do about that without finding
1997          * some other way of determining whether it's an Ethernet or 802.11
1998          * device.)
1999          */
2000         if (v == DLT_EN10MB && p->dlt_count == 0) {
2001                 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2002                 /*
2003                  * If that fails, just leave the list empty.
2004                  */
2005                 if (p->dlt_list != NULL) {
2006                         p->dlt_list[0] = DLT_EN10MB;
2007                         p->dlt_list[1] = DLT_DOCSIS;
2008                         p->dlt_count = 2;
2009                 }
2010         }
2011 #ifdef PCAP_FDDIPAD
2012         if (v == DLT_FDDI)
2013                 p->fddipad = PCAP_FDDIPAD;
2014         else
2015                 p->fddipad = 0;
2016 #endif
2017         p->linktype = v;
2018
2019 #if defined(BIOCGHDRCMPLT) && defined(BIOCSHDRCMPLT)
2020         /*
2021          * Do a BIOCSHDRCMPLT, if defined, to turn that flag on, so
2022          * the link-layer source address isn't forcibly overwritten.
2023          * (Should we ignore errors?  Should we do this only if
2024          * we're open for writing?)
2025          *
2026          * XXX - I seem to remember some packet-sending bug in some
2027          * BSDs - check CVS log for "bpf.c"?
2028          */
2029         if (ioctl(fd, BIOCSHDRCMPLT, &spoof_eth_src) == -1) {
2030                 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2031                     "BIOCSHDRCMPLT: %s", pcap_strerror(errno));
2032                 status = PCAP_ERROR;
2033                 goto bad;
2034         }
2035 #endif
2036         /* set timeout */
2037 #ifdef HAVE_ZEROCOPY_BPF
2038         if (p->md.timeout != 0 && !p->md.zerocopy) {
2039 #else
2040         if (p->md.timeout) {
2041 #endif
2042                 /*
2043                  * XXX - is this seconds/nanoseconds in AIX?
2044                  * (Treating it as such doesn't fix the timeout
2045                  * problem described below.)
2046                  *
2047                  * XXX - Mac OS X 10.6 mishandles BIOCSRTIMEOUT in
2048                  * 64-bit userland - it takes, as an argument, a
2049                  * "struct BPF_TIMEVAL", which has 32-bit tv_sec
2050                  * and tv_usec, rather than a "struct timeval".
2051                  *
2052                  * If this platform defines "struct BPF_TIMEVAL",
2053                  * we check whether the structure size in BIOCSRTIMEOUT
2054                  * is that of a "struct timeval" and, if not, we use
2055                  * a "struct BPF_TIMEVAL" rather than a "struct timeval".
2056                  * (That way, if the bug is fixed in a future release,
2057                  * we will still do the right thing.)
2058                  */
2059                 struct timeval to;
2060 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2061                 struct BPF_TIMEVAL bpf_to;
2062
2063                 if (IOCPARM_LEN(BIOCSRTIMEOUT) != sizeof(struct timeval)) {
2064                         bpf_to.tv_sec = p->md.timeout / 1000;
2065                         bpf_to.tv_usec = (p->md.timeout * 1000) % 1000000;
2066                         if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&bpf_to) < 0) {
2067                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2068                                     "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2069                                 status = PCAP_ERROR;
2070                                 goto bad;
2071                         }
2072                 } else {
2073 #endif
2074                         to.tv_sec = p->md.timeout / 1000;
2075                         to.tv_usec = (p->md.timeout * 1000) % 1000000;
2076                         if (ioctl(p->fd, BIOCSRTIMEOUT, (caddr_t)&to) < 0) {
2077                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2078                                     "BIOCSRTIMEOUT: %s", pcap_strerror(errno));
2079                                 status = PCAP_ERROR;
2080                                 goto bad;
2081                         }
2082 #ifdef HAVE_STRUCT_BPF_TIMEVAL
2083                 }
2084 #endif
2085         }
2086
2087 #ifdef _AIX
2088 #ifdef  BIOCIMMEDIATE
2089         /*
2090          * Darren Reed notes that
2091          *
2092          *      On AIX (4.2 at least), if BIOCIMMEDIATE is not set, the
2093          *      timeout appears to be ignored and it waits until the buffer
2094          *      is filled before returning.  The result of not having it
2095          *      set is almost worse than useless if your BPF filter
2096          *      is reducing things to only a few packets (i.e. one every
2097          *      second or so).
2098          *
2099          * so we turn BIOCIMMEDIATE mode on if this is AIX.
2100          *
2101          * We don't turn it on for other platforms, as that means we
2102          * get woken up for every packet, which may not be what we want;
2103          * in the Winter 1993 USENIX paper on BPF, they say:
2104          *
2105          *      Since a process might want to look at every packet on a
2106          *      network and the time between packets can be only a few
2107          *      microseconds, it is not possible to do a read system call
2108          *      per packet and BPF must collect the data from several
2109          *      packets and return it as a unit when the monitoring
2110          *      application does a read.
2111          *
2112          * which I infer is the reason for the timeout - it means we
2113          * wait that amount of time, in the hopes that more packets
2114          * will arrive and we'll get them all with one read.
2115          *
2116          * Setting BIOCIMMEDIATE mode on FreeBSD (and probably other
2117          * BSDs) causes the timeout to be ignored.
2118          *
2119          * On the other hand, some platforms (e.g., Linux) don't support
2120          * timeouts, they just hand stuff to you as soon as it arrives;
2121          * if that doesn't cause a problem on those platforms, it may
2122          * be OK to have BIOCIMMEDIATE mode on BSD as well.
2123          *
2124          * (Note, though, that applications may depend on the read
2125          * completing, even if no packets have arrived, when the timeout
2126          * expires, e.g. GUI applications that have to check for input
2127          * while waiting for packets to arrive; a non-zero timeout
2128          * prevents "select()" from working right on FreeBSD and
2129          * possibly other BSDs, as the timer doesn't start until a
2130          * "read()" is done, so the timer isn't in effect if the
2131          * application is blocked on a "select()", and the "select()"
2132          * doesn't get woken up for a BPF device until the buffer
2133          * fills up.)
2134          */
2135         v = 1;
2136         if (ioctl(p->fd, BIOCIMMEDIATE, &v) < 0) {
2137                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCIMMEDIATE: %s",
2138                     pcap_strerror(errno));
2139                 status = PCAP_ERROR;
2140                 goto bad;
2141         }
2142 #endif  /* BIOCIMMEDIATE */
2143 #endif  /* _AIX */
2144
2145         if (p->opt.promisc) {
2146                 /* set promiscuous mode, just warn if it fails */
2147                 if (ioctl(p->fd, BIOCPROMISC, NULL) < 0) {
2148                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCPROMISC: %s",
2149                             pcap_strerror(errno));
2150                         status = PCAP_WARNING_PROMISC_NOTSUP;
2151                 }
2152         }
2153
2154         if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
2155                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCGBLEN: %s",
2156                     pcap_strerror(errno));
2157                 status = PCAP_ERROR;
2158                 goto bad;
2159         }
2160         p->bufsize = v;
2161 #ifdef HAVE_ZEROCOPY_BPF
2162         if (!p->md.zerocopy) {
2163 #endif
2164         p->buffer = (u_char *)malloc(p->bufsize);
2165         if (p->buffer == NULL) {
2166                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2167                     pcap_strerror(errno));
2168                 status = PCAP_ERROR;
2169                 goto bad;
2170         }
2171 #ifdef _AIX
2172         /* For some strange reason this seems to prevent the EFAULT
2173          * problems we have experienced from AIX BPF. */
2174         memset(p->buffer, 0x0, p->bufsize);
2175 #endif
2176 #ifdef HAVE_ZEROCOPY_BPF
2177         }
2178 #endif
2179
2180         /*
2181          * If there's no filter program installed, there's
2182          * no indication to the kernel of what the snapshot
2183          * length should be, so no snapshotting is done.
2184          *
2185          * Therefore, when we open the device, we install
2186          * an "accept everything" filter with the specified
2187          * snapshot length.
2188          */
2189         total_insn.code = (u_short)(BPF_RET | BPF_K);
2190         total_insn.jt = 0;
2191         total_insn.jf = 0;
2192         total_insn.k = p->snapshot;
2193
2194         total_prog.bf_len = 1;
2195         total_prog.bf_insns = &total_insn;
2196         if (ioctl(p->fd, BIOCSETF, (caddr_t)&total_prog) < 0) {
2197                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2198                     pcap_strerror(errno));
2199                 status = PCAP_ERROR;
2200                 goto bad;
2201         }
2202
2203         /*
2204          * On most BPF platforms, either you can do a "select()" or
2205          * "poll()" on a BPF file descriptor and it works correctly,
2206          * or you can do it and it will return "readable" if the
2207          * hold buffer is full but not if the timeout expires *and*
2208          * a non-blocking read will, if the hold buffer is empty
2209          * but the store buffer isn't empty, rotate the buffers
2210          * and return what packets are available.
2211          *
2212          * In the latter case, the fact that a non-blocking read
2213          * will give you the available packets means you can work
2214          * around the failure of "select()" and "poll()" to wake up
2215          * and return "readable" when the timeout expires by using
2216          * the timeout as the "select()" or "poll()" timeout, putting
2217          * the BPF descriptor into non-blocking mode, and read from
2218          * it regardless of whether "select()" reports it as readable
2219          * or not.
2220          *
2221          * However, in FreeBSD 4.3 and 4.4, "select()" and "poll()"
2222          * won't wake up and return "readable" if the timer expires
2223          * and non-blocking reads return EWOULDBLOCK if the hold
2224          * buffer is empty, even if the store buffer is non-empty.
2225          *
2226          * This means the workaround in question won't work.
2227          *
2228          * Therefore, on FreeBSD 4.3 and 4.4, we set "p->selectable_fd"
2229          * to -1, which means "sorry, you can't use 'select()' or 'poll()'
2230          * here".  On all other BPF platforms, we set it to the FD for
2231          * the BPF device; in NetBSD, OpenBSD, and Darwin, a non-blocking
2232          * read will, if the hold buffer is empty and the store buffer
2233          * isn't empty, rotate the buffers and return what packets are
2234          * there (and in sufficiently recent versions of OpenBSD
2235          * "select()" and "poll()" should work correctly).
2236          *
2237          * XXX - what about AIX?
2238          */
2239         p->selectable_fd = p->fd;       /* assume select() works until we know otherwise */
2240         if (have_osinfo) {
2241                 /*
2242                  * We can check what OS this is.
2243                  */
2244                 if (strcmp(osinfo.sysname, "FreeBSD") == 0) {
2245                         if (strncmp(osinfo.release, "4.3-", 4) == 0 ||
2246                              strncmp(osinfo.release, "4.4-", 4) == 0)
2247                                 p->selectable_fd = -1;
2248                 }
2249         }
2250
2251         p->read_op = pcap_read_bpf;
2252         p->inject_op = pcap_inject_bpf;
2253         p->setfilter_op = pcap_setfilter_bpf;
2254         p->setdirection_op = pcap_setdirection_bpf;
2255         p->set_datalink_op = pcap_set_datalink_bpf;
2256         p->getnonblock_op = pcap_getnonblock_bpf;
2257         p->setnonblock_op = pcap_setnonblock_bpf;
2258         p->stats_op = pcap_stats_bpf;
2259         p->cleanup_op = pcap_cleanup_bpf;
2260
2261         return (status);
2262  bad:
2263         pcap_cleanup_bpf(p);
2264         return (status);
2265 }
2266
2267 int
2268 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2269 {
2270 #ifdef HAVE_DAG_API
2271         if (dag_platform_finddevs(alldevsp, errbuf) < 0)
2272                 return (-1);
2273 #endif /* HAVE_DAG_API */
2274 #ifdef HAVE_SNF_API
2275         if (snf_platform_finddevs(alldevsp, errbuf) < 0)
2276                 return (-1);
2277 #endif /* HAVE_SNF_API */
2278
2279         return (0);
2280 }
2281
2282 #ifdef HAVE_BSD_IEEE80211
2283 static int
2284 monitor_mode(pcap_t *p, int set)
2285 {
2286         int sock;
2287         struct ifmediareq req;
2288         int *media_list;
2289         int i;
2290         int can_do;
2291         struct ifreq ifr;
2292
2293         sock = socket(AF_INET, SOCK_DGRAM, 0);
2294         if (sock == -1) {
2295                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't open socket: %s",
2296                     pcap_strerror(errno));
2297                 return (PCAP_ERROR);
2298         }
2299
2300         memset(&req, 0, sizeof req);
2301         strncpy(req.ifm_name, p->opt.source, sizeof req.ifm_name);
2302
2303         /*
2304          * Find out how many media types we have.
2305          */
2306         if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2307                 /*
2308                  * Can't get the media types.
2309                  */
2310                 switch (errno) {
2311
2312                 case ENXIO:
2313                         /*
2314                          * There's no such device.
2315                          */
2316                         close(sock);
2317                         return (PCAP_ERROR_NO_SUCH_DEVICE);
2318
2319                 case EINVAL:
2320                         /*
2321                          * Interface doesn't support SIOC{G,S}IFMEDIA.
2322                          */
2323                         close(sock);
2324                         return (PCAP_ERROR_RFMON_NOTSUP);
2325
2326                 default:
2327                         snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2328                             "SIOCGIFMEDIA 1: %s", pcap_strerror(errno));
2329                         close(sock);
2330                         return (PCAP_ERROR);
2331                 }
2332         }
2333         if (req.ifm_count == 0) {
2334                 /*
2335                  * No media types.
2336                  */
2337                 close(sock);
2338                 return (PCAP_ERROR_RFMON_NOTSUP);
2339         }
2340
2341         /*
2342          * Allocate a buffer to hold all the media types, and
2343          * get the media types.
2344          */
2345         media_list = malloc(req.ifm_count * sizeof(int));
2346         if (media_list == NULL) {
2347                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s",
2348                     pcap_strerror(errno));
2349                 close(sock);
2350                 return (PCAP_ERROR);
2351         }
2352         req.ifm_ulist = media_list;
2353         if (ioctl(sock, SIOCGIFMEDIA, &req) < 0) {
2354                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "SIOCGIFMEDIA: %s",
2355                     pcap_strerror(errno));
2356                 free(media_list);
2357                 close(sock);
2358                 return (PCAP_ERROR);
2359         }
2360
2361         /*
2362          * Look for an 802.11 "automatic" media type.
2363          * We assume that all 802.11 adapters have that media type,
2364          * and that it will carry the monitor mode supported flag.
2365          */
2366         can_do = 0;
2367         for (i = 0; i < req.ifm_count; i++) {
2368                 if (IFM_TYPE(media_list[i]) == IFM_IEEE80211
2369                     && IFM_SUBTYPE(media_list[i]) == IFM_AUTO) {
2370                         /* OK, does it do monitor mode? */
2371                         if (media_list[i] & IFM_IEEE80211_MONITOR) {
2372                                 can_do = 1;
2373                                 break;
2374                         }
2375                 }
2376         }
2377         free(media_list);
2378         if (!can_do) {
2379                 /*
2380                  * This adapter doesn't support monitor mode.
2381                  */
2382                 close(sock);
2383                 return (PCAP_ERROR_RFMON_NOTSUP);
2384         }
2385
2386         if (set) {
2387                 /*
2388                  * Don't just check whether we can enable monitor mode,
2389                  * do so, if it's not already enabled.
2390                  */
2391                 if ((req.ifm_current & IFM_IEEE80211_MONITOR) == 0) {
2392                         /*
2393                          * Monitor mode isn't currently on, so turn it on,
2394                          * and remember that we should turn it off when the
2395                          * pcap_t is closed.
2396                          */
2397
2398                         /*
2399                          * If we haven't already done so, arrange to have
2400                          * "pcap_close_all()" called when we exit.
2401                          */
2402                         if (!pcap_do_addexit(p)) {
2403                                 /*
2404                                  * "atexit()" failed; don't put the interface
2405                                  * in monitor mode, just give up.
2406                                  */
2407                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2408                                      "atexit failed");
2409                                 close(sock);
2410                                 return (PCAP_ERROR);
2411                         }
2412                         memset(&ifr, 0, sizeof(ifr));
2413                         (void)strncpy(ifr.ifr_name, p->opt.source,
2414                             sizeof(ifr.ifr_name));
2415                         ifr.ifr_media = req.ifm_current | IFM_IEEE80211_MONITOR;
2416                         if (ioctl(sock, SIOCSIFMEDIA, &ifr) == -1) {
2417                                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
2418                                      "SIOCSIFMEDIA: %s", pcap_strerror(errno));
2419                                 close(sock);
2420                                 return (PCAP_ERROR);
2421                         }
2422
2423                         p->md.must_do_on_close |= MUST_CLEAR_RFMON;
2424
2425                         /*
2426                          * Add this to the list of pcaps to close when we exit.
2427                          */
2428                         pcap_add_to_pcaps_to_close(p);
2429                 }
2430         }
2431         return (0);
2432 }
2433 #endif /* HAVE_BSD_IEEE80211 */
2434
2435 #if defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211))
2436 /*
2437  * Check whether we have any 802.11 link-layer types; return the best
2438  * of the 802.11 link-layer types if we find one, and return -1
2439  * otherwise.
2440  *
2441  * DLT_IEEE802_11_RADIO, with the radiotap header, is considered the
2442  * best 802.11 link-layer type; any of the other 802.11-plus-radio
2443  * headers are second-best; 802.11 with no radio information is
2444  * the least good.
2445  */
2446 static int
2447 find_802_11(struct bpf_dltlist *bdlp)
2448 {
2449         int new_dlt;
2450         int i;
2451
2452         /*
2453          * Scan the list of DLT_ values, looking for 802.11 values,
2454          * and, if we find any, choose the best of them.
2455          */
2456         new_dlt = -1;
2457         for (i = 0; i < bdlp->bfl_len; i++) {
2458                 switch (bdlp->bfl_list[i]) {
2459
2460                 case DLT_IEEE802_11:
2461                         /*
2462                          * 802.11, but no radio.
2463                          *
2464                          * Offer this, and select it as the new mode
2465                          * unless we've already found an 802.11
2466                          * header with radio information.
2467                          */
2468                         if (new_dlt == -1)
2469                                 new_dlt = bdlp->bfl_list[i];
2470                         break;
2471
2472                 case DLT_PRISM_HEADER:
2473                 case DLT_AIRONET_HEADER:
2474                 case DLT_IEEE802_11_RADIO_AVS:
2475                         /*
2476                          * 802.11 with radio, but not radiotap.
2477                          *
2478                          * Offer this, and select it as the new mode
2479                          * unless we've already found the radiotap DLT_.
2480                          */
2481                         if (new_dlt != DLT_IEEE802_11_RADIO)
2482                                 new_dlt = bdlp->bfl_list[i];
2483                         break;
2484
2485                 case DLT_IEEE802_11_RADIO:
2486                         /*
2487                          * 802.11 with radiotap.
2488                          *
2489                          * Offer this, and select it as the new mode.
2490                          */
2491                         new_dlt = bdlp->bfl_list[i];
2492                         break;
2493
2494                 default:
2495                         /*
2496                          * Not 802.11.
2497                          */
2498                         break;
2499                 }
2500         }
2501
2502         return (new_dlt);
2503 }
2504 #endif /* defined(BIOCGDLTLIST) && (defined(__APPLE__) || defined(HAVE_BSD_IEEE80211)) */
2505
2506 #if defined(__APPLE__) && defined(BIOCGDLTLIST)
2507 /*
2508  * Remove DLT_EN10MB from the list of DLT_ values, as we're in monitor mode,
2509  * and DLT_EN10MB isn't supported in monitor mode.
2510  */
2511 static void
2512 remove_en(pcap_t *p)
2513 {
2514         int i, j;
2515
2516         /*
2517          * Scan the list of DLT_ values and discard DLT_EN10MB.
2518          */
2519         j = 0;
2520         for (i = 0; i < p->dlt_count; i++) {
2521                 switch (p->dlt_list[i]) {
2522
2523                 case DLT_EN10MB:
2524                         /*
2525                          * Don't offer this one.
2526                          */
2527                         continue;
2528
2529                 default:
2530                         /*
2531                          * Just copy this mode over.
2532                          */
2533                         break;
2534                 }
2535
2536                 /*
2537                  * Copy this DLT_ value to its new position.
2538                  */
2539                 p->dlt_list[j] = p->dlt_list[i];
2540                 j++;
2541         }
2542
2543         /*
2544          * Set the DLT_ count to the number of entries we copied.
2545          */
2546         p->dlt_count = j;
2547 }
2548
2549 /*
2550  * Remove 802.11 link-layer types from the list of DLT_ values, as
2551  * we're not in monitor mode, and those DLT_ values will switch us
2552  * to monitor mode.
2553  */
2554 static void
2555 remove_802_11(pcap_t *p)
2556 {
2557         int i, j;
2558
2559         /*
2560          * Scan the list of DLT_ values and discard 802.11 values.
2561          */
2562         j = 0;
2563         for (i = 0; i < p->dlt_count; i++) {
2564                 switch (p->dlt_list[i]) {
2565
2566                 case DLT_IEEE802_11:
2567                 case DLT_PRISM_HEADER:
2568                 case DLT_AIRONET_HEADER:
2569                 case DLT_IEEE802_11_RADIO:
2570                 case DLT_IEEE802_11_RADIO_AVS:
2571                         /*
2572                          * 802.11.  Don't offer this one.
2573                          */
2574                         continue;
2575
2576                 default:
2577                         /*
2578                          * Just copy this mode over.
2579                          */
2580                         break;
2581                 }
2582
2583                 /*
2584                  * Copy this DLT_ value to its new position.
2585                  */
2586                 p->dlt_list[j] = p->dlt_list[i];
2587                 j++;
2588         }
2589
2590         /*
2591          * Set the DLT_ count to the number of entries we copied.
2592          */
2593         p->dlt_count = j;
2594 }
2595 #endif /* defined(__APPLE__) && defined(BIOCGDLTLIST) */
2596
2597 static int
2598 pcap_setfilter_bpf(pcap_t *p, struct bpf_program *fp)
2599 {
2600         /*
2601          * Free any user-mode filter we might happen to have installed.
2602          */
2603         pcap_freecode(&p->fcode);
2604
2605         /*
2606          * Try to install the kernel filter.
2607          */
2608         if (ioctl(p->fd, BIOCSETF, (caddr_t)fp) == 0) {
2609                 /*
2610                  * It worked.
2611                  */
2612                 p->md.use_bpf = 1;      /* filtering in the kernel */
2613
2614                 /*
2615                  * Discard any previously-received packets, as they might
2616                  * have passed whatever filter was formerly in effect, but
2617                  * might not pass this filter (BIOCSETF discards packets
2618                  * buffered in the kernel, so you can lose packets in any
2619                  * case).
2620                  */
2621                 p->cc = 0;
2622                 return (0);
2623         }
2624
2625         /*
2626          * We failed.
2627          *
2628          * If it failed with EINVAL, that's probably because the program
2629          * is invalid or too big.  Validate it ourselves; if we like it
2630          * (we currently allow backward branches, to support protochain),
2631          * run it in userland.  (There's no notion of "too big" for
2632          * userland.)
2633          *
2634          * Otherwise, just give up.
2635          * XXX - if the copy of the program into the kernel failed,
2636          * we will get EINVAL rather than, say, EFAULT on at least
2637          * some kernels.
2638          */
2639         if (errno != EINVAL) {
2640                 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "BIOCSETF: %s",
2641                     pcap_strerror(errno));
2642                 return (-1);
2643         }
2644
2645         /*
2646          * install_bpf_program() validates the program.
2647          *
2648          * XXX - what if we already have a filter in the kernel?
2649          */
2650         if (install_bpf_program(p, fp) < 0)
2651                 return (-1);
2652         p->md.use_bpf = 0;      /* filtering in userland */
2653         return (0);
2654 }
2655
2656 /*
2657  * Set direction flag: Which packets do we accept on a forwarding
2658  * single device? IN, OUT or both?
2659  */
2660 static int
2661 pcap_setdirection_bpf(pcap_t *p, pcap_direction_t d)
2662 {
2663 #if defined(BIOCSDIRECTION)
2664         u_int direction;
2665
2666         direction = (d == PCAP_D_IN) ? BPF_D_IN :
2667             ((d == PCAP_D_OUT) ? BPF_D_OUT : BPF_D_INOUT);
2668         if (ioctl(p->fd, BIOCSDIRECTION, &direction) == -1) {
2669                 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2670                     "Cannot set direction to %s: %s",
2671                         (d == PCAP_D_IN) ? "PCAP_D_IN" :
2672                         ((d == PCAP_D_OUT) ? "PCAP_D_OUT" : "PCAP_D_INOUT"),
2673                         strerror(errno));
2674                 return (-1);
2675         }
2676         return (0);
2677 #elif defined(BIOCSSEESENT)
2678         u_int seesent;
2679
2680         /*
2681          * We don't support PCAP_D_OUT.
2682          */
2683         if (d == PCAP_D_OUT) {
2684                 snprintf(p->errbuf, sizeof(p->errbuf),
2685                     "Setting direction to PCAP_D_OUT is not supported on BPF");
2686                 return -1;
2687         }
2688
2689         seesent = (d == PCAP_D_INOUT);
2690         if (ioctl(p->fd, BIOCSSEESENT, &seesent) == -1) {
2691                 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2692                     "Cannot set direction to %s: %s",
2693                         (d == PCAP_D_INOUT) ? "PCAP_D_INOUT" : "PCAP_D_IN",
2694                         strerror(errno));
2695                 return (-1);
2696         }
2697         return (0);
2698 #else
2699         (void) snprintf(p->errbuf, sizeof(p->errbuf),
2700             "This system doesn't support BIOCSSEESENT, so the direction can't be set");
2701         return (-1);
2702 #endif
2703 }
2704
2705 static int
2706 pcap_set_datalink_bpf(pcap_t *p, int dlt)
2707 {
2708 #ifdef BIOCSDLT
2709         if (ioctl(p->fd, BIOCSDLT, &dlt) == -1) {
2710                 (void) snprintf(p->errbuf, sizeof(p->errbuf),
2711                     "Cannot set DLT %d: %s", dlt, strerror(errno));
2712                 return (-1);
2713         }
2714 #endif
2715         return (0);
2716 }