xref: /freebsd/contrib/libpcap/pcap.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 /*
2  * Copyright (c) 1993, 1994, 1995, 1996, 1997, 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 the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the Computer Systems
16  *	Engineering Group at Lawrence Berkeley Laboratory.
17  * 4. Neither the name of the University nor of the Laboratory may be used
18  *    to endorse or promote products derived from this software without
19  *    specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <config.h>
35 
36 /* Get the same variety of strerror_r() as Autoconf/CMake has detected. */
37 #include "ftmacros.h"
38 
39 #include <pcap-types.h>
40 #ifndef _WIN32
41 #include <sys/param.h>
42 #ifndef MSDOS
43 #include <sys/file.h>
44 #endif
45 #include <sys/ioctl.h>
46 #include <sys/socket.h>
47 #ifdef HAVE_SYS_SOCKIO_H
48 #include <sys/sockio.h>
49 #endif
50 
51 struct mbuf;		/* Squelch compiler warnings on some platforms for */
52 struct rtentry;		/* declarations in <net/if.h> */
53 #include <net/if.h>
54 #include <netinet/in.h>
55 #endif /* _WIN32 */
56 
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #if !defined(_MSC_VER) && !defined(__BORLANDC__) && !defined(__MINGW32__)
61 #include <unistd.h>
62 #endif
63 #include <fcntl.h>
64 #include <errno.h>
65 #include <limits.h>
66 
67 #include "diag-control.h"
68 
69 #include "thread-local.h"
70 
71 #ifdef HAVE_OS_PROTO_H
72 #include "os-proto.h"
73 #endif
74 
75 #ifdef MSDOS
76 #include "pcap-dos.h"
77 #endif
78 
79 #include "pcap-int.h"
80 
81 #include "optimize.h"
82 
83 #ifdef HAVE_DAG_API
84 #include "pcap-dag.h"
85 #endif /* HAVE_DAG_API */
86 
87 #ifdef HAVE_SEPTEL_API
88 #include "pcap-septel.h"
89 #endif /* HAVE_SEPTEL_API */
90 
91 #ifdef HAVE_SNF_API
92 #include "pcap-snf.h"
93 #endif /* HAVE_SNF_API */
94 
95 #ifdef HAVE_TC_API
96 #include "pcap-tc.h"
97 #endif /* HAVE_TC_API */
98 
99 #ifdef PCAP_SUPPORT_LINUX_USBMON
100 #include "pcap-usb-linux.h"
101 #endif
102 
103 #ifdef PCAP_SUPPORT_BT
104 #include "pcap-bt-linux.h"
105 #endif
106 
107 #ifdef PCAP_SUPPORT_BT_MONITOR
108 #include "pcap-bt-monitor-linux.h"
109 #endif
110 
111 #ifdef PCAP_SUPPORT_NETFILTER
112 #include "pcap-netfilter-linux.h"
113 #endif
114 
115 #ifdef PCAP_SUPPORT_NETMAP
116 #include "pcap-netmap.h"
117 #endif
118 
119 #ifdef PCAP_SUPPORT_DBUS
120 #include "pcap-dbus.h"
121 #endif
122 
123 #ifdef PCAP_SUPPORT_RDMASNIFF
124 #include "pcap-rdmasniff.h"
125 #endif
126 
127 #ifdef PCAP_SUPPORT_DPDK
128 #include "pcap-dpdk.h"
129 #endif
130 
131 #ifdef HAVE_AIRPCAP_API
132 #include "pcap-airpcap.h"
133 #endif
134 
135 #ifdef _WIN32
136 /*
137  * To quote the WSAStartup() documentation:
138  *
139  *   The WSAStartup function typically leads to protocol-specific helper
140  *   DLLs being loaded. As a result, the WSAStartup function should not
141  *   be called from the DllMain function in a application DLL. This can
142  *   potentially cause deadlocks.
143  *
144  * and the WSACleanup() documentation:
145  *
146  *   The WSACleanup function typically leads to protocol-specific helper
147  *   DLLs being unloaded. As a result, the WSACleanup function should not
148  *   be called from the DllMain function in a application DLL. This can
149  *   potentially cause deadlocks.
150  *
151  * So we don't initialize Winsock in a DllMain() routine.
152  *
153  * pcap_init() should be called to initialize pcap on both UN*X and
154  * Windows; it will initialize Winsock on Windows.  (It will also be
155  * initialized as needed if pcap_init() hasn't been called.)
156  */
157 
158 /*
159  * Shut down Winsock.
160  *
161  * Ignores the return value of WSACleanup(); given that this is
162  * an atexit() routine, there's nothing much we can do about
163  * a failure.
164  */
165 static void
166 internal_wsockfini(void)
167 {
168 	WSACleanup();
169 }
170 
171 /*
172  * Start Winsock.
173  * Internal routine.
174  */
175 static int
176 internal_wsockinit(char *errbuf)
177 {
178 	WORD wVersionRequested;
179 	WSADATA wsaData;
180 	static int err = -1;
181 	static int done = 0;
182 	int status;
183 
184 	if (done)
185 		return (err);
186 
187 	/*
188 	 * Versions of Windows that don't support Winsock 2.2 are
189 	 * too old for us.
190 	 */
191 	wVersionRequested = MAKEWORD(2, 2);
192 	status = WSAStartup(wVersionRequested, &wsaData);
193 	done = 1;
194 	if (status != 0) {
195 		if (errbuf != NULL) {
196 			pcapint_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
197 			    status, "WSAStartup() failed");
198 		}
199 		return (err);
200 	}
201 	atexit(internal_wsockfini);
202 	err = 0;
203 	return (err);
204 }
205 
206 /*
207  * Exported in case some applications using WinPcap/Npcap called it,
208  * even though it wasn't exported.
209  */
210 int
211 wsockinit(void)
212 {
213 	return (internal_wsockinit(NULL));
214 }
215 
216 /*
217  * This is the exported function; new programs should call this.
218  * *Newer* programs should call pcap_init().
219  */
220 int
221 pcap_wsockinit(void)
222 {
223 	return (internal_wsockinit(NULL));
224 }
225 #endif /* _WIN32 */
226 
227 /*
228  * Do whatever initialization is needed for libpcap.
229  *
230  * The argument specifies whether we use the local code page or UTF-8
231  * for strings; on UN*X, we just assume UTF-8 in places where the encoding
232  * would matter, whereas, on Windows, we use the local code page for
233  * PCAP_CHAR_ENC_LOCAL and UTF-8 for PCAP_CHAR_ENC_UTF_8.
234  *
235  * On Windows, we also disable the hack in pcap_create() to deal with
236  * being handed UTF-16 strings, because if the user calls this they're
237  * explicitly declaring that they will either be passing local code
238  * page strings or UTF-8 strings, so we don't need to allow UTF-16LE
239  * strings to be passed.  For good measure, on Windows *and* UN*X,
240  * we disable pcap_lookupdev(), to prevent anybody from even
241  * *trying* to pass the result of pcap_lookupdev() - which might be
242  * UTF-16LE on Windows, for ugly compatibility reasons - to pcap_create()
243  * or pcap_open_live() or pcap_open().
244  *
245  * Returns 0 on success, -1 on error.
246  */
247 int pcapint_new_api;		/* pcap_lookupdev() always fails */
248 int pcapint_utf_8_mode;		/* Strings should be in UTF-8. */
249 
250 int
251 pcap_init(unsigned int opts, char *errbuf)
252 {
253 	static int initialized;
254 
255 	/*
256 	 * Don't allow multiple calls that set different modes; that
257 	 * may mean a library is initializing pcap in one mode and
258 	 * a program using that library, or another library used by
259 	 * that program, is initializing it in another mode.
260 	 */
261 	switch (opts) {
262 
263 	case PCAP_CHAR_ENC_LOCAL:
264 		/* Leave "UTF-8 mode" off. */
265 		if (initialized) {
266 			if (pcapint_utf_8_mode) {
267 				snprintf(errbuf, PCAP_ERRBUF_SIZE,
268 				    "Multiple pcap_init calls with different character encodings");
269 				return (PCAP_ERROR);
270 			}
271 		}
272 		break;
273 
274 	case PCAP_CHAR_ENC_UTF_8:
275 		/* Turn on "UTF-8 mode". */
276 		if (initialized) {
277 			if (!pcapint_utf_8_mode) {
278 				snprintf(errbuf, PCAP_ERRBUF_SIZE,
279 				    "Multiple pcap_init calls with different character encodings");
280 				return (PCAP_ERROR);
281 			}
282 		}
283 		pcapint_utf_8_mode = 1;
284 		break;
285 
286 	default:
287 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Unknown options specified");
288 		return (PCAP_ERROR);
289 	}
290 
291 	/*
292 	 * Turn the appropriate mode on for error messages; those routines
293 	 * are also used in rpcapd, which has no access to pcap's internal
294 	 * UTF-8 mode flag, so we have to call a routine to set its
295 	 * UTF-8 mode flag.
296 	 */
297 	pcapint_fmt_set_encoding(opts);
298 
299 	if (initialized) {
300 		/*
301 		 * Nothing more to do; for example, on Windows, we've
302 		 * already initialized Winsock.
303 		 */
304 		return (0);
305 	}
306 
307 #ifdef _WIN32
308 	/*
309 	 * Now set up Winsock.
310 	 */
311 	if (internal_wsockinit(errbuf) == -1) {
312 		/* Failed. */
313 		return (PCAP_ERROR);
314 	}
315 #endif
316 
317 	/*
318 	 * We're done.
319 	 */
320 	initialized = 1;
321 	pcapint_new_api = 1;
322 	return (0);
323 }
324 
325 /*
326  * String containing the library version.
327  * Not explicitly exported via a header file - the right API to use
328  * is pcap_lib_version() - but some programs included it, so we
329  * provide it.
330  *
331  * We declare it here, right before defining it, to squelch any
332  * warnings we might get from compilers about the lack of a
333  * declaration.
334  */
335 PCAP_API char pcap_version[];
336 PCAP_API_DEF char pcap_version[] = PACKAGE_VERSION;
337 
338 static void
339 pcap_set_not_initialized_message(pcap_t *pcap)
340 {
341 	if (pcap->activated) {
342 		/* A module probably forgot to set the function pointer */
343 		(void)snprintf(pcap->errbuf, sizeof(pcap->errbuf),
344 		    "This operation isn't properly handled by that device");
345 		return;
346 	}
347 	/* in case the caller doesn't check for PCAP_ERROR_NOT_ACTIVATED */
348 	(void)snprintf(pcap->errbuf, sizeof(pcap->errbuf),
349 	    "This handle hasn't been activated yet");
350 }
351 
352 static int
353 pcap_read_not_initialized(pcap_t *pcap, int cnt _U_, pcap_handler callback _U_,
354     u_char *user _U_)
355 {
356 	pcap_set_not_initialized_message(pcap);
357 	/* this means 'not initialized' */
358 	return (PCAP_ERROR_NOT_ACTIVATED);
359 }
360 
361 static int
362 pcap_inject_not_initialized(pcap_t *pcap, const void * buf _U_, int size _U_)
363 {
364 	pcap_set_not_initialized_message(pcap);
365 	/* this means 'not initialized' */
366 	return (PCAP_ERROR_NOT_ACTIVATED);
367 }
368 
369 static int
370 pcap_setfilter_not_initialized(pcap_t *pcap, struct bpf_program *fp _U_)
371 {
372 	pcap_set_not_initialized_message(pcap);
373 	/* this means 'not initialized' */
374 	return (PCAP_ERROR_NOT_ACTIVATED);
375 }
376 
377 static int
378 pcap_setdirection_not_initialized(pcap_t *pcap, pcap_direction_t d _U_)
379 {
380 	pcap_set_not_initialized_message(pcap);
381 	/* this means 'not initialized' */
382 	return (PCAP_ERROR_NOT_ACTIVATED);
383 }
384 
385 static int
386 pcap_set_datalink_not_initialized(pcap_t *pcap, int dlt _U_)
387 {
388 	pcap_set_not_initialized_message(pcap);
389 	/* this means 'not initialized' */
390 	return (PCAP_ERROR_NOT_ACTIVATED);
391 }
392 
393 static int
394 pcap_getnonblock_not_initialized(pcap_t *pcap)
395 {
396 	pcap_set_not_initialized_message(pcap);
397 	/* this means 'not initialized' */
398 	return (PCAP_ERROR_NOT_ACTIVATED);
399 }
400 
401 static int
402 pcap_stats_not_initialized(pcap_t *pcap, struct pcap_stat *ps _U_)
403 {
404 	pcap_set_not_initialized_message(pcap);
405 	/* this means 'not initialized' */
406 	return (PCAP_ERROR_NOT_ACTIVATED);
407 }
408 
409 #ifdef _WIN32
410 static struct pcap_stat *
411 pcap_stats_ex_not_initialized(pcap_t *pcap, int *pcap_stat_size _U_)
412 {
413 	pcap_set_not_initialized_message(pcap);
414 	return (NULL);
415 }
416 
417 static int
418 pcap_setbuff_not_initialized(pcap_t *pcap, int dim _U_)
419 {
420 	pcap_set_not_initialized_message(pcap);
421 	/* this means 'not initialized' */
422 	return (PCAP_ERROR_NOT_ACTIVATED);
423 }
424 
425 static int
426 pcap_setmode_not_initialized(pcap_t *pcap, int mode _U_)
427 {
428 	pcap_set_not_initialized_message(pcap);
429 	/* this means 'not initialized' */
430 	return (PCAP_ERROR_NOT_ACTIVATED);
431 }
432 
433 static int
434 pcap_setmintocopy_not_initialized(pcap_t *pcap, int size _U_)
435 {
436 	pcap_set_not_initialized_message(pcap);
437 	/* this means 'not initialized' */
438 	return (PCAP_ERROR_NOT_ACTIVATED);
439 }
440 
441 static HANDLE
442 pcap_getevent_not_initialized(pcap_t *pcap)
443 {
444 	pcap_set_not_initialized_message(pcap);
445 	return (INVALID_HANDLE_VALUE);
446 }
447 
448 static int
449 pcap_oid_get_request_not_initialized(pcap_t *pcap, bpf_u_int32 oid _U_,
450     void *data _U_, size_t *lenp _U_)
451 {
452 	pcap_set_not_initialized_message(pcap);
453 	return (PCAP_ERROR_NOT_ACTIVATED);
454 }
455 
456 static int
457 pcap_oid_set_request_not_initialized(pcap_t *pcap, bpf_u_int32 oid _U_,
458     const void *data _U_, size_t *lenp _U_)
459 {
460 	pcap_set_not_initialized_message(pcap);
461 	return (PCAP_ERROR_NOT_ACTIVATED);
462 }
463 
464 static u_int
465 pcap_sendqueue_transmit_not_initialized(pcap_t *pcap, pcap_send_queue* queue _U_,
466     int sync _U_)
467 {
468 	pcap_set_not_initialized_message(pcap);
469 	return (0);
470 }
471 
472 static int
473 pcap_setuserbuffer_not_initialized(pcap_t *pcap, int size _U_)
474 {
475 	pcap_set_not_initialized_message(pcap);
476 	return (PCAP_ERROR_NOT_ACTIVATED);
477 }
478 
479 static int
480 pcap_live_dump_not_initialized(pcap_t *pcap, char *filename _U_, int maxsize _U_,
481     int maxpacks _U_)
482 {
483 	pcap_set_not_initialized_message(pcap);
484 	return (PCAP_ERROR_NOT_ACTIVATED);
485 }
486 
487 static int
488 pcap_live_dump_ended_not_initialized(pcap_t *pcap, int sync _U_)
489 {
490 	pcap_set_not_initialized_message(pcap);
491 	return (PCAP_ERROR_NOT_ACTIVATED);
492 }
493 
494 static PAirpcapHandle
495 pcap_get_airpcap_handle_not_initialized(pcap_t *pcap)
496 {
497 	pcap_set_not_initialized_message(pcap);
498 	return (NULL);
499 }
500 #endif
501 
502 /*
503  * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
504  * a PCAP_ERROR value on an error.
505  */
506 int
507 pcap_can_set_rfmon(pcap_t *p)
508 {
509 	return (p->can_set_rfmon_op(p));
510 }
511 
512 /*
513  * For systems where rfmon mode is never supported.
514  */
515 static int
516 pcap_cant_set_rfmon(pcap_t *p _U_)
517 {
518 	return (0);
519 }
520 
521 /*
522  * Sets *tstamp_typesp to point to an array 1 or more supported time stamp
523  * types; the return value is the number of supported time stamp types.
524  * The list should be freed by a call to pcap_free_tstamp_types() when
525  * you're done with it.
526  *
527  * A return value of 0 means "you don't get a choice of time stamp type",
528  * in which case *tstamp_typesp is set to null.
529  *
530  * PCAP_ERROR is returned on error.
531  */
532 int
533 pcap_list_tstamp_types(pcap_t *p, int **tstamp_typesp)
534 {
535 	if (p->tstamp_type_count == 0) {
536 		/*
537 		 * We don't support multiple time stamp types.
538 		 * That means the only type we support is PCAP_TSTAMP_HOST;
539 		 * set up a list containing only that type.
540 		 */
541 		*tstamp_typesp = (int*)malloc(sizeof(**tstamp_typesp));
542 		if (*tstamp_typesp == NULL) {
543 			pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
544 			    errno, "malloc");
545 			return (PCAP_ERROR);
546 		}
547 		**tstamp_typesp = PCAP_TSTAMP_HOST;
548 		return (1);
549 	} else {
550 		*tstamp_typesp = (int*)calloc(p->tstamp_type_count,
551 					      sizeof(**tstamp_typesp));
552 		if (*tstamp_typesp == NULL) {
553 			pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
554 			    errno, "malloc");
555 			return (PCAP_ERROR);
556 		}
557 		(void)memcpy(*tstamp_typesp, p->tstamp_type_list,
558 		    sizeof(**tstamp_typesp) * p->tstamp_type_count);
559 		return (p->tstamp_type_count);
560 	}
561 }
562 
563 /*
564  * In Windows, you might have a library built with one version of the
565  * C runtime library and an application built with another version of
566  * the C runtime library, which means that the library might use one
567  * version of malloc() and free() and the application might use another
568  * version of malloc() and free().  If so, that means something
569  * allocated by the library cannot be freed by the application, so we
570  * need to have a pcap_free_tstamp_types() routine to free up the list
571  * allocated by pcap_list_tstamp_types(), even though it's just a wrapper
572  * around free().
573  */
574 void
575 pcap_free_tstamp_types(int *tstamp_type_list)
576 {
577 	free(tstamp_type_list);
578 }
579 
580 /*
581  * Default one-shot callback; overridden for capture types where the
582  * packet data cannot be guaranteed to be available after the callback
583  * returns, so that a copy must be made.
584  */
585 void
586 pcapint_oneshot(u_char *user, const struct pcap_pkthdr *h, const u_char *pkt)
587 {
588 	struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
589 
590 	*sp->hdr = *h;
591 	*sp->pkt = pkt;
592 }
593 
594 const u_char *
595 pcap_next(pcap_t *p, struct pcap_pkthdr *h)
596 {
597 	struct oneshot_userdata s;
598 	const u_char *pkt;
599 
600 	s.hdr = h;
601 	s.pkt = &pkt;
602 	s.pd = p;
603 	if (pcap_dispatch(p, 1, p->oneshot_callback, (u_char *)&s) <= 0)
604 		return (0);
605 	return (pkt);
606 }
607 
608 int
609 pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header,
610     const u_char **pkt_data)
611 {
612 	struct oneshot_userdata s;
613 
614 	s.hdr = &p->pcap_header;
615 	s.pkt = pkt_data;
616 	s.pd = p;
617 
618 	/* Saves a pointer to the packet headers */
619 	*pkt_header= &p->pcap_header;
620 
621 	if (p->rfile != NULL) {
622 		int status;
623 
624 		/* We are on an offline capture */
625 		status = pcapint_offline_read(p, 1, p->oneshot_callback,
626 		    (u_char *)&s);
627 
628 		/*
629 		 * Return codes for pcapint_offline_read() are:
630 		 *   -  0: EOF
631 		 *   - -1: error
632 		 *   - >0: OK - result is number of packets read, so
633 		 *         it will be 1 in this case, as we've passed
634 		 *         a maximum packet count of 1
635 		 * The first one ('0') conflicts with the return code of
636 		 * 0 from pcap_read() meaning "no packets arrived before
637 		 * the timeout expired", so we map it to -2 so you can
638 		 * distinguish between an EOF from a savefile and a
639 		 * "no packets arrived before the timeout expired, try
640 		 * again" from a live capture.
641 		 */
642 		if (status == 0)
643 			return (-2);
644 		else
645 			return (status);
646 	}
647 
648 	/*
649 	 * Return codes for pcap_read() are:
650 	 *   -  0: timeout
651 	 *   - -1: error
652 	 *   - -2: loop was broken out of with pcap_breakloop()
653 	 *   - >0: OK, result is number of packets captured, so
654 	 *         it will be 1 in this case, as we've passed
655 	 *         a maximum packet count of 1
656 	 * The first one ('0') conflicts with the return code of 0 from
657 	 * pcapint_offline_read() meaning "end of file".
658 	*/
659 	return (p->read_op(p, 1, p->oneshot_callback, (u_char *)&s));
660 }
661 
662 /*
663  * Implementation of a pcap_if_list_t.
664  */
665 struct pcap_if_list {
666 	pcap_if_t *beginning;
667 };
668 
669 static struct capture_source_type {
670 	int (*findalldevs_op)(pcap_if_list_t *, char *);
671 	pcap_t *(*create_op)(const char *, char *, int *);
672 } capture_source_types[] = {
673 #ifdef HAVE_DAG_API
674 	{ dag_findalldevs, dag_create },
675 #endif
676 #ifdef HAVE_SEPTEL_API
677 	{ septel_findalldevs, septel_create },
678 #endif
679 #ifdef HAVE_SNF_API
680 	{ snf_findalldevs, snf_create },
681 #endif
682 #ifdef HAVE_TC_API
683 	{ TcFindAllDevs, TcCreate },
684 #endif
685 #ifdef PCAP_SUPPORT_BT
686 	{ bt_findalldevs, bt_create },
687 #endif
688 #ifdef PCAP_SUPPORT_BT_MONITOR
689 	{ bt_monitor_findalldevs, bt_monitor_create },
690 #endif
691 #ifdef PCAP_SUPPORT_LINUX_USBMON
692 	{ usb_findalldevs, usb_create },
693 #endif
694 #ifdef PCAP_SUPPORT_NETFILTER
695 	{ netfilter_findalldevs, netfilter_create },
696 #endif
697 #ifdef PCAP_SUPPORT_NETMAP
698 	{ pcap_netmap_findalldevs, pcap_netmap_create },
699 #endif
700 #ifdef PCAP_SUPPORT_DBUS
701 	{ dbus_findalldevs, dbus_create },
702 #endif
703 #ifdef PCAP_SUPPORT_RDMASNIFF
704 	{ rdmasniff_findalldevs, rdmasniff_create },
705 #endif
706 #ifdef PCAP_SUPPORT_DPDK
707 	{ pcap_dpdk_findalldevs, pcap_dpdk_create },
708 #endif
709 #ifdef HAVE_AIRPCAP_API
710 	{ airpcap_findalldevs, airpcap_create },
711 #endif
712 	{ NULL, NULL }
713 };
714 
715 /*
716  * Get a list of all capture sources that are up and that we can open.
717  * Returns -1 on error, 0 otherwise.
718  * The list, as returned through "alldevsp", may be null if no interfaces
719  * were up and could be opened.
720  */
721 int
722 pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
723 {
724 	size_t i;
725 	pcap_if_list_t devlist;
726 
727 	/*
728 	 * Find all the local network interfaces on which we
729 	 * can capture.
730 	 */
731 	devlist.beginning = NULL;
732 	if (pcapint_platform_finddevs(&devlist, errbuf) == -1) {
733 		/*
734 		 * Failed - free all of the entries we were given
735 		 * before we failed.
736 		 */
737 		if (devlist.beginning != NULL)
738 			pcap_freealldevs(devlist.beginning);
739 		*alldevsp = NULL;
740 		return (-1);
741 	}
742 
743 	/*
744 	 * Ask each of the non-local-network-interface capture
745 	 * source types what interfaces they have.
746 	 */
747 	for (i = 0; capture_source_types[i].findalldevs_op != NULL; i++) {
748 		if (capture_source_types[i].findalldevs_op(&devlist, errbuf) == -1) {
749 			/*
750 			 * We had an error; free the list we've been
751 			 * constructing.
752 			 */
753 			if (devlist.beginning != NULL)
754 				pcap_freealldevs(devlist.beginning);
755 			*alldevsp = NULL;
756 			return (-1);
757 		}
758 	}
759 
760 	/*
761 	 * Return the first entry of the list of all devices.
762 	 */
763 	*alldevsp = devlist.beginning;
764 	return (0);
765 }
766 
767 static struct sockaddr *
768 dup_sockaddr(struct sockaddr *sa, size_t sa_length)
769 {
770 	struct sockaddr *newsa;
771 
772 	if ((newsa = malloc(sa_length)) == NULL)
773 		return (NULL);
774 	return (memcpy(newsa, sa, sa_length));
775 }
776 
777 /*
778  * Construct a "figure of merit" for an interface, for use when sorting
779  * the list of interfaces, in which interfaces that are up are superior
780  * to interfaces that aren't up, interfaces that are up and running are
781  * superior to interfaces that are up but not running, and non-loopback
782  * interfaces that are up and running are superior to loopback interfaces,
783  * and interfaces with the same flags have a figure of merit that's higher
784  * the lower the instance number.
785  *
786  * The goal is to try to put the interfaces most likely to be useful for
787  * capture at the beginning of the list.
788  *
789  * The figure of merit, which is lower the "better" the interface is,
790  * has the uppermost bit set if the interface isn't running, the bit
791  * below that set if the interface isn't up, the bit below that
792  * set if the interface is a loopback interface, and the bit below
793  * that set if it's the "any" interface.
794  *
795  * Note: we don't sort by unit number because 1) not all interfaces have
796  * a unit number (systemd, for example, might assign interface names
797  * based on the interface's MAC address or on the physical location of
798  * the adapter's connector), and 2) if the name does end with a simple
799  * unit number, it's not a global property of the interface, it's only
800  * useful as a sort key for device names with the same prefix, so xyz0
801  * shouldn't necessarily sort before abc2.  This means that interfaces
802  * with the same figure of merit will be sorted by the order in which
803  * the mechanism from which we're getting the interfaces supplies them.
804  */
805 static u_int
806 get_figure_of_merit(pcap_if_t *dev)
807 {
808 	u_int n;
809 
810 	n = 0;
811 	if (!(dev->flags & PCAP_IF_RUNNING))
812 		n |= 0x80000000;
813 	if (!(dev->flags & PCAP_IF_UP))
814 		n |= 0x40000000;
815 
816 	/*
817 	 * Give non-wireless interfaces that aren't disconnected a better
818 	 * figure of merit than interfaces that are disconnected, as
819 	 * "disconnected" should indicate that the interface isn't
820 	 * plugged into a network and thus won't give you any traffic.
821 	 *
822 	 * For wireless interfaces, it means "associated with a network",
823 	 * which we presume not to necessarily prevent capture, as you
824 	 * might run the adapter in some flavor of monitor mode.
825 	 */
826 	if (!(dev->flags & PCAP_IF_WIRELESS) &&
827 	    (dev->flags & PCAP_IF_CONNECTION_STATUS) == PCAP_IF_CONNECTION_STATUS_DISCONNECTED)
828 		n |= 0x20000000;
829 
830 	/*
831 	 * Sort loopback devices after non-loopback devices, *except* for
832 	 * disconnected devices.
833 	 */
834 	if (dev->flags & PCAP_IF_LOOPBACK)
835 		n |= 0x10000000;
836 
837 	/*
838 	 * Sort the "any" device before loopback and disconnected devices,
839 	 * but after all other devices.
840 	 */
841 	if (strcmp(dev->name, "any") == 0)
842 		n |= 0x08000000;
843 
844 	return (n);
845 }
846 
847 #ifndef _WIN32
848 /*
849  * Try to get a description for a given device.
850  * Returns a malloced description if it could and NULL if it couldn't.
851  *
852  * XXX - on FreeBSDs that support it, should it get the sysctl named
853  * "dev.{adapter family name}.{adapter unit}.%desc" to get a description
854  * of the adapter?  Note that "dev.an.0.%desc" is "Aironet PC4500/PC4800"
855  * with my Cisco 350 card, so the name isn't entirely descriptive.  The
856  * "dev.an.0.%pnpinfo" has a better description, although one might argue
857  * that the problem is really a driver bug - if it can find out that it's
858  * a Cisco 340 or 350, rather than an old Aironet card, it should use
859  * that in the description.
860  *
861  * Do NetBSD, DragonflyBSD, or OpenBSD support this as well?  FreeBSD
862  * and OpenBSD let you get a description, but it's not generated by the OS,
863  * it's set with another ioctl that ifconfig supports; we use that to get
864  * a description in FreeBSD and OpenBSD, but if there is no such
865  * description available, it still might be nice to get some description
866  * string based on the device type or something such as that.
867  *
868  * In macOS, the System Configuration framework can apparently return
869  * names in 10.4 and later.
870  *
871  * It also appears that freedesktop.org's HAL offers an "info.product"
872  * string, but the HAL specification says it "should not be used in any
873  * UI" and "subsystem/capability specific properties" should be used
874  * instead and, in any case, I think HAL is being deprecated in
875  * favor of other stuff such as DeviceKit.  DeviceKit doesn't appear
876  * to have any obvious product information for devices, but maybe
877  * I haven't looked hard enough.
878  *
879  * Using the System Configuration framework, or HAL, or DeviceKit, or
880  * whatever, would require that libpcap applications be linked with
881  * the frameworks/libraries in question.  That shouldn't be a problem
882  * for programs linking with the shared version of libpcap (unless
883  * you're running on AIX - which I think is the only UN*X that doesn't
884  * support linking a shared library with other libraries on which it
885  * depends, and having an executable linked only with the first shared
886  * library automatically pick up the other libraries when started -
887  * and using HAL or whatever).  Programs linked with the static
888  * version of libpcap would have to use pcap-config with the --static
889  * flag in order to get the right linker flags in order to pick up
890  * the additional libraries/frameworks; those programs need that anyway
891  * for libpcap 1.1 and beyond on Linux, as, by default, it requires
892  * -lnl.
893  *
894  * Do any other UN*Xes, or desktop environments support getting a
895  * description?
896  */
897 static char *
898 #ifdef SIOCGIFDESCR
899 get_if_description(const char *name)
900 {
901 	char *description = NULL;
902 	int s;
903 	struct ifreq ifrdesc;
904 #ifndef IFDESCRSIZE
905 	size_t descrlen = 64;
906 #else
907 	size_t descrlen = IFDESCRSIZE;
908 #endif /* IFDESCRSIZE */
909 
910 	/*
911 	 * Get the description for the interface.
912 	 */
913 	memset(&ifrdesc, 0, sizeof ifrdesc);
914 	pcapint_strlcpy(ifrdesc.ifr_name, name, sizeof ifrdesc.ifr_name);
915 	s = socket(AF_INET, SOCK_DGRAM, 0);
916 	if (s >= 0) {
917 #ifdef __FreeBSD__
918 		/*
919 		 * On FreeBSD, if the buffer isn't big enough for the
920 		 * description, the ioctl succeeds, but the description
921 		 * isn't copied, ifr_buffer.length is set to the description
922 		 * length, and ifr_buffer.buffer is set to NULL.
923 		 */
924 		for (;;) {
925 			free(description);
926 			if ((description = malloc(descrlen)) != NULL) {
927 				ifrdesc.ifr_buffer.buffer = description;
928 				ifrdesc.ifr_buffer.length = descrlen;
929 				if (ioctl(s, SIOCGIFDESCR, &ifrdesc) == 0) {
930 					if (ifrdesc.ifr_buffer.buffer ==
931 					    description)
932 						break;
933 					else
934 						descrlen = ifrdesc.ifr_buffer.length;
935 				} else {
936 					/*
937 					 * Failed to get interface description.
938 					 */
939 					free(description);
940 					description = NULL;
941 					break;
942 				}
943 			} else
944 				break;
945 		}
946 #else /* __FreeBSD__ */
947 		/*
948 		 * The only other OS that currently supports
949 		 * SIOCGIFDESCR is OpenBSD, and it has no way
950 		 * to get the description length - it's clamped
951 		 * to a maximum of IFDESCRSIZE.
952 		 */
953 		if ((description = malloc(descrlen)) != NULL) {
954 			ifrdesc.ifr_data = (caddr_t)description;
955 			if (ioctl(s, SIOCGIFDESCR, &ifrdesc) != 0) {
956 				/*
957 				 * Failed to get interface description.
958 				 */
959 				free(description);
960 				description = NULL;
961 			}
962 		}
963 #endif /* __FreeBSD__ */
964 		close(s);
965 		if (description != NULL && description[0] == '\0') {
966 			/*
967 			 * Description is empty, so discard it.
968 			 */
969 			free(description);
970 			description = NULL;
971 		}
972 	}
973 
974 #ifdef __FreeBSD__
975 	/*
976 	 * For FreeBSD, if we didn't get a description, and this is
977 	 * a device with a name of the form usbusN, label it as a USB
978 	 * bus.
979 	 */
980 	if (description == NULL) {
981 		if (strncmp(name, "usbus", 5) == 0) {
982 			/*
983 			 * OK, it begins with "usbus".
984 			 */
985 			long busnum;
986 			char *p;
987 
988 			errno = 0;
989 			busnum = strtol(name + 5, &p, 10);
990 			if (errno == 0 && p != name + 5 && *p == '\0' &&
991 			    busnum >= 0 && busnum <= INT_MAX) {
992 				/*
993 				 * OK, it's a valid number that's not
994 				 * bigger than INT_MAX.  Construct
995 				 * a description from it.
996 				 * (If that fails, we don't worry about
997 				 * it, we just return NULL.)
998 				 */
999 				if (pcapint_asprintf(&description,
1000 				    "USB bus number %ld", busnum) == -1) {
1001 					/* Failed. */
1002 					description = NULL;
1003 				}
1004 			}
1005 		}
1006 	}
1007 #endif
1008 	return (description);
1009 #else /* SIOCGIFDESCR */
1010 get_if_description(const char *name _U_)
1011 {
1012 	return (NULL);
1013 #endif /* SIOCGIFDESCR */
1014 }
1015 
1016 /*
1017  * Look for a given device in the specified list of devices.
1018  *
1019  * If we find it, return a pointer to its entry.
1020  *
1021  * If we don't find it, attempt to add an entry for it, with the specified
1022  * IFF_ flags and description, and, if that succeeds, return a pointer to
1023  * the new entry, otherwise return NULL and set errbuf to an error message.
1024  */
1025 pcap_if_t *
1026 pcapint_find_or_add_if(pcap_if_list_t *devlistp, const char *name,
1027     uint64_t if_flags, get_if_flags_func get_flags_func, char *errbuf)
1028 {
1029 	bpf_u_int32 pcap_flags;
1030 
1031 	/*
1032 	 * Convert IFF_ flags to pcap flags.
1033 	 */
1034 	pcap_flags = 0;
1035 #ifdef IFF_LOOPBACK
1036 	if (if_flags & IFF_LOOPBACK)
1037 		pcap_flags |= PCAP_IF_LOOPBACK;
1038 #else
1039 	/*
1040 	 * We don't have IFF_LOOPBACK, so look at the device name to
1041 	 * see if it looks like a loopback device.
1042 	 */
1043 	if (name[0] == 'l' && name[1] == 'o' &&
1044 	    (PCAP_ISDIGIT(name[2]) || name[2] == '\0'))
1045 		pcap_flags |= PCAP_IF_LOOPBACK;
1046 #endif
1047 #ifdef IFF_UP
1048 	if (if_flags & IFF_UP)
1049 		pcap_flags |= PCAP_IF_UP;
1050 #endif
1051 #ifdef IFF_RUNNING
1052 	if (if_flags & IFF_RUNNING)
1053 		pcap_flags |= PCAP_IF_RUNNING;
1054 #endif
1055 
1056 	/*
1057 	 * Attempt to find an entry for this device; if we don't find one,
1058 	 * attempt to add one.
1059 	 */
1060 	return (pcapint_find_or_add_dev(devlistp, name, pcap_flags,
1061 	    get_flags_func, get_if_description(name), errbuf));
1062 }
1063 
1064 /*
1065  * Look for a given device in the specified list of devices.
1066  *
1067  * If we find it, then, if the specified address isn't null, add it to
1068  * the list of addresses for the device and return 0.
1069  *
1070  * If we don't find it, attempt to add an entry for it, with the specified
1071  * IFF_ flags and description, and, if that succeeds, add the specified
1072  * address to its list of addresses if that address is non-null, and
1073  * return 0, otherwise return -1 and set errbuf to an error message.
1074  *
1075  * (We can get called with a null address because we might get a list
1076  * of interface name/address combinations from the underlying OS, with
1077  * the address being absent in some cases, rather than a list of
1078  * interfaces with each interface having a list of addresses, so this
1079  * call may be the only call made to add to the list, and we want to
1080  * add interfaces even if they have no addresses.)
1081  */
1082 int
1083 pcapint_add_addr_to_if(pcap_if_list_t *devlistp, const char *name,
1084     uint64_t if_flags, get_if_flags_func get_flags_func,
1085     struct sockaddr *addr, size_t addr_size,
1086     struct sockaddr *netmask, size_t netmask_size,
1087     struct sockaddr *broadaddr, size_t broadaddr_size,
1088     struct sockaddr *dstaddr, size_t dstaddr_size,
1089     char *errbuf)
1090 {
1091 	pcap_if_t *curdev;
1092 
1093 	/*
1094 	 * Check whether the device exists and, if not, add it.
1095 	 */
1096 	curdev = pcapint_find_or_add_if(devlistp, name, if_flags, get_flags_func,
1097 	    errbuf);
1098 	if (curdev == NULL) {
1099 		/*
1100 		 * Error - give up.
1101 		 */
1102 		return (-1);
1103 	}
1104 
1105 	if (addr == NULL) {
1106 		/*
1107 		 * There's no address to add; this entry just meant
1108 		 * "here's a new interface".
1109 		 */
1110 		return (0);
1111 	}
1112 
1113 	/*
1114 	 * "curdev" is an entry for this interface, and we have an
1115 	 * address for it; add an entry for that address to the
1116 	 * interface's list of addresses.
1117 	 */
1118 	return (pcapint_add_addr_to_dev(curdev, addr, addr_size, netmask,
1119 	    netmask_size, broadaddr, broadaddr_size, dstaddr,
1120 	    dstaddr_size, errbuf));
1121 }
1122 #endif /* _WIN32 */
1123 
1124 /*
1125  * Add an entry to the list of addresses for an interface.
1126  * "curdev" is the entry for that interface.
1127  */
1128 int
1129 pcapint_add_addr_to_dev(pcap_if_t *curdev,
1130     struct sockaddr *addr, size_t addr_size,
1131     struct sockaddr *netmask, size_t netmask_size,
1132     struct sockaddr *broadaddr, size_t broadaddr_size,
1133     struct sockaddr *dstaddr, size_t dstaddr_size,
1134     char *errbuf)
1135 {
1136 	pcap_addr_t *curaddr, *prevaddr, *nextaddr;
1137 
1138 	/*
1139 	 * Allocate the new entry and fill it in.
1140 	 */
1141 	curaddr = (pcap_addr_t *)malloc(sizeof(pcap_addr_t));
1142 	if (curaddr == NULL) {
1143 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1144 		    errno, "malloc");
1145 		return (-1);
1146 	}
1147 
1148 	curaddr->next = NULL;
1149 	if (addr != NULL && addr_size != 0) {
1150 		curaddr->addr = (struct sockaddr *)dup_sockaddr(addr, addr_size);
1151 		if (curaddr->addr == NULL) {
1152 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1153 			    errno, "malloc");
1154 			free(curaddr);
1155 			return (-1);
1156 		}
1157 	} else
1158 		curaddr->addr = NULL;
1159 
1160 	if (netmask != NULL && netmask_size != 0) {
1161 		curaddr->netmask = (struct sockaddr *)dup_sockaddr(netmask, netmask_size);
1162 		if (curaddr->netmask == NULL) {
1163 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1164 			    errno, "malloc");
1165 			if (curaddr->addr != NULL)
1166 				free(curaddr->addr);
1167 			free(curaddr);
1168 			return (-1);
1169 		}
1170 	} else
1171 		curaddr->netmask = NULL;
1172 
1173 	if (broadaddr != NULL && broadaddr_size != 0) {
1174 		curaddr->broadaddr = (struct sockaddr *)dup_sockaddr(broadaddr, broadaddr_size);
1175 		if (curaddr->broadaddr == NULL) {
1176 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1177 			    errno, "malloc");
1178 			if (curaddr->netmask != NULL)
1179 				free(curaddr->netmask);
1180 			if (curaddr->addr != NULL)
1181 				free(curaddr->addr);
1182 			free(curaddr);
1183 			return (-1);
1184 		}
1185 	} else
1186 		curaddr->broadaddr = NULL;
1187 
1188 	if (dstaddr != NULL && dstaddr_size != 0) {
1189 		curaddr->dstaddr = (struct sockaddr *)dup_sockaddr(dstaddr, dstaddr_size);
1190 		if (curaddr->dstaddr == NULL) {
1191 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1192 			    errno, "malloc");
1193 			if (curaddr->broadaddr != NULL)
1194 				free(curaddr->broadaddr);
1195 			if (curaddr->netmask != NULL)
1196 				free(curaddr->netmask);
1197 			if (curaddr->addr != NULL)
1198 				free(curaddr->addr);
1199 			free(curaddr);
1200 			return (-1);
1201 		}
1202 	} else
1203 		curaddr->dstaddr = NULL;
1204 
1205 	/*
1206 	 * Find the end of the list of addresses.
1207 	 */
1208 	for (prevaddr = curdev->addresses; prevaddr != NULL; prevaddr = nextaddr) {
1209 		nextaddr = prevaddr->next;
1210 		if (nextaddr == NULL) {
1211 			/*
1212 			 * This is the end of the list.
1213 			 */
1214 			break;
1215 		}
1216 	}
1217 
1218 	if (prevaddr == NULL) {
1219 		/*
1220 		 * The list was empty; this is the first member.
1221 		 */
1222 		curdev->addresses = curaddr;
1223 	} else {
1224 		/*
1225 		 * "prevaddr" is the last member of the list; append
1226 		 * this member to it.
1227 		 */
1228 		prevaddr->next = curaddr;
1229 	}
1230 
1231 	return (0);
1232 }
1233 
1234 /*
1235  * Look for a given device in the specified list of devices.
1236  *
1237  * If we find it, return 0 and set *curdev_ret to point to it.
1238  *
1239  * If we don't find it, attempt to add an entry for it, with the specified
1240  * flags and description, and, if that succeeds, return 0, otherwise
1241  * return -1 and set errbuf to an error message.
1242  */
1243 pcap_if_t *
1244 pcapint_find_or_add_dev(pcap_if_list_t *devlistp, const char *name, bpf_u_int32 flags,
1245     get_if_flags_func get_flags_func, const char *description, char *errbuf)
1246 {
1247 	pcap_if_t *curdev;
1248 
1249 	/*
1250 	 * Is there already an entry in the list for this device?
1251 	 */
1252 	curdev = pcapint_find_dev(devlistp, name);
1253 	if (curdev != NULL) {
1254 		/*
1255 		 * Yes, return it.
1256 		 */
1257 		return (curdev);
1258 	}
1259 
1260 	/*
1261 	 * No, we didn't find it.
1262 	 */
1263 
1264 	/*
1265 	 * Try to get additional flags for the device.
1266 	 */
1267 	if ((*get_flags_func)(name, &flags, errbuf) == -1) {
1268 		/*
1269 		 * Failed.
1270 		 */
1271 		return (NULL);
1272 	}
1273 
1274 	/*
1275 	 * Now, try to add it to the list of devices.
1276 	 */
1277 	return (pcapint_add_dev(devlistp, name, flags, description, errbuf));
1278 }
1279 
1280 /*
1281  * Look for a given device in the specified list of devices, and return
1282  * the entry for it if we find it or NULL if we don't.
1283  */
1284 pcap_if_t *
1285 pcapint_find_dev(pcap_if_list_t *devlistp, const char *name)
1286 {
1287 	pcap_if_t *curdev;
1288 
1289 	/*
1290 	 * Is there an entry in the list for this device?
1291 	 */
1292 	for (curdev = devlistp->beginning; curdev != NULL;
1293 	    curdev = curdev->next) {
1294 		if (strcmp(name, curdev->name) == 0) {
1295 			/*
1296 			 * We found it, so, yes, there is.  No need to
1297 			 * add it.  Provide the entry we found to our
1298 			 * caller.
1299 			 */
1300 			return (curdev);
1301 		}
1302 	}
1303 
1304 	/*
1305 	 * No.
1306 	 */
1307 	return (NULL);
1308 }
1309 
1310 /*
1311  * Attempt to add an entry for a device, with the specified flags
1312  * and description, and, if that succeeds, return 0 and return a pointer
1313  * to the new entry, otherwise return NULL and set errbuf to an error
1314  * message.
1315  *
1316  * If we weren't given a description, try to get one.
1317  */
1318 pcap_if_t *
1319 pcapint_add_dev(pcap_if_list_t *devlistp, const char *name, bpf_u_int32 flags,
1320     const char *description, char *errbuf)
1321 {
1322 	pcap_if_t *curdev, *prevdev, *nextdev;
1323 	u_int this_figure_of_merit, nextdev_figure_of_merit;
1324 
1325 	curdev = malloc(sizeof(pcap_if_t));
1326 	if (curdev == NULL) {
1327 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1328 		    errno, "malloc");
1329 		return (NULL);
1330 	}
1331 
1332 	/*
1333 	 * Fill in the entry.
1334 	 */
1335 	curdev->next = NULL;
1336 	curdev->name = strdup(name);
1337 	if (curdev->name == NULL) {
1338 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1339 		    errno, "malloc");
1340 		free(curdev);
1341 		return (NULL);
1342 	}
1343 	if (description == NULL) {
1344 		/*
1345 		 * We weren't handed a description for the interface.
1346 		 */
1347 		curdev->description = NULL;
1348 	} else {
1349 		/*
1350 		 * We were handed a description; make a copy.
1351 		 */
1352 		curdev->description = strdup(description);
1353 		if (curdev->description == NULL) {
1354 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1355 			    errno, "malloc");
1356 			free(curdev->name);
1357 			free(curdev);
1358 			return (NULL);
1359 		}
1360 	}
1361 	curdev->addresses = NULL;	/* list starts out as empty */
1362 	curdev->flags = flags;
1363 
1364 	/*
1365 	 * Add it to the list, in the appropriate location.
1366 	 * First, get the "figure of merit" for this interface.
1367 	 */
1368 	this_figure_of_merit = get_figure_of_merit(curdev);
1369 
1370 	/*
1371 	 * Now look for the last interface with an figure of merit
1372 	 * less than or equal to the new interface's figure of merit.
1373 	 *
1374 	 * We start with "prevdev" being NULL, meaning we're before
1375 	 * the first element in the list.
1376 	 */
1377 	prevdev = NULL;
1378 	for (;;) {
1379 		/*
1380 		 * Get the interface after this one.
1381 		 */
1382 		if (prevdev == NULL) {
1383 			/*
1384 			 * The next element is the first element.
1385 			 */
1386 			nextdev = devlistp->beginning;
1387 		} else
1388 			nextdev = prevdev->next;
1389 
1390 		/*
1391 		 * Are we at the end of the list?
1392 		 */
1393 		if (nextdev == NULL) {
1394 			/*
1395 			 * Yes - we have to put the new entry after "prevdev".
1396 			 */
1397 			break;
1398 		}
1399 
1400 		/*
1401 		 * Is the new interface's figure of merit less
1402 		 * than the next interface's figure of merit,
1403 		 * meaning that the new interface is better
1404 		 * than the next interface?
1405 		 */
1406 		nextdev_figure_of_merit = get_figure_of_merit(nextdev);
1407 		if (this_figure_of_merit < nextdev_figure_of_merit) {
1408 			/*
1409 			 * Yes - we should put the new entry
1410 			 * before "nextdev", i.e. after "prevdev".
1411 			 */
1412 			break;
1413 		}
1414 
1415 		prevdev = nextdev;
1416 	}
1417 
1418 	/*
1419 	 * Insert before "nextdev".
1420 	 */
1421 	curdev->next = nextdev;
1422 
1423 	/*
1424 	 * Insert after "prevdev" - unless "prevdev" is null,
1425 	 * in which case this is the first interface.
1426 	 */
1427 	if (prevdev == NULL) {
1428 		/*
1429 		 * This is the first interface.  Make it
1430 		 * the first element in the list of devices.
1431 		 */
1432 		devlistp->beginning = curdev;
1433 	} else
1434 		prevdev->next = curdev;
1435 	return (curdev);
1436 }
1437 
1438 /*
1439  * Add an entry for the "any" device.
1440  */
1441 pcap_if_t *
1442 pcap_add_any_dev(pcap_if_list_t *devlistp, char *errbuf)
1443 {
1444 	static const char any_descr[] = "Pseudo-device that captures on all interfaces";
1445 
1446 	/*
1447 	 * As it refers to all network devices, not to any particular
1448 	 * network device, the notion of "connected" vs. "disconnected"
1449 	 * doesn't apply to the "any" device.
1450 	 */
1451 	return pcapint_add_dev(devlistp, "any",
1452 	    PCAP_IF_UP|PCAP_IF_RUNNING|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
1453 	    any_descr, errbuf);
1454 }
1455 
1456 /*
1457  * Free a list of interfaces.
1458  */
1459 void
1460 pcap_freealldevs(pcap_if_t *alldevs)
1461 {
1462 	pcap_if_t *curdev, *nextdev;
1463 	pcap_addr_t *curaddr, *nextaddr;
1464 
1465 	for (curdev = alldevs; curdev != NULL; curdev = nextdev) {
1466 		nextdev = curdev->next;
1467 
1468 		/*
1469 		 * Free all addresses.
1470 		 */
1471 		for (curaddr = curdev->addresses; curaddr != NULL; curaddr = nextaddr) {
1472 			nextaddr = curaddr->next;
1473 			if (curaddr->addr)
1474 				free(curaddr->addr);
1475 			if (curaddr->netmask)
1476 				free(curaddr->netmask);
1477 			if (curaddr->broadaddr)
1478 				free(curaddr->broadaddr);
1479 			if (curaddr->dstaddr)
1480 				free(curaddr->dstaddr);
1481 			free(curaddr);
1482 		}
1483 
1484 		/*
1485 		 * Free the name string.
1486 		 */
1487 		free(curdev->name);
1488 
1489 		/*
1490 		 * Free the description string, if any.
1491 		 */
1492 		if (curdev->description != NULL)
1493 			free(curdev->description);
1494 
1495 		/*
1496 		 * Free the interface.
1497 		 */
1498 		free(curdev);
1499 	}
1500 }
1501 
1502 /*
1503  * pcap-npf.c has its own pcap_lookupdev(), for compatibility reasons, as
1504  * it actually returns the names of all interfaces, with a NUL separator
1505  * between them; some callers may depend on that.
1506  *
1507  * MS-DOS has its own pcap_lookupdev(), but that might be useful only
1508  * as an optimization.
1509  *
1510  * In all other cases, we just use pcap_findalldevs() to get a list of
1511  * devices, and pick from that list.
1512  */
1513 #if !defined(HAVE_PACKET32) && !defined(MSDOS)
1514 /*
1515  * Return the name of a network interface attached to the system, or NULL
1516  * if none can be found.  The interface must be configured up; the
1517  * lowest unit number is preferred; loopback is ignored.
1518  */
1519 char *
1520 pcap_lookupdev(char *errbuf)
1521 {
1522 	pcap_if_t *alldevs;
1523 #ifdef _WIN32
1524   /*
1525    * Windows - use the same size as the old WinPcap 3.1 code.
1526    * XXX - this is probably bigger than it needs to be.
1527    */
1528   #define IF_NAMESIZE 8192
1529 #else
1530   /*
1531    * UN*X - use the system's interface name size.
1532    * XXX - that might not be large enough for capture devices
1533    * that aren't regular network interfaces.
1534    */
1535   /* for old BSD systems, including bsdi3 */
1536   #ifndef IF_NAMESIZE
1537   #define IF_NAMESIZE IFNAMSIZ
1538   #endif
1539 #endif
1540 	static char device[IF_NAMESIZE + 1];
1541 	char *ret;
1542 
1543 	/*
1544 	 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1545 	 * it may return UTF-16 strings, for backwards-compatibility
1546 	 * reasons, and we're also disabling the hack to make that work,
1547 	 * for not-going-past-the-end-of-a-string reasons, and 2) we
1548 	 * want its behavior to be consistent.
1549 	 *
1550 	 * In addition, it's not thread-safe, so we've marked it as
1551 	 * deprecated.
1552 	 */
1553 	if (pcapint_new_api) {
1554 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
1555 		    "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1556 		return (NULL);
1557 	}
1558 
1559 	if (pcap_findalldevs(&alldevs, errbuf) == -1)
1560 		return (NULL);
1561 
1562 	if (alldevs == NULL || (alldevs->flags & PCAP_IF_LOOPBACK)) {
1563 		/*
1564 		 * There are no devices on the list, or the first device
1565 		 * on the list is a loopback device, which means there
1566 		 * are no non-loopback devices on the list.  This means
1567 		 * we can't return any device.
1568 		 *
1569 		 * XXX - why not return a loopback device?  If we can't
1570 		 * capture on it, it won't be on the list, and if it's
1571 		 * on the list, there aren't any non-loopback devices,
1572 		 * so why not just supply it as the default device?
1573 		 */
1574 		(void)pcapint_strlcpy(errbuf, "no suitable device found",
1575 		    PCAP_ERRBUF_SIZE);
1576 		ret = NULL;
1577 	} else {
1578 		/*
1579 		 * Return the name of the first device on the list.
1580 		 */
1581 		(void)pcapint_strlcpy(device, alldevs->name, sizeof(device));
1582 		ret = device;
1583 	}
1584 
1585 	pcap_freealldevs(alldevs);
1586 	return (ret);
1587 }
1588 #endif /* !defined(HAVE_PACKET32) && !defined(MSDOS) */
1589 
1590 #if !defined(_WIN32) && !defined(MSDOS)
1591 /*
1592  * We don't just fetch the entire list of devices, search for the
1593  * particular device, and use its first IPv4 address, as that's too
1594  * much work to get just one device's netmask.
1595  *
1596  * If we had an API to get attributes for a given device, we could
1597  * use that.
1598  */
1599 int
1600 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
1601     char *errbuf)
1602 {
1603 	register int fd;
1604 	register struct sockaddr_in *sin4;
1605 	struct ifreq ifr;
1606 
1607 	/*
1608 	 * The pseudo-device "any" listens on all interfaces and therefore
1609 	 * has the network address and -mask "0.0.0.0" therefore catching
1610 	 * all traffic. Using NULL for the interface is the same as "any".
1611 	 */
1612 	if (!device || strcmp(device, "any") == 0
1613 #ifdef HAVE_DAG_API
1614 	    || strstr(device, "dag") != NULL
1615 #endif
1616 #ifdef HAVE_SEPTEL_API
1617 	    || strstr(device, "septel") != NULL
1618 #endif
1619 #ifdef PCAP_SUPPORT_BT
1620 	    || strstr(device, "bluetooth") != NULL
1621 #endif
1622 #ifdef PCAP_SUPPORT_LINUX_USBMON
1623 	    || strstr(device, "usbmon") != NULL
1624 #endif
1625 #ifdef HAVE_SNF_API
1626 	    || strstr(device, "snf") != NULL
1627 #endif
1628 #ifdef PCAP_SUPPORT_NETMAP
1629 	    || strncmp(device, "netmap:", 7) == 0
1630 	    || strncmp(device, "vale", 4) == 0
1631 #endif
1632 #ifdef PCAP_SUPPORT_DPDK
1633 	    || strncmp(device, "dpdk:", 5) == 0
1634 #endif
1635 	    ) {
1636 		*netp = *maskp = 0;
1637 		return 0;
1638 	}
1639 
1640 	fd = socket(AF_INET, SOCK_DGRAM, 0);
1641 	if (fd < 0) {
1642 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1643 		    errno, "socket");
1644 		return (-1);
1645 	}
1646 	memset(&ifr, 0, sizeof(ifr));
1647 #ifdef __linux__
1648 	/* XXX Work around Linux kernel bug */
1649 	ifr.ifr_addr.sa_family = AF_INET;
1650 #endif
1651 	(void)pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1652 #if defined(__HAIKU__) && defined(__clang__)
1653 	/*
1654 	 * In Haiku R1/beta4 <unistd.h> ioctl() is a macro that needs to take 4
1655 	 * arguments to initialize its intermediate 2-member structure fully so
1656 	 * that Clang does not generate a -Wmissing-field-initializers warning
1657 	 * (which manifests only when it runs with -Werror).  This workaround
1658 	 * can be removed as soon as there is a Haiku release that fixes the
1659 	 * problem.  See also https://review.haiku-os.org/c/haiku/+/6369
1660 	 */
1661 	if (ioctl(fd, SIOCGIFADDR, (char *)&ifr, sizeof(ifr)) < 0) {
1662 #else
1663 	if (ioctl(fd, SIOCGIFADDR, (char *)&ifr) < 0) {
1664 #endif /* __HAIKU__ && __clang__ */
1665 		if (errno == EADDRNOTAVAIL) {
1666 			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1667 			    "%s: no IPv4 address assigned", device);
1668 		} else {
1669 			pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1670 			    errno, "SIOCGIFADDR: %s", device);
1671 		}
1672 		(void)close(fd);
1673 		return (-1);
1674 	}
1675 	sin4 = (struct sockaddr_in *)&ifr.ifr_addr;
1676 	*netp = sin4->sin_addr.s_addr;
1677 	memset(&ifr, 0, sizeof(ifr));
1678 #ifdef __linux__
1679 	/* XXX Work around Linux kernel bug */
1680 	ifr.ifr_addr.sa_family = AF_INET;
1681 #endif
1682 	(void)pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1683 #if defined(__HAIKU__) && defined(__clang__)
1684 	/* Same as above. */
1685 	if (ioctl(fd, SIOCGIFNETMASK, (char *)&ifr, sizeof(ifr)) < 0) {
1686 #else
1687 	if (ioctl(fd, SIOCGIFNETMASK, (char *)&ifr) < 0) {
1688 #endif /* __HAIKU__ && __clang__ */
1689 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1690 		    errno, "SIOCGIFNETMASK: %s", device);
1691 		(void)close(fd);
1692 		return (-1);
1693 	}
1694 	(void)close(fd);
1695 	*maskp = sin4->sin_addr.s_addr;
1696 	if (*maskp == 0) {
1697 		if (IN_CLASSA(*netp))
1698 			*maskp = IN_CLASSA_NET;
1699 		else if (IN_CLASSB(*netp))
1700 			*maskp = IN_CLASSB_NET;
1701 		else if (IN_CLASSC(*netp))
1702 			*maskp = IN_CLASSC_NET;
1703 		else {
1704 			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1705 			    "inet class for 0x%x unknown", *netp);
1706 			return (-1);
1707 		}
1708 	}
1709 	*netp &= *maskp;
1710 	return (0);
1711 }
1712 #endif /* !defined(_WIN32) && !defined(MSDOS) */
1713 
1714 #ifdef ENABLE_REMOTE
1715 #include "pcap-rpcap.h"
1716 
1717 /*
1718  * Extract a substring from a string.
1719  */
1720 static char *
1721 get_substring(const char *p, size_t len, char *ebuf)
1722 {
1723 	char *token;
1724 
1725 	token = malloc(len + 1);
1726 	if (token == NULL) {
1727 		pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1728 		    errno, "malloc");
1729 		return (NULL);
1730 	}
1731 	memcpy(token, p, len);
1732 	token[len] = '\0';
1733 	return (token);
1734 }
1735 
1736 /*
1737  * Parse a capture source that might be a URL.
1738  *
1739  * If the source is not a URL, *schemep, *userinfop, *hostp, and *portp
1740  * are set to NULL, *pathp is set to point to the source, and 0 is
1741  * returned.
1742  *
1743  * If source is a URL, and the URL refers to a local device (a special
1744  * case of rpcap:), *schemep, *userinfop, *hostp, and *portp are set
1745  * to NULL, *pathp is set to point to the device name, and 0 is returned.
1746  *
1747  * If source is a URL, and it's not a special case that refers to a local
1748  * device, and the parse succeeds:
1749  *
1750  *    *schemep is set to point to an allocated string containing the scheme;
1751  *
1752  *    if user information is present in the URL, *userinfop is set to point
1753  *    to an allocated string containing the user information, otherwise
1754  *    it's set to NULL;
1755  *
1756  *    if host information is present in the URL, *hostp is set to point
1757  *    to an allocated string containing the host information, otherwise
1758  *    it's set to NULL;
1759  *
1760  *    if a port number is present in the URL, *portp is set to point
1761  *    to an allocated string containing the port number, otherwise
1762  *    it's set to NULL;
1763  *
1764  *    *pathp is set to point to an allocated string containing the
1765  *    path;
1766  *
1767  * and 0 is returned.
1768  *
1769  * If the parse fails, ebuf is set to an error string, and -1 is returned.
1770  */
1771 static int
1772 pcap_parse_source(const char *source, char **schemep, char **userinfop,
1773     char **hostp, char **portp, char **pathp, char *ebuf)
1774 {
1775 	char *colonp;
1776 	size_t scheme_len;
1777 	char *scheme;
1778 	const char *endp;
1779 	size_t authority_len;
1780 	char *authority;
1781 	char *parsep, *atsignp, *bracketp;
1782 	char *userinfo, *host, *port, *path;
1783 
1784 	/*
1785 	 * Start out returning nothing.
1786 	 */
1787 	*schemep = NULL;
1788 	*userinfop = NULL;
1789 	*hostp = NULL;
1790 	*portp = NULL;
1791 	*pathp = NULL;
1792 
1793 	/*
1794 	 * RFC 3986 says:
1795 	 *
1796 	 *   URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
1797 	 *
1798 	 *   hier-part   = "//" authority path-abempty
1799 	 *               / path-absolute
1800 	 *               / path-rootless
1801 	 *               / path-empty
1802 	 *
1803 	 *   authority   = [ userinfo "@" ] host [ ":" port ]
1804 	 *
1805 	 *   userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
1806          *
1807          * Step 1: look for the ":" at the end of the scheme.
1808 	 * A colon in the source is *NOT* sufficient to indicate that
1809 	 * this is a URL, as interface names on some platforms might
1810 	 * include colons (e.g., I think some Solaris interfaces
1811 	 * might).
1812 	 */
1813 	colonp = strchr(source, ':');
1814 	if (colonp == NULL) {
1815 		/*
1816 		 * The source is the device to open.
1817 		 * Return a NULL pointer for the scheme, user information,
1818 		 * host, and port, and return the device as the path.
1819 		 */
1820 		*pathp = strdup(source);
1821 		if (*pathp == NULL) {
1822 			pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1823 			    errno, "malloc");
1824 			return (-1);
1825 		}
1826 		return (0);
1827 	}
1828 
1829 	/*
1830 	 * All schemes must have "//" after them, i.e. we only support
1831 	 * hier-part   = "//" authority path-abempty, not
1832 	 * hier-part   = path-absolute
1833 	 * hier-part   = path-rootless
1834 	 * hier-part   = path-empty
1835 	 *
1836 	 * We need that in order to distinguish between a local device
1837 	 * name that happens to contain a colon and a URI.
1838 	 */
1839 	if (strncmp(colonp + 1, "//", 2) != 0) {
1840 		/*
1841 		 * The source is the device to open.
1842 		 * Return a NULL pointer for the scheme, user information,
1843 		 * host, and port, and return the device as the path.
1844 		 */
1845 		*pathp = strdup(source);
1846 		if (*pathp == NULL) {
1847 			pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1848 			    errno, "malloc");
1849 			return (-1);
1850 		}
1851 		return (0);
1852 	}
1853 
1854 	/*
1855 	 * XXX - check whether the purported scheme could be a scheme?
1856 	 */
1857 
1858 	/*
1859 	 * OK, this looks like a URL.
1860 	 * Get the scheme.
1861 	 */
1862 	scheme_len = colonp - source;
1863 	scheme = malloc(scheme_len + 1);
1864 	if (scheme == NULL) {
1865 		pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1866 		    errno, "malloc");
1867 		return (-1);
1868 	}
1869 	memcpy(scheme, source, scheme_len);
1870 	scheme[scheme_len] = '\0';
1871 
1872 	/*
1873 	 * Treat file: specially - take everything after file:// as
1874 	 * the pathname.
1875 	 */
1876 	if (pcapint_strcasecmp(scheme, "file") == 0) {
1877 		*pathp = strdup(colonp + 3);
1878 		if (*pathp == NULL) {
1879 			pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1880 			    errno, "malloc");
1881 			free(scheme);
1882 			return (-1);
1883 		}
1884 		*schemep = scheme;
1885 		return (0);
1886 	}
1887 
1888 	/*
1889 	 * The WinPcap documentation says you can specify a local
1890 	 * interface with "rpcap://{device}"; we special-case
1891 	 * that here.  If the scheme is "rpcap", and there are
1892 	 * no slashes past the "//", we just return the device.
1893 	 *
1894 	 * XXX - %-escaping?
1895 	 */
1896 	if ((pcapint_strcasecmp(scheme, "rpcap") == 0 ||
1897 	    pcapint_strcasecmp(scheme, "rpcaps") == 0) &&
1898 	    strchr(colonp + 3, '/') == NULL) {
1899 		/*
1900 		 * Local device.
1901 		 *
1902 		 * Return a NULL pointer for the scheme, user information,
1903 		 * host, and port, and return the device as the path.
1904 		 */
1905 		free(scheme);
1906 		*pathp = strdup(colonp + 3);
1907 		if (*pathp == NULL) {
1908 			pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1909 			    errno, "malloc");
1910 			return (-1);
1911 		}
1912 		return (0);
1913 	}
1914 
1915 	/*
1916 	 * OK, now start parsing the authority.
1917 	 * Get token, terminated with / or terminated at the end of
1918 	 * the string.
1919 	 */
1920 	authority_len = strcspn(colonp + 3, "/");
1921 	authority = get_substring(colonp + 3, authority_len, ebuf);
1922 	if (authority == NULL) {
1923 		/*
1924 		 * Error.
1925 		 */
1926 		free(scheme);
1927 		return (-1);
1928 	}
1929 	endp = colonp + 3 + authority_len;
1930 
1931 	/*
1932 	 * Now carve the authority field into its components.
1933 	 */
1934 	parsep = authority;
1935 
1936 	/*
1937 	 * Is there a userinfo field?
1938 	 */
1939 	atsignp = strchr(parsep, '@');
1940 	if (atsignp != NULL) {
1941 		/*
1942 		 * Yes.
1943 		 */
1944 		size_t userinfo_len;
1945 
1946 		userinfo_len = atsignp - parsep;
1947 		userinfo = get_substring(parsep, userinfo_len, ebuf);
1948 		if (userinfo == NULL) {
1949 			/*
1950 			 * Error.
1951 			 */
1952 			free(authority);
1953 			free(scheme);
1954 			return (-1);
1955 		}
1956 		parsep = atsignp + 1;
1957 	} else {
1958 		/*
1959 		 * No.
1960 		 */
1961 		userinfo = NULL;
1962 	}
1963 
1964 	/*
1965 	 * Is there a host field?
1966 	 */
1967 	if (*parsep == '\0') {
1968 		/*
1969 		 * No; there's no host field or port field.
1970 		 */
1971 		host = NULL;
1972 		port = NULL;
1973 	} else {
1974 		/*
1975 		 * Yes.
1976 		 */
1977 		size_t host_len;
1978 
1979 		/*
1980 		 * Is it an IP-literal?
1981 		 */
1982 		if (*parsep == '[') {
1983 			/*
1984 			 * Yes.
1985 			 * Treat everything up to the closing square
1986 			 * bracket as the IP-Literal; we don't worry
1987 			 * about whether it's a valid IPv6address or
1988 			 * IPvFuture (or an IPv4address, for that
1989 			 * matter, just in case we get handed a
1990 			 * URL with an IPv4 IP-Literal, of the sort
1991 			 * that pcap_createsrcstr() used to generate,
1992 			 * and that pcap_parsesrcstr(), in the original
1993 			 * WinPcap code, accepted).
1994 			 */
1995 			bracketp = strchr(parsep, ']');
1996 			if (bracketp == NULL) {
1997 				/*
1998 				 * There's no closing square bracket.
1999 				 */
2000 				snprintf(ebuf, PCAP_ERRBUF_SIZE,
2001 				    "IP-literal in URL doesn't end with ]");
2002 				free(userinfo);
2003 				free(authority);
2004 				free(scheme);
2005 				return (-1);
2006 			}
2007 			if (*(bracketp + 1) != '\0' &&
2008 			    *(bracketp + 1) != ':') {
2009 				/*
2010 				 * There's extra crud after the
2011 				 * closing square bracket.
2012 				 */
2013 				snprintf(ebuf, PCAP_ERRBUF_SIZE,
2014 				    "Extra text after IP-literal in URL");
2015 				free(userinfo);
2016 				free(authority);
2017 				free(scheme);
2018 				return (-1);
2019 			}
2020 			host_len = (bracketp - 1) - parsep;
2021 			host = get_substring(parsep + 1, host_len, ebuf);
2022 			if (host == NULL) {
2023 				/*
2024 				 * Error.
2025 				 */
2026 				free(userinfo);
2027 				free(authority);
2028 				free(scheme);
2029 				return (-1);
2030 			}
2031 			parsep = bracketp + 1;
2032 		} else {
2033 			/*
2034 			 * No.
2035 			 * Treat everything up to a : or the end of
2036 			 * the string as the host.
2037 			 */
2038 			host_len = strcspn(parsep, ":");
2039 			host = get_substring(parsep, host_len, ebuf);
2040 			if (host == NULL) {
2041 				/*
2042 				 * Error.
2043 				 */
2044 				free(userinfo);
2045 				free(authority);
2046 				free(scheme);
2047 				return (-1);
2048 			}
2049 			parsep = parsep + host_len;
2050 		}
2051 
2052 		/*
2053 		 * Is there a port field?
2054 		 */
2055 		if (*parsep == ':') {
2056 			/*
2057 			 * Yes.  It's the rest of the authority field.
2058 			 */
2059 			size_t port_len;
2060 
2061 			parsep++;
2062 			port_len = strlen(parsep);
2063 			port = get_substring(parsep, port_len, ebuf);
2064 			if (port == NULL) {
2065 				/*
2066 				 * Error.
2067 				 */
2068 				free(host);
2069 				free(userinfo);
2070 				free(authority);
2071 				free(scheme);
2072 				return (-1);
2073 			}
2074 		} else {
2075 			/*
2076 			 * No.
2077 			 */
2078 			port = NULL;
2079 		}
2080 	}
2081 	free(authority);
2082 
2083 	/*
2084 	 * Everything else is the path.  Strip off the leading /.
2085 	 */
2086 	if (*endp == '\0')
2087 		path = strdup("");
2088 	else
2089 		path = strdup(endp + 1);
2090 	if (path == NULL) {
2091 		pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
2092 		    errno, "malloc");
2093 		free(port);
2094 		free(host);
2095 		free(userinfo);
2096 		free(scheme);
2097 		return (-1);
2098 	}
2099 	*schemep = scheme;
2100 	*userinfop = userinfo;
2101 	*hostp = host;
2102 	*portp = port;
2103 	*pathp = path;
2104 	return (0);
2105 }
2106 
2107 int
2108 pcapint_createsrcstr_ex(char *source, int type, const char *host, const char *port,
2109     const char *name, unsigned char uses_ssl, char *errbuf)
2110 {
2111 	switch (type) {
2112 
2113 	case PCAP_SRC_FILE:
2114 		pcapint_strlcpy(source, PCAP_SRC_FILE_STRING, PCAP_BUF_SIZE);
2115 		if (name != NULL && *name != '\0') {
2116 			pcapint_strlcat(source, name, PCAP_BUF_SIZE);
2117 			return (0);
2118 		} else {
2119 			snprintf(errbuf, PCAP_ERRBUF_SIZE,
2120 			    "The file name cannot be NULL.");
2121 			return (-1);
2122 		}
2123 
2124 	case PCAP_SRC_IFREMOTE:
2125 		pcapint_strlcpy(source,
2126 		    (uses_ssl ? "rpcaps://" : PCAP_SRC_IF_STRING),
2127 		    PCAP_BUF_SIZE);
2128 		if (host != NULL && *host != '\0') {
2129 			if (strchr(host, ':') != NULL) {
2130 				/*
2131 				 * The host name contains a colon, so it's
2132 				 * probably an IPv6 address, and needs to
2133 				 * be included in square brackets.
2134 				 */
2135 				pcapint_strlcat(source, "[", PCAP_BUF_SIZE);
2136 				pcapint_strlcat(source, host, PCAP_BUF_SIZE);
2137 				pcapint_strlcat(source, "]", PCAP_BUF_SIZE);
2138 			} else
2139 				pcapint_strlcat(source, host, PCAP_BUF_SIZE);
2140 
2141 			if (port != NULL && *port != '\0') {
2142 				pcapint_strlcat(source, ":", PCAP_BUF_SIZE);
2143 				pcapint_strlcat(source, port, PCAP_BUF_SIZE);
2144 			}
2145 
2146 			pcapint_strlcat(source, "/", PCAP_BUF_SIZE);
2147 		} else {
2148 			snprintf(errbuf, PCAP_ERRBUF_SIZE,
2149 			    "The host name cannot be NULL.");
2150 			return (-1);
2151 		}
2152 
2153 		if (name != NULL && *name != '\0')
2154 			pcapint_strlcat(source, name, PCAP_BUF_SIZE);
2155 
2156 		return (0);
2157 
2158 	case PCAP_SRC_IFLOCAL:
2159 		pcapint_strlcpy(source, PCAP_SRC_IF_STRING, PCAP_BUF_SIZE);
2160 
2161 		if (name != NULL && *name != '\0')
2162 			pcapint_strlcat(source, name, PCAP_BUF_SIZE);
2163 
2164 		return (0);
2165 
2166 	default:
2167 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
2168 		    "The interface type is not valid.");
2169 		return (-1);
2170 	}
2171 }
2172 
2173 
2174 int
2175 pcap_createsrcstr(char *source, int type, const char *host, const char *port,
2176     const char *name, char *errbuf)
2177 {
2178 	return (pcapint_createsrcstr_ex(source, type, host, port, name, 0, errbuf));
2179 }
2180 
2181 int
2182 pcapint_parsesrcstr_ex(const char *source, int *type, char *host, char *port,
2183     char *name, unsigned char *uses_ssl, char *errbuf)
2184 {
2185 	char *scheme, *tmpuserinfo, *tmphost, *tmpport, *tmppath;
2186 
2187 	/* Initialization stuff */
2188 	if (host)
2189 		*host = '\0';
2190 	if (port)
2191 		*port = '\0';
2192 	if (name)
2193 		*name = '\0';
2194 	if (uses_ssl)
2195 		*uses_ssl = 0;
2196 
2197 	/* Parse the source string */
2198 	if (pcap_parse_source(source, &scheme, &tmpuserinfo, &tmphost,
2199 	    &tmpport, &tmppath, errbuf) == -1) {
2200 		/*
2201 		 * Fail.
2202 		 */
2203 		return (-1);
2204 	}
2205 
2206 	if (scheme == NULL) {
2207 		/*
2208 		 * Local device.
2209 		 */
2210 		if (name && tmppath)
2211 			pcapint_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2212 		if (type)
2213 			*type = PCAP_SRC_IFLOCAL;
2214 		free(tmppath);
2215 		free(tmpport);
2216 		free(tmphost);
2217 		free(tmpuserinfo);
2218 		return (0);
2219 	}
2220 
2221 	int is_rpcap = 0;
2222 	if (strcmp(scheme, "rpcaps") == 0) {
2223 		is_rpcap = 1;
2224 		if (uses_ssl) *uses_ssl = 1;
2225 	} else if (strcmp(scheme, "rpcap") == 0) {
2226 		is_rpcap = 1;
2227 	}
2228 
2229 	if (is_rpcap) {
2230 		/*
2231 		 * rpcap[s]://
2232 		 *
2233 		 * pcap_parse_source() has already handled the case of
2234 		 * rpcap[s]://device
2235 		 */
2236 		if (host && tmphost) {
2237 			if (tmpuserinfo)
2238 				snprintf(host, PCAP_BUF_SIZE, "%s@%s",
2239 				    tmpuserinfo, tmphost);
2240 			else
2241 				pcapint_strlcpy(host, tmphost, PCAP_BUF_SIZE);
2242 		}
2243 		if (port && tmpport)
2244 			pcapint_strlcpy(port, tmpport, PCAP_BUF_SIZE);
2245 		if (name && tmppath)
2246 			pcapint_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2247 		if (type)
2248 			*type = PCAP_SRC_IFREMOTE;
2249 		free(tmppath);
2250 		free(tmpport);
2251 		free(tmphost);
2252 		free(tmpuserinfo);
2253 		free(scheme);
2254 		return (0);
2255 	}
2256 
2257 	if (strcmp(scheme, "file") == 0) {
2258 		/*
2259 		 * file://
2260 		 */
2261 		if (name && tmppath)
2262 			pcapint_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2263 		if (type)
2264 			*type = PCAP_SRC_FILE;
2265 		free(tmppath);
2266 		free(tmpport);
2267 		free(tmphost);
2268 		free(tmpuserinfo);
2269 		free(scheme);
2270 		return (0);
2271 	}
2272 
2273 	/*
2274 	 * Neither rpcap: nor file:; just treat the entire string
2275 	 * as a local device.
2276 	 */
2277 	if (name)
2278 		pcapint_strlcpy(name, source, PCAP_BUF_SIZE);
2279 	if (type)
2280 		*type = PCAP_SRC_IFLOCAL;
2281 	free(tmppath);
2282 	free(tmpport);
2283 	free(tmphost);
2284 	free(tmpuserinfo);
2285 	free(scheme);
2286 	return (0);
2287 }
2288 
2289 int
2290 pcap_parsesrcstr(const char *source, int *type, char *host, char *port,
2291     char *name, char *errbuf)
2292 {
2293 	return (pcapint_parsesrcstr_ex(source, type, host, port, name, NULL, errbuf));
2294 }
2295 #endif
2296 
2297 pcap_t *
2298 pcap_create(const char *device, char *errbuf)
2299 {
2300 	size_t i;
2301 	int is_theirs;
2302 	pcap_t *p;
2303 	char *device_str;
2304 
2305 	/*
2306 	 * A null device name is equivalent to the "any" device -
2307 	 * which might not be supported on this platform, but
2308 	 * this means that you'll get a "not supported" error
2309 	 * rather than, say, a crash when we try to dereference
2310 	 * the null pointer.
2311 	 */
2312 	if (device == NULL)
2313 		device_str = strdup("any");
2314 	else {
2315 #ifdef _WIN32
2316 		/*
2317 		 * On Windows, for backwards compatibility reasons,
2318 		 * pcap_lookupdev() returns a pointer to a sequence of
2319 		 * pairs of UTF-16LE device names and local code page
2320 		 * description strings.
2321 		 *
2322 		 * This means that if a program uses pcap_lookupdev()
2323 		 * to get a default device, and hands that to an API
2324 		 * that opens devices, we'll get handed a UTF-16LE
2325 		 * string, not a string in the local code page.
2326 		 *
2327 		 * To work around that, we check whether the string
2328 		 * looks as if it might be a UTF-16LE string and, if
2329 		 * so, convert it back to the local code page's
2330 		 * extended ASCII.
2331 		 *
2332 		 * We disable that check in "new API" mode, because:
2333 		 *
2334 		 *   1) You *cannot* reliably detect whether a
2335 		 *   string is UTF-16LE or not; "a" could either
2336 		 *   be a one-character ASCII string or the first
2337 		 *   character of a UTF-16LE string.
2338 		 *
2339 		 *   2) Doing that test can run past the end of
2340 		 *   the string, if it's a 1-character ASCII
2341 		 *   string
2342 		 *
2343 		 * This particular version of this heuristic dates
2344 		 * back to WinPcap 4.1.1; PacketOpenAdapter() does
2345 		 * uses the same heuristic, with the exact same
2346 		 * vulnerability.
2347 		 *
2348 		 * That's why we disable this in "new API" mode.
2349 		 * We keep it around in legacy mode for backwards
2350 		 * compatibility.
2351 		 */
2352 		if (!pcapint_new_api && device[0] != '\0' && device[1] == '\0') {
2353 			size_t length;
2354 
2355 			length = wcslen((wchar_t *)device);
2356 			device_str = (char *)malloc(length + 1);
2357 			if (device_str == NULL) {
2358 				pcapint_fmt_errmsg_for_errno(errbuf,
2359 				    PCAP_ERRBUF_SIZE, errno,
2360 				    "malloc");
2361 				return (NULL);
2362 			}
2363 
2364 			snprintf(device_str, length + 1, "%ws",
2365 			    (const wchar_t *)device);
2366 		} else
2367 #endif
2368 			device_str = strdup(device);
2369 	}
2370 	if (device_str == NULL) {
2371 		pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2372 		    errno, "malloc");
2373 		return (NULL);
2374 	}
2375 
2376 	/*
2377 	 * Try each of the non-local-network-interface capture
2378 	 * source types until we find one that works for this
2379 	 * device or run out of types.
2380 	 */
2381 	for (i = 0; capture_source_types[i].create_op != NULL; i++) {
2382 		is_theirs = 0;
2383 		p = capture_source_types[i].create_op(device_str, errbuf,
2384 		    &is_theirs);
2385 		if (is_theirs) {
2386 			/*
2387 			 * The device name refers to a device of the
2388 			 * type in question; either it succeeded,
2389 			 * in which case p refers to a pcap_t to
2390 			 * later activate for the device, or it
2391 			 * failed, in which case p is null and we
2392 			 * should return that to report the failure
2393 			 * to create.
2394 			 */
2395 			if (p == NULL) {
2396 				/*
2397 				 * We assume the caller filled in errbuf.
2398 				 */
2399 				free(device_str);
2400 				return (NULL);
2401 			}
2402 			p->opt.device = device_str;
2403 			return (p);
2404 		}
2405 	}
2406 
2407 	/*
2408 	 * OK, try it as a regular network interface.
2409 	 */
2410 	p = pcapint_create_interface(device_str, errbuf);
2411 	if (p == NULL) {
2412 		/*
2413 		 * We assume the caller filled in errbuf.
2414 		 */
2415 		free(device_str);
2416 		return (NULL);
2417 	}
2418 	p->opt.device = device_str;
2419 	return (p);
2420 }
2421 
2422 /*
2423  * Set nonblocking mode on an unactivated pcap_t; this sets a flag
2424  * checked by pcap_activate(), which sets the mode after calling
2425  * the activate routine.
2426  */
2427 static int
2428 pcap_setnonblock_unactivated(pcap_t *p, int nonblock)
2429 {
2430 	p->opt.nonblock = nonblock;
2431 	return (0);
2432 }
2433 
2434 static void
2435 initialize_ops(pcap_t *p)
2436 {
2437 	/*
2438 	 * Set operation pointers for operations that only work on
2439 	 * an activated pcap_t to point to a routine that returns
2440 	 * a "this isn't activated" error.
2441 	 */
2442 	p->read_op = pcap_read_not_initialized;
2443 	p->inject_op = pcap_inject_not_initialized;
2444 	p->setfilter_op = pcap_setfilter_not_initialized;
2445 	p->setdirection_op = pcap_setdirection_not_initialized;
2446 	p->set_datalink_op = pcap_set_datalink_not_initialized;
2447 	p->getnonblock_op = pcap_getnonblock_not_initialized;
2448 	p->stats_op = pcap_stats_not_initialized;
2449 #ifdef _WIN32
2450 	p->stats_ex_op = pcap_stats_ex_not_initialized;
2451 	p->setbuff_op = pcap_setbuff_not_initialized;
2452 	p->setmode_op = pcap_setmode_not_initialized;
2453 	p->setmintocopy_op = pcap_setmintocopy_not_initialized;
2454 	p->getevent_op = pcap_getevent_not_initialized;
2455 	p->oid_get_request_op = pcap_oid_get_request_not_initialized;
2456 	p->oid_set_request_op = pcap_oid_set_request_not_initialized;
2457 	p->sendqueue_transmit_op = pcap_sendqueue_transmit_not_initialized;
2458 	p->setuserbuffer_op = pcap_setuserbuffer_not_initialized;
2459 	p->live_dump_op = pcap_live_dump_not_initialized;
2460 	p->live_dump_ended_op = pcap_live_dump_ended_not_initialized;
2461 	p->get_airpcap_handle_op = pcap_get_airpcap_handle_not_initialized;
2462 #endif
2463 
2464 	/*
2465 	 * Default cleanup operation - implementations can override
2466 	 * this, but should call pcapint_cleanup_live_common() after
2467 	 * doing their own additional cleanup.
2468 	 */
2469 	p->cleanup_op = pcapint_cleanup_live_common;
2470 
2471 	/*
2472 	 * In most cases, the standard one-shot callback can
2473 	 * be used for pcap_next()/pcap_next_ex().
2474 	 */
2475 	p->oneshot_callback = pcapint_oneshot;
2476 
2477 	/*
2478 	 * Default breakloop operation - implementations can override
2479 	 * this, but should call pcapint_breakloop_common() before doing
2480 	 * their own logic.
2481 	 */
2482 	p->breakloop_op = pcapint_breakloop_common;
2483 }
2484 
2485 static pcap_t *
2486 pcap_alloc_pcap_t(char *ebuf, size_t total_size, size_t private_offset)
2487 {
2488 	char *chunk;
2489 	pcap_t *p;
2490 
2491 	/*
2492 	 * total_size is the size of a structure containing a pcap_t
2493 	 * followed by a private structure.
2494 	 */
2495 	chunk = calloc(total_size, 1);
2496 	if (chunk == NULL) {
2497 		pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
2498 		    errno, "malloc");
2499 		return (NULL);
2500 	}
2501 
2502 	/*
2503 	 * Get a pointer to the pcap_t at the beginning.
2504 	 */
2505 	p = (pcap_t *)chunk;
2506 
2507 #ifdef _WIN32
2508 	p->handle = INVALID_HANDLE_VALUE;	/* not opened yet */
2509 #else /* _WIN32 */
2510 	p->fd = -1;	/* not opened yet */
2511 #ifndef MSDOS
2512 	p->selectable_fd = -1;
2513 	p->required_select_timeout = NULL;
2514 #endif /* MSDOS */
2515 #endif /* _WIN32 */
2516 
2517 	/*
2518 	 * private_offset is the offset, in bytes, of the private
2519 	 * data from the beginning of the structure.
2520 	 *
2521 	 * Set the pointer to the private data; that's private_offset
2522 	 * bytes past the pcap_t.
2523 	 */
2524 	p->priv = (void *)(chunk + private_offset);
2525 
2526 	return (p);
2527 }
2528 
2529 pcap_t *
2530 pcapint_create_common(char *ebuf, size_t total_size, size_t private_offset)
2531 {
2532 	pcap_t *p;
2533 
2534 	p = pcap_alloc_pcap_t(ebuf, total_size, private_offset);
2535 	if (p == NULL)
2536 		return (NULL);
2537 
2538 	/*
2539 	 * Default to "can't set rfmon mode"; if it's supported by
2540 	 * a platform, the create routine that called us can set
2541 	 * the op to its routine to check whether a particular
2542 	 * device supports it.
2543 	 */
2544 	p->can_set_rfmon_op = pcap_cant_set_rfmon;
2545 
2546 	/*
2547 	 * If pcap_setnonblock() is called on a not-yet-activated
2548 	 * pcap_t, default to setting a flag and turning
2549 	 * on non-blocking mode when activated.
2550 	 */
2551 	p->setnonblock_op = pcap_setnonblock_unactivated;
2552 
2553 	initialize_ops(p);
2554 
2555 	/* put in some defaults*/
2556 	p->snapshot = 0;		/* max packet size unspecified */
2557 	p->opt.timeout = 0;		/* no timeout specified */
2558 	p->opt.buffer_size = 0;		/* use the platform's default */
2559 	p->opt.promisc = 0;
2560 	p->opt.rfmon = 0;
2561 	p->opt.immediate = 0;
2562 	p->opt.tstamp_type = -1;	/* default to not setting time stamp type */
2563 	p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
2564 	/*
2565 	 * Platform-dependent options.
2566 	 */
2567 #ifdef __linux__
2568 	p->opt.protocol = 0;
2569 #endif
2570 #ifdef _WIN32
2571 	p->opt.nocapture_local = 0;
2572 #endif
2573 
2574 	/*
2575 	 * Start out with no BPF code generation flags set.
2576 	 */
2577 	p->bpf_codegen_flags = 0;
2578 
2579 	return (p);
2580 }
2581 
2582 int
2583 pcapint_check_activated(pcap_t *p)
2584 {
2585 	if (p->activated) {
2586 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't perform "
2587 			" operation on activated capture");
2588 		return (-1);
2589 	}
2590 	return (0);
2591 }
2592 
2593 int
2594 pcap_set_snaplen(pcap_t *p, int snaplen)
2595 {
2596 	if (pcapint_check_activated(p))
2597 		return (PCAP_ERROR_ACTIVATED);
2598 	p->snapshot = snaplen;
2599 	return (0);
2600 }
2601 
2602 int
2603 pcap_set_promisc(pcap_t *p, int promisc)
2604 {
2605 	if (pcapint_check_activated(p))
2606 		return (PCAP_ERROR_ACTIVATED);
2607 	p->opt.promisc = promisc;
2608 	return (0);
2609 }
2610 
2611 int
2612 pcap_set_rfmon(pcap_t *p, int rfmon)
2613 {
2614 	if (pcapint_check_activated(p))
2615 		return (PCAP_ERROR_ACTIVATED);
2616 	p->opt.rfmon = rfmon;
2617 	return (0);
2618 }
2619 
2620 int
2621 pcap_set_timeout(pcap_t *p, int timeout_ms)
2622 {
2623 	if (pcapint_check_activated(p))
2624 		return (PCAP_ERROR_ACTIVATED);
2625 	p->opt.timeout = timeout_ms;
2626 	return (0);
2627 }
2628 
2629 int
2630 pcap_set_tstamp_type(pcap_t *p, int tstamp_type)
2631 {
2632 	int i;
2633 
2634 	if (pcapint_check_activated(p))
2635 		return (PCAP_ERROR_ACTIVATED);
2636 
2637 	/*
2638 	 * The argument should have been u_int, but that's too late
2639 	 * to change now - it's an API.
2640 	 */
2641 	if (tstamp_type < 0)
2642 		return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
2643 
2644 	/*
2645 	 * If p->tstamp_type_count is 0, we only support PCAP_TSTAMP_HOST;
2646 	 * the default time stamp type is PCAP_TSTAMP_HOST.
2647 	 */
2648 	if (p->tstamp_type_count == 0) {
2649 		if (tstamp_type == PCAP_TSTAMP_HOST) {
2650 			p->opt.tstamp_type = tstamp_type;
2651 			return (0);
2652 		}
2653 	} else {
2654 		/*
2655 		 * Check whether we claim to support this type of time stamp.
2656 		 */
2657 		for (i = 0; i < p->tstamp_type_count; i++) {
2658 			if (p->tstamp_type_list[i] == (u_int)tstamp_type) {
2659 				/*
2660 				 * Yes.
2661 				 */
2662 				p->opt.tstamp_type = tstamp_type;
2663 				return (0);
2664 			}
2665 		}
2666 	}
2667 
2668 	/*
2669 	 * We don't support this type of time stamp.
2670 	 */
2671 	return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
2672 }
2673 
2674 int
2675 pcap_set_immediate_mode(pcap_t *p, int immediate)
2676 {
2677 	if (pcapint_check_activated(p))
2678 		return (PCAP_ERROR_ACTIVATED);
2679 	p->opt.immediate = immediate;
2680 	return (0);
2681 }
2682 
2683 int
2684 pcap_set_buffer_size(pcap_t *p, int buffer_size)
2685 {
2686 	if (pcapint_check_activated(p))
2687 		return (PCAP_ERROR_ACTIVATED);
2688 	if (buffer_size <= 0) {
2689 		/*
2690 		 * Silently ignore invalid values.
2691 		 */
2692 		return (0);
2693 	}
2694 	p->opt.buffer_size = buffer_size;
2695 	return (0);
2696 }
2697 
2698 int
2699 pcap_set_tstamp_precision(pcap_t *p, int tstamp_precision)
2700 {
2701 	int i;
2702 
2703 	if (pcapint_check_activated(p))
2704 		return (PCAP_ERROR_ACTIVATED);
2705 
2706 	/*
2707 	 * The argument should have been u_int, but that's too late
2708 	 * to change now - it's an API.
2709 	 */
2710 	if (tstamp_precision < 0)
2711 		return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
2712 
2713 	/*
2714 	 * If p->tstamp_precision_count is 0, we only support setting
2715 	 * the time stamp precision to microsecond precision; every
2716 	 * pcap module *MUST* support microsecond precision, even if
2717 	 * it does so by converting the native precision to
2718 	 * microseconds.
2719 	 */
2720 	if (p->tstamp_precision_count == 0) {
2721 		if (tstamp_precision == PCAP_TSTAMP_PRECISION_MICRO) {
2722 			p->opt.tstamp_precision = tstamp_precision;
2723 			return (0);
2724 		}
2725 	} else {
2726 		/*
2727 		 * Check whether we claim to support this precision of
2728 		 * time stamp.
2729 		 */
2730 		for (i = 0; i < p->tstamp_precision_count; i++) {
2731 			if (p->tstamp_precision_list[i] == (u_int)tstamp_precision) {
2732 				/*
2733 				 * Yes.
2734 				 */
2735 				p->opt.tstamp_precision = tstamp_precision;
2736 				return (0);
2737 			}
2738 		}
2739 	}
2740 
2741 	/*
2742 	 * We don't support this time stamp precision.
2743 	 */
2744 	return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
2745 }
2746 
2747 int
2748 pcap_get_tstamp_precision(pcap_t *p)
2749 {
2750         return (p->opt.tstamp_precision);
2751 }
2752 
2753 int
2754 pcap_activate(pcap_t *p)
2755 {
2756 	int status;
2757 
2758 	/*
2759 	 * Catch attempts to re-activate an already-activated
2760 	 * pcap_t; this should, for example, catch code that
2761 	 * calls pcap_open_live() followed by pcap_activate(),
2762 	 * as some code that showed up in a Stack Exchange
2763 	 * question did.
2764 	 */
2765 	if (pcapint_check_activated(p))
2766 		return (PCAP_ERROR_ACTIVATED);
2767 	status = p->activate_op(p);
2768 	if (status >= 0) {
2769 		/*
2770 		 * If somebody requested non-blocking mode before
2771 		 * calling pcap_activate(), turn it on now.
2772 		 */
2773 		if (p->opt.nonblock) {
2774 			status = p->setnonblock_op(p, 1);
2775 			if (status < 0) {
2776 				/*
2777 				 * Failed.  Undo everything done by
2778 				 * the activate operation.
2779 				 */
2780 				p->cleanup_op(p);
2781 				initialize_ops(p);
2782 				return (status);
2783 			}
2784 		}
2785 		p->activated = 1;
2786 	} else {
2787 		if (p->errbuf[0] == '\0') {
2788 			/*
2789 			 * No error message supplied by the activate routine;
2790 			 * for the benefit of programs that don't specially
2791 			 * handle errors other than PCAP_ERROR, return the
2792 			 * error message corresponding to the status.
2793 			 */
2794 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
2795 			    pcap_statustostr(status));
2796 		}
2797 
2798 		/*
2799 		 * Undo any operation pointer setting, etc. done by
2800 		 * the activate operation.
2801 		 */
2802 		initialize_ops(p);
2803 	}
2804 	return (status);
2805 }
2806 
2807 pcap_t *
2808 pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf)
2809 {
2810 	pcap_t *p;
2811 	int status;
2812 #ifdef ENABLE_REMOTE
2813 	char host[PCAP_BUF_SIZE + 1];
2814 	char port[PCAP_BUF_SIZE + 1];
2815 	char name[PCAP_BUF_SIZE + 1];
2816 	int srctype;
2817 
2818 	/*
2819 	 * A null device name is equivalent to the "any" device -
2820 	 * which might not be supported on this platform, but
2821 	 * this means that you'll get a "not supported" error
2822 	 * rather than, say, a crash when we try to dereference
2823 	 * the null pointer.
2824 	 */
2825 	if (device == NULL)
2826 		device = "any";
2827 
2828 	/*
2829 	 * Retrofit - we have to make older applications compatible with
2830 	 * remote capture.
2831 	 * So we're calling pcap_open_remote() from here; this is a very
2832 	 * dirty hack.
2833 	 * Obviously, we cannot exploit all the new features; for instance,
2834 	 * we cannot send authentication, we cannot use a UDP data connection,
2835 	 * and so on.
2836 	 */
2837 	if (pcap_parsesrcstr(device, &srctype, host, port, name, errbuf))
2838 		return (NULL);
2839 
2840 	if (srctype == PCAP_SRC_IFREMOTE) {
2841 		/*
2842 		 * Although we already have host, port and iface, we prefer
2843 		 * to pass only 'device' to pcap_open_rpcap(), so that it has
2844 		 * to call pcap_parsesrcstr() again.
2845 		 * This is less optimized, but much clearer.
2846 		 */
2847 		return (pcap_open_rpcap(device, snaplen,
2848 		    promisc ? PCAP_OPENFLAG_PROMISCUOUS : 0, to_ms,
2849 		    NULL, errbuf));
2850 	}
2851 	if (srctype == PCAP_SRC_FILE) {
2852 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown URL scheme \"file\"");
2853 		return (NULL);
2854 	}
2855 	if (srctype == PCAP_SRC_IFLOCAL) {
2856 		/*
2857 		 * If it starts with rpcap://, that refers to a local device
2858 		 * (no host part in the URL). Remove the rpcap://, and
2859 		 * fall through to the regular open path.
2860 		 */
2861 		if (strncmp(device, PCAP_SRC_IF_STRING, strlen(PCAP_SRC_IF_STRING)) == 0) {
2862 			size_t len = strlen(device) - strlen(PCAP_SRC_IF_STRING) + 1;
2863 
2864 			if (len > 0)
2865 				device += strlen(PCAP_SRC_IF_STRING);
2866 		}
2867 	}
2868 #endif	/* ENABLE_REMOTE */
2869 
2870 	p = pcap_create(device, errbuf);
2871 	if (p == NULL)
2872 		return (NULL);
2873 	status = pcap_set_snaplen(p, snaplen);
2874 	if (status < 0)
2875 		goto fail;
2876 	status = pcap_set_promisc(p, promisc);
2877 	if (status < 0)
2878 		goto fail;
2879 	status = pcap_set_timeout(p, to_ms);
2880 	if (status < 0)
2881 		goto fail;
2882 	/*
2883 	 * Mark this as opened with pcap_open_live(), so that, for
2884 	 * example, we show the full list of DLT_ values, rather
2885 	 * than just the ones that are compatible with capturing
2886 	 * when not in monitor mode.  That allows existing applications
2887 	 * to work the way they used to work, but allows new applications
2888 	 * that know about the new open API to, for example, find out the
2889 	 * DLT_ values that they can select without changing whether
2890 	 * the adapter is in monitor mode or not.
2891 	 */
2892 	p->oldstyle = 1;
2893 	status = pcap_activate(p);
2894 	if (status < 0)
2895 		goto fail;
2896 	return (p);
2897 fail:
2898 	if (status == PCAP_ERROR) {
2899 		/*
2900 		 * Another buffer is a bit cumbersome, but it avoids
2901 		 * -Wformat-truncation.
2902 		 */
2903 		char trimbuf[PCAP_ERRBUF_SIZE - 5]; /* 2 bytes shorter */
2904 
2905 		pcapint_strlcpy(trimbuf, p->errbuf, sizeof(trimbuf));
2906 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %.*s", device,
2907 		    PCAP_ERRBUF_SIZE - 3, trimbuf);
2908 	} else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
2909 	    status == PCAP_ERROR_PERM_DENIED ||
2910 	    status == PCAP_ERROR_PROMISC_PERM_DENIED) {
2911 		/*
2912 		 * Only show the additional message if it's not
2913 		 * empty.
2914 		 */
2915 		if (p->errbuf[0] != '\0') {
2916 			/*
2917 			 * Idem.
2918 			 */
2919 			char trimbuf[PCAP_ERRBUF_SIZE - 8]; /* 2 bytes shorter */
2920 
2921 			pcapint_strlcpy(trimbuf, p->errbuf, sizeof(trimbuf));
2922 			snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%.*s)",
2923 			    device, pcap_statustostr(status),
2924 			    PCAP_ERRBUF_SIZE - 6, trimbuf);
2925 		} else {
2926 			snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s",
2927 			    device, pcap_statustostr(status));
2928 		}
2929 	} else {
2930 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", device,
2931 		    pcap_statustostr(status));
2932 	}
2933 	pcap_close(p);
2934 	return (NULL);
2935 }
2936 
2937 pcap_t *
2938 pcapint_open_offline_common(char *ebuf, size_t total_size, size_t private_offset)
2939 {
2940 	pcap_t *p;
2941 
2942 	p = pcap_alloc_pcap_t(ebuf, total_size, private_offset);
2943 	if (p == NULL)
2944 		return (NULL);
2945 
2946 	p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
2947 
2948 	return (p);
2949 }
2950 
2951 int
2952 pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
2953 {
2954 	return (p->read_op(p, cnt, callback, user));
2955 }
2956 
2957 int
2958 pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
2959 {
2960 	register int n;
2961 
2962 	for (;;) {
2963 		if (p->rfile != NULL) {
2964 			/*
2965 			 * 0 means EOF, so don't loop if we get 0.
2966 			 */
2967 			n = pcapint_offline_read(p, cnt, callback, user);
2968 		} else {
2969 			/*
2970 			 * XXX keep reading until we get something
2971 			 * (or an error occurs)
2972 			 */
2973 			do {
2974 				n = p->read_op(p, cnt, callback, user);
2975 			} while (n == 0);
2976 		}
2977 		if (n <= 0)
2978 			return (n);
2979 		if (!PACKET_COUNT_IS_UNLIMITED(cnt)) {
2980 			cnt -= n;
2981 			if (cnt <= 0)
2982 				return (0);
2983 		}
2984 	}
2985 }
2986 
2987 /*
2988  * Force the loop in "pcap_read()" or "pcap_read_offline()" to terminate.
2989  */
2990 void
2991 pcap_breakloop(pcap_t *p)
2992 {
2993 	p->breakloop_op(p);
2994 }
2995 
2996 int
2997 pcap_datalink(pcap_t *p)
2998 {
2999 	if (!p->activated)
3000 		return (PCAP_ERROR_NOT_ACTIVATED);
3001 	return (p->linktype);
3002 }
3003 
3004 int
3005 pcap_datalink_ext(pcap_t *p)
3006 {
3007 	if (!p->activated)
3008 		return (PCAP_ERROR_NOT_ACTIVATED);
3009 	return (p->linktype_ext);
3010 }
3011 
3012 int
3013 pcap_list_datalinks(pcap_t *p, int **dlt_buffer)
3014 {
3015 	if (!p->activated)
3016 		return (PCAP_ERROR_NOT_ACTIVATED);
3017 	if (p->dlt_count == 0) {
3018 		/*
3019 		 * We couldn't fetch the list of DLTs, which means
3020 		 * this platform doesn't support changing the
3021 		 * DLT for an interface.  Return a list of DLTs
3022 		 * containing only the DLT this device supports.
3023 		 */
3024 		*dlt_buffer = (int*)malloc(sizeof(**dlt_buffer));
3025 		if (*dlt_buffer == NULL) {
3026 			pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3027 			    errno, "malloc");
3028 			return (PCAP_ERROR);
3029 		}
3030 		**dlt_buffer = p->linktype;
3031 		return (1);
3032 	} else {
3033 		*dlt_buffer = (int*)calloc(p->dlt_count, sizeof(**dlt_buffer));
3034 		if (*dlt_buffer == NULL) {
3035 			pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3036 			    errno, "malloc");
3037 			return (PCAP_ERROR);
3038 		}
3039 		(void)memcpy(*dlt_buffer, p->dlt_list,
3040 		    sizeof(**dlt_buffer) * p->dlt_count);
3041 		return (p->dlt_count);
3042 	}
3043 }
3044 
3045 /*
3046  * In Windows, you might have a library built with one version of the
3047  * C runtime library and an application built with another version of
3048  * the C runtime library, which means that the library might use one
3049  * version of malloc() and free() and the application might use another
3050  * version of malloc() and free().  If so, that means something
3051  * allocated by the library cannot be freed by the application, so we
3052  * need to have a pcap_free_datalinks() routine to free up the list
3053  * allocated by pcap_list_datalinks(), even though it's just a wrapper
3054  * around free().
3055  */
3056 void
3057 pcap_free_datalinks(int *dlt_list)
3058 {
3059 	free(dlt_list);
3060 }
3061 
3062 int
3063 pcap_set_datalink(pcap_t *p, int dlt)
3064 {
3065 	int i;
3066 	const char *dlt_name;
3067 
3068 	if (dlt < 0)
3069 		goto unsupported;
3070 
3071 	if (p->dlt_count == 0 || p->set_datalink_op == NULL) {
3072 		/*
3073 		 * We couldn't fetch the list of DLTs, or we don't
3074 		 * have a "set datalink" operation, which means
3075 		 * this platform doesn't support changing the
3076 		 * DLT for an interface.  Check whether the new
3077 		 * DLT is the one this interface supports.
3078 		 */
3079 		if (p->linktype != dlt)
3080 			goto unsupported;
3081 
3082 		/*
3083 		 * It is, so there's nothing we need to do here.
3084 		 */
3085 		return (0);
3086 	}
3087 	for (i = 0; i < p->dlt_count; i++)
3088 		if (p->dlt_list[i] == (u_int)dlt)
3089 			break;
3090 	if (i >= p->dlt_count)
3091 		goto unsupported;
3092 	if (p->dlt_count == 2 && p->dlt_list[0] == DLT_EN10MB &&
3093 	    dlt == DLT_DOCSIS) {
3094 		/*
3095 		 * This is presumably an Ethernet device, as the first
3096 		 * link-layer type it offers is DLT_EN10MB, and the only
3097 		 * other type it offers is DLT_DOCSIS.  That means that
3098 		 * we can't tell the driver to supply DOCSIS link-layer
3099 		 * headers - we're just pretending that's what we're
3100 		 * getting, as, presumably, we're capturing on a dedicated
3101 		 * link to a Cisco Cable Modem Termination System, and
3102 		 * it's putting raw DOCSIS frames on the wire inside low-level
3103 		 * Ethernet framing.
3104 		 */
3105 		p->linktype = dlt;
3106 		return (0);
3107 	}
3108 	if (p->set_datalink_op(p, dlt) == -1)
3109 		return (-1);
3110 	p->linktype = dlt;
3111 	return (0);
3112 
3113 unsupported:
3114 	dlt_name = pcap_datalink_val_to_name(dlt);
3115 	if (dlt_name != NULL) {
3116 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
3117 		    "%s is not one of the DLTs supported by this device",
3118 		    dlt_name);
3119 	} else {
3120 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
3121 		    "DLT %d is not one of the DLTs supported by this device",
3122 		    dlt);
3123 	}
3124 	return (-1);
3125 }
3126 
3127 /*
3128  * This array is designed for mapping upper and lower case letter
3129  * together for a case independent comparison.  The mappings are
3130  * based upon ascii character sequences.
3131  */
3132 static const u_char charmap[] = {
3133 	(u_char)'\000', (u_char)'\001', (u_char)'\002', (u_char)'\003',
3134 	(u_char)'\004', (u_char)'\005', (u_char)'\006', (u_char)'\007',
3135 	(u_char)'\010', (u_char)'\011', (u_char)'\012', (u_char)'\013',
3136 	(u_char)'\014', (u_char)'\015', (u_char)'\016', (u_char)'\017',
3137 	(u_char)'\020', (u_char)'\021', (u_char)'\022', (u_char)'\023',
3138 	(u_char)'\024', (u_char)'\025', (u_char)'\026', (u_char)'\027',
3139 	(u_char)'\030', (u_char)'\031', (u_char)'\032', (u_char)'\033',
3140 	(u_char)'\034', (u_char)'\035', (u_char)'\036', (u_char)'\037',
3141 	(u_char)'\040', (u_char)'\041', (u_char)'\042', (u_char)'\043',
3142 	(u_char)'\044', (u_char)'\045', (u_char)'\046', (u_char)'\047',
3143 	(u_char)'\050', (u_char)'\051', (u_char)'\052', (u_char)'\053',
3144 	(u_char)'\054', (u_char)'\055', (u_char)'\056', (u_char)'\057',
3145 	(u_char)'\060', (u_char)'\061', (u_char)'\062', (u_char)'\063',
3146 	(u_char)'\064', (u_char)'\065', (u_char)'\066', (u_char)'\067',
3147 	(u_char)'\070', (u_char)'\071', (u_char)'\072', (u_char)'\073',
3148 	(u_char)'\074', (u_char)'\075', (u_char)'\076', (u_char)'\077',
3149 	(u_char)'\100', (u_char)'\141', (u_char)'\142', (u_char)'\143',
3150 	(u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
3151 	(u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
3152 	(u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
3153 	(u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
3154 	(u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
3155 	(u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\133',
3156 	(u_char)'\134', (u_char)'\135', (u_char)'\136', (u_char)'\137',
3157 	(u_char)'\140', (u_char)'\141', (u_char)'\142', (u_char)'\143',
3158 	(u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
3159 	(u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
3160 	(u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
3161 	(u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
3162 	(u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
3163 	(u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\173',
3164 	(u_char)'\174', (u_char)'\175', (u_char)'\176', (u_char)'\177',
3165 	(u_char)'\200', (u_char)'\201', (u_char)'\202', (u_char)'\203',
3166 	(u_char)'\204', (u_char)'\205', (u_char)'\206', (u_char)'\207',
3167 	(u_char)'\210', (u_char)'\211', (u_char)'\212', (u_char)'\213',
3168 	(u_char)'\214', (u_char)'\215', (u_char)'\216', (u_char)'\217',
3169 	(u_char)'\220', (u_char)'\221', (u_char)'\222', (u_char)'\223',
3170 	(u_char)'\224', (u_char)'\225', (u_char)'\226', (u_char)'\227',
3171 	(u_char)'\230', (u_char)'\231', (u_char)'\232', (u_char)'\233',
3172 	(u_char)'\234', (u_char)'\235', (u_char)'\236', (u_char)'\237',
3173 	(u_char)'\240', (u_char)'\241', (u_char)'\242', (u_char)'\243',
3174 	(u_char)'\244', (u_char)'\245', (u_char)'\246', (u_char)'\247',
3175 	(u_char)'\250', (u_char)'\251', (u_char)'\252', (u_char)'\253',
3176 	(u_char)'\254', (u_char)'\255', (u_char)'\256', (u_char)'\257',
3177 	(u_char)'\260', (u_char)'\261', (u_char)'\262', (u_char)'\263',
3178 	(u_char)'\264', (u_char)'\265', (u_char)'\266', (u_char)'\267',
3179 	(u_char)'\270', (u_char)'\271', (u_char)'\272', (u_char)'\273',
3180 	(u_char)'\274', (u_char)'\275', (u_char)'\276', (u_char)'\277',
3181 	(u_char)'\300', (u_char)'\341', (u_char)'\342', (u_char)'\343',
3182 	(u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
3183 	(u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
3184 	(u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
3185 	(u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
3186 	(u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
3187 	(u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\333',
3188 	(u_char)'\334', (u_char)'\335', (u_char)'\336', (u_char)'\337',
3189 	(u_char)'\340', (u_char)'\341', (u_char)'\342', (u_char)'\343',
3190 	(u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
3191 	(u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
3192 	(u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
3193 	(u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
3194 	(u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
3195 	(u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\373',
3196 	(u_char)'\374', (u_char)'\375', (u_char)'\376', (u_char)'\377',
3197 };
3198 
3199 int
3200 pcapint_strcasecmp(const char *s1, const char *s2)
3201 {
3202 	register const u_char	*cm = charmap,
3203 				*us1 = (const u_char *)s1,
3204 				*us2 = (const u_char *)s2;
3205 
3206 	while (cm[*us1] == cm[*us2++])
3207 		if (*us1++ == '\0')
3208 			return(0);
3209 	return (cm[*us1] - cm[*--us2]);
3210 }
3211 
3212 struct dlt_choice {
3213 	const char *name;
3214 	const char *description;
3215 	int	dlt;
3216 };
3217 
3218 #define DLT_CHOICE(code, description) { #code, description, DLT_ ## code }
3219 #define DLT_CHOICE_SENTINEL { NULL, NULL, 0 }
3220 
3221 static struct dlt_choice dlt_choices[] = {
3222 	DLT_CHOICE(NULL, "BSD loopback"),
3223 	DLT_CHOICE(EN10MB, "Ethernet"),
3224 	DLT_CHOICE(IEEE802, "Token ring"),
3225 	DLT_CHOICE(ARCNET, "BSD ARCNET"),
3226 	DLT_CHOICE(SLIP, "SLIP"),
3227 	DLT_CHOICE(PPP, "PPP"),
3228 	DLT_CHOICE(FDDI, "FDDI"),
3229 	DLT_CHOICE(ATM_RFC1483, "RFC 1483 LLC-encapsulated ATM"),
3230 	DLT_CHOICE(RAW, "Raw IP"),
3231 	DLT_CHOICE(SLIP_BSDOS, "BSD/OS SLIP"),
3232 	DLT_CHOICE(PPP_BSDOS, "BSD/OS PPP"),
3233 	DLT_CHOICE(ATM_CLIP, "Linux Classical IP over ATM"),
3234 	DLT_CHOICE(PPP_SERIAL, "PPP over serial"),
3235 	DLT_CHOICE(PPP_ETHER, "PPPoE"),
3236 	DLT_CHOICE(SYMANTEC_FIREWALL, "Symantec Firewall"),
3237 	DLT_CHOICE(C_HDLC, "Cisco HDLC"),
3238 	DLT_CHOICE(IEEE802_11, "802.11"),
3239 	DLT_CHOICE(FRELAY, "Frame Relay"),
3240 	DLT_CHOICE(LOOP, "OpenBSD loopback"),
3241 	DLT_CHOICE(ENC, "OpenBSD encapsulated IP"),
3242 	DLT_CHOICE(LINUX_SLL, "Linux cooked v1"),
3243 	DLT_CHOICE(LTALK, "Localtalk"),
3244 	DLT_CHOICE(PFLOG, "OpenBSD pflog file"),
3245 	DLT_CHOICE(PFSYNC, "Packet filter state syncing"),
3246 	DLT_CHOICE(PRISM_HEADER, "802.11 plus Prism header"),
3247 	DLT_CHOICE(IP_OVER_FC, "RFC 2625 IP-over-Fibre Channel"),
3248 	DLT_CHOICE(SUNATM, "Sun raw ATM"),
3249 	DLT_CHOICE(IEEE802_11_RADIO, "802.11 plus radiotap header"),
3250 	DLT_CHOICE(ARCNET_LINUX, "Linux ARCNET"),
3251 	DLT_CHOICE(JUNIPER_MLPPP, "Juniper Multi-Link PPP"),
3252 	DLT_CHOICE(JUNIPER_MLFR, "Juniper Multi-Link Frame Relay"),
3253 	DLT_CHOICE(JUNIPER_ES, "Juniper Encryption Services PIC"),
3254 	DLT_CHOICE(JUNIPER_GGSN, "Juniper GGSN PIC"),
3255 	DLT_CHOICE(JUNIPER_MFR, "Juniper FRF.16 Frame Relay"),
3256 	DLT_CHOICE(JUNIPER_ATM2, "Juniper ATM2 PIC"),
3257 	DLT_CHOICE(JUNIPER_SERVICES, "Juniper Advanced Services PIC"),
3258 	DLT_CHOICE(JUNIPER_ATM1, "Juniper ATM1 PIC"),
3259 	DLT_CHOICE(APPLE_IP_OVER_IEEE1394, "Apple IP-over-IEEE 1394"),
3260 	DLT_CHOICE(MTP2_WITH_PHDR, "SS7 MTP2 with Pseudo-header"),
3261 	DLT_CHOICE(MTP2, "SS7 MTP2"),
3262 	DLT_CHOICE(MTP3, "SS7 MTP3"),
3263 	DLT_CHOICE(SCCP, "SS7 SCCP"),
3264 	DLT_CHOICE(DOCSIS, "DOCSIS"),
3265 	DLT_CHOICE(LINUX_IRDA, "Linux IrDA"),
3266 	DLT_CHOICE(IEEE802_11_RADIO_AVS, "802.11 plus AVS radio information header"),
3267 	DLT_CHOICE(JUNIPER_MONITOR, "Juniper Passive Monitor PIC"),
3268 	DLT_CHOICE(BACNET_MS_TP, "BACnet MS/TP"),
3269 	DLT_CHOICE(PPP_PPPD, "PPP for pppd, with direction flag"),
3270 	DLT_CHOICE(JUNIPER_PPPOE, "Juniper PPPoE"),
3271 	DLT_CHOICE(JUNIPER_PPPOE_ATM, "Juniper PPPoE/ATM"),
3272 	DLT_CHOICE(GPRS_LLC, "GPRS LLC"),
3273 	DLT_CHOICE(GPF_T, "GPF-T"),
3274 	DLT_CHOICE(GPF_F, "GPF-F"),
3275 	DLT_CHOICE(JUNIPER_PIC_PEER, "Juniper PIC Peer"),
3276 	DLT_CHOICE(ERF_ETH, "Ethernet with Endace ERF header"),
3277 	DLT_CHOICE(ERF_POS, "Packet-over-SONET with Endace ERF header"),
3278 	DLT_CHOICE(LINUX_LAPD, "Linux vISDN LAPD"),
3279 	DLT_CHOICE(JUNIPER_ETHER, "Juniper Ethernet"),
3280 	DLT_CHOICE(JUNIPER_PPP, "Juniper PPP"),
3281 	DLT_CHOICE(JUNIPER_FRELAY, "Juniper Frame Relay"),
3282 	DLT_CHOICE(JUNIPER_CHDLC, "Juniper C-HDLC"),
3283 	DLT_CHOICE(MFR, "FRF.16 Frame Relay"),
3284 	DLT_CHOICE(JUNIPER_VP, "Juniper Voice PIC"),
3285 	DLT_CHOICE(A429, "Arinc 429"),
3286 	DLT_CHOICE(A653_ICM, "Arinc 653 Interpartition Communication"),
3287 	DLT_CHOICE(USB_FREEBSD, "USB with FreeBSD header"),
3288 	DLT_CHOICE(BLUETOOTH_HCI_H4, "Bluetooth HCI UART transport layer"),
3289 	DLT_CHOICE(IEEE802_16_MAC_CPS, "IEEE 802.16 MAC Common Part Sublayer"),
3290 	DLT_CHOICE(USB_LINUX, "USB with Linux header"),
3291 	DLT_CHOICE(CAN20B, "Controller Area Network (CAN) v. 2.0B"),
3292 	DLT_CHOICE(IEEE802_15_4_LINUX, "IEEE 802.15.4 with Linux padding"),
3293 	DLT_CHOICE(PPI, "Per-Packet Information"),
3294 	DLT_CHOICE(IEEE802_16_MAC_CPS_RADIO, "IEEE 802.16 MAC Common Part Sublayer plus radiotap header"),
3295 	DLT_CHOICE(JUNIPER_ISM, "Juniper Integrated Service Module"),
3296 	DLT_CHOICE(IEEE802_15_4, "IEEE 802.15.4 with FCS"),
3297 	DLT_CHOICE(SITA, "SITA pseudo-header"),
3298 	DLT_CHOICE(ERF, "Endace ERF header"),
3299 	DLT_CHOICE(RAIF1, "Ethernet with u10 Networks pseudo-header"),
3300 	DLT_CHOICE(IPMB_KONTRON, "IPMB with Kontron pseudo-header"),
3301 	DLT_CHOICE(JUNIPER_ST, "Juniper Secure Tunnel"),
3302 	DLT_CHOICE(BLUETOOTH_HCI_H4_WITH_PHDR, "Bluetooth HCI UART transport layer plus pseudo-header"),
3303 	DLT_CHOICE(AX25_KISS, "AX.25 with KISS header"),
3304 	DLT_CHOICE(IPMB_LINUX, "IPMB with Linux/Pigeon Point pseudo-header"),
3305 	DLT_CHOICE(IEEE802_15_4_NONASK_PHY, "IEEE 802.15.4 with non-ASK PHY data"),
3306 	DLT_CHOICE(MPLS, "MPLS with label as link-layer header"),
3307 	DLT_CHOICE(LINUX_EVDEV, "Linux evdev events"),
3308 	DLT_CHOICE(USB_LINUX_MMAPPED, "USB with padded Linux header"),
3309 	DLT_CHOICE(DECT, "DECT"),
3310 	DLT_CHOICE(AOS, "AOS Space Data Link protocol"),
3311 	DLT_CHOICE(WIHART, "WirelessHART"),
3312 	DLT_CHOICE(FC_2, "Fibre Channel FC-2"),
3313 	DLT_CHOICE(FC_2_WITH_FRAME_DELIMS, "Fibre Channel FC-2 with frame delimiters"),
3314 	DLT_CHOICE(IPNET, "Solaris ipnet"),
3315 	DLT_CHOICE(CAN_SOCKETCAN, "CAN-bus with SocketCAN headers"),
3316 	DLT_CHOICE(IPV4, "Raw IPv4"),
3317 	DLT_CHOICE(IPV6, "Raw IPv6"),
3318 	DLT_CHOICE(IEEE802_15_4_NOFCS, "IEEE 802.15.4 without FCS"),
3319 	DLT_CHOICE(DBUS, "D-Bus"),
3320 	DLT_CHOICE(JUNIPER_VS, "Juniper Virtual Server"),
3321 	DLT_CHOICE(JUNIPER_SRX_E2E, "Juniper SRX E2E"),
3322 	DLT_CHOICE(JUNIPER_FIBRECHANNEL, "Juniper Fibre Channel"),
3323 	DLT_CHOICE(DVB_CI, "DVB-CI"),
3324 	DLT_CHOICE(MUX27010, "MUX27010"),
3325 	DLT_CHOICE(STANAG_5066_D_PDU, "STANAG 5066 D_PDUs"),
3326 	DLT_CHOICE(JUNIPER_ATM_CEMIC, "Juniper ATM CEMIC"),
3327 	DLT_CHOICE(NFLOG, "Linux netfilter log messages"),
3328 	DLT_CHOICE(NETANALYZER, "Ethernet with Hilscher netANALYZER pseudo-header"),
3329 	DLT_CHOICE(NETANALYZER_TRANSPARENT, "Ethernet with Hilscher netANALYZER pseudo-header and with preamble and SFD"),
3330 	DLT_CHOICE(IPOIB, "RFC 4391 IP-over-Infiniband"),
3331 	DLT_CHOICE(MPEG_2_TS, "MPEG-2 transport stream"),
3332 	DLT_CHOICE(NG40, "ng40 protocol tester Iub/Iur"),
3333 	DLT_CHOICE(NFC_LLCP, "NFC LLCP PDUs with pseudo-header"),
3334 	DLT_CHOICE(INFINIBAND, "InfiniBand"),
3335 	DLT_CHOICE(SCTP, "SCTP"),
3336 	DLT_CHOICE(USBPCAP, "USB with USBPcap header"),
3337 	DLT_CHOICE(RTAC_SERIAL, "Schweitzer Engineering Laboratories RTAC packets"),
3338 	DLT_CHOICE(BLUETOOTH_LE_LL, "Bluetooth Low Energy air interface"),
3339 	DLT_CHOICE(NETLINK, "Linux netlink"),
3340 	DLT_CHOICE(BLUETOOTH_LINUX_MONITOR, "Bluetooth Linux Monitor"),
3341 	DLT_CHOICE(BLUETOOTH_BREDR_BB, "Bluetooth Basic Rate/Enhanced Data Rate baseband packets"),
3342 	DLT_CHOICE(BLUETOOTH_LE_LL_WITH_PHDR, "Bluetooth Low Energy air interface with pseudo-header"),
3343 	DLT_CHOICE(PROFIBUS_DL, "PROFIBUS data link layer"),
3344 	DLT_CHOICE(PKTAP, "Apple DLT_PKTAP"),
3345 	DLT_CHOICE(EPON, "Ethernet with 802.3 Clause 65 EPON preamble"),
3346 	DLT_CHOICE(IPMI_HPM_2, "IPMI trace packets"),
3347 	DLT_CHOICE(ZWAVE_R1_R2, "Z-Wave RF profile R1 and R2 packets"),
3348 	DLT_CHOICE(ZWAVE_R3, "Z-Wave RF profile R3 packets"),
3349 	DLT_CHOICE(WATTSTOPPER_DLM, "WattStopper Digital Lighting Management (DLM) and Legrand Nitoo Open protocol"),
3350 	DLT_CHOICE(ISO_14443, "ISO 14443 messages"),
3351 	DLT_CHOICE(RDS, "IEC 62106 Radio Data System groups"),
3352 	DLT_CHOICE(USB_DARWIN, "USB with Darwin header"),
3353 	DLT_CHOICE(OPENFLOW, "OpenBSD DLT_OPENFLOW"),
3354 	DLT_CHOICE(SDLC, "IBM SDLC frames"),
3355 	DLT_CHOICE(TI_LLN_SNIFFER, "TI LLN sniffer frames"),
3356 	DLT_CHOICE(VSOCK, "Linux vsock"),
3357 	DLT_CHOICE(NORDIC_BLE, "Nordic Semiconductor Bluetooth LE sniffer frames"),
3358 	DLT_CHOICE(DOCSIS31_XRA31, "Excentis XRA-31 DOCSIS 3.1 RF sniffer frames"),
3359 	DLT_CHOICE(ETHERNET_MPACKET, "802.3br mPackets"),
3360 	DLT_CHOICE(DISPLAYPORT_AUX, "DisplayPort AUX channel monitoring data"),
3361 	DLT_CHOICE(LINUX_SLL2, "Linux cooked v2"),
3362 	DLT_CHOICE(OPENVIZSLA, "OpenVizsla USB"),
3363 	DLT_CHOICE(EBHSCR, "Elektrobit High Speed Capture and Replay (EBHSCR)"),
3364 	DLT_CHOICE(VPP_DISPATCH, "VPP graph dispatch tracer"),
3365 	DLT_CHOICE(DSA_TAG_BRCM, "Broadcom tag"),
3366 	DLT_CHOICE(DSA_TAG_BRCM_PREPEND, "Broadcom tag (prepended)"),
3367 	DLT_CHOICE(IEEE802_15_4_TAP, "IEEE 802.15.4 with pseudo-header"),
3368 	DLT_CHOICE(DSA_TAG_DSA, "Marvell DSA"),
3369 	DLT_CHOICE(DSA_TAG_EDSA, "Marvell EDSA"),
3370 	DLT_CHOICE(ELEE, "ELEE lawful intercept packets"),
3371 	DLT_CHOICE(Z_WAVE_SERIAL, "Z-Wave serial frames between host and chip"),
3372 	DLT_CHOICE(USB_2_0, "USB 2.0/1.1/1.0 as transmitted over the cable"),
3373 	DLT_CHOICE(ATSC_ALP, "ATSC Link-Layer Protocol packets"),
3374 	DLT_CHOICE_SENTINEL
3375 };
3376 
3377 int
3378 pcap_datalink_name_to_val(const char *name)
3379 {
3380 	int i;
3381 
3382 	for (i = 0; dlt_choices[i].name != NULL; i++) {
3383 		if (pcapint_strcasecmp(dlt_choices[i].name, name) == 0)
3384 			return (dlt_choices[i].dlt);
3385 	}
3386 	return (-1);
3387 }
3388 
3389 const char *
3390 pcap_datalink_val_to_name(int dlt)
3391 {
3392 	int i;
3393 
3394 	for (i = 0; dlt_choices[i].name != NULL; i++) {
3395 		if (dlt_choices[i].dlt == dlt)
3396 			return (dlt_choices[i].name);
3397 	}
3398 	return (NULL);
3399 }
3400 
3401 const char *
3402 pcap_datalink_val_to_description(int dlt)
3403 {
3404 	int i;
3405 
3406 	for (i = 0; dlt_choices[i].name != NULL; i++) {
3407 		if (dlt_choices[i].dlt == dlt)
3408 			return (dlt_choices[i].description);
3409 	}
3410 	return (NULL);
3411 }
3412 
3413 const char *
3414 pcap_datalink_val_to_description_or_dlt(int dlt)
3415 {
3416         static thread_local char unkbuf[40];
3417         const char *description;
3418 
3419         description = pcap_datalink_val_to_description(dlt);
3420         if (description != NULL) {
3421                 return description;
3422         } else {
3423                 (void)snprintf(unkbuf, sizeof(unkbuf), "DLT %d", dlt);
3424                 return unkbuf;
3425         }
3426 }
3427 
3428 struct tstamp_type_choice {
3429 	const char *name;
3430 	const char *description;
3431 	int	type;
3432 };
3433 
3434 static struct tstamp_type_choice tstamp_type_choices[] = {
3435 	{ "host", "Host", PCAP_TSTAMP_HOST },
3436 	{ "host_lowprec", "Host, low precision", PCAP_TSTAMP_HOST_LOWPREC },
3437 	{ "host_hiprec", "Host, high precision", PCAP_TSTAMP_HOST_HIPREC },
3438 	{ "adapter", "Adapter", PCAP_TSTAMP_ADAPTER },
3439 	{ "adapter_unsynced", "Adapter, not synced with system time", PCAP_TSTAMP_ADAPTER_UNSYNCED },
3440 	{ "host_hiprec_unsynced", "Host, high precision, not synced with system time", PCAP_TSTAMP_HOST_HIPREC_UNSYNCED },
3441 	{ NULL, NULL, 0 }
3442 };
3443 
3444 int
3445 pcap_tstamp_type_name_to_val(const char *name)
3446 {
3447 	int i;
3448 
3449 	for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3450 		if (pcapint_strcasecmp(tstamp_type_choices[i].name, name) == 0)
3451 			return (tstamp_type_choices[i].type);
3452 	}
3453 	return (PCAP_ERROR);
3454 }
3455 
3456 const char *
3457 pcap_tstamp_type_val_to_name(int tstamp_type)
3458 {
3459 	int i;
3460 
3461 	for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3462 		if (tstamp_type_choices[i].type == tstamp_type)
3463 			return (tstamp_type_choices[i].name);
3464 	}
3465 	return (NULL);
3466 }
3467 
3468 const char *
3469 pcap_tstamp_type_val_to_description(int tstamp_type)
3470 {
3471 	int i;
3472 
3473 	for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3474 		if (tstamp_type_choices[i].type == tstamp_type)
3475 			return (tstamp_type_choices[i].description);
3476 	}
3477 	return (NULL);
3478 }
3479 
3480 int
3481 pcap_snapshot(pcap_t *p)
3482 {
3483 	if (!p->activated)
3484 		return (PCAP_ERROR_NOT_ACTIVATED);
3485 	return (p->snapshot);
3486 }
3487 
3488 int
3489 pcap_is_swapped(pcap_t *p)
3490 {
3491 	if (!p->activated)
3492 		return (PCAP_ERROR_NOT_ACTIVATED);
3493 	return (p->swapped);
3494 }
3495 
3496 int
3497 pcap_major_version(pcap_t *p)
3498 {
3499 	if (!p->activated)
3500 		return (PCAP_ERROR_NOT_ACTIVATED);
3501 	return (p->version_major);
3502 }
3503 
3504 int
3505 pcap_minor_version(pcap_t *p)
3506 {
3507 	if (!p->activated)
3508 		return (PCAP_ERROR_NOT_ACTIVATED);
3509 	return (p->version_minor);
3510 }
3511 
3512 int
3513 pcap_bufsize(pcap_t *p)
3514 {
3515 	if (!p->activated)
3516 		return (PCAP_ERROR_NOT_ACTIVATED);
3517 	return (p->bufsize);
3518 }
3519 
3520 FILE *
3521 pcap_file(pcap_t *p)
3522 {
3523 	return (p->rfile);
3524 }
3525 
3526 #ifdef _WIN32
3527 int
3528 pcap_fileno(pcap_t *p)
3529 {
3530 	if (p->handle != INVALID_HANDLE_VALUE) {
3531 		/*
3532 		 * This is a bogus and now-deprecated API; we
3533 		 * squelch the narrowing warning for the cast
3534 		 * from HANDLE to intptr_t.  If Windows programmers
3535 		 * need to get at the HANDLE for a pcap_t, *if*
3536 		 * there is one, they should request such a
3537 		 * routine (and be prepared for it to return
3538 		 * INVALID_HANDLE_VALUE).
3539 		 */
3540 DIAG_OFF_NARROWING
3541 		return ((int)(intptr_t)p->handle);
3542 DIAG_ON_NARROWING
3543 	} else
3544 		return (PCAP_ERROR);
3545 }
3546 #else /* _WIN32 */
3547 int
3548 pcap_fileno(pcap_t *p)
3549 {
3550 	return (p->fd);
3551 }
3552 #endif /* _WIN32 */
3553 
3554 #if !defined(_WIN32) && !defined(MSDOS)
3555 int
3556 pcap_get_selectable_fd(pcap_t *p)
3557 {
3558 	return (p->selectable_fd);
3559 }
3560 
3561 const struct timeval *
3562 pcap_get_required_select_timeout(pcap_t *p)
3563 {
3564 	return (p->required_select_timeout);
3565 }
3566 #endif
3567 
3568 void
3569 pcap_perror(pcap_t *p, const char *prefix)
3570 {
3571 	fprintf(stderr, "%s: %s\n", prefix, p->errbuf);
3572 }
3573 
3574 char *
3575 pcap_geterr(pcap_t *p)
3576 {
3577 	return (p->errbuf);
3578 }
3579 
3580 int
3581 pcap_getnonblock(pcap_t *p, char *errbuf)
3582 {
3583 	int ret;
3584 
3585 	ret = p->getnonblock_op(p);
3586 	if (ret == -1) {
3587 		/*
3588 		 * The get nonblock operation sets p->errbuf; this
3589 		 * function *shouldn't* have had a separate errbuf
3590 		 * argument, as it didn't need one, but I goofed
3591 		 * when adding it.
3592 		 *
3593 		 * We copy the error message to errbuf, so callers
3594 		 * can find it in either place.
3595 		 */
3596 		pcapint_strlcpy(errbuf, p->errbuf, PCAP_ERRBUF_SIZE);
3597 	}
3598 	return (ret);
3599 }
3600 
3601 /*
3602  * Get the current non-blocking mode setting, under the assumption that
3603  * it's just the standard POSIX non-blocking flag.
3604  */
3605 #if !defined(_WIN32) && !defined(MSDOS)
3606 int
3607 pcapint_getnonblock_fd(pcap_t *p)
3608 {
3609 	int fdflags;
3610 
3611 	fdflags = fcntl(p->fd, F_GETFL, 0);
3612 	if (fdflags == -1) {
3613 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3614 		    errno, "F_GETFL");
3615 		return (-1);
3616 	}
3617 	if (fdflags & O_NONBLOCK)
3618 		return (1);
3619 	else
3620 		return (0);
3621 }
3622 #endif
3623 
3624 int
3625 pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)
3626 {
3627 	int ret;
3628 
3629 	ret = p->setnonblock_op(p, nonblock);
3630 	if (ret == -1) {
3631 		/*
3632 		 * The set nonblock operation sets p->errbuf; this
3633 		 * function *shouldn't* have had a separate errbuf
3634 		 * argument, as it didn't need one, but I goofed
3635 		 * when adding it.
3636 		 *
3637 		 * We copy the error message to errbuf, so callers
3638 		 * can find it in either place.
3639 		 */
3640 		pcapint_strlcpy(errbuf, p->errbuf, PCAP_ERRBUF_SIZE);
3641 	}
3642 	return (ret);
3643 }
3644 
3645 #if !defined(_WIN32) && !defined(MSDOS)
3646 /*
3647  * Set non-blocking mode, under the assumption that it's just the
3648  * standard POSIX non-blocking flag.  (This can be called by the
3649  * per-platform non-blocking-mode routine if that routine also
3650  * needs to do some additional work.)
3651  */
3652 int
3653 pcapint_setnonblock_fd(pcap_t *p, int nonblock)
3654 {
3655 	int fdflags;
3656 
3657 	fdflags = fcntl(p->fd, F_GETFL, 0);
3658 	if (fdflags == -1) {
3659 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3660 		    errno, "F_GETFL");
3661 		return (-1);
3662 	}
3663 	if (nonblock)
3664 		fdflags |= O_NONBLOCK;
3665 	else
3666 		fdflags &= ~O_NONBLOCK;
3667 	if (fcntl(p->fd, F_SETFL, fdflags) == -1) {
3668 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3669 		    errno, "F_SETFL");
3670 		return (-1);
3671 	}
3672 	return (0);
3673 }
3674 #endif
3675 
3676 /*
3677  * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
3678  */
3679 const char *
3680 pcap_statustostr(int errnum)
3681 {
3682 	static thread_local char ebuf[15+10+1];
3683 
3684 	switch (errnum) {
3685 
3686 	case PCAP_WARNING:
3687 		return("Generic warning");
3688 
3689 	case PCAP_WARNING_TSTAMP_TYPE_NOTSUP:
3690 		return ("That type of time stamp is not supported by that device");
3691 
3692 	case PCAP_WARNING_PROMISC_NOTSUP:
3693 		return ("That device doesn't support promiscuous mode");
3694 
3695 	case PCAP_ERROR:
3696 		return("Generic error");
3697 
3698 	case PCAP_ERROR_BREAK:
3699 		return("Loop terminated by pcap_breakloop");
3700 
3701 	case PCAP_ERROR_NOT_ACTIVATED:
3702 		return("The pcap_t has not been activated");
3703 
3704 	case PCAP_ERROR_ACTIVATED:
3705 		return ("The setting can't be changed after the pcap_t is activated");
3706 
3707 	case PCAP_ERROR_NO_SUCH_DEVICE:
3708 		return ("No such device exists");
3709 
3710 	case PCAP_ERROR_RFMON_NOTSUP:
3711 		return ("That device doesn't support monitor mode");
3712 
3713 	case PCAP_ERROR_NOT_RFMON:
3714 		return ("That operation is supported only in monitor mode");
3715 
3716 	case PCAP_ERROR_PERM_DENIED:
3717 		return ("You don't have permission to perform this capture on that device");
3718 
3719 	case PCAP_ERROR_IFACE_NOT_UP:
3720 		return ("That device is not up");
3721 
3722 	case PCAP_ERROR_CANTSET_TSTAMP_TYPE:
3723 		return ("That device doesn't support setting the time stamp type");
3724 
3725 	case PCAP_ERROR_PROMISC_PERM_DENIED:
3726 		return ("You don't have permission to capture in promiscuous mode on that device");
3727 
3728 	case PCAP_ERROR_TSTAMP_PRECISION_NOTSUP:
3729 		return ("That device doesn't support that time stamp precision");
3730 
3731 	case PCAP_ERROR_CAPTURE_NOTSUP:
3732 		return ("Packet capture is not supported on that device");
3733 	}
3734 	(void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
3735 	return(ebuf);
3736 }
3737 
3738 /*
3739  * A long time ago the purpose of this function was to hide the difference
3740  * between those Unix-like OSes that implemented strerror() and those that
3741  * didn't.  All the currently supported OSes implement strerror(), which is in
3742  * POSIX.1-2001, uniformly and that particular problem no longer exists.  But
3743  * now they implement a few incompatible thread-safe variants of strerror(),
3744  * and hiding that difference is the current purpose of this function.
3745  */
3746 const char *
3747 pcap_strerror(int errnum)
3748 {
3749 #ifdef _WIN32
3750 	static thread_local char errbuf[PCAP_ERRBUF_SIZE];
3751 	errno_t err = strerror_s(errbuf, PCAP_ERRBUF_SIZE, errnum);
3752 
3753 	if (err != 0) /* err = 0 if successful */
3754 		pcapint_strlcpy(errbuf, "strerror_s() error", PCAP_ERRBUF_SIZE);
3755 	return (errbuf);
3756 #elif defined(HAVE_GNU_STRERROR_R)
3757 	/*
3758 	 * We have a GNU-style strerror_r(), which is *not* guaranteed to
3759 	 * do anything to the buffer handed to it, and which returns a
3760 	 * pointer to the error string, which may or may not be in
3761 	 * the buffer.
3762 	 *
3763 	 * It is, however, guaranteed to succeed.
3764 	 *
3765 	 * At the time of this writing this applies to the following cases,
3766 	 * each of which allows to use either the GNU implementation or the
3767 	 * POSIX implementation, and this source tree defines _GNU_SOURCE to
3768 	 * use the GNU implementation:
3769 	 * - Hurd
3770 	 * - Linux with GNU libc
3771 	 * - Linux with uClibc-ng
3772 	 */
3773 	static thread_local char errbuf[PCAP_ERRBUF_SIZE];
3774 	return strerror_r(errnum, errbuf, PCAP_ERRBUF_SIZE);
3775 #elif defined(HAVE_POSIX_STRERROR_R)
3776 	/*
3777 	 * We have a POSIX-style strerror_r(), which is guaranteed to fill
3778 	 * in the buffer, but is not guaranteed to succeed.
3779 	 *
3780 	 * At the time of this writing this applies to the following cases:
3781 	 * - AIX 7
3782 	 * - FreeBSD
3783 	 * - Haiku
3784 	 * - HP-UX 11
3785 	 * - illumos
3786 	 * - Linux with musl libc
3787 	 * - macOS
3788 	 * - NetBSD
3789 	 * - OpenBSD
3790 	 * - Solaris 10 & 11
3791 	 */
3792 	static thread_local char errbuf[PCAP_ERRBUF_SIZE];
3793 	int err = strerror_r(errnum, errbuf, PCAP_ERRBUF_SIZE);
3794 	switch (err) {
3795 	case 0:
3796 		/* That worked. */
3797 		break;
3798 
3799 	case EINVAL:
3800 		/*
3801 		 * UNIX 03 says this isn't guaranteed to produce a
3802 		 * fallback error message.
3803 		 */
3804 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
3805 		         "Unknown error: %d", errnum);
3806 		break;
3807 	case ERANGE:
3808 		/*
3809 		 * UNIX 03 says this isn't guaranteed to produce a
3810 		 * fallback error message.
3811 		 */
3812 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
3813 		         "Message for error %d is too long", errnum);
3814 		break;
3815 	default:
3816 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
3817 		         "strerror_r(%d, ...) unexpectedly returned %d",
3818 		         errnum, err);
3819 	}
3820 	return errbuf;
3821 #else
3822 	/*
3823 	 * At the time of this writing every supported OS implements strerror()
3824 	 * and at least one thread-safe variant thereof, so this is a very
3825 	 * unlikely last-resort branch.  Particular implementations of strerror()
3826 	 * may be thread-safe, but this is neither required nor guaranteed.
3827 	 */
3828 	return (strerror(errnum));
3829 #endif /* _WIN32 */
3830 }
3831 
3832 int
3833 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
3834 {
3835 	return (p->setfilter_op(p, fp));
3836 }
3837 
3838 /*
3839  * Set direction flag, which controls whether we accept only incoming
3840  * packets, only outgoing packets, or both.
3841  * Note that, depending on the platform, some or all direction arguments
3842  * might not be supported.
3843  */
3844 int
3845 pcap_setdirection(pcap_t *p, pcap_direction_t d)
3846 {
3847 	if (p->setdirection_op == NULL) {
3848 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
3849 		    "Setting direction is not supported on this device");
3850 		return (-1);
3851 	} else {
3852 		switch (d) {
3853 
3854 		case PCAP_D_IN:
3855 		case PCAP_D_OUT:
3856 		case PCAP_D_INOUT:
3857 			/*
3858 			 * Valid direction.
3859 			 */
3860 			return (p->setdirection_op(p, d));
3861 
3862 		default:
3863 			/*
3864 			 * Invalid direction.
3865 			 */
3866 			snprintf(p->errbuf, sizeof(p->errbuf),
3867 			    "Invalid direction");
3868 			return (-1);
3869 		}
3870 	}
3871 }
3872 
3873 int
3874 pcap_stats(pcap_t *p, struct pcap_stat *ps)
3875 {
3876 	return (p->stats_op(p, ps));
3877 }
3878 
3879 #ifdef _WIN32
3880 struct pcap_stat *
3881 pcap_stats_ex(pcap_t *p, int *pcap_stat_size)
3882 {
3883 	return (p->stats_ex_op(p, pcap_stat_size));
3884 }
3885 
3886 int
3887 pcap_setbuff(pcap_t *p, int dim)
3888 {
3889 	return (p->setbuff_op(p, dim));
3890 }
3891 
3892 int
3893 pcap_setmode(pcap_t *p, int mode)
3894 {
3895 	return (p->setmode_op(p, mode));
3896 }
3897 
3898 int
3899 pcap_setmintocopy(pcap_t *p, int size)
3900 {
3901 	return (p->setmintocopy_op(p, size));
3902 }
3903 
3904 HANDLE
3905 pcap_getevent(pcap_t *p)
3906 {
3907 	return (p->getevent_op(p));
3908 }
3909 
3910 int
3911 pcap_oid_get_request(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
3912 {
3913 	return (p->oid_get_request_op(p, oid, data, lenp));
3914 }
3915 
3916 int
3917 pcap_oid_set_request(pcap_t *p, bpf_u_int32 oid, const void *data, size_t *lenp)
3918 {
3919 	return (p->oid_set_request_op(p, oid, data, lenp));
3920 }
3921 
3922 pcap_send_queue *
3923 pcap_sendqueue_alloc(u_int memsize)
3924 {
3925 	pcap_send_queue *tqueue;
3926 
3927 	/* Allocate the queue */
3928 	tqueue = (pcap_send_queue *)malloc(sizeof(pcap_send_queue));
3929 	if (tqueue == NULL){
3930 		return (NULL);
3931 	}
3932 
3933 	/* Allocate the buffer */
3934 	tqueue->buffer = (char *)malloc(memsize);
3935 	if (tqueue->buffer == NULL) {
3936 		free(tqueue);
3937 		return (NULL);
3938 	}
3939 
3940 	tqueue->maxlen = memsize;
3941 	tqueue->len = 0;
3942 
3943 	return (tqueue);
3944 }
3945 
3946 void
3947 pcap_sendqueue_destroy(pcap_send_queue *queue)
3948 {
3949 	free(queue->buffer);
3950 	free(queue);
3951 }
3952 
3953 int
3954 pcap_sendqueue_queue(pcap_send_queue *queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
3955 {
3956 	if (queue->len + sizeof(struct pcap_pkthdr) + pkt_header->caplen > queue->maxlen){
3957 		return (-1);
3958 	}
3959 
3960 	/* Copy the pcap_pkthdr header*/
3961 	memcpy(queue->buffer + queue->len, pkt_header, sizeof(struct pcap_pkthdr));
3962 	queue->len += sizeof(struct pcap_pkthdr);
3963 
3964 	/* copy the packet */
3965 	memcpy(queue->buffer + queue->len, pkt_data, pkt_header->caplen);
3966 	queue->len += pkt_header->caplen;
3967 
3968 	return (0);
3969 }
3970 
3971 u_int
3972 pcap_sendqueue_transmit(pcap_t *p, pcap_send_queue *queue, int sync)
3973 {
3974 	return (p->sendqueue_transmit_op(p, queue, sync));
3975 }
3976 
3977 int
3978 pcap_setuserbuffer(pcap_t *p, int size)
3979 {
3980 	return (p->setuserbuffer_op(p, size));
3981 }
3982 
3983 int
3984 pcap_live_dump(pcap_t *p, char *filename, int maxsize, int maxpacks)
3985 {
3986 	return (p->live_dump_op(p, filename, maxsize, maxpacks));
3987 }
3988 
3989 int
3990 pcap_live_dump_ended(pcap_t *p, int sync)
3991 {
3992 	return (p->live_dump_ended_op(p, sync));
3993 }
3994 
3995 PAirpcapHandle
3996 pcap_get_airpcap_handle(pcap_t *p)
3997 {
3998 	PAirpcapHandle handle;
3999 
4000 	handle = p->get_airpcap_handle_op(p);
4001 	if (handle == NULL) {
4002 		(void)snprintf(p->errbuf, sizeof(p->errbuf),
4003 		    "This isn't an AirPcap device");
4004 	}
4005 	return (handle);
4006 }
4007 #endif
4008 
4009 /*
4010  * On some platforms, we need to clean up promiscuous or monitor mode
4011  * when we close a device - and we want that to happen even if the
4012  * application just exits without explicitly closing devices.
4013  * On those platforms, we need to register a "close all the pcaps"
4014  * routine to be called when we exit, and need to maintain a list of
4015  * pcaps that need to be closed to clean up modes.
4016  *
4017  * XXX - not thread-safe.
4018  */
4019 
4020 /*
4021  * List of pcaps on which we've done something that needs to be
4022  * cleaned up.
4023  * If there are any such pcaps, we arrange to call "pcap_close_all()"
4024  * when we exit, and have it close all of them.
4025  */
4026 static struct pcap *pcaps_to_close;
4027 
4028 /*
4029  * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
4030  * be called on exit.
4031  */
4032 static int did_atexit;
4033 
4034 static void
4035 pcap_close_all(void)
4036 {
4037 	struct pcap *handle;
4038 
4039 	while ((handle = pcaps_to_close) != NULL) {
4040 		pcap_close(handle);
4041 
4042 		/*
4043 		 * If a pcap module adds a pcap_t to the "close all"
4044 		 * list by calling pcapint_add_to_pcaps_to_close(), it
4045 		 * must have a cleanup routine that removes it from the
4046 		 * list, by calling pcapint_remove_from_pcaps_to_close(),
4047 		 * and must make that cleanup routine the cleanup_op
4048 		 * for the pcap_t.
4049 		 *
4050 		 * That means that, after pcap_close() - which calls
4051 		 * the cleanup_op for the pcap_t - the pcap_t must
4052 		 * have been removed from the list, so pcaps_to_close
4053 		 * must not be equal to handle.
4054 		 *
4055 		 * We check for that, and abort if handle is still
4056 		 * at the head of the list, to prevent infinite loops.
4057 		 */
4058 		if (pcaps_to_close == handle)
4059 			abort();
4060 	}
4061 }
4062 
4063 int
4064 pcapint_do_addexit(pcap_t *p)
4065 {
4066 	/*
4067 	 * If we haven't already done so, arrange to have
4068 	 * "pcap_close_all()" called when we exit.
4069 	 */
4070 	if (!did_atexit) {
4071 		if (atexit(pcap_close_all) != 0) {
4072 			/*
4073 			 * "atexit()" failed; let our caller know.
4074 			 */
4075 			pcapint_strlcpy(p->errbuf, "atexit failed", PCAP_ERRBUF_SIZE);
4076 			return (0);
4077 		}
4078 		did_atexit = 1;
4079 	}
4080 	return (1);
4081 }
4082 
4083 void
4084 pcapint_add_to_pcaps_to_close(pcap_t *p)
4085 {
4086 	p->next = pcaps_to_close;
4087 	pcaps_to_close = p;
4088 }
4089 
4090 void
4091 pcapint_remove_from_pcaps_to_close(pcap_t *p)
4092 {
4093 	pcap_t *pc, *prevpc;
4094 
4095 	for (pc = pcaps_to_close, prevpc = NULL; pc != NULL;
4096 	    prevpc = pc, pc = pc->next) {
4097 		if (pc == p) {
4098 			/*
4099 			 * Found it.  Remove it from the list.
4100 			 */
4101 			if (prevpc == NULL) {
4102 				/*
4103 				 * It was at the head of the list.
4104 				 */
4105 				pcaps_to_close = pc->next;
4106 			} else {
4107 				/*
4108 				 * It was in the middle of the list.
4109 				 */
4110 				prevpc->next = pc->next;
4111 			}
4112 			break;
4113 		}
4114 	}
4115 }
4116 
4117 void
4118 pcapint_breakloop_common(pcap_t *p)
4119 {
4120 	p->break_loop = 1;
4121 }
4122 
4123 
4124 void
4125 pcapint_cleanup_live_common(pcap_t *p)
4126 {
4127 	if (p->opt.device != NULL) {
4128 		free(p->opt.device);
4129 		p->opt.device = NULL;
4130 	}
4131 	if (p->buffer != NULL) {
4132 		free(p->buffer);
4133 		p->buffer = NULL;
4134 	}
4135 	if (p->dlt_list != NULL) {
4136 		free(p->dlt_list);
4137 		p->dlt_list = NULL;
4138 		p->dlt_count = 0;
4139 	}
4140 	if (p->tstamp_type_list != NULL) {
4141 		free(p->tstamp_type_list);
4142 		p->tstamp_type_list = NULL;
4143 		p->tstamp_type_count = 0;
4144 	}
4145 	if (p->tstamp_precision_list != NULL) {
4146 		free(p->tstamp_precision_list);
4147 		p->tstamp_precision_list = NULL;
4148 		p->tstamp_precision_count = 0;
4149 	}
4150 	pcap_freecode(&p->fcode);
4151 #if !defined(_WIN32) && !defined(MSDOS)
4152 	if (p->fd >= 0) {
4153 		close(p->fd);
4154 		p->fd = -1;
4155 	}
4156 	p->selectable_fd = -1;
4157 #endif
4158 }
4159 
4160 /*
4161  * API compatible with WinPcap's "send a packet" routine - returns -1
4162  * on error, 0 otherwise.
4163  *
4164  * XXX - what if we get a short write?
4165  */
4166 int
4167 pcap_sendpacket(pcap_t *p, const u_char *buf, int size)
4168 {
4169 	if (size <= 0) {
4170 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4171 		    errno, "The number of bytes to be sent must be positive");
4172 		return (PCAP_ERROR);
4173 	}
4174 
4175 	if (p->inject_op(p, buf, size) == -1)
4176 		return (-1);
4177 	return (0);
4178 }
4179 
4180 /*
4181  * API compatible with OpenBSD's "send a packet" routine - returns -1 on
4182  * error, number of bytes written otherwise.
4183  */
4184 int
4185 pcap_inject(pcap_t *p, const void *buf, size_t size)
4186 {
4187 	/*
4188 	 * We return the number of bytes written, so the number of
4189 	 * bytes to write must fit in an int.
4190 	 */
4191 	if (size > INT_MAX) {
4192 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4193 		    errno, "More than %d bytes cannot be injected", INT_MAX);
4194 		return (PCAP_ERROR);
4195 	}
4196 
4197 	if (size == 0) {
4198 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4199 		    errno, "The number of bytes to be injected must not be zero");
4200 		return (PCAP_ERROR);
4201 	}
4202 
4203 	return (p->inject_op(p, buf, (int)size));
4204 }
4205 
4206 void
4207 pcap_close(pcap_t *p)
4208 {
4209 	p->cleanup_op(p);
4210 	free(p);
4211 }
4212 
4213 /*
4214  * Helpers for safely loading code at run time.
4215  * Currently Windows-only.
4216  */
4217 #ifdef _WIN32
4218 //
4219 // This wrapper around loadlibrary appends the system folder (usually
4220 // C:\Windows\System32) to the relative path of the DLL, so that the DLL
4221 // is always loaded from an absolute path (it's no longer possible to
4222 // load modules from the application folder).
4223 // This solves the DLL Hijacking issue discovered in August 2010:
4224 //
4225 // https://blog.rapid7.com/2010/08/23/exploiting-dll-hijacking-flaws/
4226 // https://blog.rapid7.com/2010/08/23/application-dll-load-hijacking/
4227 // (the purported Rapid7 blog post link in the first of those two links
4228 // is broken; the second of those links works.)
4229 //
4230 // If any links there are broken from all the content shuffling Rapid&
4231 // did, see archived versions of the posts at their original homes, at
4232 //
4233 // https://web.archive.org/web/20110122175058/http://blog.metasploit.com/2010/08/exploiting-dll-hijacking-flaws.html
4234 // https://web.archive.org/web/20100828112111/http://blog.rapid7.com/?p=5325
4235 //
4236 pcap_code_handle_t
4237 pcapint_load_code(const char *name)
4238 {
4239 	/*
4240 	 * XXX - should this work in UTF-16LE rather than in the local
4241 	 * ANSI code page?
4242 	 */
4243 	CHAR path[MAX_PATH];
4244 	CHAR fullFileName[MAX_PATH];
4245 	UINT res;
4246 	HMODULE hModule = NULL;
4247 
4248 	do
4249 	{
4250 		res = GetSystemDirectoryA(path, MAX_PATH);
4251 
4252 		if (res == 0) {
4253 			//
4254 			// some bad failure occurred;
4255 			//
4256 			break;
4257 		}
4258 
4259 		if (res > MAX_PATH) {
4260 			//
4261 			// the buffer was not big enough
4262 			//
4263 			SetLastError(ERROR_INSUFFICIENT_BUFFER);
4264 			break;
4265 		}
4266 
4267 		if (res + 1 + strlen(name) + 1 < MAX_PATH) {
4268 			memcpy(fullFileName, path, res * sizeof(TCHAR));
4269 			fullFileName[res] = '\\';
4270 			memcpy(&fullFileName[res + 1], name, (strlen(name) + 1) * sizeof(TCHAR));
4271 
4272 			hModule = LoadLibraryA(fullFileName);
4273 		} else
4274 			SetLastError(ERROR_INSUFFICIENT_BUFFER);
4275 
4276 	} while(FALSE);
4277 
4278 	return hModule;
4279 }
4280 
4281 pcap_funcptr_t
4282 pcapint_find_function(pcap_code_handle_t code, const char *func)
4283 {
4284 	return (GetProcAddress(code, func));
4285 }
4286 #endif
4287 
4288 /*
4289  * Given a BPF program, a pcap_pkthdr structure for a packet, and the raw
4290  * data for the packet, check whether the packet passes the filter.
4291  * Returns the return value of the filter program, which will be zero if
4292  * the packet doesn't pass and non-zero if the packet does pass.
4293  */
4294 int
4295 pcap_offline_filter(const struct bpf_program *fp, const struct pcap_pkthdr *h,
4296     const u_char *pkt)
4297 {
4298 	const struct bpf_insn *fcode = fp->bf_insns;
4299 
4300 	if (fcode != NULL)
4301 		return (pcapint_filter(fcode, pkt, h->len, h->caplen));
4302 	else
4303 		return (0);
4304 }
4305 
4306 static int
4307 pcap_can_set_rfmon_dead(pcap_t *p)
4308 {
4309 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4310 	    "Rfmon mode doesn't apply on a pcap_open_dead pcap_t");
4311 	return (PCAP_ERROR);
4312 }
4313 
4314 static int
4315 pcap_read_dead(pcap_t *p, int cnt _U_, pcap_handler callback _U_,
4316     u_char *user _U_)
4317 {
4318 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4319 	    "Packets aren't available from a pcap_open_dead pcap_t");
4320 	return (-1);
4321 }
4322 
4323 static void
4324 pcap_breakloop_dead(pcap_t *p _U_)
4325 {
4326 	/*
4327 	 * A "dead" pcap_t is just a placeholder to use in order to
4328 	 * compile a filter to BPF code or to open a savefile for
4329 	 * writing.  It doesn't support any operations, including
4330 	 * capturing or reading packets, so there will never be a
4331 	 * get-packets loop in progress to break out *of*.
4332 	 *
4333 	 * As such, this routine doesn't need to do anything.
4334 	 */
4335 }
4336 
4337 static int
4338 pcap_inject_dead(pcap_t *p, const void *buf _U_, int size _U_)
4339 {
4340 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4341 	    "Packets can't be sent on a pcap_open_dead pcap_t");
4342 	return (-1);
4343 }
4344 
4345 static int
4346 pcap_setfilter_dead(pcap_t *p, struct bpf_program *fp _U_)
4347 {
4348 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4349 	    "A filter cannot be set on a pcap_open_dead pcap_t");
4350 	return (-1);
4351 }
4352 
4353 static int
4354 pcap_setdirection_dead(pcap_t *p, pcap_direction_t d _U_)
4355 {
4356 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4357 	    "The packet direction cannot be set on a pcap_open_dead pcap_t");
4358 	return (-1);
4359 }
4360 
4361 static int
4362 pcap_set_datalink_dead(pcap_t *p, int dlt _U_)
4363 {
4364 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4365 	    "The link-layer header type cannot be set on a pcap_open_dead pcap_t");
4366 	return (-1);
4367 }
4368 
4369 static int
4370 pcap_getnonblock_dead(pcap_t *p)
4371 {
4372 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4373 	    "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4374 	return (-1);
4375 }
4376 
4377 static int
4378 pcap_setnonblock_dead(pcap_t *p, int nonblock _U_)
4379 {
4380 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4381 	    "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4382 	return (-1);
4383 }
4384 
4385 static int
4386 pcap_stats_dead(pcap_t *p, struct pcap_stat *ps _U_)
4387 {
4388 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4389 	    "Statistics aren't available from a pcap_open_dead pcap_t");
4390 	return (-1);
4391 }
4392 
4393 #ifdef _WIN32
4394 static struct pcap_stat *
4395 pcap_stats_ex_dead(pcap_t *p, int *pcap_stat_size _U_)
4396 {
4397 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4398 	    "Statistics aren't available from a pcap_open_dead pcap_t");
4399 	return (NULL);
4400 }
4401 
4402 static int
4403 pcap_setbuff_dead(pcap_t *p, int dim _U_)
4404 {
4405 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4406 	    "The kernel buffer size cannot be set on a pcap_open_dead pcap_t");
4407 	return (-1);
4408 }
4409 
4410 static int
4411 pcap_setmode_dead(pcap_t *p, int mode _U_)
4412 {
4413 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4414 	    "impossible to set mode on a pcap_open_dead pcap_t");
4415 	return (-1);
4416 }
4417 
4418 static int
4419 pcap_setmintocopy_dead(pcap_t *p, int size _U_)
4420 {
4421 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4422 	    "The mintocopy parameter cannot be set on a pcap_open_dead pcap_t");
4423 	return (-1);
4424 }
4425 
4426 static HANDLE
4427 pcap_getevent_dead(pcap_t *p)
4428 {
4429 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4430 	    "A pcap_open_dead pcap_t has no event handle");
4431 	return (INVALID_HANDLE_VALUE);
4432 }
4433 
4434 static int
4435 pcap_oid_get_request_dead(pcap_t *p, bpf_u_int32 oid _U_, void *data _U_,
4436     size_t *lenp _U_)
4437 {
4438 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4439 	    "An OID get request cannot be performed on a pcap_open_dead pcap_t");
4440 	return (PCAP_ERROR);
4441 }
4442 
4443 static int
4444 pcap_oid_set_request_dead(pcap_t *p, bpf_u_int32 oid _U_, const void *data _U_,
4445     size_t *lenp _U_)
4446 {
4447 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4448 	    "An OID set request cannot be performed on a pcap_open_dead pcap_t");
4449 	return (PCAP_ERROR);
4450 }
4451 
4452 static u_int
4453 pcap_sendqueue_transmit_dead(pcap_t *p, pcap_send_queue *queue _U_,
4454     int sync _U_)
4455 {
4456 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4457 	    "Packets cannot be transmitted on a pcap_open_dead pcap_t");
4458 	return (0);
4459 }
4460 
4461 static int
4462 pcap_setuserbuffer_dead(pcap_t *p, int size _U_)
4463 {
4464 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4465 	    "The user buffer cannot be set on a pcap_open_dead pcap_t");
4466 	return (-1);
4467 }
4468 
4469 static int
4470 pcap_live_dump_dead(pcap_t *p, char *filename _U_, int maxsize _U_,
4471     int maxpacks _U_)
4472 {
4473 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4474 	    "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4475 	return (-1);
4476 }
4477 
4478 static int
4479 pcap_live_dump_ended_dead(pcap_t *p, int sync _U_)
4480 {
4481 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4482 	    "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4483 	return (-1);
4484 }
4485 
4486 static PAirpcapHandle
4487 pcap_get_airpcap_handle_dead(pcap_t *p _U_)
4488 {
4489 	return (NULL);
4490 }
4491 #endif /* _WIN32 */
4492 
4493 static void
4494 pcap_cleanup_dead(pcap_t *p _U_)
4495 {
4496 	/* Nothing to do. */
4497 }
4498 
4499 pcap_t *
4500 pcap_open_dead_with_tstamp_precision(int linktype, int snaplen, u_int precision)
4501 {
4502 	pcap_t *p;
4503 
4504 	switch (precision) {
4505 
4506 	case PCAP_TSTAMP_PRECISION_MICRO:
4507 	case PCAP_TSTAMP_PRECISION_NANO:
4508 		break;
4509 
4510 	default:
4511 		/*
4512 		 * This doesn't really matter, but we don't have any way
4513 		 * to report particular errors, so the only failure we
4514 		 * should have is a memory allocation failure.  Just
4515 		 * pick microsecond precision.
4516 		 */
4517 		precision = PCAP_TSTAMP_PRECISION_MICRO;
4518 		break;
4519 	}
4520 	p = malloc(sizeof(*p));
4521 	if (p == NULL)
4522 		return NULL;
4523 	memset (p, 0, sizeof(*p));
4524 	p->snapshot = snaplen;
4525 	p->linktype = linktype;
4526 	p->opt.tstamp_precision = precision;
4527 	p->can_set_rfmon_op = pcap_can_set_rfmon_dead;
4528 	p->read_op = pcap_read_dead;
4529 	p->inject_op = pcap_inject_dead;
4530 	p->setfilter_op = pcap_setfilter_dead;
4531 	p->setdirection_op = pcap_setdirection_dead;
4532 	p->set_datalink_op = pcap_set_datalink_dead;
4533 	p->getnonblock_op = pcap_getnonblock_dead;
4534 	p->setnonblock_op = pcap_setnonblock_dead;
4535 	p->stats_op = pcap_stats_dead;
4536 #ifdef _WIN32
4537 	p->stats_ex_op = pcap_stats_ex_dead;
4538 	p->setbuff_op = pcap_setbuff_dead;
4539 	p->setmode_op = pcap_setmode_dead;
4540 	p->setmintocopy_op = pcap_setmintocopy_dead;
4541 	p->getevent_op = pcap_getevent_dead;
4542 	p->oid_get_request_op = pcap_oid_get_request_dead;
4543 	p->oid_set_request_op = pcap_oid_set_request_dead;
4544 	p->sendqueue_transmit_op = pcap_sendqueue_transmit_dead;
4545 	p->setuserbuffer_op = pcap_setuserbuffer_dead;
4546 	p->live_dump_op = pcap_live_dump_dead;
4547 	p->live_dump_ended_op = pcap_live_dump_ended_dead;
4548 	p->get_airpcap_handle_op = pcap_get_airpcap_handle_dead;
4549 #endif
4550 	p->breakloop_op = pcap_breakloop_dead;
4551 	p->cleanup_op = pcap_cleanup_dead;
4552 
4553 	/*
4554 	 * A "dead" pcap_t never requires special BPF code generation.
4555 	 */
4556 	p->bpf_codegen_flags = 0;
4557 
4558 	p->activated = 1;
4559 	return (p);
4560 }
4561 
4562 pcap_t *
4563 pcap_open_dead(int linktype, int snaplen)
4564 {
4565 	return (pcap_open_dead_with_tstamp_precision(linktype, snaplen,
4566 	    PCAP_TSTAMP_PRECISION_MICRO));
4567 }
4568 
4569 #ifdef YYDEBUG
4570 /*
4571  * Set the internal "debug printout" flag for the filter expression parser.
4572  * The code to print that stuff is present only if YYDEBUG is defined, so
4573  * the flag, and the routine to set it, are defined only if YYDEBUG is
4574  * defined.
4575  *
4576  * This is intended for libpcap developers, not for general use.
4577  * If you want to set these in a program, you'll have to declare this
4578  * routine yourself, with the appropriate DLL import attribute on Windows;
4579  * it's not declared in any header file, and won't be declared in any
4580  * header file provided by libpcap.
4581  */
4582 PCAP_API void pcap_set_parser_debug(int value);
4583 
4584 PCAP_API_DEF void
4585 pcap_set_parser_debug(int value)
4586 {
4587 	pcap_debug = value;
4588 }
4589 #endif
4590