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
44 /* Old-school MinGW have these headers in a different place.
46 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
47 #include <ddk/ntddndis.h>
50 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
56 #endif /* HAVE_DAG_API */
58 #include "diag-control.h"
60 #include "pcap-airpcap.h"
62 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
63 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
64 static int pcap_getnonblock_npf(pcap_t
*);
65 static int pcap_setnonblock_npf(pcap_t
*, int);
67 /*dimension of the buffer in the pcap_t structure*/
68 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
70 /*dimension of the buffer in the kernel driver NPF */
71 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
73 /* Equivalent to ntohs(), but a lot faster under Windows */
74 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
77 * Private data for capturing on WinPcap/Npcap devices.
80 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
82 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
83 int filtering_in_kernel
; /* using kernel filter */
86 int dag_fcs_bits
; /* Number of checksum bits from link layer */
90 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
91 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
96 * Define stub versions of the monitor-mode support routines if this
97 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
100 #ifndef HAVE_NPCAP_PACKET_API
102 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
105 * We don't support monitor mode.
111 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
114 * This should never be called, as PacketIsMonitorModeSupported()
115 * will return 0, meaning "we don't support monitor mode, so
116 * don't try to turn it on or off".
122 PacketGetMonitorMode(PCHAR AdapterName _U_
)
125 * This should fail, so that pcap_activate_npf() returns
126 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
134 * Sigh. PacketRequest() will have made a DeviceIoControl()
135 * call to the NPF driver to perform the OID request, with a
136 * BIOCQUERYOID ioctl. The kernel code should get back one
137 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
138 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
139 * supported by the OS or the driver, but that doesn't seem
140 * to make it to the caller of PacketRequest() in a
143 #define NDIS_STATUS_INVALID_OID 0xc0010017
144 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
145 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
148 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
151 PACKET_OID_DATA
*oid_data_arg
;
154 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
155 * It should be big enough to hold "*lenp" bytes of data; it
156 * will actually be slightly larger, as PACKET_OID_DATA has a
157 * 1-byte data array at the end, standing in for the variable-length
158 * data that's actually there.
160 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
161 if (oid_data_arg
== NULL
) {
162 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
163 "Couldn't allocate argument buffer for PacketRequest");
168 * No need to copy the data - we're doing a fetch.
170 oid_data_arg
->Oid
= oid
;
171 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
172 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
173 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
174 GetLastError(), "Error calling PacketRequest");
180 * Get the length actually supplied.
182 *lenp
= oid_data_arg
->Length
;
185 * Copy back the data we fetched.
187 memcpy(data
, oid_data_arg
->Data
, *lenp
);
193 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
195 struct pcap_win
*pw
= p
->priv
;
196 struct bpf_stat bstats
;
199 * Try to get statistics.
201 * (Please note - "struct pcap_stat" is *not* the same as
202 * WinPcap's "struct bpf_stat". It might currently have the
203 * same layout, but let's not cheat.
205 * Note also that we don't fill in ps_capt, as we might have
206 * been called by code compiled against an earlier version of
207 * WinPcap that didn't have ps_capt, in which case filling it
208 * in would stomp on whatever comes after the structure passed
211 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
212 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
213 GetLastError(), "PacketGetStats error");
216 ps
->ps_recv
= bstats
.bs_recv
;
217 ps
->ps_drop
= bstats
.bs_drop
;
220 * XXX - PacketGetStats() doesn't fill this in, so we just
224 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
233 * Win32-only routine for getting statistics.
235 * This way is definitely safer than passing the pcap_stat * from the userland.
236 * In fact, there could happen than the user allocates a variable which is not
237 * big enough for the new structure, and the library will write in a zone
238 * which is not allocated to this variable.
240 * In this way, we're pretty sure we are writing on memory allocated to this
243 * XXX - but this is the wrong way to handle statistics. Instead, we should
244 * have an API that returns data in a form like the Options section of a
245 * pcapng Interface Statistics Block:
247 * 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
249 * which would let us add new statistics straightforwardly and indicate which
250 * statistics we are and are *not* providing, rather than having to provide
251 * possibly-bogus values for statistics we can't provide.
253 static struct pcap_stat
*
254 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
256 struct pcap_win
*pw
= p
->priv
;
257 struct bpf_stat bstats
;
259 *pcap_stat_size
= sizeof (p
->stat
);
262 * Try to get statistics.
264 * (Please note - "struct pcap_stat" is *not* the same as
265 * WinPcap's "struct bpf_stat". It might currently have the
266 * same layout, but let's not cheat.)
268 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
269 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
270 GetLastError(), "PacketGetStatsEx error");
273 p
->stat
.ps_recv
= bstats
.bs_recv
;
274 p
->stat
.ps_drop
= bstats
.bs_drop
;
275 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
277 p
->stat
.ps_capt
= bstats
.bs_capt
;
282 /* Set the dimension of the kernel-level capture buffer */
284 pcap_setbuff_npf(pcap_t
*p
, int dim
)
286 struct pcap_win
*pw
= p
->priv
;
288 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
290 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
296 /* Set the driver working mode */
298 pcap_setmode_npf(pcap_t
*p
, int mode
)
300 struct pcap_win
*pw
= p
->priv
;
302 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
304 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
311 /*set the minimum amount of data that will release a read call*/
313 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
315 struct pcap_win
*pw
= p
->priv
;
317 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
319 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
326 pcap_getevent_npf(pcap_t
*p
)
328 struct pcap_win
*pw
= p
->priv
;
330 return (PacketGetReadEvent(pw
->adapter
));
334 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
336 struct pcap_win
*pw
= p
->priv
;
338 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
342 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
345 struct pcap_win
*pw
= p
->priv
;
346 PACKET_OID_DATA
*oid_data_arg
;
349 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
350 * It should be big enough to hold "*lenp" bytes of data; it
351 * will actually be slightly larger, as PACKET_OID_DATA has a
352 * 1-byte data array at the end, standing in for the variable-length
353 * data that's actually there.
355 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
356 if (oid_data_arg
== NULL
) {
357 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
358 "Couldn't allocate argument buffer for PacketRequest");
362 oid_data_arg
->Oid
= oid
;
363 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
364 memcpy(oid_data_arg
->Data
, data
, *lenp
);
365 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
366 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
367 GetLastError(), "Error calling PacketRequest");
373 * Get the length actually copied.
375 *lenp
= oid_data_arg
->Length
;
378 * No need to copy the data - we're doing a set.
385 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
387 struct pcap_win
*pw
= p
->priv
;
390 res
= PacketSendPackets(pw
->adapter
,
395 if(res
!= queue
->len
){
396 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
397 GetLastError(), "Error queueing packets");
404 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
406 unsigned char *new_buff
;
409 /* Bogus parameter */
410 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
411 "Error: invalid size %d",size
);
415 /* Allocate the buffer */
416 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
419 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
420 "Error: not enough memory");
433 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
435 struct pcap_win
*pw
= p
->priv
;
438 /* Set the packet driver in dump mode */
439 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
441 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
442 "Error setting dump mode");
446 /* Set the name of the dump file */
447 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
449 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
450 "Error setting kernel dump file name");
454 /* Set the limits of the dump file */
455 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
457 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
458 "Error setting dump limit");
466 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
468 struct pcap_win
*pw
= p
->priv
;
470 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
473 #ifdef HAVE_AIRPCAP_API
474 static PAirpcapHandle
475 pcap_get_airpcap_handle_npf(pcap_t
*p
)
477 struct pcap_win
*pw
= p
->priv
;
479 return (PacketGetAirPcapHandle(pw
->adapter
));
481 #else /* HAVE_AIRPCAP_API */
482 static PAirpcapHandle
483 pcap_get_airpcap_handle_npf(pcap_t
*p _U_
)
487 #endif /* HAVE_AIRPCAP_API */
490 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
495 register u_char
*bp
, *ep
;
497 struct pcap_win
*pw
= p
->priv
;
502 * Has "pcap_breakloop()" been called?
506 * Yes - clear the flag that indicates that it
507 * has, and return PCAP_ERROR_BREAK to indicate
508 * that we were told to break out of the loop.
511 return (PCAP_ERROR_BREAK
);
515 * Capture the packets.
517 * The PACKET structure had a bunch of extra stuff for
518 * Windows 9x/Me, but the only interesting data in it
519 * in the versions of Windows that we support is just
520 * a copy of p->buffer, a copy of p->buflen, and the
521 * actual number of bytes read returned from
522 * PacketReceivePacket(), none of which has to be
523 * retained from call to call, so we just keep one on
526 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
527 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
529 * Did the device go away?
530 * If so, the error we get is ERROR_GEN_FAILURE.
532 DWORD errcode
= GetLastError();
534 if (errcode
== ERROR_GEN_FAILURE
) {
536 * The device on which we're capturing
537 * went away, or it became unusable
538 * by NPF due to a suspend/resume.
540 * XXX - hopefully no other error
541 * conditions are indicated by this.
543 * XXX - we really should return an
544 * appropriate error for that, but
545 * pcap_dispatch() etc. aren't
546 * documented as having error returns
547 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
549 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
550 "The interface disappeared");
552 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
553 PCAP_ERRBUF_SIZE
, errcode
,
554 "PacketReceivePacket error");
559 cc
= Packet
.ulBytesReceived
;
567 * Loop through each packet.
569 #define bhp ((struct bpf_hdr *)bp)
573 register u_int caplen
, hdrlen
;
576 * Has "pcap_breakloop()" been called?
577 * If so, return immediately - if we haven't read any
578 * packets, clear the flag and return PCAP_ERROR_BREAK
579 * to indicate that we were told to break out of the loop,
580 * otherwise leave the flag set, so that the *next* call
581 * will break out of the loop without having read any
582 * packets, and return the number of packets we've
588 return (PCAP_ERROR_BREAK
);
591 p
->cc
= (int) (ep
- bp
);
598 caplen
= bhp
->bh_caplen
;
599 hdrlen
= bhp
->bh_hdrlen
;
603 * Short-circuit evaluation: if using BPF filter
604 * in kernel, no need to do it now - we already know
605 * the packet passed the filter.
607 * XXX - pcap_filter() should always return TRUE if
608 * handed a null pointer for the program, but it might
609 * just try to "run" the filter, so we check here.
611 if (pw
->filtering_in_kernel
||
612 p
->fcode
.bf_insns
== NULL
||
613 pcap_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
615 switch (p
->rmt_samp
.method
) {
617 case PCAP_SAMP_1_EVERY_N
:
618 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
620 /* Discard all packets that are not '1 out of N' */
621 if (pw
->samp_npkt
!= 0) {
622 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
627 case PCAP_SAMP_FIRST_AFTER_N_MS
:
629 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
632 * Check if the timestamp of the arrived
633 * packet is smaller than our target time.
635 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
636 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
637 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
642 * The arrived packet is suitable for being
643 * delivered to our caller, so let's update
646 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
647 if (pw
->samp_time
.tv_usec
> 1000000) {
648 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
649 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
653 #endif /* ENABLE_REMOTE */
656 * XXX A bpf_hdr matches a pcap_pkthdr.
658 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
659 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
660 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
662 p
->cc
= (int) (ep
- bp
);
669 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
679 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
681 struct pcap_win
*pw
= p
->priv
;
684 int packet_len
= 0, caplen
= 0;
685 struct pcap_pkthdr pcap_header
;
688 dag_record_t
*header
;
689 unsigned erf_record_len
;
693 unsigned dfp
= pw
->adapter
->DagFastProcess
;
696 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
699 * Get new packets from the network.
701 * The PACKET structure had a bunch of extra stuff for
702 * Windows 9x/Me, but the only interesting data in it
703 * in the versions of Windows that we support is just
704 * a copy of p->buffer, a copy of p->buflen, and the
705 * actual number of bytes read returned from
706 * PacketReceivePacket(), none of which has to be
707 * retained from call to call, so we just keep one on
710 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
711 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
712 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
716 cc
= Packet
.ulBytesReceived
;
718 /* The timeout has expired but we no packets arrived */
720 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
723 header
= (dag_record_t
*)p
->bp
;
725 endofbuf
= (char*)header
+ cc
;
728 * Cycle through the packets
732 erf_record_len
= SWAPS(header
->rlen
);
733 if((char*)header
+ erf_record_len
> endofbuf
)
736 /* Increase the number of captured packets */
739 /* Find the beginning of the packet */
740 dp
= ((u_char
*)header
) + dag_record_size
;
742 /* Determine actual packet len */
746 packet_len
= ATM_SNAPLEN
;
747 caplen
= ATM_SNAPLEN
;
753 swt
= SWAPS(header
->wlen
);
754 packet_len
= swt
- (pw
->dag_fcs_bits
);
755 caplen
= erf_record_len
- dag_record_size
- 2;
756 if (caplen
> packet_len
)
765 swt
= SWAPS(header
->wlen
);
766 packet_len
= swt
- (pw
->dag_fcs_bits
);
767 caplen
= erf_record_len
- dag_record_size
;
768 if (caplen
> packet_len
)
776 if(caplen
> p
->snapshot
)
777 caplen
= p
->snapshot
;
780 * Has "pcap_breakloop()" been called?
781 * If so, return immediately - if we haven't read any
782 * packets, clear the flag and return -2 to indicate
783 * that we were told to break out of the loop, otherwise
784 * leave the flag set, so that the *next* call will break
785 * out of the loop without having read any packets, and
786 * return the number of packets we've processed so far.
797 p
->bp
= (char*)header
;
798 p
->cc
= endofbuf
- (char*)header
;
805 /* convert between timestamp formats */
807 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
808 ts
= (ts
& 0xffffffffi
64) * 1000000;
809 ts
+= 0x80000000; /* rounding */
810 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
811 if (pcap_header
.ts
.tv_usec
>= 1000000) {
812 pcap_header
.ts
.tv_usec
-= 1000000;
813 pcap_header
.ts
.tv_sec
++;
817 /* No underlaying filtering system. We need to filter on our own */
818 if (p
->fcode
.bf_insns
)
820 if (pcap_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
822 /* Move to next packet */
823 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
828 /* Fill the header for the user suppplied callback function */
829 pcap_header
.caplen
= caplen
;
830 pcap_header
.len
= packet_len
;
832 /* Call the callback function */
833 (*callback
)(user
, &pcap_header
, dp
);
835 /* Move to next packet */
836 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
838 /* Stop if the number of packets requested by user has been reached*/
839 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
841 p
->bp
= (char*)header
;
842 p
->cc
= endofbuf
- (char*)header
;
846 while((u_char
*)header
< endofbuf
);
850 #endif /* HAVE_DAG_API */
852 /* Send a packet to the network */
854 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
856 struct pcap_win
*pw
= p
->priv
;
859 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
860 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
861 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
866 * We assume it all got sent if "PacketSendPacket()" succeeded.
867 * "pcap_inject()" is expected to return the number of bytes
874 pcap_cleanup_npf(pcap_t
*p
)
876 struct pcap_win
*pw
= p
->priv
;
878 if (pw
->adapter
!= NULL
) {
879 PacketCloseAdapter(pw
->adapter
);
882 if (pw
->rfmon_selfstart
)
884 PacketSetMonitorMode(p
->opt
.device
, 0);
886 pcap_cleanup_live_common(p
);
890 pcap_breakloop_npf(pcap_t
*p
)
892 pcap_breakloop_common(p
);
893 struct pcap_win
*pw
= p
->priv
;
895 /* XXX - what if this fails? */
896 SetEvent(PacketGetReadEvent(pw
->adapter
));
900 pcap_activate_npf(pcap_t
*p
)
902 struct pcap_win
*pw
= p
->priv
;
909 * Monitor mode is supported on Windows Vista and later.
911 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
913 pw
->rfmon_selfstart
= 0;
917 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
919 pw
->rfmon_selfstart
= 0;
920 // Monitor mode is not supported.
923 return PCAP_ERROR_RFMON_NOTSUP
;
932 pw
->rfmon_selfstart
= 1;
937 /* Init Winsock if it hasn't already been initialized */
940 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
942 if (pw
->adapter
== NULL
)
944 DWORD errcode
= GetLastError();
947 * What error did we get when trying to open the adapter?
953 * There's no such device.
955 return (PCAP_ERROR_NO_SUCH_DEVICE
);
957 case ERROR_ACCESS_DENIED
:
959 * There is, but we don't have permission to
962 return (PCAP_ERROR_PERM_DENIED
);
966 * Unknown - report details.
968 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
969 errcode
, "Error opening adapter");
970 if (pw
->rfmon_selfstart
)
972 PacketSetMonitorMode(p
->opt
.device
, 0);
979 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
981 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
982 GetLastError(), "Cannot determine the network type");
987 switch (type
.LinkType
)
990 p
->linktype
= DLT_EN10MB
;
993 case NdisMedium802_3
:
994 p
->linktype
= DLT_EN10MB
;
996 * This is (presumably) a real Ethernet capture; give it a
997 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
998 * that an application can let you choose it, in case you're
999 * capturing DOCSIS traffic that a Cisco Cable Modem
1000 * Termination System is putting out onto an Ethernet (it
1001 * doesn't put an Ethernet header onto the wire, it puts raw
1002 * DOCSIS frames out on the wire inside the low-level
1003 * Ethernet framing).
1005 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1007 * If that fails, just leave the list empty.
1009 if (p
->dlt_list
!= NULL
) {
1010 p
->dlt_list
[0] = DLT_EN10MB
;
1011 p
->dlt_list
[1] = DLT_DOCSIS
;
1016 case NdisMediumFddi
:
1017 p
->linktype
= DLT_FDDI
;
1020 case NdisMedium802_5
:
1021 p
->linktype
= DLT_IEEE802
;
1024 case NdisMediumArcnetRaw
:
1025 p
->linktype
= DLT_ARCNET
;
1028 case NdisMediumArcnet878_2
:
1029 p
->linktype
= DLT_ARCNET
;
1033 p
->linktype
= DLT_ATM_RFC1483
;
1036 case NdisMediumCHDLC
:
1037 p
->linktype
= DLT_CHDLC
;
1040 case NdisMediumPPPSerial
:
1041 p
->linktype
= DLT_PPP_SERIAL
;
1044 case NdisMediumNull
:
1045 p
->linktype
= DLT_NULL
;
1048 case NdisMediumBare80211
:
1049 p
->linktype
= DLT_IEEE802_11
;
1052 case NdisMediumRadio80211
:
1053 p
->linktype
= DLT_IEEE802_11_RADIO
;
1057 p
->linktype
= DLT_PPI
;
1060 case NdisMediumWirelessWan
:
1061 p
->linktype
= DLT_RAW
;
1066 * An unknown medium type is assumed to supply Ethernet
1067 * headers; if not, the user will have to report it,
1068 * so that the medium type and link-layer header type
1069 * can be determined. If we were to fail here, we
1070 * might get the link-layer type in the error, but
1071 * the user wouldn't get a capture, so we wouldn't
1072 * be able to determine the link-layer type; we report
1073 * a warning with the link-layer type, so at least
1074 * some programs will report the warning.
1076 p
->linktype
= DLT_EN10MB
;
1077 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1078 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1080 status
= PCAP_WARNING
;
1085 * Turn a negative snapshot value (invalid), a snapshot value of
1086 * 0 (unspecified), or a value bigger than the normal maximum
1087 * value, into the maximum allowed value.
1089 * If some application really *needs* a bigger snapshot
1090 * length, we should just increase MAXIMUM_SNAPLEN.
1092 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1093 p
->snapshot
= MAXIMUM_SNAPLEN
;
1095 /* Set promiscuous mode */
1099 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1101 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1107 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1108 * protocols and all packets indicated by the NIC" but if no protocol
1109 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1110 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1111 * capture incoming frames.
1113 if (PacketSetHwFilter(pw
->adapter
,
1114 NDIS_PACKET_TYPE_ALL_LOCAL
|
1115 NDIS_PACKET_TYPE_DIRECTED
|
1116 NDIS_PACKET_TYPE_BROADCAST
|
1117 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1119 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1124 /* Set the buffer size */
1125 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1127 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1130 * Traditional Adapter
1133 * If the buffer size wasn't explicitly set, default to
1134 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1136 if (p
->opt
.buffer_size
== 0)
1137 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1139 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1141 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1145 p
->buffer
= malloc(p
->bufsize
);
1146 if (p
->buffer
== NULL
)
1148 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1153 if (p
->opt
.immediate
)
1155 /* tell the driver to copy the buffer as soon as data arrives */
1156 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1158 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1159 PCAP_ERRBUF_SIZE
, GetLastError(),
1160 "Error calling PacketSetMinToCopy");
1166 /* tell the driver to copy the buffer only if it contains at least 16K */
1167 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1169 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1170 PCAP_ERRBUF_SIZE
, GetLastError(),
1171 "Error calling PacketSetMinToCopy");
1181 * We have DAG support.
1190 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1191 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1192 strstr(_strlwr(p
->opt
.device
), "dag"));
1195 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1196 if(status
!= ERROR_SUCCESS
)
1199 status
= RegQueryValueEx(dagkey
,
1206 if(status
!= ERROR_SUCCESS
)
1211 RegCloseKey(dagkey
);
1216 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1218 /* Set the length of the FCS associated to any packet. This value
1219 * will be subtracted to the packet length */
1220 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1221 #else /* HAVE_DAG_API */
1226 #endif /* HAVE_DAG_API */
1229 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1231 /* disable loopback capture if requested */
1232 if (p
->opt
.nocapture_local
)
1234 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1236 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1237 "Unable to disable the capture of loopback packets.");
1243 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1245 /* install dag specific handlers for read and setfilter */
1246 p
->read_op
= pcap_read_win32_dag
;
1247 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1251 #endif /* HAVE_DAG_API */
1252 /* install traditional npf handlers for read and setfilter */
1253 p
->read_op
= pcap_read_npf
;
1254 p
->setfilter_op
= pcap_setfilter_npf
;
1257 #endif /* HAVE_DAG_API */
1258 p
->setdirection_op
= NULL
; /* Not implemented. */
1259 /* XXX - can this be implemented on some versions of Windows? */
1260 p
->inject_op
= pcap_inject_npf
;
1261 p
->set_datalink_op
= NULL
; /* can't change data link type */
1262 p
->getnonblock_op
= pcap_getnonblock_npf
;
1263 p
->setnonblock_op
= pcap_setnonblock_npf
;
1264 p
->stats_op
= pcap_stats_npf
;
1265 p
->breakloop_op
= pcap_breakloop_npf
;
1266 p
->stats_ex_op
= pcap_stats_ex_npf
;
1267 p
->setbuff_op
= pcap_setbuff_npf
;
1268 p
->setmode_op
= pcap_setmode_npf
;
1269 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1270 p
->getevent_op
= pcap_getevent_npf
;
1271 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1272 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1273 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1274 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1275 p
->live_dump_op
= pcap_live_dump_npf
;
1276 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1277 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1278 p
->cleanup_op
= pcap_cleanup_npf
;
1281 * XXX - this is only done because WinPcap supported
1282 * pcap_fileno() returning the hFile HANDLE from the
1283 * ADAPTER structure. We make no general guarantees
1284 * that the caller can do anything useful with it.
1286 * (Not that we make any general guarantee of that
1287 * sort on UN*X, either, any more, given that not
1288 * all capture devices are regular OS network
1291 p
->handle
= pw
->adapter
->hFile
;
1295 pcap_cleanup_npf(p
);
1296 return (PCAP_ERROR
);
1300 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1303 pcap_can_set_rfmon_npf(pcap_t
*p
)
1305 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1309 pcap_create_interface(const char *device _U_
, char *ebuf
)
1313 p
= pcap_create_common(ebuf
, sizeof(struct pcap_win
));
1317 p
->activate_op
= pcap_activate_npf
;
1318 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1323 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1325 struct pcap_win
*pw
= p
->priv
;
1327 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1329 * Kernel filter not installed.
1331 * XXX - we don't know whether this failed because:
1333 * the kernel rejected the filter program as invalid,
1334 * in which case we should fall back on userland
1337 * the kernel rejected the filter program as too big,
1338 * in which case we should again fall back on
1339 * userland filtering;
1341 * there was some other problem, in which case we
1342 * should probably report an error.
1344 * For NPF devices, the Win32 status will be
1345 * STATUS_INVALID_DEVICE_REQUEST for invalid
1346 * filters, but I don't know what it'd be for
1347 * other problems, and for some other devices
1348 * it might not be set at all.
1350 * So we just fall back on userland filtering in
1355 * install_bpf_program() validates the program.
1357 * XXX - what if we already have a filter in the kernel?
1359 if (install_bpf_program(p
, fp
) < 0)
1361 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1368 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1371 * Discard any previously-received packets, as they might have
1372 * passed whatever filter was formerly in effect, but might
1373 * not pass this filter (BIOCSETF discards packets buffered
1374 * in the kernel, so you can lose packets in any case).
1381 * We filter at user level, since the kernel driver does't process the packets
1384 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1388 pcap_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1392 /* Install a user level filter */
1393 if (install_bpf_program(p
, fp
) < 0)
1400 pcap_getnonblock_npf(pcap_t
*p
)
1402 struct pcap_win
*pw
= p
->priv
;
1405 * XXX - if there were a PacketGetReadTimeout() call, we
1406 * would use it, and return 1 if the timeout is -1
1409 return (pw
->nonblock
);
1413 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1415 struct pcap_win
*pw
= p
->priv
;
1420 * Set the packet buffer timeout to -1 for non-blocking
1426 * Restore the timeout set when the device was opened.
1427 * (Note that this may be -1, in which case we're not
1428 * really leaving non-blocking mode. However, although
1429 * the timeout argument to pcap_set_timeout() and
1430 * pcap_open_live() is an int, you're not supposed to
1431 * supply a negative value, so that "shouldn't happen".)
1433 newtimeout
= p
->opt
.timeout
;
1435 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1436 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1437 GetLastError(), "PacketSetReadTimeout");
1440 pw
->nonblock
= (newtimeout
== -1);
1445 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1446 const char *description
, char *errbuf
)
1449 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1453 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1456 * Add an entry for this interface, with no addresses.
1458 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1459 if (curdev
== NULL
) {
1467 * Get the list of addresses for the interface.
1469 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1473 * We don't return an error, because this can happen with
1474 * NdisWan interfaces, and we want to supply them even
1475 * if we can't supply their addresses.
1477 * We return an entry with an empty address list.
1483 * Now add the addresses.
1485 while (if_addr_size
-- > 0) {
1487 * "curdev" is an entry for this interface; add an entry for
1488 * this address to its list of addresses.
1490 res
= add_addr_to_dev(curdev
,
1491 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1492 sizeof (struct sockaddr_storage
),
1493 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1494 sizeof (struct sockaddr_storage
),
1495 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1496 sizeof (struct sockaddr_storage
),
1512 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1518 NDIS_HARDWARE_STATUS hardware_status
;
1519 #ifdef OID_GEN_PHYSICAL_MEDIUM
1520 NDIS_PHYSICAL_MEDIUM phys_medium
;
1521 bpf_u_int32 gen_physical_medium_oids
[] = {
1522 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1523 OID_GEN_PHYSICAL_MEDIUM_EX
,
1525 OID_GEN_PHYSICAL_MEDIUM
1527 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1529 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1530 #ifdef OID_GEN_LINK_STATE
1531 NDIS_LINK_STATE link_state
;
1535 if (*flags
& PCAP_IF_LOOPBACK
) {
1537 * Loopback interface, so the connection status doesn't
1538 * apply. and it's not wireless (or wired, for that
1539 * matter...). We presume it's up and running.
1541 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1546 * We need to open the adapter to get this information.
1548 * XXX - PacketOpenAdapter() takes a non-const pointer
1549 * as an argument, so we make a copy of the argument and
1552 name_copy
= strdup(name
);
1553 adapter
= PacketOpenAdapter(name_copy
);
1555 if (adapter
== NULL
) {
1557 * Give up; if they try to open this device, it'll fail.
1562 #ifdef HAVE_AIRPCAP_API
1564 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1565 * Just set these flags (and none of the '*flags' entered with).
1567 if (PacketGetAirPcapHandle(adapter
)) {
1569 * Must be "up" and "running" if the above if succeeded.
1571 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1574 * An airpcap device is a wireless device (duh!)
1576 *flags
|= PCAP_IF_WIRELESS
;
1579 * A "network assosiation state" makes no sense for airpcap.
1581 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1582 PacketCloseAdapter(adapter
);
1588 * Get the hardware status, and derive "up" and "running" from
1591 len
= sizeof (hardware_status
);
1592 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1593 &hardware_status
, &len
, errbuf
);
1595 switch (hardware_status
) {
1597 case NdisHardwareStatusReady
:
1599 * "Available and capable of sending and receiving
1600 * data over the wire", so up and running.
1602 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1605 case NdisHardwareStatusInitializing
:
1606 case NdisHardwareStatusReset
:
1608 * "Initializing" or "Resetting", so up, but
1611 *flags
|= PCAP_IF_UP
;
1614 case NdisHardwareStatusClosing
:
1615 case NdisHardwareStatusNotReady
:
1617 * "Closing" or "Not ready", so neither up nor
1630 * Can't get the hardware status, so assume both up and
1633 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1637 * Get the network type.
1639 #ifdef OID_GEN_PHYSICAL_MEDIUM
1641 * Try the OIDs we have for this, in order.
1643 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1644 len
= sizeof (phys_medium
);
1645 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1646 &phys_medium
, &len
, errbuf
);
1654 * Failed. We can't determine whether it failed
1655 * because that particular OID isn't supported
1656 * or because some other problem occurred, so we
1657 * just drive on and try the next OID.
1662 * We got the physical medium.
1664 switch (phys_medium
) {
1666 case NdisPhysicalMediumWirelessLan
:
1667 case NdisPhysicalMediumWirelessWan
:
1668 case NdisPhysicalMediumNative802_11
:
1669 case NdisPhysicalMediumBluetooth
:
1670 case NdisPhysicalMediumUWB
:
1671 case NdisPhysicalMediumIrda
:
1675 *flags
|= PCAP_IF_WIRELESS
;
1688 * Get the connection status.
1690 #ifdef OID_GEN_LINK_STATE
1691 len
= sizeof(link_state
);
1692 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
1696 * NOTE: this also gives us the receive and transmit
1699 switch (link_state
.MediaConnectState
) {
1701 case MediaConnectStateConnected
:
1705 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1708 case MediaConnectStateDisconnected
:
1710 * It's disconnected.
1712 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1717 * It's unknown whether it's connected or not.
1724 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1730 * OK, OID_GEN_LINK_STATE didn't work, try
1731 * OID_GEN_MEDIA_CONNECT_STATUS.
1733 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1734 &connect_status
, &len
, errbuf
);
1736 switch (connect_status
) {
1738 case NdisMediaStateConnected
:
1742 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1745 case NdisMediaStateDisconnected
:
1747 * It's disconnected.
1749 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1754 PacketCloseAdapter(adapter
);
1759 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1768 * Find out how big a buffer we need.
1770 * This call should always return FALSE; if the error is
1771 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1772 * the size of the buffer we need, otherwise there's a
1773 * problem, and NameLength should be set to 0.
1775 * It shouldn't require NameLength to be set, but,
1776 * at least as of WinPcap 4.1.3, it checks whether
1777 * NameLength is big enough before it checks for a
1778 * NULL buffer argument, so, while it'll still do
1779 * the right thing if NameLength is uninitialized and
1780 * whatever junk happens to be there is big enough
1781 * (because the pointer argument will be null), it's
1782 * still reading an uninitialized variable.
1785 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1787 DWORD last_error
= GetLastError();
1789 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1791 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1792 last_error
, "PacketGetAdapterNames");
1797 if (NameLength
<= 0)
1799 AdaptersName
= (char*) malloc(NameLength
);
1800 if (AdaptersName
== NULL
)
1802 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1806 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1807 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1808 GetLastError(), "PacketGetAdapterNames");
1814 * "PacketGetAdapterNames()" returned a list of
1815 * null-terminated ASCII interface name strings,
1816 * terminated by a null string, followed by a list
1817 * of null-terminated ASCII interface description
1818 * strings, terminated by a null string.
1819 * This means there are two ASCII nulls at the end
1820 * of the first list.
1822 * Find the end of the first list; that's the
1823 * beginning of the second list.
1825 desc
= &AdaptersName
[0];
1826 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1830 * Found it - "desc" points to the first of the two
1831 * nulls at the end of the list of names, so the
1832 * first byte of the list of descriptions is two bytes
1838 * Loop over the elements in the first list.
1840 name
= &AdaptersName
[0];
1841 while (*name
!= '\0') {
1842 bpf_u_int32 flags
= 0;
1844 #ifdef HAVE_AIRPCAP_API
1846 * Is this an AirPcap device?
1847 * If so, ignore it; it'll get added later, by the
1850 if (device_is_airpcap(name
, errbuf
) == 1) {
1851 name
+= strlen(name
) + 1;
1852 desc
+= strlen(desc
) + 1;
1857 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1859 * Is this a loopback interface?
1861 if (PacketIsLoopbackAdapter(name
)) {
1863 flags
|= PCAP_IF_LOOPBACK
;
1867 * Get additional flags.
1869 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1878 * Add an entry for this interface.
1880 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1888 name
+= strlen(name
) + 1;
1889 desc
+= strlen(desc
) + 1;
1897 * Return the name of a network interface attached to the system, or NULL
1898 * if none can be found. The interface must be configured up; the
1899 * lowest unit number is preferred; loopback is ignored.
1901 * In the best of all possible worlds, this would be the same as on
1902 * UN*X, but there may be software that expects this to return a
1903 * full list of devices after the first device.
1905 #define ADAPTERSNAME_LEN 8192
1907 pcap_lookupdev(char *errbuf
)
1910 DWORD dwWindowsMajorVersion
;
1913 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1914 * it may return UTF-16 strings, for backwards-compatibility
1915 * reasons, and we're also disabling the hack to make that work,
1916 * for not-going-past-the-end-of-a-string reasons, and 2) we
1917 * want its behavior to be consistent.
1919 * In addition, it's not thread-safe, so we've marked it as
1923 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1924 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1928 /* disable MSVC's GetVersion() deprecated warning here */
1929 DIAG_OFF_DEPRECATION
1930 dwVersion
= GetVersion(); /* get the OS version */
1932 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1934 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1936 * Windows 95, 98, ME.
1938 ULONG NameLength
= ADAPTERSNAME_LEN
;
1939 static char AdaptersName
[ADAPTERSNAME_LEN
];
1941 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1942 return (AdaptersName
);
1947 * Windows NT (NT 4.0 and later).
1948 * Convert the names to Unicode for backward compatibility.
1950 ULONG NameLength
= ADAPTERSNAME_LEN
;
1951 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1952 size_t BufferSpaceLeft
;
1957 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
1960 if(TAdaptersName
== NULL
)
1962 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
1966 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
1968 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1969 GetLastError(), "PacketGetAdapterNames");
1970 free(TAdaptersName
);
1975 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
1976 tAstr
= (char*)TAdaptersName
;
1977 Unameptr
= AdaptersName
;
1980 * Convert the device names to Unicode into AdapterName.
1984 * Length of the name, including the terminating
1987 namelen
= strlen(tAstr
) + 1;
1990 * Do we have room for the name in the Unicode
1993 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
1999 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
2002 * Copy the name, converting ASCII to Unicode.
2003 * namelen includes the NUL, so we copy it as
2006 for (i
= 0; i
< namelen
; i
++)
2007 *Unameptr
++ = *tAstr
++;
2010 * Count this adapter.
2013 } while (namelen
!= 1);
2016 * Copy the descriptions, but don't convert them from
2019 Adescptr
= (char *)Unameptr
;
2024 desclen
= strlen(tAstr
) + 1;
2027 * Do we have room for the name in the Unicode
2030 if (BufferSpaceLeft
< desclen
) {
2038 * Just copy the ASCII string.
2039 * namelen includes the NUL, so we copy it as
2042 memcpy(Adescptr
, tAstr
, desclen
);
2043 Adescptr
+= desclen
;
2045 BufferSpaceLeft
-= desclen
;
2049 free(TAdaptersName
);
2050 return (char *)(AdaptersName
);
2055 * We can't use the same code that we use on UN*X, as that's doing
2056 * UN*X-specific calls.
2058 * We don't just fetch the entire list of devices, search for the
2059 * particular device, and use its first IPv4 address, as that's too
2060 * much work to get just one device's netmask.
2063 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2067 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2068 * in order to skip non IPv4 (i.e. IPv6 addresses)
2070 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2071 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2072 struct sockaddr_in
*t_addr
;
2075 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2080 for(i
= 0; i
< if_addr_size
; i
++)
2082 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2084 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2085 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2086 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2087 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2099 static const char *pcap_lib_version_string
;
2101 #ifdef HAVE_VERSION_H
2103 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2104 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2107 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2108 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2109 * for the packet.dll version number as well.)
2111 #include "../../version.h"
2113 static const char pcap_version_string
[] =
2114 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2117 pcap_lib_version(void)
2119 if (pcap_lib_version_string
== NULL
) {
2121 * Generate the version string.
2123 char *packet_version_string
= PacketGetVersion();
2125 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2127 * WinPcap/Npcap version string and packet.dll version
2128 * string are the same; just report the WinPcap/Npcap
2131 pcap_lib_version_string
= pcap_version_string
;
2134 * WinPcap/Npcap version string and packet.dll version
2135 * string are different; that shouldn't be the
2136 * case (the two libraries should come from the
2137 * same version of WinPcap/Npcap), so we report both
2140 char *full_pcap_version_string
;
2142 if (pcap_asprintf(&full_pcap_version_string
,
2143 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
,
2144 packet_version_string
) != -1) {
2146 pcap_lib_version_string
= full_pcap_version_string
;
2150 return (pcap_lib_version_string
);
2153 #else /* HAVE_VERSION_H */
2156 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2160 pcap_lib_version(void)
2162 if (pcap_lib_version_string
== NULL
) {
2164 * Generate the version string. Report the packet.dll
2167 char *full_pcap_version_string
;
2169 if (pcap_asprintf(&full_pcap_version_string
,
2170 PCAP_VERSION_STRING
" (packet.dll version %s)",
2171 PacketGetVersion()) != -1) {
2173 pcap_lib_version_string
= full_pcap_version_string
;
2176 return (pcap_lib_version_string
);
2178 #endif /* HAVE_VERSION_H */