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