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