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