]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libpcap/pcap.c
MFC r313695, r313760, r314769, r314863, r314865, r316125
[FreeBSD/FreeBSD.git] / contrib / libpcap / pcap.c
1 /*
2  * Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the Computer Systems
16  *      Engineering Group at Lawrence Berkeley Laboratory.
17  * 4. Neither the name of the University nor of the Laboratory may be used
18  *    to endorse or promote products derived from this software without
19  *    specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include "config.h"
36 #endif
37
38 #ifdef _WIN32
39 #include <pcap-stdinc.h>
40 #else /* _WIN32 */
41 #if HAVE_INTTYPES_H
42 #include <inttypes.h>
43 #elif HAVE_STDINT_H
44 #include <stdint.h>
45 #endif
46 #ifdef HAVE_SYS_BITYPES_H
47 #include <sys/bitypes.h>
48 #endif
49 #include <sys/types.h>
50 #include <sys/mman.h>
51 #endif /* _WIN32 */
52
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #if !defined(_MSC_VER) && !defined(__BORLANDC__) && !defined(__MINGW32__)
57 #include <unistd.h>
58 #endif
59 #include <fcntl.h>
60 #include <errno.h>
61
62 #ifdef HAVE_OS_PROTO_H
63 #include "os-proto.h"
64 #endif
65
66 #ifdef MSDOS
67 #include "pcap-dos.h"
68 #endif
69
70 #include "pcap-int.h"
71
72 #ifdef HAVE_DAG_API
73 #include "pcap-dag.h"
74 #endif /* HAVE_DAG_API */
75
76 #ifdef HAVE_SEPTEL_API
77 #include "pcap-septel.h"
78 #endif /* HAVE_SEPTEL_API */
79
80 #ifdef HAVE_SNF_API
81 #include "pcap-snf.h"
82 #endif /* HAVE_SNF_API */
83
84 #ifdef HAVE_TC_API
85 #include "pcap-tc.h"
86 #endif /* HAVE_TC_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_BT_MONITOR
97 #include "pcap-bt-monitor-linux.h"
98 #endif
99
100 #ifdef PCAP_SUPPORT_NETFILTER
101 #include "pcap-netfilter-linux.h"
102 #endif
103
104 #ifdef PCAP_SUPPORT_NETMAP
105 pcap_t* pcap_netmap_create(const char *device, char *ebuf, int *is_ours);
106 #endif
107
108 #ifdef PCAP_SUPPORT_DBUS
109 #include "pcap-dbus.h"
110 #endif
111
112 static int
113 pcap_not_initialized(pcap_t *pcap)
114 {
115         /* in case the caller doesn't check for PCAP_ERROR_NOT_ACTIVATED */
116         (void)pcap_snprintf(pcap->errbuf, sizeof(pcap->errbuf),
117             "This handle hasn't been activated yet");
118         /* this means 'not initialized' */
119         return (PCAP_ERROR_NOT_ACTIVATED);
120 }
121
122 #ifdef _WIN32
123 static void *
124 pcap_not_initialized_ptr(pcap_t *pcap)
125 {
126         (void)pcap_snprintf(pcap->errbuf, sizeof(pcap->errbuf),
127             "This handle hasn't been activated yet");
128         return (NULL);
129 }
130
131 static HANDLE
132 pcap_getevent_not_initialized(pcap_t *pcap)
133 {
134         (void)pcap_snprintf(pcap->errbuf, sizeof(pcap->errbuf),
135             "This handle hasn't been activated yet");
136         return (INVALID_HANDLE_VALUE);
137 }
138
139 static u_int
140 pcap_sendqueue_transmit_not_initialized(pcap_t *pcap, pcap_send_queue* queue, int sync)
141 {
142         (void)pcap_snprintf(pcap->errbuf, sizeof(pcap->errbuf),
143             "This handle hasn't been activated yet");
144         return (0);
145 }
146
147 static PAirpcapHandle
148 pcap_get_airpcap_handle_not_initialized(pcap_t *pcap)
149 {
150         (void)pcap_snprintf(pcap->errbuf, sizeof(pcap->errbuf),
151             "This handle hasn't been activated yet");
152         return (NULL);
153 }
154 #endif
155
156 /*
157  * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
158  * a PCAP_ERROR value on an error.
159  */
160 int
161 pcap_can_set_rfmon(pcap_t *p)
162 {
163         return (p->can_set_rfmon_op(p));
164 }
165
166 /*
167  * For systems where rfmon mode is never supported.
168  */
169 static int
170 pcap_cant_set_rfmon(pcap_t *p _U_)
171 {
172         return (0);
173 }
174
175 /*
176  * Sets *tstamp_typesp to point to an array 1 or more supported time stamp
177  * types; the return value is the number of supported time stamp types.
178  * The list should be freed by a call to pcap_free_tstamp_types() when
179  * you're done with it.
180  *
181  * A return value of 0 means "you don't get a choice of time stamp type",
182  * in which case *tstamp_typesp is set to null.
183  *
184  * PCAP_ERROR is returned on error.
185  */
186 int
187 pcap_list_tstamp_types(pcap_t *p, int **tstamp_typesp)
188 {
189         if (p->tstamp_type_count == 0) {
190                 /*
191                  * We don't support multiple time stamp types.
192                  */
193                 *tstamp_typesp = NULL;
194         } else {
195                 *tstamp_typesp = (int*)calloc(sizeof(**tstamp_typesp),
196                     p->tstamp_type_count);
197                 if (*tstamp_typesp == NULL) {
198                         (void)pcap_snprintf(p->errbuf, sizeof(p->errbuf),
199                             "malloc: %s", pcap_strerror(errno));
200                         return (PCAP_ERROR);
201                 }
202                 (void)memcpy(*tstamp_typesp, p->tstamp_type_list,
203                     sizeof(**tstamp_typesp) * p->tstamp_type_count);
204         }
205         return (p->tstamp_type_count);
206 }
207
208 /*
209  * In Windows, you might have a library built with one version of the
210  * C runtime library and an application built with another version of
211  * the C runtime library, which means that the library might use one
212  * version of malloc() and free() and the application might use another
213  * version of malloc() and free().  If so, that means something
214  * allocated by the library cannot be freed by the application, so we
215  * need to have a pcap_free_tstamp_types() routine to free up the list
216  * allocated by pcap_list_tstamp_types(), even though it's just a wrapper
217  * around free().
218  */
219 void
220 pcap_free_tstamp_types(int *tstamp_type_list)
221 {
222         free(tstamp_type_list);
223 }
224
225 /*
226  * Default one-shot callback; overridden for capture types where the
227  * packet data cannot be guaranteed to be available after the callback
228  * returns, so that a copy must be made.
229  */
230 void
231 pcap_oneshot(u_char *user, const struct pcap_pkthdr *h, const u_char *pkt)
232 {
233         struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
234
235         *sp->hdr = *h;
236         *sp->pkt = pkt;
237 }
238
239 const u_char *
240 pcap_next(pcap_t *p, struct pcap_pkthdr *h)
241 {
242         struct oneshot_userdata s;
243         const u_char *pkt;
244
245         s.hdr = h;
246         s.pkt = &pkt;
247         s.pd = p;
248         if (pcap_dispatch(p, 1, p->oneshot_callback, (u_char *)&s) <= 0)
249                 return (0);
250         return (pkt);
251 }
252
253 int
254 pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header,
255     const u_char **pkt_data)
256 {
257         struct oneshot_userdata s;
258
259         s.hdr = &p->pcap_header;
260         s.pkt = pkt_data;
261         s.pd = p;
262
263         /* Saves a pointer to the packet headers */
264         *pkt_header= &p->pcap_header;
265
266         if (p->rfile != NULL) {
267                 int status;
268
269                 /* We are on an offline capture */
270                 status = pcap_offline_read(p, 1, p->oneshot_callback,
271                     (u_char *)&s);
272
273                 /*
274                  * Return codes for pcap_offline_read() are:
275                  *   -  0: EOF
276                  *   - -1: error
277                  *   - >1: OK
278                  * The first one ('0') conflicts with the return code of
279                  * 0 from pcap_read() meaning "no packets arrived before
280                  * the timeout expired", so we map it to -2 so you can
281                  * distinguish between an EOF from a savefile and a
282                  * "no packets arrived before the timeout expired, try
283                  * again" from a live capture.
284                  */
285                 if (status == 0)
286                         return (-2);
287                 else
288                         return (status);
289         }
290
291         /*
292          * Return codes for pcap_read() are:
293          *   -  0: timeout
294          *   - -1: error
295          *   - -2: loop was broken out of with pcap_breakloop()
296          *   - >1: OK
297          * The first one ('0') conflicts with the return code of 0 from
298          * pcap_offline_read() meaning "end of file".
299         */
300         return (p->read_op(p, 1, p->oneshot_callback, (u_char *)&s));
301 }
302
303 static struct capture_source_type {
304         int (*findalldevs_op)(pcap_if_t **, char *);
305         pcap_t *(*create_op)(const char *, char *, int *);
306 } capture_source_types[] = {
307 #ifdef PCAP_SUPPORT_NETMAP
308         { NULL, pcap_netmap_create },
309 #endif
310 #ifdef HAVE_DAG_API
311         { dag_findalldevs, dag_create },
312 #endif
313 #ifdef HAVE_SEPTEL_API
314         { septel_findalldevs, septel_create },
315 #endif
316 #ifdef HAVE_SNF_API
317         { snf_findalldevs, snf_create },
318 #endif
319 #ifdef HAVE_TC_API
320         { TcFindAllDevs, TcCreate },
321 #endif
322 #ifdef PCAP_SUPPORT_BT
323         { bt_findalldevs, bt_create },
324 #endif
325 #ifdef PCAP_SUPPORT_BT_MONITOR
326         { bt_monitor_findalldevs, bt_monitor_create },
327 #endif
328 #ifdef PCAP_SUPPORT_USB
329         { usb_findalldevs, usb_create },
330 #endif
331 #ifdef PCAP_SUPPORT_NETFILTER
332         { netfilter_findalldevs, netfilter_create },
333 #endif
334 #ifdef PCAP_SUPPORT_DBUS
335         { dbus_findalldevs, dbus_create },
336 #endif
337         { NULL, NULL }
338 };
339
340 /*
341  * Get a list of all capture sources that are up and that we can open.
342  * Returns -1 on error, 0 otherwise.
343  * The list, as returned through "alldevsp", may be null if no interfaces
344  * were up and could be opened.
345  */
346 int
347 pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
348 {
349         size_t i;
350
351         /*
352          * Find all the local network interfaces on which we
353          * can capture.
354          */
355         if (pcap_platform_finddevs(alldevsp, errbuf) == -1)
356                 return (-1);
357
358         /*
359          * Ask each of the non-local-network-interface capture
360          * source types what interfaces they have.
361          */
362         for (i = 0; capture_source_types[i].findalldevs_op != NULL; i++) {
363                 if (capture_source_types[i].findalldevs_op(alldevsp, errbuf) == -1) {
364                         /*
365                          * We had an error; free the list we've been
366                          * constructing.
367                          */
368                         if (*alldevsp != NULL) {
369                                 pcap_freealldevs(*alldevsp);
370                                 *alldevsp = NULL;
371                         }
372                         return (-1);
373                 }
374         }
375
376         return (0);
377 }
378
379 pcap_t *
380 pcap_create(const char *device, char *errbuf)
381 {
382         size_t i;
383         int is_theirs;
384         pcap_t *p;
385         char *device_str;
386
387         /*
388          * A null device name is equivalent to the "any" device -
389          * which might not be supported on this platform, but
390          * this means that you'll get a "not supported" error
391          * rather than, say, a crash when we try to dereference
392          * the null pointer.
393          */
394         if (device == NULL)
395                 device_str = strdup("any");
396         else {
397 #ifdef _WIN32
398                 /*
399                  * If the string appears to be little-endian UCS-2/UTF-16,
400                  * convert it to ASCII.
401                  *
402                  * XXX - to UTF-8 instead?  Or report an error if any
403                  * character isn't ASCII?
404                  */
405                 if (device[0] != '\0' && device[1] == '\0') {
406                         size_t length;
407
408                         length = wcslen((wchar_t *)device);
409                         device_str = (char *)malloc(length + 1);
410                         if (device_str == NULL) {
411                                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
412                                     "malloc: %s", pcap_strerror(errno));
413                                 return (NULL);
414                         }
415
416                         pcap_snprintf(device_str, length + 1, "%ws",
417                             (const wchar_t *)device);
418                 } else
419 #endif
420                         device_str = strdup(device);
421         }
422         if (device_str == NULL) {
423                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
424                     "malloc: %s", pcap_strerror(errno));
425                 return (NULL);
426         }
427
428         /*
429          * Try each of the non-local-network-interface capture
430          * source types until we find one that works for this
431          * device or run out of types.
432          */
433         for (i = 0; capture_source_types[i].create_op != NULL; i++) {
434                 is_theirs = 0;
435                 p = capture_source_types[i].create_op(device_str, errbuf,
436                     &is_theirs);
437                 if (is_theirs) {
438                         /*
439                          * The device name refers to a device of the
440                          * type in question; either it succeeded,
441                          * in which case p refers to a pcap_t to
442                          * later activate for the device, or it
443                          * failed, in which case p is null and we
444                          * should return that to report the failure
445                          * to create.
446                          */
447                         if (p == NULL) {
448                                 /*
449                                  * We assume the caller filled in errbuf.
450                                  */
451                                 free(device_str);
452                                 return (NULL);
453                         }
454                         p->opt.device = device_str;
455                         return (p);
456                 }
457         }
458
459         /*
460          * OK, try it as a regular network interface.
461          */
462         p = pcap_create_interface(device_str, errbuf);
463         if (p == NULL) {
464                 /*
465                  * We assume the caller filled in errbuf.
466                  */
467                 free(device_str);
468                 return (NULL);
469         }
470         p->opt.device = device_str;
471         return (p);
472 }
473
474 static void
475 initialize_ops(pcap_t *p)
476 {
477         /*
478          * Set operation pointers for operations that only work on
479          * an activated pcap_t to point to a routine that returns
480          * a "this isn't activated" error.
481          */
482         p->read_op = (read_op_t)pcap_not_initialized;
483         p->inject_op = (inject_op_t)pcap_not_initialized;
484         p->setfilter_op = (setfilter_op_t)pcap_not_initialized;
485         p->setdirection_op = (setdirection_op_t)pcap_not_initialized;
486         p->set_datalink_op = (set_datalink_op_t)pcap_not_initialized;
487         p->getnonblock_op = (getnonblock_op_t)pcap_not_initialized;
488         p->setnonblock_op = (setnonblock_op_t)pcap_not_initialized;
489         p->stats_op = (stats_op_t)pcap_not_initialized;
490 #ifdef _WIN32
491         p->stats_ex_op = (stats_ex_op_t)pcap_not_initialized_ptr;
492         p->setbuff_op = (setbuff_op_t)pcap_not_initialized;
493         p->setmode_op = (setmode_op_t)pcap_not_initialized;
494         p->setmintocopy_op = (setmintocopy_op_t)pcap_not_initialized;
495         p->getevent_op = pcap_getevent_not_initialized;
496         p->oid_get_request_op = (oid_get_request_op_t)pcap_not_initialized;
497         p->oid_set_request_op = (oid_set_request_op_t)pcap_not_initialized;
498         p->sendqueue_transmit_op = pcap_sendqueue_transmit_not_initialized;
499         p->setuserbuffer_op = (setuserbuffer_op_t)pcap_not_initialized;
500         p->live_dump_op = (live_dump_op_t)pcap_not_initialized;
501         p->live_dump_ended_op = (live_dump_ended_op_t)pcap_not_initialized;
502         p->get_airpcap_handle_op = pcap_get_airpcap_handle_not_initialized;
503 #endif
504
505         /*
506          * Default cleanup operation - implementations can override
507          * this, but should call pcap_cleanup_live_common() after
508          * doing their own additional cleanup.
509          */
510         p->cleanup_op = pcap_cleanup_live_common;
511
512         /*
513          * In most cases, the standard one-shot callback can
514          * be used for pcap_next()/pcap_next_ex().
515          */
516         p->oneshot_callback = pcap_oneshot;
517 }
518
519 static pcap_t *
520 pcap_alloc_pcap_t(char *ebuf, size_t size)
521 {
522         char *chunk;
523         pcap_t *p;
524
525         /*
526          * Allocate a chunk of memory big enough for a pcap_t
527          * plus a structure following it of size "size".  The
528          * structure following it is a private data structure
529          * for the routines that handle this pcap_t.
530          */
531         chunk = malloc(sizeof (pcap_t) + size);
532         if (chunk == NULL) {
533                 pcap_snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
534                     pcap_strerror(errno));
535                 return (NULL);
536         }
537         memset(chunk, 0, sizeof (pcap_t) + size);
538
539         /*
540          * Get a pointer to the pcap_t at the beginning.
541          */
542         p = (pcap_t *)chunk;
543
544 #ifndef _WIN32
545         p->fd = -1;     /* not opened yet */
546         p->selectable_fd = -1;
547 #endif
548
549         if (size == 0) {
550                 /* No private data was requested. */
551                 p->priv = NULL;
552         } else {
553                 /*
554                  * Set the pointer to the private data; that's the structure
555                  * of size "size" following the pcap_t.
556                  */
557                 p->priv = (void *)(chunk + sizeof (pcap_t));
558         }
559
560         return (p);
561 }
562
563 pcap_t *
564 pcap_create_common(char *ebuf, size_t size)
565 {
566         pcap_t *p;
567
568         p = pcap_alloc_pcap_t(ebuf, size);
569         if (p == NULL)
570                 return (NULL);
571
572         /*
573          * Default to "can't set rfmon mode"; if it's supported by
574          * a platform, the create routine that called us can set
575          * the op to its routine to check whether a particular
576          * device supports it.
577          */
578         p->can_set_rfmon_op = pcap_cant_set_rfmon;
579
580         initialize_ops(p);
581
582         /* put in some defaults*/
583         p->snapshot = MAXIMUM_SNAPLEN;  /* max packet size */
584         p->opt.timeout = 0;             /* no timeout specified */
585         p->opt.buffer_size = 0;         /* use the platform's default */
586         p->opt.promisc = 0;
587         p->opt.rfmon = 0;
588         p->opt.immediate = 0;
589         p->opt.tstamp_type = -1;        /* default to not setting time stamp type */
590         p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
591
592         /*
593          * Start out with no BPF code generation flags set.
594          */
595         p->bpf_codegen_flags = 0;
596
597         return (p);
598 }
599
600 int
601 pcap_check_activated(pcap_t *p)
602 {
603         if (p->activated) {
604                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't perform "
605                         " operation on activated capture");
606                 return (-1);
607         }
608         return (0);
609 }
610
611 int
612 pcap_set_snaplen(pcap_t *p, int snaplen)
613 {
614         if (pcap_check_activated(p))
615                 return (PCAP_ERROR_ACTIVATED);
616
617         /*
618          * Turn invalid values, or excessively large values, into
619          * the maximum allowed value.
620          *
621          * If some application really *needs* a bigger snapshot
622          * length, we should just increase MAXIMUM_SNAPLEN.
623          */
624         if (snaplen <= 0 || snaplen > MAXIMUM_SNAPLEN)
625                 snaplen = MAXIMUM_SNAPLEN;
626         p->snapshot = snaplen;
627         return (0);
628 }
629
630 int
631 pcap_set_promisc(pcap_t *p, int promisc)
632 {
633         if (pcap_check_activated(p))
634                 return (PCAP_ERROR_ACTIVATED);
635         p->opt.promisc = promisc;
636         return (0);
637 }
638
639 int
640 pcap_set_rfmon(pcap_t *p, int rfmon)
641 {
642         if (pcap_check_activated(p))
643                 return (PCAP_ERROR_ACTIVATED);
644         p->opt.rfmon = rfmon;
645         return (0);
646 }
647
648 int
649 pcap_set_timeout(pcap_t *p, int timeout_ms)
650 {
651         if (pcap_check_activated(p))
652                 return (PCAP_ERROR_ACTIVATED);
653         p->opt.timeout = timeout_ms;
654         return (0);
655 }
656
657 int
658 pcap_set_tstamp_type(pcap_t *p, int tstamp_type)
659 {
660         int i;
661
662         if (pcap_check_activated(p))
663                 return (PCAP_ERROR_ACTIVATED);
664
665         /*
666          * The argument should have been u_int, but that's too late
667          * to change now - it's an API.
668          */
669         if (tstamp_type < 0)
670                 return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
671
672         /*
673          * If p->tstamp_type_count is 0, we only support PCAP_TSTAMP_HOST;
674          * the default time stamp type is PCAP_TSTAMP_HOST.
675          */
676         if (p->tstamp_type_count == 0) {
677                 if (tstamp_type == PCAP_TSTAMP_HOST) {
678                         p->opt.tstamp_type = tstamp_type;
679                         return (0);
680                 }
681         } else {
682                 /*
683                  * Check whether we claim to support this type of time stamp.
684                  */
685                 for (i = 0; i < p->tstamp_type_count; i++) {
686                         if (p->tstamp_type_list[i] == (u_int)tstamp_type) {
687                                 /*
688                                  * Yes.
689                                  */
690                                 p->opt.tstamp_type = tstamp_type;
691                                 return (0);
692                         }
693                 }
694         }
695
696         /*
697          * We don't support this type of time stamp.
698          */
699         return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
700 }
701
702 int
703 pcap_set_immediate_mode(pcap_t *p, int immediate)
704 {
705         if (pcap_check_activated(p))
706                 return (PCAP_ERROR_ACTIVATED);
707         p->opt.immediate = immediate;
708         return (0);
709 }
710
711 int
712 pcap_set_buffer_size(pcap_t *p, int buffer_size)
713 {
714         if (pcap_check_activated(p))
715                 return (PCAP_ERROR_ACTIVATED);
716         if (buffer_size <= 0) {
717                 /*
718                  * Silently ignore invalid values.
719                  */
720                 return (0);
721         }
722         p->opt.buffer_size = buffer_size;
723         return (0);
724 }
725
726 int
727 pcap_set_tstamp_precision(pcap_t *p, int tstamp_precision)
728 {
729         int i;
730
731         if (pcap_check_activated(p))
732                 return (PCAP_ERROR_ACTIVATED);
733
734         /*
735          * The argument should have been u_int, but that's too late
736          * to change now - it's an API.
737          */
738         if (tstamp_precision < 0)
739                 return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
740
741         /*
742          * If p->tstamp_precision_count is 0, we only support setting
743          * the time stamp precision to microsecond precision; every
744          * pcap module *MUST* support microsecond precision, even if
745          * it does so by converting the native precision to
746          * microseconds.
747          */
748         if (p->tstamp_precision_count == 0) {
749                 if (tstamp_precision == PCAP_TSTAMP_PRECISION_MICRO) {
750                         p->opt.tstamp_precision = tstamp_precision;
751                         return (0);
752                 }
753         } else {
754                 /*
755                  * Check whether we claim to support this precision of
756                  * time stamp.
757                  */
758                 for (i = 0; i < p->tstamp_precision_count; i++) {
759                         if (p->tstamp_precision_list[i] == (u_int)tstamp_precision) {
760                                 /*
761                                  * Yes.
762                                  */
763                                 p->opt.tstamp_precision = tstamp_precision;
764                                 return (0);
765                         }
766                 }
767         }
768
769         /*
770          * We don't support this time stamp precision.
771          */
772         return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
773 }
774
775 int
776 pcap_get_tstamp_precision(pcap_t *p)
777 {
778         return (p->opt.tstamp_precision);
779 }
780
781 int
782 pcap_activate(pcap_t *p)
783 {
784         int status;
785
786         /*
787          * Catch attempts to re-activate an already-activated
788          * pcap_t; this should, for example, catch code that
789          * calls pcap_open_live() followed by pcap_activate(),
790          * as some code that showed up in a Stack Exchange
791          * question did.
792          */
793         if (pcap_check_activated(p))
794                 return (PCAP_ERROR_ACTIVATED);
795         status = p->activate_op(p);
796         if (status >= 0)
797                 p->activated = 1;
798         else {
799                 if (p->errbuf[0] == '\0') {
800                         /*
801                          * No error message supplied by the activate routine;
802                          * for the benefit of programs that don't specially
803                          * handle errors other than PCAP_ERROR, return the
804                          * error message corresponding to the status.
805                          */
806                         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
807                             pcap_statustostr(status));
808                 }
809
810                 /*
811                  * Undo any operation pointer setting, etc. done by
812                  * the activate operation.
813                  */
814                 initialize_ops(p);
815         }
816         return (status);
817 }
818
819 pcap_t *
820 pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf)
821 {
822         pcap_t *p;
823         int status;
824
825         p = pcap_create(device, errbuf);
826         if (p == NULL)
827                 return (NULL);
828         status = pcap_set_snaplen(p, snaplen);
829         if (status < 0)
830                 goto fail;
831         status = pcap_set_promisc(p, promisc);
832         if (status < 0)
833                 goto fail;
834         status = pcap_set_timeout(p, to_ms);
835         if (status < 0)
836                 goto fail;
837         /*
838          * Mark this as opened with pcap_open_live(), so that, for
839          * example, we show the full list of DLT_ values, rather
840          * than just the ones that are compatible with capturing
841          * when not in monitor mode.  That allows existing applications
842          * to work the way they used to work, but allows new applications
843          * that know about the new open API to, for example, find out the
844          * DLT_ values that they can select without changing whether
845          * the adapter is in monitor mode or not.
846          */
847         p->oldstyle = 1;
848         status = pcap_activate(p);
849         if (status < 0)
850                 goto fail;
851         return (p);
852 fail:
853         if (status == PCAP_ERROR)
854                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", device,
855                     p->errbuf);
856         else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
857             status == PCAP_ERROR_PERM_DENIED ||
858             status == PCAP_ERROR_PROMISC_PERM_DENIED)
859                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%s)", device,
860                     pcap_statustostr(status), p->errbuf);
861         else
862                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", device,
863                     pcap_statustostr(status));
864         pcap_close(p);
865         return (NULL);
866 }
867
868 pcap_t *
869 pcap_open_offline_common(char *ebuf, size_t size)
870 {
871         pcap_t *p;
872
873         p = pcap_alloc_pcap_t(ebuf, size);
874         if (p == NULL)
875                 return (NULL);
876
877         p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
878
879         return (p);
880 }
881
882 int
883 pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
884 {
885         return (p->read_op(p, cnt, callback, user));
886 }
887
888 int
889 pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
890 {
891         register int n;
892
893         for (;;) {
894                 if (p->rfile != NULL) {
895                         /*
896                          * 0 means EOF, so don't loop if we get 0.
897                          */
898                         n = pcap_offline_read(p, cnt, callback, user);
899                 } else {
900                         /*
901                          * XXX keep reading until we get something
902                          * (or an error occurs)
903                          */
904                         do {
905                                 n = p->read_op(p, cnt, callback, user);
906                         } while (n == 0);
907                 }
908                 if (n <= 0)
909                         return (n);
910                 if (!PACKET_COUNT_IS_UNLIMITED(cnt)) {
911                         cnt -= n;
912                         if (cnt <= 0)
913                                 return (0);
914                 }
915         }
916 }
917
918 /*
919  * Force the loop in "pcap_read()" or "pcap_read_offline()" to terminate.
920  */
921 void
922 pcap_breakloop(pcap_t *p)
923 {
924         p->break_loop = 1;
925 }
926
927 int
928 pcap_datalink(pcap_t *p)
929 {
930         if (!p->activated)
931                 return (PCAP_ERROR_NOT_ACTIVATED);
932         return (p->linktype);
933 }
934
935 int
936 pcap_datalink_ext(pcap_t *p)
937 {
938         if (!p->activated)
939                 return (PCAP_ERROR_NOT_ACTIVATED);
940         return (p->linktype_ext);
941 }
942
943 int
944 pcap_list_datalinks(pcap_t *p, int **dlt_buffer)
945 {
946         if (!p->activated)
947                 return (PCAP_ERROR_NOT_ACTIVATED);
948         if (p->dlt_count == 0) {
949                 /*
950                  * We couldn't fetch the list of DLTs, which means
951                  * this platform doesn't support changing the
952                  * DLT for an interface.  Return a list of DLTs
953                  * containing only the DLT this device supports.
954                  */
955                 *dlt_buffer = (int*)malloc(sizeof(**dlt_buffer));
956                 if (*dlt_buffer == NULL) {
957                         (void)pcap_snprintf(p->errbuf, sizeof(p->errbuf),
958                             "malloc: %s", pcap_strerror(errno));
959                         return (PCAP_ERROR);
960                 }
961                 **dlt_buffer = p->linktype;
962                 return (1);
963         } else {
964                 *dlt_buffer = (int*)calloc(sizeof(**dlt_buffer), p->dlt_count);
965                 if (*dlt_buffer == NULL) {
966                         (void)pcap_snprintf(p->errbuf, sizeof(p->errbuf),
967                             "malloc: %s", pcap_strerror(errno));
968                         return (PCAP_ERROR);
969                 }
970                 (void)memcpy(*dlt_buffer, p->dlt_list,
971                     sizeof(**dlt_buffer) * p->dlt_count);
972                 return (p->dlt_count);
973         }
974 }
975
976 /*
977  * In Windows, you might have a library built with one version of the
978  * C runtime library and an application built with another version of
979  * the C runtime library, which means that the library might use one
980  * version of malloc() and free() and the application might use another
981  * version of malloc() and free().  If so, that means something
982  * allocated by the library cannot be freed by the application, so we
983  * need to have a pcap_free_datalinks() routine to free up the list
984  * allocated by pcap_list_datalinks(), even though it's just a wrapper
985  * around free().
986  */
987 void
988 pcap_free_datalinks(int *dlt_list)
989 {
990         free(dlt_list);
991 }
992
993 int
994 pcap_set_datalink(pcap_t *p, int dlt)
995 {
996         int i;
997         const char *dlt_name;
998
999         if (dlt < 0)
1000                 goto unsupported;
1001
1002         if (p->dlt_count == 0 || p->set_datalink_op == NULL) {
1003                 /*
1004                  * We couldn't fetch the list of DLTs, or we don't
1005                  * have a "set datalink" operation, which means
1006                  * this platform doesn't support changing the
1007                  * DLT for an interface.  Check whether the new
1008                  * DLT is the one this interface supports.
1009                  */
1010                 if (p->linktype != dlt)
1011                         goto unsupported;
1012
1013                 /*
1014                  * It is, so there's nothing we need to do here.
1015                  */
1016                 return (0);
1017         }
1018         for (i = 0; i < p->dlt_count; i++)
1019                 if (p->dlt_list[i] == (u_int)dlt)
1020                         break;
1021         if (i >= p->dlt_count)
1022                 goto unsupported;
1023         if (p->dlt_count == 2 && p->dlt_list[0] == DLT_EN10MB &&
1024             dlt == DLT_DOCSIS) {
1025                 /*
1026                  * This is presumably an Ethernet device, as the first
1027                  * link-layer type it offers is DLT_EN10MB, and the only
1028                  * other type it offers is DLT_DOCSIS.  That means that
1029                  * we can't tell the driver to supply DOCSIS link-layer
1030                  * headers - we're just pretending that's what we're
1031                  * getting, as, presumably, we're capturing on a dedicated
1032                  * link to a Cisco Cable Modem Termination System, and
1033                  * it's putting raw DOCSIS frames on the wire inside low-level
1034                  * Ethernet framing.
1035                  */
1036                 p->linktype = dlt;
1037                 return (0);
1038         }
1039         if (p->set_datalink_op(p, dlt) == -1)
1040                 return (-1);
1041         p->linktype = dlt;
1042         return (0);
1043
1044 unsupported:
1045         dlt_name = pcap_datalink_val_to_name(dlt);
1046         if (dlt_name != NULL) {
1047                 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
1048                     "%s is not one of the DLTs supported by this device",
1049                     dlt_name);
1050         } else {
1051                 (void) pcap_snprintf(p->errbuf, sizeof(p->errbuf),
1052                     "DLT %d is not one of the DLTs supported by this device",
1053                     dlt);
1054         }
1055         return (-1);
1056 }
1057
1058 /*
1059  * This array is designed for mapping upper and lower case letter
1060  * together for a case independent comparison.  The mappings are
1061  * based upon ascii character sequences.
1062  */
1063 static const u_char charmap[] = {
1064         (u_char)'\000', (u_char)'\001', (u_char)'\002', (u_char)'\003',
1065         (u_char)'\004', (u_char)'\005', (u_char)'\006', (u_char)'\007',
1066         (u_char)'\010', (u_char)'\011', (u_char)'\012', (u_char)'\013',
1067         (u_char)'\014', (u_char)'\015', (u_char)'\016', (u_char)'\017',
1068         (u_char)'\020', (u_char)'\021', (u_char)'\022', (u_char)'\023',
1069         (u_char)'\024', (u_char)'\025', (u_char)'\026', (u_char)'\027',
1070         (u_char)'\030', (u_char)'\031', (u_char)'\032', (u_char)'\033',
1071         (u_char)'\034', (u_char)'\035', (u_char)'\036', (u_char)'\037',
1072         (u_char)'\040', (u_char)'\041', (u_char)'\042', (u_char)'\043',
1073         (u_char)'\044', (u_char)'\045', (u_char)'\046', (u_char)'\047',
1074         (u_char)'\050', (u_char)'\051', (u_char)'\052', (u_char)'\053',
1075         (u_char)'\054', (u_char)'\055', (u_char)'\056', (u_char)'\057',
1076         (u_char)'\060', (u_char)'\061', (u_char)'\062', (u_char)'\063',
1077         (u_char)'\064', (u_char)'\065', (u_char)'\066', (u_char)'\067',
1078         (u_char)'\070', (u_char)'\071', (u_char)'\072', (u_char)'\073',
1079         (u_char)'\074', (u_char)'\075', (u_char)'\076', (u_char)'\077',
1080         (u_char)'\100', (u_char)'\141', (u_char)'\142', (u_char)'\143',
1081         (u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
1082         (u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
1083         (u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
1084         (u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
1085         (u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
1086         (u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\133',
1087         (u_char)'\134', (u_char)'\135', (u_char)'\136', (u_char)'\137',
1088         (u_char)'\140', (u_char)'\141', (u_char)'\142', (u_char)'\143',
1089         (u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
1090         (u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
1091         (u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
1092         (u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
1093         (u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
1094         (u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\173',
1095         (u_char)'\174', (u_char)'\175', (u_char)'\176', (u_char)'\177',
1096         (u_char)'\200', (u_char)'\201', (u_char)'\202', (u_char)'\203',
1097         (u_char)'\204', (u_char)'\205', (u_char)'\206', (u_char)'\207',
1098         (u_char)'\210', (u_char)'\211', (u_char)'\212', (u_char)'\213',
1099         (u_char)'\214', (u_char)'\215', (u_char)'\216', (u_char)'\217',
1100         (u_char)'\220', (u_char)'\221', (u_char)'\222', (u_char)'\223',
1101         (u_char)'\224', (u_char)'\225', (u_char)'\226', (u_char)'\227',
1102         (u_char)'\230', (u_char)'\231', (u_char)'\232', (u_char)'\233',
1103         (u_char)'\234', (u_char)'\235', (u_char)'\236', (u_char)'\237',
1104         (u_char)'\240', (u_char)'\241', (u_char)'\242', (u_char)'\243',
1105         (u_char)'\244', (u_char)'\245', (u_char)'\246', (u_char)'\247',
1106         (u_char)'\250', (u_char)'\251', (u_char)'\252', (u_char)'\253',
1107         (u_char)'\254', (u_char)'\255', (u_char)'\256', (u_char)'\257',
1108         (u_char)'\260', (u_char)'\261', (u_char)'\262', (u_char)'\263',
1109         (u_char)'\264', (u_char)'\265', (u_char)'\266', (u_char)'\267',
1110         (u_char)'\270', (u_char)'\271', (u_char)'\272', (u_char)'\273',
1111         (u_char)'\274', (u_char)'\275', (u_char)'\276', (u_char)'\277',
1112         (u_char)'\300', (u_char)'\341', (u_char)'\342', (u_char)'\343',
1113         (u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
1114         (u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
1115         (u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
1116         (u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
1117         (u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
1118         (u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\333',
1119         (u_char)'\334', (u_char)'\335', (u_char)'\336', (u_char)'\337',
1120         (u_char)'\340', (u_char)'\341', (u_char)'\342', (u_char)'\343',
1121         (u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
1122         (u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
1123         (u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
1124         (u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
1125         (u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
1126         (u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\373',
1127         (u_char)'\374', (u_char)'\375', (u_char)'\376', (u_char)'\377',
1128 };
1129
1130 int
1131 pcap_strcasecmp(const char *s1, const char *s2)
1132 {
1133         register const u_char   *cm = charmap,
1134                                 *us1 = (const u_char *)s1,
1135                                 *us2 = (const u_char *)s2;
1136
1137         while (cm[*us1] == cm[*us2++])
1138                 if (*us1++ == '\0')
1139                         return(0);
1140         return (cm[*us1] - cm[*--us2]);
1141 }
1142
1143 struct dlt_choice {
1144         const char *name;
1145         const char *description;
1146         int     dlt;
1147 };
1148
1149 #define DLT_CHOICE(code, description) { #code, description, DLT_ ## code }
1150 #define DLT_CHOICE_SENTINEL { NULL, NULL, 0 }
1151
1152 static struct dlt_choice dlt_choices[] = {
1153         DLT_CHOICE(NULL, "BSD loopback"),
1154         DLT_CHOICE(EN10MB, "Ethernet"),
1155         DLT_CHOICE(IEEE802, "Token ring"),
1156         DLT_CHOICE(ARCNET, "BSD ARCNET"),
1157         DLT_CHOICE(SLIP, "SLIP"),
1158         DLT_CHOICE(PPP, "PPP"),
1159         DLT_CHOICE(FDDI, "FDDI"),
1160         DLT_CHOICE(ATM_RFC1483, "RFC 1483 LLC-encapsulated ATM"),
1161         DLT_CHOICE(RAW, "Raw IP"),
1162         DLT_CHOICE(SLIP_BSDOS, "BSD/OS SLIP"),
1163         DLT_CHOICE(PPP_BSDOS, "BSD/OS PPP"),
1164         DLT_CHOICE(ATM_CLIP, "Linux Classical IP-over-ATM"),
1165         DLT_CHOICE(PPP_SERIAL, "PPP over serial"),
1166         DLT_CHOICE(PPP_ETHER, "PPPoE"),
1167         DLT_CHOICE(SYMANTEC_FIREWALL, "Symantec Firewall"),
1168         DLT_CHOICE(C_HDLC, "Cisco HDLC"),
1169         DLT_CHOICE(IEEE802_11, "802.11"),
1170         DLT_CHOICE(FRELAY, "Frame Relay"),
1171         DLT_CHOICE(LOOP, "OpenBSD loopback"),
1172         DLT_CHOICE(ENC, "OpenBSD encapsulated IP"),
1173         DLT_CHOICE(LINUX_SLL, "Linux cooked"),
1174         DLT_CHOICE(LTALK, "Localtalk"),
1175         DLT_CHOICE(PFLOG, "OpenBSD pflog file"),
1176         DLT_CHOICE(PFSYNC, "Packet filter state syncing"),
1177         DLT_CHOICE(PRISM_HEADER, "802.11 plus Prism header"),
1178         DLT_CHOICE(IP_OVER_FC, "RFC 2625 IP-over-Fibre Channel"),
1179         DLT_CHOICE(SUNATM, "Sun raw ATM"),
1180         DLT_CHOICE(IEEE802_11_RADIO, "802.11 plus radiotap header"),
1181         DLT_CHOICE(ARCNET_LINUX, "Linux ARCNET"),
1182         DLT_CHOICE(JUNIPER_MLPPP, "Juniper Multi-Link PPP"),
1183         DLT_CHOICE(JUNIPER_MLFR, "Juniper Multi-Link Frame Relay"),
1184         DLT_CHOICE(JUNIPER_ES, "Juniper Encryption Services PIC"),
1185         DLT_CHOICE(JUNIPER_GGSN, "Juniper GGSN PIC"),
1186         DLT_CHOICE(JUNIPER_MFR, "Juniper FRF.16 Frame Relay"),
1187         DLT_CHOICE(JUNIPER_ATM2, "Juniper ATM2 PIC"),
1188         DLT_CHOICE(JUNIPER_SERVICES, "Juniper Advanced Services PIC"),
1189         DLT_CHOICE(JUNIPER_ATM1, "Juniper ATM1 PIC"),
1190         DLT_CHOICE(APPLE_IP_OVER_IEEE1394, "Apple IP-over-IEEE 1394"),
1191         DLT_CHOICE(MTP2_WITH_PHDR, "SS7 MTP2 with Pseudo-header"),
1192         DLT_CHOICE(MTP2, "SS7 MTP2"),
1193         DLT_CHOICE(MTP3, "SS7 MTP3"),
1194         DLT_CHOICE(SCCP, "SS7 SCCP"),
1195         DLT_CHOICE(DOCSIS, "DOCSIS"),
1196         DLT_CHOICE(LINUX_IRDA, "Linux IrDA"),
1197         DLT_CHOICE(IEEE802_11_RADIO_AVS, "802.11 plus AVS radio information header"),
1198         DLT_CHOICE(JUNIPER_MONITOR, "Juniper Passive Monitor PIC"),
1199         DLT_CHOICE(BACNET_MS_TP, "BACnet MS/TP"),
1200         DLT_CHOICE(PPP_PPPD, "PPP for pppd, with direction flag"),
1201         DLT_CHOICE(JUNIPER_PPPOE, "Juniper PPPoE"),
1202         DLT_CHOICE(JUNIPER_PPPOE_ATM, "Juniper PPPoE/ATM"),
1203         DLT_CHOICE(GPRS_LLC, "GPRS LLC"),
1204         DLT_CHOICE(GPF_T, "GPF-T"),
1205         DLT_CHOICE(GPF_F, "GPF-F"),
1206         DLT_CHOICE(JUNIPER_PIC_PEER, "Juniper PIC Peer"),
1207         DLT_CHOICE(ERF_ETH,     "Ethernet with Endace ERF header"),
1208         DLT_CHOICE(ERF_POS, "Packet-over-SONET with Endace ERF header"),
1209         DLT_CHOICE(LINUX_LAPD, "Linux vISDN LAPD"),
1210         DLT_CHOICE(JUNIPER_ETHER, "Juniper Ethernet"),
1211         DLT_CHOICE(JUNIPER_PPP, "Juniper PPP"),
1212         DLT_CHOICE(JUNIPER_FRELAY, "Juniper Frame Relay"),
1213         DLT_CHOICE(JUNIPER_CHDLC, "Juniper C-HDLC"),
1214         DLT_CHOICE(MFR, "FRF.16 Frame Relay"),
1215         DLT_CHOICE(JUNIPER_VP, "Juniper Voice PIC"),
1216         DLT_CHOICE(A429, "Arinc 429"),
1217         DLT_CHOICE(A653_ICM, "Arinc 653 Interpartition Communication"),
1218         DLT_CHOICE(USB_FREEBSD, "USB with FreeBSD header"),
1219         DLT_CHOICE(BLUETOOTH_HCI_H4, "Bluetooth HCI UART transport layer"),
1220         DLT_CHOICE(IEEE802_16_MAC_CPS, "IEEE 802.16 MAC Common Part Sublayer"),
1221         DLT_CHOICE(USB_LINUX, "USB with Linux header"),
1222         DLT_CHOICE(CAN20B, "Controller Area Network (CAN) v. 2.0B"),
1223         DLT_CHOICE(IEEE802_15_4_LINUX, "IEEE 802.15.4 with Linux padding"),
1224         DLT_CHOICE(PPI, "Per-Packet Information"),
1225         DLT_CHOICE(IEEE802_16_MAC_CPS_RADIO, "IEEE 802.16 MAC Common Part Sublayer plus radiotap header"),
1226         DLT_CHOICE(JUNIPER_ISM, "Juniper Integrated Service Module"),
1227         DLT_CHOICE(IEEE802_15_4, "IEEE 802.15.4 with FCS"),
1228         DLT_CHOICE(SITA, "SITA pseudo-header"),
1229         DLT_CHOICE(ERF, "Endace ERF header"),
1230         DLT_CHOICE(RAIF1, "Ethernet with u10 Networks pseudo-header"),
1231         DLT_CHOICE(IPMB, "IPMB"),
1232         DLT_CHOICE(JUNIPER_ST, "Juniper Secure Tunnel"),
1233         DLT_CHOICE(BLUETOOTH_HCI_H4_WITH_PHDR, "Bluetooth HCI UART transport layer plus pseudo-header"),
1234         DLT_CHOICE(AX25_KISS, "AX.25 with KISS header"),
1235         DLT_CHOICE(IEEE802_15_4_NONASK_PHY, "IEEE 802.15.4 with non-ASK PHY data"),
1236         DLT_CHOICE(MPLS, "MPLS with label as link-layer header"),
1237         DLT_CHOICE(LINUX_EVDEV, "Linux evdev events"),
1238         DLT_CHOICE(USB_LINUX_MMAPPED, "USB with padded Linux header"),
1239         DLT_CHOICE(DECT, "DECT"),
1240         DLT_CHOICE(AOS, "AOS Space Data Link protocol"),
1241         DLT_CHOICE(WIHART, "Wireless HART"),
1242         DLT_CHOICE(FC_2, "Fibre Channel FC-2"),
1243         DLT_CHOICE(FC_2_WITH_FRAME_DELIMS, "Fibre Channel FC-2 with frame delimiters"),
1244         DLT_CHOICE(IPNET, "Solaris ipnet"),
1245         DLT_CHOICE(CAN_SOCKETCAN, "CAN-bus with SocketCAN headers"),
1246         DLT_CHOICE(IPV4, "Raw IPv4"),
1247         DLT_CHOICE(IPV6, "Raw IPv6"),
1248         DLT_CHOICE(IEEE802_15_4_NOFCS, "IEEE 802.15.4 without FCS"),
1249         DLT_CHOICE(DBUS, "D-Bus"),
1250         DLT_CHOICE(JUNIPER_VS, "Juniper Virtual Server"),
1251         DLT_CHOICE(JUNIPER_SRX_E2E, "Juniper SRX E2E"),
1252         DLT_CHOICE(JUNIPER_FIBRECHANNEL, "Juniper Fibre Channel"),
1253         DLT_CHOICE(DVB_CI, "DVB-CI"),
1254         DLT_CHOICE(MUX27010, "MUX27010"),
1255         DLT_CHOICE(STANAG_5066_D_PDU, "STANAG 5066 D_PDUs"),
1256         DLT_CHOICE(JUNIPER_ATM_CEMIC, "Juniper ATM CEMIC"),
1257         DLT_CHOICE(NFLOG, "Linux netfilter log messages"),
1258         DLT_CHOICE(NETANALYZER, "Ethernet with Hilscher netANALYZER pseudo-header"),
1259         DLT_CHOICE(NETANALYZER_TRANSPARENT, "Ethernet with Hilscher netANALYZER pseudo-header and with preamble and SFD"),
1260         DLT_CHOICE(IPOIB, "RFC 4391 IP-over-Infiniband"),
1261         DLT_CHOICE(MPEG_2_TS, "MPEG-2 transport stream"),
1262         DLT_CHOICE(NG40, "ng40 protocol tester Iub/Iur"),
1263         DLT_CHOICE(NFC_LLCP, "NFC LLCP PDUs with pseudo-header"),
1264         DLT_CHOICE(INFINIBAND, "InfiniBand"),
1265         DLT_CHOICE(SCTP, "SCTP"),
1266         DLT_CHOICE(USBPCAP, "USB with USBPcap header"),
1267         DLT_CHOICE(RTAC_SERIAL, "Schweitzer Engineering Laboratories RTAC packets"),
1268         DLT_CHOICE(BLUETOOTH_LE_LL, "Bluetooth Low Energy air interface"),
1269         DLT_CHOICE(NETLINK, "Linux netlink"),
1270         DLT_CHOICE(BLUETOOTH_LINUX_MONITOR, "Bluetooth Linux Monitor"),
1271         DLT_CHOICE(BLUETOOTH_BREDR_BB, "Bluetooth Basic Rate/Enhanced Data Rate baseband packets"),
1272         DLT_CHOICE(BLUETOOTH_LE_LL_WITH_PHDR, "Bluetooth Low Energy air interface with pseudo-header"),
1273         DLT_CHOICE(PROFIBUS_DL, "PROFIBUS data link layer"),
1274         DLT_CHOICE(PKTAP, "Apple DLT_PKTAP"),
1275         DLT_CHOICE(EPON, "Ethernet with 802.3 Clause 65 EPON preamble"),
1276         DLT_CHOICE(IPMI_HPM_2, "IPMI trace packets"),
1277         DLT_CHOICE(ZWAVE_R1_R2, "Z-Wave RF profile R1 and R2 packets"),
1278         DLT_CHOICE(ZWAVE_R3, "Z-Wave RF profile R3 packets"),
1279         DLT_CHOICE(WATTSTOPPER_DLM, "WattStopper Digital Lighting Management (DLM) and Legrand Nitoo Open protocol"),
1280         DLT_CHOICE(ISO_14443, "ISO 14443 messages"),
1281         DLT_CHOICE(RDS, "IEC 62106 Radio Data System groups"),
1282         DLT_CHOICE_SENTINEL
1283 };
1284
1285 int
1286 pcap_datalink_name_to_val(const char *name)
1287 {
1288         int i;
1289
1290         for (i = 0; dlt_choices[i].name != NULL; i++) {
1291                 if (pcap_strcasecmp(dlt_choices[i].name, name) == 0)
1292                         return (dlt_choices[i].dlt);
1293         }
1294         return (-1);
1295 }
1296
1297 const char *
1298 pcap_datalink_val_to_name(int dlt)
1299 {
1300         int i;
1301
1302         for (i = 0; dlt_choices[i].name != NULL; i++) {
1303                 if (dlt_choices[i].dlt == dlt)
1304                         return (dlt_choices[i].name);
1305         }
1306         return (NULL);
1307 }
1308
1309 const char *
1310 pcap_datalink_val_to_description(int dlt)
1311 {
1312         int i;
1313
1314         for (i = 0; dlt_choices[i].name != NULL; i++) {
1315                 if (dlt_choices[i].dlt == dlt)
1316                         return (dlt_choices[i].description);
1317         }
1318         return (NULL);
1319 }
1320
1321 struct tstamp_type_choice {
1322         const char *name;
1323         const char *description;
1324         int     type;
1325 };
1326
1327 static struct tstamp_type_choice tstamp_type_choices[] = {
1328         { "host", "Host", PCAP_TSTAMP_HOST },
1329         { "host_lowprec", "Host, low precision", PCAP_TSTAMP_HOST_LOWPREC },
1330         { "host_hiprec", "Host, high precision", PCAP_TSTAMP_HOST_HIPREC },
1331         { "adapter", "Adapter", PCAP_TSTAMP_ADAPTER },
1332         { "adapter_unsynced", "Adapter, not synced with system time", PCAP_TSTAMP_ADAPTER_UNSYNCED },
1333         { NULL, NULL, 0 }
1334 };
1335
1336 int
1337 pcap_tstamp_type_name_to_val(const char *name)
1338 {
1339         int i;
1340
1341         for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
1342                 if (pcap_strcasecmp(tstamp_type_choices[i].name, name) == 0)
1343                         return (tstamp_type_choices[i].type);
1344         }
1345         return (PCAP_ERROR);
1346 }
1347
1348 const char *
1349 pcap_tstamp_type_val_to_name(int tstamp_type)
1350 {
1351         int i;
1352
1353         for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
1354                 if (tstamp_type_choices[i].type == tstamp_type)
1355                         return (tstamp_type_choices[i].name);
1356         }
1357         return (NULL);
1358 }
1359
1360 const char *
1361 pcap_tstamp_type_val_to_description(int tstamp_type)
1362 {
1363         int i;
1364
1365         for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
1366                 if (tstamp_type_choices[i].type == tstamp_type)
1367                         return (tstamp_type_choices[i].description);
1368         }
1369         return (NULL);
1370 }
1371
1372 int
1373 pcap_snapshot(pcap_t *p)
1374 {
1375         if (!p->activated)
1376                 return (PCAP_ERROR_NOT_ACTIVATED);
1377         return (p->snapshot);
1378 }
1379
1380 int
1381 pcap_is_swapped(pcap_t *p)
1382 {
1383         if (!p->activated)
1384                 return (PCAP_ERROR_NOT_ACTIVATED);
1385         return (p->swapped);
1386 }
1387
1388 int
1389 pcap_major_version(pcap_t *p)
1390 {
1391         if (!p->activated)
1392                 return (PCAP_ERROR_NOT_ACTIVATED);
1393         return (p->version_major);
1394 }
1395
1396 int
1397 pcap_minor_version(pcap_t *p)
1398 {
1399         if (!p->activated)
1400                 return (PCAP_ERROR_NOT_ACTIVATED);
1401         return (p->version_minor);
1402 }
1403
1404 FILE *
1405 pcap_file(pcap_t *p)
1406 {
1407         return (p->rfile);
1408 }
1409
1410 int
1411 pcap_fileno(pcap_t *p)
1412 {
1413 #ifndef _WIN32
1414         return (p->fd);
1415 #else
1416         if (p->adapter != NULL)
1417                 return ((int)(DWORD)p->adapter->hFile);
1418         else
1419                 return (PCAP_ERROR);
1420 #endif
1421 }
1422
1423 #if !defined(_WIN32) && !defined(MSDOS)
1424 int
1425 pcap_get_selectable_fd(pcap_t *p)
1426 {
1427         return (p->selectable_fd);
1428 }
1429 #endif
1430
1431 void
1432 pcap_perror(pcap_t *p, const char *prefix)
1433 {
1434         fprintf(stderr, "%s: %s\n", prefix, p->errbuf);
1435 }
1436
1437 char *
1438 pcap_geterr(pcap_t *p)
1439 {
1440         return (p->errbuf);
1441 }
1442
1443 int
1444 pcap_getnonblock(pcap_t *p, char *errbuf)
1445 {
1446         int ret;
1447
1448         ret = p->getnonblock_op(p, errbuf);
1449         if (ret == -1) {
1450                 /*
1451                  * In case somebody depended on the bug wherein
1452                  * the error message was put into p->errbuf
1453                  * by pcap_getnonblock_fd().
1454                  */
1455                 strlcpy(p->errbuf, errbuf, PCAP_ERRBUF_SIZE);
1456         }
1457         return (ret);
1458 }
1459
1460 /*
1461  * Get the current non-blocking mode setting, under the assumption that
1462  * it's just the standard POSIX non-blocking flag.
1463  */
1464 #if !defined(_WIN32) && !defined(MSDOS)
1465 int
1466 pcap_getnonblock_fd(pcap_t *p, char *errbuf)
1467 {
1468         int fdflags;
1469
1470         fdflags = fcntl(p->fd, F_GETFL, 0);
1471         if (fdflags == -1) {
1472                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
1473                     pcap_strerror(errno));
1474                 return (-1);
1475         }
1476         if (fdflags & O_NONBLOCK)
1477                 return (1);
1478         else
1479                 return (0);
1480 }
1481 #endif
1482
1483 int
1484 pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)
1485 {
1486         int ret;
1487
1488         ret = p->setnonblock_op(p, nonblock, errbuf);
1489         if (ret == -1) {
1490                 /*
1491                  * In case somebody depended on the bug wherein
1492                  * the error message was put into p->errbuf
1493                  * by pcap_setnonblock_fd().
1494                  */
1495                 strlcpy(p->errbuf, errbuf, PCAP_ERRBUF_SIZE);
1496         }
1497         return (ret);
1498 }
1499
1500 #if !defined(_WIN32) && !defined(MSDOS)
1501 /*
1502  * Set non-blocking mode, under the assumption that it's just the
1503  * standard POSIX non-blocking flag.  (This can be called by the
1504  * per-platform non-blocking-mode routine if that routine also
1505  * needs to do some additional work.)
1506  */
1507 int
1508 pcap_setnonblock_fd(pcap_t *p, int nonblock, char *errbuf)
1509 {
1510         int fdflags;
1511
1512         fdflags = fcntl(p->fd, F_GETFL, 0);
1513         if (fdflags == -1) {
1514                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
1515                     pcap_strerror(errno));
1516                 return (-1);
1517         }
1518         if (nonblock)
1519                 fdflags |= O_NONBLOCK;
1520         else
1521                 fdflags &= ~O_NONBLOCK;
1522         if (fcntl(p->fd, F_SETFL, fdflags) == -1) {
1523                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "F_SETFL: %s",
1524                     pcap_strerror(errno));
1525                 return (-1);
1526         }
1527         return (0);
1528 }
1529 #endif
1530
1531 #ifdef _WIN32
1532 /*
1533  * Generate a string for a Win32-specific error (i.e. an error generated when
1534  * calling a Win32 API).
1535  * For errors occurred during standard C calls, we still use pcap_strerror()
1536  */
1537 void
1538 pcap_win32_err_to_str(DWORD error, char *errbuf)
1539 {
1540         size_t errlen;
1541         char *p;
1542
1543         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, errbuf,
1544             PCAP_ERRBUF_SIZE, NULL);
1545
1546         /*
1547          * "FormatMessage()" "helpfully" sticks CR/LF at the end of the
1548          * message.  Get rid of it.
1549          */
1550         errlen = strlen(errbuf);
1551         if (errlen >= 2) {
1552                 errbuf[errlen - 1] = '\0';
1553                 errbuf[errlen - 2] = '\0';
1554         }
1555         p = strchr(errbuf, '\0');
1556         pcap_snprintf (p, PCAP_ERRBUF_SIZE+1-(p-errbuf), " (%lu)", error);
1557 }
1558 #endif
1559
1560 /*
1561  * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
1562  */
1563 const char *
1564 pcap_statustostr(int errnum)
1565 {
1566         static char ebuf[15+10+1];
1567
1568         switch (errnum) {
1569
1570         case PCAP_WARNING:
1571                 return("Generic warning");
1572
1573         case PCAP_WARNING_TSTAMP_TYPE_NOTSUP:
1574                 return ("That type of time stamp is not supported by that device");
1575
1576         case PCAP_WARNING_PROMISC_NOTSUP:
1577                 return ("That device doesn't support promiscuous mode");
1578
1579         case PCAP_ERROR:
1580                 return("Generic error");
1581
1582         case PCAP_ERROR_BREAK:
1583                 return("Loop terminated by pcap_breakloop");
1584
1585         case PCAP_ERROR_NOT_ACTIVATED:
1586                 return("The pcap_t has not been activated");
1587
1588         case PCAP_ERROR_ACTIVATED:
1589                 return ("The setting can't be changed after the pcap_t is activated");
1590
1591         case PCAP_ERROR_NO_SUCH_DEVICE:
1592                 return ("No such device exists");
1593
1594         case PCAP_ERROR_RFMON_NOTSUP:
1595                 return ("That device doesn't support monitor mode");
1596
1597         case PCAP_ERROR_NOT_RFMON:
1598                 return ("That operation is supported only in monitor mode");
1599
1600         case PCAP_ERROR_PERM_DENIED:
1601                 return ("You don't have permission to capture on that device");
1602
1603         case PCAP_ERROR_IFACE_NOT_UP:
1604                 return ("That device is not up");
1605
1606         case PCAP_ERROR_CANTSET_TSTAMP_TYPE:
1607                 return ("That device doesn't support setting the time stamp type");
1608
1609         case PCAP_ERROR_PROMISC_PERM_DENIED:
1610                 return ("You don't have permission to capture in promiscuous mode on that device");
1611
1612         case PCAP_ERROR_TSTAMP_PRECISION_NOTSUP:
1613                 return ("That device doesn't support that time stamp precision");
1614         }
1615         (void)pcap_snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
1616         return(ebuf);
1617 }
1618
1619 /*
1620  * Not all systems have strerror().
1621  */
1622 const char *
1623 pcap_strerror(int errnum)
1624 {
1625 #ifdef HAVE_STRERROR
1626 #ifdef _WIN32
1627         static char errbuf[PCAP_ERRBUF_SIZE];
1628         errno_t errno;
1629         errno = strerror_s(errbuf, PCAP_ERRBUF_SIZE, errnum);
1630         if (errno != 0) /* errno = 0 if successful */
1631                 strlcpy(errbuf, "strerror_s() error", PCAP_ERRBUF_SIZE);
1632         return (errbuf);
1633 #else
1634         return (strerror(errnum));
1635 #endif /* _WIN32 */
1636 #else
1637         extern int sys_nerr;
1638         extern const char *const sys_errlist[];
1639         static char errbuf[PCAP_ERRBUF_SIZE];
1640
1641         if ((unsigned int)errnum < sys_nerr)
1642                 return ((char *)sys_errlist[errnum]);
1643         (void)pcap_snprintf(errbuf, sizeof errbuf, "Unknown error: %d", errnum);
1644         return (errbuf);
1645 #endif
1646 }
1647
1648 int
1649 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
1650 {
1651         return (p->setfilter_op(p, fp));
1652 }
1653
1654 /*
1655  * Set direction flag, which controls whether we accept only incoming
1656  * packets, only outgoing packets, or both.
1657  * Note that, depending on the platform, some or all direction arguments
1658  * might not be supported.
1659  */
1660 int
1661 pcap_setdirection(pcap_t *p, pcap_direction_t d)
1662 {
1663         if (p->setdirection_op == NULL) {
1664                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1665                     "Setting direction is not implemented on this platform");
1666                 return (-1);
1667         } else
1668                 return (p->setdirection_op(p, d));
1669 }
1670
1671 int
1672 pcap_stats(pcap_t *p, struct pcap_stat *ps)
1673 {
1674         return (p->stats_op(p, ps));
1675 }
1676
1677 static int
1678 pcap_stats_dead(pcap_t *p, struct pcap_stat *ps _U_)
1679 {
1680         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1681             "Statistics aren't available from a pcap_open_dead pcap_t");
1682         return (-1);
1683 }
1684
1685 #ifdef _WIN32
1686 struct pcap_stat *
1687 pcap_stats_ex(pcap_t *p, int *pcap_stat_size)
1688 {
1689         return (p->stats_ex_op(p, pcap_stat_size));
1690 }
1691
1692 int
1693 pcap_setbuff(pcap_t *p, int dim)
1694 {
1695         return (p->setbuff_op(p, dim));
1696 }
1697
1698 static int
1699 pcap_setbuff_dead(pcap_t *p, int dim)
1700 {
1701         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1702             "The kernel buffer size cannot be set on a pcap_open_dead pcap_t");
1703         return (-1);
1704 }
1705
1706 int
1707 pcap_setmode(pcap_t *p, int mode)
1708 {
1709         return (p->setmode_op(p, mode));
1710 }
1711
1712 static int
1713 pcap_setmode_dead(pcap_t *p, int mode)
1714 {
1715         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1716             "impossible to set mode on a pcap_open_dead pcap_t");
1717         return (-1);
1718 }
1719
1720 int
1721 pcap_setmintocopy(pcap_t *p, int size)
1722 {
1723         return (p->setmintocopy_op(p, size));
1724 }
1725
1726 static int
1727 pcap_setmintocopy_dead(pcap_t *p, int size)
1728 {
1729         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1730             "The mintocopy parameter cannot be set on a pcap_open_dead pcap_t");
1731         return (-1);
1732 }
1733
1734 HANDLE
1735 pcap_getevent(pcap_t *p)
1736 {
1737         return (p->getevent_op(p));
1738 }
1739
1740 static HANDLE
1741 pcap_getevent_dead(pcap_t *p)
1742 {
1743         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1744             "A pcap_open_dead pcap_t has no event handle");
1745         return (INVALID_HANDLE_VALUE);
1746 }
1747
1748 int
1749 pcap_oid_get_request(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
1750 {
1751         return (p->oid_get_request_op(p, oid, data, lenp));
1752 }
1753
1754 static int
1755 pcap_oid_get_request_dead(pcap_t *p, bpf_u_int32 oid _U_, void *data _U_,
1756     size_t *lenp _U_)
1757 {
1758         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1759             "An OID get request cannot be performed on a pcap_open_dead pcap_t");
1760         return (PCAP_ERROR);
1761 }
1762
1763 int
1764 pcap_oid_set_request(pcap_t *p, bpf_u_int32 oid, const void *data, size_t *lenp)
1765 {
1766         return (p->oid_set_request_op(p, oid, data, lenp));
1767 }
1768
1769 static int
1770 pcap_oid_set_request_dead(pcap_t *p, bpf_u_int32 oid _U_, const void *data _U_,
1771     size_t *lenp _U_)
1772 {
1773         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1774             "An OID set request cannot be performed on a pcap_open_dead pcap_t");
1775         return (PCAP_ERROR);
1776 }
1777
1778 pcap_send_queue *
1779 pcap_sendqueue_alloc(u_int memsize)
1780 {
1781         pcap_send_queue *tqueue;
1782
1783         /* Allocate the queue */
1784         tqueue = (pcap_send_queue *)malloc(sizeof(pcap_send_queue));
1785         if (tqueue == NULL){
1786                 return (NULL);
1787         }
1788
1789         /* Allocate the buffer */
1790         tqueue->buffer = (char *)malloc(memsize);
1791         if (tqueue->buffer == NULL) {
1792                 free(tqueue);
1793                 return (NULL);
1794         }
1795
1796         tqueue->maxlen = memsize;
1797         tqueue->len = 0;
1798
1799         return (tqueue);
1800 }
1801
1802 void
1803 pcap_sendqueue_destroy(pcap_send_queue *queue)
1804 {
1805         free(queue->buffer);
1806         free(queue);
1807 }
1808
1809 int
1810 pcap_sendqueue_queue(pcap_send_queue *queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
1811 {
1812         if (queue->len + sizeof(struct pcap_pkthdr) + pkt_header->caplen > queue->maxlen){
1813                 return (-1);
1814         }
1815
1816         /* Copy the pcap_pkthdr header*/
1817         memcpy(queue->buffer + queue->len, pkt_header, sizeof(struct pcap_pkthdr));
1818         queue->len += sizeof(struct pcap_pkthdr);
1819
1820         /* copy the packet */
1821         memcpy(queue->buffer + queue->len, pkt_data, pkt_header->caplen);
1822         queue->len += pkt_header->caplen;
1823
1824         return (0);
1825 }
1826
1827 u_int
1828 pcap_sendqueue_transmit(pcap_t *p, pcap_send_queue *queue, int sync)
1829 {
1830         return (p->sendqueue_transmit_op(p, queue, sync));
1831 }
1832
1833 static u_int
1834 pcap_sendqueue_transmit_dead(pcap_t *p, pcap_send_queue *queue, int sync)
1835 {
1836         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1837             "Packets cannot be transmitted on a pcap_open_dead pcap_t");
1838         return (0);
1839 }
1840
1841 int
1842 pcap_setuserbuffer(pcap_t *p, int size)
1843 {
1844         return (p->setuserbuffer_op(p, size));
1845 }
1846
1847 static int
1848 pcap_setuserbuffer_dead(pcap_t *p, int size)
1849 {
1850         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1851             "The user buffer cannot be set on a pcap_open_dead pcap_t");
1852         return (-1);
1853 }
1854
1855 int
1856 pcap_live_dump(pcap_t *p, char *filename, int maxsize, int maxpacks)
1857 {
1858         return (p->live_dump_op(p, filename, maxsize, maxpacks));
1859 }
1860
1861 static int
1862 pcap_live_dump_dead(pcap_t *p, char *filename, int maxsize, int maxpacks)
1863 {
1864         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1865             "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
1866         return (-1);
1867 }
1868
1869 int
1870 pcap_live_dump_ended(pcap_t *p, int sync)
1871 {
1872         return (p->live_dump_ended_op(p, sync));
1873 }
1874
1875 static int
1876 pcap_live_dump_ended_dead(pcap_t *p, int sync)
1877 {
1878         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1879             "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
1880         return (-1);
1881 }
1882
1883 PAirpcapHandle
1884 pcap_get_airpcap_handle(pcap_t *p)
1885 {
1886         PAirpcapHandle handle;
1887
1888         handle = p->get_airpcap_handle_op(p);
1889         if (handle == NULL) {
1890                 (void)pcap_snprintf(p->errbuf, sizeof(p->errbuf),
1891                     "This isn't an AirPcap device");
1892         }
1893         return (handle);
1894 }
1895
1896 static PAirpcapHandle
1897 pcap_get_airpcap_handle_dead(pcap_t *p)
1898 {
1899         return (NULL);
1900 }
1901 #endif
1902
1903 /*
1904  * On some platforms, we need to clean up promiscuous or monitor mode
1905  * when we close a device - and we want that to happen even if the
1906  * application just exits without explicitl closing devices.
1907  * On those platforms, we need to register a "close all the pcaps"
1908  * routine to be called when we exit, and need to maintain a list of
1909  * pcaps that need to be closed to clean up modes.
1910  *
1911  * XXX - not thread-safe.
1912  */
1913
1914 /*
1915  * List of pcaps on which we've done something that needs to be
1916  * cleaned up.
1917  * If there are any such pcaps, we arrange to call "pcap_close_all()"
1918  * when we exit, and have it close all of them.
1919  */
1920 static struct pcap *pcaps_to_close;
1921
1922 /*
1923  * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
1924  * be called on exit.
1925  */
1926 static int did_atexit;
1927
1928 static void
1929 pcap_close_all(void)
1930 {
1931         struct pcap *handle;
1932
1933         while ((handle = pcaps_to_close) != NULL)
1934                 pcap_close(handle);
1935 }
1936
1937 int
1938 pcap_do_addexit(pcap_t *p)
1939 {
1940         /*
1941          * If we haven't already done so, arrange to have
1942          * "pcap_close_all()" called when we exit.
1943          */
1944         if (!did_atexit) {
1945                 if (atexit(pcap_close_all) != 0) {
1946                         /*
1947                          * "atexit()" failed; let our caller know.
1948                          */
1949                         strlcpy(p->errbuf, "atexit failed", PCAP_ERRBUF_SIZE);
1950                         return (0);
1951                 }
1952                 did_atexit = 1;
1953         }
1954         return (1);
1955 }
1956
1957 void
1958 pcap_add_to_pcaps_to_close(pcap_t *p)
1959 {
1960         p->next = pcaps_to_close;
1961         pcaps_to_close = p;
1962 }
1963
1964 void
1965 pcap_remove_from_pcaps_to_close(pcap_t *p)
1966 {
1967         pcap_t *pc, *prevpc;
1968
1969         for (pc = pcaps_to_close, prevpc = NULL; pc != NULL;
1970             prevpc = pc, pc = pc->next) {
1971                 if (pc == p) {
1972                         /*
1973                          * Found it.  Remove it from the list.
1974                          */
1975                         if (prevpc == NULL) {
1976                                 /*
1977                                  * It was at the head of the list.
1978                                  */
1979                                 pcaps_to_close = pc->next;
1980                         } else {
1981                                 /*
1982                                  * It was in the middle of the list.
1983                                  */
1984                                 prevpc->next = pc->next;
1985                         }
1986                         break;
1987                 }
1988         }
1989 }
1990
1991 void
1992 pcap_cleanup_live_common(pcap_t *p)
1993 {
1994         if (p->buffer != NULL) {
1995                 free(p->buffer);
1996                 p->buffer = NULL;
1997         }
1998         if (p->dlt_list != NULL) {
1999                 free(p->dlt_list);
2000                 p->dlt_list = NULL;
2001                 p->dlt_count = 0;
2002         }
2003         if (p->tstamp_type_list != NULL) {
2004                 free(p->tstamp_type_list);
2005                 p->tstamp_type_list = NULL;
2006                 p->tstamp_type_count = 0;
2007         }
2008         if (p->tstamp_precision_list != NULL) {
2009                 free(p->tstamp_precision_list);
2010                 p->tstamp_precision_list = NULL;
2011                 p->tstamp_precision_count = 0;
2012         }
2013         pcap_freecode(&p->fcode);
2014 #if !defined(_WIN32) && !defined(MSDOS)
2015         if (p->fd >= 0) {
2016                 close(p->fd);
2017                 p->fd = -1;
2018         }
2019         p->selectable_fd = -1;
2020 #endif
2021 }
2022
2023 static void
2024 pcap_cleanup_dead(pcap_t *p _U_)
2025 {
2026         /* Nothing to do. */
2027 }
2028
2029 pcap_t *
2030 pcap_open_dead_with_tstamp_precision(int linktype, int snaplen, u_int precision)
2031 {
2032         pcap_t *p;
2033
2034         switch (precision) {
2035
2036         case PCAP_TSTAMP_PRECISION_MICRO:
2037         case PCAP_TSTAMP_PRECISION_NANO:
2038                 break;
2039
2040         default:
2041                 return NULL;
2042         }
2043         p = malloc(sizeof(*p));
2044         if (p == NULL)
2045                 return NULL;
2046         memset (p, 0, sizeof(*p));
2047         p->snapshot = snaplen;
2048         p->linktype = linktype;
2049         p->opt.tstamp_precision = precision;
2050         p->stats_op = pcap_stats_dead;
2051 #ifdef _WIN32
2052         p->stats_ex_op = (stats_ex_op_t)pcap_not_initialized_ptr;
2053         p->setbuff_op = pcap_setbuff_dead;
2054         p->setmode_op = pcap_setmode_dead;
2055         p->setmintocopy_op = pcap_setmintocopy_dead;
2056         p->getevent_op = pcap_getevent_dead;
2057         p->oid_get_request_op = pcap_oid_get_request_dead;
2058         p->oid_set_request_op = pcap_oid_set_request_dead;
2059         p->sendqueue_transmit_op = pcap_sendqueue_transmit_dead;
2060         p->setuserbuffer_op = pcap_setuserbuffer_dead;
2061         p->live_dump_op = pcap_live_dump_dead;
2062         p->live_dump_ended_op = pcap_live_dump_ended_dead;
2063         p->get_airpcap_handle_op = pcap_get_airpcap_handle_dead;
2064 #endif
2065         p->cleanup_op = pcap_cleanup_dead;
2066
2067         /*
2068          * A "dead" pcap_t never requires special BPF code generation.
2069          */
2070         p->bpf_codegen_flags = 0;
2071
2072         p->activated = 1;
2073         return (p);
2074 }
2075
2076 pcap_t *
2077 pcap_open_dead(int linktype, int snaplen)
2078 {
2079         return (pcap_open_dead_with_tstamp_precision(linktype, snaplen,
2080             PCAP_TSTAMP_PRECISION_MICRO));
2081 }
2082
2083 /*
2084  * API compatible with WinPcap's "send a packet" routine - returns -1
2085  * on error, 0 otherwise.
2086  *
2087  * XXX - what if we get a short write?
2088  */
2089 int
2090 pcap_sendpacket(pcap_t *p, const u_char *buf, int size)
2091 {
2092         if (p->inject_op(p, buf, size) == -1)
2093                 return (-1);
2094         return (0);
2095 }
2096
2097 /*
2098  * API compatible with OpenBSD's "send a packet" routine - returns -1 on
2099  * error, number of bytes written otherwise.
2100  */
2101 int
2102 pcap_inject(pcap_t *p, const void *buf, size_t size)
2103 {
2104         return (p->inject_op(p, buf, size));
2105 }
2106
2107 void
2108 pcap_close(pcap_t *p)
2109 {
2110         if (p->opt.device != NULL)
2111                 free(p->opt.device);
2112         p->cleanup_op(p);
2113         free(p);
2114 }
2115
2116 /*
2117  * Given a BPF program, a pcap_pkthdr structure for a packet, and the raw
2118  * data for the packet, check whether the packet passes the filter.
2119  * Returns the return value of the filter program, which will be zero if
2120  * the packet doesn't pass and non-zero if the packet does pass.
2121  */
2122 int
2123 pcap_offline_filter(const struct bpf_program *fp, const struct pcap_pkthdr *h,
2124     const u_char *pkt)
2125 {
2126         const struct bpf_insn *fcode = fp->bf_insns;
2127
2128         if (fcode != NULL)
2129                 return (bpf_filter(fcode, pkt, h->len, h->caplen));
2130         else
2131                 return (0);
2132 }
2133
2134 #include "pcap_version.h"
2135
2136 #ifdef _WIN32
2137
2138 static char *full_pcap_version_string;
2139
2140 #ifdef HAVE_VERSION_H
2141 /*
2142  * libpcap being built for Windows, as part of a WinPcap/Npcap source
2143  * tree.  Include version.h from that source tree to get the WinPcap/Npcap
2144  * version.
2145  *
2146  * XXX - it'd be nice if we could somehow generate the WinPcap version number
2147  * when building WinPcap.  (It'd be nice to do so for the packet.dll version
2148  * number as well.)
2149  */
2150 #include "../../version.h"
2151
2152 static const char wpcap_version_string[] = WINPCAP_VER_STRING;
2153 static const char pcap_version_string_fmt[] =
2154         WINPCAP_PRODUCT_NAME " version %s, based on %s";
2155 static const char pcap_version_string_packet_dll_fmt[] =
2156         WINPCAP_PRODUCT_NAME " version %s (packet.dll version %s), based on %s";
2157
2158 const char *
2159 pcap_lib_version(void)
2160 {
2161         char *packet_version_string;
2162         size_t full_pcap_version_string_len;
2163
2164         if (full_pcap_version_string == NULL) {
2165                 /*
2166                  * Generate the version string.
2167                  */
2168                 packet_version_string = PacketGetVersion();
2169                 if (strcmp(wpcap_version_string, packet_version_string) == 0) {
2170                         /*
2171                          * WinPcap version string and packet.dll version
2172                          * string are the same; just report the WinPcap
2173                          * version.
2174                          */
2175                         full_pcap_version_string_len =
2176                             (sizeof pcap_version_string_fmt - 4) +
2177                             strlen(wpcap_version_string) +
2178                             strlen(pcap_version_string);
2179                         full_pcap_version_string =
2180                             malloc(full_pcap_version_string_len);
2181                         if (full_pcap_version_string == NULL)
2182                                 return (NULL);
2183                         pcap_snprintf(full_pcap_version_string,
2184                             full_pcap_version_string_len,
2185                             pcap_version_string_fmt,
2186                             wpcap_version_string,
2187                             pcap_version_string);
2188                 } else {
2189                         /*
2190                          * WinPcap version string and packet.dll version
2191                          * string are different; that shouldn't be the
2192                          * case (the two libraries should come from the
2193                          * same version of WinPcap), so we report both
2194                          * versions.
2195                          */
2196                         full_pcap_version_string_len =
2197                             (sizeof pcap_version_string_packet_dll_fmt - 6) +
2198                             strlen(wpcap_version_string) +
2199                             strlen(packet_version_string) +
2200                             strlen(pcap_version_string);
2201                         full_pcap_version_string = malloc(full_pcap_version_string_len);
2202                         if (full_pcap_version_string == NULL)
2203                                 return (NULL);
2204                         pcap_snprintf(full_pcap_version_string,
2205                             full_pcap_version_string_len,
2206                             pcap_version_string_packet_dll_fmt,
2207                             wpcap_version_string,
2208                             packet_version_string,
2209                             pcap_version_string);
2210                 }
2211         }
2212         return (full_pcap_version_string);
2213 }
2214
2215 #else /* HAVE_VERSION_H */
2216
2217 /*
2218  * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2219  * tree.
2220  */
2221 static const char pcap_version_string_packet_dll_fmt[] =
2222         "%s (packet.dll version %s)";
2223 const char *
2224 pcap_lib_version(void)
2225 {
2226         char *packet_version_string;
2227         size_t full_pcap_version_string_len;
2228
2229         if (full_pcap_version_string == NULL) {
2230                 /*
2231                  * Generate the version string.  Report the packet.dll
2232                  * version.
2233                  */
2234                 packet_version_string = PacketGetVersion();
2235                 full_pcap_version_string_len =
2236                     (sizeof pcap_version_string_packet_dll_fmt - 4) +
2237                     strlen(pcap_version_string) +
2238                     strlen(packet_version_string);
2239                 full_pcap_version_string = malloc(full_pcap_version_string_len);
2240                 if (full_pcap_version_string == NULL)
2241                         return (NULL);
2242                 pcap_snprintf(full_pcap_version_string,
2243                     full_pcap_version_string_len,
2244                     pcap_version_string_packet_dll_fmt,
2245                     pcap_version_string,
2246                     packet_version_string);
2247         }
2248         return (full_pcap_version_string);
2249 }
2250
2251 #endif /* HAVE_VERSION_H */
2252
2253 #elif defined(MSDOS)
2254
2255 static char *full_pcap_version_string;
2256
2257 const char *
2258 pcap_lib_version (void)
2259 {
2260         char *packet_version_string;
2261         size_t full_pcap_version_string_len;
2262         static char dospfx[] = "DOS-";
2263
2264         if (full_pcap_version_string == NULL) {
2265                 /*
2266                  * Generate the version string.
2267                  */
2268                 full_pcap_version_string_len =
2269                     sizeof dospfx + strlen(pcap_version_string);
2270                 full_pcap_version_string =
2271                     malloc(full_pcap_version_string_len);
2272                 if (full_pcap_version_string == NULL)
2273                         return (NULL);
2274                 strcpy(full_pcap_version_string, dospfx);
2275                 strcat(full_pcap_version_string, pcap_version_string);
2276         }
2277         return (full_pcap_version_string);
2278 }
2279
2280 #else /* UN*X */
2281
2282 const char *
2283 pcap_lib_version(void)
2284 {
2285         return (pcap_version_string);
2286 }
2287 #endif
2288
2289 #ifdef YYDEBUG
2290 /*
2291  * Set the internal "debug printout" flag for the filter expression parser.
2292  * The code to print that stuff is present only if YYDEBUG is defined, so
2293  * the flag, and the routine to set it, are defined only if YYDEBUG is
2294  * defined.
2295  *
2296  * This is intended for libpcap developers, not for general use.
2297  * If you want to set these in a program, you'll have to declare this
2298  * routine yourself, with the appropriate DLL import attribute on Windows;
2299  * it's not declared in any header file, and won't be declared in any
2300  * header file provided by libpcap.
2301  */
2302 PCAP_API void pcap_set_parser_debug(int value);
2303
2304 PCAP_API_DEF void
2305 pcap_set_parser_debug(int value)
2306 {
2307         extern int pcap_debug;
2308
2309         pcap_debug = value;
2310 }
2311 #endif
2312
2313 #ifdef BDEBUG
2314 /*
2315  * Set the internal "debug printout" flag for the filter expression optimizer.
2316  * The code to print that stuff is present only if BDEBUG is defined, so
2317  * the flag, and the routine to set it, are defined only if BDEBUG is
2318  * defined.
2319  *
2320  * This is intended for libpcap developers, not for general use.
2321  * If you want to set these in a program, you'll have to declare this
2322  * routine yourself, with the appropriate DLL import attribute on Windows;
2323  * it's not declared in any header file, and won't be declared in any
2324  * header file provided by libpcap.
2325  */
2326 PCAP_API void pcap_set_optimizer_debug(int value);
2327
2328 PCAP_API_DEF void
2329 pcap_set_optimizer_debug(int value)
2330 {
2331         extern int pcap_optimizer_debug;
2332
2333         pcap_optimizer_debug = value;
2334 }
2335 #endif