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