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