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
43 * XXX - TEMPORARY TO FIGURE OUT WHY WE'RE NOT GETTING WARNINGS ABOUT
44 * ASSIGNMENT OF A POINTER TO CONST CHAR VALUE TO A POINTER TO CHAR
47 extern LPCSTR
PacketGetLPCSTR(void);
48 extern const char *PacketGetConstCharStar(void);
52 /* Old-school MinGW have these headers in a different place.
54 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
55 #include <ddk/ntddndis.h>
58 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
64 #endif /* HAVE_DAG_API */
66 #include "diag-control.h"
68 #include "pcap-airpcap.h"
70 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
71 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
72 static int pcap_getnonblock_npf(pcap_t
*);
73 static int pcap_setnonblock_npf(pcap_t
*, int);
75 /*dimension of the buffer in the pcap_t structure*/
76 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
78 /*dimension of the buffer in the kernel driver NPF */
79 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
81 /* Equivalent to ntohs(), but a lot faster under Windows */
82 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
85 * Private data for capturing on WinPcap/Npcap devices.
88 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
90 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
91 int filtering_in_kernel
; /* using kernel filter */
94 int dag_fcs_bits
; /* Number of checksum bits from link layer */
98 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
99 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
104 * Define stub versions of the monitor-mode support routines if this
105 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
108 #ifndef HAVE_NPCAP_PACKET_API
110 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
113 * We don't support monitor mode.
119 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
122 * This should never be called, as PacketIsMonitorModeSupported()
123 * will return 0, meaning "we don't support monitor mode, so
124 * don't try to turn it on or off".
130 PacketGetMonitorMode(PCHAR AdapterName _U_
)
133 * This should fail, so that pcap_activate_npf() returns
134 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
142 * Sigh. PacketRequest() will have made a DeviceIoControl()
143 * call to the NPF driver to perform the OID request, with a
144 * BIOCQUERYOID ioctl. The kernel code should get back one
145 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
146 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
147 * supported by the OS or the driver, but that doesn't seem
148 * to make it to the caller of PacketRequest() in a
151 #define NDIS_STATUS_INVALID_OID 0xc0010017
152 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
153 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
156 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
159 PACKET_OID_DATA
*oid_data_arg
;
162 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
163 * It should be big enough to hold "*lenp" bytes of data; it
164 * will actually be slightly larger, as PACKET_OID_DATA has a
165 * 1-byte data array at the end, standing in for the variable-length
166 * data that's actually there.
168 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
169 if (oid_data_arg
== NULL
) {
170 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
171 "Couldn't allocate argument buffer for PacketRequest");
176 * No need to copy the data - we're doing a fetch.
178 oid_data_arg
->Oid
= oid
;
179 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
180 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
181 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
182 GetLastError(), "Error calling PacketRequest");
188 * Get the length actually supplied.
190 *lenp
= oid_data_arg
->Length
;
193 * Copy back the data we fetched.
195 memcpy(data
, oid_data_arg
->Data
, *lenp
);
201 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
203 struct pcap_win
*pw
= p
->priv
;
204 struct bpf_stat bstats
;
207 * Try to get statistics.
209 * (Please note - "struct pcap_stat" is *not* the same as
210 * WinPcap's "struct bpf_stat". It might currently have the
211 * same layout, but let's not cheat.
213 * Note also that we don't fill in ps_capt, as we might have
214 * been called by code compiled against an earlier version of
215 * WinPcap that didn't have ps_capt, in which case filling it
216 * in would stomp on whatever comes after the structure passed
219 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
220 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
221 GetLastError(), "PacketGetStats error");
224 ps
->ps_recv
= bstats
.bs_recv
;
225 ps
->ps_drop
= bstats
.bs_drop
;
228 * XXX - PacketGetStats() doesn't fill this in, so we just
232 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
241 * Win32-only routine for getting statistics.
243 * This way is definitely safer than passing the pcap_stat * from the userland.
244 * In fact, there could happen than the user allocates a variable which is not
245 * big enough for the new structure, and the library will write in a zone
246 * which is not allocated to this variable.
248 * In this way, we're pretty sure we are writing on memory allocated to this
251 * XXX - but this is the wrong way to handle statistics. Instead, we should
252 * have an API that returns data in a form like the Options section of a
253 * pcapng Interface Statistics Block:
255 * 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
257 * which would let us add new statistics straightforwardly and indicate which
258 * statistics we are and are *not* providing, rather than having to provide
259 * possibly-bogus values for statistics we can't provide.
261 static struct pcap_stat
*
262 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
264 struct pcap_win
*pw
= p
->priv
;
265 struct bpf_stat bstats
;
267 *pcap_stat_size
= sizeof (p
->stat
);
270 * Try to get statistics.
272 * (Please note - "struct pcap_stat" is *not* the same as
273 * WinPcap's "struct bpf_stat". It might currently have the
274 * same layout, but let's not cheat.)
276 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
277 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
278 GetLastError(), "PacketGetStatsEx error");
281 p
->stat
.ps_recv
= bstats
.bs_recv
;
282 p
->stat
.ps_drop
= bstats
.bs_drop
;
283 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
285 * Just in case this is ever compiled for a target other than
286 * Windows, which is somewhere between extemely unlikely and
290 p
->stat
.ps_capt
= bstats
.bs_capt
;
295 /* Set the dimension of the kernel-level capture buffer */
297 pcap_setbuff_npf(pcap_t
*p
, int dim
)
299 struct pcap_win
*pw
= p
->priv
;
301 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
303 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
309 /* Set the driver working mode */
311 pcap_setmode_npf(pcap_t
*p
, int mode
)
313 struct pcap_win
*pw
= p
->priv
;
315 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
317 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
324 /*set the minimum amount of data that will release a read call*/
326 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
328 struct pcap_win
*pw
= p
->priv
;
330 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
332 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
339 pcap_getevent_npf(pcap_t
*p
)
341 struct pcap_win
*pw
= p
->priv
;
343 return (PacketGetReadEvent(pw
->adapter
));
347 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
349 struct pcap_win
*pw
= p
->priv
;
351 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
355 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
358 struct pcap_win
*pw
= p
->priv
;
359 PACKET_OID_DATA
*oid_data_arg
;
362 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
363 * It should be big enough to hold "*lenp" bytes of data; it
364 * will actually be slightly larger, as PACKET_OID_DATA has a
365 * 1-byte data array at the end, standing in for the variable-length
366 * data that's actually there.
368 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
369 if (oid_data_arg
== NULL
) {
370 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
371 "Couldn't allocate argument buffer for PacketRequest");
375 oid_data_arg
->Oid
= oid
;
376 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
377 memcpy(oid_data_arg
->Data
, data
, *lenp
);
378 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
379 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
380 GetLastError(), "Error calling PacketRequest");
386 * Get the length actually copied.
388 *lenp
= oid_data_arg
->Length
;
391 * No need to copy the data - we're doing a set.
398 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
400 struct pcap_win
*pw
= p
->priv
;
403 res
= PacketSendPackets(pw
->adapter
,
408 if(res
!= queue
->len
){
409 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
410 GetLastError(), "Error queueing packets");
417 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
419 unsigned char *new_buff
;
422 /* Bogus parameter */
423 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
424 "Error: invalid size %d",size
);
428 /* Allocate the buffer */
429 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
432 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
433 "Error: not enough memory");
446 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
448 struct pcap_win
*pw
= p
->priv
;
451 /* Set the packet driver in dump mode */
452 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
454 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
455 "Error setting dump mode");
459 /* Set the name of the dump file */
460 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
462 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
463 "Error setting kernel dump file name");
467 /* Set the limits of the dump file */
468 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
470 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
471 "Error setting dump limit");
479 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
481 struct pcap_win
*pw
= p
->priv
;
483 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
486 #ifdef HAVE_AIRPCAP_API
487 static PAirpcapHandle
488 pcap_get_airpcap_handle_npf(pcap_t
*p
)
490 struct pcap_win
*pw
= p
->priv
;
492 return (PacketGetAirPcapHandle(pw
->adapter
));
494 #else /* HAVE_AIRPCAP_API */
495 static PAirpcapHandle
496 pcap_get_airpcap_handle_npf(pcap_t
*p _U_
)
500 #endif /* HAVE_AIRPCAP_API */
503 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
508 register u_char
*bp
, *ep
;
510 struct pcap_win
*pw
= p
->priv
;
515 * Has "pcap_breakloop()" been called?
519 * Yes - clear the flag that indicates that it
520 * has, and return PCAP_ERROR_BREAK to indicate
521 * that we were told to break out of the loop.
524 return (PCAP_ERROR_BREAK
);
528 * Capture the packets.
530 * The PACKET structure had a bunch of extra stuff for
531 * Windows 9x/Me, but the only interesting data in it
532 * in the versions of Windows that we support is just
533 * a copy of p->buffer, a copy of p->buflen, and the
534 * actual number of bytes read returned from
535 * PacketReceivePacket(), none of which has to be
536 * retained from call to call, so we just keep one on
539 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
540 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
542 * Did the device go away?
543 * If so, the error we get is ERROR_GEN_FAILURE.
545 DWORD errcode
= GetLastError();
547 if (errcode
== ERROR_GEN_FAILURE
) {
549 * The device on which we're capturing
550 * went away, or it became unusable
551 * by NPF due to a suspend/resume.
553 * XXX - hopefully no other error
554 * conditions are indicated by this.
556 * XXX - we really should return an
557 * appropriate error for that, but
558 * pcap_dispatch() etc. aren't
559 * documented as having error returns
560 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
562 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
563 "The interface disappeared");
565 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
566 PCAP_ERRBUF_SIZE
, errcode
,
567 "PacketReceivePacket error");
572 cc
= Packet
.ulBytesReceived
;
580 * Loop through each packet.
582 #define bhp ((struct bpf_hdr *)bp)
586 register u_int caplen
, hdrlen
;
589 * Has "pcap_breakloop()" been called?
590 * If so, return immediately - if we haven't read any
591 * packets, clear the flag and return PCAP_ERROR_BREAK
592 * to indicate that we were told to break out of the loop,
593 * otherwise leave the flag set, so that the *next* call
594 * will break out of the loop without having read any
595 * packets, and return the number of packets we've
601 return (PCAP_ERROR_BREAK
);
604 p
->cc
= (int) (ep
- bp
);
611 caplen
= bhp
->bh_caplen
;
612 hdrlen
= bhp
->bh_hdrlen
;
616 * Short-circuit evaluation: if using BPF filter
617 * in kernel, no need to do it now - we already know
618 * the packet passed the filter.
620 * XXX - pcap_filter() should always return TRUE if
621 * handed a null pointer for the program, but it might
622 * just try to "run" the filter, so we check here.
624 if (pw
->filtering_in_kernel
||
625 p
->fcode
.bf_insns
== NULL
||
626 pcap_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
628 switch (p
->rmt_samp
.method
) {
630 case PCAP_SAMP_1_EVERY_N
:
631 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
633 /* Discard all packets that are not '1 out of N' */
634 if (pw
->samp_npkt
!= 0) {
635 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
640 case PCAP_SAMP_FIRST_AFTER_N_MS
:
642 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
645 * Check if the timestamp of the arrived
646 * packet is smaller than our target time.
648 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
649 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
650 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
655 * The arrived packet is suitable for being
656 * delivered to our caller, so let's update
659 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
660 if (pw
->samp_time
.tv_usec
> 1000000) {
661 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
662 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
666 #endif /* ENABLE_REMOTE */
669 * XXX A bpf_hdr matches a pcap_pkthdr.
671 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
672 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
673 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
675 p
->cc
= (int) (ep
- bp
);
682 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
692 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
694 struct pcap_win
*pw
= p
->priv
;
697 int packet_len
= 0, caplen
= 0;
698 struct pcap_pkthdr pcap_header
;
701 dag_record_t
*header
;
702 unsigned erf_record_len
;
706 unsigned dfp
= pw
->adapter
->DagFastProcess
;
709 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
712 * Get new packets from the network.
714 * The PACKET structure had a bunch of extra stuff for
715 * Windows 9x/Me, but the only interesting data in it
716 * in the versions of Windows that we support is just
717 * a copy of p->buffer, a copy of p->buflen, and the
718 * actual number of bytes read returned from
719 * PacketReceivePacket(), none of which has to be
720 * retained from call to call, so we just keep one on
723 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
724 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
725 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
729 cc
= Packet
.ulBytesReceived
;
731 /* The timeout has expired but we no packets arrived */
733 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
736 header
= (dag_record_t
*)p
->bp
;
738 endofbuf
= (char*)header
+ cc
;
741 * Cycle through the packets
745 erf_record_len
= SWAPS(header
->rlen
);
746 if((char*)header
+ erf_record_len
> endofbuf
)
749 /* Increase the number of captured packets */
752 /* Find the beginning of the packet */
753 dp
= ((u_char
*)header
) + dag_record_size
;
755 /* Determine actual packet len */
759 packet_len
= ATM_SNAPLEN
;
760 caplen
= ATM_SNAPLEN
;
766 swt
= SWAPS(header
->wlen
);
767 packet_len
= swt
- (pw
->dag_fcs_bits
);
768 caplen
= erf_record_len
- dag_record_size
- 2;
769 if (caplen
> packet_len
)
778 swt
= SWAPS(header
->wlen
);
779 packet_len
= swt
- (pw
->dag_fcs_bits
);
780 caplen
= erf_record_len
- dag_record_size
;
781 if (caplen
> packet_len
)
789 if(caplen
> p
->snapshot
)
790 caplen
= p
->snapshot
;
793 * Has "pcap_breakloop()" been called?
794 * If so, return immediately - if we haven't read any
795 * packets, clear the flag and return -2 to indicate
796 * that we were told to break out of the loop, otherwise
797 * leave the flag set, so that the *next* call will break
798 * out of the loop without having read any packets, and
799 * return the number of packets we've processed so far.
810 p
->bp
= (char*)header
;
811 p
->cc
= endofbuf
- (char*)header
;
818 /* convert between timestamp formats */
820 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
821 ts
= (ts
& 0xffffffffi
64) * 1000000;
822 ts
+= 0x80000000; /* rounding */
823 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
824 if (pcap_header
.ts
.tv_usec
>= 1000000) {
825 pcap_header
.ts
.tv_usec
-= 1000000;
826 pcap_header
.ts
.tv_sec
++;
830 /* No underlaying filtering system. We need to filter on our own */
831 if (p
->fcode
.bf_insns
)
833 if (pcap_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
835 /* Move to next packet */
836 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
841 /* Fill the header for the user suppplied callback function */
842 pcap_header
.caplen
= caplen
;
843 pcap_header
.len
= packet_len
;
845 /* Call the callback function */
846 (*callback
)(user
, &pcap_header
, dp
);
848 /* Move to next packet */
849 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
851 /* Stop if the number of packets requested by user has been reached*/
852 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
854 p
->bp
= (char*)header
;
855 p
->cc
= endofbuf
- (char*)header
;
859 while((u_char
*)header
< endofbuf
);
863 #endif /* HAVE_DAG_API */
865 /* Send a packet to the network */
867 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
869 struct pcap_win
*pw
= p
->priv
;
872 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
873 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
874 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
879 * We assume it all got sent if "PacketSendPacket()" succeeded.
880 * "pcap_inject()" is expected to return the number of bytes
887 pcap_cleanup_npf(pcap_t
*p
)
889 struct pcap_win
*pw
= p
->priv
;
891 if (pw
->adapter
!= NULL
) {
892 PacketCloseAdapter(pw
->adapter
);
895 if (pw
->rfmon_selfstart
)
897 PacketSetMonitorMode(p
->opt
.device
, 0);
899 pcap_cleanup_live_common(p
);
903 pcap_breakloop_npf(pcap_t
*p
)
905 pcap_breakloop_common(p
);
906 struct pcap_win
*pw
= p
->priv
;
908 /* XXX - what if this fails? */
909 SetEvent(PacketGetReadEvent(pw
->adapter
));
913 pcap_activate_npf(pcap_t
*p
)
915 struct pcap_win
*pw
= p
->priv
;
922 * Monitor mode is supported on Windows Vista and later.
924 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
926 pw
->rfmon_selfstart
= 0;
930 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
932 pw
->rfmon_selfstart
= 0;
933 // Monitor mode is not supported.
936 return PCAP_ERROR_RFMON_NOTSUP
;
945 pw
->rfmon_selfstart
= 1;
950 /* Init Winsock if it hasn't already been initialized */
953 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
955 if (pw
->adapter
== NULL
)
957 DWORD errcode
= GetLastError();
960 * What error did we get when trying to open the adapter?
966 * There's no such device.
968 return (PCAP_ERROR_NO_SUCH_DEVICE
);
970 case ERROR_ACCESS_DENIED
:
972 * There is, but we don't have permission to
975 return (PCAP_ERROR_PERM_DENIED
);
979 * Unknown - report details.
981 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
982 errcode
, "Error opening adapter");
983 if (pw
->rfmon_selfstart
)
985 PacketSetMonitorMode(p
->opt
.device
, 0);
992 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
994 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
995 GetLastError(), "Cannot determine the network type");
1000 switch (type
.LinkType
)
1003 p
->linktype
= DLT_EN10MB
;
1006 case NdisMedium802_3
:
1007 p
->linktype
= DLT_EN10MB
;
1009 * This is (presumably) a real Ethernet capture; give it a
1010 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1011 * that an application can let you choose it, in case you're
1012 * capturing DOCSIS traffic that a Cisco Cable Modem
1013 * Termination System is putting out onto an Ethernet (it
1014 * doesn't put an Ethernet header onto the wire, it puts raw
1015 * DOCSIS frames out on the wire inside the low-level
1016 * Ethernet framing).
1018 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1020 * If that fails, just leave the list empty.
1022 if (p
->dlt_list
!= NULL
) {
1023 p
->dlt_list
[0] = DLT_EN10MB
;
1024 p
->dlt_list
[1] = DLT_DOCSIS
;
1029 case NdisMediumFddi
:
1030 p
->linktype
= DLT_FDDI
;
1033 case NdisMedium802_5
:
1034 p
->linktype
= DLT_IEEE802
;
1037 case NdisMediumArcnetRaw
:
1038 p
->linktype
= DLT_ARCNET
;
1041 case NdisMediumArcnet878_2
:
1042 p
->linktype
= DLT_ARCNET
;
1046 p
->linktype
= DLT_ATM_RFC1483
;
1049 case NdisMediumCHDLC
:
1050 p
->linktype
= DLT_CHDLC
;
1053 case NdisMediumPPPSerial
:
1054 p
->linktype
= DLT_PPP_SERIAL
;
1057 case NdisMediumNull
:
1058 p
->linktype
= DLT_NULL
;
1061 case NdisMediumBare80211
:
1062 p
->linktype
= DLT_IEEE802_11
;
1065 case NdisMediumRadio80211
:
1066 p
->linktype
= DLT_IEEE802_11_RADIO
;
1070 p
->linktype
= DLT_PPI
;
1073 case NdisMediumWirelessWan
:
1074 p
->linktype
= DLT_RAW
;
1079 * An unknown medium type is assumed to supply Ethernet
1080 * headers; if not, the user will have to report it,
1081 * so that the medium type and link-layer header type
1082 * can be determined. If we were to fail here, we
1083 * might get the link-layer type in the error, but
1084 * the user wouldn't get a capture, so we wouldn't
1085 * be able to determine the link-layer type; we report
1086 * a warning with the link-layer type, so at least
1087 * some programs will report the warning.
1089 p
->linktype
= DLT_EN10MB
;
1090 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1091 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1093 status
= PCAP_WARNING
;
1098 * Turn a negative snapshot value (invalid), a snapshot value of
1099 * 0 (unspecified), or a value bigger than the normal maximum
1100 * value, into the maximum allowed value.
1102 * If some application really *needs* a bigger snapshot
1103 * length, we should just increase MAXIMUM_SNAPLEN.
1105 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1106 p
->snapshot
= MAXIMUM_SNAPLEN
;
1108 /* Set promiscuous mode */
1112 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1114 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1120 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1121 * protocols and all packets indicated by the NIC" but if no protocol
1122 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1123 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1124 * capture incoming frames.
1126 if (PacketSetHwFilter(pw
->adapter
,
1127 NDIS_PACKET_TYPE_ALL_LOCAL
|
1128 NDIS_PACKET_TYPE_DIRECTED
|
1129 NDIS_PACKET_TYPE_BROADCAST
|
1130 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1132 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1137 /* Set the buffer size */
1138 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1140 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1143 * Traditional Adapter
1146 * If the buffer size wasn't explicitly set, default to
1147 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1149 if (p
->opt
.buffer_size
== 0)
1150 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1152 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1154 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1158 p
->buffer
= malloc(p
->bufsize
);
1159 if (p
->buffer
== NULL
)
1161 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1166 if (p
->opt
.immediate
)
1168 /* tell the driver to copy the buffer as soon as data arrives */
1169 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1171 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1172 PCAP_ERRBUF_SIZE
, GetLastError(),
1173 "Error calling PacketSetMinToCopy");
1179 /* tell the driver to copy the buffer only if it contains at least 16K */
1180 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1182 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1183 PCAP_ERRBUF_SIZE
, GetLastError(),
1184 "Error calling PacketSetMinToCopy");
1194 * We have DAG support.
1203 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1204 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1205 strstr(_strlwr(p
->opt
.device
), "dag"));
1208 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1209 if(status
!= ERROR_SUCCESS
)
1212 status
= RegQueryValueEx(dagkey
,
1219 if(status
!= ERROR_SUCCESS
)
1224 RegCloseKey(dagkey
);
1229 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1231 /* Set the length of the FCS associated to any packet. This value
1232 * will be subtracted to the packet length */
1233 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1234 #else /* HAVE_DAG_API */
1239 #endif /* HAVE_DAG_API */
1242 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1244 /* disable loopback capture if requested */
1245 if (p
->opt
.nocapture_local
)
1247 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1249 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1250 "Unable to disable the capture of loopback packets.");
1256 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1258 /* install dag specific handlers for read and setfilter */
1259 p
->read_op
= pcap_read_win32_dag
;
1260 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1264 #endif /* HAVE_DAG_API */
1265 /* install traditional npf handlers for read and setfilter */
1266 p
->read_op
= pcap_read_npf
;
1267 p
->setfilter_op
= pcap_setfilter_npf
;
1270 #endif /* HAVE_DAG_API */
1271 p
->setdirection_op
= NULL
; /* Not implemented. */
1272 /* XXX - can this be implemented on some versions of Windows? */
1273 p
->inject_op
= pcap_inject_npf
;
1274 p
->set_datalink_op
= NULL
; /* can't change data link type */
1275 p
->getnonblock_op
= pcap_getnonblock_npf
;
1276 p
->setnonblock_op
= pcap_setnonblock_npf
;
1277 p
->stats_op
= pcap_stats_npf
;
1278 p
->breakloop_op
= pcap_breakloop_npf
;
1279 p
->stats_ex_op
= pcap_stats_ex_npf
;
1280 p
->setbuff_op
= pcap_setbuff_npf
;
1281 p
->setmode_op
= pcap_setmode_npf
;
1282 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1283 p
->getevent_op
= pcap_getevent_npf
;
1284 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1285 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1286 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1287 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1288 p
->live_dump_op
= pcap_live_dump_npf
;
1289 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1290 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1291 p
->cleanup_op
= pcap_cleanup_npf
;
1294 * XXX - this is only done because WinPcap supported
1295 * pcap_fileno() returning the hFile HANDLE from the
1296 * ADAPTER structure. We make no general guarantees
1297 * that the caller can do anything useful with it.
1299 * (Not that we make any general guarantee of that
1300 * sort on UN*X, either, any more, given that not
1301 * all capture devices are regular OS network
1304 p
->handle
= pw
->adapter
->hFile
;
1308 pcap_cleanup_npf(p
);
1309 return (PCAP_ERROR
);
1313 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1316 pcap_can_set_rfmon_npf(pcap_t
*p
)
1318 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1322 pcap_create_interface(const char *device _U_
, char *ebuf
)
1326 p
= PCAP_CREATE_COMMON(ebuf
, struct pcap_win
);
1330 p
->activate_op
= pcap_activate_npf
;
1331 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1336 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1338 struct pcap_win
*pw
= p
->priv
;
1340 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1342 * Kernel filter not installed.
1344 * XXX - we don't know whether this failed because:
1346 * the kernel rejected the filter program as invalid,
1347 * in which case we should fall back on userland
1350 * the kernel rejected the filter program as too big,
1351 * in which case we should again fall back on
1352 * userland filtering;
1354 * there was some other problem, in which case we
1355 * should probably report an error.
1357 * For NPF devices, the Win32 status will be
1358 * STATUS_INVALID_DEVICE_REQUEST for invalid
1359 * filters, but I don't know what it'd be for
1360 * other problems, and for some other devices
1361 * it might not be set at all.
1363 * So we just fall back on userland filtering in
1368 * install_bpf_program() validates the program.
1370 * XXX - what if we already have a filter in the kernel?
1372 if (install_bpf_program(p
, fp
) < 0)
1374 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1381 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1384 * Discard any previously-received packets, as they might have
1385 * passed whatever filter was formerly in effect, but might
1386 * not pass this filter (BIOCSETF discards packets buffered
1387 * in the kernel, so you can lose packets in any case).
1394 * We filter at user level, since the kernel driver does't process the packets
1397 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1401 pcap_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1405 /* Install a user level filter */
1406 if (install_bpf_program(p
, fp
) < 0)
1413 pcap_getnonblock_npf(pcap_t
*p
)
1415 struct pcap_win
*pw
= p
->priv
;
1418 * XXX - if there were a PacketGetReadTimeout() call, we
1419 * would use it, and return 1 if the timeout is -1
1422 return (pw
->nonblock
);
1426 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1428 struct pcap_win
*pw
= p
->priv
;
1433 * Set the packet buffer timeout to -1 for non-blocking
1439 * Restore the timeout set when the device was opened.
1440 * (Note that this may be -1, in which case we're not
1441 * really leaving non-blocking mode. However, although
1442 * the timeout argument to pcap_set_timeout() and
1443 * pcap_open_live() is an int, you're not supposed to
1444 * supply a negative value, so that "shouldn't happen".)
1446 newtimeout
= p
->opt
.timeout
;
1448 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1449 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1450 GetLastError(), "PacketSetReadTimeout");
1453 pw
->nonblock
= (newtimeout
== -1);
1458 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1459 const char *description
, char *errbuf
)
1462 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1466 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1469 * Add an entry for this interface, with no addresses.
1471 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1472 if (curdev
== NULL
) {
1480 * Get the list of addresses for the interface.
1482 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1486 * We don't return an error, because this can happen with
1487 * NdisWan interfaces, and we want to supply them even
1488 * if we can't supply their addresses.
1490 * We return an entry with an empty address list.
1496 * Now add the addresses.
1498 while (if_addr_size
-- > 0) {
1500 * "curdev" is an entry for this interface; add an entry for
1501 * this address to its list of addresses.
1503 res
= add_addr_to_dev(curdev
,
1504 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1505 sizeof (struct sockaddr_storage
),
1506 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1507 sizeof (struct sockaddr_storage
),
1508 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1509 sizeof (struct sockaddr_storage
),
1525 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1531 NDIS_HARDWARE_STATUS hardware_status
;
1532 #ifdef OID_GEN_PHYSICAL_MEDIUM
1533 NDIS_PHYSICAL_MEDIUM phys_medium
;
1534 bpf_u_int32 gen_physical_medium_oids
[] = {
1535 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1536 OID_GEN_PHYSICAL_MEDIUM_EX
,
1538 OID_GEN_PHYSICAL_MEDIUM
1540 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1542 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1543 #ifdef OID_GEN_LINK_STATE
1544 NDIS_LINK_STATE link_state
;
1548 if (*flags
& PCAP_IF_LOOPBACK
) {
1550 * Loopback interface, so the connection status doesn't
1551 * apply. and it's not wireless (or wired, for that
1552 * matter...). We presume it's up and running.
1554 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1559 * We need to open the adapter to get this information.
1561 * XXX - PacketOpenAdapter() takes a non-const pointer
1562 * as an argument, so we make a copy of the argument and
1565 name_copy
= strdup(name
);
1566 adapter
= PacketOpenAdapter(name_copy
);
1568 if (adapter
== NULL
) {
1570 * Give up; if they try to open this device, it'll fail.
1575 #ifdef HAVE_AIRPCAP_API
1577 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1578 * Just set these flags (and none of the '*flags' entered with).
1580 if (PacketGetAirPcapHandle(adapter
)) {
1582 * Must be "up" and "running" if the above if succeeded.
1584 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1587 * An airpcap device is a wireless device (duh!)
1589 *flags
|= PCAP_IF_WIRELESS
;
1592 * A "network assosiation state" makes no sense for airpcap.
1594 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1595 PacketCloseAdapter(adapter
);
1601 * Get the hardware status, and derive "up" and "running" from
1604 len
= sizeof (hardware_status
);
1605 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1606 &hardware_status
, &len
, errbuf
);
1608 switch (hardware_status
) {
1610 case NdisHardwareStatusReady
:
1612 * "Available and capable of sending and receiving
1613 * data over the wire", so up and running.
1615 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1618 case NdisHardwareStatusInitializing
:
1619 case NdisHardwareStatusReset
:
1621 * "Initializing" or "Resetting", so up, but
1624 *flags
|= PCAP_IF_UP
;
1627 case NdisHardwareStatusClosing
:
1628 case NdisHardwareStatusNotReady
:
1630 * "Closing" or "Not ready", so neither up nor
1643 * Can't get the hardware status, so assume both up and
1646 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1650 * Get the network type.
1652 #ifdef OID_GEN_PHYSICAL_MEDIUM
1654 * Try the OIDs we have for this, in order.
1656 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1657 len
= sizeof (phys_medium
);
1658 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1659 &phys_medium
, &len
, errbuf
);
1667 * Failed. We can't determine whether it failed
1668 * because that particular OID isn't supported
1669 * or because some other problem occurred, so we
1670 * just drive on and try the next OID.
1675 * We got the physical medium.
1677 switch (phys_medium
) {
1679 case NdisPhysicalMediumWirelessLan
:
1680 case NdisPhysicalMediumWirelessWan
:
1681 case NdisPhysicalMediumNative802_11
:
1682 case NdisPhysicalMediumBluetooth
:
1683 case NdisPhysicalMediumUWB
:
1684 case NdisPhysicalMediumIrda
:
1688 *flags
|= PCAP_IF_WIRELESS
;
1701 * Get the connection status.
1703 #ifdef OID_GEN_LINK_STATE
1704 len
= sizeof(link_state
);
1705 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
1709 * NOTE: this also gives us the receive and transmit
1712 switch (link_state
.MediaConnectState
) {
1714 case MediaConnectStateConnected
:
1718 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1721 case MediaConnectStateDisconnected
:
1723 * It's disconnected.
1725 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1730 * It's unknown whether it's connected or not.
1737 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1743 * OK, OID_GEN_LINK_STATE didn't work, try
1744 * OID_GEN_MEDIA_CONNECT_STATUS.
1746 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1747 &connect_status
, &len
, errbuf
);
1749 switch (connect_status
) {
1751 case NdisMediaStateConnected
:
1755 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1758 case NdisMediaStateDisconnected
:
1760 * It's disconnected.
1762 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1767 PacketCloseAdapter(adapter
);
1772 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1781 * Find out how big a buffer we need.
1783 * This call should always return FALSE; if the error is
1784 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1785 * the size of the buffer we need, otherwise there's a
1786 * problem, and NameLength should be set to 0.
1788 * It shouldn't require NameLength to be set, but,
1789 * at least as of WinPcap 4.1.3, it checks whether
1790 * NameLength is big enough before it checks for a
1791 * NULL buffer argument, so, while it'll still do
1792 * the right thing if NameLength is uninitialized and
1793 * whatever junk happens to be there is big enough
1794 * (because the pointer argument will be null), it's
1795 * still reading an uninitialized variable.
1798 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1800 DWORD last_error
= GetLastError();
1802 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1804 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1805 last_error
, "PacketGetAdapterNames");
1810 if (NameLength
<= 0)
1812 AdaptersName
= (char*) malloc(NameLength
);
1813 if (AdaptersName
== NULL
)
1815 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1819 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1820 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1821 GetLastError(), "PacketGetAdapterNames");
1827 * "PacketGetAdapterNames()" returned a list of
1828 * null-terminated ASCII interface name strings,
1829 * terminated by a null string, followed by a list
1830 * of null-terminated ASCII interface description
1831 * strings, terminated by a null string.
1832 * This means there are two ASCII nulls at the end
1833 * of the first list.
1835 * Find the end of the first list; that's the
1836 * beginning of the second list.
1838 desc
= &AdaptersName
[0];
1839 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1843 * Found it - "desc" points to the first of the two
1844 * nulls at the end of the list of names, so the
1845 * first byte of the list of descriptions is two bytes
1851 * Loop over the elements in the first list.
1853 name
= &AdaptersName
[0];
1854 while (*name
!= '\0') {
1855 bpf_u_int32 flags
= 0;
1857 #ifdef HAVE_AIRPCAP_API
1859 * Is this an AirPcap device?
1860 * If so, ignore it; it'll get added later, by the
1863 if (device_is_airpcap(name
, errbuf
) == 1) {
1864 name
+= strlen(name
) + 1;
1865 desc
+= strlen(desc
) + 1;
1870 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1872 * Is this a loopback interface?
1874 if (PacketIsLoopbackAdapter(name
)) {
1876 flags
|= PCAP_IF_LOOPBACK
;
1880 * Get additional flags.
1882 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1891 * Add an entry for this interface.
1893 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1901 name
+= strlen(name
) + 1;
1902 desc
+= strlen(desc
) + 1;
1910 * Return the name of a network interface attached to the system, or NULL
1911 * if none can be found. The interface must be configured up; the
1912 * lowest unit number is preferred; loopback is ignored.
1914 * In the best of all possible worlds, this would be the same as on
1915 * UN*X, but there may be software that expects this to return a
1916 * full list of devices after the first device.
1918 #define ADAPTERSNAME_LEN 8192
1920 pcap_lookupdev(char *errbuf
)
1923 DWORD dwWindowsMajorVersion
;
1926 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1927 * it may return UTF-16 strings, for backwards-compatibility
1928 * reasons, and we're also disabling the hack to make that work,
1929 * for not-going-past-the-end-of-a-string reasons, and 2) we
1930 * want its behavior to be consistent.
1932 * In addition, it's not thread-safe, so we've marked it as
1936 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1937 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1941 /* disable MSVC's GetVersion() deprecated warning here */
1942 DIAG_OFF_DEPRECATION
1943 dwVersion
= GetVersion(); /* get the OS version */
1945 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1947 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1949 * Windows 95, 98, ME.
1951 ULONG NameLength
= ADAPTERSNAME_LEN
;
1952 static char AdaptersName
[ADAPTERSNAME_LEN
];
1954 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1955 return (AdaptersName
);
1960 * Windows NT (NT 4.0 and later).
1961 * Convert the names to Unicode for backward compatibility.
1963 ULONG NameLength
= ADAPTERSNAME_LEN
;
1964 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1965 size_t BufferSpaceLeft
;
1970 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
1973 if(TAdaptersName
== NULL
)
1975 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
1979 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
1981 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1982 GetLastError(), "PacketGetAdapterNames");
1983 free(TAdaptersName
);
1988 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
1989 tAstr
= (char*)TAdaptersName
;
1990 Unameptr
= AdaptersName
;
1993 * Convert the device names to Unicode into AdapterName.
1997 * Length of the name, including the terminating
2000 namelen
= strlen(tAstr
) + 1;
2003 * Do we have room for the name in the Unicode
2006 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
2012 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
2015 * Copy the name, converting ASCII to Unicode.
2016 * namelen includes the NUL, so we copy it as
2019 for (i
= 0; i
< namelen
; i
++)
2020 *Unameptr
++ = *tAstr
++;
2023 * Count this adapter.
2026 } while (namelen
!= 1);
2029 * Copy the descriptions, but don't convert them from
2032 Adescptr
= (char *)Unameptr
;
2037 desclen
= strlen(tAstr
) + 1;
2040 * Do we have room for the name in the Unicode
2043 if (BufferSpaceLeft
< desclen
) {
2051 * Just copy the ASCII string.
2052 * namelen includes the NUL, so we copy it as
2055 memcpy(Adescptr
, tAstr
, desclen
);
2056 Adescptr
+= desclen
;
2058 BufferSpaceLeft
-= desclen
;
2062 free(TAdaptersName
);
2063 return (char *)(AdaptersName
);
2068 * We can't use the same code that we use on UN*X, as that's doing
2069 * UN*X-specific calls.
2071 * We don't just fetch the entire list of devices, search for the
2072 * particular device, and use its first IPv4 address, as that's too
2073 * much work to get just one device's netmask.
2076 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2080 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2081 * in order to skip non IPv4 (i.e. IPv6 addresses)
2083 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2084 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2085 struct sockaddr_in
*t_addr
;
2088 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2093 for(i
= 0; i
< if_addr_size
; i
++)
2095 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2097 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2098 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2099 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2100 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2112 static const char *pcap_lib_version_string
;
2114 #ifdef HAVE_VERSION_H
2116 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2117 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2120 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2121 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2122 * for the packet.dll version number as well.)
2124 #include "../../version.h"
2126 static const char pcap_version_string
[] =
2127 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2130 pcap_lib_version(void)
2132 if (pcap_lib_version_string
== NULL
) {
2134 * Generate the version string.
2136 char *packet_version_string
= PacketGetVersion();
2137 char *packet_LPCSTR
= PacketGetLPCSTR();
2138 char *packet_const_char_star
= PacketGetConstCharStar();
2140 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2142 * WinPcap/Npcap version string and packet.dll version
2143 * string are the same; just report the WinPcap/Npcap
2146 pcap_lib_version_string
= pcap_version_string
;
2149 * WinPcap/Npcap version string and packet.dll version
2150 * string are different; that shouldn't be the
2151 * case (the two libraries should come from the
2152 * same version of WinPcap/Npcap), so we report both
2155 char *full_pcap_version_string
;
2157 if (pcap_asprintf(&full_pcap_version_string
,
2158 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
" blah blah blah %s %s",
2159 packet_version_string
,
2160 packet_LPCSTR
, packet_const_char_star
) != -1) {
2162 pcap_lib_version_string
= full_pcap_version_string
;
2166 return (pcap_lib_version_string
);
2169 #else /* HAVE_VERSION_H */
2172 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2176 pcap_lib_version(void)
2178 if (pcap_lib_version_string
== NULL
) {
2180 * Generate the version string. Report the packet.dll
2183 char *full_pcap_version_string
;
2185 if (pcap_asprintf(&full_pcap_version_string
,
2186 PCAP_VERSION_STRING
" (packet.dll version %s)",
2187 PacketGetVersion()) != -1) {
2189 pcap_lib_version_string
= full_pcap_version_string
;
2192 return (pcap_lib_version_string
);
2194 #endif /* HAVE_VERSION_H */