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 */
66 #endif /* HAVE_DAG_API */
68 #include "diag-control.h"
70 #include "pcap-airpcap.h"
72 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
73 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
74 static int pcap_getnonblock_npf(pcap_t
*);
75 static int pcap_setnonblock_npf(pcap_t
*, int);
77 /*dimension of the buffer in the pcap_t structure*/
78 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
80 /*dimension of the buffer in the kernel driver NPF */
81 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
83 /* Equivalent to ntohs(), but a lot faster under Windows */
84 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
87 * Private data for capturing on WinPcap/Npcap devices.
90 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
92 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
93 int filtering_in_kernel
; /* using kernel filter */
96 int dag_fcs_bits
; /* Number of checksum bits from link layer */
100 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
101 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
106 * Define stub versions of the monitor-mode support routines if this
107 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
110 #ifndef HAVE_NPCAP_PACKET_API
112 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
115 * We don't support monitor mode.
121 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
124 * This should never be called, as PacketIsMonitorModeSupported()
125 * will return 0, meaning "we don't support monitor mode, so
126 * don't try to turn it on or off".
132 PacketGetMonitorMode(PCHAR AdapterName _U_
)
135 * This should fail, so that pcap_activate_npf() returns
136 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
144 * If a driver returns an NTSTATUS value:
146 * https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/87fba13e-bf06-450e-83b1-9241dc81e781
148 * with the "Customer" bit set, it will not be mapped to a Windows error
149 * value in userland, so it will be returned by GetLastError().
151 * Note that "driver" here includes the Npcap NPF driver, as various
152 * versions would take NT status values and set the "Customer" bit
153 * before returning the status code. The commit message for the
154 * change that started doing that is
156 * Returned a customer-defined NTSTATUS in OID requests to avoid
157 * NTSTATUS-to-Win32 Error code translation.
159 * but I don't know why the goal was to avoid that translation. For
160 * a while, I suspected that the NT status STATUS_NOT_SUPPORTED was
161 * getting mapped to ERROR_GEN_FAILURE, but, in the cases where
162 * attempts to set promiscuous mode on regular Ethernet devices were
163 * failing with ERROR_GEN_FAILURE, it turns out that the drivers for
164 * those devices were NetAdapterCx drivers, and Microsoft's NetAdapterCx
165 * mechanism wasn't providing the correct "bytes processed" value on
166 * attempts to set OIDs, and the Npcap NPF driver was checking for
167 * that and returning STATUS_UNSUCCESSFUL, which gets mapped to
168 * ERROR_GEN_FAILURE, so perhaps there's no need to avoid that
171 * Attempting to set the hardware filter on a Microsoft Surface Pro's
172 * Mobile Broadband Adapter returns an error that appears to be
173 * NDIS_STATUS_NOT_SUPPORTED ORed with the "Customer" bit, so it's
174 * probably indicating that it doesn't support that. It was probably
175 * the NPF driver setting that bit.
177 #define NT_STATUS_CUSTOMER_DEFINED 0x20000000
180 * PacketRequest() makes a DeviceIoControl() call to the NPF driver to
181 * perform the OID request, with a BIOCQUERYOID ioctl. The kernel code
182 * should get back one of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
183 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't supported by
184 * the OS or the driver.
186 * Currently, that code may be returned by the Npcap NPF driver with the
187 * NT_STATUS_CUSTOMER_DEFINED bit. That prevents the return status from
188 * being mapped to a Windows error code; if the NPF driver were to stop
189 * ORing in the NT_STATUS_CUSTOMER_DEFINED bit, it's not obvious how those
190 * the NDIS_STATUS_ values that don't correspond to NTSTATUS values would
191 * be translated to Windows error values (NDIS_STATUS_NOT_SUPPORTED is
192 * the same as STATUS_NOT_SUPPORTED, which is an NTSTATUS value that is
193 * mapped to ERROR_NOT_SUPPORTED).
195 #define NDIS_STATUS_INVALID_OID 0xc0010017
196 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
197 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
200 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
203 PACKET_OID_DATA
*oid_data_arg
;
206 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
207 * It should be big enough to hold "*lenp" bytes of data; it
208 * will actually be slightly larger, as PACKET_OID_DATA has a
209 * 1-byte data array at the end, standing in for the variable-length
210 * data that's actually there.
212 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
213 if (oid_data_arg
== NULL
) {
214 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
215 "Couldn't allocate argument buffer for PacketRequest");
220 * No need to copy the data - we're doing a fetch.
222 oid_data_arg
->Oid
= oid
;
223 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
224 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
225 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
226 GetLastError(), "Error calling PacketRequest");
232 * Get the length actually supplied.
234 *lenp
= oid_data_arg
->Length
;
237 * Copy back the data we fetched.
239 memcpy(data
, oid_data_arg
->Data
, *lenp
);
245 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
247 struct pcap_win
*pw
= p
->priv
;
248 struct bpf_stat bstats
;
251 * Try to get statistics.
253 * (Please note - "struct pcap_stat" is *not* the same as
254 * WinPcap's "struct bpf_stat". It might currently have the
255 * same layout, but let's not cheat.
257 * Note also that we don't fill in ps_capt, as we might have
258 * been called by code compiled against an earlier version of
259 * WinPcap that didn't have ps_capt, in which case filling it
260 * in would stomp on whatever comes after the structure passed
263 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
264 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
265 GetLastError(), "PacketGetStats error");
268 ps
->ps_recv
= bstats
.bs_recv
;
269 ps
->ps_drop
= bstats
.bs_drop
;
272 * XXX - PacketGetStats() doesn't fill this in, so we just
276 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
285 * Win32-only routine for getting statistics.
287 * This way is definitely safer than passing the pcap_stat * from the userland.
288 * In fact, there could happen than the user allocates a variable which is not
289 * big enough for the new structure, and the library will write in a zone
290 * which is not allocated to this variable.
292 * In this way, we're pretty sure we are writing on memory allocated to this
295 * XXX - but this is the wrong way to handle statistics. Instead, we should
296 * have an API that returns data in a form like the Options section of a
297 * pcapng Interface Statistics Block:
299 * https://xml2rfc.tools.ietf.org/cgi-bin/xml2rfc.cgi?url=https://raw.githubusercontent.com/pcapng/pcapng/master/draft-tuexen-opsawg-pcapng.xml&modeAsFormat=html/ascii&type=ascii#rfc.section.4.6
301 * which would let us add new statistics straightforwardly and indicate which
302 * statistics we are and are *not* providing, rather than having to provide
303 * possibly-bogus values for statistics we can't provide.
305 static struct pcap_stat
*
306 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
308 struct pcap_win
*pw
= p
->priv
;
309 struct bpf_stat bstats
;
311 *pcap_stat_size
= sizeof (p
->stat
);
314 * Try to get statistics.
316 * (Please note - "struct pcap_stat" is *not* the same as
317 * WinPcap's "struct bpf_stat". It might currently have the
318 * same layout, but let's not cheat.)
320 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
321 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
322 GetLastError(), "PacketGetStatsEx error");
325 p
->stat
.ps_recv
= bstats
.bs_recv
;
326 p
->stat
.ps_drop
= bstats
.bs_drop
;
327 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
329 * Just in case this is ever compiled for a target other than
330 * Windows, which is somewhere between extremely unlikely and
334 p
->stat
.ps_capt
= bstats
.bs_capt
;
339 /* Set the dimension of the kernel-level capture buffer */
341 pcap_setbuff_npf(pcap_t
*p
, int dim
)
343 struct pcap_win
*pw
= p
->priv
;
345 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
347 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
353 /* Set the driver working mode */
355 pcap_setmode_npf(pcap_t
*p
, int mode
)
357 struct pcap_win
*pw
= p
->priv
;
359 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
361 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
368 /*set the minimum amount of data that will release a read call*/
370 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
372 struct pcap_win
*pw
= p
->priv
;
374 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
376 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
383 pcap_getevent_npf(pcap_t
*p
)
385 struct pcap_win
*pw
= p
->priv
;
387 return (PacketGetReadEvent(pw
->adapter
));
391 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
393 struct pcap_win
*pw
= p
->priv
;
395 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
399 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
402 struct pcap_win
*pw
= p
->priv
;
403 PACKET_OID_DATA
*oid_data_arg
;
406 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
407 * It should be big enough to hold "*lenp" bytes of data; it
408 * will actually be slightly larger, as PACKET_OID_DATA has a
409 * 1-byte data array at the end, standing in for the variable-length
410 * data that's actually there.
412 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
413 if (oid_data_arg
== NULL
) {
414 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
415 "Couldn't allocate argument buffer for PacketRequest");
419 oid_data_arg
->Oid
= oid
;
420 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
421 memcpy(oid_data_arg
->Data
, data
, *lenp
);
422 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
423 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
424 GetLastError(), "Error calling PacketRequest");
430 * Get the length actually copied.
432 *lenp
= oid_data_arg
->Length
;
435 * No need to copy the data - we're doing a set.
442 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
444 struct pcap_win
*pw
= p
->priv
;
447 res
= PacketSendPackets(pw
->adapter
,
452 if(res
!= queue
->len
){
453 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
454 GetLastError(), "Error queueing packets");
461 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
463 unsigned char *new_buff
;
466 /* Bogus parameter */
467 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
468 "Error: invalid size %d",size
);
472 /* Allocate the buffer */
473 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
476 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
477 "Error: not enough memory");
489 #ifdef HAVE_NPCAP_PACKET_API
491 * Kernel dump mode isn't supported in Npcap; calls to PacketSetDumpName(),
492 * PacketSetDumpLimits(), and PacketIsDumpEnded() will get compile-time
493 * deprecation warnings.
495 * Avoid calling them; just return errors indicating that kernel dump
496 * mode isn't supported in Npcap.
499 pcap_live_dump_npf(pcap_t
*p
, char *filename _U_
, int maxsize _U_
,
502 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
503 "Npcap doesn't support kernel dump mode");
507 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
509 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
510 "Npcap doesn't support kernel dump mode");
513 #else /* HAVE_NPCAP_PACKET_API */
515 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
517 struct pcap_win
*pw
= p
->priv
;
520 /* Set the packet driver in dump mode */
521 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
523 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
524 "Error setting dump mode");
528 /* Set the name of the dump file */
529 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
531 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
532 "Error setting kernel dump file name");
536 /* Set the limits of the dump file */
537 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
539 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
540 "Error setting dump limit");
548 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
550 struct pcap_win
*pw
= p
->priv
;
552 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
554 #endif /* HAVE_NPCAP_PACKET_API */
556 #ifdef HAVE_AIRPCAP_API
557 static PAirpcapHandle
558 pcap_get_airpcap_handle_npf(pcap_t
*p
)
560 struct pcap_win
*pw
= p
->priv
;
562 return (PacketGetAirPcapHandle(pw
->adapter
));
564 #else /* HAVE_AIRPCAP_API */
565 static PAirpcapHandle
566 pcap_get_airpcap_handle_npf(pcap_t
*p _U_
)
570 #endif /* HAVE_AIRPCAP_API */
573 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
578 register u_char
*bp
, *ep
;
580 struct pcap_win
*pw
= p
->priv
;
585 * Has "pcap_breakloop()" been called?
589 * Yes - clear the flag that indicates that it
590 * has, and return PCAP_ERROR_BREAK to indicate
591 * that we were told to break out of the loop.
594 return (PCAP_ERROR_BREAK
);
598 * Capture the packets.
600 * The PACKET structure had a bunch of extra stuff for
601 * Windows 9x/Me, but the only interesting data in it
602 * in the versions of Windows that we support is just
603 * a copy of p->buffer, a copy of p->buflen, and the
604 * actual number of bytes read returned from
605 * PacketReceivePacket(), none of which has to be
606 * retained from call to call, so we just keep one on
609 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
610 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
612 * Did the device go away?
613 * If so, the error we get can either be
614 * ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
616 DWORD errcode
= GetLastError();
618 if (errcode
== ERROR_GEN_FAILURE
||
619 errcode
== ERROR_DEVICE_REMOVED
) {
621 * The device on which we're capturing
622 * went away, or it became unusable
623 * by NPF due to a suspend/resume.
625 * ERROR_GEN_FAILURE comes from
626 * STATUS_UNSUCCESSFUL, as well as some
627 * other NT status codes that the Npcap
628 * driver is unlikely to return.
629 * XXX - hopefully no other error
630 * conditions are indicated by this.
632 * ERROR_DEVICE_REMOVED comes from
633 * STATUS_DEVICE_REMOVED.
635 * We report the Windows status code
636 * name and the corresponding NT status
637 * code name, for the benefit of attempts
638 * to debug cases where this error is
639 * reported when the device *wasn't*
640 * removed, either because it's not
641 * removable, it's removable but wasn't
642 * removed, or it's a device that doesn't
643 * correspond to a physical device.
645 * XXX - we really should return an
646 * appropriate error for that, but
647 * pcap_dispatch() etc. aren't
648 * documented as having error returns
649 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
651 const char *errcode_msg
;
653 if (errcode
== ERROR_GEN_FAILURE
)
654 errcode_msg
= "ERROR_GEN_FAILURE/STATUS_UNSUCCESSFUL";
656 errcode_msg
= "ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED";
657 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
658 "The interface disappeared (error code %s)",
661 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
662 PCAP_ERRBUF_SIZE
, errcode
,
663 "PacketReceivePacket error");
668 cc
= Packet
.ulBytesReceived
;
676 * Loop through each packet.
678 * This assumes that a single buffer of packets will have
679 * <= INT_MAX packets, so the packet count doesn't overflow.
681 #define bhp ((struct bpf_hdr *)bp)
685 register u_int caplen
, hdrlen
;
689 * Has "pcap_breakloop()" been called?
690 * If so, return immediately - if we haven't read any
691 * packets, clear the flag and return PCAP_ERROR_BREAK
692 * to indicate that we were told to break out of the loop,
693 * otherwise leave the flag set, so that the *next* call
694 * will break out of the loop without having read any
695 * packets, and return the number of packets we've
701 return (PCAP_ERROR_BREAK
);
704 p
->cc
= (u_int
) (ep
- bp
);
711 caplen
= bhp
->bh_caplen
;
712 hdrlen
= bhp
->bh_hdrlen
;
716 * Compute the number of bytes for this packet in
719 * That's the sum of the header length and the packet
720 * data length plus, if this is not the last packet,
721 * the padding required to align the next packet on
722 * the appropriate boundary.
724 * That means that it should be the minimum of the
725 * number of bytes left in the buffer and the
726 * rounded-up sum of the header and packet data lengths.
728 packet_bytes
= min((u_int
)(ep
- bp
), Packet_WORDALIGN(caplen
+ hdrlen
));
731 * Short-circuit evaluation: if using BPF filter
732 * in kernel, no need to do it now - we already know
733 * the packet passed the filter.
735 * XXX - pcapint_filter() should always return TRUE if
736 * handed a null pointer for the program, but it might
737 * just try to "run" the filter, so we check here.
739 if (pw
->filtering_in_kernel
||
740 p
->fcode
.bf_insns
== NULL
||
741 pcapint_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
743 switch (p
->rmt_samp
.method
) {
745 case PCAP_SAMP_1_EVERY_N
:
746 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
748 /* Discard all packets that are not '1 out of N' */
749 if (pw
->samp_npkt
!= 0) {
755 case PCAP_SAMP_FIRST_AFTER_N_MS
:
757 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
760 * Check if the timestamp of the arrived
761 * packet is smaller than our target time.
763 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
764 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
770 * The arrived packet is suitable for being
771 * delivered to our caller, so let's update
774 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
775 if (pw
->samp_time
.tv_usec
> 1000000) {
776 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
777 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
781 #endif /* ENABLE_REMOTE */
784 * XXX A bpf_hdr matches a pcap_pkthdr.
786 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
788 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
790 p
->cc
= (u_int
) (ep
- bp
);
807 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
809 struct pcap_win
*pw
= p
->priv
;
812 int packet_len
= 0, caplen
= 0;
813 struct pcap_pkthdr pcap_header
;
816 dag_record_t
*header
;
817 unsigned erf_record_len
;
821 unsigned dfp
= pw
->adapter
->DagFastProcess
;
824 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
827 * Get new packets from the network.
829 * The PACKET structure had a bunch of extra stuff for
830 * Windows 9x/Me, but the only interesting data in it
831 * in the versions of Windows that we support is just
832 * a copy of p->buffer, a copy of p->buflen, and the
833 * actual number of bytes read returned from
834 * PacketReceivePacket(), none of which has to be
835 * retained from call to call, so we just keep one on
838 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
839 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
840 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
844 cc
= Packet
.ulBytesReceived
;
846 /* The timeout has expired but we no packets arrived */
848 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
851 header
= (dag_record_t
*)p
->bp
;
853 endofbuf
= (char*)header
+ cc
;
856 * This can conceivably process more than INT_MAX packets,
857 * which would overflow the packet count, causing it either
858 * to look like a negative number, and thus cause us to
859 * return a value that looks like an error, or overflow
860 * back into positive territory, and thus cause us to
861 * return a too-low count.
863 * Therefore, if the packet count is unlimited, we clip
864 * it at INT_MAX; this routine is not expected to
865 * process packets indefinitely, so that's not an issue.
867 if (PACKET_COUNT_IS_UNLIMITED(cnt
))
871 * Cycle through the packets
875 erf_record_len
= SWAPS(header
->rlen
);
876 if((char*)header
+ erf_record_len
> endofbuf
)
879 /* Increase the number of captured packets */
882 /* Find the beginning of the packet */
883 dp
= ((u_char
*)header
) + dag_record_size
;
885 /* Determine actual packet len */
889 packet_len
= ATM_SNAPLEN
;
890 caplen
= ATM_SNAPLEN
;
896 swt
= SWAPS(header
->wlen
);
897 packet_len
= swt
- (pw
->dag_fcs_bits
);
898 caplen
= erf_record_len
- dag_record_size
- 2;
899 if (caplen
> packet_len
)
908 swt
= SWAPS(header
->wlen
);
909 packet_len
= swt
- (pw
->dag_fcs_bits
);
910 caplen
= erf_record_len
- dag_record_size
;
911 if (caplen
> packet_len
)
919 if(caplen
> p
->snapshot
)
920 caplen
= p
->snapshot
;
923 * Has "pcap_breakloop()" been called?
924 * If so, return immediately - if we haven't read any
925 * packets, clear the flag and return -2 to indicate
926 * that we were told to break out of the loop, otherwise
927 * leave the flag set, so that the *next* call will break
928 * out of the loop without having read any packets, and
929 * return the number of packets we've processed so far.
940 p
->bp
= (char*)header
;
941 p
->cc
= endofbuf
- (char*)header
;
948 /* convert between timestamp formats */
950 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
951 ts
= (ts
& 0xffffffffi
64) * 1000000;
952 ts
+= 0x80000000; /* rounding */
953 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
954 if (pcap_header
.ts
.tv_usec
>= 1000000) {
955 pcap_header
.ts
.tv_usec
-= 1000000;
956 pcap_header
.ts
.tv_sec
++;
960 /* No underlying filtering system. We need to filter on our own */
961 if (p
->fcode
.bf_insns
)
963 if (pcapint_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
965 /* Move to next packet */
966 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
971 /* Fill the header for the user supplied callback function */
972 pcap_header
.caplen
= caplen
;
973 pcap_header
.len
= packet_len
;
975 /* Call the callback function */
976 (*callback
)(user
, &pcap_header
, dp
);
978 /* Move to next packet */
979 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
981 /* Stop if the number of packets requested by user has been reached*/
982 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
984 p
->bp
= (char*)header
;
985 p
->cc
= endofbuf
- (char*)header
;
989 while((u_char
*)header
< endofbuf
);
993 #endif /* HAVE_DAG_API */
995 /* Send a packet to the network */
997 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
999 struct pcap_win
*pw
= p
->priv
;
1002 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
1003 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
1004 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1005 GetLastError(), "send error: PacketSendPacket failed");
1010 * We assume it all got sent if "PacketSendPacket()" succeeded.
1011 * "pcap_inject()" is expected to return the number of bytes
1018 pcap_cleanup_npf(pcap_t
*p
)
1020 struct pcap_win
*pw
= p
->priv
;
1022 if (pw
->adapter
!= NULL
) {
1023 PacketCloseAdapter(pw
->adapter
);
1026 if (pw
->rfmon_selfstart
)
1028 PacketSetMonitorMode(p
->opt
.device
, 0);
1030 pcapint_cleanup_live_common(p
);
1034 pcap_breakloop_npf(pcap_t
*p
)
1036 pcapint_breakloop_common(p
);
1037 struct pcap_win
*pw
= p
->priv
;
1039 /* XXX - what if this fails? */
1040 SetEvent(PacketGetReadEvent(pw
->adapter
));
1044 pcap_activate_npf(pcap_t
*p
)
1046 struct pcap_win
*pw
= p
->priv
;
1050 struct bpf_insn total_insn
;
1051 struct bpf_program total_prog
;
1055 * Monitor mode is supported on Windows Vista and later.
1057 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
1059 pw
->rfmon_selfstart
= 0;
1063 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
1065 pw
->rfmon_selfstart
= 0;
1066 // Monitor mode is not supported.
1069 return PCAP_ERROR_RFMON_NOTSUP
;
1078 pw
->rfmon_selfstart
= 1;
1083 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
1085 if (pw
->adapter
== NULL
)
1087 DWORD errcode
= GetLastError();
1090 * What error did we get when trying to open the adapter?
1094 case ERROR_BAD_UNIT
:
1096 * There's no such device.
1097 * There's nothing to add, so clear the error
1100 p
->errbuf
[0] = '\0';
1101 return (PCAP_ERROR_NO_SUCH_DEVICE
);
1103 case ERROR_ACCESS_DENIED
:
1105 * There is, but we don't have permission to
1108 * XXX - we currently get ERROR_BAD_UNIT if the
1109 * user says "no" to the UAC prompt.
1111 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1112 "The helper program for \"Admin-only Mode\" must be allowed to make changes to your device");
1113 return (PCAP_ERROR_PERM_DENIED
);
1117 * Unknown - report details.
1119 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1120 errcode
, "Error opening adapter");
1121 if (pw
->rfmon_selfstart
)
1123 PacketSetMonitorMode(p
->opt
.device
, 0);
1125 return (PCAP_ERROR
);
1129 /*get network type*/
1130 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
1132 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1133 GetLastError(), "Cannot determine the network type");
1137 /*Set the linktype*/
1138 switch (type
.LinkType
)
1141 * NDIS-defined medium types.
1143 case NdisMedium802_3
:
1144 p
->linktype
= DLT_EN10MB
;
1146 * This is (presumably) a real Ethernet capture; give it a
1147 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1148 * that an application can let you choose it, in case you're
1149 * capturing DOCSIS traffic that a Cisco Cable Modem
1150 * Termination System is putting out onto an Ethernet (it
1151 * doesn't put an Ethernet header onto the wire, it puts raw
1152 * DOCSIS frames out on the wire inside the low-level
1153 * Ethernet framing).
1155 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1156 if (p
->dlt_list
== NULL
)
1158 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1162 p
->dlt_list
[0] = DLT_EN10MB
;
1163 p
->dlt_list
[1] = DLT_DOCSIS
;
1167 case NdisMedium802_5
:
1171 p
->linktype
= DLT_IEEE802
;
1174 case NdisMediumFddi
:
1175 p
->linktype
= DLT_FDDI
;
1179 p
->linktype
= DLT_EN10MB
;
1182 case NdisMediumArcnetRaw
:
1183 p
->linktype
= DLT_ARCNET
;
1186 case NdisMediumArcnet878_2
:
1187 p
->linktype
= DLT_ARCNET
;
1191 p
->linktype
= DLT_ATM_RFC1483
;
1194 case NdisMediumWirelessWan
:
1195 p
->linktype
= DLT_RAW
;
1199 p
->linktype
= DLT_RAW
;
1203 * Npcap-defined medium types.
1205 case NdisMediumNull
:
1206 p
->linktype
= DLT_NULL
;
1209 case NdisMediumCHDLC
:
1210 p
->linktype
= DLT_CHDLC
;
1213 case NdisMediumPPPSerial
:
1214 p
->linktype
= DLT_PPP_SERIAL
;
1217 case NdisMediumBare80211
:
1218 p
->linktype
= DLT_IEEE802_11
;
1221 case NdisMediumRadio80211
:
1222 p
->linktype
= DLT_IEEE802_11_RADIO
;
1226 p
->linktype
= DLT_PPI
;
1231 * An unknown medium type is assumed to supply Ethernet
1232 * headers; if not, the user will have to report it,
1233 * so that the medium type and link-layer header type
1234 * can be determined. If we were to fail here, we
1235 * might get the link-layer type in the error, but
1236 * the user wouldn't get a capture, so we wouldn't
1237 * be able to determine the link-layer type; we report
1238 * a warning with the link-layer type, so at least
1239 * some programs will report the warning.
1241 p
->linktype
= DLT_EN10MB
;
1242 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1243 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1245 status
= PCAP_WARNING
;
1249 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1251 * Set the timestamp type.
1252 * (Yes, we require PacketGetTimestampModes(), not just
1253 * PacketSetTimestampMode(). If we have the former, we
1254 * have the latter, unless somebody's using a version
1255 * of Npcap that they've hacked to provide the former
1256 * but not the latter; if they've done that, either
1257 * they're confused or they're trolling us.)
1259 switch (p
->opt
.tstamp_type
) {
1261 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED
:
1263 * Better than low-res, but *not* synchronized with
1266 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION
))
1268 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1269 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1274 case PCAP_TSTAMP_HOST_LOWPREC
:
1276 * Low-res, but synchronized with the OS clock.
1278 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_QUERYSYSTEMTIME
))
1280 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1281 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1286 case PCAP_TSTAMP_HOST_HIPREC
:
1288 * High-res, and synchronized with the OS clock.
1290 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE
))
1292 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1293 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1298 case PCAP_TSTAMP_HOST
:
1300 * XXX - do whatever the default is, for now.
1301 * Set to the highest resolution that's synchronized
1302 * with the system clock?
1306 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1309 * Turn a negative snapshot value (invalid), a snapshot value of
1310 * 0 (unspecified), or a value bigger than the normal maximum
1311 * value, into the maximum allowed value.
1313 * If some application really *needs* a bigger snapshot
1314 * length, we should just increase MAXIMUM_SNAPLEN.
1316 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1317 p
->snapshot
= MAXIMUM_SNAPLEN
;
1319 /* Set promiscuous mode */
1323 * For future reference, in case we ever want to query
1324 * whether an adapter supports promiscuous mode, that
1325 * would be done on Windows by querying the value
1326 * of the OID_GEN_SUPPORTED_PACKET_FILTERS OID.
1328 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1330 DWORD errcode
= GetLastError();
1333 * Suppress spurious error generated by non-compliant
1334 * MS Surface mobile adapters that appear to
1335 * return NDIS_STATUS_NOT_SUPPORTED for attempts
1336 * to set the hardware filter.
1338 * It appears to be reporting NDIS_STATUS_NOT_SUPPORTED,
1339 * but with the NT status value "Customer" bit set;
1340 * the Npcap NPF driver sets that bit in some cases.
1342 * If we knew that this meant "promiscuous mode
1343 * isn't supported", we could add a "promiscuous
1344 * mode isn't supported" error code and return
1347 * 1) we don't know that it means that
1348 * rather than meaning "we reject attempts
1349 * to set the filter, even though the NDIS
1350 * specifications say you shouldn't do that"
1354 * 2) other interface types that don't
1355 * support promiscuous mode, at least
1356 * on UN*Xes, just silently ignore
1357 * attempts to set promiscuous mode
1359 * and rejecting it with an error could disrupt
1360 * attempts to capture, as many programs (tcpdump,
1361 * *shark) default to promiscuous mode.
1363 * Alternatively, we could return the "promiscuous
1364 * mode not supported" *warning* value, so that
1365 * correct code will either ignore it or report
1366 * it and continue capturing. (This may require
1367 * a pcap_init() flag to request that return
1368 * value, so that old incorrect programs that
1369 * assume a non-zero return from pcap_activate()
1370 * is an error don't break.)
1372 * We check here for ERROR_NOT_SUPPORTED, which
1373 * is what NDIS_STATUS_NOT_SUPPORTED (which is
1374 * the same value as the NTSTATUS value
1375 * STATUS_NOT_SUPPORTED) gets mapped to, as
1376 * well as NDIS_STATUS_NOT_SUPPORTED with the
1377 * "Customer" bit set.
1379 if (errcode
!= ERROR_NOT_SUPPORTED
&&
1380 errcode
!= (NDIS_STATUS_NOT_SUPPORTED
|NT_STATUS_CUSTOMER_DEFINED
))
1382 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1383 PCAP_ERRBUF_SIZE
, errcode
,
1384 "failed to set hardware filter to promiscuous mode");
1392 * NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by
1393 * installed protocols and all packets indicated by the NIC",
1394 * but if no protocol drivers (like TCP/IP) are installed,
1395 * NDIS_PACKET_TYPE_DIRECTED, NDIS_PACKET_TYPE_BROADCAST,
1396 * and NDIS_PACKET_TYPE_MULTICAST are needed to capture
1399 if (PacketSetHwFilter(pw
->adapter
,
1400 NDIS_PACKET_TYPE_ALL_LOCAL
|
1401 NDIS_PACKET_TYPE_DIRECTED
|
1402 NDIS_PACKET_TYPE_BROADCAST
|
1403 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1405 DWORD errcode
= GetLastError();
1408 * Suppress spurious error generated by non-compliant
1409 * MS Surface mobile adapters.
1411 if (errcode
!= (NDIS_STATUS_NOT_SUPPORTED
|NT_STATUS_CUSTOMER_DEFINED
))
1413 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1414 PCAP_ERRBUF_SIZE
, errcode
,
1415 "failed to set hardware filter to non-promiscuous mode");
1421 /* Set the buffer size */
1422 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1424 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1427 * Traditional Adapter
1430 * If the buffer size wasn't explicitly set, default to
1431 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1433 if (p
->opt
.buffer_size
== 0)
1434 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1436 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1438 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1442 p
->buffer
= malloc(p
->bufsize
);
1443 if (p
->buffer
== NULL
)
1445 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1450 if (p
->opt
.immediate
)
1452 /* tell the driver to copy the buffer as soon as data arrives */
1453 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1455 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1456 PCAP_ERRBUF_SIZE
, GetLastError(),
1457 "Error calling PacketSetMinToCopy");
1463 /* tell the driver to copy the buffer only if it contains at least 16K */
1464 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1466 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1467 PCAP_ERRBUF_SIZE
, GetLastError(),
1468 "Error calling PacketSetMinToCopy");
1478 * We have DAG support.
1487 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1488 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1489 strstr(_strlwr(p
->opt
.device
), "dag"));
1492 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1493 if(status
!= ERROR_SUCCESS
)
1496 status
= RegQueryValueEx(dagkey
,
1503 if(status
!= ERROR_SUCCESS
)
1508 RegCloseKey(dagkey
);
1513 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1515 /* Set the length of the FCS associated to any packet. This value
1516 * will be subtracted to the packet length */
1517 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1518 #else /* HAVE_DAG_API */
1523 #endif /* HAVE_DAG_API */
1527 * If there's no filter program installed, there's
1528 * no indication to the kernel of what the snapshot
1529 * length should be, so no snapshotting is done.
1531 * Therefore, when we open the device, we install
1532 * an "accept everything" filter with the specified
1535 total_insn
.code
= (u_short
)(BPF_RET
| BPF_K
);
1538 total_insn
.k
= p
->snapshot
;
1540 total_prog
.bf_len
= 1;
1541 total_prog
.bf_insns
= &total_insn
;
1542 if (!PacketSetBpf(pw
->adapter
, &total_prog
)) {
1543 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1544 GetLastError(), "PacketSetBpf");
1545 status
= PCAP_ERROR
;
1549 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1551 /* disable loopback capture if requested */
1552 if (p
->opt
.nocapture_local
)
1554 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1556 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1557 "Unable to disable the capture of loopback packets.");
1563 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1565 /* install dag specific handlers for read and setfilter */
1566 p
->read_op
= pcap_read_win32_dag
;
1567 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1571 #endif /* HAVE_DAG_API */
1572 /* install traditional npf handlers for read and setfilter */
1573 p
->read_op
= pcap_read_npf
;
1574 p
->setfilter_op
= pcap_setfilter_npf
;
1577 #endif /* HAVE_DAG_API */
1578 p
->setdirection_op
= NULL
; /* Not implemented. */
1579 /* XXX - can this be implemented on some versions of Windows? */
1580 p
->inject_op
= pcap_inject_npf
;
1581 p
->set_datalink_op
= NULL
; /* can't change data link type */
1582 p
->getnonblock_op
= pcap_getnonblock_npf
;
1583 p
->setnonblock_op
= pcap_setnonblock_npf
;
1584 p
->stats_op
= pcap_stats_npf
;
1585 p
->breakloop_op
= pcap_breakloop_npf
;
1586 p
->stats_ex_op
= pcap_stats_ex_npf
;
1587 p
->setbuff_op
= pcap_setbuff_npf
;
1588 p
->setmode_op
= pcap_setmode_npf
;
1589 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1590 p
->getevent_op
= pcap_getevent_npf
;
1591 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1592 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1593 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1594 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1595 p
->live_dump_op
= pcap_live_dump_npf
;
1596 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1597 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1598 p
->cleanup_op
= pcap_cleanup_npf
;
1601 * XXX - this is only done because WinPcap supported
1602 * pcap_fileno() returning the hFile HANDLE from the
1603 * ADAPTER structure. We make no general guarantees
1604 * that the caller can do anything useful with it.
1606 * (Not that we make any general guarantee of that
1607 * sort on UN*X, either, anymore, given that not
1608 * all capture devices are regular OS network
1611 p
->handle
= pw
->adapter
->hFile
;
1615 pcap_cleanup_npf(p
);
1616 return (PCAP_ERROR
);
1620 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1623 pcap_can_set_rfmon_npf(pcap_t
*p
)
1625 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1629 * Get a list of time stamp types.
1631 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1633 get_ts_types(const char *device
, pcap_t
*p
, char *ebuf
)
1635 char *device_copy
= NULL
;
1636 ADAPTER
*adapter
= NULL
;
1638 /* Npcap 1.00 driver is buggy and will write 16 bytes regardless of
1639 * buffer size. Using a sufficient stack buffer avoids overflow and
1640 * avoids a heap allocation in most (currently all) cases.
1644 DWORD error
= ERROR_SUCCESS
;
1645 ULONG
*modes
= NULL
;
1650 * First, find out how many time stamp modes we have.
1651 * To do that, we have to open the adapter.
1653 * XXX - PacketOpenAdapter() takes a non-const pointer
1654 * as an argument, so we make a copy of the argument and
1657 device_copy
= strdup(device
);
1658 if (device_copy
== NULL
) {
1659 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1664 adapter
= PacketOpenAdapter(device_copy
);
1665 if (adapter
== NULL
)
1667 error
= GetLastError();
1669 * If we can't open the device now, we won't be
1670 * able to later, either.
1672 * If the error is something that indicates
1673 * that the device doesn't exist, or that they
1674 * don't have permission to open the device - or
1675 * perhaps that they don't have permission to get
1676 * a list of devices, if PacketOpenAdapter() does
1677 * that - the user will find that out when they try
1678 * to activate the device; just return an empty
1679 * list of time stamp types.
1681 * Treating either of those as errors will, for
1682 * example, cause "tcpdump -i <number>" to fail,
1683 * because it first tries to pass the interface
1684 * name to pcap_create() and pcap_activate(),
1685 * in order to handle OSes where interfaces can
1686 * have names that are just numbers (stand up
1687 * and say hello, Linux!), and, if pcap_activate()
1688 * fails with a "no such device" error, checks
1689 * whether the interface name is a valid number
1690 * and, if so, tries to use it as an index in
1691 * the list of interfaces.
1693 * That means pcap_create() must succeed even
1694 * for interfaces that don't exist, with the
1695 * failure occurring at pcap_activate() time.
1697 if (error
== ERROR_BAD_UNIT
||
1698 error
== ERROR_ACCESS_DENIED
) {
1699 p
->tstamp_type_count
= 0;
1700 p
->tstamp_type_list
= NULL
;
1703 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1704 PCAP_ERRBUF_SIZE
, error
,
1705 "Error opening adapter");
1712 * Get the total number of time stamp modes.
1714 * The buffer for PacketGetTimestampModes() is
1715 * a sequence of 1 or more ULONGs. What's
1716 * passed to PacketGetTimestampModes() should have
1717 * the total number of ULONGs in the first ULONG;
1718 * what's returned *from* PacketGetTimestampModes()
1719 * has the total number of time stamp modes in
1722 * Yes, that means if there are N time stamp
1723 * modes, the first ULONG should be set to N+1
1724 * on input, and will be set to N on output.
1726 * We first make a call to PacketGetTimestampModes()
1727 * with a pointer to a single ULONG set to 1; the
1728 * call should fail with ERROR_MORE_DATA (unless
1729 * there are *no* modes, but that should never
1730 * happen), and that ULONG should be set to the
1733 ts_modes
[0] = sizeof(ts_modes
) / sizeof(ULONG
);
1734 ret
= PacketGetTimestampModes(adapter
, ts_modes
);
1737 * OK, it failed. Did it fail with
1740 error
= GetLastError();
1741 if (error
!= ERROR_MORE_DATA
) {
1743 * No, did it fail with ERROR_INVALID_FUNCTION?
1745 if (error
== ERROR_INVALID_FUNCTION
) {
1747 * This is probably due to
1748 * the driver with which Packet.dll
1749 * communicates being older, or
1750 * being a WinPcap driver, so
1751 * that it doesn't support
1752 * BIOCGTIMESTAMPMODES.
1754 * Tell the user to try uninstalling
1755 * Npcap - and WinPcap if installed -
1756 * and re-installing it, to flush
1757 * out all older drivers.
1759 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1760 "PacketGetTimestampModes() failed with ERROR_INVALID_FUNCTION; try uninstalling Npcap, and WinPcap if installed, and re-installing it from npcap.com");
1766 * No, some other error. Fail.
1768 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1769 PCAP_ERRBUF_SIZE
, error
,
1770 "Error calling PacketGetTimestampModes");
1776 * Yes, so we now know how many types to fetch.
1778 * The buffer needs to have one ULONG for the
1779 * count and num_ts_modes ULONGs for the
1780 * num_ts_modes time stamp types.
1782 num_ts_modes
= ts_modes
[0];
1783 modes
= (ULONG
*)malloc((1 + num_ts_modes
) * sizeof(ULONG
));
1784 if (modes
== NULL
) {
1785 /* Out of memory. */
1786 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1790 modes
[0] = 1 + num_ts_modes
;
1791 if (!PacketGetTimestampModes(adapter
, modes
)) {
1792 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1793 PCAP_ERRBUF_SIZE
, GetLastError(),
1794 "Error calling PacketGetTimestampModes");
1798 if (modes
[0] != num_ts_modes
) {
1799 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1800 "First PacketGetTimestampModes() call gives %lu modes, second call gives %lu modes",
1801 num_ts_modes
, modes
[0]);
1808 num_ts_modes
= ts_modes
[0];
1811 /* If the driver reports no modes supported *and*
1812 * ERROR_MORE_DATA, something is seriously wrong.
1813 * We *could* ignore the error and continue without supporting
1814 * settable timestamp modes, but that would hide a bug.
1816 if (modes
[0] == 0) {
1817 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1818 "PacketGetTimestampModes() reports 0 modes supported.");
1824 * Allocate a buffer big enough for
1825 * PCAP_TSTAMP_HOST (default) plus
1826 * the explicitly specified modes.
1828 p
->tstamp_type_list
= malloc((1 + num_ts_modes
) * sizeof(u_int
));
1829 if (p
->tstamp_type_list
== NULL
) {
1830 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1834 u_int num_ts_types
= 0;
1835 p
->tstamp_type_list
[num_ts_types
] =
1838 for (ULONG i
= 0; i
< num_ts_modes
; i
++) {
1839 switch (modes
[i
+ 1]) {
1841 case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION
:
1843 * Better than low-res,
1844 * but *not* synchronized
1845 * with the OS clock.
1847 p
->tstamp_type_list
[num_ts_types
] =
1848 PCAP_TSTAMP_HOST_HIPREC_UNSYNCED
;
1852 case TIMESTAMPMODE_QUERYSYSTEMTIME
:
1854 * Low-res, but synchronized
1855 * with the OS clock.
1857 p
->tstamp_type_list
[num_ts_types
] =
1858 PCAP_TSTAMP_HOST_LOWPREC
;
1862 case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE
:
1864 * High-res, and synchronized
1865 * with the OS clock.
1867 p
->tstamp_type_list
[num_ts_types
] =
1868 PCAP_TSTAMP_HOST_HIPREC
;
1874 * Unknown, so we can't
1880 p
->tstamp_type_count
= num_ts_types
;
1883 /* Clean up temporary allocations */
1884 if (device_copy
!= NULL
) {
1887 if (modes
!= NULL
&& modes
!= ts_modes
) {
1890 if (adapter
!= NULL
) {
1891 PacketCloseAdapter(adapter
);
1896 #else /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1898 get_ts_types(const char *device _U_
, pcap_t
*p _U_
, char *ebuf _U_
)
1901 * Nothing to fetch, so it always "succeeds".
1905 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1908 pcapint_create_interface(const char *device _U_
, char *ebuf
)
1912 p
= PCAP_CREATE_COMMON(ebuf
, struct pcap_win
);
1916 p
->activate_op
= pcap_activate_npf
;
1917 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1919 if (get_ts_types(device
, p
, ebuf
) == -1) {
1927 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1929 struct pcap_win
*pw
= p
->priv
;
1931 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1933 * Kernel filter not installed.
1935 * XXX - we don't know whether this failed because:
1937 * the kernel rejected the filter program as invalid,
1938 * in which case we should fall back on userland
1941 * the kernel rejected the filter program as too big,
1942 * in which case we should again fall back on
1943 * userland filtering;
1945 * there was some other problem, in which case we
1946 * should probably report an error.
1948 * For NPF devices, the Win32 status will be
1949 * STATUS_INVALID_DEVICE_REQUEST for invalid
1950 * filters, but I don't know what it'd be for
1951 * other problems, and for some other devices
1952 * it might not be set at all.
1954 * So we just fall back on userland filtering in
1959 * pcapint_install_bpf_program() validates the program.
1961 * XXX - what if we already have a filter in the kernel?
1963 if (pcapint_install_bpf_program(p
, fp
) < 0)
1965 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1972 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1975 * Discard any previously-received packets, as they might have
1976 * passed whatever filter was formerly in effect, but might
1977 * not pass this filter (BIOCSETF discards packets buffered
1978 * in the kernel, so you can lose packets in any case).
1985 * We filter at user level, since the kernel driver doesn't process the packets
1988 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1992 pcapint_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1996 /* Install a user level filter */
1997 if (pcapint_install_bpf_program(p
, fp
) < 0)
2004 pcap_getnonblock_npf(pcap_t
*p
)
2006 struct pcap_win
*pw
= p
->priv
;
2009 * XXX - if there were a PacketGetReadTimeout() call, we
2010 * would use it, and return 1 if the timeout is -1
2013 return (pw
->nonblock
);
2017 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
2019 struct pcap_win
*pw
= p
->priv
;
2024 * Set the packet buffer timeout to -1 for non-blocking
2030 * Restore the timeout set when the device was opened.
2031 * (Note that this may be -1, in which case we're not
2032 * really leaving non-blocking mode. However, although
2033 * the timeout argument to pcap_set_timeout() and
2034 * pcap_open_live() is an int, you're not supposed to
2035 * supply a negative value, so that "shouldn't happen".)
2037 newtimeout
= p
->opt
.timeout
;
2039 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
2040 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
2041 GetLastError(), "PacketSetReadTimeout");
2044 pw
->nonblock
= (newtimeout
== -1);
2049 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
2050 const char *description
, char *errbuf
)
2053 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2057 if_addr_size
= MAX_NETWORK_ADDRESSES
;
2060 * Add an entry for this interface, with no addresses.
2062 curdev
= pcapint_add_dev(devlistp
, name
, flags
, description
, errbuf
);
2063 if (curdev
== NULL
) {
2071 * Get the list of addresses for the interface.
2073 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
2077 * We don't return an error, because this can happen with
2078 * NdisWan interfaces, and we want to supply them even
2079 * if we can't supply their addresses.
2081 * We return an entry with an empty address list.
2087 * Now add the addresses.
2089 while (if_addr_size
-- > 0) {
2091 * "curdev" is an entry for this interface; add an entry for
2092 * this address to its list of addresses.
2094 res
= pcapint_add_addr_to_dev(curdev
,
2095 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
2096 sizeof (struct sockaddr_storage
),
2097 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
2098 sizeof (struct sockaddr_storage
),
2099 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
2100 sizeof (struct sockaddr_storage
),
2116 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
2122 NDIS_HARDWARE_STATUS hardware_status
;
2123 #ifdef OID_GEN_PHYSICAL_MEDIUM
2124 NDIS_PHYSICAL_MEDIUM phys_medium
;
2125 bpf_u_int32 gen_physical_medium_oids
[] = {
2126 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
2127 OID_GEN_PHYSICAL_MEDIUM_EX
,
2129 OID_GEN_PHYSICAL_MEDIUM
2131 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
2133 #endif /* OID_GEN_PHYSICAL_MEDIUM */
2134 #ifdef OID_GEN_LINK_STATE
2135 NDIS_LINK_STATE link_state
;
2139 if (*flags
& PCAP_IF_LOOPBACK
) {
2141 * Loopback interface, so the connection status doesn't
2142 * apply. and it's not wireless (or wired, for that
2143 * matter...). We presume it's up and running.
2145 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2150 * We need to open the adapter to get this information.
2152 * XXX - PacketOpenAdapter() takes a non-const pointer
2153 * as an argument, so we make a copy of the argument and
2156 name_copy
= strdup(name
);
2157 adapter
= PacketOpenAdapter(name_copy
);
2159 if (adapter
== NULL
) {
2161 * Give up; if they try to open this device, it'll fail.
2166 #ifdef HAVE_AIRPCAP_API
2168 * Airpcap.sys do not support the below 'OID_GEN_x' values.
2169 * Just set these flags (and none of the '*flags' entered with).
2171 if (PacketGetAirPcapHandle(adapter
)) {
2173 * Must be "up" and "running" if the above if succeeded.
2175 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
2178 * An airpcap device is a wireless device (duh!)
2180 *flags
|= PCAP_IF_WIRELESS
;
2183 * A "network association state" makes no sense for airpcap.
2185 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2186 PacketCloseAdapter(adapter
);
2192 * Get the hardware status, and derive "up" and "running" from
2195 len
= sizeof (hardware_status
);
2196 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
2197 &hardware_status
, &len
, errbuf
);
2199 switch (hardware_status
) {
2201 case NdisHardwareStatusReady
:
2203 * "Available and capable of sending and receiving
2204 * data over the wire", so up and running.
2206 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
2209 case NdisHardwareStatusInitializing
:
2210 case NdisHardwareStatusReset
:
2212 * "Initializing" or "Resetting", so up, but
2215 *flags
|= PCAP_IF_UP
;
2218 case NdisHardwareStatusClosing
:
2219 case NdisHardwareStatusNotReady
:
2221 * "Closing" or "Not ready", so neither up nor
2234 * Can't get the hardware status, so assume both up and
2237 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
2241 * Get the network type.
2243 #ifdef OID_GEN_PHYSICAL_MEDIUM
2245 * Try the OIDs we have for this, in order.
2247 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
2248 len
= sizeof (phys_medium
);
2249 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
2250 &phys_medium
, &len
, errbuf
);
2258 * Failed. We can't determine whether it failed
2259 * because that particular OID isn't supported
2260 * or because some other problem occurred, so we
2261 * just drive on and try the next OID.
2266 * We got the physical medium.
2268 * XXX - we might want to check for NdisPhysicalMediumWiMax
2269 * and NdisPhysicalMediumNative802_15_4 being
2270 * part of the enum, and check for those in the "wireless"
2273 DIAG_OFF_ENUM_SWITCH
2274 switch (phys_medium
) {
2276 case NdisPhysicalMediumWirelessLan
:
2277 case NdisPhysicalMediumWirelessWan
:
2278 case NdisPhysicalMediumNative802_11
:
2279 case NdisPhysicalMediumBluetooth
:
2280 case NdisPhysicalMediumUWB
:
2281 case NdisPhysicalMediumIrda
:
2285 *flags
|= PCAP_IF_WIRELESS
;
2290 * Not wireless or unknown
2299 * Get the connection status.
2301 #ifdef OID_GEN_LINK_STATE
2302 len
= sizeof(link_state
);
2303 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
2307 * NOTE: this also gives us the receive and transmit
2310 switch (link_state
.MediaConnectState
) {
2312 case MediaConnectStateConnected
:
2316 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2319 case MediaConnectStateDisconnected
:
2321 * It's disconnected.
2323 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2326 case MediaConnectStateUnknown
:
2329 * It's unknown whether it's connected or not.
2336 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2342 * OK, OID_GEN_LINK_STATE didn't work, try
2343 * OID_GEN_MEDIA_CONNECT_STATUS.
2345 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
2346 &connect_status
, &len
, errbuf
);
2348 switch (connect_status
) {
2350 case NdisMediaStateConnected
:
2354 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2357 case NdisMediaStateDisconnected
:
2359 * It's disconnected.
2361 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2366 PacketCloseAdapter(adapter
);
2371 pcapint_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
2380 * Find out how big a buffer we need.
2382 * This call should always return FALSE; if the error is
2383 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2384 * the size of the buffer we need, otherwise there's a
2385 * problem, and NameLength should be set to 0.
2387 * It shouldn't require NameLength to be set, but,
2388 * at least as of WinPcap 4.1.3, it checks whether
2389 * NameLength is big enough before it checks for a
2390 * NULL buffer argument, so, while it'll still do
2391 * the right thing if NameLength is uninitialized and
2392 * whatever junk happens to be there is big enough
2393 * (because the pointer argument will be null), it's
2394 * still reading an uninitialized variable.
2397 if (!PacketGetAdapterNames(NULL
, &NameLength
))
2399 DWORD last_error
= GetLastError();
2401 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
2403 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2404 last_error
, "PacketGetAdapterNames");
2409 if (NameLength
<= 0)
2411 AdaptersName
= (char*) malloc(NameLength
);
2412 if (AdaptersName
== NULL
)
2414 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
2418 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
2419 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2420 GetLastError(), "PacketGetAdapterNames");
2426 * "PacketGetAdapterNames()" returned a list of
2427 * null-terminated ASCII interface name strings,
2428 * terminated by a null string, followed by a list
2429 * of null-terminated ASCII interface description
2430 * strings, terminated by a null string.
2431 * This means there are two ASCII nulls at the end
2432 * of the first list.
2434 * Find the end of the first list; that's the
2435 * beginning of the second list.
2437 desc
= &AdaptersName
[0];
2438 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
2442 * Found it - "desc" points to the first of the two
2443 * nulls at the end of the list of names, so the
2444 * first byte of the list of descriptions is two bytes
2450 * Loop over the elements in the first list.
2452 name
= &AdaptersName
[0];
2453 while (*name
!= '\0') {
2454 bpf_u_int32 flags
= 0;
2456 #ifdef HAVE_AIRPCAP_API
2458 * Is this an AirPcap device?
2459 * If so, ignore it; it'll get added later, by the
2462 if (device_is_airpcap(name
, errbuf
) == 1) {
2463 name
+= strlen(name
) + 1;
2464 desc
+= strlen(desc
) + 1;
2469 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2471 * Is this a loopback interface?
2473 if (PacketIsLoopbackAdapter(name
)) {
2475 flags
|= PCAP_IF_LOOPBACK
;
2479 * Get additional flags.
2481 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
2490 * Add an entry for this interface.
2492 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
2500 name
+= strlen(name
) + 1;
2501 desc
+= strlen(desc
) + 1;
2509 * Return the name of a network interface attached to the system, or NULL
2510 * if none can be found. The interface must be configured up; the
2511 * lowest unit number is preferred; loopback is ignored.
2513 * In the best of all possible worlds, this would be the same as on
2514 * UN*X, but there may be software that expects this to return a
2515 * full list of devices after the first device.
2517 #define ADAPTERSNAME_LEN 8192
2519 pcap_lookupdev(char *errbuf
)
2522 DWORD dwWindowsMajorVersion
;
2525 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2526 * it may return UTF-16 strings, for backwards-compatibility
2527 * reasons, and we're also disabling the hack to make that work,
2528 * for not-going-past-the-end-of-a-string reasons, and 2) we
2529 * want its behavior to be consistent.
2531 * In addition, it's not thread-safe, so we've marked it as
2534 if (pcapint_new_api
) {
2535 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2536 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2540 /* disable MSVC's GetVersion() deprecated warning here */
2541 DIAG_OFF_DEPRECATION
2542 dwVersion
= GetVersion(); /* get the OS version */
2544 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
2546 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
2548 * Windows 95, 98, ME.
2550 ULONG NameLength
= ADAPTERSNAME_LEN
;
2551 static char AdaptersName
[ADAPTERSNAME_LEN
];
2553 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
2554 return (AdaptersName
);
2559 * Windows NT (NT 4.0 and later).
2560 * Convert the names to Unicode for backward compatibility.
2562 ULONG NameLength
= ADAPTERSNAME_LEN
;
2563 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
2564 size_t BufferSpaceLeft
;
2569 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
2572 if(TAdaptersName
== NULL
)
2574 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
2578 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
2580 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2581 GetLastError(), "PacketGetAdapterNames");
2582 free(TAdaptersName
);
2587 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
2588 tAstr
= (char*)TAdaptersName
;
2589 Unameptr
= AdaptersName
;
2592 * Convert the device names to Unicode into AdapterName.
2596 * Length of the name, including the terminating
2599 namelen
= strlen(tAstr
) + 1;
2602 * Do we have room for the name in the Unicode
2605 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
2611 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
2614 * Copy the name, converting ASCII to Unicode.
2615 * namelen includes the NUL, so we copy it as
2618 for (i
= 0; i
< namelen
; i
++)
2619 *Unameptr
++ = *tAstr
++;
2622 * Count this adapter.
2625 } while (namelen
!= 1);
2628 * Copy the descriptions, but don't convert them from
2631 Adescptr
= (char *)Unameptr
;
2636 desclen
= strlen(tAstr
) + 1;
2639 * Do we have room for the name in the Unicode
2642 if (BufferSpaceLeft
< desclen
) {
2650 * Just copy the ASCII string.
2651 * namelen includes the NUL, so we copy it as
2654 memcpy(Adescptr
, tAstr
, desclen
);
2655 Adescptr
+= desclen
;
2657 BufferSpaceLeft
-= desclen
;
2661 free(TAdaptersName
);
2662 return (char *)(AdaptersName
);
2667 * We can't use the same code that we use on UN*X, as that's doing
2668 * UN*X-specific calls.
2670 * We don't just fetch the entire list of devices, search for the
2671 * particular device, and use its first IPv4 address, as that's too
2672 * much work to get just one device's netmask.
2675 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2679 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2680 * in order to skip non IPv4 (i.e. IPv6 addresses)
2682 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2683 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2684 struct sockaddr_in
*t_addr
;
2687 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2692 for(i
= 0; i
< if_addr_size
; i
++)
2694 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2696 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2697 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2698 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2699 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2711 static const char *pcap_lib_version_string
;
2713 #ifdef HAVE_VERSION_H
2715 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2716 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2719 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2720 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2721 * for the packet.dll version number as well.)
2723 #include "../../version.h"
2725 static const char pcap_version_string
[] =
2726 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2729 pcap_lib_version(void)
2731 if (pcap_lib_version_string
== NULL
) {
2733 * Generate the version string.
2735 const char *packet_version_string
= PacketGetVersion();
2737 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2739 * WinPcap/Npcap version string and packet.dll version
2740 * string are the same; just report the WinPcap/Npcap
2743 pcap_lib_version_string
= pcap_version_string
;
2746 * WinPcap/Npcap version string and packet.dll version
2747 * string are different; that shouldn't be the
2748 * case (the two libraries should come from the
2749 * same version of WinPcap/Npcap), so we report both
2752 char *full_pcap_version_string
;
2754 if (pcapint_asprintf(&full_pcap_version_string
,
2755 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
,
2756 packet_version_string
) != -1) {
2758 pcap_lib_version_string
= full_pcap_version_string
;
2762 return (pcap_lib_version_string
);
2765 #else /* HAVE_VERSION_H */
2768 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2772 pcap_lib_version(void)
2774 if (pcap_lib_version_string
== NULL
) {
2776 * Generate the version string. Report the packet.dll
2779 char *full_pcap_version_string
;
2781 if (pcapint_asprintf(&full_pcap_version_string
,
2782 PCAP_VERSION_STRING
" (packet.dll version %s)",
2783 PacketGetVersion()) != -1) {
2785 pcap_lib_version_string
= full_pcap_version_string
;
2788 return (pcap_lib_version_string
);
2790 #endif /* HAVE_VERSION_H */