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