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