2 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2010 CACE Technologies, Davis (California)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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
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.
39 #include <limits.h> /* for INT_MAX */
40 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
46 * XXX - Packet32.h defines bpf_program, so we can't include
47 * <pcap/bpf.h>, which also defines it; that's why we define
48 * PCAP_DONT_INCLUDE_PCAP_BPF_H,
50 * However, no header in the WinPcap or Npcap SDKs defines the
51 * macros for BPF code, so we have to define them ourselves.
56 /* Old-school MinGW have these headers in a different place.
58 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
59 #include <ddk/ntddndis.h>
62 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
68 #endif /* HAVE_DAG_API */
70 #include "diag-control.h"
72 #include "pcap-airpcap.h"
74 static int pcap_setfilter_npf(pcap_t *, struct bpf_program *);
75 static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
76 static int pcap_getnonblock_npf(pcap_t *);
77 static int pcap_setnonblock_npf(pcap_t *, int);
79 /*dimension of the buffer in the pcap_t structure*/
80 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
82 /*dimension of the buffer in the kernel driver NPF */
83 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
85 /* Equivalent to ntohs(), but a lot faster under Windows */
86 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
89 * Private data for capturing on WinPcap/Npcap devices.
92 ADAPTER *adapter; /* the packet32 ADAPTER for the device */
94 int rfmon_selfstart; /* a flag tells whether the monitor mode is set by itself */
95 int filtering_in_kernel; /* using kernel filter */
98 int dag_fcs_bits; /* Number of checksum bits from link layer */
102 int samp_npkt; /* parameter needed for sampling, with '1 out of N' method has been requested */
103 struct timeval samp_time; /* parameter needed for sampling, with '1 every N ms' method has been requested */
108 * Define stub versions of the monitor-mode support routines if this
109 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
112 #ifndef HAVE_NPCAP_PACKET_API
114 PacketIsMonitorModeSupported(PCHAR AdapterName _U_)
117 * We don't support monitor mode.
123 PacketSetMonitorMode(PCHAR AdapterName _U_, int mode _U_)
126 * This should never be called, as PacketIsMonitorModeSupported()
127 * will return 0, meaning "we don't support monitor mode, so
128 * don't try to turn it on or off".
134 PacketGetMonitorMode(PCHAR AdapterName _U_)
137 * This should fail, so that pcap_activate_npf() returns
138 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
146 * Sigh. PacketRequest() will have made a DeviceIoControl()
147 * call to the NPF driver to perform the OID request, with a
148 * BIOCQUERYOID ioctl. The kernel code should get back one
149 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
150 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
151 * supported by the OS or the driver, but that doesn't seem
152 * to make it to the caller of PacketRequest() in a
155 #define NDIS_STATUS_INVALID_OID 0xc0010017
156 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
157 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
160 oid_get_request(ADAPTER *adapter, bpf_u_int32 oid, void *data, size_t *lenp,
163 PACKET_OID_DATA *oid_data_arg;
166 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
167 * It should be big enough to hold "*lenp" bytes of data; it
168 * will actually be slightly larger, as PACKET_OID_DATA has a
169 * 1-byte data array at the end, standing in for the variable-length
170 * data that's actually there.
172 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
173 if (oid_data_arg == NULL) {
174 snprintf(errbuf, PCAP_ERRBUF_SIZE,
175 "Couldn't allocate argument buffer for PacketRequest");
180 * No need to copy the data - we're doing a fetch.
182 oid_data_arg->Oid = oid;
183 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
184 if (!PacketRequest(adapter, FALSE, oid_data_arg)) {
185 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
186 GetLastError(), "Error calling PacketRequest");
192 * Get the length actually supplied.
194 *lenp = oid_data_arg->Length;
197 * Copy back the data we fetched.
199 memcpy(data, oid_data_arg->Data, *lenp);
205 pcap_stats_npf(pcap_t *p, struct pcap_stat *ps)
207 struct pcap_win *pw = p->priv;
208 struct bpf_stat bstats;
211 * Try to get statistics.
213 * (Please note - "struct pcap_stat" is *not* the same as
214 * WinPcap's "struct bpf_stat". It might currently have the
215 * same layout, but let's not cheat.
217 * Note also that we don't fill in ps_capt, as we might have
218 * been called by code compiled against an earlier version of
219 * WinPcap that didn't have ps_capt, in which case filling it
220 * in would stomp on whatever comes after the structure passed
223 if (!PacketGetStats(pw->adapter, &bstats)) {
224 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
225 GetLastError(), "PacketGetStats error");
228 ps->ps_recv = bstats.bs_recv;
229 ps->ps_drop = bstats.bs_drop;
232 * XXX - PacketGetStats() doesn't fill this in, so we just
236 ps->ps_ifdrop = bstats.ps_ifdrop;
245 * Win32-only routine for getting statistics.
247 * This way is definitely safer than passing the pcap_stat * from the userland.
248 * In fact, there could happen than the user allocates a variable which is not
249 * big enough for the new structure, and the library will write in a zone
250 * which is not allocated to this variable.
252 * In this way, we're pretty sure we are writing on memory allocated to this
255 * XXX - but this is the wrong way to handle statistics. Instead, we should
256 * have an API that returns data in a form like the Options section of a
257 * pcapng Interface Statistics Block:
259 * https://xml2rfc.tools.ietf.org/cgi-bin/xml2rfc.cgi?url=https://raw.githubusercontent.com/pcapng/pcapng/master/draft-tuexen-opsawg-pcapng.xml&modeAsFormat=html/ascii&type=ascii#rfc.section.4.6
261 * which would let us add new statistics straightforwardly and indicate which
262 * statistics we are and are *not* providing, rather than having to provide
263 * possibly-bogus values for statistics we can't provide.
265 static struct pcap_stat *
266 pcap_stats_ex_npf(pcap_t *p, int *pcap_stat_size)
268 struct pcap_win *pw = p->priv;
269 struct bpf_stat bstats;
271 *pcap_stat_size = sizeof (p->stat);
274 * Try to get statistics.
276 * (Please note - "struct pcap_stat" is *not* the same as
277 * WinPcap's "struct bpf_stat". It might currently have the
278 * same layout, but let's not cheat.)
280 if (!PacketGetStatsEx(pw->adapter, &bstats)) {
281 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
282 GetLastError(), "PacketGetStatsEx error");
285 p->stat.ps_recv = bstats.bs_recv;
286 p->stat.ps_drop = bstats.bs_drop;
287 p->stat.ps_ifdrop = bstats.ps_ifdrop;
289 * Just in case this is ever compiled for a target other than
290 * Windows, which is somewhere between extremely unlikely and
294 p->stat.ps_capt = bstats.bs_capt;
299 /* Set the dimension of the kernel-level capture buffer */
301 pcap_setbuff_npf(pcap_t *p, int dim)
303 struct pcap_win *pw = p->priv;
305 if(PacketSetBuff(pw->adapter,dim)==FALSE)
307 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
313 /* Set the driver working mode */
315 pcap_setmode_npf(pcap_t *p, int mode)
317 struct pcap_win *pw = p->priv;
319 if(PacketSetMode(pw->adapter,mode)==FALSE)
321 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
328 /*set the minimum amount of data that will release a read call*/
330 pcap_setmintocopy_npf(pcap_t *p, int size)
332 struct pcap_win *pw = p->priv;
334 if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
336 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
343 pcap_getevent_npf(pcap_t *p)
345 struct pcap_win *pw = p->priv;
347 return (PacketGetReadEvent(pw->adapter));
351 pcap_oid_get_request_npf(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
353 struct pcap_win *pw = p->priv;
355 return (oid_get_request(pw->adapter, oid, data, lenp, p->errbuf));
359 pcap_oid_set_request_npf(pcap_t *p, bpf_u_int32 oid, const void *data,
362 struct pcap_win *pw = p->priv;
363 PACKET_OID_DATA *oid_data_arg;
366 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
367 * It should be big enough to hold "*lenp" bytes of data; it
368 * will actually be slightly larger, as PACKET_OID_DATA has a
369 * 1-byte data array at the end, standing in for the variable-length
370 * data that's actually there.
372 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
373 if (oid_data_arg == NULL) {
374 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
375 "Couldn't allocate argument buffer for PacketRequest");
379 oid_data_arg->Oid = oid;
380 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
381 memcpy(oid_data_arg->Data, data, *lenp);
382 if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
383 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
384 GetLastError(), "Error calling PacketRequest");
390 * Get the length actually copied.
392 *lenp = oid_data_arg->Length;
395 * No need to copy the data - we're doing a set.
402 pcap_sendqueue_transmit_npf(pcap_t *p, pcap_send_queue *queue, int sync)
404 struct pcap_win *pw = p->priv;
407 res = PacketSendPackets(pw->adapter,
412 if(res != queue->len){
413 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
414 GetLastError(), "Error queueing packets");
421 pcap_setuserbuffer_npf(pcap_t *p, int size)
423 unsigned char *new_buff;
426 /* Bogus parameter */
427 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
428 "Error: invalid size %d",size);
432 /* Allocate the buffer */
433 new_buff=(unsigned char*)malloc(sizeof(char)*size);
436 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
437 "Error: not enough memory");
449 #ifdef HAVE_NPCAP_PACKET_API
451 * Kernel dump mode isn't supported in Npcap; calls to PacketSetDumpName(),
452 * PacketSetDumpLimits(), and PacketIsDumpEnded() will get compile-time
453 * deprecation warnings.
455 * Avoid calling them; just return errors indicating that kernel dump
456 * mode isn't supported in Npcap.
459 pcap_live_dump_npf(pcap_t *p, char *filename _U_, int maxsize _U_,
462 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
463 "Npcap doesn't support kernel dump mode");
467 pcap_live_dump_ended_npf(pcap_t *p, int sync)
469 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
470 "Npcap doesn't support kernel dump mode");
473 #else /* HAVE_NPCAP_PACKET_API */
475 pcap_live_dump_npf(pcap_t *p, char *filename, int maxsize, int maxpacks)
477 struct pcap_win *pw = p->priv;
480 /* Set the packet driver in dump mode */
481 res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
483 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
484 "Error setting dump mode");
488 /* Set the name of the dump file */
489 res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
491 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
492 "Error setting kernel dump file name");
496 /* Set the limits of the dump file */
497 res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
499 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
500 "Error setting dump limit");
508 pcap_live_dump_ended_npf(pcap_t *p, int sync)
510 struct pcap_win *pw = p->priv;
512 return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
514 #endif /* HAVE_NPCAP_PACKET_API */
516 #ifdef HAVE_AIRPCAP_API
517 static PAirpcapHandle
518 pcap_get_airpcap_handle_npf(pcap_t *p)
520 struct pcap_win *pw = p->priv;
522 return (PacketGetAirPcapHandle(pw->adapter));
524 #else /* HAVE_AIRPCAP_API */
525 static PAirpcapHandle
526 pcap_get_airpcap_handle_npf(pcap_t *p _U_)
530 #endif /* HAVE_AIRPCAP_API */
533 pcap_read_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
538 register u_char *bp, *ep;
540 struct pcap_win *pw = p->priv;
545 * Has "pcap_breakloop()" been called?
549 * Yes - clear the flag that indicates that it
550 * has, and return PCAP_ERROR_BREAK to indicate
551 * that we were told to break out of the loop.
554 return (PCAP_ERROR_BREAK);
558 * Capture the packets.
560 * The PACKET structure had a bunch of extra stuff for
561 * Windows 9x/Me, but the only interesting data in it
562 * in the versions of Windows that we support is just
563 * a copy of p->buffer, a copy of p->buflen, and the
564 * actual number of bytes read returned from
565 * PacketReceivePacket(), none of which has to be
566 * retained from call to call, so we just keep one on
569 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
570 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
572 * Did the device go away?
573 * If so, the error we get can either be
574 * ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
576 DWORD errcode = GetLastError();
578 if (errcode == ERROR_GEN_FAILURE ||
579 errcode == ERROR_DEVICE_REMOVED) {
581 * The device on which we're capturing
582 * went away, or it became unusable
583 * by NPF due to a suspend/resume.
585 * ERROR_GEN_FAILURE comes from
586 * STATUS_UNSUCCESSFUL, as well as some
587 * other NT status codes that the Npcap
588 * driver is unlikely to return.
589 * XXX - hopefully no other error
590 * conditions are indicated by this.
592 * ERROR_DEVICE_REMOVED comes from
593 * STATUS_DEVICE_REMOVED.
595 * We report the Windows status code
596 * name and the corresponding NT status
597 * code name, for the benefit of attempts
598 * to debug cases where this error is
599 * reported when the device *wasn't*
600 * removed, either because it's not
601 * removable, it's removable but wasn't
602 * removed, or it's a device that doesn't
603 * correspond to a physical device.
605 * XXX - we really should return an
606 * appropriate error for that, but
607 * pcap_dispatch() etc. aren't
608 * documented as having error returns
609 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
611 const char *errcode_msg;
613 if (errcode == ERROR_GEN_FAILURE)
614 errcode_msg = "ERROR_GEN_FAILURE/STATUS_UNSUCCESSFUL";
616 errcode_msg = "ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED";
617 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
618 "The interface disappeared (error code %s)",
621 pcap_fmt_errmsg_for_win32_err(p->errbuf,
622 PCAP_ERRBUF_SIZE, errcode,
623 "PacketReceivePacket error");
628 cc = Packet.ulBytesReceived;
636 * Loop through each packet.
638 * This assumes that a single buffer of packets will have
639 * <= INT_MAX packets, so the packet count doesn't overflow.
641 #define bhp ((struct bpf_hdr *)bp)
645 register u_int caplen, hdrlen;
648 * Has "pcap_breakloop()" been called?
649 * If so, return immediately - if we haven't read any
650 * packets, clear the flag and return PCAP_ERROR_BREAK
651 * to indicate that we were told to break out of the loop,
652 * otherwise leave the flag set, so that the *next* call
653 * will break out of the loop without having read any
654 * packets, and return the number of packets we've
660 return (PCAP_ERROR_BREAK);
663 p->cc = (int) (ep - bp);
670 caplen = bhp->bh_caplen;
671 hdrlen = bhp->bh_hdrlen;
675 * Short-circuit evaluation: if using BPF filter
676 * in kernel, no need to do it now - we already know
677 * the packet passed the filter.
679 * XXX - pcap_filter() should always return TRUE if
680 * handed a null pointer for the program, but it might
681 * just try to "run" the filter, so we check here.
683 if (pw->filtering_in_kernel ||
684 p->fcode.bf_insns == NULL ||
685 pcap_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
687 switch (p->rmt_samp.method) {
689 case PCAP_SAMP_1_EVERY_N:
690 pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
692 /* Discard all packets that are not '1 out of N' */
693 if (pw->samp_npkt != 0) {
694 bp += Packet_WORDALIGN(caplen + hdrlen);
699 case PCAP_SAMP_FIRST_AFTER_N_MS:
701 struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
704 * Check if the timestamp of the arrived
705 * packet is smaller than our target time.
707 if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
708 (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
709 bp += Packet_WORDALIGN(caplen + hdrlen);
714 * The arrived packet is suitable for being
715 * delivered to our caller, so let's update
718 pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
719 if (pw->samp_time.tv_usec > 1000000) {
720 pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
721 pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
725 #endif /* ENABLE_REMOTE */
728 * XXX A bpf_hdr matches a pcap_pkthdr.
730 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
731 bp += Packet_WORDALIGN(caplen + hdrlen);
732 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
734 p->cc = (int) (ep - bp);
741 bp += Packet_WORDALIGN(caplen + hdrlen);
751 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
753 struct pcap_win *pw = p->priv;
756 int packet_len = 0, caplen = 0;
757 struct pcap_pkthdr pcap_header;
760 dag_record_t *header;
761 unsigned erf_record_len;
765 unsigned dfp = pw->adapter->DagFastProcess;
768 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
771 * Get new packets from the network.
773 * The PACKET structure had a bunch of extra stuff for
774 * Windows 9x/Me, but the only interesting data in it
775 * in the versions of Windows that we support is just
776 * a copy of p->buffer, a copy of p->buflen, and the
777 * actual number of bytes read returned from
778 * PacketReceivePacket(), none of which has to be
779 * retained from call to call, so we just keep one on
782 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
783 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
784 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
788 cc = Packet.ulBytesReceived;
790 /* The timeout has expired but we no packets arrived */
792 header = (dag_record_t*)pw->adapter->DagBuffer;
795 header = (dag_record_t*)p->bp;
797 endofbuf = (char*)header + cc;
800 * This can conceivably process more than INT_MAX packets,
801 * which would overflow the packet count, causing it either
802 * to look like a negative number, and thus cause us to
803 * return a value that looks like an error, or overflow
804 * back into positive territory, and thus cause us to
805 * return a too-low count.
807 * Therefore, if the packet count is unlimited, we clip
808 * it at INT_MAX; this routine is not expected to
809 * process packets indefinitely, so that's not an issue.
811 if (PACKET_COUNT_IS_UNLIMITED(cnt))
815 * Cycle through the packets
819 erf_record_len = SWAPS(header->rlen);
820 if((char*)header + erf_record_len > endofbuf)
823 /* Increase the number of captured packets */
826 /* Find the beginning of the packet */
827 dp = ((u_char *)header) + dag_record_size;
829 /* Determine actual packet len */
833 packet_len = ATM_SNAPLEN;
834 caplen = ATM_SNAPLEN;
840 swt = SWAPS(header->wlen);
841 packet_len = swt - (pw->dag_fcs_bits);
842 caplen = erf_record_len - dag_record_size - 2;
843 if (caplen > packet_len)
852 swt = SWAPS(header->wlen);
853 packet_len = swt - (pw->dag_fcs_bits);
854 caplen = erf_record_len - dag_record_size;
855 if (caplen > packet_len)
863 if(caplen > p->snapshot)
864 caplen = p->snapshot;
867 * Has "pcap_breakloop()" been called?
868 * If so, return immediately - if we haven't read any
869 * packets, clear the flag and return -2 to indicate
870 * that we were told to break out of the loop, otherwise
871 * leave the flag set, so that the *next* call will break
872 * out of the loop without having read any packets, and
873 * return the number of packets we've processed so far.
884 p->bp = (char*)header;
885 p->cc = endofbuf - (char*)header;
892 /* convert between timestamp formats */
894 pcap_header.ts.tv_sec = (int)(ts >> 32);
895 ts = (ts & 0xffffffffi64) * 1000000;
896 ts += 0x80000000; /* rounding */
897 pcap_header.ts.tv_usec = (int)(ts >> 32);
898 if (pcap_header.ts.tv_usec >= 1000000) {
899 pcap_header.ts.tv_usec -= 1000000;
900 pcap_header.ts.tv_sec++;
904 /* No underlying filtering system. We need to filter on our own */
905 if (p->fcode.bf_insns)
907 if (pcap_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
909 /* Move to next packet */
910 header = (dag_record_t*)((char*)header + erf_record_len);
915 /* Fill the header for the user supplied callback function */
916 pcap_header.caplen = caplen;
917 pcap_header.len = packet_len;
919 /* Call the callback function */
920 (*callback)(user, &pcap_header, dp);
922 /* Move to next packet */
923 header = (dag_record_t*)((char*)header + erf_record_len);
925 /* Stop if the number of packets requested by user has been reached*/
926 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
928 p->bp = (char*)header;
929 p->cc = endofbuf - (char*)header;
933 while((u_char*)header < endofbuf);
937 #endif /* HAVE_DAG_API */
939 /* Send a packet to the network */
941 pcap_inject_npf(pcap_t *p, const void *buf, int size)
943 struct pcap_win *pw = p->priv;
946 PacketInitPacket(&pkt, (PVOID)buf, size);
947 if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
948 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
949 GetLastError(), "send error: PacketSendPacket failed");
954 * We assume it all got sent if "PacketSendPacket()" succeeded.
955 * "pcap_inject()" is expected to return the number of bytes
962 pcap_cleanup_npf(pcap_t *p)
964 struct pcap_win *pw = p->priv;
966 if (pw->adapter != NULL) {
967 PacketCloseAdapter(pw->adapter);
970 if (pw->rfmon_selfstart)
972 PacketSetMonitorMode(p->opt.device, 0);
974 pcap_cleanup_live_common(p);
978 pcap_breakloop_npf(pcap_t *p)
980 pcap_breakloop_common(p);
981 struct pcap_win *pw = p->priv;
983 /* XXX - what if this fails? */
984 SetEvent(PacketGetReadEvent(pw->adapter));
988 * These are NTSTATUS values:
990 * https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/87fba13e-bf06-450e-83b1-9241dc81e781
992 * with the "Customer" bit set. If a driver returns them, they are not
993 * mapped to Windows error values in userland; they're returned by
996 * Note that "driver" here includes the Npcap NPF driver, as various
997 * versions would take NT status values and set the "Customer" bit
998 * before returning the status code. The commit message for the
999 * change that started doing that is
1001 * Returned a customer-defined NTSTATUS in OID requests to avoid
1002 * NTSTATUS-to-Win32 Error code translation.
1004 * but I don't know why the goal was to avoid that translation.
1006 * Attempting to set the hardware filter on a Microsoft Surface Pro's
1007 * Mobile Broadband Adapter returns an error that appears to be
1008 * NDIS_STATUS_NOT_SUPPORTED ORed with the "Customer" bit, so it's
1009 * probably indicating that it doesn't support that.
1011 * It is likely that there are other devices which throw spurious errors,
1012 * at which point this will need refactoring to efficiently check against
1013 * a list, but for now we can just check this one value. Perhaps the
1014 * right way to do this is compare against various NDIS errors with
1015 * the "customer" bit ORed in.
1017 #define NT_STATUS_CUSTOMER_DEFINED 0x20000000
1020 pcap_activate_npf(pcap_t *p)
1022 struct pcap_win *pw = p->priv;
1026 struct bpf_insn total_insn;
1027 struct bpf_program total_prog;
1031 * Monitor mode is supported on Windows Vista and later.
1033 if (PacketGetMonitorMode(p->opt.device) == 1)
1035 pw->rfmon_selfstart = 0;
1039 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
1041 pw->rfmon_selfstart = 0;
1042 // Monitor mode is not supported.
1045 return PCAP_ERROR_RFMON_NOTSUP;
1054 pw->rfmon_selfstart = 1;
1059 /* Init Winsock if it hasn't already been initialized */
1062 pw->adapter = PacketOpenAdapter(p->opt.device);
1064 if (pw->adapter == NULL)
1066 DWORD errcode = GetLastError();
1069 * What error did we get when trying to open the adapter?
1073 case ERROR_BAD_UNIT:
1075 * There's no such device.
1076 * There's nothing to add, so clear the error
1079 p->errbuf[0] = '\0';
1080 return (PCAP_ERROR_NO_SUCH_DEVICE);
1082 case ERROR_ACCESS_DENIED:
1084 * There is, but we don't have permission to
1087 * XXX - we currently get ERROR_BAD_UNIT if the
1088 * user says "no" to the UAC prompt.
1090 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1091 "The helper program for \"Admin-only Mode\" must be allowed to make changes to your device");
1092 return (PCAP_ERROR_PERM_DENIED);
1096 * Unknown - report details.
1098 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1099 errcode, "Error opening adapter");
1100 if (pw->rfmon_selfstart)
1102 PacketSetMonitorMode(p->opt.device, 0);
1104 return (PCAP_ERROR);
1108 /*get network type*/
1109 if(PacketGetNetType (pw->adapter,&type) == FALSE)
1111 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1112 GetLastError(), "Cannot determine the network type");
1116 /*Set the linktype*/
1117 switch (type.LinkType)
1120 * NDIS-defined medium types.
1122 case NdisMedium802_3:
1123 p->linktype = DLT_EN10MB;
1125 * This is (presumably) a real Ethernet capture; give it a
1126 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1127 * that an application can let you choose it, in case you're
1128 * capturing DOCSIS traffic that a Cisco Cable Modem
1129 * Termination System is putting out onto an Ethernet (it
1130 * doesn't put an Ethernet header onto the wire, it puts raw
1131 * DOCSIS frames out on the wire inside the low-level
1132 * Ethernet framing).
1134 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1136 * If that fails, just leave the list empty.
1138 if (p->dlt_list != NULL) {
1139 p->dlt_list[0] = DLT_EN10MB;
1140 p->dlt_list[1] = DLT_DOCSIS;
1145 case NdisMedium802_5:
1149 p->linktype = DLT_IEEE802;
1152 case NdisMediumFddi:
1153 p->linktype = DLT_FDDI;
1157 p->linktype = DLT_EN10MB;
1160 case NdisMediumArcnetRaw:
1161 p->linktype = DLT_ARCNET;
1164 case NdisMediumArcnet878_2:
1165 p->linktype = DLT_ARCNET;
1169 p->linktype = DLT_ATM_RFC1483;
1172 case NdisMediumWirelessWan:
1173 p->linktype = DLT_RAW;
1177 p->linktype = DLT_RAW;
1181 * Npcap-defined medium types.
1183 case NdisMediumNull:
1184 p->linktype = DLT_NULL;
1187 case NdisMediumCHDLC:
1188 p->linktype = DLT_CHDLC;
1191 case NdisMediumPPPSerial:
1192 p->linktype = DLT_PPP_SERIAL;
1195 case NdisMediumBare80211:
1196 p->linktype = DLT_IEEE802_11;
1199 case NdisMediumRadio80211:
1200 p->linktype = DLT_IEEE802_11_RADIO;
1204 p->linktype = DLT_PPI;
1209 * An unknown medium type is assumed to supply Ethernet
1210 * headers; if not, the user will have to report it,
1211 * so that the medium type and link-layer header type
1212 * can be determined. If we were to fail here, we
1213 * might get the link-layer type in the error, but
1214 * the user wouldn't get a capture, so we wouldn't
1215 * be able to determine the link-layer type; we report
1216 * a warning with the link-layer type, so at least
1217 * some programs will report the warning.
1219 p->linktype = DLT_EN10MB;
1220 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1221 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1223 status = PCAP_WARNING;
1227 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1229 * Set the timestamp type.
1230 * (Yes, we require PacketGetTimestampModes(), not just
1231 * PacketSetTimestampMode(). If we have the former, we
1232 * have the latter, unless somebody's using a version
1233 * of Npcap that they've hacked to provide the former
1234 * but not the latter; if they've done that, either
1235 * they're confused or they're trolling us.)
1237 switch (p->opt.tstamp_type) {
1239 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED:
1241 * Better than low-res, but *not* synchronized with
1244 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION))
1246 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1247 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1252 case PCAP_TSTAMP_HOST_LOWPREC:
1254 * Low-res, but synchronized with the OS clock.
1256 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME))
1258 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1259 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1264 case PCAP_TSTAMP_HOST_HIPREC:
1266 * High-res, and synchronized with the OS clock.
1268 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE))
1270 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1271 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1276 case PCAP_TSTAMP_HOST:
1278 * XXX - do whatever the default is, for now.
1279 * Set to the highest resolution that's synchronized
1280 * with the system clock?
1284 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1287 * Turn a negative snapshot value (invalid), a snapshot value of
1288 * 0 (unspecified), or a value bigger than the normal maximum
1289 * value, into the maximum allowed value.
1291 * If some application really *needs* a bigger snapshot
1292 * length, we should just increase MAXIMUM_SNAPLEN.
1294 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1295 p->snapshot = MAXIMUM_SNAPLEN;
1297 /* Set promiscuous mode */
1301 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1303 DWORD errcode = GetLastError();
1306 * Suppress spurious error generated by non-compiant
1307 * MS Surface mobile adapters that appear to
1308 * return NDIS_STATUS_NOT_SUPPORTED for attempts
1309 * to set the hardware filter.
1311 * It appears to be reporting NDIS_STATUS_NOT_SUPPORTED,
1312 * but with the NT status value "Customer" bit set;
1313 * the Npcap NPF driver sets that bit in some cases.
1315 * If we knew that this meant "promiscuous mode
1316 * isn't supported", we could add a "promiscuous
1317 * mode isn't supported" error code and return
1320 * 1) we don't know that it means that
1321 * rather than meaning "we reject attempts
1322 * to set the filter, even though the NDIS
1323 * specifications say you shouldn't do that"
1327 * 2) other interface types that don't
1328 * support promiscuous mode, at least
1329 * on UN*Xes, just silently ignore
1330 * attempts to set promiscuous mode
1332 * and rejecting it with an error could disrupt
1333 * attempts to capture, as many programs (tcpdump,
1334 * *shark) default to promiscuous mode.
1336 * Alternatively, we could return the "promiscuous
1337 * mode not supported" *warning* value, so that
1338 * correct code will either ignore it or report
1339 * it and continue capturing. (This may require
1340 * a pcap_init() flag to request that return
1341 * value, so that old incorrect programs that
1342 * assume a non-zero return from pcap_activate()
1343 * is an error don't break.)
1345 if (errcode != (NDIS_STATUS_NOT_SUPPORTED|NT_STATUS_CUSTOMER_DEFINED))
1347 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1348 PCAP_ERRBUF_SIZE, errcode,
1349 "failed to set hardware filter to promiscuous mode");
1357 * NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by
1358 * installed protocols and all packets indicated by the NIC",
1359 * but if no protocol drivers (like TCP/IP) are installed,
1360 * NDIS_PACKET_TYPE_DIRECTED, NDIS_PACKET_TYPE_BROADCAST,
1361 * and NDIS_PACKET_TYPE_MULTICAST are needed to capture
1364 if (PacketSetHwFilter(pw->adapter,
1365 NDIS_PACKET_TYPE_ALL_LOCAL |
1366 NDIS_PACKET_TYPE_DIRECTED |
1367 NDIS_PACKET_TYPE_BROADCAST |
1368 NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1370 DWORD errcode = GetLastError();
1373 * Suppress spurious error generated by non-compiant
1374 * MS Surface mobile adapters.
1376 if (errcode != (NDIS_STATUS_NOT_SUPPORTED|NT_STATUS_CUSTOMER_DEFINED))
1378 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1379 PCAP_ERRBUF_SIZE, errcode,
1380 "failed to set hardware filter to non-promiscuous mode");
1386 /* Set the buffer size */
1387 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1389 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1392 * Traditional Adapter
1395 * If the buffer size wasn't explicitly set, default to
1396 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1398 if (p->opt.buffer_size == 0)
1399 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1401 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1403 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1407 p->buffer = malloc(p->bufsize);
1408 if (p->buffer == NULL)
1410 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1415 if (p->opt.immediate)
1417 /* tell the driver to copy the buffer as soon as data arrives */
1418 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1420 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1421 PCAP_ERRBUF_SIZE, GetLastError(),
1422 "Error calling PacketSetMinToCopy");
1428 /* tell the driver to copy the buffer only if it contains at least 16K */
1429 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1431 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1432 PCAP_ERRBUF_SIZE, GetLastError(),
1433 "Error calling PacketSetMinToCopy");
1443 * We have DAG support.
1452 snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1453 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1454 strstr(_strlwr(p->opt.device), "dag"));
1457 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1458 if(status != ERROR_SUCCESS)
1461 status = RegQueryValueEx(dagkey,
1468 if(status != ERROR_SUCCESS)
1473 RegCloseKey(dagkey);
1478 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1480 /* Set the length of the FCS associated to any packet. This value
1481 * will be subtracted to the packet length */
1482 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1483 #else /* HAVE_DAG_API */
1488 #endif /* HAVE_DAG_API */
1492 * If there's no filter program installed, there's
1493 * no indication to the kernel of what the snapshot
1494 * length should be, so no snapshotting is done.
1496 * Therefore, when we open the device, we install
1497 * an "accept everything" filter with the specified
1500 total_insn.code = (u_short)(BPF_RET | BPF_K);
1503 total_insn.k = p->snapshot;
1505 total_prog.bf_len = 1;
1506 total_prog.bf_insns = &total_insn;
1507 if (!PacketSetBpf(pw->adapter, &total_prog)) {
1508 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1509 GetLastError(), "PacketSetBpf");
1510 status = PCAP_ERROR;
1514 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1516 /* disable loopback capture if requested */
1517 if (p->opt.nocapture_local)
1519 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1521 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1522 "Unable to disable the capture of loopback packets.");
1528 if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1530 /* install dag specific handlers for read and setfilter */
1531 p->read_op = pcap_read_win32_dag;
1532 p->setfilter_op = pcap_setfilter_win32_dag;
1536 #endif /* HAVE_DAG_API */
1537 /* install traditional npf handlers for read and setfilter */
1538 p->read_op = pcap_read_npf;
1539 p->setfilter_op = pcap_setfilter_npf;
1542 #endif /* HAVE_DAG_API */
1543 p->setdirection_op = NULL; /* Not implemented. */
1544 /* XXX - can this be implemented on some versions of Windows? */
1545 p->inject_op = pcap_inject_npf;
1546 p->set_datalink_op = NULL; /* can't change data link type */
1547 p->getnonblock_op = pcap_getnonblock_npf;
1548 p->setnonblock_op = pcap_setnonblock_npf;
1549 p->stats_op = pcap_stats_npf;
1550 p->breakloop_op = pcap_breakloop_npf;
1551 p->stats_ex_op = pcap_stats_ex_npf;
1552 p->setbuff_op = pcap_setbuff_npf;
1553 p->setmode_op = pcap_setmode_npf;
1554 p->setmintocopy_op = pcap_setmintocopy_npf;
1555 p->getevent_op = pcap_getevent_npf;
1556 p->oid_get_request_op = pcap_oid_get_request_npf;
1557 p->oid_set_request_op = pcap_oid_set_request_npf;
1558 p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1559 p->setuserbuffer_op = pcap_setuserbuffer_npf;
1560 p->live_dump_op = pcap_live_dump_npf;
1561 p->live_dump_ended_op = pcap_live_dump_ended_npf;
1562 p->get_airpcap_handle_op = pcap_get_airpcap_handle_npf;
1563 p->cleanup_op = pcap_cleanup_npf;
1566 * XXX - this is only done because WinPcap supported
1567 * pcap_fileno() returning the hFile HANDLE from the
1568 * ADAPTER structure. We make no general guarantees
1569 * that the caller can do anything useful with it.
1571 * (Not that we make any general guarantee of that
1572 * sort on UN*X, either, any more, given that not
1573 * all capture devices are regular OS network
1576 p->handle = pw->adapter->hFile;
1580 pcap_cleanup_npf(p);
1581 return (PCAP_ERROR);
1585 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1588 pcap_can_set_rfmon_npf(pcap_t *p)
1590 return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1594 * Get a list of time stamp types.
1596 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1598 get_ts_types(const char *device, pcap_t *p, char *ebuf)
1600 char *device_copy = NULL;
1601 ADAPTER *adapter = NULL;
1604 DWORD error = ERROR_SUCCESS;
1605 ULONG *modes = NULL;
1610 * First, find out how many time stamp modes we have.
1611 * To do that, we have to open the adapter.
1613 * XXX - PacketOpenAdapter() takes a non-const pointer
1614 * as an argument, so we make a copy of the argument and
1617 device_copy = strdup(device);
1618 if (device_copy == NULL) {
1619 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1624 adapter = PacketOpenAdapter(device_copy);
1625 if (adapter == NULL)
1627 error = GetLastError();
1629 * If we can't open the device now, we won't be
1630 * able to later, either.
1632 * If the error is something that indicates
1633 * that the device doesn't exist, or that they
1634 * don't have permission to open the device - or
1635 * perhaps that they don't have permission to get
1636 * a list of devices, if PacketOpenAdapter() does
1637 * that - the user will find that out when they try
1638 * to activate the device; just return an empty
1639 * list of time stamp types.
1641 * Treating either of those as errors will, for
1642 * example, cause "tcpdump -i <number>" to fail,
1643 * because it first tries to pass the interface
1644 * name to pcap_create() and pcap_activate(),
1645 * in order to handle OSes where interfaces can
1646 * have names that are just numbers (stand up
1647 * and say hello, Linux!), and, if pcap_activate()
1648 * fails with a "no such device" error, checks
1649 * whether the interface name is a valid number
1650 * and, if so, tries to use it as an index in
1651 * the list of interfaces.
1653 * That means pcap_create() must succeed even
1654 * for interfaces that don't exist, with the
1655 * failure occurring at pcap_activate() time.
1657 if (error == ERROR_BAD_UNIT ||
1658 error == ERROR_ACCESS_DENIED) {
1659 p->tstamp_type_count = 0;
1660 p->tstamp_type_list = NULL;
1663 pcap_fmt_errmsg_for_win32_err(ebuf,
1664 PCAP_ERRBUF_SIZE, error,
1665 "Error opening adapter");
1672 * Get the total number of time stamp modes.
1674 * The buffer for PacketGetTimestampModes() is
1675 * a sequence of 1 or more ULONGs. What's
1676 * passed to PacketGetTimestampModes() should have
1677 * the total number of ULONGs in the first ULONG;
1678 * what's returned *from* PacketGetTimestampModes()
1679 * has the total number of time stamp modes in
1682 * Yes, that means if there are N time stamp
1683 * modes, the first ULONG should be set to N+1
1684 * on input, and will be set to N on output.
1686 * We first make a call to PacketGetTimestampModes()
1687 * with a pointer to a single ULONG set to 1; the
1688 * call should fail with ERROR_MORE_DATA (unless
1689 * there are *no* modes, but that should never
1690 * happen), and that ULONG should be set to the
1694 ret = PacketGetTimestampModes(adapter, &num_ts_modes);
1697 * OK, it failed. Did it fail with
1700 error = GetLastError();
1701 if (error != ERROR_MORE_DATA) {
1703 * No, did it fail with ERROR_INVALID_FUNCTION?
1705 if (error == ERROR_INVALID_FUNCTION) {
1707 * This is probably due to
1708 * the driver with which Packet.dll
1709 * communicates being older, or
1710 * being a WinPcap driver, so
1711 * that it doesn't support
1712 * BIOCGTIMESTAMPMODES.
1714 * Tell the user to try uninstalling
1715 * Npcap - and WinPcap if installed -
1716 * and re-installing it, to flush
1717 * out all older drivers.
1719 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1720 "PacketGetTimestampModes() failed with ERROR_INVALID_FUNCTION; try uninstalling Npcap, and WinPcap if installed, and re-installing it from npcap.com");
1726 * No, some other error. Fail.
1728 pcap_fmt_errmsg_for_win32_err(ebuf,
1729 PCAP_ERRBUF_SIZE, error,
1730 "Error calling PacketGetTimestampModes");
1735 /* else (ret == TRUE)
1736 * Unexpected success. Let's act like we got ERROR_MORE_DATA.
1737 * If it doesn't work, we'll hit some other error condition farther on.
1740 /* If the driver reports no modes supported *and*
1741 * ERROR_MORE_DATA, something is seriously wrong.
1742 * We *could* ignore the error and continue without supporting
1743 * settable timestamp modes, but that would hide a bug.
1745 if (num_ts_modes == 0) {
1746 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1747 "PacketGetTimestampModes() reports 0 modes supported.");
1753 * Yes, so we now know how many types to fetch.
1755 * The buffer needs to have one ULONG for the
1756 * count and num_ts_modes ULONGs for the
1757 * num_ts_modes time stamp types.
1759 modes = (ULONG *)malloc((1 + num_ts_modes) * sizeof(ULONG));
1760 if (modes == NULL) {
1761 /* Out of memory. */
1762 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1766 modes[0] = 1 + num_ts_modes;
1767 if (!PacketGetTimestampModes(adapter, modes)) {
1768 pcap_fmt_errmsg_for_win32_err(ebuf,
1769 PCAP_ERRBUF_SIZE, GetLastError(),
1770 "Error calling PacketGetTimestampModes");
1774 if (modes[0] != num_ts_modes) {
1775 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1776 "First PacketGetTimestampModes() call gives %lu modes, second call gives %lu modes",
1777 num_ts_modes, modes[0]);
1783 * Allocate a buffer big enough for
1784 * PCAP_TSTAMP_HOST (default) plus
1785 * the explicitly specified modes.
1787 p->tstamp_type_list = malloc((1 + num_ts_modes) * sizeof(u_int));
1788 if (p->tstamp_type_list == NULL) {
1789 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1793 u_int num_ts_types = 0;
1794 p->tstamp_type_list[num_ts_types] =
1797 for (ULONG i = 0; i < num_ts_modes; i++) {
1798 switch (modes[i + 1]) {
1800 case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION:
1802 * Better than low-res,
1803 * but *not* synchronized
1804 * with the OS clock.
1806 p->tstamp_type_list[num_ts_types] =
1807 PCAP_TSTAMP_HOST_HIPREC_UNSYNCED;
1811 case TIMESTAMPMODE_QUERYSYSTEMTIME:
1813 * Low-res, but synchronized
1814 * with the OS clock.
1816 p->tstamp_type_list[num_ts_types] =
1817 PCAP_TSTAMP_HOST_LOWPREC;
1821 case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE:
1823 * High-res, and synchronized
1824 * with the OS clock.
1826 p->tstamp_type_list[num_ts_types] =
1827 PCAP_TSTAMP_HOST_HIPREC;
1833 * Unknown, so we can't
1839 p->tstamp_type_count = num_ts_types;
1842 /* Clean up temporary allocations */
1843 if (device_copy != NULL) {
1846 if (modes != NULL) {
1849 if (adapter != NULL) {
1850 PacketCloseAdapter(adapter);
1855 #else /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1857 get_ts_types(const char *device _U_, pcap_t *p _U_, char *ebuf _U_)
1860 * Nothing to fetch, so it always "succeeds".
1864 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1867 pcap_create_interface(const char *device _U_, char *ebuf)
1871 p = PCAP_CREATE_COMMON(ebuf, struct pcap_win);
1875 p->activate_op = pcap_activate_npf;
1876 p->can_set_rfmon_op = pcap_can_set_rfmon_npf;
1878 if (get_ts_types(device, p, ebuf) == -1) {
1886 pcap_setfilter_npf(pcap_t *p, struct bpf_program *fp)
1888 struct pcap_win *pw = p->priv;
1890 if(PacketSetBpf(pw->adapter,fp)==FALSE){
1892 * Kernel filter not installed.
1894 * XXX - we don't know whether this failed because:
1896 * the kernel rejected the filter program as invalid,
1897 * in which case we should fall back on userland
1900 * the kernel rejected the filter program as too big,
1901 * in which case we should again fall back on
1902 * userland filtering;
1904 * there was some other problem, in which case we
1905 * should probably report an error.
1907 * For NPF devices, the Win32 status will be
1908 * STATUS_INVALID_DEVICE_REQUEST for invalid
1909 * filters, but I don't know what it'd be for
1910 * other problems, and for some other devices
1911 * it might not be set at all.
1913 * So we just fall back on userland filtering in
1918 * install_bpf_program() validates the program.
1920 * XXX - what if we already have a filter in the kernel?
1922 if (install_bpf_program(p, fp) < 0)
1924 pw->filtering_in_kernel = 0; /* filtering in userland */
1931 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1934 * Discard any previously-received packets, as they might have
1935 * passed whatever filter was formerly in effect, but might
1936 * not pass this filter (BIOCSETF discards packets buffered
1937 * in the kernel, so you can lose packets in any case).
1944 * We filter at user level, since the kernel driver doesn't process the packets
1947 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1951 pcap_strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1955 /* Install a user level filter */
1956 if (install_bpf_program(p, fp) < 0)
1963 pcap_getnonblock_npf(pcap_t *p)
1965 struct pcap_win *pw = p->priv;
1968 * XXX - if there were a PacketGetReadTimeout() call, we
1969 * would use it, and return 1 if the timeout is -1
1972 return (pw->nonblock);
1976 pcap_setnonblock_npf(pcap_t *p, int nonblock)
1978 struct pcap_win *pw = p->priv;
1983 * Set the packet buffer timeout to -1 for non-blocking
1989 * Restore the timeout set when the device was opened.
1990 * (Note that this may be -1, in which case we're not
1991 * really leaving non-blocking mode. However, although
1992 * the timeout argument to pcap_set_timeout() and
1993 * pcap_open_live() is an int, you're not supposed to
1994 * supply a negative value, so that "shouldn't happen".)
1996 newtimeout = p->opt.timeout;
1998 if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1999 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
2000 GetLastError(), "PacketSetReadTimeout");
2003 pw->nonblock = (newtimeout == -1);
2008 pcap_add_if_npf(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
2009 const char *description, char *errbuf)
2012 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2016 if_addr_size = MAX_NETWORK_ADDRESSES;
2019 * Add an entry for this interface, with no addresses.
2021 curdev = add_dev(devlistp, name, flags, description, errbuf);
2022 if (curdev == NULL) {
2030 * Get the list of addresses for the interface.
2032 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
2036 * We don't return an error, because this can happen with
2037 * NdisWan interfaces, and we want to supply them even
2038 * if we can't supply their addresses.
2040 * We return an entry with an empty address list.
2046 * Now add the addresses.
2048 while (if_addr_size-- > 0) {
2050 * "curdev" is an entry for this interface; add an entry for
2051 * this address to its list of addresses.
2053 res = add_addr_to_dev(curdev,
2054 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
2055 sizeof (struct sockaddr_storage),
2056 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
2057 sizeof (struct sockaddr_storage),
2058 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
2059 sizeof (struct sockaddr_storage),
2075 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
2081 NDIS_HARDWARE_STATUS hardware_status;
2082 #ifdef OID_GEN_PHYSICAL_MEDIUM
2083 NDIS_PHYSICAL_MEDIUM phys_medium;
2084 bpf_u_int32 gen_physical_medium_oids[] = {
2085 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
2086 OID_GEN_PHYSICAL_MEDIUM_EX,
2088 OID_GEN_PHYSICAL_MEDIUM
2090 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
2092 #endif /* OID_GEN_PHYSICAL_MEDIUM */
2093 #ifdef OID_GEN_LINK_STATE
2094 NDIS_LINK_STATE link_state;
2098 if (*flags & PCAP_IF_LOOPBACK) {
2100 * Loopback interface, so the connection status doesn't
2101 * apply. and it's not wireless (or wired, for that
2102 * matter...). We presume it's up and running.
2104 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING | PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2109 * We need to open the adapter to get this information.
2111 * XXX - PacketOpenAdapter() takes a non-const pointer
2112 * as an argument, so we make a copy of the argument and
2115 name_copy = strdup(name);
2116 adapter = PacketOpenAdapter(name_copy);
2118 if (adapter == NULL) {
2120 * Give up; if they try to open this device, it'll fail.
2125 #ifdef HAVE_AIRPCAP_API
2127 * Airpcap.sys do not support the below 'OID_GEN_x' values.
2128 * Just set these flags (and none of the '*flags' entered with).
2130 if (PacketGetAirPcapHandle(adapter)) {
2132 * Must be "up" and "running" if the above if succeeded.
2134 *flags = PCAP_IF_UP | PCAP_IF_RUNNING;
2137 * An airpcap device is a wireless device (duh!)
2139 *flags |= PCAP_IF_WIRELESS;
2142 * A "network association state" makes no sense for airpcap.
2144 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2145 PacketCloseAdapter(adapter);
2151 * Get the hardware status, and derive "up" and "running" from
2154 len = sizeof (hardware_status);
2155 status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
2156 &hardware_status, &len, errbuf);
2158 switch (hardware_status) {
2160 case NdisHardwareStatusReady:
2162 * "Available and capable of sending and receiving
2163 * data over the wire", so up and running.
2165 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
2168 case NdisHardwareStatusInitializing:
2169 case NdisHardwareStatusReset:
2171 * "Initializing" or "Resetting", so up, but
2174 *flags |= PCAP_IF_UP;
2177 case NdisHardwareStatusClosing:
2178 case NdisHardwareStatusNotReady:
2180 * "Closing" or "Not ready", so neither up nor
2193 * Can't get the hardware status, so assume both up and
2196 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
2200 * Get the network type.
2202 #ifdef OID_GEN_PHYSICAL_MEDIUM
2204 * Try the OIDs we have for this, in order.
2206 for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
2207 len = sizeof (phys_medium);
2208 status = oid_get_request(adapter, gen_physical_medium_oids[i],
2209 &phys_medium, &len, errbuf);
2217 * Failed. We can't determine whether it failed
2218 * because that particular OID isn't supported
2219 * or because some other problem occurred, so we
2220 * just drive on and try the next OID.
2225 * We got the physical medium.
2227 * XXX - we might want to check for NdisPhysicalMediumWiMax
2228 * and NdisPhysicalMediumNative802_15_4 being
2229 * part of the enum, and check for those in the "wireless"
2232 DIAG_OFF_ENUM_SWITCH
2233 switch (phys_medium) {
2235 case NdisPhysicalMediumWirelessLan:
2236 case NdisPhysicalMediumWirelessWan:
2237 case NdisPhysicalMediumNative802_11:
2238 case NdisPhysicalMediumBluetooth:
2239 case NdisPhysicalMediumUWB:
2240 case NdisPhysicalMediumIrda:
2244 *flags |= PCAP_IF_WIRELESS;
2249 * Not wireless or unknown
2258 * Get the connection status.
2260 #ifdef OID_GEN_LINK_STATE
2261 len = sizeof(link_state);
2262 status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
2266 * NOTE: this also gives us the receive and transmit
2269 switch (link_state.MediaConnectState) {
2271 case MediaConnectStateConnected:
2275 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2278 case MediaConnectStateDisconnected:
2280 * It's disconnected.
2282 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2285 case MediaConnectStateUnknown:
2288 * It's unknown whether it's connected or not.
2295 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2301 * OK, OID_GEN_LINK_STATE didn't work, try
2302 * OID_GEN_MEDIA_CONNECT_STATUS.
2304 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
2305 &connect_status, &len, errbuf);
2307 switch (connect_status) {
2309 case NdisMediaStateConnected:
2313 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2316 case NdisMediaStateDisconnected:
2318 * It's disconnected.
2320 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2325 PacketCloseAdapter(adapter);
2330 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2339 * Find out how big a buffer we need.
2341 * This call should always return FALSE; if the error is
2342 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2343 * the size of the buffer we need, otherwise there's a
2344 * problem, and NameLength should be set to 0.
2346 * It shouldn't require NameLength to be set, but,
2347 * at least as of WinPcap 4.1.3, it checks whether
2348 * NameLength is big enough before it checks for a
2349 * NULL buffer argument, so, while it'll still do
2350 * the right thing if NameLength is uninitialized and
2351 * whatever junk happens to be there is big enough
2352 * (because the pointer argument will be null), it's
2353 * still reading an uninitialized variable.
2356 if (!PacketGetAdapterNames(NULL, &NameLength))
2358 DWORD last_error = GetLastError();
2360 if (last_error != ERROR_INSUFFICIENT_BUFFER)
2362 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2363 last_error, "PacketGetAdapterNames");
2368 if (NameLength <= 0)
2370 AdaptersName = (char*) malloc(NameLength);
2371 if (AdaptersName == NULL)
2373 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
2377 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
2378 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2379 GetLastError(), "PacketGetAdapterNames");
2385 * "PacketGetAdapterNames()" returned a list of
2386 * null-terminated ASCII interface name strings,
2387 * terminated by a null string, followed by a list
2388 * of null-terminated ASCII interface description
2389 * strings, terminated by a null string.
2390 * This means there are two ASCII nulls at the end
2391 * of the first list.
2393 * Find the end of the first list; that's the
2394 * beginning of the second list.
2396 desc = &AdaptersName[0];
2397 while (*desc != '\0' || *(desc + 1) != '\0')
2401 * Found it - "desc" points to the first of the two
2402 * nulls at the end of the list of names, so the
2403 * first byte of the list of descriptions is two bytes
2409 * Loop over the elements in the first list.
2411 name = &AdaptersName[0];
2412 while (*name != '\0') {
2413 bpf_u_int32 flags = 0;
2415 #ifdef HAVE_AIRPCAP_API
2417 * Is this an AirPcap device?
2418 * If so, ignore it; it'll get added later, by the
2421 if (device_is_airpcap(name, errbuf) == 1) {
2422 name += strlen(name) + 1;
2423 desc += strlen(desc) + 1;
2428 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2430 * Is this a loopback interface?
2432 if (PacketIsLoopbackAdapter(name)) {
2434 flags |= PCAP_IF_LOOPBACK;
2438 * Get additional flags.
2440 if (get_if_flags(name, &flags, errbuf) == -1) {
2449 * Add an entry for this interface.
2451 if (pcap_add_if_npf(devlistp, name, flags, desc,
2459 name += strlen(name) + 1;
2460 desc += strlen(desc) + 1;
2468 * Return the name of a network interface attached to the system, or NULL
2469 * if none can be found. The interface must be configured up; the
2470 * lowest unit number is preferred; loopback is ignored.
2472 * In the best of all possible worlds, this would be the same as on
2473 * UN*X, but there may be software that expects this to return a
2474 * full list of devices after the first device.
2476 #define ADAPTERSNAME_LEN 8192
2478 pcap_lookupdev(char *errbuf)
2481 DWORD dwWindowsMajorVersion;
2484 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2485 * it may return UTF-16 strings, for backwards-compatibility
2486 * reasons, and we're also disabling the hack to make that work,
2487 * for not-going-past-the-end-of-a-string reasons, and 2) we
2488 * want its behavior to be consistent.
2490 * In addition, it's not thread-safe, so we've marked it as
2494 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2495 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2499 /* disable MSVC's GetVersion() deprecated warning here */
2500 DIAG_OFF_DEPRECATION
2501 dwVersion = GetVersion(); /* get the OS version */
2503 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
2505 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
2507 * Windows 95, 98, ME.
2509 ULONG NameLength = ADAPTERSNAME_LEN;
2510 static char AdaptersName[ADAPTERSNAME_LEN];
2512 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
2513 return (AdaptersName);
2518 * Windows NT (NT 4.0 and later).
2519 * Convert the names to Unicode for backward compatibility.
2521 ULONG NameLength = ADAPTERSNAME_LEN;
2522 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
2523 size_t BufferSpaceLeft;
2528 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
2531 if(TAdaptersName == NULL)
2533 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
2537 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
2539 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2540 GetLastError(), "PacketGetAdapterNames");
2541 free(TAdaptersName);
2546 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
2547 tAstr = (char*)TAdaptersName;
2548 Unameptr = AdaptersName;
2551 * Convert the device names to Unicode into AdapterName.
2555 * Length of the name, including the terminating
2558 namelen = strlen(tAstr) + 1;
2561 * Do we have room for the name in the Unicode
2564 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
2570 BufferSpaceLeft -= namelen * sizeof(WCHAR);
2573 * Copy the name, converting ASCII to Unicode.
2574 * namelen includes the NUL, so we copy it as
2577 for (i = 0; i < namelen; i++)
2578 *Unameptr++ = *tAstr++;
2581 * Count this adapter.
2584 } while (namelen != 1);
2587 * Copy the descriptions, but don't convert them from
2590 Adescptr = (char *)Unameptr;
2595 desclen = strlen(tAstr) + 1;
2598 * Do we have room for the name in the Unicode
2601 if (BufferSpaceLeft < desclen) {
2609 * Just copy the ASCII string.
2610 * namelen includes the NUL, so we copy it as
2613 memcpy(Adescptr, tAstr, desclen);
2614 Adescptr += desclen;
2616 BufferSpaceLeft -= desclen;
2620 free(TAdaptersName);
2621 return (char *)(AdaptersName);
2626 * We can't use the same code that we use on UN*X, as that's doing
2627 * UN*X-specific calls.
2629 * We don't just fetch the entire list of devices, search for the
2630 * particular device, and use its first IPv4 address, as that's too
2631 * much work to get just one device's netmask.
2634 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
2638 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2639 * in order to skip non IPv4 (i.e. IPv6 addresses)
2641 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2642 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
2643 struct sockaddr_in *t_addr;
2646 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
2651 for(i = 0; i < if_addr_size; i++)
2653 if(if_addrs[i].IPAddress.ss_family == AF_INET)
2655 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
2656 *netp = t_addr->sin_addr.S_un.S_addr;
2657 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
2658 *maskp = t_addr->sin_addr.S_un.S_addr;
2670 static const char *pcap_lib_version_string;
2672 #ifdef HAVE_VERSION_H
2674 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2675 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2678 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2679 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2680 * for the packet.dll version number as well.)
2682 #include "../../version.h"
2684 static const char pcap_version_string[] =
2685 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2688 pcap_lib_version(void)
2690 if (pcap_lib_version_string == NULL) {
2692 * Generate the version string.
2694 const char *packet_version_string = PacketGetVersion();
2696 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2698 * WinPcap/Npcap version string and packet.dll version
2699 * string are the same; just report the WinPcap/Npcap
2702 pcap_lib_version_string = pcap_version_string;
2705 * WinPcap/Npcap version string and packet.dll version
2706 * string are different; that shouldn't be the
2707 * case (the two libraries should come from the
2708 * same version of WinPcap/Npcap), so we report both
2711 char *full_pcap_version_string;
2713 if (pcap_asprintf(&full_pcap_version_string,
2714 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING,
2715 packet_version_string) != -1) {
2717 pcap_lib_version_string = full_pcap_version_string;
2721 return (pcap_lib_version_string);
2724 #else /* HAVE_VERSION_H */
2727 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2731 pcap_lib_version(void)
2733 if (pcap_lib_version_string == NULL) {
2735 * Generate the version string. Report the packet.dll
2738 char *full_pcap_version_string;
2740 if (pcap_asprintf(&full_pcap_version_string,
2741 PCAP_VERSION_STRING " (packet.dll version %s)",
2742 PacketGetVersion()) != -1) {
2744 pcap_lib_version_string = full_pcap_version_string;
2747 return (pcap_lib_version_string);
2749 #endif /* HAVE_VERSION_H */