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