xref: /freebsd/contrib/libpcap/pcap-npf.c (revision 4ef1c6f75d25ba0c264ab274a1b449467a6ee817)
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 #include <limits.h> /* for INT_MAX */
40 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
41 #include <Packet32.h>
42 #include <pcap-int.h>
43 #include <pcap/dlt.h>
44 
45 /*
46  * XXX - Packet32.h defines bpf_program, so we can't include
47  * <pcap/bpf.h>, which also defines it; that's why we define
48  * PCAP_DONT_INCLUDE_PCAP_BPF_H,
49  *
50  * However, no header in the WinPcap or Npcap SDKs defines the
51  * macros for BPF code, so we have to define them ourselves.
52  */
53 #define		BPF_RET		0x06
54 #define		BPF_K		0x00
55 
56 /* Old-school MinGW have these headers in a different place.
57  */
58 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
59   #include <ddk/ntddndis.h>
60   #include <ddk/ndis.h>
61 #else
62   #include <ntddndis.h>  /* MSVC/TDM-MinGW/MinGW64 */
63 #endif
64 
65 #ifdef HAVE_DAG_API
66   #include <dagnew.h>
67   #include <dagapi.h>
68 #endif /* HAVE_DAG_API */
69 
70 #include "diag-control.h"
71 
72 #include "pcap-airpcap.h"
73 
74 static int pcap_setfilter_npf(pcap_t *, struct bpf_program *);
75 static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
76 static int pcap_getnonblock_npf(pcap_t *);
77 static int pcap_setnonblock_npf(pcap_t *, int);
78 
79 /*dimension of the buffer in the pcap_t structure*/
80 #define	WIN32_DEFAULT_USER_BUFFER_SIZE 256000
81 
82 /*dimension of the buffer in the kernel driver NPF */
83 #define	WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
84 
85 /* Equivalent to ntohs(), but a lot faster under Windows */
86 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
87 
88 /*
89  * Private data for capturing on WinPcap/Npcap devices.
90  */
91 struct pcap_win {
92 	ADAPTER *adapter;		/* the packet32 ADAPTER for the device */
93 	int nonblock;
94 	int rfmon_selfstart;		/* a flag tells whether the monitor mode is set by itself */
95 	int filtering_in_kernel;	/* using kernel filter */
96 
97 #ifdef HAVE_DAG_API
98 	int	dag_fcs_bits;		/* Number of checksum bits from link layer */
99 #endif
100 
101 #ifdef ENABLE_REMOTE
102 	int samp_npkt;			/* parameter needed for sampling, with '1 out of N' method has been requested */
103 	struct timeval samp_time;	/* parameter needed for sampling, with '1 every N ms' method has been requested */
104 #endif
105 };
106 
107 /*
108  * Define stub versions of the monitor-mode support routines if this
109  * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
110  * WinPcap.
111  */
112 #ifndef HAVE_NPCAP_PACKET_API
113 static int
114 PacketIsMonitorModeSupported(PCHAR AdapterName _U_)
115 {
116 	/*
117 	 * We don't support monitor mode.
118 	 */
119 	return (0);
120 }
121 
122 static int
123 PacketSetMonitorMode(PCHAR AdapterName _U_, int mode _U_)
124 {
125 	/*
126 	 * This should never be called, as PacketIsMonitorModeSupported()
127 	 * will return 0, meaning "we don't support monitor mode, so
128 	 * don't try to turn it on or off".
129 	 */
130 	return (0);
131 }
132 
133 static int
134 PacketGetMonitorMode(PCHAR AdapterName _U_)
135 {
136 	/*
137 	 * This should fail, so that pcap_activate_npf() returns
138 	 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
139 	 * mode.
140 	 */
141 	return (-1);
142 }
143 #endif
144 
145 /*
146  * Sigh.  PacketRequest() will have made a DeviceIoControl()
147  * call to the NPF driver to perform the OID request, with a
148  * BIOCQUERYOID ioctl.  The kernel code should get back one
149  * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
150  * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
151  * supported by the OS or the driver, but that doesn't seem
152  * to make it to the caller of PacketRequest() in a
153  * reliable fashion.
154  */
155 #define NDIS_STATUS_INVALID_OID		0xc0010017
156 #define NDIS_STATUS_NOT_SUPPORTED	0xc00000bb	/* STATUS_NOT_SUPPORTED */
157 #define NDIS_STATUS_NOT_RECOGNIZED	0x00010001
158 
159 static int
160 oid_get_request(ADAPTER *adapter, bpf_u_int32 oid, void *data, size_t *lenp,
161     char *errbuf)
162 {
163 	PACKET_OID_DATA *oid_data_arg;
164 
165 	/*
166 	 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
167 	 * It should be big enough to hold "*lenp" bytes of data; it
168 	 * will actually be slightly larger, as PACKET_OID_DATA has a
169 	 * 1-byte data array at the end, standing in for the variable-length
170 	 * data that's actually there.
171 	 */
172 	oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
173 	if (oid_data_arg == NULL) {
174 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
175 		    "Couldn't allocate argument buffer for PacketRequest");
176 		return (PCAP_ERROR);
177 	}
178 
179 	/*
180 	 * No need to copy the data - we're doing a fetch.
181 	 */
182 	oid_data_arg->Oid = oid;
183 	oid_data_arg->Length = (ULONG)(*lenp);	/* XXX - check for ridiculously large value? */
184 	if (!PacketRequest(adapter, FALSE, oid_data_arg)) {
185 		pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
186 		    GetLastError(), "Error calling PacketRequest");
187 		free(oid_data_arg);
188 		return (-1);
189 	}
190 
191 	/*
192 	 * Get the length actually supplied.
193 	 */
194 	*lenp = oid_data_arg->Length;
195 
196 	/*
197 	 * Copy back the data we fetched.
198 	 */
199 	memcpy(data, oid_data_arg->Data, *lenp);
200 	free(oid_data_arg);
201 	return (0);
202 }
203 
204 static int
205 pcap_stats_npf(pcap_t *p, struct pcap_stat *ps)
206 {
207 	struct pcap_win *pw = p->priv;
208 	struct bpf_stat bstats;
209 
210 	/*
211 	 * Try to get statistics.
212 	 *
213 	 * (Please note - "struct pcap_stat" is *not* the same as
214 	 * WinPcap's "struct bpf_stat". It might currently have the
215 	 * same layout, but let's not cheat.
216 	 *
217 	 * Note also that we don't fill in ps_capt, as we might have
218 	 * been called by code compiled against an earlier version of
219 	 * WinPcap that didn't have ps_capt, in which case filling it
220 	 * in would stomp on whatever comes after the structure passed
221 	 * to us.
222 	 */
223 	if (!PacketGetStats(pw->adapter, &bstats)) {
224 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
225 		    GetLastError(), "PacketGetStats error");
226 		return (-1);
227 	}
228 	ps->ps_recv = bstats.bs_recv;
229 	ps->ps_drop = bstats.bs_drop;
230 
231 	/*
232 	 * XXX - PacketGetStats() doesn't fill this in, so we just
233 	 * return 0.
234 	 */
235 #if 0
236 	ps->ps_ifdrop = bstats.ps_ifdrop;
237 #else
238 	ps->ps_ifdrop = 0;
239 #endif
240 
241 	return (0);
242 }
243 
244 /*
245  * Win32-only routine for getting statistics.
246  *
247  * This way is definitely safer than passing the pcap_stat * from the userland.
248  * In fact, there could happen than the user allocates a variable which is not
249  * big enough for the new structure, and the library will write in a zone
250  * which is not allocated to this variable.
251  *
252  * In this way, we're pretty sure we are writing on memory allocated to this
253  * variable.
254  *
255  * XXX - but this is the wrong way to handle statistics.  Instead, we should
256  * have an API that returns data in a form like the Options section of a
257  * pcapng Interface Statistics Block:
258  *
259  *    https://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
260  *
261  * which would let us add new statistics straightforwardly and indicate which
262  * statistics we are and are *not* providing, rather than having to provide
263  * possibly-bogus values for statistics we can't provide.
264  */
265 static struct pcap_stat *
266 pcap_stats_ex_npf(pcap_t *p, int *pcap_stat_size)
267 {
268 	struct pcap_win *pw = p->priv;
269 	struct bpf_stat bstats;
270 
271 	*pcap_stat_size = sizeof (p->stat);
272 
273 	/*
274 	 * Try to get statistics.
275 	 *
276 	 * (Please note - "struct pcap_stat" is *not* the same as
277 	 * WinPcap's "struct bpf_stat". It might currently have the
278 	 * same layout, but let's not cheat.)
279 	 */
280 	if (!PacketGetStatsEx(pw->adapter, &bstats)) {
281 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
282 		    GetLastError(), "PacketGetStatsEx error");
283 		return (NULL);
284 	}
285 	p->stat.ps_recv = bstats.bs_recv;
286 	p->stat.ps_drop = bstats.bs_drop;
287 	p->stat.ps_ifdrop = bstats.ps_ifdrop;
288 	/*
289 	 * Just in case this is ever compiled for a target other than
290 	 * Windows, which is somewhere between extremely unlikely and
291 	 * impossible.
292 	 */
293 #ifdef _WIN32
294 	p->stat.ps_capt = bstats.bs_capt;
295 #endif
296 	return (&p->stat);
297 }
298 
299 /* Set the dimension of the kernel-level capture buffer */
300 static int
301 pcap_setbuff_npf(pcap_t *p, int dim)
302 {
303 	struct pcap_win *pw = p->priv;
304 
305 	if(PacketSetBuff(pw->adapter,dim)==FALSE)
306 	{
307 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
308 		return (-1);
309 	}
310 	return (0);
311 }
312 
313 /* Set the driver working mode */
314 static int
315 pcap_setmode_npf(pcap_t *p, int mode)
316 {
317 	struct pcap_win *pw = p->priv;
318 
319 	if(PacketSetMode(pw->adapter,mode)==FALSE)
320 	{
321 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
322 		return (-1);
323 	}
324 
325 	return (0);
326 }
327 
328 /*set the minimum amount of data that will release a read call*/
329 static int
330 pcap_setmintocopy_npf(pcap_t *p, int size)
331 {
332 	struct pcap_win *pw = p->priv;
333 
334 	if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
335 	{
336 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
337 		return (-1);
338 	}
339 	return (0);
340 }
341 
342 static HANDLE
343 pcap_getevent_npf(pcap_t *p)
344 {
345 	struct pcap_win *pw = p->priv;
346 
347 	return (PacketGetReadEvent(pw->adapter));
348 }
349 
350 static int
351 pcap_oid_get_request_npf(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
352 {
353 	struct pcap_win *pw = p->priv;
354 
355 	return (oid_get_request(pw->adapter, oid, data, lenp, p->errbuf));
356 }
357 
358 static int
359 pcap_oid_set_request_npf(pcap_t *p, bpf_u_int32 oid, const void *data,
360     size_t *lenp)
361 {
362 	struct pcap_win *pw = p->priv;
363 	PACKET_OID_DATA *oid_data_arg;
364 
365 	/*
366 	 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
367 	 * It should be big enough to hold "*lenp" bytes of data; it
368 	 * will actually be slightly larger, as PACKET_OID_DATA has a
369 	 * 1-byte data array at the end, standing in for the variable-length
370 	 * data that's actually there.
371 	 */
372 	oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
373 	if (oid_data_arg == NULL) {
374 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
375 		    "Couldn't allocate argument buffer for PacketRequest");
376 		return (PCAP_ERROR);
377 	}
378 
379 	oid_data_arg->Oid = oid;
380 	oid_data_arg->Length = (ULONG)(*lenp);	/* XXX - check for ridiculously large value? */
381 	memcpy(oid_data_arg->Data, data, *lenp);
382 	if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
383 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
384 		    GetLastError(), "Error calling PacketRequest");
385 		free(oid_data_arg);
386 		return (PCAP_ERROR);
387 	}
388 
389 	/*
390 	 * Get the length actually copied.
391 	 */
392 	*lenp = oid_data_arg->Length;
393 
394 	/*
395 	 * No need to copy the data - we're doing a set.
396 	 */
397 	free(oid_data_arg);
398 	return (0);
399 }
400 
401 static u_int
402 pcap_sendqueue_transmit_npf(pcap_t *p, pcap_send_queue *queue, int sync)
403 {
404 	struct pcap_win *pw = p->priv;
405 	u_int res;
406 
407 	res = PacketSendPackets(pw->adapter,
408 		queue->buffer,
409 		queue->len,
410 		(BOOLEAN)sync);
411 
412 	if(res != queue->len){
413 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
414 		    GetLastError(), "Error queueing packets");
415 	}
416 
417 	return (res);
418 }
419 
420 static int
421 pcap_setuserbuffer_npf(pcap_t *p, int size)
422 {
423 	unsigned char *new_buff;
424 
425 	if (size<=0) {
426 		/* Bogus parameter */
427 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
428 		    "Error: invalid size %d",size);
429 		return (-1);
430 	}
431 
432 	/* Allocate the buffer */
433 	new_buff=(unsigned char*)malloc(sizeof(char)*size);
434 
435 	if (!new_buff) {
436 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
437 		    "Error: not enough memory");
438 		return (-1);
439 	}
440 
441 	free(p->buffer);
442 
443 	p->buffer=new_buff;
444 	p->bufsize=size;
445 
446 	return (0);
447 }
448 
449 #ifdef HAVE_NPCAP_PACKET_API
450 /*
451  * Kernel dump mode isn't supported in Npcap; calls to PacketSetDumpName(),
452  * PacketSetDumpLimits(), and PacketIsDumpEnded() will get compile-time
453  * deprecation warnings.
454  *
455  * Avoid calling them; just return errors indicating that kernel dump
456  * mode isn't supported in Npcap.
457  */
458 static int
459 pcap_live_dump_npf(pcap_t *p, char *filename _U_, int maxsize _U_,
460     int maxpacks _U_)
461 {
462 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
463 	    "Npcap doesn't support kernel dump mode");
464 	return (-1);
465 }
466 static int
467 pcap_live_dump_ended_npf(pcap_t *p, int sync)
468 {
469 	snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
470 	    "Npcap doesn't support kernel dump mode");
471 	return (-1);
472 }
473 #else /* HAVE_NPCAP_PACKET_API */
474 static int
475 pcap_live_dump_npf(pcap_t *p, char *filename, int maxsize, int maxpacks)
476 {
477 	struct pcap_win *pw = p->priv;
478 	BOOLEAN res;
479 
480 	/* Set the packet driver in dump mode */
481 	res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
482 	if(res == FALSE){
483 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
484 		    "Error setting dump mode");
485 		return (-1);
486 	}
487 
488 	/* Set the name of the dump file */
489 	res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
490 	if(res == FALSE){
491 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
492 		    "Error setting kernel dump file name");
493 		return (-1);
494 	}
495 
496 	/* Set the limits of the dump file */
497 	res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
498 	if(res == FALSE) {
499 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
500 				"Error setting dump limit");
501 		return (-1);
502 	}
503 
504 	return (0);
505 }
506 
507 static int
508 pcap_live_dump_ended_npf(pcap_t *p, int sync)
509 {
510 	struct pcap_win *pw = p->priv;
511 
512 	return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
513 }
514 #endif /* HAVE_NPCAP_PACKET_API */
515 
516 #ifdef HAVE_AIRPCAP_API
517 static PAirpcapHandle
518 pcap_get_airpcap_handle_npf(pcap_t *p)
519 {
520 	struct pcap_win *pw = p->priv;
521 
522 	return (PacketGetAirPcapHandle(pw->adapter));
523 }
524 #else /* HAVE_AIRPCAP_API */
525 static PAirpcapHandle
526 pcap_get_airpcap_handle_npf(pcap_t *p _U_)
527 {
528 	return (NULL);
529 }
530 #endif /* HAVE_AIRPCAP_API */
531 
532 static int
533 pcap_read_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
534 {
535 	PACKET Packet;
536 	int cc;
537 	int n;
538 	register u_char *bp, *ep;
539 	u_char *datap;
540 	struct pcap_win *pw = p->priv;
541 
542 	cc = p->cc;
543 	if (cc == 0) {
544 		/*
545 		 * Has "pcap_breakloop()" been called?
546 		 */
547 		if (p->break_loop) {
548 			/*
549 			 * Yes - clear the flag that indicates that it
550 			 * has, and return PCAP_ERROR_BREAK to indicate
551 			 * that we were told to break out of the loop.
552 			 */
553 			p->break_loop = 0;
554 			return (PCAP_ERROR_BREAK);
555 		}
556 
557 		/*
558 		 * Capture the packets.
559 		 *
560 		 * The PACKET structure had a bunch of extra stuff for
561 		 * Windows 9x/Me, but the only interesting data in it
562 		 * in the versions of Windows that we support is just
563 		 * a copy of p->buffer, a copy of p->buflen, and the
564 		 * actual number of bytes read returned from
565 		 * PacketReceivePacket(), none of which has to be
566 		 * retained from call to call, so we just keep one on
567 		 * the stack.
568 		 */
569 		PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
570 		if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
571 			/*
572 			 * Did the device go away?
573 			 * If so, the error we get can either be
574 			 * ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
575 			 */
576 			DWORD errcode = GetLastError();
577 
578 			if (errcode == ERROR_GEN_FAILURE ||
579 			    errcode == ERROR_DEVICE_REMOVED) {
580 				/*
581 				 * The device on which we're capturing
582 				 * went away, or it became unusable
583 				 * by NPF due to a suspend/resume.
584 				 *
585 				 * ERROR_GEN_FAILURE comes from
586 				 * STATUS_UNSUCCESSFUL, as well as some
587 				 * other NT status codes that the Npcap
588 				 * driver is unlikely to return.
589 				 * XXX - hopefully no other error
590 				 * conditions are indicated by this.
591 				 *
592 				 * ERROR_DEVICE_REMOVED comes from
593 				 * STATUS_DEVICE_REMOVED.
594 				 *
595 				 * We report the Windows status code
596 				 * name and the corresponding NT status
597 				 * code name, for the benefit of attempts
598 				 * to debug cases where this error is
599 				 * reported when the device *wasn't*
600 				 * removed, either because it's not
601 				 * removable, it's removable but wasn't
602 				 * removed, or it's a device that doesn't
603 				 * correspond to a physical device.
604 				 *
605 				 * XXX - we really should return an
606 				 * appropriate error for that, but
607 				 * pcap_dispatch() etc. aren't
608 				 * documented as having error returns
609 				 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
610 				 */
611 				const char *errcode_msg;
612 
613 				if (errcode == ERROR_GEN_FAILURE)
614 					errcode_msg = "ERROR_GEN_FAILURE/STATUS_UNSUCCESSFUL";
615 				else
616 					errcode_msg = "ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED";
617 				snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
618 				    "The interface disappeared (error code %s)",
619 				    errcode_msg);
620 			} else {
621 				pcap_fmt_errmsg_for_win32_err(p->errbuf,
622 				    PCAP_ERRBUF_SIZE, errcode,
623 				    "PacketReceivePacket error");
624 			}
625 			return (PCAP_ERROR);
626 		}
627 
628 		cc = Packet.ulBytesReceived;
629 
630 		bp = p->buffer;
631 	}
632 	else
633 		bp = p->bp;
634 
635 	/*
636 	 * Loop through each packet.
637 	 *
638 	 * This assumes that a single buffer of packets will have
639 	 * <= INT_MAX packets, so the packet count doesn't overflow.
640 	 */
641 #define bhp ((struct bpf_hdr *)bp)
642 	n = 0;
643 	ep = bp + cc;
644 	for (;;) {
645 		register u_int caplen, hdrlen;
646 
647 		/*
648 		 * Has "pcap_breakloop()" been called?
649 		 * If so, return immediately - if we haven't read any
650 		 * packets, clear the flag and return PCAP_ERROR_BREAK
651 		 * to indicate that we were told to break out of the loop,
652 		 * otherwise leave the flag set, so that the *next* call
653 		 * will break out of the loop without having read any
654 		 * packets, and return the number of packets we've
655 		 * processed so far.
656 		 */
657 		if (p->break_loop) {
658 			if (n == 0) {
659 				p->break_loop = 0;
660 				return (PCAP_ERROR_BREAK);
661 			} else {
662 				p->bp = bp;
663 				p->cc = (int) (ep - bp);
664 				return (n);
665 			}
666 		}
667 		if (bp >= ep)
668 			break;
669 
670 		caplen = bhp->bh_caplen;
671 		hdrlen = bhp->bh_hdrlen;
672 		datap = bp + hdrlen;
673 
674 		/*
675 		 * Short-circuit evaluation: if using BPF filter
676 		 * in kernel, no need to do it now - we already know
677 		 * the packet passed the filter.
678 		 *
679 		 * XXX - pcap_filter() should always return TRUE if
680 		 * handed a null pointer for the program, but it might
681 		 * just try to "run" the filter, so we check here.
682 		 */
683 		if (pw->filtering_in_kernel ||
684 		    p->fcode.bf_insns == NULL ||
685 		    pcap_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
686 #ifdef ENABLE_REMOTE
687 			switch (p->rmt_samp.method) {
688 
689 			case PCAP_SAMP_1_EVERY_N:
690 				pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
691 
692 				/* Discard all packets that are not '1 out of N' */
693 				if (pw->samp_npkt != 0) {
694 					bp += Packet_WORDALIGN(caplen + hdrlen);
695 					continue;
696 				}
697 				break;
698 
699 			case PCAP_SAMP_FIRST_AFTER_N_MS:
700 			    {
701 				struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
702 
703 				/*
704 				 * Check if the timestamp of the arrived
705 				 * packet is smaller than our target time.
706 				 */
707 				if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
708 				   (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
709 					bp += Packet_WORDALIGN(caplen + hdrlen);
710 					continue;
711 				}
712 
713 				/*
714 				 * The arrived packet is suitable for being
715 				 * delivered to our caller, so let's update
716 				 * the target time.
717 				 */
718 				pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
719 				if (pw->samp_time.tv_usec > 1000000) {
720 					pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
721 					pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
722 				}
723 			    }
724 			}
725 #endif	/* ENABLE_REMOTE */
726 
727 			/*
728 			 * XXX A bpf_hdr matches a pcap_pkthdr.
729 			 */
730 			(*callback)(user, (struct pcap_pkthdr*)bp, datap);
731 			bp += Packet_WORDALIGN(caplen + hdrlen);
732 			if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
733 				p->bp = bp;
734 				p->cc = (int) (ep - bp);
735 				return (n);
736 			}
737 		} else {
738 			/*
739 			 * Skip this packet.
740 			 */
741 			bp += Packet_WORDALIGN(caplen + hdrlen);
742 		}
743 	}
744 #undef bhp
745 	p->cc = 0;
746 	return (n);
747 }
748 
749 #ifdef HAVE_DAG_API
750 static int
751 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
752 {
753 	struct pcap_win *pw = p->priv;
754 	PACKET Packet;
755 	u_char *dp = NULL;
756 	int	packet_len = 0, caplen = 0;
757 	struct pcap_pkthdr	pcap_header;
758 	u_char *endofbuf;
759 	int n = 0;
760 	dag_record_t *header;
761 	unsigned erf_record_len;
762 	ULONGLONG ts;
763 	int cc;
764 	unsigned swt;
765 	unsigned dfp = pw->adapter->DagFastProcess;
766 
767 	cc = p->cc;
768 	if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
769 	{
770 		/*
771 		 * Get new packets from the network.
772 		 *
773 		 * The PACKET structure had a bunch of extra stuff for
774 		 * Windows 9x/Me, but the only interesting data in it
775 		 * in the versions of Windows that we support is just
776 		 * a copy of p->buffer, a copy of p->buflen, and the
777 		 * actual number of bytes read returned from
778 		 * PacketReceivePacket(), none of which has to be
779 		 * retained from call to call, so we just keep one on
780 		 * the stack.
781 		 */
782 		PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
783 		if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
784 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
785 			return (-1);
786 		}
787 
788 		cc = Packet.ulBytesReceived;
789 		if(cc == 0)
790 			/* The timeout has expired but we no packets arrived */
791 			return (0);
792 		header = (dag_record_t*)pw->adapter->DagBuffer;
793 	}
794 	else
795 		header = (dag_record_t*)p->bp;
796 
797 	endofbuf = (char*)header + cc;
798 
799 	/*
800 	 * This can conceivably process more than INT_MAX packets,
801 	 * which would overflow the packet count, causing it either
802 	 * to look like a negative number, and thus cause us to
803 	 * return a value that looks like an error, or overflow
804 	 * back into positive territory, and thus cause us to
805 	 * return a too-low count.
806 	 *
807 	 * Therefore, if the packet count is unlimited, we clip
808 	 * it at INT_MAX; this routine is not expected to
809 	 * process packets indefinitely, so that's not an issue.
810 	 */
811 	if (PACKET_COUNT_IS_UNLIMITED(cnt))
812 		cnt = INT_MAX;
813 
814 	/*
815 	 * Cycle through the packets
816 	 */
817 	do
818 	{
819 		erf_record_len = SWAPS(header->rlen);
820 		if((char*)header + erf_record_len > endofbuf)
821 			break;
822 
823 		/* Increase the number of captured packets */
824 		p->stat.ps_recv++;
825 
826 		/* Find the beginning of the packet */
827 		dp = ((u_char *)header) + dag_record_size;
828 
829 		/* Determine actual packet len */
830 		switch(header->type)
831 		{
832 		case TYPE_ATM:
833 			packet_len = ATM_SNAPLEN;
834 			caplen = ATM_SNAPLEN;
835 			dp += 4;
836 
837 			break;
838 
839 		case TYPE_ETH:
840 			swt = SWAPS(header->wlen);
841 			packet_len = swt - (pw->dag_fcs_bits);
842 			caplen = erf_record_len - dag_record_size - 2;
843 			if (caplen > packet_len)
844 			{
845 				caplen = packet_len;
846 			}
847 			dp += 2;
848 
849 			break;
850 
851 		case TYPE_HDLC_POS:
852 			swt = SWAPS(header->wlen);
853 			packet_len = swt - (pw->dag_fcs_bits);
854 			caplen = erf_record_len - dag_record_size;
855 			if (caplen > packet_len)
856 			{
857 				caplen = packet_len;
858 			}
859 
860 			break;
861 		}
862 
863 		if(caplen > p->snapshot)
864 			caplen = p->snapshot;
865 
866 		/*
867 		 * Has "pcap_breakloop()" been called?
868 		 * If so, return immediately - if we haven't read any
869 		 * packets, clear the flag and return -2 to indicate
870 		 * that we were told to break out of the loop, otherwise
871 		 * leave the flag set, so that the *next* call will break
872 		 * out of the loop without having read any packets, and
873 		 * return the number of packets we've processed so far.
874 		 */
875 		if (p->break_loop)
876 		{
877 			if (n == 0)
878 			{
879 				p->break_loop = 0;
880 				return (-2);
881 			}
882 			else
883 			{
884 				p->bp = (char*)header;
885 				p->cc = endofbuf - (char*)header;
886 				return (n);
887 			}
888 		}
889 
890 		if(!dfp)
891 		{
892 			/* convert between timestamp formats */
893 			ts = header->ts;
894 			pcap_header.ts.tv_sec = (int)(ts >> 32);
895 			ts = (ts & 0xffffffffi64) * 1000000;
896 			ts += 0x80000000; /* rounding */
897 			pcap_header.ts.tv_usec = (int)(ts >> 32);
898 			if (pcap_header.ts.tv_usec >= 1000000) {
899 				pcap_header.ts.tv_usec -= 1000000;
900 				pcap_header.ts.tv_sec++;
901 			}
902 		}
903 
904 		/* No underlying filtering system. We need to filter on our own */
905 		if (p->fcode.bf_insns)
906 		{
907 			if (pcap_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
908 			{
909 				/* Move to next packet */
910 				header = (dag_record_t*)((char*)header + erf_record_len);
911 				continue;
912 			}
913 		}
914 
915 		/* Fill the header for the user supplied callback function */
916 		pcap_header.caplen = caplen;
917 		pcap_header.len = packet_len;
918 
919 		/* Call the callback function */
920 		(*callback)(user, &pcap_header, dp);
921 
922 		/* Move to next packet */
923 		header = (dag_record_t*)((char*)header + erf_record_len);
924 
925 		/* Stop if the number of packets requested by user has been reached*/
926 		if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
927 		{
928 			p->bp = (char*)header;
929 			p->cc = endofbuf - (char*)header;
930 			return (n);
931 		}
932 	}
933 	while((u_char*)header < endofbuf);
934 
935 	return (1);
936 }
937 #endif /* HAVE_DAG_API */
938 
939 /* Send a packet to the network */
940 static int
941 pcap_inject_npf(pcap_t *p, const void *buf, int size)
942 {
943 	struct pcap_win *pw = p->priv;
944 	PACKET pkt;
945 
946 	PacketInitPacket(&pkt, (PVOID)buf, size);
947 	if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
948 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
949 		    GetLastError(), "send error: PacketSendPacket failed");
950 		return (-1);
951 	}
952 
953 	/*
954 	 * We assume it all got sent if "PacketSendPacket()" succeeded.
955 	 * "pcap_inject()" is expected to return the number of bytes
956 	 * sent.
957 	 */
958 	return (size);
959 }
960 
961 static void
962 pcap_cleanup_npf(pcap_t *p)
963 {
964 	struct pcap_win *pw = p->priv;
965 
966 	if (pw->adapter != NULL) {
967 		PacketCloseAdapter(pw->adapter);
968 		pw->adapter = NULL;
969 	}
970 	if (pw->rfmon_selfstart)
971 	{
972 		PacketSetMonitorMode(p->opt.device, 0);
973 	}
974 	pcap_cleanup_live_common(p);
975 }
976 
977 static void
978 pcap_breakloop_npf(pcap_t *p)
979 {
980 	pcap_breakloop_common(p);
981 	struct pcap_win *pw = p->priv;
982 
983 	/* XXX - what if this fails? */
984 	SetEvent(PacketGetReadEvent(pw->adapter));
985 }
986 
987 /*
988  * These are NTSTATUS values:
989  *
990  *    https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/87fba13e-bf06-450e-83b1-9241dc81e781
991  *
992  * with the "Customer" bit set.  If a driver returns them, they are not
993  * mapped to Windows error values in userland; they're returned by
994  * GetLastError().
995  *
996  * Note that "driver" here includes the Npcap NPF driver, as various
997  * versions would take NT status values and set the "Customer" bit
998  * before returning the status code.  The commit message for the
999  * change that started doing that is
1000  *
1001  *    Returned a customer-defined NTSTATUS in OID requests to avoid
1002  *    NTSTATUS-to-Win32 Error code translation.
1003  *
1004  * but I don't know why the goal was to avoid that translation.
1005  *
1006  * Attempting to set the hardware filter on a Microsoft Surface Pro's
1007  * Mobile Broadband Adapter returns an error that appears to be
1008  * NDIS_STATUS_NOT_SUPPORTED ORed with the "Customer" bit, so it's
1009  * probably indicating that it doesn't support that.
1010  *
1011  * It is likely that there are other devices which throw spurious errors,
1012  * at which point this will need refactoring to efficiently check against
1013  * a list, but for now we can just check this one value.  Perhaps the
1014  * right way to do this is compare against various NDIS errors with
1015  * the "customer" bit ORed in.
1016  */
1017 #define NT_STATUS_CUSTOMER_DEFINED	0x20000000
1018 
1019 static int
1020 pcap_activate_npf(pcap_t *p)
1021 {
1022 	struct pcap_win *pw = p->priv;
1023 	NetType type;
1024 	int res;
1025 	int status = 0;
1026 	struct bpf_insn total_insn;
1027 	struct bpf_program total_prog;
1028 
1029 	if (p->opt.rfmon) {
1030 		/*
1031 		 * Monitor mode is supported on Windows Vista and later.
1032 		 */
1033 		if (PacketGetMonitorMode(p->opt.device) == 1)
1034 		{
1035 			pw->rfmon_selfstart = 0;
1036 		}
1037 		else
1038 		{
1039 			if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
1040 			{
1041 				pw->rfmon_selfstart = 0;
1042 				// Monitor mode is not supported.
1043 				if (res == 0)
1044 				{
1045 					return PCAP_ERROR_RFMON_NOTSUP;
1046 				}
1047 				else
1048 				{
1049 					return PCAP_ERROR;
1050 				}
1051 			}
1052 			else
1053 			{
1054 				pw->rfmon_selfstart = 1;
1055 			}
1056 		}
1057 	}
1058 
1059 	/* Init Winsock if it hasn't already been initialized */
1060 	pcap_wsockinit();
1061 
1062 	pw->adapter = PacketOpenAdapter(p->opt.device);
1063 
1064 	if (pw->adapter == NULL)
1065 	{
1066 		DWORD errcode = GetLastError();
1067 
1068 		/*
1069 		 * What error did we get when trying to open the adapter?
1070 		 */
1071 		switch (errcode) {
1072 
1073 		case ERROR_BAD_UNIT:
1074 			/*
1075 			 * There's no such device.
1076 			 * There's nothing to add, so clear the error
1077 			 * message.
1078 			 */
1079 			p->errbuf[0] = '\0';
1080 			return (PCAP_ERROR_NO_SUCH_DEVICE);
1081 
1082 		case ERROR_ACCESS_DENIED:
1083 			/*
1084 			 * There is, but we don't have permission to
1085 			 * use it.
1086 			 *
1087 			 * XXX - we currently get ERROR_BAD_UNIT if the
1088 			 * user says "no" to the UAC prompt.
1089 			 */
1090 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1091 			    "The helper program for \"Admin-only Mode\" must be allowed to make changes to your device");
1092 			return (PCAP_ERROR_PERM_DENIED);
1093 
1094 		default:
1095 			/*
1096 			 * Unknown - report details.
1097 			 */
1098 			pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1099 			    errcode, "Error opening adapter");
1100 			if (pw->rfmon_selfstart)
1101 			{
1102 				PacketSetMonitorMode(p->opt.device, 0);
1103 			}
1104 			return (PCAP_ERROR);
1105 		}
1106 	}
1107 
1108 	/*get network type*/
1109 	if(PacketGetNetType (pw->adapter,&type) == FALSE)
1110 	{
1111 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1112 		    GetLastError(), "Cannot determine the network type");
1113 		goto bad;
1114 	}
1115 
1116 	/*Set the linktype*/
1117 	switch (type.LinkType)
1118 	{
1119 	/*
1120 	 * NDIS-defined medium types.
1121 	 */
1122 	case NdisMedium802_3:
1123 		p->linktype = DLT_EN10MB;
1124 		/*
1125 		 * This is (presumably) a real Ethernet capture; give it a
1126 		 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1127 		 * that an application can let you choose it, in case you're
1128 		 * capturing DOCSIS traffic that a Cisco Cable Modem
1129 		 * Termination System is putting out onto an Ethernet (it
1130 		 * doesn't put an Ethernet header onto the wire, it puts raw
1131 		 * DOCSIS frames out on the wire inside the low-level
1132 		 * Ethernet framing).
1133 		 */
1134 		p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1135 		/*
1136 		 * If that fails, just leave the list empty.
1137 		 */
1138 		if (p->dlt_list != NULL) {
1139 			p->dlt_list[0] = DLT_EN10MB;
1140 			p->dlt_list[1] = DLT_DOCSIS;
1141 			p->dlt_count = 2;
1142 		}
1143 		break;
1144 
1145 	case NdisMedium802_5:
1146 		/*
1147 		 * Token Ring.
1148 		 */
1149 		p->linktype = DLT_IEEE802;
1150 		break;
1151 
1152 	case NdisMediumFddi:
1153 		p->linktype = DLT_FDDI;
1154 		break;
1155 
1156 	case NdisMediumWan:
1157 		p->linktype = DLT_EN10MB;
1158 		break;
1159 
1160 	case NdisMediumArcnetRaw:
1161 		p->linktype = DLT_ARCNET;
1162 		break;
1163 
1164 	case NdisMediumArcnet878_2:
1165 		p->linktype = DLT_ARCNET;
1166 		break;
1167 
1168 	case NdisMediumAtm:
1169 		p->linktype = DLT_ATM_RFC1483;
1170 		break;
1171 
1172 	case NdisMediumWirelessWan:
1173 		p->linktype = DLT_RAW;
1174 		break;
1175 
1176 	case NdisMediumIP:
1177 		p->linktype = DLT_RAW;
1178 		break;
1179 
1180 	/*
1181 	 * Npcap-defined medium types.
1182 	 */
1183 	case NdisMediumNull:
1184 		p->linktype = DLT_NULL;
1185 		break;
1186 
1187 	case NdisMediumCHDLC:
1188 		p->linktype = DLT_CHDLC;
1189 		break;
1190 
1191 	case NdisMediumPPPSerial:
1192 		p->linktype = DLT_PPP_SERIAL;
1193 		break;
1194 
1195 	case NdisMediumBare80211:
1196 		p->linktype = DLT_IEEE802_11;
1197 		break;
1198 
1199 	case NdisMediumRadio80211:
1200 		p->linktype = DLT_IEEE802_11_RADIO;
1201 		break;
1202 
1203 	case NdisMediumPpi:
1204 		p->linktype = DLT_PPI;
1205 		break;
1206 
1207 	default:
1208 		/*
1209 		 * An unknown medium type is assumed to supply Ethernet
1210 		 * headers; if not, the user will have to report it,
1211 		 * so that the medium type and link-layer header type
1212 		 * can be determined.  If we were to fail here, we
1213 		 * might get the link-layer type in the error, but
1214 		 * the user wouldn't get a capture, so we wouldn't
1215 		 * be able to determine the link-layer type; we report
1216 		 * a warning with the link-layer type, so at least
1217 		 * some programs will report the warning.
1218 		 */
1219 		p->linktype = DLT_EN10MB;
1220 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1221 		    "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1222 		    type.LinkType);
1223 		status = PCAP_WARNING;
1224 		break;
1225 	}
1226 
1227 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1228 	/*
1229 	 * Set the timestamp type.
1230 	 * (Yes, we require PacketGetTimestampModes(), not just
1231 	 * PacketSetTimestampMode().  If we have the former, we
1232 	 * have the latter, unless somebody's using a version
1233 	 * of Npcap that they've hacked to provide the former
1234 	 * but not the latter; if they've done that, either
1235 	 * they're confused or they're trolling us.)
1236 	 */
1237 	switch (p->opt.tstamp_type) {
1238 
1239 	case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED:
1240 		/*
1241 		 * Better than low-res, but *not* synchronized with
1242 		 * the OS clock.
1243 		 */
1244 		if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION))
1245 		{
1246 			pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1247 			    GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1248 			goto bad;
1249 		}
1250 		break;
1251 
1252 	case PCAP_TSTAMP_HOST_LOWPREC:
1253 		/*
1254 		 * Low-res, but synchronized with the OS clock.
1255 		 */
1256 		if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME))
1257 		{
1258 			pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1259 			    GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1260 			goto bad;
1261 		}
1262 		break;
1263 
1264 	case PCAP_TSTAMP_HOST_HIPREC:
1265 		/*
1266 		 * High-res, and synchronized with the OS clock.
1267 		 */
1268 		if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE))
1269 		{
1270 			pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1271 			    GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1272 			goto bad;
1273 		}
1274 		break;
1275 
1276 	case PCAP_TSTAMP_HOST:
1277 		/*
1278 		 * XXX - do whatever the default is, for now.
1279 		 * Set to the highest resolution that's synchronized
1280 		 * with the system clock?
1281 		 */
1282 		break;
1283 	}
1284 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1285 
1286 	/*
1287 	 * Turn a negative snapshot value (invalid), a snapshot value of
1288 	 * 0 (unspecified), or a value bigger than the normal maximum
1289 	 * value, into the maximum allowed value.
1290 	 *
1291 	 * If some application really *needs* a bigger snapshot
1292 	 * length, we should just increase MAXIMUM_SNAPLEN.
1293 	 */
1294 	if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1295 		p->snapshot = MAXIMUM_SNAPLEN;
1296 
1297 	/* Set promiscuous mode */
1298 	if (p->opt.promisc)
1299 	{
1300 
1301 		if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1302 		{
1303 			DWORD errcode = GetLastError();
1304 
1305 			/*
1306 			 * Suppress spurious error generated by non-compiant
1307 			 * MS Surface mobile adapters that appear to
1308 			 * return NDIS_STATUS_NOT_SUPPORTED for attempts
1309 			 * to set the hardware filter.
1310 			 *
1311 			 * It appears to be reporting NDIS_STATUS_NOT_SUPPORTED,
1312 			 * but with the NT status value "Customer" bit set;
1313 			 * the Npcap NPF driver sets that bit in some cases.
1314 			 *
1315 			 * If we knew that this meant "promiscuous mode
1316 			 * isn't supported", we could add a "promiscuous
1317 			 * mode isn't supported" error code and return
1318 			 * that, but:
1319 			 *
1320 			 *    1) we don't know that it means that
1321 			 *    rather than meaning "we reject attempts
1322 			 *    to set the filter, even though the NDIS
1323 			 *    specifications say you shouldn't do that"
1324 			 *
1325 			 * and
1326 			 *
1327 			 *    2) other interface types that don't
1328 			 *    support promiscuous mode, at least
1329 			 *    on UN*Xes, just silently ignore
1330 			 *    attempts to set promiscuous mode
1331 			 *
1332 			 * and rejecting it with an error could disrupt
1333 			 * attempts to capture, as many programs (tcpdump,
1334 			 * *shark) default to promiscuous mode.
1335 			 *
1336 			 * Alternatively, we could return the "promiscuous
1337 			 * mode not supported" *warning* value, so that
1338 			 * correct code will either ignore it or report
1339 			 * it and continue capturing.  (This may require
1340 			 * a pcap_init() flag to request that return
1341 			 * value, so that old incorrect programs that
1342 			 * assume a non-zero return from pcap_activate()
1343 			 * is an error don't break.)
1344 			 */
1345 			if (errcode != (NDIS_STATUS_NOT_SUPPORTED|NT_STATUS_CUSTOMER_DEFINED))
1346 			{
1347 				pcap_fmt_errmsg_for_win32_err(p->errbuf,
1348 				    PCAP_ERRBUF_SIZE, errcode,
1349 				    "failed to set hardware filter to promiscuous mode");
1350 				goto bad;
1351 			}
1352 		}
1353 	}
1354 	else
1355 	{
1356 		/*
1357 		 * NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by
1358 		 * installed protocols and all packets indicated by the NIC",
1359 		 * but if no protocol drivers (like TCP/IP) are installed,
1360 		 * NDIS_PACKET_TYPE_DIRECTED, NDIS_PACKET_TYPE_BROADCAST,
1361 		 * and NDIS_PACKET_TYPE_MULTICAST are needed to capture
1362 		 * incoming frames.
1363 		 */
1364 		if (PacketSetHwFilter(pw->adapter,
1365 			NDIS_PACKET_TYPE_ALL_LOCAL |
1366 			NDIS_PACKET_TYPE_DIRECTED |
1367 			NDIS_PACKET_TYPE_BROADCAST |
1368 			NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1369 		{
1370 			DWORD errcode = GetLastError();
1371 
1372 			/*
1373 			 * Suppress spurious error generated by non-compiant
1374 			 * MS Surface mobile adapters.
1375 			 */
1376 			if (errcode != (NDIS_STATUS_NOT_SUPPORTED|NT_STATUS_CUSTOMER_DEFINED))
1377 			{
1378 				pcap_fmt_errmsg_for_win32_err(p->errbuf,
1379 				    PCAP_ERRBUF_SIZE, errcode,
1380 				    "failed to set hardware filter to non-promiscuous mode");
1381 				goto bad;
1382 			}
1383 		}
1384 	}
1385 
1386 	/* Set the buffer size */
1387 	p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1388 
1389 	if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1390 	{
1391 	/*
1392 	 * Traditional Adapter
1393 	 */
1394 		/*
1395 		 * If the buffer size wasn't explicitly set, default to
1396 		 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1397 		 */
1398 		if (p->opt.buffer_size == 0)
1399 			p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1400 
1401 		if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1402 		{
1403 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1404 			goto bad;
1405 		}
1406 
1407 		p->buffer = malloc(p->bufsize);
1408 		if (p->buffer == NULL)
1409 		{
1410 			pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1411 			    errno, "malloc");
1412 			goto bad;
1413 		}
1414 
1415 		if (p->opt.immediate)
1416 		{
1417 			/* tell the driver to copy the buffer as soon as data arrives */
1418 			if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1419 			{
1420 				pcap_fmt_errmsg_for_win32_err(p->errbuf,
1421 				    PCAP_ERRBUF_SIZE, GetLastError(),
1422 				    "Error calling PacketSetMinToCopy");
1423 				goto bad;
1424 			}
1425 		}
1426 		else
1427 		{
1428 			/* tell the driver to copy the buffer only if it contains at least 16K */
1429 			if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1430 			{
1431 				pcap_fmt_errmsg_for_win32_err(p->errbuf,
1432 				    PCAP_ERRBUF_SIZE, GetLastError(),
1433 				    "Error calling PacketSetMinToCopy");
1434 				goto bad;
1435 			}
1436 		}
1437 	} else {
1438 		/*
1439 		 * Dag Card
1440 		 */
1441 #ifdef HAVE_DAG_API
1442 		/*
1443 		 * We have DAG support.
1444 		 */
1445 		LONG	status;
1446 		HKEY	dagkey;
1447 		DWORD	lptype;
1448 		DWORD	lpcbdata;
1449 		int		postype = 0;
1450 		char	keyname[512];
1451 
1452 		snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1453 			"SYSTEM\\CurrentControlSet\\Services\\DAG",
1454 			strstr(_strlwr(p->opt.device), "dag"));
1455 		do
1456 		{
1457 			status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1458 			if(status != ERROR_SUCCESS)
1459 				break;
1460 
1461 			status = RegQueryValueEx(dagkey,
1462 				"PosType",
1463 				NULL,
1464 				&lptype,
1465 				(char*)&postype,
1466 				&lpcbdata);
1467 
1468 			if(status != ERROR_SUCCESS)
1469 			{
1470 				postype = 0;
1471 			}
1472 
1473 			RegCloseKey(dagkey);
1474 		}
1475 		while(FALSE);
1476 
1477 
1478 		p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1479 
1480 		/* Set the length of the FCS associated to any packet. This value
1481 		 * will be subtracted to the packet length */
1482 		pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1483 #else /* HAVE_DAG_API */
1484 		/*
1485 		 * No DAG support.
1486 		 */
1487 		goto bad;
1488 #endif /* HAVE_DAG_API */
1489 	}
1490 
1491 	/*
1492 	 * If there's no filter program installed, there's
1493 	 * no indication to the kernel of what the snapshot
1494 	 * length should be, so no snapshotting is done.
1495 	 *
1496 	 * Therefore, when we open the device, we install
1497 	 * an "accept everything" filter with the specified
1498 	 * snapshot length.
1499 	 */
1500 	total_insn.code = (u_short)(BPF_RET | BPF_K);
1501 	total_insn.jt = 0;
1502 	total_insn.jf = 0;
1503 	total_insn.k = p->snapshot;
1504 
1505 	total_prog.bf_len = 1;
1506 	total_prog.bf_insns = &total_insn;
1507 	if (!PacketSetBpf(pw->adapter, &total_prog)) {
1508 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1509 		    GetLastError(), "PacketSetBpf");
1510 		status = PCAP_ERROR;
1511 		goto bad;
1512 	}
1513 
1514 	PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1515 
1516 	/* disable loopback capture if requested */
1517 	if (p->opt.nocapture_local)
1518 	{
1519 		if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1520 		{
1521 			snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1522 			    "Unable to disable the capture of loopback packets.");
1523 			goto bad;
1524 		}
1525 	}
1526 
1527 #ifdef HAVE_DAG_API
1528 	if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1529 	{
1530 		/* install dag specific handlers for read and setfilter */
1531 		p->read_op = pcap_read_win32_dag;
1532 		p->setfilter_op = pcap_setfilter_win32_dag;
1533 	}
1534 	else
1535 	{
1536 #endif /* HAVE_DAG_API */
1537 		/* install traditional npf handlers for read and setfilter */
1538 		p->read_op = pcap_read_npf;
1539 		p->setfilter_op = pcap_setfilter_npf;
1540 #ifdef HAVE_DAG_API
1541 	}
1542 #endif /* HAVE_DAG_API */
1543 	p->setdirection_op = NULL;	/* Not implemented. */
1544 	    /* XXX - can this be implemented on some versions of Windows? */
1545 	p->inject_op = pcap_inject_npf;
1546 	p->set_datalink_op = NULL;	/* can't change data link type */
1547 	p->getnonblock_op = pcap_getnonblock_npf;
1548 	p->setnonblock_op = pcap_setnonblock_npf;
1549 	p->stats_op = pcap_stats_npf;
1550 	p->breakloop_op = pcap_breakloop_npf;
1551 	p->stats_ex_op = pcap_stats_ex_npf;
1552 	p->setbuff_op = pcap_setbuff_npf;
1553 	p->setmode_op = pcap_setmode_npf;
1554 	p->setmintocopy_op = pcap_setmintocopy_npf;
1555 	p->getevent_op = pcap_getevent_npf;
1556 	p->oid_get_request_op = pcap_oid_get_request_npf;
1557 	p->oid_set_request_op = pcap_oid_set_request_npf;
1558 	p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1559 	p->setuserbuffer_op = pcap_setuserbuffer_npf;
1560 	p->live_dump_op = pcap_live_dump_npf;
1561 	p->live_dump_ended_op = pcap_live_dump_ended_npf;
1562 	p->get_airpcap_handle_op = pcap_get_airpcap_handle_npf;
1563 	p->cleanup_op = pcap_cleanup_npf;
1564 
1565 	/*
1566 	 * XXX - this is only done because WinPcap supported
1567 	 * pcap_fileno() returning the hFile HANDLE from the
1568 	 * ADAPTER structure.  We make no general guarantees
1569 	 * that the caller can do anything useful with it.
1570 	 *
1571 	 * (Not that we make any general guarantee of that
1572 	 * sort on UN*X, either, any more, given that not
1573 	 * all capture devices are regular OS network
1574 	 * interfaces.)
1575 	 */
1576 	p->handle = pw->adapter->hFile;
1577 
1578 	return (status);
1579 bad:
1580 	pcap_cleanup_npf(p);
1581 	return (PCAP_ERROR);
1582 }
1583 
1584 /*
1585 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1586 */
1587 static int
1588 pcap_can_set_rfmon_npf(pcap_t *p)
1589 {
1590 	return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1591 }
1592 
1593 /*
1594  * Get a list of time stamp types.
1595  */
1596 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1597 static int
1598 get_ts_types(const char *device, pcap_t *p, char *ebuf)
1599 {
1600 	char *device_copy = NULL;
1601 	ADAPTER *adapter = NULL;
1602 	ULONG num_ts_modes;
1603 	BOOL ret;
1604 	DWORD error = ERROR_SUCCESS;
1605 	ULONG *modes = NULL;
1606 	int status = 0;
1607 
1608 	do {
1609 		/*
1610 		 * First, find out how many time stamp modes we have.
1611 		 * To do that, we have to open the adapter.
1612 		 *
1613 		 * XXX - PacketOpenAdapter() takes a non-const pointer
1614 		 * as an argument, so we make a copy of the argument and
1615 		 * pass that to it.
1616 		 */
1617 		device_copy = strdup(device);
1618 		if (device_copy == NULL) {
1619 			pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1620 			status = -1;
1621 			break;
1622 		}
1623 
1624 		adapter = PacketOpenAdapter(device_copy);
1625 		if (adapter == NULL)
1626 		{
1627 			error = GetLastError();
1628 			/*
1629 			 * If we can't open the device now, we won't be
1630 			 * able to later, either.
1631 			 *
1632 			 * If the error is something that indicates
1633 			 * that the device doesn't exist, or that they
1634 			 * don't have permission to open the device - or
1635 			 * perhaps that they don't have permission to get
1636 			 * a list of devices, if PacketOpenAdapter() does
1637 			 * that - the user will find that out when they try
1638 			 * to activate the device; just return an empty
1639 			 * list of time stamp types.
1640 			 *
1641 			 * Treating either of those as errors will, for
1642 			 * example, cause "tcpdump -i <number>" to fail,
1643 			 * because it first tries to pass the interface
1644 			 * name to pcap_create() and pcap_activate(),
1645 			 * in order to handle OSes where interfaces can
1646 			 * have names that are just numbers (stand up
1647 			 * and say hello, Linux!), and, if pcap_activate()
1648 			 * fails with a "no such device" error, checks
1649 			 * whether the interface name is a valid number
1650 			 * and, if so, tries to use it as an index in
1651 			 * the list of interfaces.
1652 			 *
1653 			 * That means pcap_create() must succeed even
1654 			 * for interfaces that don't exist, with the
1655 			 * failure occurring at pcap_activate() time.
1656 			 */
1657 			if (error == ERROR_BAD_UNIT ||
1658 			    error == ERROR_ACCESS_DENIED) {
1659 				p->tstamp_type_count = 0;
1660 				p->tstamp_type_list = NULL;
1661 				status = 0;
1662 			} else {
1663 				pcap_fmt_errmsg_for_win32_err(ebuf,
1664 				    PCAP_ERRBUF_SIZE, error,
1665 				    "Error opening adapter");
1666 				status = -1;
1667 			}
1668 			break;
1669 		}
1670 
1671 		/*
1672 		 * Get the total number of time stamp modes.
1673 		 *
1674 		 * The buffer for PacketGetTimestampModes() is
1675 		 * a sequence of 1 or more ULONGs.  What's
1676 		 * passed to PacketGetTimestampModes() should have
1677 		 * the total number of ULONGs in the first ULONG;
1678 		 * what's returned *from* PacketGetTimestampModes()
1679 		 * has the total number of time stamp modes in
1680 		 * the first ULONG.
1681 		 *
1682 		 * Yes, that means if there are N time stamp
1683 		 * modes, the first ULONG should be set to N+1
1684 		 * on input, and will be set to N on output.
1685 		 *
1686 		 * We first make a call to PacketGetTimestampModes()
1687 		 * with a pointer to a single ULONG set to 1; the
1688 		 * call should fail with ERROR_MORE_DATA (unless
1689 		 * there are *no* modes, but that should never
1690 		 * happen), and that ULONG should be set to the
1691 		 * number of modes.
1692 		 */
1693 		num_ts_modes = 1;
1694 		ret = PacketGetTimestampModes(adapter, &num_ts_modes);
1695 		if (!ret) {
1696 			/*
1697 			 * OK, it failed.  Did it fail with
1698 			 * ERROR_MORE_DATA?
1699 			 */
1700 			error = GetLastError();
1701 			if (error != ERROR_MORE_DATA) {
1702 				/*
1703 				 * No, did it fail with ERROR_INVALID_FUNCTION?
1704 				 */
1705 				if (error == ERROR_INVALID_FUNCTION) {
1706 					/*
1707 					 * This is probably due to
1708 					 * the driver with which Packet.dll
1709 					 * communicates being older, or
1710 					 * being a WinPcap driver, so
1711 					 * that it doesn't support
1712 					 * BIOCGTIMESTAMPMODES.
1713 					 *
1714 					 * Tell the user to try uninstalling
1715 					 * Npcap - and WinPcap if installed -
1716 					 * and re-installing it, to flush
1717 					 * out all older drivers.
1718 					 */
1719 					snprintf(ebuf, PCAP_ERRBUF_SIZE,
1720 					    "PacketGetTimestampModes() failed with ERROR_INVALID_FUNCTION; try uninstalling Npcap, and WinPcap if installed, and re-installing it from npcap.com");
1721 					status = -1;
1722 					break;
1723 				}
1724 
1725 				/*
1726 				 * No, some other error.  Fail.
1727 				 */
1728 				pcap_fmt_errmsg_for_win32_err(ebuf,
1729 				    PCAP_ERRBUF_SIZE, error,
1730 				    "Error calling PacketGetTimestampModes");
1731 				status = -1;
1732 				break;
1733 			}
1734 		}
1735 		/* else (ret == TRUE)
1736 		 * Unexpected success. Let's act like we got ERROR_MORE_DATA.
1737 		 * If it doesn't work, we'll hit some other error condition farther on.
1738 		 */
1739 
1740 		/* If the driver reports no modes supported *and*
1741 		 * ERROR_MORE_DATA, something is seriously wrong.
1742 		 * We *could* ignore the error and continue without supporting
1743 		 * settable timestamp modes, but that would hide a bug.
1744 		 */
1745 		if (num_ts_modes == 0) {
1746 			snprintf(ebuf, PCAP_ERRBUF_SIZE,
1747 			    "PacketGetTimestampModes() reports 0 modes supported.");
1748 			status = -1;
1749 			break;
1750 		}
1751 
1752 		/*
1753 		 * Yes, so we now know how many types to fetch.
1754 		 *
1755 		 * The buffer needs to have one ULONG for the
1756 		 * count and num_ts_modes ULONGs for the
1757 		 * num_ts_modes time stamp types.
1758 		 */
1759 		modes = (ULONG *)malloc((1 + num_ts_modes) * sizeof(ULONG));
1760 		if (modes == NULL) {
1761 			/* Out of memory. */
1762 			pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1763 			status = -1;
1764 			break;
1765 		}
1766 		modes[0] = 1 + num_ts_modes;
1767 		if (!PacketGetTimestampModes(adapter, modes)) {
1768 			pcap_fmt_errmsg_for_win32_err(ebuf,
1769 			    PCAP_ERRBUF_SIZE, GetLastError(),
1770 			    "Error calling PacketGetTimestampModes");
1771 			status = -1;
1772 			break;
1773 		}
1774 		if (modes[0] != num_ts_modes) {
1775 			snprintf(ebuf, PCAP_ERRBUF_SIZE,
1776 			    "First PacketGetTimestampModes() call gives %lu modes, second call gives %lu modes",
1777 			    num_ts_modes, modes[0]);
1778 			status = -1;
1779 			break;
1780 		}
1781 
1782 		/*
1783 		 * Allocate a buffer big enough for
1784 		 * PCAP_TSTAMP_HOST (default) plus
1785 		 * the explicitly specified modes.
1786 		 */
1787 		p->tstamp_type_list = malloc((1 + num_ts_modes) * sizeof(u_int));
1788 		if (p->tstamp_type_list == NULL) {
1789 			pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1790 			status = -1;
1791 			break;
1792 		}
1793 		u_int num_ts_types = 0;
1794 		p->tstamp_type_list[num_ts_types] =
1795 		    PCAP_TSTAMP_HOST;
1796 		num_ts_types++;
1797 		for (ULONG i = 0; i < num_ts_modes; i++) {
1798 			switch (modes[i + 1]) {
1799 
1800 			case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION:
1801 				/*
1802 				 * Better than low-res,
1803 				 * but *not* synchronized
1804 				 * with the OS clock.
1805 				 */
1806 				p->tstamp_type_list[num_ts_types] =
1807 				    PCAP_TSTAMP_HOST_HIPREC_UNSYNCED;
1808 				num_ts_types++;
1809 				break;
1810 
1811 			case TIMESTAMPMODE_QUERYSYSTEMTIME:
1812 				/*
1813 				 * Low-res, but synchronized
1814 				 * with the OS clock.
1815 				 */
1816 				p->tstamp_type_list[num_ts_types] =
1817 				    PCAP_TSTAMP_HOST_LOWPREC;
1818 				num_ts_types++;
1819 				break;
1820 
1821 			case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE:
1822 				/*
1823 				 * High-res, and synchronized
1824 				 * with the OS clock.
1825 				 */
1826 				p->tstamp_type_list[num_ts_types] =
1827 				    PCAP_TSTAMP_HOST_HIPREC;
1828 				num_ts_types++;
1829 				break;
1830 
1831 			default:
1832 				/*
1833 				 * Unknown, so we can't
1834 				 * report it.
1835 				 */
1836 				break;
1837 			}
1838 		}
1839 		p->tstamp_type_count = num_ts_types;
1840 	} while (0);
1841 
1842 	/* Clean up temporary allocations */
1843 	if (device_copy != NULL) {
1844 		free(device_copy);
1845 	}
1846 	if (modes != NULL) {
1847 		free(modes);
1848 	}
1849 	if (adapter != NULL) {
1850 		PacketCloseAdapter(adapter);
1851 	}
1852 
1853 	return status;
1854 }
1855 #else /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1856 static int
1857 get_ts_types(const char *device _U_, pcap_t *p _U_, char *ebuf _U_)
1858 {
1859 	/*
1860 	 * Nothing to fetch, so it always "succeeds".
1861 	 */
1862 	return 0;
1863 }
1864 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1865 
1866 pcap_t *
1867 pcap_create_interface(const char *device _U_, char *ebuf)
1868 {
1869 	pcap_t *p;
1870 
1871 	p = PCAP_CREATE_COMMON(ebuf, struct pcap_win);
1872 	if (p == NULL)
1873 		return (NULL);
1874 
1875 	p->activate_op = pcap_activate_npf;
1876 	p->can_set_rfmon_op = pcap_can_set_rfmon_npf;
1877 
1878 	if (get_ts_types(device, p, ebuf) == -1) {
1879 		pcap_close(p);
1880 		return (NULL);
1881 	}
1882 	return (p);
1883 }
1884 
1885 static int
1886 pcap_setfilter_npf(pcap_t *p, struct bpf_program *fp)
1887 {
1888 	struct pcap_win *pw = p->priv;
1889 
1890 	if(PacketSetBpf(pw->adapter,fp)==FALSE){
1891 		/*
1892 		 * Kernel filter not installed.
1893 		 *
1894 		 * XXX - we don't know whether this failed because:
1895 		 *
1896 		 *  the kernel rejected the filter program as invalid,
1897 		 *  in which case we should fall back on userland
1898 		 *  filtering;
1899 		 *
1900 		 *  the kernel rejected the filter program as too big,
1901 		 *  in which case we should again fall back on
1902 		 *  userland filtering;
1903 		 *
1904 		 *  there was some other problem, in which case we
1905 		 *  should probably report an error.
1906 		 *
1907 		 * For NPF devices, the Win32 status will be
1908 		 * STATUS_INVALID_DEVICE_REQUEST for invalid
1909 		 * filters, but I don't know what it'd be for
1910 		 * other problems, and for some other devices
1911 		 * it might not be set at all.
1912 		 *
1913 		 * So we just fall back on userland filtering in
1914 		 * all cases.
1915 		 */
1916 
1917 		/*
1918 		 * install_bpf_program() validates the program.
1919 		 *
1920 		 * XXX - what if we already have a filter in the kernel?
1921 		 */
1922 		if (install_bpf_program(p, fp) < 0)
1923 			return (-1);
1924 		pw->filtering_in_kernel = 0;	/* filtering in userland */
1925 		return (0);
1926 	}
1927 
1928 	/*
1929 	 * It worked.
1930 	 */
1931 	pw->filtering_in_kernel = 1;	/* filtering in the kernel */
1932 
1933 	/*
1934 	 * Discard any previously-received packets, as they might have
1935 	 * passed whatever filter was formerly in effect, but might
1936 	 * not pass this filter (BIOCSETF discards packets buffered
1937 	 * in the kernel, so you can lose packets in any case).
1938 	 */
1939 	p->cc = 0;
1940 	return (0);
1941 }
1942 
1943 /*
1944  * We filter at user level, since the kernel driver doesn't process the packets
1945  */
1946 static int
1947 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1948 
1949 	if(!fp)
1950 	{
1951 		pcap_strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1952 		return (-1);
1953 	}
1954 
1955 	/* Install a user level filter */
1956 	if (install_bpf_program(p, fp) < 0)
1957 		return (-1);
1958 
1959 	return (0);
1960 }
1961 
1962 static int
1963 pcap_getnonblock_npf(pcap_t *p)
1964 {
1965 	struct pcap_win *pw = p->priv;
1966 
1967 	/*
1968 	 * XXX - if there were a PacketGetReadTimeout() call, we
1969 	 * would use it, and return 1 if the timeout is -1
1970 	 * and 0 otherwise.
1971 	 */
1972 	return (pw->nonblock);
1973 }
1974 
1975 static int
1976 pcap_setnonblock_npf(pcap_t *p, int nonblock)
1977 {
1978 	struct pcap_win *pw = p->priv;
1979 	int newtimeout;
1980 
1981 	if (nonblock) {
1982 		/*
1983 		 * Set the packet buffer timeout to -1 for non-blocking
1984 		 * mode.
1985 		 */
1986 		newtimeout = -1;
1987 	} else {
1988 		/*
1989 		 * Restore the timeout set when the device was opened.
1990 		 * (Note that this may be -1, in which case we're not
1991 		 * really leaving non-blocking mode.  However, although
1992 		 * the timeout argument to pcap_set_timeout() and
1993 		 * pcap_open_live() is an int, you're not supposed to
1994 		 * supply a negative value, so that "shouldn't happen".)
1995 		 */
1996 		newtimeout = p->opt.timeout;
1997 	}
1998 	if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1999 		pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
2000 		    GetLastError(), "PacketSetReadTimeout");
2001 		return (-1);
2002 	}
2003 	pw->nonblock = (newtimeout == -1);
2004 	return (0);
2005 }
2006 
2007 static int
2008 pcap_add_if_npf(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
2009     const char *description, char *errbuf)
2010 {
2011 	pcap_if_t *curdev;
2012 	npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2013 	LONG if_addr_size;
2014 	int res = 0;
2015 
2016 	if_addr_size = MAX_NETWORK_ADDRESSES;
2017 
2018 	/*
2019 	 * Add an entry for this interface, with no addresses.
2020 	 */
2021 	curdev = add_dev(devlistp, name, flags, description, errbuf);
2022 	if (curdev == NULL) {
2023 		/*
2024 		 * Failure.
2025 		 */
2026 		return (-1);
2027 	}
2028 
2029 	/*
2030 	 * Get the list of addresses for the interface.
2031 	 */
2032 	if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
2033 		/*
2034 		 * Failure.
2035 		 *
2036 		 * We don't return an error, because this can happen with
2037 		 * NdisWan interfaces, and we want to supply them even
2038 		 * if we can't supply their addresses.
2039 		 *
2040 		 * We return an entry with an empty address list.
2041 		 */
2042 		return (0);
2043 	}
2044 
2045 	/*
2046 	 * Now add the addresses.
2047 	 */
2048 	while (if_addr_size-- > 0) {
2049 		/*
2050 		 * "curdev" is an entry for this interface; add an entry for
2051 		 * this address to its list of addresses.
2052 		 */
2053 		res = add_addr_to_dev(curdev,
2054 		    (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
2055 		    sizeof (struct sockaddr_storage),
2056 		    (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
2057 		    sizeof (struct sockaddr_storage),
2058 		    (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
2059 		    sizeof (struct sockaddr_storage),
2060 		    NULL,
2061 		    0,
2062 		    errbuf);
2063 		if (res == -1) {
2064 			/*
2065 			 * Failure.
2066 			 */
2067 			break;
2068 		}
2069 	}
2070 
2071 	return (res);
2072 }
2073 
2074 static int
2075 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
2076 {
2077 	char *name_copy;
2078 	ADAPTER *adapter;
2079 	int status;
2080 	size_t len;
2081 	NDIS_HARDWARE_STATUS hardware_status;
2082 #ifdef OID_GEN_PHYSICAL_MEDIUM
2083 	NDIS_PHYSICAL_MEDIUM phys_medium;
2084 	bpf_u_int32 gen_physical_medium_oids[] = {
2085   #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
2086 		OID_GEN_PHYSICAL_MEDIUM_EX,
2087   #endif
2088 		OID_GEN_PHYSICAL_MEDIUM
2089 	};
2090 #define N_GEN_PHYSICAL_MEDIUM_OIDS	(sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
2091 	size_t i;
2092 #endif /* OID_GEN_PHYSICAL_MEDIUM */
2093 #ifdef OID_GEN_LINK_STATE
2094 	NDIS_LINK_STATE link_state;
2095 #endif
2096 	int connect_status;
2097 
2098 	if (*flags & PCAP_IF_LOOPBACK) {
2099 		/*
2100 		 * Loopback interface, so the connection status doesn't
2101 		 * apply. and it's not wireless (or wired, for that
2102 		 * matter...).  We presume it's up and running.
2103 		 */
2104 		*flags |= PCAP_IF_UP | PCAP_IF_RUNNING | PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2105 		return (0);
2106 	}
2107 
2108 	/*
2109 	 * We need to open the adapter to get this information.
2110 	 *
2111 	 * XXX - PacketOpenAdapter() takes a non-const pointer
2112 	 * as an argument, so we make a copy of the argument and
2113 	 * pass that to it.
2114 	 */
2115 	name_copy = strdup(name);
2116 	adapter = PacketOpenAdapter(name_copy);
2117 	free(name_copy);
2118 	if (adapter == NULL) {
2119 		/*
2120 		 * Give up; if they try to open this device, it'll fail.
2121 		 */
2122 		return (0);
2123 	}
2124 
2125 #ifdef HAVE_AIRPCAP_API
2126 	/*
2127 	 * Airpcap.sys do not support the below 'OID_GEN_x' values.
2128 	 * Just set these flags (and none of the '*flags' entered with).
2129 	 */
2130 	if (PacketGetAirPcapHandle(adapter)) {
2131 		/*
2132 		 * Must be "up" and "running" if the above if succeeded.
2133 		 */
2134 		*flags = PCAP_IF_UP | PCAP_IF_RUNNING;
2135 
2136 		/*
2137 		 * An airpcap device is a wireless device (duh!)
2138 		 */
2139 		*flags |= PCAP_IF_WIRELESS;
2140 
2141 		/*
2142 		 * A "network association state" makes no sense for airpcap.
2143 		 */
2144 		*flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2145 		PacketCloseAdapter(adapter);
2146 		return (0);
2147 	}
2148 #endif
2149 
2150 	/*
2151 	 * Get the hardware status, and derive "up" and "running" from
2152 	 * that.
2153 	 */
2154 	len = sizeof (hardware_status);
2155 	status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
2156 	    &hardware_status, &len, errbuf);
2157 	if (status == 0) {
2158 		switch (hardware_status) {
2159 
2160 		case NdisHardwareStatusReady:
2161 			/*
2162 			 * "Available and capable of sending and receiving
2163 			 * data over the wire", so up and running.
2164 			 */
2165 			*flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
2166 			break;
2167 
2168 		case NdisHardwareStatusInitializing:
2169 		case NdisHardwareStatusReset:
2170 			/*
2171 			 * "Initializing" or "Resetting", so up, but
2172 			 * not running.
2173 			 */
2174 			*flags |= PCAP_IF_UP;
2175 			break;
2176 
2177 		case NdisHardwareStatusClosing:
2178 		case NdisHardwareStatusNotReady:
2179 			/*
2180 			 * "Closing" or "Not ready", so neither up nor
2181 			 * running.
2182 			 */
2183 			break;
2184 
2185 		default:
2186 			/*
2187 			 * Unknown.
2188 			 */
2189 			break;
2190 		}
2191 	} else {
2192 		/*
2193 		 * Can't get the hardware status, so assume both up and
2194 		 * running.
2195 		 */
2196 		*flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
2197 	}
2198 
2199 	/*
2200 	 * Get the network type.
2201 	 */
2202 #ifdef OID_GEN_PHYSICAL_MEDIUM
2203 	/*
2204 	 * Try the OIDs we have for this, in order.
2205 	 */
2206 	for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
2207 		len = sizeof (phys_medium);
2208 		status = oid_get_request(adapter, gen_physical_medium_oids[i],
2209 		    &phys_medium, &len, errbuf);
2210 		if (status == 0) {
2211 			/*
2212 			 * Success.
2213 			 */
2214 			break;
2215 		}
2216 		/*
2217 		 * Failed.  We can't determine whether it failed
2218 		 * because that particular OID isn't supported
2219 		 * or because some other problem occurred, so we
2220 		 * just drive on and try the next OID.
2221 		 */
2222 	}
2223 	if (status == 0) {
2224 		/*
2225 		 * We got the physical medium.
2226 		 *
2227 		 * XXX - we might want to check for NdisPhysicalMediumWiMax
2228 		 * and NdisPhysicalMediumNative802_15_4 being
2229 		 * part of the enum, and check for those in the "wireless"
2230 		 * case.
2231 		 */
2232 DIAG_OFF_ENUM_SWITCH
2233 		switch (phys_medium) {
2234 
2235 		case NdisPhysicalMediumWirelessLan:
2236 		case NdisPhysicalMediumWirelessWan:
2237 		case NdisPhysicalMediumNative802_11:
2238 		case NdisPhysicalMediumBluetooth:
2239 		case NdisPhysicalMediumUWB:
2240 		case NdisPhysicalMediumIrda:
2241 			/*
2242 			 * Wireless.
2243 			 */
2244 			*flags |= PCAP_IF_WIRELESS;
2245 			break;
2246 
2247 		default:
2248 			/*
2249 			 * Not wireless or unknown
2250 			 */
2251 			break;
2252 		}
2253 DIAG_ON_ENUM_SWITCH
2254 	}
2255 #endif
2256 
2257 	/*
2258 	 * Get the connection status.
2259 	 */
2260 #ifdef OID_GEN_LINK_STATE
2261 	len = sizeof(link_state);
2262 	status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
2263 	    &len, errbuf);
2264 	if (status == 0) {
2265 		/*
2266 		 * NOTE: this also gives us the receive and transmit
2267 		 * link state.
2268 		 */
2269 		switch (link_state.MediaConnectState) {
2270 
2271 		case MediaConnectStateConnected:
2272 			/*
2273 			 * It's connected.
2274 			 */
2275 			*flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2276 			break;
2277 
2278 		case MediaConnectStateDisconnected:
2279 			/*
2280 			 * It's disconnected.
2281 			 */
2282 			*flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2283 			break;
2284 
2285 		case MediaConnectStateUnknown:
2286 		default:
2287 			/*
2288 			 * It's unknown whether it's connected or not.
2289 			 */
2290 			break;
2291 		}
2292 	}
2293 #else
2294 	/*
2295 	 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2296 	 */
2297 	status = -1;
2298 #endif
2299 	if (status == -1) {
2300 		/*
2301 		 * OK, OID_GEN_LINK_STATE didn't work, try
2302 		 * OID_GEN_MEDIA_CONNECT_STATUS.
2303 		 */
2304 		status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
2305 		    &connect_status, &len, errbuf);
2306 		if (status == 0) {
2307 			switch (connect_status) {
2308 
2309 			case NdisMediaStateConnected:
2310 				/*
2311 				 * It's connected.
2312 				 */
2313 				*flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2314 				break;
2315 
2316 			case NdisMediaStateDisconnected:
2317 				/*
2318 				 * It's disconnected.
2319 				 */
2320 				*flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2321 				break;
2322 			}
2323 		}
2324 	}
2325 	PacketCloseAdapter(adapter);
2326 	return (0);
2327 }
2328 
2329 int
2330 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2331 {
2332 	int ret = 0;
2333 	const char *desc;
2334 	char *AdaptersName;
2335 	ULONG NameLength;
2336 	char *name;
2337 
2338 	/*
2339 	 * Find out how big a buffer we need.
2340 	 *
2341 	 * This call should always return FALSE; if the error is
2342 	 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2343 	 * the size of the buffer we need, otherwise there's a
2344 	 * problem, and NameLength should be set to 0.
2345 	 *
2346 	 * It shouldn't require NameLength to be set, but,
2347 	 * at least as of WinPcap 4.1.3, it checks whether
2348 	 * NameLength is big enough before it checks for a
2349 	 * NULL buffer argument, so, while it'll still do
2350 	 * the right thing if NameLength is uninitialized and
2351 	 * whatever junk happens to be there is big enough
2352 	 * (because the pointer argument will be null), it's
2353 	 * still reading an uninitialized variable.
2354 	 */
2355 	NameLength = 0;
2356 	if (!PacketGetAdapterNames(NULL, &NameLength))
2357 	{
2358 		DWORD last_error = GetLastError();
2359 
2360 		if (last_error != ERROR_INSUFFICIENT_BUFFER)
2361 		{
2362 			pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2363 			    last_error, "PacketGetAdapterNames");
2364 			return (-1);
2365 		}
2366 	}
2367 
2368 	if (NameLength <= 0)
2369 		return 0;
2370 	AdaptersName = (char*) malloc(NameLength);
2371 	if (AdaptersName == NULL)
2372 	{
2373 		snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
2374 		return (-1);
2375 	}
2376 
2377 	if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
2378 		pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2379 		    GetLastError(), "PacketGetAdapterNames");
2380 		free(AdaptersName);
2381 		return (-1);
2382 	}
2383 
2384 	/*
2385 	 * "PacketGetAdapterNames()" returned a list of
2386 	 * null-terminated ASCII interface name strings,
2387 	 * terminated by a null string, followed by a list
2388 	 * of null-terminated ASCII interface description
2389 	 * strings, terminated by a null string.
2390 	 * This means there are two ASCII nulls at the end
2391 	 * of the first list.
2392 	 *
2393 	 * Find the end of the first list; that's the
2394 	 * beginning of the second list.
2395 	 */
2396 	desc = &AdaptersName[0];
2397 	while (*desc != '\0' || *(desc + 1) != '\0')
2398 		desc++;
2399 
2400 	/*
2401 	 * Found it - "desc" points to the first of the two
2402 	 * nulls at the end of the list of names, so the
2403 	 * first byte of the list of descriptions is two bytes
2404 	 * after it.
2405 	 */
2406 	desc += 2;
2407 
2408 	/*
2409 	 * Loop over the elements in the first list.
2410 	 */
2411 	name = &AdaptersName[0];
2412 	while (*name != '\0') {
2413 		bpf_u_int32 flags = 0;
2414 
2415 #ifdef HAVE_AIRPCAP_API
2416 		/*
2417 		 * Is this an AirPcap device?
2418 		 * If so, ignore it; it'll get added later, by the
2419 		 * AirPcap code.
2420 		 */
2421 		if (device_is_airpcap(name, errbuf) == 1) {
2422 			name += strlen(name) + 1;
2423 			desc += strlen(desc) + 1;
2424 			continue;
2425 		}
2426 #endif
2427 
2428 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2429 		/*
2430 		 * Is this a loopback interface?
2431 		 */
2432 		if (PacketIsLoopbackAdapter(name)) {
2433 			/* Yes */
2434 			flags |= PCAP_IF_LOOPBACK;
2435 		}
2436 #endif
2437 		/*
2438 		 * Get additional flags.
2439 		 */
2440 		if (get_if_flags(name, &flags, errbuf) == -1) {
2441 			/*
2442 			 * Failure.
2443 			 */
2444 			ret = -1;
2445 			break;
2446 		}
2447 
2448 		/*
2449 		 * Add an entry for this interface.
2450 		 */
2451 		if (pcap_add_if_npf(devlistp, name, flags, desc,
2452 		    errbuf) == -1) {
2453 			/*
2454 			 * Failure.
2455 			 */
2456 			ret = -1;
2457 			break;
2458 		}
2459 		name += strlen(name) + 1;
2460 		desc += strlen(desc) + 1;
2461 	}
2462 
2463 	free(AdaptersName);
2464 	return (ret);
2465 }
2466 
2467 /*
2468  * Return the name of a network interface attached to the system, or NULL
2469  * if none can be found.  The interface must be configured up; the
2470  * lowest unit number is preferred; loopback is ignored.
2471  *
2472  * In the best of all possible worlds, this would be the same as on
2473  * UN*X, but there may be software that expects this to return a
2474  * full list of devices after the first device.
2475  */
2476 #define ADAPTERSNAME_LEN	8192
2477 char *
2478 pcap_lookupdev(char *errbuf)
2479 {
2480 	DWORD dwVersion;
2481 	DWORD dwWindowsMajorVersion;
2482 
2483 	/*
2484 	 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2485 	 * it may return UTF-16 strings, for backwards-compatibility
2486 	 * reasons, and we're also disabling the hack to make that work,
2487 	 * for not-going-past-the-end-of-a-string reasons, and 2) we
2488 	 * want its behavior to be consistent.
2489 	 *
2490 	 * In addition, it's not thread-safe, so we've marked it as
2491 	 * deprecated.
2492 	 */
2493 	if (pcap_new_api) {
2494 		snprintf(errbuf, PCAP_ERRBUF_SIZE,
2495 		    "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2496 		return (NULL);
2497 	}
2498 
2499 /* disable MSVC's GetVersion() deprecated warning here */
2500 DIAG_OFF_DEPRECATION
2501 	dwVersion = GetVersion();	/* get the OS version */
2502 DIAG_ON_DEPRECATION
2503 	dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
2504 
2505 	if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
2506 		/*
2507 		 * Windows 95, 98, ME.
2508 		 */
2509 		ULONG NameLength = ADAPTERSNAME_LEN;
2510 		static char AdaptersName[ADAPTERSNAME_LEN];
2511 
2512 		if (PacketGetAdapterNames(AdaptersName,&NameLength) )
2513 			return (AdaptersName);
2514 		else
2515 			return NULL;
2516 	} else {
2517 		/*
2518 		 * Windows NT (NT 4.0 and later).
2519 		 * Convert the names to Unicode for backward compatibility.
2520 		 */
2521 		ULONG NameLength = ADAPTERSNAME_LEN;
2522 		static WCHAR AdaptersName[ADAPTERSNAME_LEN];
2523 		size_t BufferSpaceLeft;
2524 		char *tAstr;
2525 		WCHAR *Unameptr;
2526 		char *Adescptr;
2527 		size_t namelen, i;
2528 		WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
2529 		int NAdapts = 0;
2530 
2531 		if(TAdaptersName == NULL)
2532 		{
2533 			(void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
2534 			return NULL;
2535 		}
2536 
2537 		if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
2538 		{
2539 			pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2540 			    GetLastError(), "PacketGetAdapterNames");
2541 			free(TAdaptersName);
2542 			return NULL;
2543 		}
2544 
2545 
2546 		BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
2547 		tAstr = (char*)TAdaptersName;
2548 		Unameptr = AdaptersName;
2549 
2550 		/*
2551 		 * Convert the device names to Unicode into AdapterName.
2552 		 */
2553 		do {
2554 			/*
2555 			 * Length of the name, including the terminating
2556 			 * NUL.
2557 			 */
2558 			namelen = strlen(tAstr) + 1;
2559 
2560 			/*
2561 			 * Do we have room for the name in the Unicode
2562 			 * buffer?
2563 			 */
2564 			if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
2565 				/*
2566 				 * No.
2567 				 */
2568 				goto quit;
2569 			}
2570 			BufferSpaceLeft -= namelen * sizeof(WCHAR);
2571 
2572 			/*
2573 			 * Copy the name, converting ASCII to Unicode.
2574 			 * namelen includes the NUL, so we copy it as
2575 			 * well.
2576 			 */
2577 			for (i = 0; i < namelen; i++)
2578 				*Unameptr++ = *tAstr++;
2579 
2580 			/*
2581 			 * Count this adapter.
2582 			 */
2583 			NAdapts++;
2584 		} while (namelen != 1);
2585 
2586 		/*
2587 		 * Copy the descriptions, but don't convert them from
2588 		 * ASCII to Unicode.
2589 		 */
2590 		Adescptr = (char *)Unameptr;
2591 		while(NAdapts--)
2592 		{
2593 			size_t desclen;
2594 
2595 			desclen = strlen(tAstr) + 1;
2596 
2597 			/*
2598 			 * Do we have room for the name in the Unicode
2599 			 * buffer?
2600 			 */
2601 			if (BufferSpaceLeft < desclen) {
2602 				/*
2603 				 * No.
2604 				 */
2605 				goto quit;
2606 			}
2607 
2608 			/*
2609 			 * Just copy the ASCII string.
2610 			 * namelen includes the NUL, so we copy it as
2611 			 * well.
2612 			 */
2613 			memcpy(Adescptr, tAstr, desclen);
2614 			Adescptr += desclen;
2615 			tAstr += desclen;
2616 			BufferSpaceLeft -= desclen;
2617 		}
2618 
2619 	quit:
2620 		free(TAdaptersName);
2621 		return (char *)(AdaptersName);
2622 	}
2623 }
2624 
2625 /*
2626  * We can't use the same code that we use on UN*X, as that's doing
2627  * UN*X-specific calls.
2628  *
2629  * We don't just fetch the entire list of devices, search for the
2630  * particular device, and use its first IPv4 address, as that's too
2631  * much work to get just one device's netmask.
2632  */
2633 int
2634 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
2635     char *errbuf)
2636 {
2637 	/*
2638 	 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2639 	 * in order to skip non IPv4 (i.e. IPv6 addresses)
2640 	 */
2641 	npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2642 	LONG if_addr_size = MAX_NETWORK_ADDRESSES;
2643 	struct sockaddr_in *t_addr;
2644 	LONG i;
2645 
2646 	if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
2647 		*netp = *maskp = 0;
2648 		return (0);
2649 	}
2650 
2651 	for(i = 0; i < if_addr_size; i++)
2652 	{
2653 		if(if_addrs[i].IPAddress.ss_family == AF_INET)
2654 		{
2655 			t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
2656 			*netp = t_addr->sin_addr.S_un.S_addr;
2657 			t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
2658 			*maskp = t_addr->sin_addr.S_un.S_addr;
2659 
2660 			*netp &= *maskp;
2661 			return (0);
2662 		}
2663 
2664 	}
2665 
2666 	*netp = *maskp = 0;
2667 	return (0);
2668 }
2669 
2670 static const char *pcap_lib_version_string;
2671 
2672 #ifdef HAVE_VERSION_H
2673 /*
2674  * libpcap being built for Windows, as part of a WinPcap/Npcap source
2675  * tree.  Include version.h from that source tree to get the WinPcap/Npcap
2676  * version.
2677  *
2678  * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2679  * number when building as part of WinPcap/Npcap.  (It'd be nice to do so
2680  * for the packet.dll version number as well.)
2681  */
2682 #include "../../version.h"
2683 
2684 static const char pcap_version_string[] =
2685 	WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2686 
2687 const char *
2688 pcap_lib_version(void)
2689 {
2690 	if (pcap_lib_version_string == NULL) {
2691 		/*
2692 		 * Generate the version string.
2693 		 */
2694 		const char *packet_version_string = PacketGetVersion();
2695 
2696 		if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2697 			/*
2698 			 * WinPcap/Npcap version string and packet.dll version
2699 			 * string are the same; just report the WinPcap/Npcap
2700 			 * version.
2701 			 */
2702 			pcap_lib_version_string = pcap_version_string;
2703 		} else {
2704 			/*
2705 			 * WinPcap/Npcap version string and packet.dll version
2706 			 * string are different; that shouldn't be the
2707 			 * case (the two libraries should come from the
2708 			 * same version of WinPcap/Npcap), so we report both
2709 			 * versions.
2710 			 */
2711 			char *full_pcap_version_string;
2712 
2713 			if (pcap_asprintf(&full_pcap_version_string,
2714 			    WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING,
2715 			    packet_version_string) != -1) {
2716 				/* Success */
2717 				pcap_lib_version_string = full_pcap_version_string;
2718 			}
2719 		}
2720 	}
2721 	return (pcap_lib_version_string);
2722 }
2723 
2724 #else /* HAVE_VERSION_H */
2725 
2726 /*
2727  * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2728  * tree.
2729  */
2730 const char *
2731 pcap_lib_version(void)
2732 {
2733 	if (pcap_lib_version_string == NULL) {
2734 		/*
2735 		 * Generate the version string.  Report the packet.dll
2736 		 * version.
2737 		 */
2738 		char *full_pcap_version_string;
2739 
2740 		if (pcap_asprintf(&full_pcap_version_string,
2741 		    PCAP_VERSION_STRING " (packet.dll version %s)",
2742 		    PacketGetVersion()) != -1) {
2743 			/* Success */
2744 			pcap_lib_version_string = full_pcap_version_string;
2745 		}
2746 	}
2747 	return (pcap_lib_version_string);
2748 }
2749 #endif /* HAVE_VERSION_H */
2750