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