]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libpcap/pcap-npf.c
Remove spurious newline
[FreeBSD/FreeBSD.git] / contrib / libpcap / pcap-npf.c
1 /*
2  * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3  * Copyright (c) 2005 - 2010 CACE Technologies, Davis (California)
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
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. Neither the name of the Politecnico di Torino, CACE Technologies
16  * nor the names of its contributors may be used to endorse or promote
17  * products derived from this software without specific prior written
18  * permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #include <errno.h>
39 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
40 #include <Packet32.h>
41 #include <pcap-int.h>
42 #include <pcap/dlt.h>
43
44 /* Old-school MinGW have these headers in a different place.
45  */
46 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
47   #include <ddk/ntddndis.h>
48   #include <ddk/ndis.h>
49 #else
50   #include <ntddndis.h>  /* MSVC/TDM-MinGW/MinGW64 */
51 #endif
52
53 #ifdef HAVE_DAG_API
54   #include <dagnew.h>
55   #include <dagapi.h>
56 #endif /* HAVE_DAG_API */
57
58 static int pcap_setfilter_npf(pcap_t *, struct bpf_program *);
59 static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
60 static int pcap_getnonblock_npf(pcap_t *);
61 static int pcap_setnonblock_npf(pcap_t *, int);
62
63 /*dimension of the buffer in the pcap_t structure*/
64 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
65
66 /*dimension of the buffer in the kernel driver NPF */
67 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
68
69 /* Equivalent to ntohs(), but a lot faster under Windows */
70 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
71
72 /*
73  * Private data for capturing on WinPcap devices.
74  */
75 struct pcap_win {
76         ADAPTER *adapter;               /* the packet32 ADAPTER for the device */
77         int nonblock;
78         int rfmon_selfstart;            /* a flag tells whether the monitor mode is set by itself */
79         int filtering_in_kernel;        /* using kernel filter */
80
81 #ifdef HAVE_DAG_API
82         int     dag_fcs_bits;           /* Number of checksum bits from link layer */
83 #endif
84
85 #ifdef ENABLE_REMOTE
86         int samp_npkt;                  /* parameter needed for sampling, with '1 out of N' method has been requested */
87         struct timeval samp_time;       /* parameter needed for sampling, with '1 every N ms' method has been requested */
88 #endif
89 };
90
91 /*
92  * Define stub versions of the monitor-mode support routines if this
93  * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
94  * WinPcap.
95  */
96 #ifndef HAVE_NPCAP_PACKET_API
97 static int
98 PacketIsMonitorModeSupported(PCHAR AdapterName _U_)
99 {
100         /*
101          * We don't support monitor mode.
102          */
103         return (0);
104 }
105
106 static int
107 PacketSetMonitorMode(PCHAR AdapterName _U_, int mode _U_)
108 {
109         /*
110          * This should never be called, as PacketIsMonitorModeSupported()
111          * will return 0, meaning "we don't support monitor mode, so
112          * don't try to turn it on or off".
113          */
114         return (0);
115 }
116
117 static int
118 PacketGetMonitorMode(PCHAR AdapterName _U_)
119 {
120         /*
121          * This should fail, so that pcap_activate_npf() returns
122          * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
123          * mode.
124          */
125         return (-1);
126 }
127 #endif
128
129 /*
130  * Sigh.  PacketRequest() will have made a DeviceIoControl()
131  * call to the NPF driver to perform the OID request, with a
132  * BIOCQUERYOID ioctl.  The kernel code should get back one
133  * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
134  * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
135  * supported by the OS or the driver, but that doesn't seem
136  * to make it to the caller of PacketRequest() in a
137  * reiable fashion.
138  */
139 #define NDIS_STATUS_INVALID_OID         0xc0010017
140 #define NDIS_STATUS_NOT_SUPPORTED       0xc00000bb      /* STATUS_NOT_SUPPORTED */
141 #define NDIS_STATUS_NOT_RECOGNIZED      0x00010001
142
143 static int
144 oid_get_request(ADAPTER *adapter, bpf_u_int32 oid, void *data, size_t *lenp,
145     char *errbuf)
146 {
147         PACKET_OID_DATA *oid_data_arg;
148
149         /*
150          * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
151          * It should be big enough to hold "*lenp" bytes of data; it
152          * will actually be slightly larger, as PACKET_OID_DATA has a
153          * 1-byte data array at the end, standing in for the variable-length
154          * data that's actually there.
155          */
156         oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
157         if (oid_data_arg == NULL) {
158                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
159                     "Couldn't allocate argument buffer for PacketRequest");
160                 return (PCAP_ERROR);
161         }
162
163         /*
164          * No need to copy the data - we're doing a fetch.
165          */
166         oid_data_arg->Oid = oid;
167         oid_data_arg->Length = (ULONG)(*lenp);  /* XXX - check for ridiculously large value? */
168         if (!PacketRequest(adapter, FALSE, oid_data_arg)) {
169                 char errmsgbuf[PCAP_ERRBUF_SIZE+1];
170
171                 pcap_win32_err_to_str(GetLastError(), errmsgbuf);
172                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
173                     "Error calling PacketRequest: %s", errmsgbuf);
174                 free(oid_data_arg);
175                 return (-1);
176         }
177
178         /*
179          * Get the length actually supplied.
180          */
181         *lenp = oid_data_arg->Length;
182
183         /*
184          * Copy back the data we fetched.
185          */
186         memcpy(data, oid_data_arg->Data, *lenp);
187         free(oid_data_arg);
188         return (0);
189 }
190
191 static int
192 pcap_stats_npf(pcap_t *p, struct pcap_stat *ps)
193 {
194         struct pcap_win *pw = p->priv;
195         struct bpf_stat bstats;
196         char errbuf[PCAP_ERRBUF_SIZE+1];
197
198         /*
199          * Try to get statistics.
200          *
201          * (Please note - "struct pcap_stat" is *not* the same as
202          * WinPcap's "struct bpf_stat". It might currently have the
203          * same layout, but let's not cheat.
204          *
205          * Note also that we don't fill in ps_capt, as we might have
206          * been called by code compiled against an earlier version of
207          * WinPcap that didn't have ps_capt, in which case filling it
208          * in would stomp on whatever comes after the structure passed
209          * to us.
210          */
211         if (!PacketGetStats(pw->adapter, &bstats)) {
212                 pcap_win32_err_to_str(GetLastError(), errbuf);
213                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
214                     "PacketGetStats error: %s", errbuf);
215                 return (-1);
216         }
217         ps->ps_recv = bstats.bs_recv;
218         ps->ps_drop = bstats.bs_drop;
219
220         /*
221          * XXX - PacketGetStats() doesn't fill this in, so we just
222          * return 0.
223          */
224 #if 0
225         ps->ps_ifdrop = bstats.ps_ifdrop;
226 #else
227         ps->ps_ifdrop = 0;
228 #endif
229
230         return (0);
231 }
232
233 /*
234  * Win32-only routine for getting statistics.
235  *
236  * This way is definitely safer than passing the pcap_stat * from the userland.
237  * In fact, there could happen than the user allocates a variable which is not
238  * big enough for the new structure, and the library will write in a zone
239  * which is not allocated to this variable.
240  *
241  * In this way, we're pretty sure we are writing on memory allocated to this
242  * variable.
243  *
244  * XXX - but this is the wrong way to handle statistics.  Instead, we should
245  * have an API that returns data in a form like the Options section of a
246  * pcapng Interface Statistics Block:
247  *
248  *    http://xml2rfc.tools.ietf.org/cgi-bin/xml2rfc.cgi?url=https://raw.githubusercontent.com/pcapng/pcapng/master/draft-tuexen-opsawg-pcapng.xml&modeAsFormat=html/ascii&type=ascii#rfc.section.4.6
249  *
250  * which would let us add new statistics straightforwardly and indicate which
251  * statistics we are and are *not* providing, rather than having to provide
252  * possibly-bogus values for statistics we can't provide.
253  */
254 struct pcap_stat *
255 pcap_stats_ex_npf(pcap_t *p, int *pcap_stat_size)
256 {
257         struct pcap_win *pw = p->priv;
258         struct bpf_stat bstats;
259         char errbuf[PCAP_ERRBUF_SIZE+1];
260
261         *pcap_stat_size = sizeof (p->stat);
262
263         /*
264          * Try to get statistics.
265          *
266          * (Please note - "struct pcap_stat" is *not* the same as
267          * WinPcap's "struct bpf_stat". It might currently have the
268          * same layout, but let's not cheat.)
269          */
270         if (!PacketGetStatsEx(pw->adapter, &bstats)) {
271                 pcap_win32_err_to_str(GetLastError(), errbuf);
272                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
273                     "PacketGetStatsEx error: %s", errbuf);
274                 return (NULL);
275         }
276         p->stat.ps_recv = bstats.bs_recv;
277         p->stat.ps_drop = bstats.bs_drop;
278         p->stat.ps_ifdrop = bstats.ps_ifdrop;
279 #ifdef ENABLE_REMOTE
280         p->stat.ps_capt = bstats.bs_capt;
281 #endif
282         return (&p->stat);
283 }
284
285 /* Set the dimension of the kernel-level capture buffer */
286 static int
287 pcap_setbuff_npf(pcap_t *p, int dim)
288 {
289         struct pcap_win *pw = p->priv;
290
291         if(PacketSetBuff(pw->adapter,dim)==FALSE)
292         {
293                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
294                 return (-1);
295         }
296         return (0);
297 }
298
299 /* Set the driver working mode */
300 static int
301 pcap_setmode_npf(pcap_t *p, int mode)
302 {
303         struct pcap_win *pw = p->priv;
304
305         if(PacketSetMode(pw->adapter,mode)==FALSE)
306         {
307                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
308                 return (-1);
309         }
310
311         return (0);
312 }
313
314 /*set the minimum amount of data that will release a read call*/
315 static int
316 pcap_setmintocopy_npf(pcap_t *p, int size)
317 {
318         struct pcap_win *pw = p->priv;
319
320         if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
321         {
322                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
323                 return (-1);
324         }
325         return (0);
326 }
327
328 static HANDLE
329 pcap_getevent_npf(pcap_t *p)
330 {
331         struct pcap_win *pw = p->priv;
332
333         return (PacketGetReadEvent(pw->adapter));
334 }
335
336 static int
337 pcap_oid_get_request_npf(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
338 {
339         struct pcap_win *pw = p->priv;
340
341         return (oid_get_request(pw->adapter, oid, data, lenp, p->errbuf));
342 }
343
344 static int
345 pcap_oid_set_request_npf(pcap_t *p, bpf_u_int32 oid, const void *data,
346     size_t *lenp)
347 {
348         struct pcap_win *pw = p->priv;
349         PACKET_OID_DATA *oid_data_arg;
350         char errbuf[PCAP_ERRBUF_SIZE+1];
351
352         /*
353          * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
354          * It should be big enough to hold "*lenp" bytes of data; it
355          * will actually be slightly larger, as PACKET_OID_DATA has a
356          * 1-byte data array at the end, standing in for the variable-length
357          * data that's actually there.
358          */
359         oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
360         if (oid_data_arg == NULL) {
361                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
362                     "Couldn't allocate argument buffer for PacketRequest");
363                 return (PCAP_ERROR);
364         }
365
366         oid_data_arg->Oid = oid;
367         oid_data_arg->Length = (ULONG)(*lenp);  /* XXX - check for ridiculously large value? */
368         memcpy(oid_data_arg->Data, data, *lenp);
369         if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
370                 pcap_win32_err_to_str(GetLastError(), errbuf);
371                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
372                     "Error calling PacketRequest: %s", errbuf);
373                 free(oid_data_arg);
374                 return (PCAP_ERROR);
375         }
376
377         /*
378          * Get the length actually copied.
379          */
380         *lenp = oid_data_arg->Length;
381
382         /*
383          * No need to copy the data - we're doing a set.
384          */
385         free(oid_data_arg);
386         return (0);
387 }
388
389 static u_int
390 pcap_sendqueue_transmit_npf(pcap_t *p, pcap_send_queue *queue, int sync)
391 {
392         struct pcap_win *pw = p->priv;
393         u_int res;
394         char errbuf[PCAP_ERRBUF_SIZE+1];
395
396         if (pw->adapter==NULL) {
397                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
398                     "Cannot transmit a queue to an offline capture or to a TurboCap port");
399                 return (0);
400         }
401
402         res = PacketSendPackets(pw->adapter,
403                 queue->buffer,
404                 queue->len,
405                 (BOOLEAN)sync);
406
407         if(res != queue->len){
408                 pcap_win32_err_to_str(GetLastError(), errbuf);
409                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
410                     "Error opening adapter: %s", errbuf);
411         }
412
413         return (res);
414 }
415
416 static int
417 pcap_setuserbuffer_npf(pcap_t *p, int size)
418 {
419         unsigned char *new_buff;
420
421         if (size<=0) {
422                 /* Bogus parameter */
423                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
424                     "Error: invalid size %d",size);
425                 return (-1);
426         }
427
428         /* Allocate the buffer */
429         new_buff=(unsigned char*)malloc(sizeof(char)*size);
430
431         if (!new_buff) {
432                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
433                     "Error: not enough memory");
434                 return (-1);
435         }
436
437         free(p->buffer);
438
439         p->buffer=new_buff;
440         p->bufsize=size;
441
442         return (0);
443 }
444
445 static int
446 pcap_live_dump_npf(pcap_t *p, char *filename, int maxsize, int maxpacks)
447 {
448         struct pcap_win *pw = p->priv;
449         BOOLEAN res;
450
451         /* Set the packet driver in dump mode */
452         res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
453         if(res == FALSE){
454                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
455                     "Error setting dump mode");
456                 return (-1);
457         }
458
459         /* Set the name of the dump file */
460         res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
461         if(res == FALSE){
462                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
463                     "Error setting kernel dump file name");
464                 return (-1);
465         }
466
467         /* Set the limits of the dump file */
468         res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
469         if(res == FALSE) {
470                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
471                                 "Error setting dump limit");
472                 return (-1);
473         }
474
475         return (0);
476 }
477
478 static int
479 pcap_live_dump_ended_npf(pcap_t *p, int sync)
480 {
481         struct pcap_win *pw = p->priv;
482
483         return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
484 }
485
486 static PAirpcapHandle
487 pcap_get_airpcap_handle_npf(pcap_t *p)
488 {
489 #ifdef HAVE_AIRPCAP_API
490         struct pcap_win *pw = p->priv;
491
492         return (PacketGetAirPcapHandle(pw->adapter));
493 #else
494         return (NULL);
495 #endif /* HAVE_AIRPCAP_API */
496 }
497
498 static int
499 pcap_read_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
500 {
501         PACKET Packet;
502         int cc;
503         int n = 0;
504         register u_char *bp, *ep;
505         u_char *datap;
506         struct pcap_win *pw = p->priv;
507
508         cc = p->cc;
509         if (p->cc == 0) {
510                 /*
511                  * Has "pcap_breakloop()" been called?
512                  */
513                 if (p->break_loop) {
514                         /*
515                          * Yes - clear the flag that indicates that it
516                          * has, and return PCAP_ERROR_BREAK to indicate
517                          * that we were told to break out of the loop.
518                          */
519                         p->break_loop = 0;
520                         return (PCAP_ERROR_BREAK);
521                 }
522
523                 /*
524                  * Capture the packets.
525                  *
526                  * The PACKET structure had a bunch of extra stuff for
527                  * Windows 9x/Me, but the only interesting data in it
528                  * in the versions of Windows that we support is just
529                  * a copy of p->buffer, a copy of p->buflen, and the
530                  * actual number of bytes read returned from
531                  * PacketReceivePacket(), none of which has to be
532                  * retained from call to call, so we just keep one on
533                  * the stack.
534                  */
535                 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
536                 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
537                         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
538                         return (PCAP_ERROR);
539                 }
540
541                 cc = Packet.ulBytesReceived;
542
543                 bp = p->buffer;
544         }
545         else
546                 bp = p->bp;
547
548         /*
549          * Loop through each packet.
550          */
551 #define bhp ((struct bpf_hdr *)bp)
552         ep = bp + cc;
553         for (;;) {
554                 register int caplen, hdrlen;
555
556                 /*
557                  * Has "pcap_breakloop()" been called?
558                  * If so, return immediately - if we haven't read any
559                  * packets, clear the flag and return PCAP_ERROR_BREAK
560                  * to indicate that we were told to break out of the loop,
561                  * otherwise leave the flag set, so that the *next* call
562                  * will break out of the loop without having read any
563                  * packets, and return the number of packets we've
564                  * processed so far.
565                  */
566                 if (p->break_loop) {
567                         if (n == 0) {
568                                 p->break_loop = 0;
569                                 return (PCAP_ERROR_BREAK);
570                         } else {
571                                 p->bp = bp;
572                                 p->cc = (int) (ep - bp);
573                                 return (n);
574                         }
575                 }
576                 if (bp >= ep)
577                         break;
578
579                 caplen = bhp->bh_caplen;
580                 hdrlen = bhp->bh_hdrlen;
581                 datap = bp + hdrlen;
582
583                 /*
584                  * Short-circuit evaluation: if using BPF filter
585                  * in kernel, no need to do it now - we already know
586                  * the packet passed the filter.
587                  *
588                  * XXX - bpf_filter() should always return TRUE if
589                  * handed a null pointer for the program, but it might
590                  * just try to "run" the filter, so we check here.
591                  */
592                 if (pw->filtering_in_kernel ||
593                     p->fcode.bf_insns == NULL ||
594                     bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
595 #ifdef ENABLE_REMOTE
596                         switch (p->rmt_samp.method) {
597
598                         case PCAP_SAMP_1_EVERY_N:
599                                 pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
600
601                                 /* Discard all packets that are not '1 out of N' */
602                                 if (pw->samp_npkt != 0) {
603                                         bp += Packet_WORDALIGN(caplen + hdrlen);
604                                         continue;
605                                 }
606                                 break;
607
608                         case PCAP_SAMP_FIRST_AFTER_N_MS:
609                             {
610                                 struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
611
612                                 /*
613                                  * Check if the timestamp of the arrived
614                                  * packet is smaller than our target time.
615                                  */
616                                 if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
617                                    (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
618                                         bp += Packet_WORDALIGN(caplen + hdrlen);
619                                         continue;
620                                 }
621
622                                 /*
623                                  * The arrived packet is suitable for being
624                                  * delivered to our caller, so let's update
625                                  * the target time.
626                                  */
627                                 pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
628                                 if (pw->samp_time.tv_usec > 1000000) {
629                                         pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
630                                         pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
631                                 }
632                             }
633                         }
634 #endif  /* ENABLE_REMOTE */
635
636                         /*
637                          * XXX A bpf_hdr matches a pcap_pkthdr.
638                          */
639                         (*callback)(user, (struct pcap_pkthdr*)bp, datap);
640                         bp += Packet_WORDALIGN(caplen + hdrlen);
641                         if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
642                                 p->bp = bp;
643                                 p->cc = (int) (ep - bp);
644                                 return (n);
645                         }
646                 } else {
647                         /*
648                          * Skip this packet.
649                          */
650                         bp += Packet_WORDALIGN(caplen + hdrlen);
651                 }
652         }
653 #undef bhp
654         p->cc = 0;
655         return (n);
656 }
657
658 #ifdef HAVE_DAG_API
659 static int
660 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
661 {
662         struct pcap_win *pw = p->priv;
663         PACKET Packet;
664         u_char *dp = NULL;
665         int     packet_len = 0, caplen = 0;
666         struct pcap_pkthdr      pcap_header;
667         u_char *endofbuf;
668         int n = 0;
669         dag_record_t *header;
670         unsigned erf_record_len;
671         ULONGLONG ts;
672         int cc;
673         unsigned swt;
674         unsigned dfp = pw->adapter->DagFastProcess;
675
676         cc = p->cc;
677         if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
678         {
679                 /*
680                  * Get new packets from the network.
681                  *
682                  * The PACKET structure had a bunch of extra stuff for
683                  * Windows 9x/Me, but the only interesting data in it
684                  * in the versions of Windows that we support is just
685                  * a copy of p->buffer, a copy of p->buflen, and the
686                  * actual number of bytes read returned from
687                  * PacketReceivePacket(), none of which has to be
688                  * retained from call to call, so we just keep one on
689                  * the stack.
690                  */
691                 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
692                 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
693                         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
694                         return (-1);
695                 }
696
697                 cc = Packet.ulBytesReceived;
698                 if(cc == 0)
699                         /* The timeout has expired but we no packets arrived */
700                         return (0);
701                 header = (dag_record_t*)pw->adapter->DagBuffer;
702         }
703         else
704                 header = (dag_record_t*)p->bp;
705
706         endofbuf = (char*)header + cc;
707
708         /*
709          * Cycle through the packets
710          */
711         do
712         {
713                 erf_record_len = SWAPS(header->rlen);
714                 if((char*)header + erf_record_len > endofbuf)
715                         break;
716
717                 /* Increase the number of captured packets */
718                 p->stat.ps_recv++;
719
720                 /* Find the beginning of the packet */
721                 dp = ((u_char *)header) + dag_record_size;
722
723                 /* Determine actual packet len */
724                 switch(header->type)
725                 {
726                 case TYPE_ATM:
727                         packet_len = ATM_SNAPLEN;
728                         caplen = ATM_SNAPLEN;
729                         dp += 4;
730
731                         break;
732
733                 case TYPE_ETH:
734                         swt = SWAPS(header->wlen);
735                         packet_len = swt - (pw->dag_fcs_bits);
736                         caplen = erf_record_len - dag_record_size - 2;
737                         if (caplen > packet_len)
738                         {
739                                 caplen = packet_len;
740                         }
741                         dp += 2;
742
743                         break;
744
745                 case TYPE_HDLC_POS:
746                         swt = SWAPS(header->wlen);
747                         packet_len = swt - (pw->dag_fcs_bits);
748                         caplen = erf_record_len - dag_record_size;
749                         if (caplen > packet_len)
750                         {
751                                 caplen = packet_len;
752                         }
753
754                         break;
755                 }
756
757                 if(caplen > p->snapshot)
758                         caplen = p->snapshot;
759
760                 /*
761                  * Has "pcap_breakloop()" been called?
762                  * If so, return immediately - if we haven't read any
763                  * packets, clear the flag and return -2 to indicate
764                  * that we were told to break out of the loop, otherwise
765                  * leave the flag set, so that the *next* call will break
766                  * out of the loop without having read any packets, and
767                  * return the number of packets we've processed so far.
768                  */
769                 if (p->break_loop)
770                 {
771                         if (n == 0)
772                         {
773                                 p->break_loop = 0;
774                                 return (-2);
775                         }
776                         else
777                         {
778                                 p->bp = (char*)header;
779                                 p->cc = endofbuf - (char*)header;
780                                 return (n);
781                         }
782                 }
783
784                 if(!dfp)
785                 {
786                         /* convert between timestamp formats */
787                         ts = header->ts;
788                         pcap_header.ts.tv_sec = (int)(ts >> 32);
789                         ts = (ts & 0xffffffffi64) * 1000000;
790                         ts += 0x80000000; /* rounding */
791                         pcap_header.ts.tv_usec = (int)(ts >> 32);
792                         if (pcap_header.ts.tv_usec >= 1000000) {
793                                 pcap_header.ts.tv_usec -= 1000000;
794                                 pcap_header.ts.tv_sec++;
795                         }
796                 }
797
798                 /* No underlaying filtering system. We need to filter on our own */
799                 if (p->fcode.bf_insns)
800                 {
801                         if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
802                         {
803                                 /* Move to next packet */
804                                 header = (dag_record_t*)((char*)header + erf_record_len);
805                                 continue;
806                         }
807                 }
808
809                 /* Fill the header for the user suppplied callback function */
810                 pcap_header.caplen = caplen;
811                 pcap_header.len = packet_len;
812
813                 /* Call the callback function */
814                 (*callback)(user, &pcap_header, dp);
815
816                 /* Move to next packet */
817                 header = (dag_record_t*)((char*)header + erf_record_len);
818
819                 /* Stop if the number of packets requested by user has been reached*/
820                 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
821                 {
822                         p->bp = (char*)header;
823                         p->cc = endofbuf - (char*)header;
824                         return (n);
825                 }
826         }
827         while((u_char*)header < endofbuf);
828
829         return (1);
830 }
831 #endif /* HAVE_DAG_API */
832
833 /* Send a packet to the network */
834 static int
835 pcap_inject_npf(pcap_t *p, const void *buf, size_t size)
836 {
837         struct pcap_win *pw = p->priv;
838         PACKET pkt;
839
840         PacketInitPacket(&pkt, (PVOID)buf, size);
841         if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
842                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
843                 return (-1);
844         }
845
846         /*
847          * We assume it all got sent if "PacketSendPacket()" succeeded.
848          * "pcap_inject()" is expected to return the number of bytes
849          * sent.
850          */
851         return ((int)size);
852 }
853
854 static void
855 pcap_cleanup_npf(pcap_t *p)
856 {
857         struct pcap_win *pw = p->priv;
858
859         if (pw->adapter != NULL) {
860                 PacketCloseAdapter(pw->adapter);
861                 pw->adapter = NULL;
862         }
863         if (pw->rfmon_selfstart)
864         {
865                 PacketSetMonitorMode(p->opt.device, 0);
866         }
867         pcap_cleanup_live_common(p);
868 }
869
870 static int
871 pcap_activate_npf(pcap_t *p)
872 {
873         struct pcap_win *pw = p->priv;
874         NetType type;
875         int res;
876         char errbuf[PCAP_ERRBUF_SIZE+1];
877
878         if (p->opt.rfmon) {
879                 /*
880                  * Monitor mode is supported on Windows Vista and later.
881                  */
882                 if (PacketGetMonitorMode(p->opt.device) == 1)
883                 {
884                         pw->rfmon_selfstart = 0;
885                 }
886                 else
887                 {
888                         if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
889                         {
890                                 pw->rfmon_selfstart = 0;
891                                 // Monitor mode is not supported.
892                                 if (res == 0)
893                                 {
894                                         return PCAP_ERROR_RFMON_NOTSUP;
895                                 }
896                                 else
897                                 {
898                                         return PCAP_ERROR;
899                                 }
900                         }
901                         else
902                         {
903                                 pw->rfmon_selfstart = 1;
904                         }
905                 }
906         }
907
908         /* Init WinSock */
909         pcap_wsockinit();
910
911         pw->adapter = PacketOpenAdapter(p->opt.device);
912
913         if (pw->adapter == NULL)
914         {
915                 /* Adapter detected but we are not able to open it. Return failure. */
916                 pcap_win32_err_to_str(GetLastError(), errbuf);
917                 if (pw->rfmon_selfstart)
918                 {
919                         PacketSetMonitorMode(p->opt.device, 0);
920                 }
921                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
922                     "Error opening adapter: %s", errbuf);
923                 return (PCAP_ERROR);
924         }
925
926         /*get network type*/
927         if(PacketGetNetType (pw->adapter,&type) == FALSE)
928         {
929                 pcap_win32_err_to_str(GetLastError(), errbuf);
930                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
931                     "Cannot determine the network type: %s", errbuf);
932                 goto bad;
933         }
934
935         /*Set the linktype*/
936         switch (type.LinkType)
937         {
938         case NdisMediumWan:
939                 p->linktype = DLT_EN10MB;
940                 break;
941
942         case NdisMedium802_3:
943                 p->linktype = DLT_EN10MB;
944                 /*
945                  * This is (presumably) a real Ethernet capture; give it a
946                  * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
947                  * that an application can let you choose it, in case you're
948                  * capturing DOCSIS traffic that a Cisco Cable Modem
949                  * Termination System is putting out onto an Ethernet (it
950                  * doesn't put an Ethernet header onto the wire, it puts raw
951                  * DOCSIS frames out on the wire inside the low-level
952                  * Ethernet framing).
953                  */
954                 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
955                 /*
956                  * If that fails, just leave the list empty.
957                  */
958                 if (p->dlt_list != NULL) {
959                         p->dlt_list[0] = DLT_EN10MB;
960                         p->dlt_list[1] = DLT_DOCSIS;
961                         p->dlt_count = 2;
962                 }
963                 break;
964
965         case NdisMediumFddi:
966                 p->linktype = DLT_FDDI;
967                 break;
968
969         case NdisMedium802_5:
970                 p->linktype = DLT_IEEE802;
971                 break;
972
973         case NdisMediumArcnetRaw:
974                 p->linktype = DLT_ARCNET;
975                 break;
976
977         case NdisMediumArcnet878_2:
978                 p->linktype = DLT_ARCNET;
979                 break;
980
981         case NdisMediumAtm:
982                 p->linktype = DLT_ATM_RFC1483;
983                 break;
984
985         case NdisMediumCHDLC:
986                 p->linktype = DLT_CHDLC;
987                 break;
988
989         case NdisMediumPPPSerial:
990                 p->linktype = DLT_PPP_SERIAL;
991                 break;
992
993         case NdisMediumNull:
994                 p->linktype = DLT_NULL;
995                 break;
996
997         case NdisMediumBare80211:
998                 p->linktype = DLT_IEEE802_11;
999                 break;
1000
1001         case NdisMediumRadio80211:
1002                 p->linktype = DLT_IEEE802_11_RADIO;
1003                 break;
1004
1005         case NdisMediumPpi:
1006                 p->linktype = DLT_PPI;
1007                 break;
1008
1009         default:
1010                 p->linktype = DLT_EN10MB;                       /*an unknown adapter is assumed to be ethernet*/
1011                 break;
1012         }
1013
1014         /*
1015          * Turn a negative snapshot value (invalid), a snapshot value of
1016          * 0 (unspecified), or a value bigger than the normal maximum
1017          * value, into the maximum allowed value.
1018          *
1019          * If some application really *needs* a bigger snapshot
1020          * length, we should just increase MAXIMUM_SNAPLEN.
1021          */
1022         if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1023                 p->snapshot = MAXIMUM_SNAPLEN;
1024
1025         /* Set promiscuous mode */
1026         if (p->opt.promisc)
1027         {
1028
1029                 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1030                 {
1031                         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
1032                         goto bad;
1033                 }
1034         }
1035         else
1036         {
1037                 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1038                  * protocols and all packets indicated by the NIC" but if no protocol
1039                  * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1040                  * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1041                  * capture incoming frames.
1042                  */
1043                 if (PacketSetHwFilter(pw->adapter,
1044                         NDIS_PACKET_TYPE_ALL_LOCAL |
1045                         NDIS_PACKET_TYPE_DIRECTED |
1046                         NDIS_PACKET_TYPE_BROADCAST |
1047                         NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1048                 {
1049                         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
1050                         goto bad;
1051                 }
1052         }
1053
1054         /* Set the buffer size */
1055         p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1056
1057         if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1058         {
1059         /*
1060          * Traditional Adapter
1061          */
1062                 /*
1063                  * If the buffer size wasn't explicitly set, default to
1064                  * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1065                  */
1066                 if (p->opt.buffer_size == 0)
1067                         p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1068
1069                 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1070                 {
1071                         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1072                         goto bad;
1073                 }
1074
1075                 p->buffer = malloc(p->bufsize);
1076                 if (p->buffer == NULL)
1077                 {
1078                         pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1079                             errno, "malloc");
1080                         goto bad;
1081                 }
1082
1083                 if (p->opt.immediate)
1084                 {
1085                         /* tell the driver to copy the buffer as soon as data arrives */
1086                         if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1087                         {
1088                                 pcap_win32_err_to_str(GetLastError(), errbuf);
1089                                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1090                                     "Error calling PacketSetMinToCopy: %s",
1091                                     errbuf);
1092                                 goto bad;
1093                         }
1094                 }
1095                 else
1096                 {
1097                         /* tell the driver to copy the buffer only if it contains at least 16K */
1098                         if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1099                         {
1100                                 pcap_win32_err_to_str(GetLastError(), errbuf);
1101                                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1102                                     "Error calling PacketSetMinToCopy: %s",
1103                                     errbuf);
1104                                 goto bad;
1105                         }
1106                 }
1107         } else {
1108                 /*
1109                  * Dag Card
1110                  */
1111 #ifdef HAVE_DAG_API
1112                 /*
1113                  * We have DAG support.
1114                  */
1115                 LONG    status;
1116                 HKEY    dagkey;
1117                 DWORD   lptype;
1118                 DWORD   lpcbdata;
1119                 int             postype = 0;
1120                 char    keyname[512];
1121
1122                 pcap_snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1123                         "SYSTEM\\CurrentControlSet\\Services\\DAG",
1124                         strstr(_strlwr(p->opt.device), "dag"));
1125                 do
1126                 {
1127                         status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1128                         if(status != ERROR_SUCCESS)
1129                                 break;
1130
1131                         status = RegQueryValueEx(dagkey,
1132                                 "PosType",
1133                                 NULL,
1134                                 &lptype,
1135                                 (char*)&postype,
1136                                 &lpcbdata);
1137
1138                         if(status != ERROR_SUCCESS)
1139                         {
1140                                 postype = 0;
1141                         }
1142
1143                         RegCloseKey(dagkey);
1144                 }
1145                 while(FALSE);
1146
1147
1148                 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1149
1150                 /* Set the length of the FCS associated to any packet. This value
1151                  * will be subtracted to the packet length */
1152                 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1153 #else /* HAVE_DAG_API */
1154                 /*
1155                  * No DAG support.
1156                  */
1157                 goto bad;
1158 #endif /* HAVE_DAG_API */
1159         }
1160
1161         PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1162
1163         /* disable loopback capture if requested */
1164         if (p->opt.nocapture_local)
1165         {
1166                 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1167                 {
1168                         pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1169                             "Unable to disable the capture of loopback packets.");
1170                         goto bad;
1171                 }
1172         }
1173
1174 #ifdef HAVE_DAG_API
1175         if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1176         {
1177                 /* install dag specific handlers for read and setfilter */
1178                 p->read_op = pcap_read_win32_dag;
1179                 p->setfilter_op = pcap_setfilter_win32_dag;
1180         }
1181         else
1182         {
1183 #endif /* HAVE_DAG_API */
1184                 /* install traditional npf handlers for read and setfilter */
1185                 p->read_op = pcap_read_npf;
1186                 p->setfilter_op = pcap_setfilter_npf;
1187 #ifdef HAVE_DAG_API
1188         }
1189 #endif /* HAVE_DAG_API */
1190         p->setdirection_op = NULL;      /* Not implemented. */
1191             /* XXX - can this be implemented on some versions of Windows? */
1192         p->inject_op = pcap_inject_npf;
1193         p->set_datalink_op = NULL;      /* can't change data link type */
1194         p->getnonblock_op = pcap_getnonblock_npf;
1195         p->setnonblock_op = pcap_setnonblock_npf;
1196         p->stats_op = pcap_stats_npf;
1197         p->stats_ex_op = pcap_stats_ex_npf;
1198         p->setbuff_op = pcap_setbuff_npf;
1199         p->setmode_op = pcap_setmode_npf;
1200         p->setmintocopy_op = pcap_setmintocopy_npf;
1201         p->getevent_op = pcap_getevent_npf;
1202         p->oid_get_request_op = pcap_oid_get_request_npf;
1203         p->oid_set_request_op = pcap_oid_set_request_npf;
1204         p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1205         p->setuserbuffer_op = pcap_setuserbuffer_npf;
1206         p->live_dump_op = pcap_live_dump_npf;
1207         p->live_dump_ended_op = pcap_live_dump_ended_npf;
1208         p->get_airpcap_handle_op = pcap_get_airpcap_handle_npf;
1209         p->cleanup_op = pcap_cleanup_npf;
1210
1211         /*
1212          * XXX - this is only done because WinPcap supported
1213          * pcap_fileno() returning the hFile HANDLE from the
1214          * ADAPTER structure.  We make no general guarantees
1215          * that the caller can do anything useful with it.
1216          *
1217          * (Not that we make any general guarantee of that
1218          * sort on UN*X, either, any more, given that not
1219          * all capture devices are regular OS network
1220          * interfaces.)
1221          */
1222         p->handle = pw->adapter->hFile;
1223
1224         return (0);
1225 bad:
1226         pcap_cleanup_npf(p);
1227         return (PCAP_ERROR);
1228 }
1229
1230 /*
1231 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1232 */
1233 static int
1234 pcap_can_set_rfmon_npf(pcap_t *p)
1235 {
1236         return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1237 }
1238
1239 pcap_t *
1240 pcap_create_interface(const char *device _U_, char *ebuf)
1241 {
1242         pcap_t *p;
1243
1244         p = pcap_create_common(ebuf, sizeof(struct pcap_win));
1245         if (p == NULL)
1246                 return (NULL);
1247
1248         p->activate_op = pcap_activate_npf;
1249         p->can_set_rfmon_op = pcap_can_set_rfmon_npf;
1250         return (p);
1251 }
1252
1253 static int
1254 pcap_setfilter_npf(pcap_t *p, struct bpf_program *fp)
1255 {
1256         struct pcap_win *pw = p->priv;
1257
1258         if(PacketSetBpf(pw->adapter,fp)==FALSE){
1259                 /*
1260                  * Kernel filter not installed.
1261                  *
1262                  * XXX - we don't know whether this failed because:
1263                  *
1264                  *  the kernel rejected the filter program as invalid,
1265                  *  in which case we should fall back on userland
1266                  *  filtering;
1267                  *
1268                  *  the kernel rejected the filter program as too big,
1269                  *  in which case we should again fall back on
1270                  *  userland filtering;
1271                  *
1272                  *  there was some other problem, in which case we
1273                  *  should probably report an error.
1274                  *
1275                  * For NPF devices, the Win32 status will be
1276                  * STATUS_INVALID_DEVICE_REQUEST for invalid
1277                  * filters, but I don't know what it'd be for
1278                  * other problems, and for some other devices
1279                  * it might not be set at all.
1280                  *
1281                  * So we just fall back on userland filtering in
1282                  * all cases.
1283                  */
1284
1285                 /*
1286                  * install_bpf_program() validates the program.
1287                  *
1288                  * XXX - what if we already have a filter in the kernel?
1289                  */
1290                 if (install_bpf_program(p, fp) < 0)
1291                         return (-1);
1292                 pw->filtering_in_kernel = 0;    /* filtering in userland */
1293                 return (0);
1294         }
1295
1296         /*
1297          * It worked.
1298          */
1299         pw->filtering_in_kernel = 1;    /* filtering in the kernel */
1300
1301         /*
1302          * Discard any previously-received packets, as they might have
1303          * passed whatever filter was formerly in effect, but might
1304          * not pass this filter (BIOCSETF discards packets buffered
1305          * in the kernel, so you can lose packets in any case).
1306          */
1307         p->cc = 0;
1308         return (0);
1309 }
1310
1311 /*
1312  * We filter at user level, since the kernel driver does't process the packets
1313  */
1314 static int
1315 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1316
1317         if(!fp)
1318         {
1319                 strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1320                 return (-1);
1321         }
1322
1323         /* Install a user level filter */
1324         if (install_bpf_program(p, fp) < 0)
1325                 return (-1);
1326
1327         return (0);
1328 }
1329
1330 static int
1331 pcap_getnonblock_npf(pcap_t *p)
1332 {
1333         struct pcap_win *pw = p->priv;
1334
1335         /*
1336          * XXX - if there were a PacketGetReadTimeout() call, we
1337          * would use it, and return 1 if the timeout is -1
1338          * and 0 otherwise.
1339          */
1340         return (pw->nonblock);
1341 }
1342
1343 static int
1344 pcap_setnonblock_npf(pcap_t *p, int nonblock)
1345 {
1346         struct pcap_win *pw = p->priv;
1347         int newtimeout;
1348         char win_errbuf[PCAP_ERRBUF_SIZE+1];
1349
1350         if (nonblock) {
1351                 /*
1352                  * Set the packet buffer timeout to -1 for non-blocking
1353                  * mode.
1354                  */
1355                 newtimeout = -1;
1356         } else {
1357                 /*
1358                  * Restore the timeout set when the device was opened.
1359                  * (Note that this may be -1, in which case we're not
1360                  * really leaving non-blocking mode.  However, although
1361                  * the timeout argument to pcap_set_timeout() and
1362                  * pcap_open_live() is an int, you're not supposed to
1363                  * supply a negative value, so that "shouldn't happen".)
1364                  */
1365                 newtimeout = p->opt.timeout;
1366         }
1367         if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1368                 pcap_win32_err_to_str(GetLastError(), win_errbuf);
1369                 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1370                     "PacketSetReadTimeout: %s", win_errbuf);
1371                 return (-1);
1372         }
1373         pw->nonblock = (newtimeout == -1);
1374         return (0);
1375 }
1376
1377 static int
1378 pcap_add_if_npf(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
1379     const char *description, char *errbuf)
1380 {
1381         pcap_if_t *curdev;
1382         npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1383         LONG if_addr_size;
1384         int res = 0;
1385
1386         if_addr_size = MAX_NETWORK_ADDRESSES;
1387
1388         /*
1389          * Add an entry for this interface, with no addresses.
1390          */
1391         curdev = add_dev(devlistp, name, flags, description, errbuf);
1392         if (curdev == NULL) {
1393                 /*
1394                  * Failure.
1395                  */
1396                 return (-1);
1397         }
1398
1399         /*
1400          * Get the list of addresses for the interface.
1401          */
1402         if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1403                 /*
1404                  * Failure.
1405                  *
1406                  * We don't return an error, because this can happen with
1407                  * NdisWan interfaces, and we want to supply them even
1408                  * if we can't supply their addresses.
1409                  *
1410                  * We return an entry with an empty address list.
1411                  */
1412                 return (0);
1413         }
1414
1415         /*
1416          * Now add the addresses.
1417          */
1418         while (if_addr_size-- > 0) {
1419                 /*
1420                  * "curdev" is an entry for this interface; add an entry for
1421                  * this address to its list of addresses.
1422                  */
1423                 res = add_addr_to_dev(curdev,
1424                     (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1425                     sizeof (struct sockaddr_storage),
1426                     (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1427                     sizeof (struct sockaddr_storage),
1428                     (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1429                     sizeof (struct sockaddr_storage),
1430                     NULL,
1431                     0,
1432                     errbuf);
1433                 if (res == -1) {
1434                         /*
1435                          * Failure.
1436                          */
1437                         break;
1438                 }
1439         }
1440
1441         return (res);
1442 }
1443
1444 static int
1445 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
1446 {
1447         char *name_copy;
1448         ADAPTER *adapter;
1449         int status;
1450         size_t len;
1451         NDIS_HARDWARE_STATUS hardware_status;
1452 #ifdef OID_GEN_PHYSICAL_MEDIUM
1453         NDIS_PHYSICAL_MEDIUM phys_medium;
1454         bpf_u_int32 gen_physical_medium_oids[] = {
1455   #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1456                 OID_GEN_PHYSICAL_MEDIUM_EX,
1457   #endif
1458                 OID_GEN_PHYSICAL_MEDIUM
1459         };
1460 #define N_GEN_PHYSICAL_MEDIUM_OIDS      (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1461         size_t i;
1462 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1463 #ifdef OID_GEN_LINK_STATE
1464         NDIS_LINK_STATE link_state;
1465 #endif
1466         int connect_status;
1467
1468         if (*flags & PCAP_IF_LOOPBACK) {
1469                 /*
1470                  * Loopback interface, so the connection status doesn't
1471                  * apply. and it's not wireless (or wired, for that
1472                  * matter...).  We presume it's up and running.
1473                  */
1474                 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING | PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1475                 return (0);
1476         }
1477
1478         /*
1479          * We need to open the adapter to get this information.
1480          *
1481          * XXX - PacketOpenAdapter() takes a non-const pointer
1482          * as an argument, so we make a copy of the argument and
1483          * pass that to it.
1484          */
1485         name_copy = strdup(name);
1486         adapter = PacketOpenAdapter(name_copy);
1487         free(name_copy);
1488         if (adapter == NULL) {
1489                 /*
1490                  * Give up; if they try to open this device, it'll fail.
1491                  */
1492                 return (0);
1493         }
1494
1495 #ifdef HAVE_AIRPCAP_API
1496         /*
1497          * Airpcap.sys do not support the below 'OID_GEN_x' values.
1498          * Just set these flags (and none of the '*flags' entered with).
1499          */
1500         if (PacketGetAirPcapHandle(adapter)) {
1501                 /*
1502                  * Must be "up" and "running" if the above if succeeded.
1503                  */
1504                 *flags = PCAP_IF_UP | PCAP_IF_RUNNING;
1505
1506                 /*
1507                  * An airpcap device is a wireless device (duh!)
1508                  */
1509                 *flags |= PCAP_IF_WIRELESS;
1510
1511                 /*
1512                  * A "network assosiation state" makes no sense for airpcap.
1513                  */
1514                 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1515                 PacketCloseAdapter(adapter);
1516                 return (0);
1517         }
1518 #endif
1519
1520         /*
1521          * Get the hardware status, and derive "up" and "running" from
1522          * that.
1523          */
1524         len = sizeof (hardware_status);
1525         status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
1526             &hardware_status, &len, errbuf);
1527         if (status == 0) {
1528                 switch (hardware_status) {
1529
1530                 case NdisHardwareStatusReady:
1531                         /*
1532                          * "Available and capable of sending and receiving
1533                          * data over the wire", so up and running.
1534                          */
1535                         *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1536                         break;
1537
1538                 case NdisHardwareStatusInitializing:
1539                 case NdisHardwareStatusReset:
1540                         /*
1541                          * "Initializing" or "Resetting", so up, but
1542                          * not running.
1543                          */
1544                         *flags |= PCAP_IF_UP;
1545                         break;
1546
1547                 case NdisHardwareStatusClosing:
1548                 case NdisHardwareStatusNotReady:
1549                         /*
1550                          * "Closing" or "Not ready", so neither up nor
1551                          * running.
1552                          */
1553                         break;
1554                 }
1555         } else {
1556                 /*
1557                  * Can't get the hardware status, so assume both up and
1558                  * running.
1559                  */
1560                 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1561         }
1562
1563         /*
1564          * Get the network type.
1565          */
1566 #ifdef OID_GEN_PHYSICAL_MEDIUM
1567         /*
1568          * Try the OIDs we have for this, in order.
1569          */
1570         for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
1571                 len = sizeof (phys_medium);
1572                 status = oid_get_request(adapter, gen_physical_medium_oids[i],
1573                     &phys_medium, &len, errbuf);
1574                 if (status == 0) {
1575                         /*
1576                          * Success.
1577                          */
1578                         break;
1579                 }
1580                 /*
1581                  * Failed.  We can't determine whether it failed
1582                  * because that particular OID isn't supported
1583                  * or because some other problem occurred, so we
1584                  * just drive on and try the next OID.
1585                  */
1586         }
1587         if (status == 0) {
1588                 /*
1589                  * We got the physical medium.
1590                  */
1591                 switch (phys_medium) {
1592
1593                 case NdisPhysicalMediumWirelessLan:
1594                 case NdisPhysicalMediumWirelessWan:
1595                 case NdisPhysicalMediumNative802_11:
1596                 case NdisPhysicalMediumBluetooth:
1597                 case NdisPhysicalMediumUWB:
1598                 case NdisPhysicalMediumIrda:
1599                         /*
1600                          * Wireless.
1601                          */
1602                         *flags |= PCAP_IF_WIRELESS;
1603                         break;
1604
1605                 default:
1606                         /*
1607                          * Not wireless.
1608                          */
1609                         break;
1610                 }
1611         }
1612 #endif
1613
1614         /*
1615          * Get the connection status.
1616          */
1617 #ifdef OID_GEN_LINK_STATE
1618         len = sizeof(link_state);
1619         status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
1620             &len, errbuf);
1621         if (status == 0) {
1622                 /*
1623                  * NOTE: this also gives us the receive and transmit
1624                  * link state.
1625                  */
1626                 switch (link_state.MediaConnectState) {
1627
1628                 case MediaConnectStateConnected:
1629                         /*
1630                          * It's connected.
1631                          */
1632                         *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
1633                         break;
1634
1635                 case MediaConnectStateDisconnected:
1636                         /*
1637                          * It's disconnected.
1638                          */
1639                         *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
1640                         break;
1641                 }
1642         }
1643 #else
1644         /*
1645          * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1646          */
1647         status = -1;
1648 #endif
1649         if (status == -1) {
1650                 /*
1651                  * OK, OID_GEN_LINK_STATE didn't work, try
1652                  * OID_GEN_MEDIA_CONNECT_STATUS.
1653                  */
1654                 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
1655                     &connect_status, &len, errbuf);
1656                 if (status == 0) {
1657                         switch (connect_status) {
1658
1659                         case NdisMediaStateConnected:
1660                                 /*
1661                                  * It's connected.
1662                                  */
1663                                 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
1664                                 break;
1665
1666                         case NdisMediaStateDisconnected:
1667                                 /*
1668                                  * It's disconnected.
1669                                  */
1670                                 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
1671                                 break;
1672                         }
1673                 }
1674         }
1675         PacketCloseAdapter(adapter);
1676         return (0);
1677 }
1678
1679 int
1680 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
1681 {
1682         int ret = 0;
1683         const char *desc;
1684         char *AdaptersName;
1685         ULONG NameLength;
1686         char *name;
1687         char our_errbuf[PCAP_ERRBUF_SIZE+1];
1688
1689         /*
1690          * Find out how big a buffer we need.
1691          *
1692          * This call should always return FALSE; if the error is
1693          * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1694          * the size of the buffer we need, otherwise there's a
1695          * problem, and NameLength should be set to 0.
1696          *
1697          * It shouldn't require NameLength to be set, but,
1698          * at least as of WinPcap 4.1.3, it checks whether
1699          * NameLength is big enough before it checks for a
1700          * NULL buffer argument, so, while it'll still do
1701          * the right thing if NameLength is uninitialized and
1702          * whatever junk happens to be there is big enough
1703          * (because the pointer argument will be null), it's
1704          * still reading an uninitialized variable.
1705          */
1706         NameLength = 0;
1707         if (!PacketGetAdapterNames(NULL, &NameLength))
1708         {
1709                 DWORD last_error = GetLastError();
1710
1711                 if (last_error != ERROR_INSUFFICIENT_BUFFER)
1712                 {
1713                         pcap_win32_err_to_str(last_error, our_errbuf);
1714                         pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1715                             "PacketGetAdapterNames: %s", our_errbuf);
1716                         return (-1);
1717                 }
1718         }
1719
1720         if (NameLength <= 0)
1721                 return 0;
1722         AdaptersName = (char*) malloc(NameLength);
1723         if (AdaptersName == NULL)
1724         {
1725                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
1726                 return (-1);
1727         }
1728
1729         if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
1730                 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1731                 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "PacketGetAdapterNames: %s",
1732                     our_errbuf);
1733                 free(AdaptersName);
1734                 return (-1);
1735         }
1736
1737         /*
1738          * "PacketGetAdapterNames()" returned a list of
1739          * null-terminated ASCII interface name strings,
1740          * terminated by a null string, followed by a list
1741          * of null-terminated ASCII interface description
1742          * strings, terminated by a null string.
1743          * This means there are two ASCII nulls at the end
1744          * of the first list.
1745          *
1746          * Find the end of the first list; that's the
1747          * beginning of the second list.
1748          */
1749         desc = &AdaptersName[0];
1750         while (*desc != '\0' || *(desc + 1) != '\0')
1751                 desc++;
1752
1753         /*
1754          * Found it - "desc" points to the first of the two
1755          * nulls at the end of the list of names, so the
1756          * first byte of the list of descriptions is two bytes
1757          * after it.
1758          */
1759         desc += 2;
1760
1761         /*
1762          * Loop over the elements in the first list.
1763          */
1764         name = &AdaptersName[0];
1765         while (*name != '\0') {
1766                 bpf_u_int32 flags = 0;
1767 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1768                 /*
1769                  * Is this a loopback interface?
1770                  */
1771                 if (PacketIsLoopbackAdapter(name)) {
1772                         /* Yes */
1773                         flags |= PCAP_IF_LOOPBACK;
1774                 }
1775 #endif
1776                 /*
1777                  * Get additional flags.
1778                  */
1779                 if (get_if_flags(name, &flags, errbuf) == -1) {
1780                         /*
1781                          * Failure.
1782                          */
1783                         ret = -1;
1784                         break;
1785                 }
1786
1787                 /*
1788                  * Add an entry for this interface.
1789                  */
1790                 if (pcap_add_if_npf(devlistp, name, flags, desc,
1791                     errbuf) == -1) {
1792                         /*
1793                          * Failure.
1794                          */
1795                         ret = -1;
1796                         break;
1797                 }
1798                 name += strlen(name) + 1;
1799                 desc += strlen(desc) + 1;
1800         }
1801
1802         free(AdaptersName);
1803         return (ret);
1804 }
1805
1806 /*
1807  * Return the name of a network interface attached to the system, or NULL
1808  * if none can be found.  The interface must be configured up; the
1809  * lowest unit number is preferred; loopback is ignored.
1810  *
1811  * In the best of all possible worlds, this would be the same as on
1812  * UN*X, but there may be software that expects this to return a
1813  * full list of devices after the first device.
1814  */
1815 #define ADAPTERSNAME_LEN        8192
1816 char *
1817 pcap_lookupdev(char *errbuf)
1818 {
1819         DWORD dwVersion;
1820         DWORD dwWindowsMajorVersion;
1821         char our_errbuf[PCAP_ERRBUF_SIZE+1];
1822
1823 #pragma warning (push)
1824 #pragma warning (disable: 4996) /* disable MSVC's GetVersion() deprecated warning here */
1825         dwVersion = GetVersion();       /* get the OS version */
1826 #pragma warning (pop)
1827         dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
1828
1829         if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
1830                 /*
1831                  * Windows 95, 98, ME.
1832                  */
1833                 ULONG NameLength = ADAPTERSNAME_LEN;
1834                 static char AdaptersName[ADAPTERSNAME_LEN];
1835
1836                 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
1837                         return (AdaptersName);
1838                 else
1839                         return NULL;
1840         } else {
1841                 /*
1842                  * Windows NT (NT 4.0 and later).
1843                  * Convert the names to Unicode for backward compatibility.
1844                  */
1845                 ULONG NameLength = ADAPTERSNAME_LEN;
1846                 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
1847                 size_t BufferSpaceLeft;
1848                 char *tAstr;
1849                 WCHAR *Unameptr;
1850                 char *Adescptr;
1851                 size_t namelen, i;
1852                 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
1853                 int NAdapts = 0;
1854
1855                 if(TAdaptersName == NULL)
1856                 {
1857                         (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
1858                         return NULL;
1859                 }
1860
1861                 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
1862                 {
1863                         pcap_win32_err_to_str(GetLastError(), our_errbuf);
1864                         (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1865                                 "PacketGetAdapterNames: %s", our_errbuf);
1866                         free(TAdaptersName);
1867                         return NULL;
1868                 }
1869
1870
1871                 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
1872                 tAstr = (char*)TAdaptersName;
1873                 Unameptr = AdaptersName;
1874
1875                 /*
1876                  * Convert the device names to Unicode into AdapterName.
1877                  */
1878                 do {
1879                         /*
1880                          * Length of the name, including the terminating
1881                          * NUL.
1882                          */
1883                         namelen = strlen(tAstr) + 1;
1884
1885                         /*
1886                          * Do we have room for the name in the Unicode
1887                          * buffer?
1888                          */
1889                         if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
1890                                 /*
1891                                  * No.
1892                                  */
1893                                 goto quit;
1894                         }
1895                         BufferSpaceLeft -= namelen * sizeof(WCHAR);
1896
1897                         /*
1898                          * Copy the name, converting ASCII to Unicode.
1899                          * namelen includes the NUL, so we copy it as
1900                          * well.
1901                          */
1902                         for (i = 0; i < namelen; i++)
1903                                 *Unameptr++ = *tAstr++;
1904
1905                         /*
1906                          * Count this adapter.
1907                          */
1908                         NAdapts++;
1909                 } while (namelen != 1);
1910
1911                 /*
1912                  * Copy the descriptions, but don't convert them from
1913                  * ASCII to Unicode.
1914                  */
1915                 Adescptr = (char *)Unameptr;
1916                 while(NAdapts--)
1917                 {
1918                         size_t desclen;
1919
1920                         desclen = strlen(tAstr) + 1;
1921
1922                         /*
1923                          * Do we have room for the name in the Unicode
1924                          * buffer?
1925                          */
1926                         if (BufferSpaceLeft < desclen) {
1927                                 /*
1928                                  * No.
1929                                  */
1930                                 goto quit;
1931                         }
1932
1933                         /*
1934                          * Just copy the ASCII string.
1935                          * namelen includes the NUL, so we copy it as
1936                          * well.
1937                          */
1938                         memcpy(Adescptr, tAstr, desclen);
1939                         Adescptr += desclen;
1940                         tAstr += desclen;
1941                         BufferSpaceLeft -= desclen;
1942                 }
1943
1944         quit:
1945                 free(TAdaptersName);
1946                 return (char *)(AdaptersName);
1947         }
1948 }
1949
1950 /*
1951  * We can't use the same code that we use on UN*X, as that's doing
1952  * UN*X-specific calls.
1953  *
1954  * We don't just fetch the entire list of devices, search for the
1955  * particular device, and use its first IPv4 address, as that's too
1956  * much work to get just one device's netmask.
1957  */
1958 int
1959 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
1960     char *errbuf)
1961 {
1962         /*
1963          * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
1964          * in order to skip non IPv4 (i.e. IPv6 addresses)
1965          */
1966         npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1967         LONG if_addr_size = MAX_NETWORK_ADDRESSES;
1968         struct sockaddr_in *t_addr;
1969         LONG i;
1970
1971         if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
1972                 *netp = *maskp = 0;
1973                 return (0);
1974         }
1975
1976         for(i = 0; i < if_addr_size; i++)
1977         {
1978                 if(if_addrs[i].IPAddress.ss_family == AF_INET)
1979                 {
1980                         t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
1981                         *netp = t_addr->sin_addr.S_un.S_addr;
1982                         t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
1983                         *maskp = t_addr->sin_addr.S_un.S_addr;
1984
1985                         *netp &= *maskp;
1986                         return (0);
1987                 }
1988
1989         }
1990
1991         *netp = *maskp = 0;
1992         return (0);
1993 }
1994
1995 static const char *pcap_lib_version_string;
1996
1997 #ifdef HAVE_VERSION_H
1998 /*
1999  * libpcap being built for Windows, as part of a WinPcap/Npcap source
2000  * tree.  Include version.h from that source tree to get the WinPcap/Npcap
2001  * version.
2002  *
2003  * XXX - it'd be nice if we could somehow generate the WinPcap version number
2004  * when building WinPcap.  (It'd be nice to do so for the packet.dll version
2005  * number as well.)
2006  */
2007 #include "../../version.h"
2008
2009 static const char pcap_version_string[] =
2010         WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2011 static const char pcap_version_string_packet_dll_fmt[] =
2012         WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING;
2013
2014 const char *
2015 pcap_lib_version(void)
2016 {
2017         char *packet_version_string;
2018         size_t full_pcap_version_string_len;
2019         char *full_pcap_version_string;
2020
2021         if (pcap_lib_version_string == NULL) {
2022                 /*
2023                  * Generate the version string.
2024                  */
2025                 packet_version_string = PacketGetVersion();
2026                 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2027                         /*
2028                          * WinPcap version string and packet.dll version
2029                          * string are the same; just report the WinPcap
2030                          * version.
2031                          */
2032                         pcap_lib_version_string = pcap_version_string;
2033                 } else {
2034                         /*
2035                          * WinPcap version string and packet.dll version
2036                          * string are different; that shouldn't be the
2037                          * case (the two libraries should come from the
2038                          * same version of WinPcap), so we report both
2039                          * versions.
2040                          *
2041                          * The -2 is for the %s in the format string,
2042                          * which will be replaced by packet_version_string.
2043                          */
2044                         full_pcap_version_string_len =
2045                             (sizeof pcap_version_string_packet_dll_fmt - 2) +
2046                             strlen(packet_version_string);
2047                         full_pcap_version_string = malloc(full_pcap_version_string_len);
2048                         if (full_pcap_version_string == NULL)
2049                                 return (NULL);
2050                         pcap_snprintf(full_pcap_version_string,
2051                             full_pcap_version_string_len,
2052                             pcap_version_string_packet_dll_fmt,
2053                             packet_version_string);
2054                 }
2055                 pcap_lib_version_string = full_pcap_version_string;
2056         }
2057         return (pcap_lib_version_string);
2058 }
2059
2060 #else /* HAVE_VERSION_H */
2061
2062 /*
2063  * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2064  * tree.
2065  */
2066 static const char pcap_version_string_packet_dll_fmt[] =
2067         PCAP_VERSION_STRING " (packet.dll version %s)";
2068 const char *
2069 pcap_lib_version(void)
2070 {
2071         char *packet_version_string;
2072         size_t full_pcap_version_string_len;
2073         char *full_pcap_version_string;
2074
2075         if (pcap_lib_version_string == NULL) {
2076                 /*
2077                  * Generate the version string.  Report the packet.dll
2078                  * version.
2079                  *
2080                  * The -2 is for the %s in the format string, which will
2081                  * be replaced by packet_version_string.
2082                  */
2083                 packet_version_string = PacketGetVersion();
2084                 full_pcap_version_string_len =
2085                     (sizeof pcap_version_string_packet_dll_fmt - 2) +
2086                     strlen(packet_version_string);
2087                 full_pcap_version_string = malloc(full_pcap_version_string_len);
2088                 if (full_pcap_version_string == NULL)
2089                         return (NULL);
2090                 pcap_snprintf(full_pcap_version_string,
2091                     full_pcap_version_string_len,
2092                     pcap_version_string_packet_dll_fmt,
2093                     packet_version_string);
2094                 pcap_lib_version_string = full_pcap_version_string;
2095         }
2096         return (pcap_lib_version_string);
2097 }
2098 #endif /* HAVE_VERSION_H */