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.
37 #include <limits.h> /* for INT_MAX */
38 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
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,
48 * However, no header in the WinPcap or Npcap SDKs defines the
49 * macros for BPF code, so we have to define them ourselves.
54 /* Old-school MinGW have these headers in a different place.
56 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
57 #include <ddk/ntddndis.h>
60 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
63 #include "diag-control.h"
65 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
66 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
67 static int pcap_getnonblock_npf(pcap_t
*);
68 static int pcap_setnonblock_npf(pcap_t
*, int);
70 /*dimension of the buffer in the pcap_t structure*/
71 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
73 /*dimension of the buffer in the kernel driver NPF */
74 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
76 /* Equivalent to ntohs(), but a lot faster under Windows */
77 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
80 * Private data for capturing on WinPcap/Npcap devices.
83 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
85 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
86 int filtering_in_kernel
; /* using kernel filter */
89 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
90 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
95 * Define stub versions of the monitor-mode support routines if this
96 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
99 #ifndef HAVE_NPCAP_PACKET_API
101 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
104 * We don't support monitor mode.
110 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
113 * This should never be called, as PacketIsMonitorModeSupported()
114 * will return 0, meaning "we don't support monitor mode, so
115 * don't try to turn it on or off".
121 PacketGetMonitorMode(PCHAR AdapterName _U_
)
124 * This should fail, so that pcap_activate_npf() returns
125 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
133 * If a driver returns an NTSTATUS value:
135 * https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/87fba13e-bf06-450e-83b1-9241dc81e781
137 * with the "Customer" bit set, it will not be mapped to a Windows error
138 * value in userland, so it will be returned by GetLastError().
140 * Note that "driver" here includes the Npcap NPF driver, as various
141 * versions would take NT status values and set the "Customer" bit
142 * before returning the status code. The commit message for the
143 * change that started doing that is
145 * Returned a customer-defined NTSTATUS in OID requests to avoid
146 * NTSTATUS-to-Win32 Error code translation.
148 * but I don't know why the goal was to avoid that translation. For
149 * a while, I suspected that the NT status STATUS_NOT_SUPPORTED was
150 * getting mapped to ERROR_GEN_FAILURE, but, in the cases where
151 * attempts to set promiscuous mode on regular Ethernet devices were
152 * failing with ERROR_GEN_FAILURE, it turns out that the drivers for
153 * those devices were NetAdapterCx drivers, and Microsoft's NetAdapterCx
154 * mechanism wasn't providing the correct "bytes processed" value on
155 * attempts to set OIDs, and the Npcap NPF driver was checking for
156 * that and returning STATUS_UNSUCCESSFUL, which gets mapped to
157 * ERROR_GEN_FAILURE, so perhaps there's no need to avoid that
160 * Attempting to set the hardware filter on a Microsoft Surface Pro's
161 * Mobile Broadband Adapter returns an error that appears to be
162 * NDIS_STATUS_NOT_SUPPORTED ORed with the "Customer" bit, so it's
163 * probably indicating that it doesn't support that. It was probably
164 * the NPF driver setting that bit.
166 #define NT_STATUS_CUSTOMER_DEFINED 0x20000000
169 * PacketRequest() makes a DeviceIoControl() call to the NPF driver to
170 * perform the OID request, with a BIOCQUERYOID ioctl. The kernel code
171 * should get back one of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
172 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't supported by
173 * the OS or the driver.
175 * Currently, that code may be returned by the Npcap NPF driver with the
176 * NT_STATUS_CUSTOMER_DEFINED bit. That prevents the return status from
177 * being mapped to a Windows error code; if the NPF driver were to stop
178 * ORing in the NT_STATUS_CUSTOMER_DEFINED bit, it's not obvious how those
179 * the NDIS_STATUS_ values that don't correspond to NTSTATUS values would
180 * be translated to Windows error values (NDIS_STATUS_NOT_SUPPORTED is
181 * the same as STATUS_NOT_SUPPORTED, which is an NTSTATUS value that is
182 * mapped to ERROR_NOT_SUPPORTED).
184 #define NDIS_STATUS_INVALID_OID 0xc0010017
185 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
186 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
189 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
192 PACKET_OID_DATA
*oid_data_arg
;
195 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
196 * It should be big enough to hold "*lenp" bytes of data; it
197 * will actually be slightly larger, as PACKET_OID_DATA has a
198 * 1-byte data array at the end, standing in for the variable-length
199 * data that's actually there.
201 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
202 if (oid_data_arg
== NULL
) {
203 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
204 "Couldn't allocate argument buffer for PacketRequest");
209 * No need to copy the data - we're doing a fetch.
211 oid_data_arg
->Oid
= oid
;
212 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
213 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
214 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
215 GetLastError(), "Error calling PacketRequest");
221 * Get the length actually supplied.
223 *lenp
= oid_data_arg
->Length
;
226 * Copy back the data we fetched.
228 memcpy(data
, oid_data_arg
->Data
, *lenp
);
234 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
236 struct pcap_win
*pw
= p
->priv
;
237 struct bpf_stat bstats
;
240 * Try to get statistics.
242 * (Please note - "struct pcap_stat" is *not* the same as
243 * WinPcap's "struct bpf_stat". It might currently have the
244 * same layout, but let's not cheat.
246 * Note also that we don't fill in ps_capt, as we might have
247 * been called by code compiled against an earlier version of
248 * WinPcap that didn't have ps_capt, in which case filling it
249 * in would stomp on whatever comes after the structure passed
252 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
253 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
254 GetLastError(), "PacketGetStats error");
257 ps
->ps_recv
= bstats
.bs_recv
;
258 ps
->ps_drop
= bstats
.bs_drop
;
261 * XXX - PacketGetStats() doesn't fill this in, so we just
265 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
274 * Win32-only routine for getting statistics.
276 * This way is definitely safer than passing the pcap_stat * from the userland.
277 * In fact, there could happen than the user allocates a variable which is not
278 * big enough for the new structure, and the library will write in a zone
279 * which is not allocated to this variable.
281 * In this way, we're pretty sure we are writing on memory allocated to this
284 * XXX - but this is the wrong way to handle statistics. Instead, we should
285 * have an API that returns data in a form like the Options section of a
286 * pcapng Interface Statistics Block:
288 * 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
290 * which would let us add new statistics straightforwardly and indicate which
291 * statistics we are and are *not* providing, rather than having to provide
292 * possibly-bogus values for statistics we can't provide.
294 static struct pcap_stat
*
295 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
297 struct pcap_win
*pw
= p
->priv
;
298 struct bpf_stat bstats
;
300 *pcap_stat_size
= sizeof (p
->stat
);
303 * Try to get statistics.
305 * (Please note - "struct pcap_stat" is *not* the same as
306 * WinPcap's "struct bpf_stat". It might currently have the
307 * same layout, but let's not cheat.)
309 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
310 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
311 GetLastError(), "PacketGetStatsEx error");
314 p
->stat
.ps_recv
= bstats
.bs_recv
;
315 p
->stat
.ps_drop
= bstats
.bs_drop
;
316 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
318 * Just in case this is ever compiled for a target other than
319 * Windows, which is somewhere between extremely unlikely and
323 p
->stat
.ps_capt
= bstats
.bs_capt
;
328 /* Set the dimension of the kernel-level capture buffer */
330 pcap_setbuff_npf(pcap_t
*p
, int dim
)
332 struct pcap_win
*pw
= p
->priv
;
334 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
336 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
342 /* Set the driver working mode */
344 pcap_setmode_npf(pcap_t
*p
, int mode
)
346 struct pcap_win
*pw
= p
->priv
;
348 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
350 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
357 /*set the minimum amount of data that will release a read call*/
359 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
361 struct pcap_win
*pw
= p
->priv
;
363 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
365 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
372 pcap_getevent_npf(pcap_t
*p
)
374 struct pcap_win
*pw
= p
->priv
;
376 return (PacketGetReadEvent(pw
->adapter
));
380 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
382 struct pcap_win
*pw
= p
->priv
;
384 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
388 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
391 struct pcap_win
*pw
= p
->priv
;
392 PACKET_OID_DATA
*oid_data_arg
;
395 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
396 * It should be big enough to hold "*lenp" bytes of data; it
397 * will actually be slightly larger, as PACKET_OID_DATA has a
398 * 1-byte data array at the end, standing in for the variable-length
399 * data that's actually there.
401 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
402 if (oid_data_arg
== NULL
) {
403 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
404 "Couldn't allocate argument buffer for PacketRequest");
408 oid_data_arg
->Oid
= oid
;
409 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
410 memcpy(oid_data_arg
->Data
, data
, *lenp
);
411 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
412 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
413 GetLastError(), "Error calling PacketRequest");
419 * Get the length actually copied.
421 *lenp
= oid_data_arg
->Length
;
424 * No need to copy the data - we're doing a set.
431 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
433 struct pcap_win
*pw
= p
->priv
;
436 res
= PacketSendPackets(pw
->adapter
,
441 if(res
!= queue
->len
){
442 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
443 GetLastError(), "Error queueing packets");
450 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
452 unsigned char *new_buff
;
455 /* Bogus parameter */
456 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
457 "Error: invalid size %d",size
);
461 /* Allocate the buffer */
462 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
465 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
466 "Error: not enough memory");
478 #ifdef HAVE_NPCAP_PACKET_API
480 * Kernel dump mode isn't supported in Npcap; calls to PacketSetDumpName(),
481 * PacketSetDumpLimits(), and PacketIsDumpEnded() will get compile-time
482 * deprecation warnings.
484 * Avoid calling them; just return errors indicating that kernel dump
485 * mode isn't supported in Npcap.
488 pcap_live_dump_npf(pcap_t
*p
, char *filename _U_
, int maxsize _U_
,
491 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
492 "Npcap doesn't support kernel dump mode");
496 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
498 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
499 "Npcap doesn't support kernel dump mode");
502 #else /* HAVE_NPCAP_PACKET_API */
504 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
506 struct pcap_win
*pw
= p
->priv
;
509 /* Set the packet driver in dump mode */
510 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
512 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
513 "Error setting dump mode");
517 /* Set the name of the dump file */
518 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
520 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
521 "Error setting kernel dump file name");
525 /* Set the limits of the dump file */
526 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
528 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
529 "Error setting dump limit");
537 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
539 struct pcap_win
*pw
= p
->priv
;
541 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
543 #endif /* HAVE_NPCAP_PACKET_API */
546 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
551 register u_char
*bp
, *ep
;
553 struct pcap_win
*pw
= p
->priv
;
558 * Has "pcap_breakloop()" been called?
562 * Yes - clear the flag that indicates that it
563 * has, and return PCAP_ERROR_BREAK to indicate
564 * that we were told to break out of the loop.
567 return (PCAP_ERROR_BREAK
);
571 * Capture the packets.
573 * The PACKET structure had a bunch of extra stuff for
574 * Windows 9x/Me, but the only interesting data in it
575 * in the versions of Windows that we support is just
576 * a copy of p->buffer, a copy of p->buflen, and the
577 * actual number of bytes read returned from
578 * PacketReceivePacket(), none of which has to be
579 * retained from call to call, so we just keep one on
582 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
583 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
585 * Did the device go away?
586 * If so, the error we get can either be
587 * ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
589 DWORD errcode
= GetLastError();
591 if (errcode
== ERROR_GEN_FAILURE
||
592 errcode
== ERROR_DEVICE_REMOVED
) {
594 * The device on which we're capturing
595 * went away, or it became unusable
596 * by NPF due to a suspend/resume.
598 * ERROR_GEN_FAILURE comes from
599 * STATUS_UNSUCCESSFUL, as well as some
600 * other NT status codes that the Npcap
601 * driver is unlikely to return.
602 * XXX - hopefully no other error
603 * conditions are indicated by this.
605 * ERROR_DEVICE_REMOVED comes from
606 * STATUS_DEVICE_REMOVED.
608 * We report the Windows status code
609 * name and the corresponding NT status
610 * code name, for the benefit of attempts
611 * to debug cases where this error is
612 * reported when the device *wasn't*
613 * removed, either because it's not
614 * removable, it's removable but wasn't
615 * removed, or it's a device that doesn't
616 * correspond to a physical device.
618 * XXX - we really should return an
619 * appropriate error for that, but
620 * pcap_dispatch() etc. aren't
621 * documented as having error returns
622 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
624 const char *errcode_msg
;
626 if (errcode
== ERROR_GEN_FAILURE
)
627 errcode_msg
= "ERROR_GEN_FAILURE/STATUS_UNSUCCESSFUL";
629 errcode_msg
= "ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED";
630 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
631 "The interface disappeared (error code %s)",
634 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
635 PCAP_ERRBUF_SIZE
, errcode
,
636 "PacketReceivePacket error");
641 cc
= Packet
.ulBytesReceived
;
649 * Loop through each packet.
651 * This assumes that a single buffer of packets will have
652 * <= INT_MAX packets, so the packet count doesn't overflow.
654 #define bhp ((struct bpf_hdr *)bp)
658 register u_int caplen
, hdrlen
;
662 * Has "pcap_breakloop()" been called?
663 * If so, return immediately - if we haven't read any
664 * packets, clear the flag and return PCAP_ERROR_BREAK
665 * to indicate that we were told to break out of the loop,
666 * otherwise leave the flag set, so that the *next* call
667 * will break out of the loop without having read any
668 * packets, and return the number of packets we've
674 return (PCAP_ERROR_BREAK
);
677 p
->cc
= (u_int
) (ep
- bp
);
684 caplen
= bhp
->bh_caplen
;
685 hdrlen
= bhp
->bh_hdrlen
;
689 * Compute the number of bytes for this packet in
692 * That's the sum of the header length and the packet
693 * data length plus, if this is not the last packet,
694 * the padding required to align the next packet on
695 * the appropriate boundary.
697 * That means that it should be the minimum of the
698 * number of bytes left in the buffer and the
699 * rounded-up sum of the header and packet data lengths.
701 packet_bytes
= min((u_int
)(ep
- bp
), Packet_WORDALIGN(caplen
+ hdrlen
));
704 * Short-circuit evaluation: if using BPF filter
705 * in kernel, no need to do it now - we already know
706 * the packet passed the filter.
708 * XXX - pcapint_filter() should always return TRUE if
709 * handed a null pointer for the program, but it might
710 * just try to "run" the filter, so we check here.
712 if (pw
->filtering_in_kernel
||
713 p
->fcode
.bf_insns
== NULL
||
714 pcapint_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
716 switch (p
->rmt_samp
.method
) {
718 case PCAP_SAMP_1_EVERY_N
:
719 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
721 /* Discard all packets that are not '1 out of N' */
722 if (pw
->samp_npkt
!= 0) {
728 case PCAP_SAMP_FIRST_AFTER_N_MS
:
730 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
733 * Check if the timestamp of the arrived
734 * packet is smaller than our target time.
736 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
737 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
743 * The arrived packet is suitable for being
744 * delivered to our caller, so let's update
747 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
748 if (pw
->samp_time
.tv_usec
> 1000000) {
749 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
750 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
754 #endif /* ENABLE_REMOTE */
757 * XXX A bpf_hdr matches a pcap_pkthdr.
759 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
761 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
763 p
->cc
= (u_int
) (ep
- bp
);
778 /* Send a packet to the network */
780 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
782 struct pcap_win
*pw
= p
->priv
;
785 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
786 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
787 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
788 GetLastError(), "send error: PacketSendPacket failed");
793 * We assume it all got sent if "PacketSendPacket()" succeeded.
794 * "pcap_inject()" is expected to return the number of bytes
801 pcap_cleanup_npf(pcap_t
*p
)
803 struct pcap_win
*pw
= p
->priv
;
805 if (pw
->adapter
!= NULL
) {
806 PacketCloseAdapter(pw
->adapter
);
809 if (pw
->rfmon_selfstart
)
811 PacketSetMonitorMode(p
->opt
.device
, 0);
813 pcapint_cleanup_live_common(p
);
817 pcap_breakloop_npf(pcap_t
*p
)
819 pcapint_breakloop_common(p
);
820 struct pcap_win
*pw
= p
->priv
;
822 /* XXX - what if this fails? */
823 SetEvent(PacketGetReadEvent(pw
->adapter
));
827 pcap_activate_npf(pcap_t
*p
)
829 struct pcap_win
*pw
= p
->priv
;
833 struct bpf_insn total_insn
;
834 struct bpf_program total_prog
;
838 * Monitor mode is supported on Windows Vista and later.
840 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
842 pw
->rfmon_selfstart
= 0;
846 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
848 pw
->rfmon_selfstart
= 0;
849 // Monitor mode is not supported.
852 return PCAP_ERROR_RFMON_NOTSUP
;
861 pw
->rfmon_selfstart
= 1;
866 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
868 if (pw
->adapter
== NULL
)
870 DWORD errcode
= GetLastError();
873 * What error did we get when trying to open the adapter?
879 * There's no such device.
880 * There's nothing to add, so clear the error
884 return (PCAP_ERROR_NO_SUCH_DEVICE
);
886 case ERROR_ACCESS_DENIED
:
888 * There is, but we don't have permission to
891 * XXX - we currently get ERROR_BAD_UNIT if the
892 * user says "no" to the UAC prompt.
894 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
895 "The helper program for \"Admin-only Mode\" must be allowed to make changes to your device");
896 return (PCAP_ERROR_PERM_DENIED
);
900 * Unknown - report details.
902 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
903 errcode
, "Error opening adapter");
904 if (pw
->rfmon_selfstart
)
906 PacketSetMonitorMode(p
->opt
.device
, 0);
913 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
915 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
916 GetLastError(), "Cannot determine the network type");
921 switch (type
.LinkType
)
924 * NDIS-defined medium types.
926 case NdisMedium802_3
:
927 p
->linktype
= DLT_EN10MB
;
929 * This is (presumably) a real Ethernet capture; give it a
930 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
931 * that an application can let you choose it, in case you're
932 * capturing DOCSIS traffic that a Cisco Cable Modem
933 * Termination System is putting out onto an Ethernet (it
934 * doesn't put an Ethernet header onto the wire, it puts raw
935 * DOCSIS frames out on the wire inside the low-level
938 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
939 if (p
->dlt_list
== NULL
)
941 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
945 p
->dlt_list
[0] = DLT_EN10MB
;
946 p
->dlt_list
[1] = DLT_DOCSIS
;
950 case NdisMedium802_5
:
954 p
->linktype
= DLT_IEEE802
;
958 p
->linktype
= DLT_FDDI
;
962 p
->linktype
= DLT_EN10MB
;
965 case NdisMediumArcnetRaw
:
966 p
->linktype
= DLT_ARCNET
;
969 case NdisMediumArcnet878_2
:
970 p
->linktype
= DLT_ARCNET
;
974 p
->linktype
= DLT_ATM_RFC1483
;
977 case NdisMediumWirelessWan
:
978 p
->linktype
= DLT_RAW
;
982 p
->linktype
= DLT_RAW
;
986 * Npcap-defined medium types.
989 p
->linktype
= DLT_NULL
;
992 case NdisMediumCHDLC
:
993 p
->linktype
= DLT_CHDLC
;
996 case NdisMediumPPPSerial
:
997 p
->linktype
= DLT_PPP_SERIAL
;
1000 case NdisMediumBare80211
:
1001 p
->linktype
= DLT_IEEE802_11
;
1004 case NdisMediumRadio80211
:
1005 p
->linktype
= DLT_IEEE802_11_RADIO
;
1009 p
->linktype
= DLT_PPI
;
1014 * An unknown medium type is assumed to supply Ethernet
1015 * headers; if not, the user will have to report it,
1016 * so that the medium type and link-layer header type
1017 * can be determined. If we were to fail here, we
1018 * might get the link-layer type in the error, but
1019 * the user wouldn't get a capture, so we wouldn't
1020 * be able to determine the link-layer type; we report
1021 * a warning with the link-layer type, so at least
1022 * some programs will report the warning.
1024 p
->linktype
= DLT_EN10MB
;
1025 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1026 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1028 status
= PCAP_WARNING
;
1032 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1034 * Set the timestamp type.
1035 * (Yes, we require PacketGetTimestampModes(), not just
1036 * PacketSetTimestampMode(). If we have the former, we
1037 * have the latter, unless somebody's using a version
1038 * of Npcap that they've hacked to provide the former
1039 * but not the latter; if they've done that, either
1040 * they're confused or they're trolling us.)
1042 switch (p
->opt
.tstamp_type
) {
1044 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED
:
1046 * Better than low-res, but *not* synchronized with
1049 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION
))
1051 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1052 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1057 case PCAP_TSTAMP_HOST_LOWPREC
:
1059 * Low-res, but synchronized with the OS clock.
1061 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_QUERYSYSTEMTIME
))
1063 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1064 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1069 case PCAP_TSTAMP_HOST_HIPREC
:
1071 * High-res, and synchronized with the OS clock.
1073 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE
))
1075 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1076 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1081 case PCAP_TSTAMP_HOST
:
1083 * XXX - do whatever the default is, for now.
1084 * Set to the highest resolution that's synchronized
1085 * with the system clock?
1089 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1092 * Turn a negative snapshot value (invalid), a snapshot value of
1093 * 0 (unspecified), or a value bigger than the normal maximum
1094 * value, into the maximum allowed value.
1096 * If some application really *needs* a bigger snapshot
1097 * length, we should just increase MAXIMUM_SNAPLEN.
1099 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1100 p
->snapshot
= MAXIMUM_SNAPLEN
;
1102 /* Set promiscuous mode */
1106 * For future reference, in case we ever want to query
1107 * whether an adapter supports promiscuous mode, that
1108 * would be done on Windows by querying the value
1109 * of the OID_GEN_SUPPORTED_PACKET_FILTERS OID.
1111 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1113 DWORD errcode
= GetLastError();
1116 * Suppress spurious error generated by non-compliant
1117 * MS Surface mobile adapters that appear to
1118 * return NDIS_STATUS_NOT_SUPPORTED for attempts
1119 * to set the hardware filter.
1121 * It appears to be reporting NDIS_STATUS_NOT_SUPPORTED,
1122 * but with the NT status value "Customer" bit set;
1123 * the Npcap NPF driver sets that bit in some cases.
1125 * If we knew that this meant "promiscuous mode
1126 * isn't supported", we could add a "promiscuous
1127 * mode isn't supported" error code and return
1130 * 1) we don't know that it means that
1131 * rather than meaning "we reject attempts
1132 * to set the filter, even though the NDIS
1133 * specifications say you shouldn't do that"
1137 * 2) other interface types that don't
1138 * support promiscuous mode, at least
1139 * on UN*Xes, just silently ignore
1140 * attempts to set promiscuous mode
1142 * and rejecting it with an error could disrupt
1143 * attempts to capture, as many programs (tcpdump,
1144 * *shark) default to promiscuous mode.
1146 * Alternatively, we could return the "promiscuous
1147 * mode not supported" *warning* value, so that
1148 * correct code will either ignore it or report
1149 * it and continue capturing. (This may require
1150 * a pcap_init() flag to request that return
1151 * value, so that old incorrect programs that
1152 * assume a non-zero return from pcap_activate()
1153 * is an error don't break.)
1155 * We check here for ERROR_NOT_SUPPORTED, which
1156 * is what NDIS_STATUS_NOT_SUPPORTED (which is
1157 * the same value as the NTSTATUS value
1158 * STATUS_NOT_SUPPORTED) gets mapped to, as
1159 * well as NDIS_STATUS_NOT_SUPPORTED with the
1160 * "Customer" bit set.
1162 if (errcode
!= ERROR_NOT_SUPPORTED
&&
1163 errcode
!= (NDIS_STATUS_NOT_SUPPORTED
|NT_STATUS_CUSTOMER_DEFINED
))
1165 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1166 PCAP_ERRBUF_SIZE
, errcode
,
1167 "failed to set hardware filter to promiscuous mode");
1175 * NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by
1176 * installed protocols and all packets indicated by the NIC",
1177 * but if no protocol drivers (like TCP/IP) are installed,
1178 * NDIS_PACKET_TYPE_DIRECTED, NDIS_PACKET_TYPE_BROADCAST,
1179 * and NDIS_PACKET_TYPE_MULTICAST are needed to capture
1182 if (PacketSetHwFilter(pw
->adapter
,
1183 NDIS_PACKET_TYPE_ALL_LOCAL
|
1184 NDIS_PACKET_TYPE_DIRECTED
|
1185 NDIS_PACKET_TYPE_BROADCAST
|
1186 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1188 DWORD errcode
= GetLastError();
1191 * Suppress spurious error generated by non-compliant
1192 * MS Surface mobile adapters.
1194 if (errcode
!= (NDIS_STATUS_NOT_SUPPORTED
|NT_STATUS_CUSTOMER_DEFINED
))
1196 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1197 PCAP_ERRBUF_SIZE
, errcode
,
1198 "failed to set hardware filter to non-promiscuous mode");
1204 /* Set the buffer size */
1205 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1207 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1210 * Traditional Adapter
1213 * If the buffer size wasn't explicitly set, default to
1214 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1216 if (p
->opt
.buffer_size
== 0)
1217 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1219 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1221 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1225 p
->buffer
= malloc(p
->bufsize
);
1226 if (p
->buffer
== NULL
)
1228 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1233 if (p
->opt
.immediate
)
1235 /* tell the driver to copy the buffer as soon as data arrives */
1236 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1238 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1239 PCAP_ERRBUF_SIZE
, GetLastError(),
1240 "Error calling PacketSetMinToCopy");
1246 /* tell the driver to copy the buffer only if it contains at least 16K */
1247 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1249 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1250 PCAP_ERRBUF_SIZE
, GetLastError(),
1251 "Error calling PacketSetMinToCopy");
1260 * If there's no filter program installed, there's
1261 * no indication to the kernel of what the snapshot
1262 * length should be, so no snapshotting is done.
1264 * Therefore, when we open the device, we install
1265 * an "accept everything" filter with the specified
1268 total_insn
.code
= (u_short
)(BPF_RET
| BPF_K
);
1271 total_insn
.k
= p
->snapshot
;
1273 total_prog
.bf_len
= 1;
1274 total_prog
.bf_insns
= &total_insn
;
1275 if (!PacketSetBpf(pw
->adapter
, &total_prog
)) {
1276 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1277 GetLastError(), "PacketSetBpf");
1278 status
= PCAP_ERROR
;
1282 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1284 /* disable loopback capture if requested */
1285 if (p
->opt
.nocapture_local
)
1287 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1289 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1290 "Unable to disable the capture of loopback packets.");
1295 /* install traditional npf handlers for read and setfilter */
1296 p
->read_op
= pcap_read_npf
;
1297 p
->setfilter_op
= pcap_setfilter_npf
;
1298 p
->setdirection_op
= NULL
; /* Not implemented. */
1299 /* XXX - can this be implemented on some versions of Windows? */
1300 p
->inject_op
= pcap_inject_npf
;
1301 p
->set_datalink_op
= NULL
; /* can't change data link type */
1302 p
->getnonblock_op
= pcap_getnonblock_npf
;
1303 p
->setnonblock_op
= pcap_setnonblock_npf
;
1304 p
->stats_op
= pcap_stats_npf
;
1305 p
->breakloop_op
= pcap_breakloop_npf
;
1306 p
->stats_ex_op
= pcap_stats_ex_npf
;
1307 p
->setbuff_op
= pcap_setbuff_npf
;
1308 p
->setmode_op
= pcap_setmode_npf
;
1309 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1310 p
->getevent_op
= pcap_getevent_npf
;
1311 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1312 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1313 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1314 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1315 p
->live_dump_op
= pcap_live_dump_npf
;
1316 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1317 p
->cleanup_op
= pcap_cleanup_npf
;
1320 * XXX - this is only done because WinPcap supported
1321 * pcap_fileno() returning the hFile HANDLE from the
1322 * ADAPTER structure. We make no general guarantees
1323 * that the caller can do anything useful with it.
1325 * (Not that we make any general guarantee of that
1326 * sort on UN*X, either, anymore, given that not
1327 * all capture devices are regular OS network
1330 p
->handle
= pw
->adapter
->hFile
;
1334 pcap_cleanup_npf(p
);
1335 return (PCAP_ERROR
);
1339 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1342 pcap_can_set_rfmon_npf(pcap_t
*p
)
1344 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1348 * Get a list of time stamp types.
1350 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1352 get_ts_types(const char *device
, pcap_t
*p
, char *ebuf
)
1354 char *device_copy
= NULL
;
1355 ADAPTER
*adapter
= NULL
;
1357 /* Npcap 1.00 driver is buggy and will write 16 bytes regardless of
1358 * buffer size. Using a sufficient stack buffer avoids overflow and
1359 * avoids a heap allocation in most (currently all) cases.
1363 DWORD error
= ERROR_SUCCESS
;
1364 ULONG
*modes
= NULL
;
1369 * First, find out how many time stamp modes we have.
1370 * To do that, we have to open the adapter.
1372 * XXX - PacketOpenAdapter() takes a non-const pointer
1373 * as an argument, so we make a copy of the argument and
1376 device_copy
= strdup(device
);
1377 if (device_copy
== NULL
) {
1378 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1383 adapter
= PacketOpenAdapter(device_copy
);
1384 if (adapter
== NULL
)
1386 error
= GetLastError();
1388 * If we can't open the device now, we won't be
1389 * able to later, either.
1391 * If the error is something that indicates
1392 * that the device doesn't exist, or that they
1393 * don't have permission to open the device - or
1394 * perhaps that they don't have permission to get
1395 * a list of devices, if PacketOpenAdapter() does
1396 * that - the user will find that out when they try
1397 * to activate the device; just return an empty
1398 * list of time stamp types.
1400 * Treating either of those as errors will, for
1401 * example, cause "tcpdump -i <number>" to fail,
1402 * because it first tries to pass the interface
1403 * name to pcap_create() and pcap_activate(),
1404 * in order to handle OSes where interfaces can
1405 * have names that are just numbers (stand up
1406 * and say hello, Linux!), and, if pcap_activate()
1407 * fails with a "no such device" error, checks
1408 * whether the interface name is a valid number
1409 * and, if so, tries to use it as an index in
1410 * the list of interfaces.
1412 * That means pcap_create() must succeed even
1413 * for interfaces that don't exist, with the
1414 * failure occurring at pcap_activate() time.
1416 if (error
== ERROR_BAD_UNIT
||
1417 error
== ERROR_ACCESS_DENIED
) {
1418 p
->tstamp_type_count
= 0;
1419 p
->tstamp_type_list
= NULL
;
1422 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1423 PCAP_ERRBUF_SIZE
, error
,
1424 "Error opening adapter");
1431 * Get the total number of time stamp modes.
1433 * The buffer for PacketGetTimestampModes() is
1434 * a sequence of 1 or more ULONGs. What's
1435 * passed to PacketGetTimestampModes() should have
1436 * the total number of ULONGs in the first ULONG;
1437 * what's returned *from* PacketGetTimestampModes()
1438 * has the total number of time stamp modes in
1441 * Yes, that means if there are N time stamp
1442 * modes, the first ULONG should be set to N+1
1443 * on input, and will be set to N on output.
1445 * We first make a call to PacketGetTimestampModes()
1446 * with a pointer to a single ULONG set to 1; the
1447 * call should fail with ERROR_MORE_DATA (unless
1448 * there are *no* modes, but that should never
1449 * happen), and that ULONG should be set to the
1452 ts_modes
[0] = sizeof(ts_modes
) / sizeof(ULONG
);
1453 ret
= PacketGetTimestampModes(adapter
, ts_modes
);
1456 * OK, it failed. Did it fail with
1459 error
= GetLastError();
1460 if (error
!= ERROR_MORE_DATA
) {
1462 * No, did it fail with ERROR_INVALID_FUNCTION?
1464 if (error
== ERROR_INVALID_FUNCTION
) {
1466 * This is probably due to
1467 * the driver with which Packet.dll
1468 * communicates being older, or
1469 * being a WinPcap driver, so
1470 * that it doesn't support
1471 * BIOCGTIMESTAMPMODES.
1473 * Tell the user to try uninstalling
1474 * Npcap - and WinPcap if installed -
1475 * and re-installing it, to flush
1476 * out all older drivers.
1478 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1479 "PacketGetTimestampModes() failed with ERROR_INVALID_FUNCTION; try uninstalling Npcap, and WinPcap if installed, and re-installing it from npcap.com");
1485 * No, some other error. Fail.
1487 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1488 PCAP_ERRBUF_SIZE
, error
,
1489 "Error calling PacketGetTimestampModes");
1495 * Yes, so we now know how many types to fetch.
1497 * The buffer needs to have one ULONG for the
1498 * count and num_ts_modes ULONGs for the
1499 * num_ts_modes time stamp types.
1501 num_ts_modes
= ts_modes
[0];
1502 modes
= (ULONG
*)malloc((1 + num_ts_modes
) * sizeof(ULONG
));
1503 if (modes
== NULL
) {
1504 /* Out of memory. */
1505 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1509 modes
[0] = 1 + num_ts_modes
;
1510 if (!PacketGetTimestampModes(adapter
, modes
)) {
1511 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1512 PCAP_ERRBUF_SIZE
, GetLastError(),
1513 "Error calling PacketGetTimestampModes");
1517 if (modes
[0] != num_ts_modes
) {
1518 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1519 "First PacketGetTimestampModes() call gives %lu modes, second call gives %lu modes",
1520 num_ts_modes
, modes
[0]);
1527 num_ts_modes
= ts_modes
[0];
1530 /* If the driver reports no modes supported *and*
1531 * ERROR_MORE_DATA, something is seriously wrong.
1532 * We *could* ignore the error and continue without supporting
1533 * settable timestamp modes, but that would hide a bug.
1535 if (modes
[0] == 0) {
1536 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1537 "PacketGetTimestampModes() reports 0 modes supported.");
1543 * Allocate a buffer big enough for
1544 * PCAP_TSTAMP_HOST (default) plus
1545 * the explicitly specified modes.
1547 p
->tstamp_type_list
= malloc((1 + num_ts_modes
) * sizeof(u_int
));
1548 if (p
->tstamp_type_list
== NULL
) {
1549 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1553 u_int num_ts_types
= 0;
1554 p
->tstamp_type_list
[num_ts_types
] =
1557 for (ULONG i
= 0; i
< num_ts_modes
; i
++) {
1558 switch (modes
[i
+ 1]) {
1560 case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION
:
1562 * Better than low-res,
1563 * but *not* synchronized
1564 * with the OS clock.
1566 p
->tstamp_type_list
[num_ts_types
] =
1567 PCAP_TSTAMP_HOST_HIPREC_UNSYNCED
;
1571 case TIMESTAMPMODE_QUERYSYSTEMTIME
:
1573 * Low-res, but synchronized
1574 * with the OS clock.
1576 p
->tstamp_type_list
[num_ts_types
] =
1577 PCAP_TSTAMP_HOST_LOWPREC
;
1581 case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE
:
1583 * High-res, and synchronized
1584 * with the OS clock.
1586 p
->tstamp_type_list
[num_ts_types
] =
1587 PCAP_TSTAMP_HOST_HIPREC
;
1593 * Unknown, so we can't
1599 p
->tstamp_type_count
= num_ts_types
;
1602 /* Clean up temporary allocations */
1603 if (device_copy
!= NULL
) {
1606 if (modes
!= NULL
&& modes
!= ts_modes
) {
1609 if (adapter
!= NULL
) {
1610 PacketCloseAdapter(adapter
);
1615 #else /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1617 get_ts_types(const char *device _U_
, pcap_t
*p _U_
, char *ebuf _U_
)
1620 * Nothing to fetch, so it always "succeeds".
1624 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1627 pcapint_create_interface(const char *device _U_
, char *ebuf
)
1631 p
= PCAP_CREATE_COMMON(ebuf
, struct pcap_win
);
1635 p
->activate_op
= pcap_activate_npf
;
1636 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1638 if (get_ts_types(device
, p
, ebuf
) == -1) {
1646 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1648 struct pcap_win
*pw
= p
->priv
;
1650 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1652 * Kernel filter not installed.
1654 * XXX - we don't know whether this failed because:
1656 * the kernel rejected the filter program as invalid,
1657 * in which case we should fall back on userland
1660 * the kernel rejected the filter program as too big,
1661 * in which case we should again fall back on
1662 * userland filtering;
1664 * there was some other problem, in which case we
1665 * should probably report an error.
1667 * For NPF devices, the Win32 status will be
1668 * STATUS_INVALID_DEVICE_REQUEST for invalid
1669 * filters, but I don't know what it'd be for
1670 * other problems, and for some other devices
1671 * it might not be set at all.
1673 * So we just fall back on userland filtering in
1678 * pcapint_install_bpf_program() validates the program.
1680 * XXX - what if we already have a filter in the kernel?
1682 if (pcapint_install_bpf_program(p
, fp
) < 0)
1684 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1691 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1694 * Discard any previously-received packets, as they might have
1695 * passed whatever filter was formerly in effect, but might
1696 * not pass this filter (BIOCSETF discards packets buffered
1697 * in the kernel, so you can lose packets in any case).
1704 * We filter at user level, since the kernel driver doesn't process the packets
1707 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1711 pcapint_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1715 /* Install a user level filter */
1716 if (pcapint_install_bpf_program(p
, fp
) < 0)
1723 pcap_getnonblock_npf(pcap_t
*p
)
1725 struct pcap_win
*pw
= p
->priv
;
1728 * XXX - if there were a PacketGetReadTimeout() call, we
1729 * would use it, and return 1 if the timeout is -1
1732 return (pw
->nonblock
);
1736 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1738 struct pcap_win
*pw
= p
->priv
;
1743 * Set the packet buffer timeout to -1 for non-blocking
1749 * Restore the timeout set when the device was opened.
1750 * (Note that this may be -1, in which case we're not
1751 * really leaving non-blocking mode. However, although
1752 * the timeout argument to pcap_set_timeout() and
1753 * pcap_open_live() is an int, you're not supposed to
1754 * supply a negative value, so that "shouldn't happen".)
1756 newtimeout
= p
->opt
.timeout
;
1758 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1759 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1760 GetLastError(), "PacketSetReadTimeout");
1763 pw
->nonblock
= (newtimeout
== -1);
1768 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1769 const char *description
, char *errbuf
)
1772 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1776 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1779 * Add an entry for this interface, with no addresses.
1781 curdev
= pcapint_add_dev(devlistp
, name
, flags
, description
, errbuf
);
1782 if (curdev
== NULL
) {
1790 * Get the list of addresses for the interface.
1792 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1796 * We don't return an error, because this can happen with
1797 * NdisWan interfaces, and we want to supply them even
1798 * if we can't supply their addresses.
1800 * We return an entry with an empty address list.
1806 * Now add the addresses.
1808 while (if_addr_size
-- > 0) {
1810 * "curdev" is an entry for this interface; add an entry for
1811 * this address to its list of addresses.
1813 res
= pcapint_add_addr_to_dev(curdev
,
1814 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1815 sizeof (struct sockaddr_storage
),
1816 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1817 sizeof (struct sockaddr_storage
),
1818 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1819 sizeof (struct sockaddr_storage
),
1835 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1841 NDIS_HARDWARE_STATUS hardware_status
;
1842 #ifdef OID_GEN_PHYSICAL_MEDIUM
1843 NDIS_PHYSICAL_MEDIUM phys_medium
;
1844 bpf_u_int32 gen_physical_medium_oids
[] = {
1845 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1846 OID_GEN_PHYSICAL_MEDIUM_EX
,
1848 OID_GEN_PHYSICAL_MEDIUM
1850 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1852 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1853 #ifdef OID_GEN_LINK_STATE
1854 NDIS_LINK_STATE link_state
;
1858 if (*flags
& PCAP_IF_LOOPBACK
) {
1860 * Loopback interface, so the connection status doesn't
1861 * apply. and it's not wireless (or wired, for that
1862 * matter...). We presume it's up and running.
1864 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1869 * We need to open the adapter to get this information.
1871 * XXX - PacketOpenAdapter() takes a non-const pointer
1872 * as an argument, so we make a copy of the argument and
1875 name_copy
= strdup(name
);
1876 adapter
= PacketOpenAdapter(name_copy
);
1878 if (adapter
== NULL
) {
1880 * Give up; if they try to open this device, it'll fail.
1886 * Get the hardware status, and derive "up" and "running" from
1889 len
= sizeof (hardware_status
);
1890 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1891 &hardware_status
, &len
, errbuf
);
1893 switch (hardware_status
) {
1895 case NdisHardwareStatusReady
:
1897 * "Available and capable of sending and receiving
1898 * data over the wire", so up and running.
1900 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1903 case NdisHardwareStatusInitializing
:
1904 case NdisHardwareStatusReset
:
1906 * "Initializing" or "Resetting", so up, but
1909 *flags
|= PCAP_IF_UP
;
1912 case NdisHardwareStatusClosing
:
1913 case NdisHardwareStatusNotReady
:
1915 * "Closing" or "Not ready", so neither up nor
1928 * Can't get the hardware status, so assume both up and
1931 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1935 * Get the network type.
1937 #ifdef OID_GEN_PHYSICAL_MEDIUM
1939 * Try the OIDs we have for this, in order.
1941 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1942 len
= sizeof (phys_medium
);
1943 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1944 &phys_medium
, &len
, errbuf
);
1952 * Failed. We can't determine whether it failed
1953 * because that particular OID isn't supported
1954 * or because some other problem occurred, so we
1955 * just drive on and try the next OID.
1960 * We got the physical medium.
1962 * XXX - we might want to check for NdisPhysicalMediumWiMax
1963 * and NdisPhysicalMediumNative802_15_4 being
1964 * part of the enum, and check for those in the "wireless"
1967 DIAG_OFF_ENUM_SWITCH
1968 switch (phys_medium
) {
1970 case NdisPhysicalMediumWirelessLan
:
1971 case NdisPhysicalMediumWirelessWan
:
1972 case NdisPhysicalMediumNative802_11
:
1973 case NdisPhysicalMediumBluetooth
:
1974 case NdisPhysicalMediumUWB
:
1975 case NdisPhysicalMediumIrda
:
1979 *flags
|= PCAP_IF_WIRELESS
;
1984 * Not wireless or unknown
1993 * Get the connection status.
1995 #ifdef OID_GEN_LINK_STATE
1996 len
= sizeof(link_state
);
1997 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
2001 * NOTE: this also gives us the receive and transmit
2004 switch (link_state
.MediaConnectState
) {
2006 case MediaConnectStateConnected
:
2010 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2013 case MediaConnectStateDisconnected
:
2015 * It's disconnected.
2017 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2020 case MediaConnectStateUnknown
:
2023 * It's unknown whether it's connected or not.
2030 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2036 * OK, OID_GEN_LINK_STATE didn't work, try
2037 * OID_GEN_MEDIA_CONNECT_STATUS.
2039 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
2040 &connect_status
, &len
, errbuf
);
2042 switch (connect_status
) {
2044 case NdisMediaStateConnected
:
2048 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2051 case NdisMediaStateDisconnected
:
2053 * It's disconnected.
2055 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2060 PacketCloseAdapter(adapter
);
2065 pcapint_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
2074 * Find out how big a buffer we need.
2076 * This call should always return FALSE; if the error is
2077 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2078 * the size of the buffer we need, otherwise there's a
2079 * problem, and NameLength should be set to 0.
2081 * It shouldn't require NameLength to be set, but,
2082 * at least as of WinPcap 4.1.3, it checks whether
2083 * NameLength is big enough before it checks for a
2084 * NULL buffer argument, so, while it'll still do
2085 * the right thing if NameLength is uninitialized and
2086 * whatever junk happens to be there is big enough
2087 * (because the pointer argument will be null), it's
2088 * still reading an uninitialized variable.
2091 if (!PacketGetAdapterNames(NULL
, &NameLength
))
2093 DWORD last_error
= GetLastError();
2095 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
2097 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2098 last_error
, "PacketGetAdapterNames");
2103 if (NameLength
<= 0)
2105 AdaptersName
= (char*) malloc(NameLength
);
2106 if (AdaptersName
== NULL
)
2108 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
2112 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
2113 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2114 GetLastError(), "PacketGetAdapterNames");
2120 * "PacketGetAdapterNames()" returned a list of
2121 * null-terminated ASCII interface name strings,
2122 * terminated by a null string, followed by a list
2123 * of null-terminated ASCII interface description
2124 * strings, terminated by a null string.
2125 * This means there are two ASCII nulls at the end
2126 * of the first list.
2128 * Find the end of the first list; that's the
2129 * beginning of the second list.
2131 desc
= &AdaptersName
[0];
2132 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
2136 * Found it - "desc" points to the first of the two
2137 * nulls at the end of the list of names, so the
2138 * first byte of the list of descriptions is two bytes
2144 * Loop over the elements in the first list.
2146 name
= &AdaptersName
[0];
2147 while (*name
!= '\0') {
2148 bpf_u_int32 flags
= 0;
2150 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2152 * Is this a loopback interface?
2154 if (PacketIsLoopbackAdapter(name
)) {
2156 flags
|= PCAP_IF_LOOPBACK
;
2160 * Get additional flags.
2162 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
2171 * Add an entry for this interface.
2173 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
2181 name
+= strlen(name
) + 1;
2182 desc
+= strlen(desc
) + 1;
2190 * Return the name of a network interface attached to the system, or NULL
2191 * if none can be found. The interface must be configured up; the
2192 * lowest unit number is preferred; loopback is ignored.
2194 * In the best of all possible worlds, this would be the same as on
2195 * UN*X, but there may be software that expects this to return a
2196 * full list of devices after the first device.
2198 #define ADAPTERSNAME_LEN 8192
2200 pcap_lookupdev(char *errbuf
)
2203 DWORD dwWindowsMajorVersion
;
2206 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2207 * it may return UTF-16 strings, for backwards-compatibility
2208 * reasons, and we're also disabling the hack to make that work,
2209 * for not-going-past-the-end-of-a-string reasons, and 2) we
2210 * want its behavior to be consistent.
2212 * In addition, it's not thread-safe, so we've marked it as
2215 if (pcapint_new_api
) {
2216 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2217 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2221 /* disable MSVC's GetVersion() deprecated warning here */
2222 DIAG_OFF_DEPRECATION
2223 dwVersion
= GetVersion(); /* get the OS version */
2225 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
2227 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
2229 * Windows 95, 98, ME.
2231 ULONG NameLength
= ADAPTERSNAME_LEN
;
2232 static char AdaptersName
[ADAPTERSNAME_LEN
];
2234 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
2235 return (AdaptersName
);
2240 * Windows NT (NT 4.0 and later).
2241 * Convert the names to Unicode for backward compatibility.
2243 ULONG NameLength
= ADAPTERSNAME_LEN
;
2244 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
2245 size_t BufferSpaceLeft
;
2250 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
2253 if(TAdaptersName
== NULL
)
2255 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
2259 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
2261 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2262 GetLastError(), "PacketGetAdapterNames");
2263 free(TAdaptersName
);
2268 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
2269 tAstr
= (char*)TAdaptersName
;
2270 Unameptr
= AdaptersName
;
2273 * Convert the device names to Unicode into AdapterName.
2277 * Length of the name, including the terminating
2280 namelen
= strlen(tAstr
) + 1;
2283 * Do we have room for the name in the Unicode
2286 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
2292 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
2295 * Copy the name, converting ASCII to Unicode.
2296 * namelen includes the NUL, so we copy it as
2299 for (i
= 0; i
< namelen
; i
++)
2300 *Unameptr
++ = *tAstr
++;
2303 * Count this adapter.
2306 } while (namelen
!= 1);
2309 * Copy the descriptions, but don't convert them from
2312 Adescptr
= (char *)Unameptr
;
2317 desclen
= strlen(tAstr
) + 1;
2320 * Do we have room for the name in the Unicode
2323 if (BufferSpaceLeft
< desclen
) {
2331 * Just copy the ASCII string.
2332 * namelen includes the NUL, so we copy it as
2335 memcpy(Adescptr
, tAstr
, desclen
);
2336 Adescptr
+= desclen
;
2338 BufferSpaceLeft
-= desclen
;
2342 free(TAdaptersName
);
2343 return (char *)(AdaptersName
);
2348 * We can't use the same code that we use on UN*X, as that's doing
2349 * UN*X-specific calls.
2351 * We don't just fetch the entire list of devices, search for the
2352 * particular device, and use its first IPv4 address, as that's too
2353 * much work to get just one device's netmask.
2356 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2360 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2361 * in order to skip non IPv4 (i.e. IPv6 addresses)
2363 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2364 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2365 struct sockaddr_in
*t_addr
;
2368 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2373 for(i
= 0; i
< if_addr_size
; i
++)
2375 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2377 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2378 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2379 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2380 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2392 static const char *pcap_lib_version_string
;
2394 #ifdef HAVE_VERSION_H
2396 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2397 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2400 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2401 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2402 * for the packet.dll version number as well.)
2404 #include "../../version.h"
2406 static const char pcap_version_string
[] =
2407 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2410 pcap_lib_version(void)
2412 if (pcap_lib_version_string
== NULL
) {
2414 * Generate the version string.
2416 const char *packet_version_string
= PacketGetVersion();
2418 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2420 * WinPcap/Npcap version string and packet.dll version
2421 * string are the same; just report the WinPcap/Npcap
2424 pcap_lib_version_string
= pcap_version_string
;
2427 * WinPcap/Npcap version string and packet.dll version
2428 * string are different; that shouldn't be the
2429 * case (the two libraries should come from the
2430 * same version of WinPcap/Npcap), so we report both
2433 char *full_pcap_version_string
;
2435 if (pcapint_asprintf(&full_pcap_version_string
,
2436 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
,
2437 packet_version_string
) != -1) {
2439 pcap_lib_version_string
= full_pcap_version_string
;
2443 return (pcap_lib_version_string
);
2446 #else /* HAVE_VERSION_H */
2449 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2453 pcap_lib_version(void)
2455 if (pcap_lib_version_string
== NULL
) {
2457 * Generate the version string. Report the packet.dll
2460 char *full_pcap_version_string
;
2462 if (pcapint_asprintf(&full_pcap_version_string
,
2463 PCAP_VERSION_STRING
" (packet.dll version %s)",
2464 PacketGetVersion()) != -1) {
2466 pcap_lib_version_string
= full_pcap_version_string
;
2469 return (pcap_lib_version_string
);
2471 #endif /* HAVE_VERSION_H */