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