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