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