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