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