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