2 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2010 CACE Technologies, Davis (California)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the Politecnico di Torino, CACE Technologies
16 * nor the names of its contributors may be used to endorse or promote
17 * products derived from this software without specific prior written
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
45 * XXX - Packet32.h defines bpf_program, so we can't include
46 * <pcap/bpf.h>, which also defines it; that's why we define
47 * PCAP_DONT_INCLUDE_PCAP_BPF_H,
49 * However, no header in the WinPcap or Npcap SDKs defines the
50 * macros for BPF code, so we have to define them ourselves.
55 /* Old-school MinGW have these headers in a different place.
57 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
58 #include <ddk/ntddndis.h>
61 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
67 #endif /* HAVE_DAG_API */
69 #include "diag-control.h"
71 #include "pcap-airpcap.h"
73 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
74 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
75 static int pcap_getnonblock_npf(pcap_t
*);
76 static int pcap_setnonblock_npf(pcap_t
*, int);
78 /*dimension of the buffer in the pcap_t structure*/
79 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
81 /*dimension of the buffer in the kernel driver NPF */
82 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
84 /* Equivalent to ntohs(), but a lot faster under Windows */
85 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
88 * Private data for capturing on WinPcap/Npcap devices.
91 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
93 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
94 int filtering_in_kernel
; /* using kernel filter */
97 int dag_fcs_bits
; /* Number of checksum bits from link layer */
101 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
102 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
107 * Define stub versions of the monitor-mode support routines if this
108 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
111 #ifndef HAVE_NPCAP_PACKET_API
113 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
116 * We don't support monitor mode.
122 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
125 * This should never be called, as PacketIsMonitorModeSupported()
126 * will return 0, meaning "we don't support monitor mode, so
127 * don't try to turn it on or off".
133 PacketGetMonitorMode(PCHAR AdapterName _U_
)
136 * This should fail, so that pcap_activate_npf() returns
137 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
145 * Sigh. PacketRequest() will have made a DeviceIoControl()
146 * call to the NPF driver to perform the OID request, with a
147 * BIOCQUERYOID ioctl. The kernel code should get back one
148 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
149 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
150 * supported by the OS or the driver, but that doesn't seem
151 * to make it to the caller of PacketRequest() in a
154 #define NDIS_STATUS_INVALID_OID 0xc0010017
155 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
156 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
159 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
162 PACKET_OID_DATA
*oid_data_arg
;
165 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
166 * It should be big enough to hold "*lenp" bytes of data; it
167 * will actually be slightly larger, as PACKET_OID_DATA has a
168 * 1-byte data array at the end, standing in for the variable-length
169 * data that's actually there.
171 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
172 if (oid_data_arg
== NULL
) {
173 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
174 "Couldn't allocate argument buffer for PacketRequest");
179 * No need to copy the data - we're doing a fetch.
181 oid_data_arg
->Oid
= oid
;
182 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
183 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
184 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
185 GetLastError(), "Error calling PacketRequest");
191 * Get the length actually supplied.
193 *lenp
= oid_data_arg
->Length
;
196 * Copy back the data we fetched.
198 memcpy(data
, oid_data_arg
->Data
, *lenp
);
204 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
206 struct pcap_win
*pw
= p
->priv
;
207 struct bpf_stat bstats
;
210 * Try to get statistics.
212 * (Please note - "struct pcap_stat" is *not* the same as
213 * WinPcap's "struct bpf_stat". It might currently have the
214 * same layout, but let's not cheat.
216 * Note also that we don't fill in ps_capt, as we might have
217 * been called by code compiled against an earlier version of
218 * WinPcap that didn't have ps_capt, in which case filling it
219 * in would stomp on whatever comes after the structure passed
222 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
223 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
224 GetLastError(), "PacketGetStats error");
227 ps
->ps_recv
= bstats
.bs_recv
;
228 ps
->ps_drop
= bstats
.bs_drop
;
231 * XXX - PacketGetStats() doesn't fill this in, so we just
235 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
244 * Win32-only routine for getting statistics.
246 * This way is definitely safer than passing the pcap_stat * from the userland.
247 * In fact, there could happen than the user allocates a variable which is not
248 * big enough for the new structure, and the library will write in a zone
249 * which is not allocated to this variable.
251 * In this way, we're pretty sure we are writing on memory allocated to this
254 * XXX - but this is the wrong way to handle statistics. Instead, we should
255 * have an API that returns data in a form like the Options section of a
256 * pcapng Interface Statistics Block:
258 * 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
260 * which would let us add new statistics straightforwardly and indicate which
261 * statistics we are and are *not* providing, rather than having to provide
262 * possibly-bogus values for statistics we can't provide.
264 static struct pcap_stat
*
265 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
267 struct pcap_win
*pw
= p
->priv
;
268 struct bpf_stat bstats
;
270 *pcap_stat_size
= sizeof (p
->stat
);
273 * Try to get statistics.
275 * (Please note - "struct pcap_stat" is *not* the same as
276 * WinPcap's "struct bpf_stat". It might currently have the
277 * same layout, but let's not cheat.)
279 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
280 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
281 GetLastError(), "PacketGetStatsEx error");
284 p
->stat
.ps_recv
= bstats
.bs_recv
;
285 p
->stat
.ps_drop
= bstats
.bs_drop
;
286 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
288 * Just in case this is ever compiled for a target other than
289 * Windows, which is somewhere between extemely unlikely and
293 p
->stat
.ps_capt
= bstats
.bs_capt
;
298 /* Set the dimension of the kernel-level capture buffer */
300 pcap_setbuff_npf(pcap_t
*p
, int dim
)
302 struct pcap_win
*pw
= p
->priv
;
304 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
306 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
312 /* Set the driver working mode */
314 pcap_setmode_npf(pcap_t
*p
, int mode
)
316 struct pcap_win
*pw
= p
->priv
;
318 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
320 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
327 /*set the minimum amount of data that will release a read call*/
329 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
331 struct pcap_win
*pw
= p
->priv
;
333 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
335 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
342 pcap_getevent_npf(pcap_t
*p
)
344 struct pcap_win
*pw
= p
->priv
;
346 return (PacketGetReadEvent(pw
->adapter
));
350 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
352 struct pcap_win
*pw
= p
->priv
;
354 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
358 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
361 struct pcap_win
*pw
= p
->priv
;
362 PACKET_OID_DATA
*oid_data_arg
;
365 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
366 * It should be big enough to hold "*lenp" bytes of data; it
367 * will actually be slightly larger, as PACKET_OID_DATA has a
368 * 1-byte data array at the end, standing in for the variable-length
369 * data that's actually there.
371 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
372 if (oid_data_arg
== NULL
) {
373 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
374 "Couldn't allocate argument buffer for PacketRequest");
378 oid_data_arg
->Oid
= oid
;
379 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
380 memcpy(oid_data_arg
->Data
, data
, *lenp
);
381 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
382 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
383 GetLastError(), "Error calling PacketRequest");
389 * Get the length actually copied.
391 *lenp
= oid_data_arg
->Length
;
394 * No need to copy the data - we're doing a set.
401 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
403 struct pcap_win
*pw
= p
->priv
;
406 res
= PacketSendPackets(pw
->adapter
,
411 if(res
!= queue
->len
){
412 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
413 GetLastError(), "Error queueing packets");
420 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
422 unsigned char *new_buff
;
425 /* Bogus parameter */
426 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
427 "Error: invalid size %d",size
);
431 /* Allocate the buffer */
432 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
435 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
436 "Error: not enough memory");
449 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
451 struct pcap_win
*pw
= p
->priv
;
454 /* Set the packet driver in dump mode */
455 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
457 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
458 "Error setting dump mode");
462 /* Set the name of the dump file */
463 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
465 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
466 "Error setting kernel dump file name");
470 /* Set the limits of the dump file */
471 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
473 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
474 "Error setting dump limit");
482 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
484 struct pcap_win
*pw
= p
->priv
;
486 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
489 #ifdef HAVE_AIRPCAP_API
490 static PAirpcapHandle
491 pcap_get_airpcap_handle_npf(pcap_t
*p
)
493 struct pcap_win
*pw
= p
->priv
;
495 return (PacketGetAirPcapHandle(pw
->adapter
));
497 #else /* HAVE_AIRPCAP_API */
498 static PAirpcapHandle
499 pcap_get_airpcap_handle_npf(pcap_t
*p _U_
)
503 #endif /* HAVE_AIRPCAP_API */
506 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
511 register u_char
*bp
, *ep
;
513 struct pcap_win
*pw
= p
->priv
;
518 * Has "pcap_breakloop()" been called?
522 * Yes - clear the flag that indicates that it
523 * has, and return PCAP_ERROR_BREAK to indicate
524 * that we were told to break out of the loop.
527 return (PCAP_ERROR_BREAK
);
531 * Capture the packets.
533 * The PACKET structure had a bunch of extra stuff for
534 * Windows 9x/Me, but the only interesting data in it
535 * in the versions of Windows that we support is just
536 * a copy of p->buffer, a copy of p->buflen, and the
537 * actual number of bytes read returned from
538 * PacketReceivePacket(), none of which has to be
539 * retained from call to call, so we just keep one on
542 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
543 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
545 * Did the device go away?
546 * If so, the error we get is ERROR_GEN_FAILURE.
548 DWORD errcode
= GetLastError();
550 if (errcode
== ERROR_GEN_FAILURE
) {
552 * The device on which we're capturing
553 * went away, or it became unusable
554 * by NPF due to a suspend/resume.
556 * XXX - hopefully no other error
557 * conditions are indicated by this.
559 * XXX - we really should return an
560 * appropriate error for that, but
561 * pcap_dispatch() etc. aren't
562 * documented as having error returns
563 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
565 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
566 "The interface disappeared");
568 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
569 PCAP_ERRBUF_SIZE
, errcode
,
570 "PacketReceivePacket error");
575 cc
= Packet
.ulBytesReceived
;
583 * Loop through each packet.
585 #define bhp ((struct bpf_hdr *)bp)
589 register u_int caplen
, hdrlen
;
592 * Has "pcap_breakloop()" been called?
593 * If so, return immediately - if we haven't read any
594 * packets, clear the flag and return PCAP_ERROR_BREAK
595 * to indicate that we were told to break out of the loop,
596 * otherwise leave the flag set, so that the *next* call
597 * will break out of the loop without having read any
598 * packets, and return the number of packets we've
604 return (PCAP_ERROR_BREAK
);
607 p
->cc
= (int) (ep
- bp
);
614 caplen
= bhp
->bh_caplen
;
615 hdrlen
= bhp
->bh_hdrlen
;
619 * Short-circuit evaluation: if using BPF filter
620 * in kernel, no need to do it now - we already know
621 * the packet passed the filter.
623 * XXX - pcap_filter() should always return TRUE if
624 * handed a null pointer for the program, but it might
625 * just try to "run" the filter, so we check here.
627 if (pw
->filtering_in_kernel
||
628 p
->fcode
.bf_insns
== NULL
||
629 pcap_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
631 switch (p
->rmt_samp
.method
) {
633 case PCAP_SAMP_1_EVERY_N
:
634 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
636 /* Discard all packets that are not '1 out of N' */
637 if (pw
->samp_npkt
!= 0) {
638 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
643 case PCAP_SAMP_FIRST_AFTER_N_MS
:
645 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
648 * Check if the timestamp of the arrived
649 * packet is smaller than our target time.
651 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
652 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
653 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
658 * The arrived packet is suitable for being
659 * delivered to our caller, so let's update
662 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
663 if (pw
->samp_time
.tv_usec
> 1000000) {
664 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
665 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
669 #endif /* ENABLE_REMOTE */
672 * XXX A bpf_hdr matches a pcap_pkthdr.
674 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
675 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
676 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
678 p
->cc
= (int) (ep
- bp
);
685 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
695 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
697 struct pcap_win
*pw
= p
->priv
;
700 int packet_len
= 0, caplen
= 0;
701 struct pcap_pkthdr pcap_header
;
704 dag_record_t
*header
;
705 unsigned erf_record_len
;
709 unsigned dfp
= pw
->adapter
->DagFastProcess
;
712 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
715 * Get new packets from the network.
717 * The PACKET structure had a bunch of extra stuff for
718 * Windows 9x/Me, but the only interesting data in it
719 * in the versions of Windows that we support is just
720 * a copy of p->buffer, a copy of p->buflen, and the
721 * actual number of bytes read returned from
722 * PacketReceivePacket(), none of which has to be
723 * retained from call to call, so we just keep one on
726 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
727 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
728 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
732 cc
= Packet
.ulBytesReceived
;
734 /* The timeout has expired but we no packets arrived */
736 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
739 header
= (dag_record_t
*)p
->bp
;
741 endofbuf
= (char*)header
+ cc
;
744 * Cycle through the packets
748 erf_record_len
= SWAPS(header
->rlen
);
749 if((char*)header
+ erf_record_len
> endofbuf
)
752 /* Increase the number of captured packets */
755 /* Find the beginning of the packet */
756 dp
= ((u_char
*)header
) + dag_record_size
;
758 /* Determine actual packet len */
762 packet_len
= ATM_SNAPLEN
;
763 caplen
= ATM_SNAPLEN
;
769 swt
= SWAPS(header
->wlen
);
770 packet_len
= swt
- (pw
->dag_fcs_bits
);
771 caplen
= erf_record_len
- dag_record_size
- 2;
772 if (caplen
> packet_len
)
781 swt
= SWAPS(header
->wlen
);
782 packet_len
= swt
- (pw
->dag_fcs_bits
);
783 caplen
= erf_record_len
- dag_record_size
;
784 if (caplen
> packet_len
)
792 if(caplen
> p
->snapshot
)
793 caplen
= p
->snapshot
;
796 * Has "pcap_breakloop()" been called?
797 * If so, return immediately - if we haven't read any
798 * packets, clear the flag and return -2 to indicate
799 * that we were told to break out of the loop, otherwise
800 * leave the flag set, so that the *next* call will break
801 * out of the loop without having read any packets, and
802 * return the number of packets we've processed so far.
813 p
->bp
= (char*)header
;
814 p
->cc
= endofbuf
- (char*)header
;
821 /* convert between timestamp formats */
823 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
824 ts
= (ts
& 0xffffffffi
64) * 1000000;
825 ts
+= 0x80000000; /* rounding */
826 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
827 if (pcap_header
.ts
.tv_usec
>= 1000000) {
828 pcap_header
.ts
.tv_usec
-= 1000000;
829 pcap_header
.ts
.tv_sec
++;
833 /* No underlaying filtering system. We need to filter on our own */
834 if (p
->fcode
.bf_insns
)
836 if (pcap_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
838 /* Move to next packet */
839 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
844 /* Fill the header for the user suppplied callback function */
845 pcap_header
.caplen
= caplen
;
846 pcap_header
.len
= packet_len
;
848 /* Call the callback function */
849 (*callback
)(user
, &pcap_header
, dp
);
851 /* Move to next packet */
852 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
854 /* Stop if the number of packets requested by user has been reached*/
855 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
857 p
->bp
= (char*)header
;
858 p
->cc
= endofbuf
- (char*)header
;
862 while((u_char
*)header
< endofbuf
);
866 #endif /* HAVE_DAG_API */
868 /* Send a packet to the network */
870 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
872 struct pcap_win
*pw
= p
->priv
;
875 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
876 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
877 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
882 * We assume it all got sent if "PacketSendPacket()" succeeded.
883 * "pcap_inject()" is expected to return the number of bytes
890 pcap_cleanup_npf(pcap_t
*p
)
892 struct pcap_win
*pw
= p
->priv
;
894 if (pw
->adapter
!= NULL
) {
895 PacketCloseAdapter(pw
->adapter
);
898 if (pw
->rfmon_selfstart
)
900 PacketSetMonitorMode(p
->opt
.device
, 0);
902 pcap_cleanup_live_common(p
);
906 pcap_breakloop_npf(pcap_t
*p
)
908 pcap_breakloop_common(p
);
909 struct pcap_win
*pw
= p
->priv
;
911 /* XXX - what if this fails? */
912 SetEvent(PacketGetReadEvent(pw
->adapter
));
916 pcap_activate_npf(pcap_t
*p
)
918 struct pcap_win
*pw
= p
->priv
;
922 struct bpf_insn total_insn
;
923 struct bpf_program total_prog
;
927 * Monitor mode is supported on Windows Vista and later.
929 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
931 pw
->rfmon_selfstart
= 0;
935 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
937 pw
->rfmon_selfstart
= 0;
938 // Monitor mode is not supported.
941 return PCAP_ERROR_RFMON_NOTSUP
;
950 pw
->rfmon_selfstart
= 1;
955 /* Init Winsock if it hasn't already been initialized */
958 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
960 if (pw
->adapter
== NULL
)
962 DWORD errcode
= GetLastError();
965 * What error did we get when trying to open the adapter?
971 * There's no such device.
973 return (PCAP_ERROR_NO_SUCH_DEVICE
);
975 case ERROR_ACCESS_DENIED
:
977 * There is, but we don't have permission to
980 return (PCAP_ERROR_PERM_DENIED
);
984 * Unknown - report details.
986 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
987 errcode
, "Error opening adapter");
988 if (pw
->rfmon_selfstart
)
990 PacketSetMonitorMode(p
->opt
.device
, 0);
997 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
999 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1000 GetLastError(), "Cannot determine the network type");
1004 /*Set the linktype*/
1005 switch (type
.LinkType
)
1008 p
->linktype
= DLT_EN10MB
;
1011 case NdisMedium802_3
:
1012 p
->linktype
= DLT_EN10MB
;
1014 * This is (presumably) a real Ethernet capture; give it a
1015 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1016 * that an application can let you choose it, in case you're
1017 * capturing DOCSIS traffic that a Cisco Cable Modem
1018 * Termination System is putting out onto an Ethernet (it
1019 * doesn't put an Ethernet header onto the wire, it puts raw
1020 * DOCSIS frames out on the wire inside the low-level
1021 * Ethernet framing).
1023 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1025 * If that fails, just leave the list empty.
1027 if (p
->dlt_list
!= NULL
) {
1028 p
->dlt_list
[0] = DLT_EN10MB
;
1029 p
->dlt_list
[1] = DLT_DOCSIS
;
1034 case NdisMediumFddi
:
1035 p
->linktype
= DLT_FDDI
;
1038 case NdisMedium802_5
:
1039 p
->linktype
= DLT_IEEE802
;
1042 case NdisMediumArcnetRaw
:
1043 p
->linktype
= DLT_ARCNET
;
1046 case NdisMediumArcnet878_2
:
1047 p
->linktype
= DLT_ARCNET
;
1051 p
->linktype
= DLT_ATM_RFC1483
;
1054 case NdisMediumCHDLC
:
1055 p
->linktype
= DLT_CHDLC
;
1058 case NdisMediumPPPSerial
:
1059 p
->linktype
= DLT_PPP_SERIAL
;
1062 case NdisMediumNull
:
1063 p
->linktype
= DLT_NULL
;
1066 case NdisMediumBare80211
:
1067 p
->linktype
= DLT_IEEE802_11
;
1070 case NdisMediumRadio80211
:
1071 p
->linktype
= DLT_IEEE802_11_RADIO
;
1075 p
->linktype
= DLT_PPI
;
1078 case NdisMediumWirelessWan
:
1079 p
->linktype
= DLT_RAW
;
1084 * An unknown medium type is assumed to supply Ethernet
1085 * headers; if not, the user will have to report it,
1086 * so that the medium type and link-layer header type
1087 * can be determined. If we were to fail here, we
1088 * might get the link-layer type in the error, but
1089 * the user wouldn't get a capture, so we wouldn't
1090 * be able to determine the link-layer type; we report
1091 * a warning with the link-layer type, so at least
1092 * some programs will report the warning.
1094 p
->linktype
= DLT_EN10MB
;
1095 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1096 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1098 status
= PCAP_WARNING
;
1103 * Turn a negative snapshot value (invalid), a snapshot value of
1104 * 0 (unspecified), or a value bigger than the normal maximum
1105 * value, into the maximum allowed value.
1107 * If some application really *needs* a bigger snapshot
1108 * length, we should just increase MAXIMUM_SNAPLEN.
1110 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1111 p
->snapshot
= MAXIMUM_SNAPLEN
;
1113 /* Set promiscuous mode */
1117 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1119 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1125 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1126 * protocols and all packets indicated by the NIC" but if no protocol
1127 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1128 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1129 * capture incoming frames.
1131 if (PacketSetHwFilter(pw
->adapter
,
1132 NDIS_PACKET_TYPE_ALL_LOCAL
|
1133 NDIS_PACKET_TYPE_DIRECTED
|
1134 NDIS_PACKET_TYPE_BROADCAST
|
1135 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1137 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1142 /* Set the buffer size */
1143 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1145 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1148 * Traditional Adapter
1151 * If the buffer size wasn't explicitly set, default to
1152 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1154 if (p
->opt
.buffer_size
== 0)
1155 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1157 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1159 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1163 p
->buffer
= malloc(p
->bufsize
);
1164 if (p
->buffer
== NULL
)
1166 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1171 if (p
->opt
.immediate
)
1173 /* tell the driver to copy the buffer as soon as data arrives */
1174 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1176 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1177 PCAP_ERRBUF_SIZE
, GetLastError(),
1178 "Error calling PacketSetMinToCopy");
1184 /* tell the driver to copy the buffer only if it contains at least 16K */
1185 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1187 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1188 PCAP_ERRBUF_SIZE
, GetLastError(),
1189 "Error calling PacketSetMinToCopy");
1199 * We have DAG support.
1208 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1209 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1210 strstr(_strlwr(p
->opt
.device
), "dag"));
1213 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1214 if(status
!= ERROR_SUCCESS
)
1217 status
= RegQueryValueEx(dagkey
,
1224 if(status
!= ERROR_SUCCESS
)
1229 RegCloseKey(dagkey
);
1234 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1236 /* Set the length of the FCS associated to any packet. This value
1237 * will be subtracted to the packet length */
1238 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1239 #else /* HAVE_DAG_API */
1244 #endif /* HAVE_DAG_API */
1248 * If there's no filter program installed, there's
1249 * no indication to the kernel of what the snapshot
1250 * length should be, so no snapshotting is done.
1252 * Therefore, when we open the device, we install
1253 * an "accept everything" filter with the specified
1256 total_insn
.code
= (u_short
)(BPF_RET
| BPF_K
);
1259 total_insn
.k
= p
->snapshot
;
1261 total_prog
.bf_len
= 1;
1262 total_prog
.bf_insns
= &total_insn
;
1263 if (!PacketSetBpf(pw
->adapter
, &total_prog
)) {
1264 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1265 GetLastError(), "PacketSetBpf");
1266 status
= PCAP_ERROR
;
1270 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1272 /* disable loopback capture if requested */
1273 if (p
->opt
.nocapture_local
)
1275 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1277 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1278 "Unable to disable the capture of loopback packets.");
1284 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1286 /* install dag specific handlers for read and setfilter */
1287 p
->read_op
= pcap_read_win32_dag
;
1288 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1292 #endif /* HAVE_DAG_API */
1293 /* install traditional npf handlers for read and setfilter */
1294 p
->read_op
= pcap_read_npf
;
1295 p
->setfilter_op
= pcap_setfilter_npf
;
1298 #endif /* HAVE_DAG_API */
1299 p
->setdirection_op
= NULL
; /* Not implemented. */
1300 /* XXX - can this be implemented on some versions of Windows? */
1301 p
->inject_op
= pcap_inject_npf
;
1302 p
->set_datalink_op
= NULL
; /* can't change data link type */
1303 p
->getnonblock_op
= pcap_getnonblock_npf
;
1304 p
->setnonblock_op
= pcap_setnonblock_npf
;
1305 p
->stats_op
= pcap_stats_npf
;
1306 p
->breakloop_op
= pcap_breakloop_npf
;
1307 p
->stats_ex_op
= pcap_stats_ex_npf
;
1308 p
->setbuff_op
= pcap_setbuff_npf
;
1309 p
->setmode_op
= pcap_setmode_npf
;
1310 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1311 p
->getevent_op
= pcap_getevent_npf
;
1312 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1313 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1314 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1315 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1316 p
->live_dump_op
= pcap_live_dump_npf
;
1317 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1318 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1319 p
->cleanup_op
= pcap_cleanup_npf
;
1322 * XXX - this is only done because WinPcap supported
1323 * pcap_fileno() returning the hFile HANDLE from the
1324 * ADAPTER structure. We make no general guarantees
1325 * that the caller can do anything useful with it.
1327 * (Not that we make any general guarantee of that
1328 * sort on UN*X, either, any more, given that not
1329 * all capture devices are regular OS network
1332 p
->handle
= pw
->adapter
->hFile
;
1336 pcap_cleanup_npf(p
);
1337 return (PCAP_ERROR
);
1341 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1344 pcap_can_set_rfmon_npf(pcap_t
*p
)
1346 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1350 pcap_create_interface(const char *device _U_
, char *ebuf
)
1354 p
= PCAP_CREATE_COMMON(ebuf
, struct pcap_win
);
1358 p
->activate_op
= pcap_activate_npf
;
1359 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1364 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1366 struct pcap_win
*pw
= p
->priv
;
1368 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1370 * Kernel filter not installed.
1372 * XXX - we don't know whether this failed because:
1374 * the kernel rejected the filter program as invalid,
1375 * in which case we should fall back on userland
1378 * the kernel rejected the filter program as too big,
1379 * in which case we should again fall back on
1380 * userland filtering;
1382 * there was some other problem, in which case we
1383 * should probably report an error.
1385 * For NPF devices, the Win32 status will be
1386 * STATUS_INVALID_DEVICE_REQUEST for invalid
1387 * filters, but I don't know what it'd be for
1388 * other problems, and for some other devices
1389 * it might not be set at all.
1391 * So we just fall back on userland filtering in
1396 * install_bpf_program() validates the program.
1398 * XXX - what if we already have a filter in the kernel?
1400 if (install_bpf_program(p
, fp
) < 0)
1402 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1409 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1412 * Discard any previously-received packets, as they might have
1413 * passed whatever filter was formerly in effect, but might
1414 * not pass this filter (BIOCSETF discards packets buffered
1415 * in the kernel, so you can lose packets in any case).
1422 * We filter at user level, since the kernel driver does't process the packets
1425 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1429 pcap_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1433 /* Install a user level filter */
1434 if (install_bpf_program(p
, fp
) < 0)
1441 pcap_getnonblock_npf(pcap_t
*p
)
1443 struct pcap_win
*pw
= p
->priv
;
1446 * XXX - if there were a PacketGetReadTimeout() call, we
1447 * would use it, and return 1 if the timeout is -1
1450 return (pw
->nonblock
);
1454 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1456 struct pcap_win
*pw
= p
->priv
;
1461 * Set the packet buffer timeout to -1 for non-blocking
1467 * Restore the timeout set when the device was opened.
1468 * (Note that this may be -1, in which case we're not
1469 * really leaving non-blocking mode. However, although
1470 * the timeout argument to pcap_set_timeout() and
1471 * pcap_open_live() is an int, you're not supposed to
1472 * supply a negative value, so that "shouldn't happen".)
1474 newtimeout
= p
->opt
.timeout
;
1476 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1477 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1478 GetLastError(), "PacketSetReadTimeout");
1481 pw
->nonblock
= (newtimeout
== -1);
1486 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1487 const char *description
, char *errbuf
)
1490 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1494 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1497 * Add an entry for this interface, with no addresses.
1499 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1500 if (curdev
== NULL
) {
1508 * Get the list of addresses for the interface.
1510 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1514 * We don't return an error, because this can happen with
1515 * NdisWan interfaces, and we want to supply them even
1516 * if we can't supply their addresses.
1518 * We return an entry with an empty address list.
1524 * Now add the addresses.
1526 while (if_addr_size
-- > 0) {
1528 * "curdev" is an entry for this interface; add an entry for
1529 * this address to its list of addresses.
1531 res
= add_addr_to_dev(curdev
,
1532 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1533 sizeof (struct sockaddr_storage
),
1534 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1535 sizeof (struct sockaddr_storage
),
1536 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1537 sizeof (struct sockaddr_storage
),
1553 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1559 NDIS_HARDWARE_STATUS hardware_status
;
1560 #ifdef OID_GEN_PHYSICAL_MEDIUM
1561 NDIS_PHYSICAL_MEDIUM phys_medium
;
1562 bpf_u_int32 gen_physical_medium_oids
[] = {
1563 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1564 OID_GEN_PHYSICAL_MEDIUM_EX
,
1566 OID_GEN_PHYSICAL_MEDIUM
1568 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1570 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1571 #ifdef OID_GEN_LINK_STATE
1572 NDIS_LINK_STATE link_state
;
1576 if (*flags
& PCAP_IF_LOOPBACK
) {
1578 * Loopback interface, so the connection status doesn't
1579 * apply. and it's not wireless (or wired, for that
1580 * matter...). We presume it's up and running.
1582 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1587 * We need to open the adapter to get this information.
1589 * XXX - PacketOpenAdapter() takes a non-const pointer
1590 * as an argument, so we make a copy of the argument and
1593 name_copy
= strdup(name
);
1594 adapter
= PacketOpenAdapter(name_copy
);
1596 if (adapter
== NULL
) {
1598 * Give up; if they try to open this device, it'll fail.
1603 #ifdef HAVE_AIRPCAP_API
1605 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1606 * Just set these flags (and none of the '*flags' entered with).
1608 if (PacketGetAirPcapHandle(adapter
)) {
1610 * Must be "up" and "running" if the above if succeeded.
1612 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1615 * An airpcap device is a wireless device (duh!)
1617 *flags
|= PCAP_IF_WIRELESS
;
1620 * A "network assosiation state" makes no sense for airpcap.
1622 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1623 PacketCloseAdapter(adapter
);
1629 * Get the hardware status, and derive "up" and "running" from
1632 len
= sizeof (hardware_status
);
1633 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1634 &hardware_status
, &len
, errbuf
);
1636 switch (hardware_status
) {
1638 case NdisHardwareStatusReady
:
1640 * "Available and capable of sending and receiving
1641 * data over the wire", so up and running.
1643 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1646 case NdisHardwareStatusInitializing
:
1647 case NdisHardwareStatusReset
:
1649 * "Initializing" or "Resetting", so up, but
1652 *flags
|= PCAP_IF_UP
;
1655 case NdisHardwareStatusClosing
:
1656 case NdisHardwareStatusNotReady
:
1658 * "Closing" or "Not ready", so neither up nor
1671 * Can't get the hardware status, so assume both up and
1674 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1678 * Get the network type.
1680 #ifdef OID_GEN_PHYSICAL_MEDIUM
1682 * Try the OIDs we have for this, in order.
1684 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1685 len
= sizeof (phys_medium
);
1686 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1687 &phys_medium
, &len
, errbuf
);
1695 * Failed. We can't determine whether it failed
1696 * because that particular OID isn't supported
1697 * or because some other problem occurred, so we
1698 * just drive on and try the next OID.
1703 * We got the physical medium.
1705 switch (phys_medium
) {
1707 case NdisPhysicalMediumWirelessLan
:
1708 case NdisPhysicalMediumWirelessWan
:
1709 case NdisPhysicalMediumNative802_11
:
1710 case NdisPhysicalMediumBluetooth
:
1711 case NdisPhysicalMediumUWB
:
1712 case NdisPhysicalMediumIrda
:
1716 *flags
|= PCAP_IF_WIRELESS
;
1729 * Get the connection status.
1731 #ifdef OID_GEN_LINK_STATE
1732 len
= sizeof(link_state
);
1733 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
1737 * NOTE: this also gives us the receive and transmit
1740 switch (link_state
.MediaConnectState
) {
1742 case MediaConnectStateConnected
:
1746 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1749 case MediaConnectStateDisconnected
:
1751 * It's disconnected.
1753 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1758 * It's unknown whether it's connected or not.
1765 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1771 * OK, OID_GEN_LINK_STATE didn't work, try
1772 * OID_GEN_MEDIA_CONNECT_STATUS.
1774 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1775 &connect_status
, &len
, errbuf
);
1777 switch (connect_status
) {
1779 case NdisMediaStateConnected
:
1783 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1786 case NdisMediaStateDisconnected
:
1788 * It's disconnected.
1790 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1795 PacketCloseAdapter(adapter
);
1800 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1809 * Find out how big a buffer we need.
1811 * This call should always return FALSE; if the error is
1812 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1813 * the size of the buffer we need, otherwise there's a
1814 * problem, and NameLength should be set to 0.
1816 * It shouldn't require NameLength to be set, but,
1817 * at least as of WinPcap 4.1.3, it checks whether
1818 * NameLength is big enough before it checks for a
1819 * NULL buffer argument, so, while it'll still do
1820 * the right thing if NameLength is uninitialized and
1821 * whatever junk happens to be there is big enough
1822 * (because the pointer argument will be null), it's
1823 * still reading an uninitialized variable.
1826 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1828 DWORD last_error
= GetLastError();
1830 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1832 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1833 last_error
, "PacketGetAdapterNames");
1838 if (NameLength
<= 0)
1840 AdaptersName
= (char*) malloc(NameLength
);
1841 if (AdaptersName
== NULL
)
1843 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1847 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1848 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1849 GetLastError(), "PacketGetAdapterNames");
1855 * "PacketGetAdapterNames()" returned a list of
1856 * null-terminated ASCII interface name strings,
1857 * terminated by a null string, followed by a list
1858 * of null-terminated ASCII interface description
1859 * strings, terminated by a null string.
1860 * This means there are two ASCII nulls at the end
1861 * of the first list.
1863 * Find the end of the first list; that's the
1864 * beginning of the second list.
1866 desc
= &AdaptersName
[0];
1867 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1871 * Found it - "desc" points to the first of the two
1872 * nulls at the end of the list of names, so the
1873 * first byte of the list of descriptions is two bytes
1879 * Loop over the elements in the first list.
1881 name
= &AdaptersName
[0];
1882 while (*name
!= '\0') {
1883 bpf_u_int32 flags
= 0;
1885 #ifdef HAVE_AIRPCAP_API
1887 * Is this an AirPcap device?
1888 * If so, ignore it; it'll get added later, by the
1891 if (device_is_airpcap(name
, errbuf
) == 1) {
1892 name
+= strlen(name
) + 1;
1893 desc
+= strlen(desc
) + 1;
1898 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1900 * Is this a loopback interface?
1902 if (PacketIsLoopbackAdapter(name
)) {
1904 flags
|= PCAP_IF_LOOPBACK
;
1908 * Get additional flags.
1910 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1919 * Add an entry for this interface.
1921 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1929 name
+= strlen(name
) + 1;
1930 desc
+= strlen(desc
) + 1;
1938 * Return the name of a network interface attached to the system, or NULL
1939 * if none can be found. The interface must be configured up; the
1940 * lowest unit number is preferred; loopback is ignored.
1942 * In the best of all possible worlds, this would be the same as on
1943 * UN*X, but there may be software that expects this to return a
1944 * full list of devices after the first device.
1946 #define ADAPTERSNAME_LEN 8192
1948 pcap_lookupdev(char *errbuf
)
1951 DWORD dwWindowsMajorVersion
;
1954 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1955 * it may return UTF-16 strings, for backwards-compatibility
1956 * reasons, and we're also disabling the hack to make that work,
1957 * for not-going-past-the-end-of-a-string reasons, and 2) we
1958 * want its behavior to be consistent.
1960 * In addition, it's not thread-safe, so we've marked it as
1964 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1965 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1969 /* disable MSVC's GetVersion() deprecated warning here */
1970 DIAG_OFF_DEPRECATION
1971 dwVersion
= GetVersion(); /* get the OS version */
1973 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1975 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1977 * Windows 95, 98, ME.
1979 ULONG NameLength
= ADAPTERSNAME_LEN
;
1980 static char AdaptersName
[ADAPTERSNAME_LEN
];
1982 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1983 return (AdaptersName
);
1988 * Windows NT (NT 4.0 and later).
1989 * Convert the names to Unicode for backward compatibility.
1991 ULONG NameLength
= ADAPTERSNAME_LEN
;
1992 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1993 size_t BufferSpaceLeft
;
1998 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
2001 if(TAdaptersName
== NULL
)
2003 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
2007 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
2009 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
2010 GetLastError(), "PacketGetAdapterNames");
2011 free(TAdaptersName
);
2016 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
2017 tAstr
= (char*)TAdaptersName
;
2018 Unameptr
= AdaptersName
;
2021 * Convert the device names to Unicode into AdapterName.
2025 * Length of the name, including the terminating
2028 namelen
= strlen(tAstr
) + 1;
2031 * Do we have room for the name in the Unicode
2034 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
2040 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
2043 * Copy the name, converting ASCII to Unicode.
2044 * namelen includes the NUL, so we copy it as
2047 for (i
= 0; i
< namelen
; i
++)
2048 *Unameptr
++ = *tAstr
++;
2051 * Count this adapter.
2054 } while (namelen
!= 1);
2057 * Copy the descriptions, but don't convert them from
2060 Adescptr
= (char *)Unameptr
;
2065 desclen
= strlen(tAstr
) + 1;
2068 * Do we have room for the name in the Unicode
2071 if (BufferSpaceLeft
< desclen
) {
2079 * Just copy the ASCII string.
2080 * namelen includes the NUL, so we copy it as
2083 memcpy(Adescptr
, tAstr
, desclen
);
2084 Adescptr
+= desclen
;
2086 BufferSpaceLeft
-= desclen
;
2090 free(TAdaptersName
);
2091 return (char *)(AdaptersName
);
2096 * We can't use the same code that we use on UN*X, as that's doing
2097 * UN*X-specific calls.
2099 * We don't just fetch the entire list of devices, search for the
2100 * particular device, and use its first IPv4 address, as that's too
2101 * much work to get just one device's netmask.
2104 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2108 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2109 * in order to skip non IPv4 (i.e. IPv6 addresses)
2111 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2112 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2113 struct sockaddr_in
*t_addr
;
2116 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2121 for(i
= 0; i
< if_addr_size
; i
++)
2123 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2125 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2126 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2127 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2128 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2140 static const char *pcap_lib_version_string
;
2142 #ifdef HAVE_VERSION_H
2144 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2145 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2148 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2149 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2150 * for the packet.dll version number as well.)
2152 #include "../../version.h"
2154 static const char pcap_version_string
[] =
2155 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2158 pcap_lib_version(void)
2160 if (pcap_lib_version_string
== NULL
) {
2162 * Generate the version string.
2164 const char *packet_version_string
= PacketGetVersion();
2166 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2168 * WinPcap/Npcap version string and packet.dll version
2169 * string are the same; just report the WinPcap/Npcap
2172 pcap_lib_version_string
= pcap_version_string
;
2175 * WinPcap/Npcap version string and packet.dll version
2176 * string are different; that shouldn't be the
2177 * case (the two libraries should come from the
2178 * same version of WinPcap/Npcap), so we report both
2181 char *full_pcap_version_string
;
2183 if (pcap_asprintf(&full_pcap_version_string
,
2184 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
,
2185 packet_version_string
) != -1) {
2187 pcap_lib_version_string
= full_pcap_version_string
;
2191 return (pcap_lib_version_string
);
2194 #else /* HAVE_VERSION_H */
2197 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2201 pcap_lib_version(void)
2203 if (pcap_lib_version_string
== NULL
) {
2205 * Generate the version string. Report the packet.dll
2208 char *full_pcap_version_string
;
2210 if (pcap_asprintf(&full_pcap_version_string
,
2211 PCAP_VERSION_STRING
" (packet.dll version %s)",
2212 PacketGetVersion()) != -1) {
2214 pcap_lib_version_string
= full_pcap_version_string
;
2217 return (pcap_lib_version_string
);
2219 #endif /* HAVE_VERSION_H */