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