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