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