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