xref: /freebsd/contrib/libpcap/pcap.c (revision 4fd0d10e0fe684211328bc148edf89a792425b39)
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 #ifndef lint
35 static const char rcsid[] _U_ =
36     "@(#) $Header: /tcpdump/master/libpcap/pcap.c,v 1.128 2008-12-23 20:13:29 guy Exp $ (LBL)";
37 #endif
38 
39 #ifdef HAVE_CONFIG_H
40 #include "config.h"
41 #endif
42 
43 #ifdef WIN32
44 #include <pcap-stdinc.h>
45 #else /* WIN32 */
46 #if HAVE_INTTYPES_H
47 #include <inttypes.h>
48 #elif HAVE_STDINT_H
49 #include <stdint.h>
50 #endif
51 #ifdef HAVE_SYS_BITYPES_H
52 #include <sys/bitypes.h>
53 #endif
54 #include <sys/types.h>
55 #include <sys/mman.h>
56 #endif /* WIN32 */
57 
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #if !defined(_MSC_VER) && !defined(__BORLANDC__) && !defined(__MINGW32__)
62 #include <unistd.h>
63 #endif
64 #include <fcntl.h>
65 #include <errno.h>
66 
67 #ifdef HAVE_OS_PROTO_H
68 #include "os-proto.h"
69 #endif
70 
71 #ifdef MSDOS
72 #include "pcap-dos.h"
73 #endif
74 
75 #include "pcap-int.h"
76 
77 #ifdef HAVE_DAG_API
78 #include "pcap-dag.h"
79 #endif /* HAVE_DAG_API */
80 
81 #ifdef HAVE_SEPTEL_API
82 #include "pcap-septel.h"
83 #endif /* HAVE_SEPTEL_API */
84 
85 #ifdef HAVE_SNF_API
86 #include "pcap-snf.h"
87 #endif /* HAVE_SNF_API */
88 
89 #ifdef PCAP_SUPPORT_USB
90 #include "pcap-usb-linux.h"
91 #endif
92 
93 #ifdef PCAP_SUPPORT_BT
94 #include "pcap-bt-linux.h"
95 #endif
96 
97 #ifdef PCAP_SUPPORT_CAN
98 #include "pcap-can-linux.h"
99 #endif
100 
101 #ifdef PCAP_SUPPORT_CANUSB
102 #include "pcap-canusb-linux.h"
103 #endif
104 
105 #ifdef PCAP_SUPPORT_NETFILTER
106 #include "pcap-netfilter-linux.h"
107 #endif
108 
109 int
110 pcap_not_initialized(pcap_t *pcap)
111 {
112 	/* this means 'not initialized' */
113 	return (PCAP_ERROR_NOT_ACTIVATED);
114 }
115 
116 /*
117  * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
118  * a PCAP_ERROR value on an error.
119  */
120 int
121 pcap_can_set_rfmon(pcap_t *p)
122 {
123 	return (p->can_set_rfmon_op(p));
124 }
125 
126 /*
127  * For systems where rfmon mode is never supported.
128  */
129 static int
130 pcap_cant_set_rfmon(pcap_t *p _U_)
131 {
132 	return (0);
133 }
134 
135 /*
136  * Sets *tstamp_typesp to point to an array 1 or more supported time stamp
137  * types; the return value is the number of supported time stamp types.
138  * The list should be freed by a call to pcap_free_tstamp_types() when
139  * you're done with it.
140  *
141  * A return value of 0 means "you don't get a choice of time stamp type",
142  * in which case *tstamp_typesp is set to null.
143  *
144  * PCAP_ERROR is returned on error.
145  */
146 int
147 pcap_list_tstamp_types(pcap_t *p, int **tstamp_typesp)
148 {
149 	if (p->tstamp_type_count == 0) {
150 		/*
151 		 * We don't support multiple time stamp types.
152 		 */
153 		*tstamp_typesp = NULL;
154 	} else {
155 		*tstamp_typesp = (int*)calloc(sizeof(**tstamp_typesp),
156 		    p->tstamp_type_count);
157 		if (*tstamp_typesp == NULL) {
158 			(void)snprintf(p->errbuf, sizeof(p->errbuf),
159 			    "malloc: %s", pcap_strerror(errno));
160 			return (PCAP_ERROR);
161 		}
162 		(void)memcpy(*tstamp_typesp, p->tstamp_type_list,
163 		    sizeof(**tstamp_typesp) * p->tstamp_type_count);
164 	}
165 	return (p->tstamp_type_count);
166 }
167 
168 /*
169  * In Windows, you might have a library built with one version of the
170  * C runtime library and an application built with another version of
171  * the C runtime library, which means that the library might use one
172  * version of malloc() and free() and the application might use another
173  * version of malloc() and free().  If so, that means something
174  * allocated by the library cannot be freed by the application, so we
175  * need to have a pcap_free_tstamp_types() routine to free up the list
176  * allocated by pcap_list_tstamp_types(), even though it's just a wrapper
177  * around free().
178  */
179 void
180 pcap_free_tstamp_types(int *tstamp_type_list)
181 {
182 	free(tstamp_type_list);
183 }
184 
185 /*
186  * Default one-shot callback; overridden for capture types where the
187  * packet data cannot be guaranteed to be available after the callback
188  * returns, so that a copy must be made.
189  */
190 static void
191 pcap_oneshot(u_char *user, const struct pcap_pkthdr *h, const u_char *pkt)
192 {
193 	struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
194 
195 	*sp->hdr = *h;
196 	*sp->pkt = pkt;
197 }
198 
199 const u_char *
200 pcap_next(pcap_t *p, struct pcap_pkthdr *h)
201 {
202 	struct oneshot_userdata s;
203 	const u_char *pkt;
204 
205 	s.hdr = h;
206 	s.pkt = &pkt;
207 	s.pd = p;
208 	if (pcap_dispatch(p, 1, p->oneshot_callback, (u_char *)&s) <= 0)
209 		return (0);
210 	return (pkt);
211 }
212 
213 int
214 pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header,
215     const u_char **pkt_data)
216 {
217 	struct oneshot_userdata s;
218 
219 	s.hdr = &p->pcap_header;
220 	s.pkt = pkt_data;
221 	s.pd = p;
222 
223 	/* Saves a pointer to the packet headers */
224 	*pkt_header= &p->pcap_header;
225 
226 	if (p->sf.rfile != NULL) {
227 		int status;
228 
229 		/* We are on an offline capture */
230 		status = pcap_offline_read(p, 1, p->oneshot_callback,
231 		    (u_char *)&s);
232 
233 		/*
234 		 * Return codes for pcap_offline_read() are:
235 		 *   -  0: EOF
236 		 *   - -1: error
237 		 *   - >1: OK
238 		 * The first one ('0') conflicts with the return code of
239 		 * 0 from pcap_read() meaning "no packets arrived before
240 		 * the timeout expired", so we map it to -2 so you can
241 		 * distinguish between an EOF from a savefile and a
242 		 * "no packets arrived before the timeout expired, try
243 		 * again" from a live capture.
244 		 */
245 		if (status == 0)
246 			return (-2);
247 		else
248 			return (status);
249 	}
250 
251 	/*
252 	 * Return codes for pcap_read() are:
253 	 *   -  0: timeout
254 	 *   - -1: error
255 	 *   - -2: loop was broken out of with pcap_breakloop()
256 	 *   - >1: OK
257 	 * The first one ('0') conflicts with the return code of 0 from
258 	 * pcap_offline_read() meaning "end of file".
259 	*/
260 	return (p->read_op(p, 1, p->oneshot_callback, (u_char *)&s));
261 }
262 
263 #if defined(DAG_ONLY)
264 int
265 pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
266 {
267 	return (dag_findalldevs(alldevsp, errbuf));
268 }
269 
270 pcap_t *
271 pcap_create(const char *source, char *errbuf)
272 {
273 	return (dag_create(source, errbuf));
274 }
275 #elif defined(SEPTEL_ONLY)
276 int
277 pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
278 {
279 	return (septel_findalldevs(alldevsp, errbuf));
280 }
281 
282 pcap_t *
283 pcap_create(const char *source, char *errbuf)
284 {
285 	return (septel_create(source, errbuf));
286 }
287 #elif defined(SNF_ONLY)
288 int
289 pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
290 {
291 	return (snf_findalldevs(alldevsp, errbuf));
292 }
293 
294 pcap_t *
295 pcap_create(const char *source, char *errbuf)
296 {
297 	return (snf_create(source, errbuf));
298 }
299 #else /* regular pcap */
300 struct capture_source_type {
301 	int (*findalldevs_op)(pcap_if_t **, char *);
302 	pcap_t *(*create_op)(const char *, char *, int *);
303 } capture_source_types[] = {
304 #ifdef HAVE_DAG_API
305 	{ dag_findalldevs, dag_create },
306 #endif
307 #ifdef HAVE_SEPTEL_API
308 	{ septel_findalldevs, septel_create },
309 #endif
310 #ifdef HAVE_SNF_API
311 	{ snf_findalldevs, snf_create },
312 #endif
313 #ifdef PCAP_SUPPORT_BT
314 	{ bt_findalldevs, bt_create },
315 #endif
316 #if PCAP_SUPPORT_CANUSB
317 	{ canusb_findalldevs, canusb_create },
318 #endif
319 #ifdef PCAP_SUPPORT_CAN
320 	{ can_findalldevs, can_create },
321 #endif
322 #ifdef PCAP_SUPPORT_USB
323 	{ usb_findalldevs, usb_create },
324 #endif
325 #ifdef PCAP_SUPPORT_NETFILTER
326 	{ netfilter_findalldevs, netfilter_create },
327 #endif
328 	{ NULL, NULL }
329 };
330 
331 /*
332  * Get a list of all capture sources that are up and that we can open.
333  * Returns -1 on error, 0 otherwise.
334  * The list, as returned through "alldevsp", may be null if no interfaces
335  * were up and could be opened.
336  */
337 int
338 pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
339 {
340 	size_t i;
341 
342 	/*
343 	 * Get the list of regular interfaces first.
344 	 */
345 	if (pcap_findalldevs_interfaces(alldevsp, errbuf) == -1)
346 		return (-1);	/* failure */
347 
348 	/*
349 	 * Add any interfaces that need a platform-specific mechanism
350 	 * to find.
351 	 */
352 	if (pcap_platform_finddevs(alldevsp, errbuf) == -1) {
353 		/*
354 		 * We had an error; free the list we've been
355 		 * constructing.
356 		 */
357 		if (*alldevsp != NULL) {
358 			pcap_freealldevs(*alldevsp);
359 			*alldevsp = NULL;
360 		}
361 		return (-1);
362 	}
363 
364 	/*
365 	 * Ask each of the non-local-network-interface capture
366 	 * source types what interfaces they have.
367 	 */
368 	for (i = 0; capture_source_types[i].findalldevs_op != NULL; i++) {
369 		if (capture_source_types[i].findalldevs_op(alldevsp, errbuf) == -1) {
370 			/*
371 			 * We had an error; free the list we've been
372 			 * constructing.
373 			 */
374 			if (*alldevsp != NULL) {
375 				pcap_freealldevs(*alldevsp);
376 				*alldevsp = NULL;
377 			}
378 			return (-1);
379 		}
380 	}
381 	return (0);
382 }
383 
384 pcap_t *
385 pcap_create(const char *source, char *errbuf)
386 {
387 	size_t i;
388 	int is_theirs;
389 	pcap_t *p;
390 
391 	/*
392 	 * A null source name is equivalent to the "any" device -
393 	 * which might not be supported on this platform, but
394 	 * this means that you'll get a "not supported" error
395 	 * rather than, say, a crash when we try to dereference
396 	 * the null pointer.
397 	 */
398 	if (source == NULL)
399 		source = "any";
400 
401 	/*
402 	 * Try each of the non-local-network-interface capture
403 	 * source types until we find one that works for this
404 	 * device or run out of types.
405 	 */
406 	for (i = 0; capture_source_types[i].create_op != NULL; i++) {
407 		is_theirs = 0;
408 		p = capture_source_types[i].create_op(source, errbuf, &is_theirs);
409 		if (is_theirs) {
410 			/*
411 			 * The device name refers to a device of the
412 			 * type in question; either it succeeded,
413 			 * in which case p refers to a pcap_t to
414 			 * later activate for the device, or it
415 			 * failed, in which case p is null and we
416 			 * should return that to report the failure
417 			 * to create.
418 			 */
419 			return (p);
420 		}
421 	}
422 
423 	/*
424 	 * OK, try it as a regular network interface.
425 	 */
426 	return (pcap_create_interface(source, errbuf));
427 }
428 #endif
429 
430 static void
431 initialize_ops(pcap_t *p)
432 {
433 	/*
434 	 * Set operation pointers for operations that only work on
435 	 * an activated pcap_t to point to a routine that returns
436 	 * a "this isn't activated" error.
437 	 */
438 	p->read_op = (read_op_t)pcap_not_initialized;
439 	p->inject_op = (inject_op_t)pcap_not_initialized;
440 	p->setfilter_op = (setfilter_op_t)pcap_not_initialized;
441 	p->setdirection_op = (setdirection_op_t)pcap_not_initialized;
442 	p->set_datalink_op = (set_datalink_op_t)pcap_not_initialized;
443 	p->getnonblock_op = (getnonblock_op_t)pcap_not_initialized;
444 	p->setnonblock_op = (setnonblock_op_t)pcap_not_initialized;
445 	p->stats_op = (stats_op_t)pcap_not_initialized;
446 #ifdef WIN32
447 	p->setbuff_op = (setbuff_op_t)pcap_not_initialized;
448 	p->setmode_op = (setmode_op_t)pcap_not_initialized;
449 	p->setmintocopy_op = (setmintocopy_op_t)pcap_not_initialized;
450 #endif
451 
452 	/*
453 	 * Default cleanup operation - implementations can override
454 	 * this, but should call pcap_cleanup_live_common() after
455 	 * doing their own additional cleanup.
456 	 */
457 	p->cleanup_op = pcap_cleanup_live_common;
458 
459 	/*
460 	 * In most cases, the standard one-short callback can
461 	 * be used for pcap_next()/pcap_next_ex().
462 	 */
463 	p->oneshot_callback = pcap_oneshot;
464 }
465 
466 pcap_t *
467 pcap_create_common(const char *source, char *ebuf)
468 {
469 	pcap_t *p;
470 
471 	p = malloc(sizeof(*p));
472 	if (p == NULL) {
473 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
474 		    pcap_strerror(errno));
475 		return (NULL);
476 	}
477 	memset(p, 0, sizeof(*p));
478 #ifndef WIN32
479 	p->fd = -1;	/* not opened yet */
480 	p->selectable_fd = -1;
481 	p->send_fd = -1;
482 #endif
483 
484 	p->opt.source = strdup(source);
485 	if (p->opt.source == NULL) {
486 		snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
487 		    pcap_strerror(errno));
488 		free(p);
489 		return (NULL);
490 	}
491 
492 	/*
493 	 * Default to "can't set rfmon mode"; if it's supported by
494 	 * a platform, the create routine that called us can set
495 	 * the op to its routine to check whether a particular
496 	 * device supports it.
497 	 */
498 	p->can_set_rfmon_op = pcap_cant_set_rfmon;
499 
500 	initialize_ops(p);
501 
502 	/* put in some defaults*/
503 	pcap_set_timeout(p, 0);
504 	pcap_set_snaplen(p, 65535);	/* max packet size */
505 	p->opt.promisc = 0;
506 	p->opt.buffer_size = 0;
507 	p->opt.tstamp_type = -1;	/* default to not setting time stamp type */
508 	return (p);
509 }
510 
511 int
512 pcap_check_activated(pcap_t *p)
513 {
514 	if (p->activated) {
515 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't perform "
516 			" operation on activated capture");
517 		return (-1);
518 	}
519 	return (0);
520 }
521 
522 int
523 pcap_set_snaplen(pcap_t *p, int snaplen)
524 {
525 	if (pcap_check_activated(p))
526 		return (PCAP_ERROR_ACTIVATED);
527 	p->snapshot = snaplen;
528 	return (0);
529 }
530 
531 int
532 pcap_set_promisc(pcap_t *p, int promisc)
533 {
534 	if (pcap_check_activated(p))
535 		return (PCAP_ERROR_ACTIVATED);
536 	p->opt.promisc = promisc;
537 	return (0);
538 }
539 
540 int
541 pcap_set_rfmon(pcap_t *p, int rfmon)
542 {
543 	if (pcap_check_activated(p))
544 		return (PCAP_ERROR_ACTIVATED);
545 	p->opt.rfmon = rfmon;
546 	return (0);
547 }
548 
549 int
550 pcap_set_timeout(pcap_t *p, int timeout_ms)
551 {
552 	if (pcap_check_activated(p))
553 		return (PCAP_ERROR_ACTIVATED);
554 	p->md.timeout = timeout_ms;
555 	return (0);
556 }
557 
558 int
559 pcap_set_tstamp_type(pcap_t *p, int tstamp_type)
560 {
561 	int i;
562 
563 	if (pcap_check_activated(p))
564 		return (PCAP_ERROR_ACTIVATED);
565 
566 	/*
567 	 * If p->tstamp_type_count is 0, we don't support setting
568 	 * the time stamp type at all.
569 	 */
570 	if (p->tstamp_type_count == 0)
571 		return (PCAP_ERROR_CANTSET_TSTAMP_TYPE);
572 
573 	/*
574 	 * Check whether we claim to support this type of time stamp.
575 	 */
576 	for (i = 0; i < p->tstamp_type_count; i++) {
577 		if (p->tstamp_type_list[i] == tstamp_type) {
578 			/*
579 			 * Yes.
580 			 */
581 			p->opt.tstamp_type = tstamp_type;
582 			return (0);
583 		}
584 	}
585 
586 	/*
587 	 * No.  We support setting the time stamp type, but not to this
588 	 * particular value.
589 	 */
590 	return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
591 }
592 
593 int
594 pcap_set_buffer_size(pcap_t *p, int buffer_size)
595 {
596 	if (pcap_check_activated(p))
597 		return (PCAP_ERROR_ACTIVATED);
598 	p->opt.buffer_size = buffer_size;
599 	return (0);
600 }
601 
602 int
603 pcap_activate(pcap_t *p)
604 {
605 	int status;
606 
607 	/*
608 	 * Catch attempts to re-activate an already-activated
609 	 * pcap_t; this should, for example, catch code that
610 	 * calls pcap_open_live() followed by pcap_activate(),
611 	 * as some code that showed up in a Stack Exchange
612 	 * question did.
613 	 */
614 	if (pcap_check_activated(p))
615 		return (PCAP_ERROR_ACTIVATED);
616 	status = p->activate_op(p);
617 	if (status >= 0)
618 		p->activated = 1;
619 	else {
620 		if (p->errbuf[0] == '\0') {
621 			/*
622 			 * No error message supplied by the activate routine;
623 			 * for the benefit of programs that don't specially
624 			 * handle errors other than PCAP_ERROR, return the
625 			 * error message corresponding to the status.
626 			 */
627 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
628 			    pcap_statustostr(status));
629 		}
630 
631 		/*
632 		 * Undo any operation pointer setting, etc. done by
633 		 * the activate operation.
634 		 */
635 		initialize_ops(p);
636 	}
637 	return (status);
638 }
639 
640 pcap_t *
641 pcap_open_live(const char *source, int snaplen, int promisc, int to_ms, char *errbuf)
642 {
643 	pcap_t *p;
644 	int status;
645 
646 	p = pcap_create(source, errbuf);
647 	if (p == NULL)
648 		return (NULL);
649 	status = pcap_set_snaplen(p, snaplen);
650 	if (status < 0)
651 		goto fail;
652 	status = pcap_set_promisc(p, promisc);
653 	if (status < 0)
654 		goto fail;
655 	status = pcap_set_timeout(p, to_ms);
656 	if (status < 0)
657 		goto fail;
658 	/*
659 	 * Mark this as opened with pcap_open_live(), so that, for
660 	 * example, we show the full list of DLT_ values, rather
661 	 * than just the ones that are compatible with capturing
662 	 * when not in monitor mode.  That allows existing applications
663 	 * to work the way they used to work, but allows new applications
664 	 * that know about the new open API to, for example, find out the
665 	 * DLT_ values that they can select without changing whether
666 	 * the adapter is in monitor mode or not.
667 	 */
668 	p->oldstyle = 1;
669 	status = pcap_activate(p);
670 	if (status < 0)
671 		goto fail;
672 	return (p);
673 fail:
674 	if (status == PCAP_ERROR)
675 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
676 		    p->errbuf);
677 	else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
678 	    status == PCAP_ERROR_PERM_DENIED ||
679 	    status == PCAP_ERROR_PROMISC_PERM_DENIED)
680 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%s)", source,
681 		    pcap_statustostr(status), p->errbuf);
682 	else
683 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
684 		    pcap_statustostr(status));
685 	pcap_close(p);
686 	return (NULL);
687 }
688 
689 int
690 pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
691 {
692 	return (p->read_op(p, cnt, callback, user));
693 }
694 
695 /*
696  * XXX - is this necessary?
697  */
698 int
699 pcap_read(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
700 {
701 
702 	return (p->read_op(p, cnt, callback, user));
703 }
704 
705 int
706 pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
707 {
708 	register int n;
709 
710 	for (;;) {
711 		if (p->sf.rfile != NULL) {
712 			/*
713 			 * 0 means EOF, so don't loop if we get 0.
714 			 */
715 			n = pcap_offline_read(p, cnt, callback, user);
716 		} else {
717 			/*
718 			 * XXX keep reading until we get something
719 			 * (or an error occurs)
720 			 */
721 			do {
722 				n = p->read_op(p, cnt, callback, user);
723 			} while (n == 0);
724 		}
725 		if (n <= 0)
726 			return (n);
727 		if (cnt > 0) {
728 			cnt -= n;
729 			if (cnt <= 0)
730 				return (0);
731 		}
732 	}
733 }
734 
735 /*
736  * Force the loop in "pcap_read()" or "pcap_read_offline()" to terminate.
737  */
738 void
739 pcap_breakloop(pcap_t *p)
740 {
741 	p->break_loop = 1;
742 }
743 
744 int
745 pcap_datalink(pcap_t *p)
746 {
747 	return (p->linktype);
748 }
749 
750 int
751 pcap_datalink_ext(pcap_t *p)
752 {
753 	return (p->linktype_ext);
754 }
755 
756 int
757 pcap_list_datalinks(pcap_t *p, int **dlt_buffer)
758 {
759 	if (p->dlt_count == 0) {
760 		/*
761 		 * We couldn't fetch the list of DLTs, which means
762 		 * this platform doesn't support changing the
763 		 * DLT for an interface.  Return a list of DLTs
764 		 * containing only the DLT this device supports.
765 		 */
766 		*dlt_buffer = (int*)malloc(sizeof(**dlt_buffer));
767 		if (*dlt_buffer == NULL) {
768 			(void)snprintf(p->errbuf, sizeof(p->errbuf),
769 			    "malloc: %s", pcap_strerror(errno));
770 			return (-1);
771 		}
772 		**dlt_buffer = p->linktype;
773 		return (1);
774 	} else {
775 		*dlt_buffer = (int*)calloc(sizeof(**dlt_buffer), p->dlt_count);
776 		if (*dlt_buffer == NULL) {
777 			(void)snprintf(p->errbuf, sizeof(p->errbuf),
778 			    "malloc: %s", pcap_strerror(errno));
779 			return (-1);
780 		}
781 		(void)memcpy(*dlt_buffer, p->dlt_list,
782 		    sizeof(**dlt_buffer) * p->dlt_count);
783 		return (p->dlt_count);
784 	}
785 }
786 
787 /*
788  * In Windows, you might have a library built with one version of the
789  * C runtime library and an application built with another version of
790  * the C runtime library, which means that the library might use one
791  * version of malloc() and free() and the application might use another
792  * version of malloc() and free().  If so, that means something
793  * allocated by the library cannot be freed by the application, so we
794  * need to have a pcap_free_datalinks() routine to free up the list
795  * allocated by pcap_list_datalinks(), even though it's just a wrapper
796  * around free().
797  */
798 void
799 pcap_free_datalinks(int *dlt_list)
800 {
801 	free(dlt_list);
802 }
803 
804 int
805 pcap_set_datalink(pcap_t *p, int dlt)
806 {
807 	int i;
808 	const char *dlt_name;
809 
810 	if (p->dlt_count == 0 || p->set_datalink_op == NULL) {
811 		/*
812 		 * We couldn't fetch the list of DLTs, or we don't
813 		 * have a "set datalink" operation, which means
814 		 * this platform doesn't support changing the
815 		 * DLT for an interface.  Check whether the new
816 		 * DLT is the one this interface supports.
817 		 */
818 		if (p->linktype != dlt)
819 			goto unsupported;
820 
821 		/*
822 		 * It is, so there's nothing we need to do here.
823 		 */
824 		return (0);
825 	}
826 	for (i = 0; i < p->dlt_count; i++)
827 		if (p->dlt_list[i] == dlt)
828 			break;
829 	if (i >= p->dlt_count)
830 		goto unsupported;
831 	if (p->dlt_count == 2 && p->dlt_list[0] == DLT_EN10MB &&
832 	    dlt == DLT_DOCSIS) {
833 		/*
834 		 * This is presumably an Ethernet device, as the first
835 		 * link-layer type it offers is DLT_EN10MB, and the only
836 		 * other type it offers is DLT_DOCSIS.  That means that
837 		 * we can't tell the driver to supply DOCSIS link-layer
838 		 * headers - we're just pretending that's what we're
839 		 * getting, as, presumably, we're capturing on a dedicated
840 		 * link to a Cisco Cable Modem Termination System, and
841 		 * it's putting raw DOCSIS frames on the wire inside low-level
842 		 * Ethernet framing.
843 		 */
844 		p->linktype = dlt;
845 		return (0);
846 	}
847 	if (p->set_datalink_op(p, dlt) == -1)
848 		return (-1);
849 	p->linktype = dlt;
850 	return (0);
851 
852 unsupported:
853 	dlt_name = pcap_datalink_val_to_name(dlt);
854 	if (dlt_name != NULL) {
855 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
856 		    "%s is not one of the DLTs supported by this device",
857 		    dlt_name);
858 	} else {
859 		(void) snprintf(p->errbuf, sizeof(p->errbuf),
860 		    "DLT %d is not one of the DLTs supported by this device",
861 		    dlt);
862 	}
863 	return (-1);
864 }
865 
866 /*
867  * This array is designed for mapping upper and lower case letter
868  * together for a case independent comparison.  The mappings are
869  * based upon ascii character sequences.
870  */
871 static const u_char charmap[] = {
872 	(u_char)'\000', (u_char)'\001', (u_char)'\002', (u_char)'\003',
873 	(u_char)'\004', (u_char)'\005', (u_char)'\006', (u_char)'\007',
874 	(u_char)'\010', (u_char)'\011', (u_char)'\012', (u_char)'\013',
875 	(u_char)'\014', (u_char)'\015', (u_char)'\016', (u_char)'\017',
876 	(u_char)'\020', (u_char)'\021', (u_char)'\022', (u_char)'\023',
877 	(u_char)'\024', (u_char)'\025', (u_char)'\026', (u_char)'\027',
878 	(u_char)'\030', (u_char)'\031', (u_char)'\032', (u_char)'\033',
879 	(u_char)'\034', (u_char)'\035', (u_char)'\036', (u_char)'\037',
880 	(u_char)'\040', (u_char)'\041', (u_char)'\042', (u_char)'\043',
881 	(u_char)'\044', (u_char)'\045', (u_char)'\046', (u_char)'\047',
882 	(u_char)'\050', (u_char)'\051', (u_char)'\052', (u_char)'\053',
883 	(u_char)'\054', (u_char)'\055', (u_char)'\056', (u_char)'\057',
884 	(u_char)'\060', (u_char)'\061', (u_char)'\062', (u_char)'\063',
885 	(u_char)'\064', (u_char)'\065', (u_char)'\066', (u_char)'\067',
886 	(u_char)'\070', (u_char)'\071', (u_char)'\072', (u_char)'\073',
887 	(u_char)'\074', (u_char)'\075', (u_char)'\076', (u_char)'\077',
888 	(u_char)'\100', (u_char)'\141', (u_char)'\142', (u_char)'\143',
889 	(u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
890 	(u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
891 	(u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
892 	(u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
893 	(u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
894 	(u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\133',
895 	(u_char)'\134', (u_char)'\135', (u_char)'\136', (u_char)'\137',
896 	(u_char)'\140', (u_char)'\141', (u_char)'\142', (u_char)'\143',
897 	(u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
898 	(u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
899 	(u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
900 	(u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
901 	(u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
902 	(u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\173',
903 	(u_char)'\174', (u_char)'\175', (u_char)'\176', (u_char)'\177',
904 	(u_char)'\200', (u_char)'\201', (u_char)'\202', (u_char)'\203',
905 	(u_char)'\204', (u_char)'\205', (u_char)'\206', (u_char)'\207',
906 	(u_char)'\210', (u_char)'\211', (u_char)'\212', (u_char)'\213',
907 	(u_char)'\214', (u_char)'\215', (u_char)'\216', (u_char)'\217',
908 	(u_char)'\220', (u_char)'\221', (u_char)'\222', (u_char)'\223',
909 	(u_char)'\224', (u_char)'\225', (u_char)'\226', (u_char)'\227',
910 	(u_char)'\230', (u_char)'\231', (u_char)'\232', (u_char)'\233',
911 	(u_char)'\234', (u_char)'\235', (u_char)'\236', (u_char)'\237',
912 	(u_char)'\240', (u_char)'\241', (u_char)'\242', (u_char)'\243',
913 	(u_char)'\244', (u_char)'\245', (u_char)'\246', (u_char)'\247',
914 	(u_char)'\250', (u_char)'\251', (u_char)'\252', (u_char)'\253',
915 	(u_char)'\254', (u_char)'\255', (u_char)'\256', (u_char)'\257',
916 	(u_char)'\260', (u_char)'\261', (u_char)'\262', (u_char)'\263',
917 	(u_char)'\264', (u_char)'\265', (u_char)'\266', (u_char)'\267',
918 	(u_char)'\270', (u_char)'\271', (u_char)'\272', (u_char)'\273',
919 	(u_char)'\274', (u_char)'\275', (u_char)'\276', (u_char)'\277',
920 	(u_char)'\300', (u_char)'\341', (u_char)'\342', (u_char)'\343',
921 	(u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
922 	(u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
923 	(u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
924 	(u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
925 	(u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
926 	(u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\333',
927 	(u_char)'\334', (u_char)'\335', (u_char)'\336', (u_char)'\337',
928 	(u_char)'\340', (u_char)'\341', (u_char)'\342', (u_char)'\343',
929 	(u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
930 	(u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
931 	(u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
932 	(u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
933 	(u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
934 	(u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\373',
935 	(u_char)'\374', (u_char)'\375', (u_char)'\376', (u_char)'\377',
936 };
937 
938 int
939 pcap_strcasecmp(const char *s1, const char *s2)
940 {
941 	register const u_char	*cm = charmap,
942 				*us1 = (const u_char *)s1,
943 				*us2 = (const u_char *)s2;
944 
945 	while (cm[*us1] == cm[*us2++])
946 		if (*us1++ == '\0')
947 			return(0);
948 	return (cm[*us1] - cm[*--us2]);
949 }
950 
951 struct dlt_choice {
952 	const char *name;
953 	const char *description;
954 	int	dlt;
955 };
956 
957 #define DLT_CHOICE(code, description) { #code, description, code }
958 #define DLT_CHOICE_SENTINEL { NULL, NULL, 0 }
959 
960 static struct dlt_choice dlt_choices[] = {
961 	DLT_CHOICE(DLT_NULL, "BSD loopback"),
962 	DLT_CHOICE(DLT_EN10MB, "Ethernet"),
963 	DLT_CHOICE(DLT_IEEE802, "Token ring"),
964 	DLT_CHOICE(DLT_ARCNET, "BSD ARCNET"),
965 	DLT_CHOICE(DLT_SLIP, "SLIP"),
966 	DLT_CHOICE(DLT_PPP, "PPP"),
967 	DLT_CHOICE(DLT_FDDI, "FDDI"),
968 	DLT_CHOICE(DLT_ATM_RFC1483, "RFC 1483 LLC-encapsulated ATM"),
969 	DLT_CHOICE(DLT_RAW, "Raw IP"),
970 	DLT_CHOICE(DLT_SLIP_BSDOS, "BSD/OS SLIP"),
971 	DLT_CHOICE(DLT_PPP_BSDOS, "BSD/OS PPP"),
972 	DLT_CHOICE(DLT_ATM_CLIP, "Linux Classical IP-over-ATM"),
973 	DLT_CHOICE(DLT_PPP_SERIAL, "PPP over serial"),
974 	DLT_CHOICE(DLT_PPP_ETHER, "PPPoE"),
975         DLT_CHOICE(DLT_SYMANTEC_FIREWALL, "Symantec Firewall"),
976 	DLT_CHOICE(DLT_C_HDLC, "Cisco HDLC"),
977 	DLT_CHOICE(DLT_IEEE802_11, "802.11"),
978 	DLT_CHOICE(DLT_FRELAY, "Frame Relay"),
979 	DLT_CHOICE(DLT_LOOP, "OpenBSD loopback"),
980 	DLT_CHOICE(DLT_ENC, "OpenBSD encapsulated IP"),
981 	DLT_CHOICE(DLT_LINUX_SLL, "Linux cooked"),
982 	DLT_CHOICE(DLT_LTALK, "Localtalk"),
983 	DLT_CHOICE(DLT_PFLOG, "OpenBSD pflog file"),
984 	DLT_CHOICE(DLT_PFSYNC, "Packet filter state syncing"),
985 	DLT_CHOICE(DLT_PRISM_HEADER, "802.11 plus Prism header"),
986 	DLT_CHOICE(DLT_IP_OVER_FC, "RFC 2625 IP-over-Fibre Channel"),
987 	DLT_CHOICE(DLT_SUNATM, "Sun raw ATM"),
988 	DLT_CHOICE(DLT_IEEE802_11_RADIO, "802.11 plus radiotap header"),
989 	DLT_CHOICE(DLT_ARCNET_LINUX, "Linux ARCNET"),
990         DLT_CHOICE(DLT_JUNIPER_MLPPP, "Juniper Multi-Link PPP"),
991 	DLT_CHOICE(DLT_JUNIPER_MLFR, "Juniper Multi-Link Frame Relay"),
992         DLT_CHOICE(DLT_JUNIPER_ES, "Juniper Encryption Services PIC"),
993         DLT_CHOICE(DLT_JUNIPER_GGSN, "Juniper GGSN PIC"),
994 	DLT_CHOICE(DLT_JUNIPER_MFR, "Juniper FRF.16 Frame Relay"),
995         DLT_CHOICE(DLT_JUNIPER_ATM2, "Juniper ATM2 PIC"),
996         DLT_CHOICE(DLT_JUNIPER_SERVICES, "Juniper Advanced Services PIC"),
997         DLT_CHOICE(DLT_JUNIPER_ATM1, "Juniper ATM1 PIC"),
998 	DLT_CHOICE(DLT_APPLE_IP_OVER_IEEE1394, "Apple IP-over-IEEE 1394"),
999 	DLT_CHOICE(DLT_MTP2_WITH_PHDR, "SS7 MTP2 with Pseudo-header"),
1000 	DLT_CHOICE(DLT_MTP2, "SS7 MTP2"),
1001 	DLT_CHOICE(DLT_MTP3, "SS7 MTP3"),
1002 	DLT_CHOICE(DLT_SCCP, "SS7 SCCP"),
1003 	DLT_CHOICE(DLT_DOCSIS, "DOCSIS"),
1004 	DLT_CHOICE(DLT_LINUX_IRDA, "Linux IrDA"),
1005 	DLT_CHOICE(DLT_IEEE802_11_RADIO_AVS, "802.11 plus AVS radio information header"),
1006         DLT_CHOICE(DLT_JUNIPER_MONITOR, "Juniper Passive Monitor PIC"),
1007 	DLT_CHOICE(DLT_PPP_PPPD, "PPP for pppd, with direction flag"),
1008 	DLT_CHOICE(DLT_JUNIPER_PPPOE, "Juniper PPPoE"),
1009 	DLT_CHOICE(DLT_JUNIPER_PPPOE_ATM, "Juniper PPPoE/ATM"),
1010 	DLT_CHOICE(DLT_GPRS_LLC, "GPRS LLC"),
1011 	DLT_CHOICE(DLT_GPF_T, "GPF-T"),
1012 	DLT_CHOICE(DLT_GPF_F, "GPF-F"),
1013 	DLT_CHOICE(DLT_JUNIPER_PIC_PEER, "Juniper PIC Peer"),
1014 	DLT_CHOICE(DLT_ERF_ETH,	"Ethernet with Endace ERF header"),
1015 	DLT_CHOICE(DLT_ERF_POS, "Packet-over-SONET with Endace ERF header"),
1016 	DLT_CHOICE(DLT_LINUX_LAPD, "Linux vISDN LAPD"),
1017 	DLT_CHOICE(DLT_JUNIPER_ETHER, "Juniper Ethernet"),
1018 	DLT_CHOICE(DLT_JUNIPER_PPP, "Juniper PPP"),
1019 	DLT_CHOICE(DLT_JUNIPER_FRELAY, "Juniper Frame Relay"),
1020 	DLT_CHOICE(DLT_JUNIPER_CHDLC, "Juniper C-HDLC"),
1021 	DLT_CHOICE(DLT_MFR, "FRF.16 Frame Relay"),
1022 	DLT_CHOICE(DLT_JUNIPER_VP, "Juniper Voice PIC"),
1023 	DLT_CHOICE(DLT_A429, "Arinc 429"),
1024 	DLT_CHOICE(DLT_A653_ICM, "Arinc 653 Interpartition Communication"),
1025 	DLT_CHOICE(DLT_USB, "USB"),
1026 	DLT_CHOICE(DLT_BLUETOOTH_HCI_H4, "Bluetooth HCI UART transport layer"),
1027 	DLT_CHOICE(DLT_IEEE802_16_MAC_CPS, "IEEE 802.16 MAC Common Part Sublayer"),
1028 	DLT_CHOICE(DLT_USB_LINUX, "USB with Linux header"),
1029 	DLT_CHOICE(DLT_CAN20B, "Controller Area Network (CAN) v. 2.0B"),
1030 	DLT_CHOICE(DLT_IEEE802_15_4_LINUX, "IEEE 802.15.4 with Linux padding"),
1031 	DLT_CHOICE(DLT_PPI, "Per-Packet Information"),
1032 	DLT_CHOICE(DLT_IEEE802_16_MAC_CPS_RADIO, "IEEE 802.16 MAC Common Part Sublayer plus radiotap header"),
1033 	DLT_CHOICE(DLT_JUNIPER_ISM, "Juniper Integrated Service Module"),
1034 	DLT_CHOICE(DLT_IEEE802_15_4, "IEEE 802.15.4 with FCS"),
1035 	DLT_CHOICE(DLT_SITA, "SITA pseudo-header"),
1036 	DLT_CHOICE(DLT_ERF, "Endace ERF header"),
1037 	DLT_CHOICE(DLT_RAIF1, "Ethernet with u10 Networks pseudo-header"),
1038 	DLT_CHOICE(DLT_IPMB, "IPMB"),
1039 	DLT_CHOICE(DLT_JUNIPER_ST, "Juniper Secure Tunnel"),
1040 	DLT_CHOICE(DLT_BLUETOOTH_HCI_H4_WITH_PHDR, "Bluetooth HCI UART transport layer plus pseudo-header"),
1041 	DLT_CHOICE(DLT_AX25_KISS, "AX.25 with KISS header"),
1042 	DLT_CHOICE(DLT_IEEE802_15_4_NONASK_PHY, "IEEE 802.15.4 with non-ASK PHY data"),
1043 	DLT_CHOICE(DLT_MPLS, "MPLS with label as link-layer header"),
1044 	DLT_CHOICE(DLT_USB_LINUX_MMAPPED, "USB with padded Linux header"),
1045 	DLT_CHOICE(DLT_DECT, "DECT"),
1046 	DLT_CHOICE(DLT_AOS, "AOS Space Data Link protocol"),
1047 	DLT_CHOICE(DLT_WIHART, "Wireless HART"),
1048 	DLT_CHOICE(DLT_FC_2, "Fibre Channel FC-2"),
1049 	DLT_CHOICE(DLT_FC_2_WITH_FRAME_DELIMS, "Fibre Channel FC-2 with frame delimiters"),
1050 	DLT_CHOICE(DLT_IPNET, "Solaris ipnet"),
1051 	DLT_CHOICE(DLT_CAN_SOCKETCAN, "CAN-bus with SocketCAN headers"),
1052 	DLT_CHOICE(DLT_IPV4, "Raw IPv4"),
1053 	DLT_CHOICE(DLT_IPV6, "Raw IPv6"),
1054 	DLT_CHOICE(DLT_IEEE802_15_4_NOFCS, "IEEE 802.15.4 without FCS"),
1055 	DLT_CHOICE(DLT_JUNIPER_VS, "Juniper Virtual Server"),
1056 	DLT_CHOICE(DLT_JUNIPER_SRX_E2E, "Juniper SRX E2E"),
1057 	DLT_CHOICE(DLT_JUNIPER_FIBRECHANNEL, "Juniper Fibre Channel"),
1058 	DLT_CHOICE(DLT_DVB_CI, "DVB-CI"),
1059 	DLT_CHOICE(DLT_JUNIPER_ATM_CEMIC, "Juniper ATM CEMIC"),
1060 	DLT_CHOICE(DLT_NFLOG, "Linux netfilter log messages"),
1061 	DLT_CHOICE(DLT_NETANALYZER, "Ethernet with Hilscher netANALYZER pseudo-header"),
1062 	DLT_CHOICE(DLT_NETANALYZER_TRANSPARENT, "Ethernet with Hilscher netANALYZER pseudo-header and with preamble and SFD"),
1063 	DLT_CHOICE(DLT_IPOIB, "RFC 4391 IP-over-Infiniband"),
1064 	DLT_CHOICE_SENTINEL
1065 };
1066 
1067 int
1068 pcap_datalink_name_to_val(const char *name)
1069 {
1070 	int i;
1071 
1072 	for (i = 0; dlt_choices[i].name != NULL; i++) {
1073 		if (pcap_strcasecmp(dlt_choices[i].name + sizeof("DLT_") - 1,
1074 		    name) == 0)
1075 			return (dlt_choices[i].dlt);
1076 	}
1077 	return (-1);
1078 }
1079 
1080 const char *
1081 pcap_datalink_val_to_name(int dlt)
1082 {
1083 	int i;
1084 
1085 	for (i = 0; dlt_choices[i].name != NULL; i++) {
1086 		if (dlt_choices[i].dlt == dlt)
1087 			return (dlt_choices[i].name + sizeof("DLT_") - 1);
1088 	}
1089 	return (NULL);
1090 }
1091 
1092 const char *
1093 pcap_datalink_val_to_description(int dlt)
1094 {
1095 	int i;
1096 
1097 	for (i = 0; dlt_choices[i].name != NULL; i++) {
1098 		if (dlt_choices[i].dlt == dlt)
1099 			return (dlt_choices[i].description);
1100 	}
1101 	return (NULL);
1102 }
1103 
1104 struct tstamp_type_choice {
1105 	const char *name;
1106 	const char *description;
1107 	int	type;
1108 };
1109 
1110 static struct tstamp_type_choice tstamp_type_choices[] = {
1111 	{ "host", "Host", PCAP_TSTAMP_HOST },
1112 	{ "host_lowprec", "Host, low precision", PCAP_TSTAMP_HOST_LOWPREC },
1113 	{ "host_hiprec", "Host, high precision", PCAP_TSTAMP_HOST_HIPREC },
1114 	{ "adapter", "Adapter", PCAP_TSTAMP_ADAPTER },
1115 	{ "adapter_unsynced", "Adapter, not synced with system time", PCAP_TSTAMP_ADAPTER_UNSYNCED },
1116 	{ NULL, NULL, 0 }
1117 };
1118 
1119 int
1120 pcap_tstamp_type_name_to_val(const char *name)
1121 {
1122 	int i;
1123 
1124 	for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
1125 		if (pcap_strcasecmp(tstamp_type_choices[i].name, name) == 0)
1126 			return (tstamp_type_choices[i].type);
1127 	}
1128 	return (PCAP_ERROR);
1129 }
1130 
1131 const char *
1132 pcap_tstamp_type_val_to_name(int tstamp_type)
1133 {
1134 	int i;
1135 
1136 	for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
1137 		if (tstamp_type_choices[i].type == tstamp_type)
1138 			return (tstamp_type_choices[i].name);
1139 	}
1140 	return (NULL);
1141 }
1142 
1143 const char *
1144 pcap_tstamp_type_val_to_description(int tstamp_type)
1145 {
1146 	int i;
1147 
1148 	for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
1149 		if (tstamp_type_choices[i].type == tstamp_type)
1150 			return (tstamp_type_choices[i].description);
1151 	}
1152 	return (NULL);
1153 }
1154 
1155 int
1156 pcap_snapshot(pcap_t *p)
1157 {
1158 	return (p->snapshot);
1159 }
1160 
1161 int
1162 pcap_is_swapped(pcap_t *p)
1163 {
1164 	return (p->sf.swapped);
1165 }
1166 
1167 int
1168 pcap_major_version(pcap_t *p)
1169 {
1170 	return (p->sf.version_major);
1171 }
1172 
1173 int
1174 pcap_minor_version(pcap_t *p)
1175 {
1176 	return (p->sf.version_minor);
1177 }
1178 
1179 FILE *
1180 pcap_file(pcap_t *p)
1181 {
1182 	return (p->sf.rfile);
1183 }
1184 
1185 int
1186 pcap_fileno(pcap_t *p)
1187 {
1188 #ifndef WIN32
1189 	return (p->fd);
1190 #else
1191 	if (p->adapter != NULL)
1192 		return ((int)(DWORD)p->adapter->hFile);
1193 	else
1194 		return (-1);
1195 #endif
1196 }
1197 
1198 #if !defined(WIN32) && !defined(MSDOS)
1199 int
1200 pcap_get_selectable_fd(pcap_t *p)
1201 {
1202 	return (p->selectable_fd);
1203 }
1204 #endif
1205 
1206 void
1207 pcap_perror(pcap_t *p, char *prefix)
1208 {
1209 	fprintf(stderr, "%s: %s\n", prefix, p->errbuf);
1210 }
1211 
1212 char *
1213 pcap_geterr(pcap_t *p)
1214 {
1215 	return (p->errbuf);
1216 }
1217 
1218 int
1219 pcap_getnonblock(pcap_t *p, char *errbuf)
1220 {
1221 	int ret;
1222 
1223 	ret = p->getnonblock_op(p, errbuf);
1224 	if (ret == -1) {
1225 		/*
1226 		 * In case somebody depended on the bug wherein
1227 		 * the error message was put into p->errbuf
1228 		 * by pcap_getnonblock_fd().
1229 		 */
1230 		strlcpy(p->errbuf, errbuf, PCAP_ERRBUF_SIZE);
1231 	}
1232 	return (ret);
1233 }
1234 
1235 /*
1236  * Get the current non-blocking mode setting, under the assumption that
1237  * it's just the standard POSIX non-blocking flag.
1238  *
1239  * We don't look at "p->nonblock", in case somebody tweaked the FD
1240  * directly.
1241  */
1242 #if !defined(WIN32) && !defined(MSDOS)
1243 int
1244 pcap_getnonblock_fd(pcap_t *p, char *errbuf)
1245 {
1246 	int fdflags;
1247 
1248 	fdflags = fcntl(p->fd, F_GETFL, 0);
1249 	if (fdflags == -1) {
1250 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
1251 		    pcap_strerror(errno));
1252 		return (-1);
1253 	}
1254 	if (fdflags & O_NONBLOCK)
1255 		return (1);
1256 	else
1257 		return (0);
1258 }
1259 #endif
1260 
1261 int
1262 pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)
1263 {
1264 	int ret;
1265 
1266 	ret = p->setnonblock_op(p, nonblock, errbuf);
1267 	if (ret == -1) {
1268 		/*
1269 		 * In case somebody depended on the bug wherein
1270 		 * the error message was put into p->errbuf
1271 		 * by pcap_setnonblock_fd().
1272 		 */
1273 		strlcpy(p->errbuf, errbuf, PCAP_ERRBUF_SIZE);
1274 	}
1275 	return (ret);
1276 }
1277 
1278 #if !defined(WIN32) && !defined(MSDOS)
1279 /*
1280  * Set non-blocking mode, under the assumption that it's just the
1281  * standard POSIX non-blocking flag.  (This can be called by the
1282  * per-platform non-blocking-mode routine if that routine also
1283  * needs to do some additional work.)
1284  */
1285 int
1286 pcap_setnonblock_fd(pcap_t *p, int nonblock, char *errbuf)
1287 {
1288 	int fdflags;
1289 
1290 	fdflags = fcntl(p->fd, F_GETFL, 0);
1291 	if (fdflags == -1) {
1292 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
1293 		    pcap_strerror(errno));
1294 		return (-1);
1295 	}
1296 	if (nonblock)
1297 		fdflags |= O_NONBLOCK;
1298 	else
1299 		fdflags &= ~O_NONBLOCK;
1300 	if (fcntl(p->fd, F_SETFL, fdflags) == -1) {
1301 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "F_SETFL: %s",
1302 		    pcap_strerror(errno));
1303 		return (-1);
1304 	}
1305 	return (0);
1306 }
1307 #endif
1308 
1309 #ifdef WIN32
1310 /*
1311  * Generate a string for the last Win32-specific error (i.e. an error generated when
1312  * calling a Win32 API).
1313  * For errors occurred during standard C calls, we still use pcap_strerror()
1314  */
1315 char *
1316 pcap_win32strerror(void)
1317 {
1318 	DWORD error;
1319 	static char errbuf[PCAP_ERRBUF_SIZE+1];
1320 	int errlen;
1321 	char *p;
1322 
1323 	error = GetLastError();
1324 	FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
1325 	    PCAP_ERRBUF_SIZE, NULL);
1326 
1327 	/*
1328 	 * "FormatMessage()" "helpfully" sticks CR/LF at the end of the
1329 	 * message.  Get rid of it.
1330 	 */
1331 	errlen = strlen(errbuf);
1332 	if (errlen >= 2) {
1333 		errbuf[errlen - 1] = '\0';
1334 		errbuf[errlen - 2] = '\0';
1335 	}
1336 	p = strchr(errbuf, '\0');
1337 	snprintf (p, sizeof(errbuf)-(p-errbuf), " (%lu)", error);
1338 	return (errbuf);
1339 }
1340 #endif
1341 
1342 /*
1343  * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
1344  */
1345 const char *
1346 pcap_statustostr(int errnum)
1347 {
1348 	static char ebuf[15+10+1];
1349 
1350 	switch (errnum) {
1351 
1352 	case PCAP_WARNING:
1353 		return("Generic warning");
1354 
1355 	case PCAP_WARNING_TSTAMP_TYPE_NOTSUP:
1356 		return ("That type of time stamp is not supported by that device");
1357 
1358 	case PCAP_WARNING_PROMISC_NOTSUP:
1359 		return ("That device doesn't support promiscuous mode");
1360 
1361 	case PCAP_ERROR:
1362 		return("Generic error");
1363 
1364 	case PCAP_ERROR_BREAK:
1365 		return("Loop terminated by pcap_breakloop");
1366 
1367 	case PCAP_ERROR_NOT_ACTIVATED:
1368 		return("The pcap_t has not been activated");
1369 
1370 	case PCAP_ERROR_ACTIVATED:
1371 		return ("The setting can't be changed after the pcap_t is activated");
1372 
1373 	case PCAP_ERROR_NO_SUCH_DEVICE:
1374 		return ("No such device exists");
1375 
1376 	case PCAP_ERROR_RFMON_NOTSUP:
1377 		return ("That device doesn't support monitor mode");
1378 
1379 	case PCAP_ERROR_NOT_RFMON:
1380 		return ("That operation is supported only in monitor mode");
1381 
1382 	case PCAP_ERROR_PERM_DENIED:
1383 		return ("You don't have permission to capture on that device");
1384 
1385 	case PCAP_ERROR_IFACE_NOT_UP:
1386 		return ("That device is not up");
1387 
1388 	case PCAP_ERROR_CANTSET_TSTAMP_TYPE:
1389 		return ("That device doesn't support setting the time stamp type");
1390 
1391 	case PCAP_ERROR_PROMISC_PERM_DENIED:
1392 		return ("You don't have permission to capture in promiscuous mode on that device");
1393 	}
1394 	(void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
1395 	return(ebuf);
1396 }
1397 
1398 /*
1399  * Not all systems have strerror().
1400  */
1401 const char *
1402 pcap_strerror(int errnum)
1403 {
1404 #ifdef HAVE_STRERROR
1405 	return (strerror(errnum));
1406 #else
1407 	extern int sys_nerr;
1408 	extern const char *const sys_errlist[];
1409 	static char ebuf[15+10+1];
1410 
1411 	if ((unsigned int)errnum < sys_nerr)
1412 		return ((char *)sys_errlist[errnum]);
1413 	(void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
1414 	return(ebuf);
1415 #endif
1416 }
1417 
1418 int
1419 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
1420 {
1421 	return (p->setfilter_op(p, fp));
1422 }
1423 
1424 /*
1425  * Set direction flag, which controls whether we accept only incoming
1426  * packets, only outgoing packets, or both.
1427  * Note that, depending on the platform, some or all direction arguments
1428  * might not be supported.
1429  */
1430 int
1431 pcap_setdirection(pcap_t *p, pcap_direction_t d)
1432 {
1433 	if (p->setdirection_op == NULL) {
1434 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1435 		    "Setting direction is not implemented on this platform");
1436 		return (-1);
1437 	} else
1438 		return (p->setdirection_op(p, d));
1439 }
1440 
1441 int
1442 pcap_stats(pcap_t *p, struct pcap_stat *ps)
1443 {
1444 	return (p->stats_op(p, ps));
1445 }
1446 
1447 static int
1448 pcap_stats_dead(pcap_t *p, struct pcap_stat *ps _U_)
1449 {
1450 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1451 	    "Statistics aren't available from a pcap_open_dead pcap_t");
1452 	return (-1);
1453 }
1454 
1455 #ifdef WIN32
1456 int
1457 pcap_setbuff(pcap_t *p, int dim)
1458 {
1459 	return (p->setbuff_op(p, dim));
1460 }
1461 
1462 static int
1463 pcap_setbuff_dead(pcap_t *p, int dim)
1464 {
1465 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1466 	    "The kernel buffer size cannot be set on a pcap_open_dead pcap_t");
1467 	return (-1);
1468 }
1469 
1470 int
1471 pcap_setmode(pcap_t *p, int mode)
1472 {
1473 	return (p->setmode_op(p, mode));
1474 }
1475 
1476 static int
1477 pcap_setmode_dead(pcap_t *p, int mode)
1478 {
1479 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1480 	    "impossible to set mode on a pcap_open_dead pcap_t");
1481 	return (-1);
1482 }
1483 
1484 int
1485 pcap_setmintocopy(pcap_t *p, int size)
1486 {
1487 	return (p->setmintocopy_op(p, size));
1488 }
1489 
1490 static int
1491 pcap_setmintocopy_dead(pcap_t *p, int size)
1492 {
1493 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1494 	    "The mintocopy parameter cannot be set on a pcap_open_dead pcap_t");
1495 	return (-1);
1496 }
1497 #endif
1498 
1499 /*
1500  * On some platforms, we need to clean up promiscuous or monitor mode
1501  * when we close a device - and we want that to happen even if the
1502  * application just exits without explicitl closing devices.
1503  * On those platforms, we need to register a "close all the pcaps"
1504  * routine to be called when we exit, and need to maintain a list of
1505  * pcaps that need to be closed to clean up modes.
1506  *
1507  * XXX - not thread-safe.
1508  */
1509 
1510 /*
1511  * List of pcaps on which we've done something that needs to be
1512  * cleaned up.
1513  * If there are any such pcaps, we arrange to call "pcap_close_all()"
1514  * when we exit, and have it close all of them.
1515  */
1516 static struct pcap *pcaps_to_close;
1517 
1518 /*
1519  * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1520  * be called on exit.
1521  */
1522 static int did_atexit;
1523 
1524 static void
1525 pcap_close_all(void)
1526 {
1527 	struct pcap *handle;
1528 
1529 	while ((handle = pcaps_to_close) != NULL)
1530 		pcap_close(handle);
1531 }
1532 
1533 int
1534 pcap_do_addexit(pcap_t *p)
1535 {
1536 	/*
1537 	 * If we haven't already done so, arrange to have
1538 	 * "pcap_close_all()" called when we exit.
1539 	 */
1540 	if (!did_atexit) {
1541 		if (atexit(pcap_close_all) == -1) {
1542 			/*
1543 			 * "atexit()" failed; let our caller know.
1544 			 */
1545 			strncpy(p->errbuf, "atexit failed",
1546 			    PCAP_ERRBUF_SIZE);
1547 			return (0);
1548 		}
1549 		did_atexit = 1;
1550 	}
1551 	return (1);
1552 }
1553 
1554 void
1555 pcap_add_to_pcaps_to_close(pcap_t *p)
1556 {
1557 	p->md.next = pcaps_to_close;
1558 	pcaps_to_close = p;
1559 }
1560 
1561 void
1562 pcap_remove_from_pcaps_to_close(pcap_t *p)
1563 {
1564 	pcap_t *pc, *prevpc;
1565 
1566 	for (pc = pcaps_to_close, prevpc = NULL; pc != NULL;
1567 	    prevpc = pc, pc = pc->md.next) {
1568 		if (pc == p) {
1569 			/*
1570 			 * Found it.  Remove it from the list.
1571 			 */
1572 			if (prevpc == NULL) {
1573 				/*
1574 				 * It was at the head of the list.
1575 				 */
1576 				pcaps_to_close = pc->md.next;
1577 			} else {
1578 				/*
1579 				 * It was in the middle of the list.
1580 				 */
1581 				prevpc->md.next = pc->md.next;
1582 			}
1583 			break;
1584 		}
1585 	}
1586 }
1587 
1588 void
1589 pcap_cleanup_live_common(pcap_t *p)
1590 {
1591 	if (p->buffer != NULL) {
1592 		free(p->buffer);
1593 		p->buffer = NULL;
1594 	}
1595 	if (p->dlt_list != NULL) {
1596 		free(p->dlt_list);
1597 		p->dlt_list = NULL;
1598 		p->dlt_count = 0;
1599 	}
1600 	if (p->tstamp_type_list != NULL) {
1601 		free(p->tstamp_type_list);
1602 		p->tstamp_type_list = NULL;
1603 		p->tstamp_type_count = 0;
1604 	}
1605 	pcap_freecode(&p->fcode);
1606 #if !defined(WIN32) && !defined(MSDOS)
1607 	if (p->fd >= 0) {
1608 		close(p->fd);
1609 		p->fd = -1;
1610 	}
1611 	p->selectable_fd = -1;
1612 	p->send_fd = -1;
1613 #endif
1614 }
1615 
1616 static void
1617 pcap_cleanup_dead(pcap_t *p _U_)
1618 {
1619 	/* Nothing to do. */
1620 }
1621 
1622 pcap_t *
1623 pcap_open_dead(int linktype, int snaplen)
1624 {
1625 	pcap_t *p;
1626 
1627 	p = malloc(sizeof(*p));
1628 	if (p == NULL)
1629 		return NULL;
1630 	memset (p, 0, sizeof(*p));
1631 	p->snapshot = snaplen;
1632 	p->linktype = linktype;
1633 	p->stats_op = pcap_stats_dead;
1634 #ifdef WIN32
1635 	p->setbuff_op = pcap_setbuff_dead;
1636 	p->setmode_op = pcap_setmode_dead;
1637 	p->setmintocopy_op = pcap_setmintocopy_dead;
1638 #endif
1639 	p->cleanup_op = pcap_cleanup_dead;
1640 	p->activated = 1;
1641 	return (p);
1642 }
1643 
1644 /*
1645  * API compatible with WinPcap's "send a packet" routine - returns -1
1646  * on error, 0 otherwise.
1647  *
1648  * XXX - what if we get a short write?
1649  */
1650 int
1651 pcap_sendpacket(pcap_t *p, const u_char *buf, int size)
1652 {
1653 	if (p->inject_op(p, buf, size) == -1)
1654 		return (-1);
1655 	return (0);
1656 }
1657 
1658 /*
1659  * API compatible with OpenBSD's "send a packet" routine - returns -1 on
1660  * error, number of bytes written otherwise.
1661  */
1662 int
1663 pcap_inject(pcap_t *p, const void *buf, size_t size)
1664 {
1665 	return (p->inject_op(p, buf, size));
1666 }
1667 
1668 void
1669 pcap_close(pcap_t *p)
1670 {
1671 	if (p->opt.source != NULL)
1672 		free(p->opt.source);
1673 	p->cleanup_op(p);
1674 	free(p);
1675 }
1676 
1677 /*
1678  * Given a BPF program, a pcap_pkthdr structure for a packet, and the raw
1679  * data for the packet, check whether the packet passes the filter.
1680  * Returns the return value of the filter program, which will be zero if
1681  * the packet doesn't pass and non-zero if the packet does pass.
1682  */
1683 int
1684 pcap_offline_filter(const struct bpf_program *fp, const struct pcap_pkthdr *h,
1685     const u_char *pkt)
1686 {
1687 	const struct bpf_insn *fcode = fp->bf_insns;
1688 
1689 	if (fcode != NULL)
1690 		return (bpf_filter(fcode, pkt, h->len, h->caplen));
1691 	else
1692 		return (0);
1693 }
1694 
1695 /*
1696  * We make the version string static, and return a pointer to it, rather
1697  * than exporting the version string directly.  On at least some UNIXes,
1698  * if you import data from a shared library into an program, the data is
1699  * bound into the program binary, so if the string in the version of the
1700  * library with which the program was linked isn't the same as the
1701  * string in the version of the library with which the program is being
1702  * run, various undesirable things may happen (warnings, the string
1703  * being the one from the version of the library with which the program
1704  * was linked, or even weirder things, such as the string being the one
1705  * from the library but being truncated).
1706  */
1707 #ifdef HAVE_VERSION_H
1708 #include "version.h"
1709 #else
1710 static const char pcap_version_string[] = "libpcap version 1.x.y";
1711 #endif
1712 
1713 #ifdef WIN32
1714 /*
1715  * XXX - it'd be nice if we could somehow generate the WinPcap and libpcap
1716  * version numbers when building WinPcap.  (It'd be nice to do so for
1717  * the packet.dll version number as well.)
1718  */
1719 static const char wpcap_version_string[] = "4.0";
1720 static const char pcap_version_string_fmt[] =
1721     "WinPcap version %s, based on %s";
1722 static const char pcap_version_string_packet_dll_fmt[] =
1723     "WinPcap version %s (packet.dll version %s), based on %s";
1724 static char *full_pcap_version_string;
1725 
1726 const char *
1727 pcap_lib_version(void)
1728 {
1729 	char *packet_version_string;
1730 	size_t full_pcap_version_string_len;
1731 
1732 	if (full_pcap_version_string == NULL) {
1733 		/*
1734 		 * Generate the version string.
1735 		 */
1736 		packet_version_string = PacketGetVersion();
1737 		if (strcmp(wpcap_version_string, packet_version_string) == 0) {
1738 			/*
1739 			 * WinPcap version string and packet.dll version
1740 			 * string are the same; just report the WinPcap
1741 			 * version.
1742 			 */
1743 			full_pcap_version_string_len =
1744 			    (sizeof pcap_version_string_fmt - 4) +
1745 			    strlen(wpcap_version_string) +
1746 			    strlen(pcap_version_string);
1747 			full_pcap_version_string =
1748 			    malloc(full_pcap_version_string_len);
1749 			sprintf(full_pcap_version_string,
1750 			    pcap_version_string_fmt, wpcap_version_string,
1751 			    pcap_version_string);
1752 		} else {
1753 			/*
1754 			 * WinPcap version string and packet.dll version
1755 			 * string are different; that shouldn't be the
1756 			 * case (the two libraries should come from the
1757 			 * same version of WinPcap), so we report both
1758 			 * versions.
1759 			 */
1760 			full_pcap_version_string_len =
1761 			    (sizeof pcap_version_string_packet_dll_fmt - 6) +
1762 			    strlen(wpcap_version_string) +
1763 			    strlen(packet_version_string) +
1764 			    strlen(pcap_version_string);
1765 			full_pcap_version_string = malloc(full_pcap_version_string_len);
1766 
1767 			sprintf(full_pcap_version_string,
1768 			    pcap_version_string_packet_dll_fmt,
1769 			    wpcap_version_string, packet_version_string,
1770 			    pcap_version_string);
1771 		}
1772 	}
1773 	return (full_pcap_version_string);
1774 }
1775 
1776 #elif defined(MSDOS)
1777 
1778 static char *full_pcap_version_string;
1779 
1780 const char *
1781 pcap_lib_version (void)
1782 {
1783 	char *packet_version_string;
1784 	size_t full_pcap_version_string_len;
1785 	static char dospfx[] = "DOS-";
1786 
1787 	if (full_pcap_version_string == NULL) {
1788 		/*
1789 		 * Generate the version string.
1790 		 */
1791 		full_pcap_version_string_len =
1792 		    sizeof dospfx + strlen(pcap_version_string);
1793 		full_pcap_version_string =
1794 		    malloc(full_pcap_version_string_len);
1795 		strcpy(full_pcap_version_string, dospfx);
1796 		strcat(full_pcap_version_string, pcap_version_string);
1797 	}
1798 	return (full_pcap_version_string);
1799 }
1800 
1801 #else /* UN*X */
1802 
1803 const char *
1804 pcap_lib_version(void)
1805 {
1806 	return (pcap_version_string);
1807 }
1808 #endif
1809