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