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 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
59 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
60 static int pcap_getnonblock_npf(pcap_t
*);
61 static int pcap_setnonblock_npf(pcap_t
*, int);
63 /*dimension of the buffer in the pcap_t structure*/
64 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
66 /*dimension of the buffer in the kernel driver NPF */
67 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
69 /* Equivalent to ntohs(), but a lot faster under Windows */
70 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
73 * Private data for capturing on WinPcap/Npcap devices.
76 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
78 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
79 int filtering_in_kernel
; /* using kernel filter */
82 int dag_fcs_bits
; /* Number of checksum bits from link layer */
86 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
87 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
92 * Define stub versions of the monitor-mode support routines if this
93 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
96 #ifndef HAVE_NPCAP_PACKET_API
98 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
101 * We don't support monitor mode.
107 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
110 * This should never be called, as PacketIsMonitorModeSupported()
111 * will return 0, meaning "we don't support monitor mode, so
112 * don't try to turn it on or off".
118 PacketGetMonitorMode(PCHAR AdapterName _U_
)
121 * This should fail, so that pcap_activate_npf() returns
122 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
130 * Sigh. PacketRequest() will have made a DeviceIoControl()
131 * call to the NPF driver to perform the OID request, with a
132 * BIOCQUERYOID ioctl. The kernel code should get back one
133 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
134 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
135 * supported by the OS or the driver, but that doesn't seem
136 * to make it to the caller of PacketRequest() in a
139 #define NDIS_STATUS_INVALID_OID 0xc0010017
140 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
141 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
144 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
147 PACKET_OID_DATA
*oid_data_arg
;
150 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
151 * It should be big enough to hold "*lenp" bytes of data; it
152 * will actually be slightly larger, as PACKET_OID_DATA has a
153 * 1-byte data array at the end, standing in for the variable-length
154 * data that's actually there.
156 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
157 if (oid_data_arg
== NULL
) {
158 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
159 "Couldn't allocate argument buffer for PacketRequest");
164 * No need to copy the data - we're doing a fetch.
166 oid_data_arg
->Oid
= oid
;
167 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
168 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
169 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
170 GetLastError(), "Error calling PacketRequest");
176 * Get the length actually supplied.
178 *lenp
= oid_data_arg
->Length
;
181 * Copy back the data we fetched.
183 memcpy(data
, oid_data_arg
->Data
, *lenp
);
189 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
191 struct pcap_win
*pw
= p
->priv
;
192 struct bpf_stat bstats
;
195 * Try to get statistics.
197 * (Please note - "struct pcap_stat" is *not* the same as
198 * WinPcap's "struct bpf_stat". It might currently have the
199 * same layout, but let's not cheat.
201 * Note also that we don't fill in ps_capt, as we might have
202 * been called by code compiled against an earlier version of
203 * WinPcap that didn't have ps_capt, in which case filling it
204 * in would stomp on whatever comes after the structure passed
207 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
208 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
209 GetLastError(), "PacketGetStats error");
212 ps
->ps_recv
= bstats
.bs_recv
;
213 ps
->ps_drop
= bstats
.bs_drop
;
216 * XXX - PacketGetStats() doesn't fill this in, so we just
220 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
229 * Win32-only routine for getting statistics.
231 * This way is definitely safer than passing the pcap_stat * from the userland.
232 * In fact, there could happen than the user allocates a variable which is not
233 * big enough for the new structure, and the library will write in a zone
234 * which is not allocated to this variable.
236 * In this way, we're pretty sure we are writing on memory allocated to this
239 * XXX - but this is the wrong way to handle statistics. Instead, we should
240 * have an API that returns data in a form like the Options section of a
241 * pcapng Interface Statistics Block:
243 * http://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
245 * which would let us add new statistics straightforwardly and indicate which
246 * statistics we are and are *not* providing, rather than having to provide
247 * possibly-bogus values for statistics we can't provide.
250 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
252 struct pcap_win
*pw
= p
->priv
;
253 struct bpf_stat bstats
;
255 *pcap_stat_size
= sizeof (p
->stat
);
258 * Try to get statistics.
260 * (Please note - "struct pcap_stat" is *not* the same as
261 * WinPcap's "struct bpf_stat". It might currently have the
262 * same layout, but let's not cheat.)
264 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
265 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
266 GetLastError(), "PacketGetStatsEx error");
269 p
->stat
.ps_recv
= bstats
.bs_recv
;
270 p
->stat
.ps_drop
= bstats
.bs_drop
;
271 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
273 p
->stat
.ps_capt
= bstats
.bs_capt
;
278 /* Set the dimension of the kernel-level capture buffer */
280 pcap_setbuff_npf(pcap_t
*p
, int dim
)
282 struct pcap_win
*pw
= p
->priv
;
284 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
286 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
292 /* Set the driver working mode */
294 pcap_setmode_npf(pcap_t
*p
, int mode
)
296 struct pcap_win
*pw
= p
->priv
;
298 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
300 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
307 /*set the minimum amount of data that will release a read call*/
309 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
311 struct pcap_win
*pw
= p
->priv
;
313 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
315 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
322 pcap_getevent_npf(pcap_t
*p
)
324 struct pcap_win
*pw
= p
->priv
;
326 return (PacketGetReadEvent(pw
->adapter
));
330 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
332 struct pcap_win
*pw
= p
->priv
;
334 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
338 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
341 struct pcap_win
*pw
= p
->priv
;
342 PACKET_OID_DATA
*oid_data_arg
;
345 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
346 * It should be big enough to hold "*lenp" bytes of data; it
347 * will actually be slightly larger, as PACKET_OID_DATA has a
348 * 1-byte data array at the end, standing in for the variable-length
349 * data that's actually there.
351 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
352 if (oid_data_arg
== NULL
) {
353 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
354 "Couldn't allocate argument buffer for PacketRequest");
358 oid_data_arg
->Oid
= oid
;
359 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
360 memcpy(oid_data_arg
->Data
, data
, *lenp
);
361 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
362 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
363 GetLastError(), "Error calling PacketRequest");
369 * Get the length actually copied.
371 *lenp
= oid_data_arg
->Length
;
374 * No need to copy the data - we're doing a set.
381 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
383 struct pcap_win
*pw
= p
->priv
;
386 if (pw
->adapter
==NULL
) {
387 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
388 "Cannot transmit a queue to an offline capture or to a TurboCap port");
392 res
= PacketSendPackets(pw
->adapter
,
397 if(res
!= queue
->len
){
398 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
399 GetLastError(), "Error opening adapter");
406 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
408 unsigned char *new_buff
;
411 /* Bogus parameter */
412 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
413 "Error: invalid size %d",size
);
417 /* Allocate the buffer */
418 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
421 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
422 "Error: not enough memory");
435 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
437 struct pcap_win
*pw
= p
->priv
;
440 /* Set the packet driver in dump mode */
441 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
443 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
444 "Error setting dump mode");
448 /* Set the name of the dump file */
449 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
451 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
452 "Error setting kernel dump file name");
456 /* Set the limits of the dump file */
457 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
459 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
460 "Error setting dump limit");
468 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
470 struct pcap_win
*pw
= p
->priv
;
472 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
475 static PAirpcapHandle
476 pcap_get_airpcap_handle_npf(pcap_t
*p
)
478 #ifdef HAVE_AIRPCAP_API
479 struct pcap_win
*pw
= p
->priv
;
481 return (PacketGetAirPcapHandle(pw
->adapter
));
484 #endif /* HAVE_AIRPCAP_API */
488 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
493 register u_char
*bp
, *ep
;
495 struct pcap_win
*pw
= p
->priv
;
500 * Has "pcap_breakloop()" been called?
504 * Yes - clear the flag that indicates that it
505 * has, and return PCAP_ERROR_BREAK to indicate
506 * that we were told to break out of the loop.
509 return (PCAP_ERROR_BREAK
);
513 * Capture the packets.
515 * The PACKET structure had a bunch of extra stuff for
516 * Windows 9x/Me, but the only interesting data in it
517 * in the versions of Windows that we support is just
518 * a copy of p->buffer, a copy of p->buflen, and the
519 * actual number of bytes read returned from
520 * PacketReceivePacket(), none of which has to be
521 * retained from call to call, so we just keep one on
524 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
525 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
527 * Did the device go away?
528 * If so, the error we get is ERROR_GEN_FAILURE.
530 DWORD errcode
= GetLastError();
532 if (errcode
== ERROR_GEN_FAILURE
) {
534 * The device on which we're capturing
535 * went away, or it became unusable
536 * by NPF due to a suspend/resume.
538 * XXX - hopefully no other error
539 * conditions are indicated by this.
541 * XXX - we really should return an
542 * appropriate error for that, but
543 * pcap_dispatch() etc. aren't
544 * documented as having error returns
545 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
547 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
548 "The interface disappeared");
550 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
551 PCAP_ERRBUF_SIZE
, errcode
,
552 "PacketReceivePacket error");
557 cc
= Packet
.ulBytesReceived
;
565 * Loop through each packet.
567 #define bhp ((struct bpf_hdr *)bp)
570 register int caplen
, hdrlen
;
573 * Has "pcap_breakloop()" been called?
574 * If so, return immediately - if we haven't read any
575 * packets, clear the flag and return PCAP_ERROR_BREAK
576 * to indicate that we were told to break out of the loop,
577 * otherwise leave the flag set, so that the *next* call
578 * will break out of the loop without having read any
579 * packets, and return the number of packets we've
585 return (PCAP_ERROR_BREAK
);
588 p
->cc
= (int) (ep
- bp
);
595 caplen
= bhp
->bh_caplen
;
596 hdrlen
= bhp
->bh_hdrlen
;
600 * Short-circuit evaluation: if using BPF filter
601 * in kernel, no need to do it now - we already know
602 * the packet passed the filter.
604 * XXX - pcap_filter() should always return TRUE if
605 * handed a null pointer for the program, but it might
606 * just try to "run" the filter, so we check here.
608 if (pw
->filtering_in_kernel
||
609 p
->fcode
.bf_insns
== NULL
||
610 pcap_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
612 switch (p
->rmt_samp
.method
) {
614 case PCAP_SAMP_1_EVERY_N
:
615 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
617 /* Discard all packets that are not '1 out of N' */
618 if (pw
->samp_npkt
!= 0) {
619 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
624 case PCAP_SAMP_FIRST_AFTER_N_MS
:
626 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
629 * Check if the timestamp of the arrived
630 * packet is smaller than our target time.
632 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
633 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
634 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
639 * The arrived packet is suitable for being
640 * delivered to our caller, so let's update
643 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
644 if (pw
->samp_time
.tv_usec
> 1000000) {
645 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
646 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
650 #endif /* ENABLE_REMOTE */
653 * XXX A bpf_hdr matches a pcap_pkthdr.
655 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
656 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
657 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
659 p
->cc
= (int) (ep
- bp
);
666 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
676 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
678 struct pcap_win
*pw
= p
->priv
;
681 int packet_len
= 0, caplen
= 0;
682 struct pcap_pkthdr pcap_header
;
685 dag_record_t
*header
;
686 unsigned erf_record_len
;
690 unsigned dfp
= pw
->adapter
->DagFastProcess
;
693 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
696 * Get new packets from the network.
698 * The PACKET structure had a bunch of extra stuff for
699 * Windows 9x/Me, but the only interesting data in it
700 * in the versions of Windows that we support is just
701 * a copy of p->buffer, a copy of p->buflen, and the
702 * actual number of bytes read returned from
703 * PacketReceivePacket(), none of which has to be
704 * retained from call to call, so we just keep one on
707 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
708 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
709 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
713 cc
= Packet
.ulBytesReceived
;
715 /* The timeout has expired but we no packets arrived */
717 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
720 header
= (dag_record_t
*)p
->bp
;
722 endofbuf
= (char*)header
+ cc
;
725 * Cycle through the packets
729 erf_record_len
= SWAPS(header
->rlen
);
730 if((char*)header
+ erf_record_len
> endofbuf
)
733 /* Increase the number of captured packets */
736 /* Find the beginning of the packet */
737 dp
= ((u_char
*)header
) + dag_record_size
;
739 /* Determine actual packet len */
743 packet_len
= ATM_SNAPLEN
;
744 caplen
= ATM_SNAPLEN
;
750 swt
= SWAPS(header
->wlen
);
751 packet_len
= swt
- (pw
->dag_fcs_bits
);
752 caplen
= erf_record_len
- dag_record_size
- 2;
753 if (caplen
> packet_len
)
762 swt
= SWAPS(header
->wlen
);
763 packet_len
= swt
- (pw
->dag_fcs_bits
);
764 caplen
= erf_record_len
- dag_record_size
;
765 if (caplen
> packet_len
)
773 if(caplen
> p
->snapshot
)
774 caplen
= p
->snapshot
;
777 * Has "pcap_breakloop()" been called?
778 * If so, return immediately - if we haven't read any
779 * packets, clear the flag and return -2 to indicate
780 * that we were told to break out of the loop, otherwise
781 * leave the flag set, so that the *next* call will break
782 * out of the loop without having read any packets, and
783 * return the number of packets we've processed so far.
794 p
->bp
= (char*)header
;
795 p
->cc
= endofbuf
- (char*)header
;
802 /* convert between timestamp formats */
804 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
805 ts
= (ts
& 0xffffffffi
64) * 1000000;
806 ts
+= 0x80000000; /* rounding */
807 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
808 if (pcap_header
.ts
.tv_usec
>= 1000000) {
809 pcap_header
.ts
.tv_usec
-= 1000000;
810 pcap_header
.ts
.tv_sec
++;
814 /* No underlaying filtering system. We need to filter on our own */
815 if (p
->fcode
.bf_insns
)
817 if (pcap_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
819 /* Move to next packet */
820 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
825 /* Fill the header for the user suppplied callback function */
826 pcap_header
.caplen
= caplen
;
827 pcap_header
.len
= packet_len
;
829 /* Call the callback function */
830 (*callback
)(user
, &pcap_header
, dp
);
832 /* Move to next packet */
833 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
835 /* Stop if the number of packets requested by user has been reached*/
836 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
838 p
->bp
= (char*)header
;
839 p
->cc
= endofbuf
- (char*)header
;
843 while((u_char
*)header
< endofbuf
);
847 #endif /* HAVE_DAG_API */
849 /* Send a packet to the network */
851 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
853 struct pcap_win
*pw
= p
->priv
;
856 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
857 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
858 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
863 * We assume it all got sent if "PacketSendPacket()" succeeded.
864 * "pcap_inject()" is expected to return the number of bytes
871 pcap_cleanup_npf(pcap_t
*p
)
873 struct pcap_win
*pw
= p
->priv
;
875 if (pw
->adapter
!= NULL
) {
876 PacketCloseAdapter(pw
->adapter
);
879 if (pw
->rfmon_selfstart
)
881 PacketSetMonitorMode(p
->opt
.device
, 0);
883 pcap_cleanup_live_common(p
);
887 pcap_breakloop_npf(pcap_t
*p
)
889 pcap_breakloop_common(p
);
890 struct pcap_win
*pw
= p
->priv
;
892 /* XXX - what if this fails? */
893 SetEvent(PacketGetReadEvent(pw
->adapter
));
897 pcap_activate_npf(pcap_t
*p
)
899 struct pcap_win
*pw
= p
->priv
;
906 * Monitor mode is supported on Windows Vista and later.
908 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
910 pw
->rfmon_selfstart
= 0;
914 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
916 pw
->rfmon_selfstart
= 0;
917 // Monitor mode is not supported.
920 return PCAP_ERROR_RFMON_NOTSUP
;
929 pw
->rfmon_selfstart
= 1;
937 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
939 if (pw
->adapter
== NULL
)
941 /* Adapter detected but we are not able to open it. Return failure. */
942 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
943 GetLastError(), "Error opening adapter");
944 if (pw
->rfmon_selfstart
)
946 PacketSetMonitorMode(p
->opt
.device
, 0);
952 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
954 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
955 GetLastError(), "Cannot determine the network type");
960 switch (type
.LinkType
)
963 p
->linktype
= DLT_EN10MB
;
966 case NdisMedium802_3
:
967 p
->linktype
= DLT_EN10MB
;
969 * This is (presumably) a real Ethernet capture; give it a
970 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
971 * that an application can let you choose it, in case you're
972 * capturing DOCSIS traffic that a Cisco Cable Modem
973 * Termination System is putting out onto an Ethernet (it
974 * doesn't put an Ethernet header onto the wire, it puts raw
975 * DOCSIS frames out on the wire inside the low-level
978 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
980 * If that fails, just leave the list empty.
982 if (p
->dlt_list
!= NULL
) {
983 p
->dlt_list
[0] = DLT_EN10MB
;
984 p
->dlt_list
[1] = DLT_DOCSIS
;
990 p
->linktype
= DLT_FDDI
;
993 case NdisMedium802_5
:
994 p
->linktype
= DLT_IEEE802
;
997 case NdisMediumArcnetRaw
:
998 p
->linktype
= DLT_ARCNET
;
1001 case NdisMediumArcnet878_2
:
1002 p
->linktype
= DLT_ARCNET
;
1006 p
->linktype
= DLT_ATM_RFC1483
;
1009 case NdisMediumCHDLC
:
1010 p
->linktype
= DLT_CHDLC
;
1013 case NdisMediumPPPSerial
:
1014 p
->linktype
= DLT_PPP_SERIAL
;
1017 case NdisMediumNull
:
1018 p
->linktype
= DLT_NULL
;
1021 case NdisMediumBare80211
:
1022 p
->linktype
= DLT_IEEE802_11
;
1025 case NdisMediumRadio80211
:
1026 p
->linktype
= DLT_IEEE802_11_RADIO
;
1030 p
->linktype
= DLT_PPI
;
1033 #ifdef NdisMediumWirelessWan
1034 case NdisMediumWirelessWan
:
1035 p
->linktype
= DLT_RAW
;
1041 * An unknown medium type is assumed to supply Ethernet
1042 * headers; if not, the user will have to report it,
1043 * so that the medium type and link-layer header type
1044 * can be determined. If we were to fail here, we
1045 * might get the link-layer type in the error, but
1046 * the user wouldn't get a capture, so we wouldn't
1047 * be able to determine the link-layer type; we report
1048 * a warning with the link-layer type, so at least
1049 * some programs will report the warning.
1051 p
->linktype
= DLT_EN10MB
;
1052 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1053 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1055 status
= PCAP_WARNING
;
1060 * Turn a negative snapshot value (invalid), a snapshot value of
1061 * 0 (unspecified), or a value bigger than the normal maximum
1062 * value, into the maximum allowed value.
1064 * If some application really *needs* a bigger snapshot
1065 * length, we should just increase MAXIMUM_SNAPLEN.
1067 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1068 p
->snapshot
= MAXIMUM_SNAPLEN
;
1070 /* Set promiscuous mode */
1074 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1076 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1082 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1083 * protocols and all packets indicated by the NIC" but if no protocol
1084 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1085 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1086 * capture incoming frames.
1088 if (PacketSetHwFilter(pw
->adapter
,
1089 NDIS_PACKET_TYPE_ALL_LOCAL
|
1090 NDIS_PACKET_TYPE_DIRECTED
|
1091 NDIS_PACKET_TYPE_BROADCAST
|
1092 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1094 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1099 /* Set the buffer size */
1100 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1102 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1105 * Traditional Adapter
1108 * If the buffer size wasn't explicitly set, default to
1109 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1111 if (p
->opt
.buffer_size
== 0)
1112 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1114 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1116 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1120 p
->buffer
= malloc(p
->bufsize
);
1121 if (p
->buffer
== NULL
)
1123 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1128 if (p
->opt
.immediate
)
1130 /* tell the driver to copy the buffer as soon as data arrives */
1131 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1133 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1134 PCAP_ERRBUF_SIZE
, GetLastError(),
1135 "Error calling PacketSetMinToCopy");
1141 /* tell the driver to copy the buffer only if it contains at least 16K */
1142 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1144 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1145 PCAP_ERRBUF_SIZE
, GetLastError(),
1146 "Error calling PacketSetMinToCopy");
1156 * We have DAG support.
1165 pcap_snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1166 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1167 strstr(_strlwr(p
->opt
.device
), "dag"));
1170 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1171 if(status
!= ERROR_SUCCESS
)
1174 status
= RegQueryValueEx(dagkey
,
1181 if(status
!= ERROR_SUCCESS
)
1186 RegCloseKey(dagkey
);
1191 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1193 /* Set the length of the FCS associated to any packet. This value
1194 * will be subtracted to the packet length */
1195 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1196 #else /* HAVE_DAG_API */
1201 #endif /* HAVE_DAG_API */
1204 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1206 /* disable loopback capture if requested */
1207 if (p
->opt
.nocapture_local
)
1209 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1211 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1212 "Unable to disable the capture of loopback packets.");
1218 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1220 /* install dag specific handlers for read and setfilter */
1221 p
->read_op
= pcap_read_win32_dag
;
1222 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1226 #endif /* HAVE_DAG_API */
1227 /* install traditional npf handlers for read and setfilter */
1228 p
->read_op
= pcap_read_npf
;
1229 p
->setfilter_op
= pcap_setfilter_npf
;
1232 #endif /* HAVE_DAG_API */
1233 p
->setdirection_op
= NULL
; /* Not implemented. */
1234 /* XXX - can this be implemented on some versions of Windows? */
1235 p
->inject_op
= pcap_inject_npf
;
1236 p
->set_datalink_op
= NULL
; /* can't change data link type */
1237 p
->getnonblock_op
= pcap_getnonblock_npf
;
1238 p
->setnonblock_op
= pcap_setnonblock_npf
;
1239 p
->stats_op
= pcap_stats_npf
;
1240 p
->breakloop_op
= pcap_breakloop_npf
;
1241 p
->stats_ex_op
= pcap_stats_ex_npf
;
1242 p
->setbuff_op
= pcap_setbuff_npf
;
1243 p
->setmode_op
= pcap_setmode_npf
;
1244 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1245 p
->getevent_op
= pcap_getevent_npf
;
1246 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1247 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1248 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1249 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1250 p
->live_dump_op
= pcap_live_dump_npf
;
1251 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1252 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1253 p
->cleanup_op
= pcap_cleanup_npf
;
1256 * XXX - this is only done because WinPcap supported
1257 * pcap_fileno() returning the hFile HANDLE from the
1258 * ADAPTER structure. We make no general guarantees
1259 * that the caller can do anything useful with it.
1261 * (Not that we make any general guarantee of that
1262 * sort on UN*X, either, any more, given that not
1263 * all capture devices are regular OS network
1266 p
->handle
= pw
->adapter
->hFile
;
1270 pcap_cleanup_npf(p
);
1271 return (PCAP_ERROR
);
1275 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1278 pcap_can_set_rfmon_npf(pcap_t
*p
)
1280 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1284 pcap_create_interface(const char *device _U_
, char *ebuf
)
1288 p
= pcap_create_common(ebuf
, sizeof(struct pcap_win
));
1292 p
->activate_op
= pcap_activate_npf
;
1293 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1298 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1300 struct pcap_win
*pw
= p
->priv
;
1302 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1304 * Kernel filter not installed.
1306 * XXX - we don't know whether this failed because:
1308 * the kernel rejected the filter program as invalid,
1309 * in which case we should fall back on userland
1312 * the kernel rejected the filter program as too big,
1313 * in which case we should again fall back on
1314 * userland filtering;
1316 * there was some other problem, in which case we
1317 * should probably report an error.
1319 * For NPF devices, the Win32 status will be
1320 * STATUS_INVALID_DEVICE_REQUEST for invalid
1321 * filters, but I don't know what it'd be for
1322 * other problems, and for some other devices
1323 * it might not be set at all.
1325 * So we just fall back on userland filtering in
1330 * install_bpf_program() validates the program.
1332 * XXX - what if we already have a filter in the kernel?
1334 if (install_bpf_program(p
, fp
) < 0)
1336 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1343 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1346 * Discard any previously-received packets, as they might have
1347 * passed whatever filter was formerly in effect, but might
1348 * not pass this filter (BIOCSETF discards packets buffered
1349 * in the kernel, so you can lose packets in any case).
1356 * We filter at user level, since the kernel driver does't process the packets
1359 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1363 pcap_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1367 /* Install a user level filter */
1368 if (install_bpf_program(p
, fp
) < 0)
1375 pcap_getnonblock_npf(pcap_t
*p
)
1377 struct pcap_win
*pw
= p
->priv
;
1380 * XXX - if there were a PacketGetReadTimeout() call, we
1381 * would use it, and return 1 if the timeout is -1
1384 return (pw
->nonblock
);
1388 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1390 struct pcap_win
*pw
= p
->priv
;
1395 * Set the packet buffer timeout to -1 for non-blocking
1401 * Restore the timeout set when the device was opened.
1402 * (Note that this may be -1, in which case we're not
1403 * really leaving non-blocking mode. However, although
1404 * the timeout argument to pcap_set_timeout() and
1405 * pcap_open_live() is an int, you're not supposed to
1406 * supply a negative value, so that "shouldn't happen".)
1408 newtimeout
= p
->opt
.timeout
;
1410 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1411 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1412 GetLastError(), "PacketSetReadTimeout");
1415 pw
->nonblock
= (newtimeout
== -1);
1420 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1421 const char *description
, char *errbuf
)
1424 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1428 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1431 * Add an entry for this interface, with no addresses.
1433 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1434 if (curdev
== NULL
) {
1442 * Get the list of addresses for the interface.
1444 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1448 * We don't return an error, because this can happen with
1449 * NdisWan interfaces, and we want to supply them even
1450 * if we can't supply their addresses.
1452 * We return an entry with an empty address list.
1458 * Now add the addresses.
1460 while (if_addr_size
-- > 0) {
1462 * "curdev" is an entry for this interface; add an entry for
1463 * this address to its list of addresses.
1465 res
= add_addr_to_dev(curdev
,
1466 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1467 sizeof (struct sockaddr_storage
),
1468 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1469 sizeof (struct sockaddr_storage
),
1470 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1471 sizeof (struct sockaddr_storage
),
1487 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1493 NDIS_HARDWARE_STATUS hardware_status
;
1494 #ifdef OID_GEN_PHYSICAL_MEDIUM
1495 NDIS_PHYSICAL_MEDIUM phys_medium
;
1496 bpf_u_int32 gen_physical_medium_oids
[] = {
1497 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1498 OID_GEN_PHYSICAL_MEDIUM_EX
,
1500 OID_GEN_PHYSICAL_MEDIUM
1502 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1504 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1505 #ifdef OID_GEN_LINK_STATE
1506 NDIS_LINK_STATE link_state
;
1510 if (*flags
& PCAP_IF_LOOPBACK
) {
1512 * Loopback interface, so the connection status doesn't
1513 * apply. and it's not wireless (or wired, for that
1514 * matter...). We presume it's up and running.
1516 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1521 * We need to open the adapter to get this information.
1523 * XXX - PacketOpenAdapter() takes a non-const pointer
1524 * as an argument, so we make a copy of the argument and
1527 name_copy
= strdup(name
);
1528 adapter
= PacketOpenAdapter(name_copy
);
1530 if (adapter
== NULL
) {
1532 * Give up; if they try to open this device, it'll fail.
1537 #ifdef HAVE_AIRPCAP_API
1539 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1540 * Just set these flags (and none of the '*flags' entered with).
1542 if (PacketGetAirPcapHandle(adapter
)) {
1544 * Must be "up" and "running" if the above if succeeded.
1546 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1549 * An airpcap device is a wireless device (duh!)
1551 *flags
|= PCAP_IF_WIRELESS
;
1554 * A "network assosiation state" makes no sense for airpcap.
1556 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1557 PacketCloseAdapter(adapter
);
1563 * Get the hardware status, and derive "up" and "running" from
1566 len
= sizeof (hardware_status
);
1567 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1568 &hardware_status
, &len
, errbuf
);
1570 switch (hardware_status
) {
1572 case NdisHardwareStatusReady
:
1574 * "Available and capable of sending and receiving
1575 * data over the wire", so up and running.
1577 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1580 case NdisHardwareStatusInitializing
:
1581 case NdisHardwareStatusReset
:
1583 * "Initializing" or "Resetting", so up, but
1586 *flags
|= PCAP_IF_UP
;
1589 case NdisHardwareStatusClosing
:
1590 case NdisHardwareStatusNotReady
:
1592 * "Closing" or "Not ready", so neither up nor
1599 * Can't get the hardware status, so assume both up and
1602 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1606 * Get the network type.
1608 #ifdef OID_GEN_PHYSICAL_MEDIUM
1610 * Try the OIDs we have for this, in order.
1612 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1613 len
= sizeof (phys_medium
);
1614 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1615 &phys_medium
, &len
, errbuf
);
1623 * Failed. We can't determine whether it failed
1624 * because that particular OID isn't supported
1625 * or because some other problem occurred, so we
1626 * just drive on and try the next OID.
1631 * We got the physical medium.
1633 switch (phys_medium
) {
1635 case NdisPhysicalMediumWirelessLan
:
1636 case NdisPhysicalMediumWirelessWan
:
1637 case NdisPhysicalMediumNative802_11
:
1638 case NdisPhysicalMediumBluetooth
:
1639 case NdisPhysicalMediumUWB
:
1640 case NdisPhysicalMediumIrda
:
1644 *flags
|= PCAP_IF_WIRELESS
;
1657 * Get the connection status.
1659 #ifdef OID_GEN_LINK_STATE
1660 len
= sizeof(link_state
);
1661 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
1665 * NOTE: this also gives us the receive and transmit
1668 switch (link_state
.MediaConnectState
) {
1670 case MediaConnectStateConnected
:
1674 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1677 case MediaConnectStateDisconnected
:
1679 * It's disconnected.
1681 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1687 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1693 * OK, OID_GEN_LINK_STATE didn't work, try
1694 * OID_GEN_MEDIA_CONNECT_STATUS.
1696 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1697 &connect_status
, &len
, errbuf
);
1699 switch (connect_status
) {
1701 case NdisMediaStateConnected
:
1705 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1708 case NdisMediaStateDisconnected
:
1710 * It's disconnected.
1712 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1717 PacketCloseAdapter(adapter
);
1722 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1731 * Find out how big a buffer we need.
1733 * This call should always return FALSE; if the error is
1734 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1735 * the size of the buffer we need, otherwise there's a
1736 * problem, and NameLength should be set to 0.
1738 * It shouldn't require NameLength to be set, but,
1739 * at least as of WinPcap 4.1.3, it checks whether
1740 * NameLength is big enough before it checks for a
1741 * NULL buffer argument, so, while it'll still do
1742 * the right thing if NameLength is uninitialized and
1743 * whatever junk happens to be there is big enough
1744 * (because the pointer argument will be null), it's
1745 * still reading an uninitialized variable.
1748 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1750 DWORD last_error
= GetLastError();
1752 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1754 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1755 last_error
, "PacketGetAdapterNames");
1760 if (NameLength
<= 0)
1762 AdaptersName
= (char*) malloc(NameLength
);
1763 if (AdaptersName
== NULL
)
1765 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1769 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1770 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1771 GetLastError(), "PacketGetAdapterNames");
1777 * "PacketGetAdapterNames()" returned a list of
1778 * null-terminated ASCII interface name strings,
1779 * terminated by a null string, followed by a list
1780 * of null-terminated ASCII interface description
1781 * strings, terminated by a null string.
1782 * This means there are two ASCII nulls at the end
1783 * of the first list.
1785 * Find the end of the first list; that's the
1786 * beginning of the second list.
1788 desc
= &AdaptersName
[0];
1789 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1793 * Found it - "desc" points to the first of the two
1794 * nulls at the end of the list of names, so the
1795 * first byte of the list of descriptions is two bytes
1801 * Loop over the elements in the first list.
1803 name
= &AdaptersName
[0];
1804 while (*name
!= '\0') {
1805 bpf_u_int32 flags
= 0;
1806 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1808 * Is this a loopback interface?
1810 if (PacketIsLoopbackAdapter(name
)) {
1812 flags
|= PCAP_IF_LOOPBACK
;
1816 * Get additional flags.
1818 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1827 * Add an entry for this interface.
1829 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1837 name
+= strlen(name
) + 1;
1838 desc
+= strlen(desc
) + 1;
1846 * Return the name of a network interface attached to the system, or NULL
1847 * if none can be found. The interface must be configured up; the
1848 * lowest unit number is preferred; loopback is ignored.
1850 * In the best of all possible worlds, this would be the same as on
1851 * UN*X, but there may be software that expects this to return a
1852 * full list of devices after the first device.
1854 #define ADAPTERSNAME_LEN 8192
1856 pcap_lookupdev(char *errbuf
)
1859 DWORD dwWindowsMajorVersion
;
1861 #pragma warning (push)
1862 #pragma warning (disable: 4996) /* disable MSVC's GetVersion() deprecated warning here */
1863 dwVersion
= GetVersion(); /* get the OS version */
1864 #pragma warning (pop)
1865 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1867 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1869 * Windows 95, 98, ME.
1871 ULONG NameLength
= ADAPTERSNAME_LEN
;
1872 static char AdaptersName
[ADAPTERSNAME_LEN
];
1874 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1875 return (AdaptersName
);
1880 * Windows NT (NT 4.0 and later).
1881 * Convert the names to Unicode for backward compatibility.
1883 ULONG NameLength
= ADAPTERSNAME_LEN
;
1884 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1885 size_t BufferSpaceLeft
;
1890 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
1893 if(TAdaptersName
== NULL
)
1895 (void)pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
1899 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
1901 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1902 GetLastError(), "PacketGetAdapterNames");
1903 free(TAdaptersName
);
1908 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
1909 tAstr
= (char*)TAdaptersName
;
1910 Unameptr
= AdaptersName
;
1913 * Convert the device names to Unicode into AdapterName.
1917 * Length of the name, including the terminating
1920 namelen
= strlen(tAstr
) + 1;
1923 * Do we have room for the name in the Unicode
1926 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
1932 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
1935 * Copy the name, converting ASCII to Unicode.
1936 * namelen includes the NUL, so we copy it as
1939 for (i
= 0; i
< namelen
; i
++)
1940 *Unameptr
++ = *tAstr
++;
1943 * Count this adapter.
1946 } while (namelen
!= 1);
1949 * Copy the descriptions, but don't convert them from
1952 Adescptr
= (char *)Unameptr
;
1957 desclen
= strlen(tAstr
) + 1;
1960 * Do we have room for the name in the Unicode
1963 if (BufferSpaceLeft
< desclen
) {
1971 * Just copy the ASCII string.
1972 * namelen includes the NUL, so we copy it as
1975 memcpy(Adescptr
, tAstr
, desclen
);
1976 Adescptr
+= desclen
;
1978 BufferSpaceLeft
-= desclen
;
1982 free(TAdaptersName
);
1983 return (char *)(AdaptersName
);
1988 * We can't use the same code that we use on UN*X, as that's doing
1989 * UN*X-specific calls.
1991 * We don't just fetch the entire list of devices, search for the
1992 * particular device, and use its first IPv4 address, as that's too
1993 * much work to get just one device's netmask.
1996 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2000 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2001 * in order to skip non IPv4 (i.e. IPv6 addresses)
2003 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2004 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2005 struct sockaddr_in
*t_addr
;
2008 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2013 for(i
= 0; i
< if_addr_size
; i
++)
2015 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2017 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2018 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2019 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2020 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2032 static const char *pcap_lib_version_string
;
2034 #ifdef HAVE_VERSION_H
2036 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2037 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2040 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2041 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2042 * for the packet.dll version number as well.)
2044 #include "../../version.h"
2046 static const char pcap_version_string
[] =
2047 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2050 pcap_lib_version(void)
2052 if (pcap_lib_version_string
== NULL
) {
2054 * Generate the version string.
2056 char *packet_version_string
= PacketGetVersion();
2058 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2060 * WinPcap/Npcap version string and packet.dll version
2061 * string are the same; just report the WinPcap/Npcap
2064 pcap_lib_version_string
= pcap_version_string
;
2067 * WinPcap/Npcap version string and packet.dll version
2068 * string are different; that shouldn't be the
2069 * case (the two libraries should come from the
2070 * same version of WinPcap/Npcap), so we report both
2073 char *full_pcap_version_string
;
2075 if (pcap_asprintf(&full_pcap_version_string
,
2076 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
,
2077 packet_version_string
) != -1) {
2079 pcap_lib_version_string
= full_pcap_version_string
;
2083 return (pcap_lib_version_string
);
2086 #else /* HAVE_VERSION_H */
2089 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2093 pcap_lib_version(void)
2095 if (pcap_lib_version_string
== NULL
) {
2097 * Generate the version string. Report the packet.dll
2100 char *full_pcap_version_string
;
2102 if (pcap_asprintf(&full_pcap_version_string
,
2103 PCAP_VERSION_STRING
" (packet.dll version %s)",
2104 PacketGetVersion()) != -1) {
2106 pcap_lib_version_string
= full_pcap_version_string
;
2109 return (pcap_lib_version_string
);
2111 #endif /* HAVE_VERSION_H */