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 /* Init Winsock if it hasn't already been initialized */
1086 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
1088 if (pw
->adapter
== NULL
)
1090 DWORD errcode
= GetLastError();
1093 * What error did we get when trying to open the adapter?
1097 case ERROR_BAD_UNIT
:
1099 * There's no such device.
1100 * There's nothing to add, so clear the error
1103 p
->errbuf
[0] = '\0';
1104 return (PCAP_ERROR_NO_SUCH_DEVICE
);
1106 case ERROR_ACCESS_DENIED
:
1108 * There is, but we don't have permission to
1111 * XXX - we currently get ERROR_BAD_UNIT if the
1112 * user says "no" to the UAC prompt.
1114 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1115 "The helper program for \"Admin-only Mode\" must be allowed to make changes to your device");
1116 return (PCAP_ERROR_PERM_DENIED
);
1120 * Unknown - report details.
1122 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1123 errcode
, "Error opening adapter");
1124 if (pw
->rfmon_selfstart
)
1126 PacketSetMonitorMode(p
->opt
.device
, 0);
1128 return (PCAP_ERROR
);
1132 /*get network type*/
1133 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
1135 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1136 GetLastError(), "Cannot determine the network type");
1140 /*Set the linktype*/
1141 switch (type
.LinkType
)
1144 * NDIS-defined medium types.
1146 case NdisMedium802_3
:
1147 p
->linktype
= DLT_EN10MB
;
1149 * This is (presumably) a real Ethernet capture; give it a
1150 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1151 * that an application can let you choose it, in case you're
1152 * capturing DOCSIS traffic that a Cisco Cable Modem
1153 * Termination System is putting out onto an Ethernet (it
1154 * doesn't put an Ethernet header onto the wire, it puts raw
1155 * DOCSIS frames out on the wire inside the low-level
1156 * Ethernet framing).
1158 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1159 if (p
->dlt_list
== NULL
)
1161 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1165 p
->dlt_list
[0] = DLT_EN10MB
;
1166 p
->dlt_list
[1] = DLT_DOCSIS
;
1170 case NdisMedium802_5
:
1174 p
->linktype
= DLT_IEEE802
;
1177 case NdisMediumFddi
:
1178 p
->linktype
= DLT_FDDI
;
1182 p
->linktype
= DLT_EN10MB
;
1185 case NdisMediumArcnetRaw
:
1186 p
->linktype
= DLT_ARCNET
;
1189 case NdisMediumArcnet878_2
:
1190 p
->linktype
= DLT_ARCNET
;
1194 p
->linktype
= DLT_ATM_RFC1483
;
1197 case NdisMediumWirelessWan
:
1198 p
->linktype
= DLT_RAW
;
1202 p
->linktype
= DLT_RAW
;
1206 * Npcap-defined medium types.
1208 case NdisMediumNull
:
1209 p
->linktype
= DLT_NULL
;
1212 case NdisMediumCHDLC
:
1213 p
->linktype
= DLT_CHDLC
;
1216 case NdisMediumPPPSerial
:
1217 p
->linktype
= DLT_PPP_SERIAL
;
1220 case NdisMediumBare80211
:
1221 p
->linktype
= DLT_IEEE802_11
;
1224 case NdisMediumRadio80211
:
1225 p
->linktype
= DLT_IEEE802_11_RADIO
;
1229 p
->linktype
= DLT_PPI
;
1234 * An unknown medium type is assumed to supply Ethernet
1235 * headers; if not, the user will have to report it,
1236 * so that the medium type and link-layer header type
1237 * can be determined. If we were to fail here, we
1238 * might get the link-layer type in the error, but
1239 * the user wouldn't get a capture, so we wouldn't
1240 * be able to determine the link-layer type; we report
1241 * a warning with the link-layer type, so at least
1242 * some programs will report the warning.
1244 p
->linktype
= DLT_EN10MB
;
1245 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1246 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1248 status
= PCAP_WARNING
;
1252 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1254 * Set the timestamp type.
1255 * (Yes, we require PacketGetTimestampModes(), not just
1256 * PacketSetTimestampMode(). If we have the former, we
1257 * have the latter, unless somebody's using a version
1258 * of Npcap that they've hacked to provide the former
1259 * but not the latter; if they've done that, either
1260 * they're confused or they're trolling us.)
1262 switch (p
->opt
.tstamp_type
) {
1264 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED
:
1266 * Better than low-res, but *not* synchronized with
1269 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION
))
1271 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1272 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1277 case PCAP_TSTAMP_HOST_LOWPREC
:
1279 * Low-res, but synchronized with the OS clock.
1281 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_QUERYSYSTEMTIME
))
1283 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1284 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1289 case PCAP_TSTAMP_HOST_HIPREC
:
1291 * High-res, and synchronized with the OS clock.
1293 if (!PacketSetTimestampMode(pw
->adapter
, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE
))
1295 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1296 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1301 case PCAP_TSTAMP_HOST
:
1303 * XXX - do whatever the default is, for now.
1304 * Set to the highest resolution that's synchronized
1305 * with the system clock?
1309 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1312 * Turn a negative snapshot value (invalid), a snapshot value of
1313 * 0 (unspecified), or a value bigger than the normal maximum
1314 * value, into the maximum allowed value.
1316 * If some application really *needs* a bigger snapshot
1317 * length, we should just increase MAXIMUM_SNAPLEN.
1319 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1320 p
->snapshot
= MAXIMUM_SNAPLEN
;
1322 /* Set promiscuous mode */
1326 * For future reference, in case we ever want to query
1327 * whether an adapter supports promiscuous mode, that
1328 * would be done on Windows by querying the value
1329 * of the OID_GEN_SUPPORTED_PACKET_FILTERS OID.
1331 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1333 DWORD errcode
= GetLastError();
1336 * Suppress spurious error generated by non-compliant
1337 * MS Surface mobile adapters that appear to
1338 * return NDIS_STATUS_NOT_SUPPORTED for attempts
1339 * to set the hardware filter.
1341 * It appears to be reporting NDIS_STATUS_NOT_SUPPORTED,
1342 * but with the NT status value "Customer" bit set;
1343 * the Npcap NPF driver sets that bit in some cases.
1345 * If we knew that this meant "promiscuous mode
1346 * isn't supported", we could add a "promiscuous
1347 * mode isn't supported" error code and return
1350 * 1) we don't know that it means that
1351 * rather than meaning "we reject attempts
1352 * to set the filter, even though the NDIS
1353 * specifications say you shouldn't do that"
1357 * 2) other interface types that don't
1358 * support promiscuous mode, at least
1359 * on UN*Xes, just silently ignore
1360 * attempts to set promiscuous mode
1362 * and rejecting it with an error could disrupt
1363 * attempts to capture, as many programs (tcpdump,
1364 * *shark) default to promiscuous mode.
1366 * Alternatively, we could return the "promiscuous
1367 * mode not supported" *warning* value, so that
1368 * correct code will either ignore it or report
1369 * it and continue capturing. (This may require
1370 * a pcap_init() flag to request that return
1371 * value, so that old incorrect programs that
1372 * assume a non-zero return from pcap_activate()
1373 * is an error don't break.)
1375 * We check here for ERROR_NOT_SUPPORTED, which
1376 * is what NDIS_STATUS_NOT_SUPPORTED (which is
1377 * the same value as the NTSTATUS value
1378 * STATUS_NOT_SUPPORTED) gets mapped to, as
1379 * well as NDIS_STATUS_NOT_SUPPORTED with the
1380 * "Customer" bit set.
1382 if (errcode
!= ERROR_NOT_SUPPORTED
&&
1383 errcode
!= (NDIS_STATUS_NOT_SUPPORTED
|NT_STATUS_CUSTOMER_DEFINED
))
1385 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1386 PCAP_ERRBUF_SIZE
, errcode
,
1387 "failed to set hardware filter to promiscuous mode");
1395 * NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by
1396 * installed protocols and all packets indicated by the NIC",
1397 * but if no protocol drivers (like TCP/IP) are installed,
1398 * NDIS_PACKET_TYPE_DIRECTED, NDIS_PACKET_TYPE_BROADCAST,
1399 * and NDIS_PACKET_TYPE_MULTICAST are needed to capture
1402 if (PacketSetHwFilter(pw
->adapter
,
1403 NDIS_PACKET_TYPE_ALL_LOCAL
|
1404 NDIS_PACKET_TYPE_DIRECTED
|
1405 NDIS_PACKET_TYPE_BROADCAST
|
1406 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1408 DWORD errcode
= GetLastError();
1411 * Suppress spurious error generated by non-compliant
1412 * MS Surface mobile adapters.
1414 if (errcode
!= (NDIS_STATUS_NOT_SUPPORTED
|NT_STATUS_CUSTOMER_DEFINED
))
1416 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1417 PCAP_ERRBUF_SIZE
, errcode
,
1418 "failed to set hardware filter to non-promiscuous mode");
1424 /* Set the buffer size */
1425 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1427 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1430 * Traditional Adapter
1433 * If the buffer size wasn't explicitly set, default to
1434 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1436 if (p
->opt
.buffer_size
== 0)
1437 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1439 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1441 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1445 p
->buffer
= malloc(p
->bufsize
);
1446 if (p
->buffer
== NULL
)
1448 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1453 if (p
->opt
.immediate
)
1455 /* tell the driver to copy the buffer as soon as data arrives */
1456 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1458 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1459 PCAP_ERRBUF_SIZE
, GetLastError(),
1460 "Error calling PacketSetMinToCopy");
1466 /* tell the driver to copy the buffer only if it contains at least 16K */
1467 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1469 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
,
1470 PCAP_ERRBUF_SIZE
, GetLastError(),
1471 "Error calling PacketSetMinToCopy");
1481 * We have DAG support.
1490 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1491 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1492 strstr(_strlwr(p
->opt
.device
), "dag"));
1495 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1496 if(status
!= ERROR_SUCCESS
)
1499 status
= RegQueryValueEx(dagkey
,
1506 if(status
!= ERROR_SUCCESS
)
1511 RegCloseKey(dagkey
);
1516 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1518 /* Set the length of the FCS associated to any packet. This value
1519 * will be subtracted to the packet length */
1520 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1521 #else /* HAVE_DAG_API */
1526 #endif /* HAVE_DAG_API */
1530 * If there's no filter program installed, there's
1531 * no indication to the kernel of what the snapshot
1532 * length should be, so no snapshotting is done.
1534 * Therefore, when we open the device, we install
1535 * an "accept everything" filter with the specified
1538 total_insn
.code
= (u_short
)(BPF_RET
| BPF_K
);
1541 total_insn
.k
= p
->snapshot
;
1543 total_prog
.bf_len
= 1;
1544 total_prog
.bf_insns
= &total_insn
;
1545 if (!PacketSetBpf(pw
->adapter
, &total_prog
)) {
1546 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1547 GetLastError(), "PacketSetBpf");
1548 status
= PCAP_ERROR
;
1552 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1554 /* disable loopback capture if requested */
1555 if (p
->opt
.nocapture_local
)
1557 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1559 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1560 "Unable to disable the capture of loopback packets.");
1566 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1568 /* install dag specific handlers for read and setfilter */
1569 p
->read_op
= pcap_read_win32_dag
;
1570 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1574 #endif /* HAVE_DAG_API */
1575 /* install traditional npf handlers for read and setfilter */
1576 p
->read_op
= pcap_read_npf
;
1577 p
->setfilter_op
= pcap_setfilter_npf
;
1580 #endif /* HAVE_DAG_API */
1581 p
->setdirection_op
= NULL
; /* Not implemented. */
1582 /* XXX - can this be implemented on some versions of Windows? */
1583 p
->inject_op
= pcap_inject_npf
;
1584 p
->set_datalink_op
= NULL
; /* can't change data link type */
1585 p
->getnonblock_op
= pcap_getnonblock_npf
;
1586 p
->setnonblock_op
= pcap_setnonblock_npf
;
1587 p
->stats_op
= pcap_stats_npf
;
1588 p
->breakloop_op
= pcap_breakloop_npf
;
1589 p
->stats_ex_op
= pcap_stats_ex_npf
;
1590 p
->setbuff_op
= pcap_setbuff_npf
;
1591 p
->setmode_op
= pcap_setmode_npf
;
1592 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1593 p
->getevent_op
= pcap_getevent_npf
;
1594 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1595 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1596 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1597 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1598 p
->live_dump_op
= pcap_live_dump_npf
;
1599 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1600 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1601 p
->cleanup_op
= pcap_cleanup_npf
;
1604 * XXX - this is only done because WinPcap supported
1605 * pcap_fileno() returning the hFile HANDLE from the
1606 * ADAPTER structure. We make no general guarantees
1607 * that the caller can do anything useful with it.
1609 * (Not that we make any general guarantee of that
1610 * sort on UN*X, either, anymore, given that not
1611 * all capture devices are regular OS network
1614 p
->handle
= pw
->adapter
->hFile
;
1618 pcap_cleanup_npf(p
);
1619 return (PCAP_ERROR
);
1623 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1626 pcap_can_set_rfmon_npf(pcap_t
*p
)
1628 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1632 * Get a list of time stamp types.
1634 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1636 get_ts_types(const char *device
, pcap_t
*p
, char *ebuf
)
1638 char *device_copy
= NULL
;
1639 ADAPTER
*adapter
= NULL
;
1641 /* Npcap 1.00 driver is buggy and will write 16 bytes regardless of
1642 * buffer size. Using a sufficient stack buffer avoids overflow and
1643 * avoids a heap allocation in most (currently all) cases.
1647 DWORD error
= ERROR_SUCCESS
;
1648 ULONG
*modes
= NULL
;
1653 * First, find out how many time stamp modes we have.
1654 * To do that, we have to open the adapter.
1656 * XXX - PacketOpenAdapter() takes a non-const pointer
1657 * as an argument, so we make a copy of the argument and
1660 device_copy
= strdup(device
);
1661 if (device_copy
== NULL
) {
1662 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1667 adapter
= PacketOpenAdapter(device_copy
);
1668 if (adapter
== NULL
)
1670 error
= GetLastError();
1672 * If we can't open the device now, we won't be
1673 * able to later, either.
1675 * If the error is something that indicates
1676 * that the device doesn't exist, or that they
1677 * don't have permission to open the device - or
1678 * perhaps that they don't have permission to get
1679 * a list of devices, if PacketOpenAdapter() does
1680 * that - the user will find that out when they try
1681 * to activate the device; just return an empty
1682 * list of time stamp types.
1684 * Treating either of those as errors will, for
1685 * example, cause "tcpdump -i <number>" to fail,
1686 * because it first tries to pass the interface
1687 * name to pcap_create() and pcap_activate(),
1688 * in order to handle OSes where interfaces can
1689 * have names that are just numbers (stand up
1690 * and say hello, Linux!), and, if pcap_activate()
1691 * fails with a "no such device" error, checks
1692 * whether the interface name is a valid number
1693 * and, if so, tries to use it as an index in
1694 * the list of interfaces.
1696 * That means pcap_create() must succeed even
1697 * for interfaces that don't exist, with the
1698 * failure occurring at pcap_activate() time.
1700 if (error
== ERROR_BAD_UNIT
||
1701 error
== ERROR_ACCESS_DENIED
) {
1702 p
->tstamp_type_count
= 0;
1703 p
->tstamp_type_list
= NULL
;
1706 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1707 PCAP_ERRBUF_SIZE
, error
,
1708 "Error opening adapter");
1715 * Get the total number of time stamp modes.
1717 * The buffer for PacketGetTimestampModes() is
1718 * a sequence of 1 or more ULONGs. What's
1719 * passed to PacketGetTimestampModes() should have
1720 * the total number of ULONGs in the first ULONG;
1721 * what's returned *from* PacketGetTimestampModes()
1722 * has the total number of time stamp modes in
1725 * Yes, that means if there are N time stamp
1726 * modes, the first ULONG should be set to N+1
1727 * on input, and will be set to N on output.
1729 * We first make a call to PacketGetTimestampModes()
1730 * with a pointer to a single ULONG set to 1; the
1731 * call should fail with ERROR_MORE_DATA (unless
1732 * there are *no* modes, but that should never
1733 * happen), and that ULONG should be set to the
1736 ts_modes
[0] = sizeof(ts_modes
) / sizeof(ULONG
);
1737 ret
= PacketGetTimestampModes(adapter
, ts_modes
);
1740 * OK, it failed. Did it fail with
1743 error
= GetLastError();
1744 if (error
!= ERROR_MORE_DATA
) {
1746 * No, did it fail with ERROR_INVALID_FUNCTION?
1748 if (error
== ERROR_INVALID_FUNCTION
) {
1750 * This is probably due to
1751 * the driver with which Packet.dll
1752 * communicates being older, or
1753 * being a WinPcap driver, so
1754 * that it doesn't support
1755 * BIOCGTIMESTAMPMODES.
1757 * Tell the user to try uninstalling
1758 * Npcap - and WinPcap if installed -
1759 * and re-installing it, to flush
1760 * out all older drivers.
1762 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1763 "PacketGetTimestampModes() failed with ERROR_INVALID_FUNCTION; try uninstalling Npcap, and WinPcap if installed, and re-installing it from npcap.com");
1769 * No, some other error. Fail.
1771 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1772 PCAP_ERRBUF_SIZE
, error
,
1773 "Error calling PacketGetTimestampModes");
1779 * Yes, so we now know how many types to fetch.
1781 * The buffer needs to have one ULONG for the
1782 * count and num_ts_modes ULONGs for the
1783 * num_ts_modes time stamp types.
1785 num_ts_modes
= ts_modes
[0];
1786 modes
= (ULONG
*)malloc((1 + num_ts_modes
) * sizeof(ULONG
));
1787 if (modes
== NULL
) {
1788 /* Out of memory. */
1789 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1793 modes
[0] = 1 + num_ts_modes
;
1794 if (!PacketGetTimestampModes(adapter
, modes
)) {
1795 pcapint_fmt_errmsg_for_win32_err(ebuf
,
1796 PCAP_ERRBUF_SIZE
, GetLastError(),
1797 "Error calling PacketGetTimestampModes");
1801 if (modes
[0] != num_ts_modes
) {
1802 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1803 "First PacketGetTimestampModes() call gives %lu modes, second call gives %lu modes",
1804 num_ts_modes
, modes
[0]);
1811 num_ts_modes
= ts_modes
[0];
1814 /* If the driver reports no modes supported *and*
1815 * ERROR_MORE_DATA, something is seriously wrong.
1816 * We *could* ignore the error and continue without supporting
1817 * settable timestamp modes, but that would hide a bug.
1819 if (modes
[0] == 0) {
1820 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1821 "PacketGetTimestampModes() reports 0 modes supported.");
1827 * Allocate a buffer big enough for
1828 * PCAP_TSTAMP_HOST (default) plus
1829 * the explicitly specified modes.
1831 p
->tstamp_type_list
= malloc((1 + num_ts_modes
) * sizeof(u_int
));
1832 if (p
->tstamp_type_list
== NULL
) {
1833 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
, errno
, "malloc");
1837 u_int num_ts_types
= 0;
1838 p
->tstamp_type_list
[num_ts_types
] =
1841 for (ULONG i
= 0; i
< num_ts_modes
; i
++) {
1842 switch (modes
[i
+ 1]) {
1844 case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION
:
1846 * Better than low-res,
1847 * but *not* synchronized
1848 * with the OS clock.
1850 p
->tstamp_type_list
[num_ts_types
] =
1851 PCAP_TSTAMP_HOST_HIPREC_UNSYNCED
;
1855 case TIMESTAMPMODE_QUERYSYSTEMTIME
:
1857 * Low-res, but synchronized
1858 * with the OS clock.
1860 p
->tstamp_type_list
[num_ts_types
] =
1861 PCAP_TSTAMP_HOST_LOWPREC
;
1865 case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE
:
1867 * High-res, and synchronized
1868 * with the OS clock.
1870 p
->tstamp_type_list
[num_ts_types
] =
1871 PCAP_TSTAMP_HOST_HIPREC
;
1877 * Unknown, so we can't
1883 p
->tstamp_type_count
= num_ts_types
;
1886 /* Clean up temporary allocations */
1887 if (device_copy
!= NULL
) {
1890 if (modes
!= NULL
&& modes
!= ts_modes
) {
1893 if (adapter
!= NULL
) {
1894 PacketCloseAdapter(adapter
);
1899 #else /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1901 get_ts_types(const char *device _U_
, pcap_t
*p _U_
, char *ebuf _U_
)
1904 * Nothing to fetch, so it always "succeeds".
1908 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1911 pcapint_create_interface(const char *device _U_
, char *ebuf
)
1915 p
= PCAP_CREATE_COMMON(ebuf
, struct pcap_win
);
1919 p
->activate_op
= pcap_activate_npf
;
1920 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1922 if (get_ts_types(device
, p
, ebuf
) == -1) {
1930 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1932 struct pcap_win
*pw
= p
->priv
;
1934 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1936 * Kernel filter not installed.
1938 * XXX - we don't know whether this failed because:
1940 * the kernel rejected the filter program as invalid,
1941 * in which case we should fall back on userland
1944 * the kernel rejected the filter program as too big,
1945 * in which case we should again fall back on
1946 * userland filtering;
1948 * there was some other problem, in which case we
1949 * should probably report an error.
1951 * For NPF devices, the Win32 status will be
1952 * STATUS_INVALID_DEVICE_REQUEST for invalid
1953 * filters, but I don't know what it'd be for
1954 * other problems, and for some other devices
1955 * it might not be set at all.
1957 * So we just fall back on userland filtering in
1962 * pcapint_install_bpf_program() validates the program.
1964 * XXX - what if we already have a filter in the kernel?
1966 if (pcapint_install_bpf_program(p
, fp
) < 0)
1968 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1975 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1978 * Discard any previously-received packets, as they might have
1979 * passed whatever filter was formerly in effect, but might
1980 * not pass this filter (BIOCSETF discards packets buffered
1981 * in the kernel, so you can lose packets in any case).
1988 * We filter at user level, since the kernel driver doesn't process the packets
1991 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1995 pcapint_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1999 /* Install a user level filter */
2000 if (pcapint_install_bpf_program(p
, fp
) < 0)
2007 pcap_getnonblock_npf(pcap_t
*p
)
2009 struct pcap_win
*pw
= p
->priv
;
2012 * XXX - if there were a PacketGetReadTimeout() call, we
2013 * would use it, and return 1 if the timeout is -1
2016 return (pw
->nonblock
);
2020 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
2022 struct pcap_win
*pw
= p
->priv
;
2027 * Set the packet buffer timeout to -1 for non-blocking
2033 * Restore the timeout set when the device was opened.
2034 * (Note that this may be -1, in which case we're not
2035 * really leaving non-blocking mode. However, although
2036 * the timeout argument to pcap_set_timeout() and
2037 * pcap_open_live() is an int, you're not supposed to
2038 * supply a negative value, so that "shouldn't happen".)
2040 newtimeout
= p
->opt
.timeout
;
2042 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
2043 pcapint_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
2044 GetLastError(), "PacketSetReadTimeout");
2047 pw
->nonblock
= (newtimeout
== -1);
2052 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
2053 const char *description
, char *errbuf
)
2056 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2060 if_addr_size
= MAX_NETWORK_ADDRESSES
;
2063 * Add an entry for this interface, with no addresses.
2065 curdev
= pcapint_add_dev(devlistp
, name
, flags
, description
, errbuf
);
2066 if (curdev
== NULL
) {
2074 * Get the list of addresses for the interface.
2076 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
2080 * We don't return an error, because this can happen with
2081 * NdisWan interfaces, and we want to supply them even
2082 * if we can't supply their addresses.
2084 * We return an entry with an empty address list.
2090 * Now add the addresses.
2092 while (if_addr_size
-- > 0) {
2094 * "curdev" is an entry for this interface; add an entry for
2095 * this address to its list of addresses.
2097 res
= pcapint_add_addr_to_dev(curdev
,
2098 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
2099 sizeof (struct sockaddr_storage
),
2100 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
2101 sizeof (struct sockaddr_storage
),
2102 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
2103 sizeof (struct sockaddr_storage
),
2119 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
2125 NDIS_HARDWARE_STATUS hardware_status
;
2126 #ifdef OID_GEN_PHYSICAL_MEDIUM
2127 NDIS_PHYSICAL_MEDIUM phys_medium
;
2128 bpf_u_int32 gen_physical_medium_oids
[] = {
2129 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
2130 OID_GEN_PHYSICAL_MEDIUM_EX
,
2132 OID_GEN_PHYSICAL_MEDIUM
2134 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
2136 #endif /* OID_GEN_PHYSICAL_MEDIUM */
2137 #ifdef OID_GEN_LINK_STATE
2138 NDIS_LINK_STATE link_state
;
2142 if (*flags
& PCAP_IF_LOOPBACK
) {
2144 * Loopback interface, so the connection status doesn't
2145 * apply. and it's not wireless (or wired, for that
2146 * matter...). We presume it's up and running.
2148 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2153 * We need to open the adapter to get this information.
2155 * XXX - PacketOpenAdapter() takes a non-const pointer
2156 * as an argument, so we make a copy of the argument and
2159 name_copy
= strdup(name
);
2160 adapter
= PacketOpenAdapter(name_copy
);
2162 if (adapter
== NULL
) {
2164 * Give up; if they try to open this device, it'll fail.
2169 #ifdef HAVE_AIRPCAP_API
2171 * Airpcap.sys do not support the below 'OID_GEN_x' values.
2172 * Just set these flags (and none of the '*flags' entered with).
2174 if (PacketGetAirPcapHandle(adapter
)) {
2176 * Must be "up" and "running" if the above if succeeded.
2178 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
2181 * An airpcap device is a wireless device (duh!)
2183 *flags
|= PCAP_IF_WIRELESS
;
2186 * A "network association state" makes no sense for airpcap.
2188 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
2189 PacketCloseAdapter(adapter
);
2195 * Get the hardware status, and derive "up" and "running" from
2198 len
= sizeof (hardware_status
);
2199 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
2200 &hardware_status
, &len
, errbuf
);
2202 switch (hardware_status
) {
2204 case NdisHardwareStatusReady
:
2206 * "Available and capable of sending and receiving
2207 * data over the wire", so up and running.
2209 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
2212 case NdisHardwareStatusInitializing
:
2213 case NdisHardwareStatusReset
:
2215 * "Initializing" or "Resetting", so up, but
2218 *flags
|= PCAP_IF_UP
;
2221 case NdisHardwareStatusClosing
:
2222 case NdisHardwareStatusNotReady
:
2224 * "Closing" or "Not ready", so neither up nor
2237 * Can't get the hardware status, so assume both up and
2240 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
2244 * Get the network type.
2246 #ifdef OID_GEN_PHYSICAL_MEDIUM
2248 * Try the OIDs we have for this, in order.
2250 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
2251 len
= sizeof (phys_medium
);
2252 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
2253 &phys_medium
, &len
, errbuf
);
2261 * Failed. We can't determine whether it failed
2262 * because that particular OID isn't supported
2263 * or because some other problem occurred, so we
2264 * just drive on and try the next OID.
2269 * We got the physical medium.
2271 * XXX - we might want to check for NdisPhysicalMediumWiMax
2272 * and NdisPhysicalMediumNative802_15_4 being
2273 * part of the enum, and check for those in the "wireless"
2276 DIAG_OFF_ENUM_SWITCH
2277 switch (phys_medium
) {
2279 case NdisPhysicalMediumWirelessLan
:
2280 case NdisPhysicalMediumWirelessWan
:
2281 case NdisPhysicalMediumNative802_11
:
2282 case NdisPhysicalMediumBluetooth
:
2283 case NdisPhysicalMediumUWB
:
2284 case NdisPhysicalMediumIrda
:
2288 *flags
|= PCAP_IF_WIRELESS
;
2293 * Not wireless or unknown
2302 * Get the connection status.
2304 #ifdef OID_GEN_LINK_STATE
2305 len
= sizeof(link_state
);
2306 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
2310 * NOTE: this also gives us the receive and transmit
2313 switch (link_state
.MediaConnectState
) {
2315 case MediaConnectStateConnected
:
2319 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2322 case MediaConnectStateDisconnected
:
2324 * It's disconnected.
2326 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2329 case MediaConnectStateUnknown
:
2332 * It's unknown whether it's connected or not.
2339 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2345 * OK, OID_GEN_LINK_STATE didn't work, try
2346 * OID_GEN_MEDIA_CONNECT_STATUS.
2348 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
2349 &connect_status
, &len
, errbuf
);
2351 switch (connect_status
) {
2353 case NdisMediaStateConnected
:
2357 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
2360 case NdisMediaStateDisconnected
:
2362 * It's disconnected.
2364 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
2369 PacketCloseAdapter(adapter
);
2374 pcapint_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
2383 * Find out how big a buffer we need.
2385 * This call should always return FALSE; if the error is
2386 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2387 * the size of the buffer we need, otherwise there's a
2388 * problem, and NameLength should be set to 0.
2390 * It shouldn't require NameLength to be set, but,
2391 * at least as of WinPcap 4.1.3, it checks whether
2392 * NameLength is big enough before it checks for a
2393 * NULL buffer argument, so, while it'll still do
2394 * the right thing if NameLength is uninitialized and
2395 * whatever junk happens to be there is big enough
2396 * (because the pointer argument will be null), it's
2397 * still reading an uninitialized variable.
2400 if (!PacketGetAdapterNames(NULL
, &NameLength
))
2402 DWORD last_error
= GetLastError();
2404 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
2406 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2407 last_error
, "PacketGetAdapterNames");
2412 if (NameLength
<= 0)
2414 AdaptersName
= (char*) malloc(NameLength
);
2415 if (AdaptersName
== NULL
)
2417 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
2421 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
2422 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2423 GetLastError(), "PacketGetAdapterNames");
2429 * "PacketGetAdapterNames()" returned a list of
2430 * null-terminated ASCII interface name strings,
2431 * terminated by a null string, followed by a list
2432 * of null-terminated ASCII interface description
2433 * strings, terminated by a null string.
2434 * This means there are two ASCII nulls at the end
2435 * of the first list.
2437 * Find the end of the first list; that's the
2438 * beginning of the second list.
2440 desc
= &AdaptersName
[0];
2441 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
2445 * Found it - "desc" points to the first of the two
2446 * nulls at the end of the list of names, so the
2447 * first byte of the list of descriptions is two bytes
2453 * Loop over the elements in the first list.
2455 name
= &AdaptersName
[0];
2456 while (*name
!= '\0') {
2457 bpf_u_int32 flags
= 0;
2459 #ifdef HAVE_AIRPCAP_API
2461 * Is this an AirPcap device?
2462 * If so, ignore it; it'll get added later, by the
2465 if (device_is_airpcap(name
, errbuf
) == 1) {
2466 name
+= strlen(name
) + 1;
2467 desc
+= strlen(desc
) + 1;
2472 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2474 * Is this a loopback interface?
2476 if (PacketIsLoopbackAdapter(name
)) {
2478 flags
|= PCAP_IF_LOOPBACK
;
2482 * Get additional flags.
2484 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
2493 * Add an entry for this interface.
2495 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
2503 name
+= strlen(name
) + 1;
2504 desc
+= strlen(desc
) + 1;
2512 * Return the name of a network interface attached to the system, or NULL
2513 * if none can be found. The interface must be configured up; the
2514 * lowest unit number is preferred; loopback is ignored.
2516 * In the best of all possible worlds, this would be the same as on
2517 * UN*X, but there may be software that expects this to return a
2518 * full list of devices after the first device.
2520 #define ADAPTERSNAME_LEN 8192
2522 pcap_lookupdev(char *errbuf
)
2525 DWORD dwWindowsMajorVersion
;
2528 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2529 * it may return UTF-16 strings, for backwards-compatibility
2530 * reasons, and we're also disabling the hack to make that work,
2531 * for not-going-past-the-end-of-a-string reasons, and 2) we
2532 * want its behavior to be consistent.
2534 * In addition, it's not thread-safe, so we've marked it as
2537 if (pcapint_new_api
) {
2538 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2539 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2543 /* disable MSVC's GetVersion() deprecated warning here */
2544 DIAG_OFF_DEPRECATION
2545 dwVersion
= GetVersion(); /* get the OS version */
2547 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
2549 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
2551 * Windows 95, 98, ME.
2553 ULONG NameLength
= ADAPTERSNAME_LEN
;
2554 static char AdaptersName
[ADAPTERSNAME_LEN
];
2556 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
2557 return (AdaptersName
);
2562 * Windows NT (NT 4.0 and later).
2563 * Convert the names to Unicode for backward compatibility.
2565 ULONG NameLength
= ADAPTERSNAME_LEN
;
2566 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
2567 size_t BufferSpaceLeft
;
2572 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
2575 if(TAdaptersName
== NULL
)
2577 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
2581 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
2583 pcapint_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2584 GetLastError(), "PacketGetAdapterNames");
2585 free(TAdaptersName
);
2590 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
2591 tAstr
= (char*)TAdaptersName
;
2592 Unameptr
= AdaptersName
;
2595 * Convert the device names to Unicode into AdapterName.
2599 * Length of the name, including the terminating
2602 namelen
= strlen(tAstr
) + 1;
2605 * Do we have room for the name in the Unicode
2608 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
2614 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
2617 * Copy the name, converting ASCII to Unicode.
2618 * namelen includes the NUL, so we copy it as
2621 for (i
= 0; i
< namelen
; i
++)
2622 *Unameptr
++ = *tAstr
++;
2625 * Count this adapter.
2628 } while (namelen
!= 1);
2631 * Copy the descriptions, but don't convert them from
2634 Adescptr
= (char *)Unameptr
;
2639 desclen
= strlen(tAstr
) + 1;
2642 * Do we have room for the name in the Unicode
2645 if (BufferSpaceLeft
< desclen
) {
2653 * Just copy the ASCII string.
2654 * namelen includes the NUL, so we copy it as
2657 memcpy(Adescptr
, tAstr
, desclen
);
2658 Adescptr
+= desclen
;
2660 BufferSpaceLeft
-= desclen
;
2664 free(TAdaptersName
);
2665 return (char *)(AdaptersName
);
2670 * We can't use the same code that we use on UN*X, as that's doing
2671 * UN*X-specific calls.
2673 * We don't just fetch the entire list of devices, search for the
2674 * particular device, and use its first IPv4 address, as that's too
2675 * much work to get just one device's netmask.
2678 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2682 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2683 * in order to skip non IPv4 (i.e. IPv6 addresses)
2685 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2686 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2687 struct sockaddr_in
*t_addr
;
2690 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2695 for(i
= 0; i
< if_addr_size
; i
++)
2697 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2699 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2700 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2701 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2702 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2714 static const char *pcap_lib_version_string
;
2716 #ifdef HAVE_VERSION_H
2718 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2719 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2722 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2723 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2724 * for the packet.dll version number as well.)
2726 #include "../../version.h"
2728 static const char pcap_version_string
[] =
2729 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2732 pcap_lib_version(void)
2734 if (pcap_lib_version_string
== NULL
) {
2736 * Generate the version string.
2738 const char *packet_version_string
= PacketGetVersion();
2740 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2742 * WinPcap/Npcap version string and packet.dll version
2743 * string are the same; just report the WinPcap/Npcap
2746 pcap_lib_version_string
= pcap_version_string
;
2749 * WinPcap/Npcap version string and packet.dll version
2750 * string are different; that shouldn't be the
2751 * case (the two libraries should come from the
2752 * same version of WinPcap/Npcap), so we report both
2755 char *full_pcap_version_string
;
2757 if (pcapint_asprintf(&full_pcap_version_string
,
2758 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
,
2759 packet_version_string
) != -1) {
2761 pcap_lib_version_string
= full_pcap_version_string
;
2765 return (pcap_lib_version_string
);
2768 #else /* HAVE_VERSION_H */
2771 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2775 pcap_lib_version(void)
2777 if (pcap_lib_version_string
== NULL
) {
2779 * Generate the version string. Report the packet.dll
2782 char *full_pcap_version_string
;
2784 if (pcapint_asprintf(&full_pcap_version_string
,
2785 PCAP_VERSION_STRING
" (packet.dll version %s)",
2786 PacketGetVersion()) != -1) {
2788 pcap_lib_version_string
= full_pcap_version_string
;
2791 return (pcap_lib_version_string
);
2793 #endif /* HAVE_VERSION_H */