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