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