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 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 char errmsgbuf
[PCAP_ERRBUF_SIZE
+1];
171 pcap_win32_err_to_str(GetLastError(), errmsgbuf
);
172 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
173 "Error calling PacketRequest: %s", errmsgbuf
);
179 * Get the length actually supplied.
181 *lenp
= oid_data_arg
->Length
;
184 * Copy back the data we fetched.
186 memcpy(data
, oid_data_arg
->Data
, *lenp
);
192 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
194 struct pcap_win
*pw
= p
->priv
;
195 struct bpf_stat bstats
;
196 char errbuf
[PCAP_ERRBUF_SIZE
+1];
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_win32_err_to_str(GetLastError(), errbuf
);
213 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
214 "PacketGetStats error: %s", errbuf
);
217 ps
->ps_recv
= bstats
.bs_recv
;
218 ps
->ps_drop
= bstats
.bs_drop
;
221 * XXX - PacketGetStats() doesn't fill this in, so we just
225 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
234 * Win32-only routine for getting statistics.
236 * This way is definitely safer than passing the pcap_stat * from the userland.
237 * In fact, there could happen than the user allocates a variable which is not
238 * big enough for the new structure, and the library will write in a zone
239 * which is not allocated to this variable.
241 * In this way, we're pretty sure we are writing on memory allocated to this
244 * XXX - but this is the wrong way to handle statistics. Instead, we should
245 * have an API that returns data in a form like the Options section of a
246 * pcapng Interface Statistics Block:
248 * 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
250 * which would let us add new statistics straightforwardly and indicate which
251 * statistics we are and are *not* providing, rather than having to provide
252 * possibly-bogus values for statistics we can't provide.
255 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
257 struct pcap_win
*pw
= p
->priv
;
258 struct bpf_stat bstats
;
259 char errbuf
[PCAP_ERRBUF_SIZE
+1];
261 *pcap_stat_size
= sizeof (p
->stat
);
264 * Try to get statistics.
266 * (Please note - "struct pcap_stat" is *not* the same as
267 * WinPcap's "struct bpf_stat". It might currently have the
268 * same layout, but let's not cheat.)
270 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
271 pcap_win32_err_to_str(GetLastError(), errbuf
);
272 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
273 "PacketGetStatsEx error: %s", errbuf
);
276 p
->stat
.ps_recv
= bstats
.bs_recv
;
277 p
->stat
.ps_drop
= bstats
.bs_drop
;
278 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
280 p
->stat
.ps_capt
= bstats
.bs_capt
;
285 /* Set the dimension of the kernel-level capture buffer */
287 pcap_setbuff_npf(pcap_t
*p
, int dim
)
289 struct pcap_win
*pw
= p
->priv
;
291 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
293 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
299 /* Set the driver working mode */
301 pcap_setmode_npf(pcap_t
*p
, int mode
)
303 struct pcap_win
*pw
= p
->priv
;
305 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
307 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
314 /*set the minimum amount of data that will release a read call*/
316 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
318 struct pcap_win
*pw
= p
->priv
;
320 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
322 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
329 pcap_getevent_npf(pcap_t
*p
)
331 struct pcap_win
*pw
= p
->priv
;
333 return (PacketGetReadEvent(pw
->adapter
));
337 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
339 struct pcap_win
*pw
= p
->priv
;
341 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
345 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
348 struct pcap_win
*pw
= p
->priv
;
349 PACKET_OID_DATA
*oid_data_arg
;
350 char errbuf
[PCAP_ERRBUF_SIZE
+1];
353 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
354 * It should be big enough to hold "*lenp" bytes of data; it
355 * will actually be slightly larger, as PACKET_OID_DATA has a
356 * 1-byte data array at the end, standing in for the variable-length
357 * data that's actually there.
359 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
360 if (oid_data_arg
== NULL
) {
361 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
362 "Couldn't allocate argument buffer for PacketRequest");
366 oid_data_arg
->Oid
= oid
;
367 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
368 memcpy(oid_data_arg
->Data
, data
, *lenp
);
369 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
370 pcap_win32_err_to_str(GetLastError(), errbuf
);
371 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
372 "Error calling PacketRequest: %s", errbuf
);
378 * Get the length actually copied.
380 *lenp
= oid_data_arg
->Length
;
383 * No need to copy the data - we're doing a set.
390 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
392 struct pcap_win
*pw
= p
->priv
;
394 char errbuf
[PCAP_ERRBUF_SIZE
+1];
396 if (pw
->adapter
==NULL
) {
397 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
398 "Cannot transmit a queue to an offline capture or to a TurboCap port");
402 res
= PacketSendPackets(pw
->adapter
,
407 if(res
!= queue
->len
){
408 pcap_win32_err_to_str(GetLastError(), errbuf
);
409 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
410 "Error opening adapter: %s", errbuf
);
417 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
419 unsigned char *new_buff
;
422 /* Bogus parameter */
423 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
424 "Error: invalid size %d",size
);
428 /* Allocate the buffer */
429 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
432 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
433 "Error: not enough memory");
446 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
448 struct pcap_win
*pw
= p
->priv
;
451 /* Set the packet driver in dump mode */
452 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
454 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
455 "Error setting dump mode");
459 /* Set the name of the dump file */
460 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
462 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
463 "Error setting kernel dump file name");
467 /* Set the limits of the dump file */
468 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
470 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
471 "Error setting dump limit");
479 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
481 struct pcap_win
*pw
= p
->priv
;
483 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
486 static PAirpcapHandle
487 pcap_get_airpcap_handle_npf(pcap_t
*p
)
489 #ifdef HAVE_AIRPCAP_API
490 struct pcap_win
*pw
= p
->priv
;
492 return (PacketGetAirPcapHandle(pw
->adapter
));
495 #endif /* HAVE_AIRPCAP_API */
499 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
504 register u_char
*bp
, *ep
;
506 struct pcap_win
*pw
= p
->priv
;
511 * Has "pcap_breakloop()" been called?
515 * Yes - clear the flag that indicates that it
516 * has, and return PCAP_ERROR_BREAK to indicate
517 * that we were told to break out of the loop.
520 return (PCAP_ERROR_BREAK
);
524 * Capture the packets.
526 * The PACKET structure had a bunch of extra stuff for
527 * Windows 9x/Me, but the only interesting data in it
528 * in the versions of Windows that we support is just
529 * a copy of p->buffer, a copy of p->buflen, and the
530 * actual number of bytes read returned from
531 * PacketReceivePacket(), none of which has to be
532 * retained from call to call, so we just keep one on
535 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
536 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
537 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
541 cc
= Packet
.ulBytesReceived
;
549 * Loop through each packet.
551 #define bhp ((struct bpf_hdr *)bp)
554 register int caplen
, hdrlen
;
557 * Has "pcap_breakloop()" been called?
558 * If so, return immediately - if we haven't read any
559 * packets, clear the flag and return PCAP_ERROR_BREAK
560 * to indicate that we were told to break out of the loop,
561 * otherwise leave the flag set, so that the *next* call
562 * will break out of the loop without having read any
563 * packets, and return the number of packets we've
569 return (PCAP_ERROR_BREAK
);
572 p
->cc
= (int) (ep
- bp
);
579 caplen
= bhp
->bh_caplen
;
580 hdrlen
= bhp
->bh_hdrlen
;
584 * Short-circuit evaluation: if using BPF filter
585 * in kernel, no need to do it now - we already know
586 * the packet passed the filter.
588 * XXX - bpf_filter() should always return TRUE if
589 * handed a null pointer for the program, but it might
590 * just try to "run" the filter, so we check here.
592 if (pw
->filtering_in_kernel
||
593 p
->fcode
.bf_insns
== NULL
||
594 bpf_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
596 switch (p
->rmt_samp
.method
) {
598 case PCAP_SAMP_1_EVERY_N
:
599 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
601 /* Discard all packets that are not '1 out of N' */
602 if (pw
->samp_npkt
!= 0) {
603 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
608 case PCAP_SAMP_FIRST_AFTER_N_MS
:
610 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
613 * Check if the timestamp of the arrived
614 * packet is smaller than our target time.
616 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
617 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
618 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
623 * The arrived packet is suitable for being
624 * delivered to our caller, so let's update
627 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
628 if (pw
->samp_time
.tv_usec
> 1000000) {
629 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
630 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
634 #endif /* ENABLE_REMOTE */
637 * XXX A bpf_hdr matches a pcap_pkthdr.
639 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
640 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
641 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
643 p
->cc
= (int) (ep
- bp
);
650 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
660 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
662 struct pcap_win
*pw
= p
->priv
;
665 int packet_len
= 0, caplen
= 0;
666 struct pcap_pkthdr pcap_header
;
669 dag_record_t
*header
;
670 unsigned erf_record_len
;
674 unsigned dfp
= pw
->adapter
->DagFastProcess
;
677 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
680 * Get new packets from the network.
682 * The PACKET structure had a bunch of extra stuff for
683 * Windows 9x/Me, but the only interesting data in it
684 * in the versions of Windows that we support is just
685 * a copy of p->buffer, a copy of p->buflen, and the
686 * actual number of bytes read returned from
687 * PacketReceivePacket(), none of which has to be
688 * retained from call to call, so we just keep one on
691 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
692 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
693 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
697 cc
= Packet
.ulBytesReceived
;
699 /* The timeout has expired but we no packets arrived */
701 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
704 header
= (dag_record_t
*)p
->bp
;
706 endofbuf
= (char*)header
+ cc
;
709 * Cycle through the packets
713 erf_record_len
= SWAPS(header
->rlen
);
714 if((char*)header
+ erf_record_len
> endofbuf
)
717 /* Increase the number of captured packets */
720 /* Find the beginning of the packet */
721 dp
= ((u_char
*)header
) + dag_record_size
;
723 /* Determine actual packet len */
727 packet_len
= ATM_SNAPLEN
;
728 caplen
= ATM_SNAPLEN
;
734 swt
= SWAPS(header
->wlen
);
735 packet_len
= swt
- (pw
->dag_fcs_bits
);
736 caplen
= erf_record_len
- dag_record_size
- 2;
737 if (caplen
> packet_len
)
746 swt
= SWAPS(header
->wlen
);
747 packet_len
= swt
- (pw
->dag_fcs_bits
);
748 caplen
= erf_record_len
- dag_record_size
;
749 if (caplen
> packet_len
)
757 if(caplen
> p
->snapshot
)
758 caplen
= p
->snapshot
;
761 * Has "pcap_breakloop()" been called?
762 * If so, return immediately - if we haven't read any
763 * packets, clear the flag and return -2 to indicate
764 * that we were told to break out of the loop, otherwise
765 * leave the flag set, so that the *next* call will break
766 * out of the loop without having read any packets, and
767 * return the number of packets we've processed so far.
778 p
->bp
= (char*)header
;
779 p
->cc
= endofbuf
- (char*)header
;
786 /* convert between timestamp formats */
788 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
789 ts
= (ts
& 0xffffffffi
64) * 1000000;
790 ts
+= 0x80000000; /* rounding */
791 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
792 if (pcap_header
.ts
.tv_usec
>= 1000000) {
793 pcap_header
.ts
.tv_usec
-= 1000000;
794 pcap_header
.ts
.tv_sec
++;
798 /* No underlaying filtering system. We need to filter on our own */
799 if (p
->fcode
.bf_insns
)
801 if (bpf_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
803 /* Move to next packet */
804 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
809 /* Fill the header for the user suppplied callback function */
810 pcap_header
.caplen
= caplen
;
811 pcap_header
.len
= packet_len
;
813 /* Call the callback function */
814 (*callback
)(user
, &pcap_header
, dp
);
816 /* Move to next packet */
817 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
819 /* Stop if the number of packets requested by user has been reached*/
820 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
822 p
->bp
= (char*)header
;
823 p
->cc
= endofbuf
- (char*)header
;
827 while((u_char
*)header
< endofbuf
);
831 #endif /* HAVE_DAG_API */
833 /* Send a packet to the network */
835 pcap_inject_npf(pcap_t
*p
, const void *buf
, size_t size
)
837 struct pcap_win
*pw
= p
->priv
;
840 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
841 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
842 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
847 * We assume it all got sent if "PacketSendPacket()" succeeded.
848 * "pcap_inject()" is expected to return the number of bytes
855 pcap_cleanup_npf(pcap_t
*p
)
857 struct pcap_win
*pw
= p
->priv
;
859 if (pw
->adapter
!= NULL
) {
860 PacketCloseAdapter(pw
->adapter
);
863 if (pw
->rfmon_selfstart
)
865 PacketSetMonitorMode(p
->opt
.device
, 0);
867 pcap_cleanup_live_common(p
);
871 pcap_activate_npf(pcap_t
*p
)
873 struct pcap_win
*pw
= p
->priv
;
876 char errbuf
[PCAP_ERRBUF_SIZE
+1];
880 * Monitor mode is supported on Windows Vista and later.
882 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
884 pw
->rfmon_selfstart
= 0;
888 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
890 pw
->rfmon_selfstart
= 0;
891 // Monitor mode is not supported.
894 return PCAP_ERROR_RFMON_NOTSUP
;
903 pw
->rfmon_selfstart
= 1;
911 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
913 if (pw
->adapter
== NULL
)
915 /* Adapter detected but we are not able to open it. Return failure. */
916 pcap_win32_err_to_str(GetLastError(), errbuf
);
917 if (pw
->rfmon_selfstart
)
919 PacketSetMonitorMode(p
->opt
.device
, 0);
921 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
922 "Error opening adapter: %s", errbuf
);
927 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
929 pcap_win32_err_to_str(GetLastError(), errbuf
);
930 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
931 "Cannot determine the network type: %s", errbuf
);
936 switch (type
.LinkType
)
939 p
->linktype
= DLT_EN10MB
;
942 case NdisMedium802_3
:
943 p
->linktype
= DLT_EN10MB
;
945 * This is (presumably) a real Ethernet capture; give it a
946 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
947 * that an application can let you choose it, in case you're
948 * capturing DOCSIS traffic that a Cisco Cable Modem
949 * Termination System is putting out onto an Ethernet (it
950 * doesn't put an Ethernet header onto the wire, it puts raw
951 * DOCSIS frames out on the wire inside the low-level
954 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
956 * If that fails, just leave the list empty.
958 if (p
->dlt_list
!= NULL
) {
959 p
->dlt_list
[0] = DLT_EN10MB
;
960 p
->dlt_list
[1] = DLT_DOCSIS
;
966 p
->linktype
= DLT_FDDI
;
969 case NdisMedium802_5
:
970 p
->linktype
= DLT_IEEE802
;
973 case NdisMediumArcnetRaw
:
974 p
->linktype
= DLT_ARCNET
;
977 case NdisMediumArcnet878_2
:
978 p
->linktype
= DLT_ARCNET
;
982 p
->linktype
= DLT_ATM_RFC1483
;
985 case NdisMediumCHDLC
:
986 p
->linktype
= DLT_CHDLC
;
989 case NdisMediumPPPSerial
:
990 p
->linktype
= DLT_PPP_SERIAL
;
994 p
->linktype
= DLT_NULL
;
997 case NdisMediumBare80211
:
998 p
->linktype
= DLT_IEEE802_11
;
1001 case NdisMediumRadio80211
:
1002 p
->linktype
= DLT_IEEE802_11_RADIO
;
1006 p
->linktype
= DLT_PPI
;
1010 p
->linktype
= DLT_EN10MB
; /*an unknown adapter is assumed to be ethernet*/
1015 * Turn a negative snapshot value (invalid), a snapshot value of
1016 * 0 (unspecified), or a value bigger than the normal maximum
1017 * value, into the maximum allowed value.
1019 * If some application really *needs* a bigger snapshot
1020 * length, we should just increase MAXIMUM_SNAPLEN.
1022 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1023 p
->snapshot
= MAXIMUM_SNAPLEN
;
1025 /* Set promiscuous mode */
1029 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1031 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1037 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_ALL_LOCAL
) == FALSE
)
1039 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1044 /* Set the buffer size */
1045 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1047 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1050 * Traditional Adapter
1053 * If the buffer size wasn't explicitly set, default to
1054 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1056 if (p
->opt
.buffer_size
== 0)
1057 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1059 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1061 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1065 p
->buffer
= malloc(p
->bufsize
);
1066 if (p
->buffer
== NULL
)
1068 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1073 if (p
->opt
.immediate
)
1075 /* tell the driver to copy the buffer as soon as data arrives */
1076 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1078 pcap_win32_err_to_str(GetLastError(), errbuf
);
1079 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1080 "Error calling PacketSetMinToCopy: %s",
1087 /* tell the driver to copy the buffer only if it contains at least 16K */
1088 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1090 pcap_win32_err_to_str(GetLastError(), errbuf
);
1091 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1092 "Error calling PacketSetMinToCopy: %s",
1103 * We have DAG support.
1112 pcap_snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1113 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1114 strstr(_strlwr(p
->opt
.device
), "dag"));
1117 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1118 if(status
!= ERROR_SUCCESS
)
1121 status
= RegQueryValueEx(dagkey
,
1128 if(status
!= ERROR_SUCCESS
)
1133 RegCloseKey(dagkey
);
1138 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1140 /* Set the length of the FCS associated to any packet. This value
1141 * will be subtracted to the packet length */
1142 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1143 #else /* HAVE_DAG_API */
1148 #endif /* HAVE_DAG_API */
1151 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1153 /* disable loopback capture if requested */
1154 if (p
->opt
.nocapture_local
)
1156 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1158 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1159 "Unable to disable the capture of loopback packets.");
1165 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1167 /* install dag specific handlers for read and setfilter */
1168 p
->read_op
= pcap_read_win32_dag
;
1169 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1173 #endif /* HAVE_DAG_API */
1174 /* install traditional npf handlers for read and setfilter */
1175 p
->read_op
= pcap_read_npf
;
1176 p
->setfilter_op
= pcap_setfilter_npf
;
1179 #endif /* HAVE_DAG_API */
1180 p
->setdirection_op
= NULL
; /* Not implemented. */
1181 /* XXX - can this be implemented on some versions of Windows? */
1182 p
->inject_op
= pcap_inject_npf
;
1183 p
->set_datalink_op
= NULL
; /* can't change data link type */
1184 p
->getnonblock_op
= pcap_getnonblock_npf
;
1185 p
->setnonblock_op
= pcap_setnonblock_npf
;
1186 p
->stats_op
= pcap_stats_npf
;
1187 p
->stats_ex_op
= pcap_stats_ex_npf
;
1188 p
->setbuff_op
= pcap_setbuff_npf
;
1189 p
->setmode_op
= pcap_setmode_npf
;
1190 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1191 p
->getevent_op
= pcap_getevent_npf
;
1192 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1193 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1194 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1195 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1196 p
->live_dump_op
= pcap_live_dump_npf
;
1197 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1198 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1199 p
->cleanup_op
= pcap_cleanup_npf
;
1202 * XXX - this is only done because WinPcap supported
1203 * pcap_fileno() returning the hFile HANDLE from the
1204 * ADAPTER structure. We make no general guarantees
1205 * that the caller can do anything useful with it.
1207 * (Not that we make any general guarantee of that
1208 * sort on UN*X, either, any more, given that not
1209 * all capture devices are regular OS network
1212 p
->handle
= pw
->adapter
->hFile
;
1216 pcap_cleanup_npf(p
);
1217 return (PCAP_ERROR
);
1221 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1224 pcap_can_set_rfmon_npf(pcap_t
*p
)
1226 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1230 pcap_create_interface(const char *device _U_
, char *ebuf
)
1234 p
= pcap_create_common(ebuf
, sizeof(struct pcap_win
));
1238 p
->activate_op
= pcap_activate_npf
;
1239 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1244 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1246 struct pcap_win
*pw
= p
->priv
;
1248 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1250 * Kernel filter not installed.
1252 * XXX - we don't know whether this failed because:
1254 * the kernel rejected the filter program as invalid,
1255 * in which case we should fall back on userland
1258 * the kernel rejected the filter program as too big,
1259 * in which case we should again fall back on
1260 * userland filtering;
1262 * there was some other problem, in which case we
1263 * should probably report an error.
1265 * For NPF devices, the Win32 status will be
1266 * STATUS_INVALID_DEVICE_REQUEST for invalid
1267 * filters, but I don't know what it'd be for
1268 * other problems, and for some other devices
1269 * it might not be set at all.
1271 * So we just fall back on userland filtering in
1276 * install_bpf_program() validates the program.
1278 * XXX - what if we already have a filter in the kernel?
1280 if (install_bpf_program(p
, fp
) < 0)
1282 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1289 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1292 * Discard any previously-received packets, as they might have
1293 * passed whatever filter was formerly in effect, but might
1294 * not pass this filter (BIOCSETF discards packets buffered
1295 * in the kernel, so you can lose packets in any case).
1302 * We filter at user level, since the kernel driver does't process the packets
1305 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1309 strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1313 /* Install a user level filter */
1314 if (install_bpf_program(p
, fp
) < 0)
1321 pcap_getnonblock_npf(pcap_t
*p
)
1323 struct pcap_win
*pw
= p
->priv
;
1326 * XXX - if there were a PacketGetReadTimeout() call, we
1327 * would use it, and return 1 if the timeout is -1
1330 return (pw
->nonblock
);
1334 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1336 struct pcap_win
*pw
= p
->priv
;
1338 char win_errbuf
[PCAP_ERRBUF_SIZE
+1];
1342 * Set the packet buffer timeout to -1 for non-blocking
1348 * Restore the timeout set when the device was opened.
1349 * (Note that this may be -1, in which case we're not
1350 * really leaving non-blocking mode. However, although
1351 * the timeout argument to pcap_set_timeout() and
1352 * pcap_open_live() is an int, you're not supposed to
1353 * supply a negative value, so that "shouldn't happen".)
1355 newtimeout
= p
->opt
.timeout
;
1357 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1358 pcap_win32_err_to_str(GetLastError(), win_errbuf
);
1359 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1360 "PacketSetReadTimeout: %s", win_errbuf
);
1363 pw
->nonblock
= (newtimeout
== -1);
1368 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1369 const char *description
, char *errbuf
)
1372 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1376 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1379 * Add an entry for this interface, with no addresses.
1381 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1382 if (curdev
== NULL
) {
1390 * Get the list of addresses for the interface.
1392 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1396 * We don't return an error, because this can happen with
1397 * NdisWan interfaces, and we want to supply them even
1398 * if we can't supply their addresses.
1400 * We return an entry with an empty address list.
1406 * Now add the addresses.
1408 while (if_addr_size
-- > 0) {
1410 * "curdev" is an entry for this interface; add an entry for
1411 * this address to its list of addresses.
1413 res
= add_addr_to_dev(curdev
,
1414 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1415 sizeof (struct sockaddr_storage
),
1416 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1417 sizeof (struct sockaddr_storage
),
1418 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1419 sizeof (struct sockaddr_storage
),
1435 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1441 NDIS_HARDWARE_STATUS hardware_status
;
1442 #ifdef OID_GEN_PHYSICAL_MEDIUM
1443 NDIS_PHYSICAL_MEDIUM phys_medium
;
1444 bpf_u_int32 gen_physical_medium_oids
[] = {
1445 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1446 OID_GEN_PHYSICAL_MEDIUM_EX
,
1448 OID_GEN_PHYSICAL_MEDIUM
1450 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1452 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1453 #ifdef OID_GEN_MEDIA_CONNECT_STATUS_EX
1454 NET_IF_MEDIA_CONNECT_STATE connect_state_ex
;
1458 if (*flags
& PCAP_IF_LOOPBACK
) {
1460 * Loopback interface, so the connection status doesn't
1461 * apply. and it's not wireless (or wired, for that
1462 * matter...). We presume it's up and running.
1464 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1469 * We need to open the adapter to get this information.
1471 * XXX - PacketOpenAdapter() takes a non-const pointer
1472 * as an argument, so we make a copy of the argument and
1475 name_copy
= strdup(name
);
1476 adapter
= PacketOpenAdapter(name_copy
);
1478 if (adapter
== NULL
) {
1480 * Give up; if they try to open this device, it'll fail.
1485 #ifdef HAVE_AIRPCAP_API
1487 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1488 * Just set these flags (and none of the '*flags' entered with).
1490 if (PacketGetAirPcapHandle(adapter
)) {
1492 * Must be "up" and "running" if the above if succeeded.
1494 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1497 * An airpcap device is a wireless device (duh!)
1499 *flags
|= PCAP_IF_WIRELESS
;
1502 * A "network assosiation state" makes no sense for airpcap.
1504 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1505 PacketCloseAdapter(adapter
);
1511 * Get the hardware status, and derive "up" and "running" from
1514 len
= sizeof (hardware_status
);
1515 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1516 &hardware_status
, &len
, errbuf
);
1518 switch (hardware_status
) {
1520 case NdisHardwareStatusReady
:
1522 * "Available and capable of sending and receiving
1523 * data over the wire", so up and running.
1525 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1528 case NdisHardwareStatusInitializing
:
1529 case NdisHardwareStatusReset
:
1531 * "Initializing" or "Resetting", so up, but
1534 *flags
|= PCAP_IF_UP
;
1537 case NdisHardwareStatusClosing
:
1538 case NdisHardwareStatusNotReady
:
1540 * "Closing" or "Not ready", so neither up nor
1547 * Can't get the hardware status, so assume both up and
1550 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1554 * Get the network type.
1556 #ifdef OID_GEN_PHYSICAL_MEDIUM
1558 * Try the OIDs we have for this, in order.
1560 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1561 len
= sizeof (phys_medium
);
1562 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1563 &phys_medium
, &len
, errbuf
);
1571 * Failed. We can't determine whether it failed
1572 * because that particular OID isn't supported
1573 * or because some other problem occurred, so we
1574 * just drive on and try the next OID.
1579 * We got the physical medium.
1581 switch (phys_medium
) {
1583 case NdisPhysicalMediumWirelessLan
:
1584 case NdisPhysicalMediumWirelessWan
:
1585 case NdisPhysicalMediumNative802_11
:
1586 case NdisPhysicalMediumBluetooth
:
1587 case NdisPhysicalMediumUWB
:
1588 case NdisPhysicalMediumIrda
:
1592 *flags
|= PCAP_IF_WIRELESS
;
1605 * Get the connection status.
1607 #ifdef OID_GEN_MEDIA_CONNECT_STATUS_EX
1608 len
= sizeof(connect_state_ex
);
1609 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS_EX
,
1610 &connect_state_ex
, &len
, errbuf
);
1612 switch (connect_state_ex
) {
1614 case MediaConnectStateConnected
:
1618 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1621 case MediaConnectStateDisconnected
:
1623 * It's disconnected.
1625 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1631 * OID_GEN_MEDIA_CONNECT_STATUS_EX isn't supported because it's
1638 * OK, OID_GEN_MEDIA_CONNECT_STATUS_EX didn't work,
1639 * try OID_GEN_MEDIA_CONNECT_STATUS.
1641 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1642 &connect_state
, &len
, errbuf
);
1644 switch (connect_state
) {
1646 case NdisMediaStateConnected
:
1650 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1653 case NdisMediaStateDisconnected
:
1655 * It's disconnected.
1657 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1662 PacketCloseAdapter(adapter
);
1667 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1674 char our_errbuf
[PCAP_ERRBUF_SIZE
+1];
1677 * Find out how big a buffer we need.
1679 * This call should always return FALSE; if the error is
1680 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1681 * the size of the buffer we need, otherwise there's a
1682 * problem, and NameLength should be set to 0.
1684 * It shouldn't require NameLength to be set, but,
1685 * at least as of WinPcap 4.1.3, it checks whether
1686 * NameLength is big enough before it checks for a
1687 * NULL buffer argument, so, while it'll still do
1688 * the right thing if NameLength is uninitialized and
1689 * whatever junk happens to be there is big enough
1690 * (because the pointer argument will be null), it's
1691 * still reading an uninitialized variable.
1694 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1696 DWORD last_error
= GetLastError();
1698 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1700 pcap_win32_err_to_str(last_error
, our_errbuf
);
1701 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1702 "PacketGetAdapterNames: %s", our_errbuf
);
1707 if (NameLength
<= 0)
1709 AdaptersName
= (char*) malloc(NameLength
);
1710 if (AdaptersName
== NULL
)
1712 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1716 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1717 pcap_win32_err_to_str(GetLastError(), our_errbuf
);
1718 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "PacketGetAdapterNames: %s",
1725 * "PacketGetAdapterNames()" returned a list of
1726 * null-terminated ASCII interface name strings,
1727 * terminated by a null string, followed by a list
1728 * of null-terminated ASCII interface description
1729 * strings, terminated by a null string.
1730 * This means there are two ASCII nulls at the end
1731 * of the first list.
1733 * Find the end of the first list; that's the
1734 * beginning of the second list.
1736 desc
= &AdaptersName
[0];
1737 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1741 * Found it - "desc" points to the first of the two
1742 * nulls at the end of the list of names, so the
1743 * first byte of the list of descriptions is two bytes
1749 * Loop over the elements in the first list.
1751 name
= &AdaptersName
[0];
1752 while (*name
!= '\0') {
1753 bpf_u_int32 flags
= 0;
1754 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1756 * Is this a loopback interface?
1758 if (PacketIsLoopbackAdapter(name
)) {
1760 flags
|= PCAP_IF_LOOPBACK
;
1764 * Get additional flags.
1766 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1775 * Add an entry for this interface.
1777 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1785 name
+= strlen(name
) + 1;
1786 desc
+= strlen(desc
) + 1;
1794 * Return the name of a network interface attached to the system, or NULL
1795 * if none can be found. The interface must be configured up; the
1796 * lowest unit number is preferred; loopback is ignored.
1798 * In the best of all possible worlds, this would be the same as on
1799 * UN*X, but there may be software that expects this to return a
1800 * full list of devices after the first device.
1802 #define ADAPTERSNAME_LEN 8192
1804 pcap_lookupdev(char *errbuf
)
1807 DWORD dwWindowsMajorVersion
;
1808 char our_errbuf
[PCAP_ERRBUF_SIZE
+1];
1810 #pragma warning (push)
1811 #pragma warning (disable: 4996) /* disable MSVC's GetVersion() deprecated warning here */
1812 dwVersion
= GetVersion(); /* get the OS version */
1813 #pragma warning (pop)
1814 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1816 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1818 * Windows 95, 98, ME.
1820 ULONG NameLength
= ADAPTERSNAME_LEN
;
1821 static char AdaptersName
[ADAPTERSNAME_LEN
];
1823 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1824 return (AdaptersName
);
1829 * Windows NT (NT 4.0 and later).
1830 * Convert the names to Unicode for backward compatibility.
1832 ULONG NameLength
= ADAPTERSNAME_LEN
;
1833 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1834 size_t BufferSpaceLeft
;
1839 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
1842 if(TAdaptersName
== NULL
)
1844 (void)pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
1848 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
1850 pcap_win32_err_to_str(GetLastError(), our_errbuf
);
1851 (void)pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1852 "PacketGetAdapterNames: %s", our_errbuf
);
1853 free(TAdaptersName
);
1858 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
1859 tAstr
= (char*)TAdaptersName
;
1860 Unameptr
= AdaptersName
;
1863 * Convert the device names to Unicode into AdapterName.
1867 * Length of the name, including the terminating
1870 namelen
= strlen(tAstr
) + 1;
1873 * Do we have room for the name in the Unicode
1876 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
1882 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
1885 * Copy the name, converting ASCII to Unicode.
1886 * namelen includes the NUL, so we copy it as
1889 for (i
= 0; i
< namelen
; i
++)
1890 *Unameptr
++ = *tAstr
++;
1893 * Count this adapter.
1896 } while (namelen
!= 1);
1899 * Copy the descriptions, but don't convert them from
1902 Adescptr
= (char *)Unameptr
;
1907 desclen
= strlen(tAstr
) + 1;
1910 * Do we have room for the name in the Unicode
1913 if (BufferSpaceLeft
< desclen
) {
1921 * Just copy the ASCII string.
1922 * namelen includes the NUL, so we copy it as
1925 memcpy(Adescptr
, tAstr
, desclen
);
1926 Adescptr
+= desclen
;
1928 BufferSpaceLeft
-= desclen
;
1932 free(TAdaptersName
);
1933 return (char *)(AdaptersName
);
1938 * We can't use the same code that we use on UN*X, as that's doing
1939 * UN*X-specific calls.
1941 * We don't just fetch the entire list of devices, search for the
1942 * particular device, and use its first IPv4 address, as that's too
1943 * much work to get just one device's netmask.
1946 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
1950 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
1951 * in order to skip non IPv4 (i.e. IPv6 addresses)
1953 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1954 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
1955 struct sockaddr_in
*t_addr
;
1958 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
1963 for(i
= 0; i
< if_addr_size
; i
++)
1965 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
1967 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
1968 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
1969 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
1970 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
1982 static const char *pcap_lib_version_string
;
1984 #ifdef HAVE_VERSION_H
1986 * libpcap being built for Windows, as part of a WinPcap/Npcap source
1987 * tree. Include version.h from that source tree to get the WinPcap/Npcap
1990 * XXX - it'd be nice if we could somehow generate the WinPcap version number
1991 * when building WinPcap. (It'd be nice to do so for the packet.dll version
1994 #include "../../version.h"
1996 static const char pcap_version_string
[] =
1997 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
1998 static const char pcap_version_string_packet_dll_fmt
[] =
1999 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
;
2002 pcap_lib_version(void)
2004 char *packet_version_string
;
2005 size_t full_pcap_version_string_len
;
2006 char *full_pcap_version_string
;
2008 if (pcap_lib_version_string
== NULL
) {
2010 * Generate the version string.
2012 packet_version_string
= PacketGetVersion();
2013 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2015 * WinPcap version string and packet.dll version
2016 * string are the same; just report the WinPcap
2019 pcap_lib_version_string
= pcap_version_string
;
2022 * WinPcap version string and packet.dll version
2023 * string are different; that shouldn't be the
2024 * case (the two libraries should come from the
2025 * same version of WinPcap), so we report both
2028 * The -2 is for the %s in the format string,
2029 * which will be replaced by packet_version_string.
2031 full_pcap_version_string_len
=
2032 (sizeof pcap_version_string_packet_dll_fmt
- 2) +
2033 strlen(packet_version_string
);
2034 full_pcap_version_string
= malloc(full_pcap_version_string_len
);
2035 if (full_pcap_version_string
== NULL
)
2037 pcap_snprintf(full_pcap_version_string
,
2038 full_pcap_version_string_len
,
2039 pcap_version_string_packet_dll_fmt
,
2040 packet_version_string
);
2042 pcap_lib_version_string
= full_pcap_version_string
;
2044 return (pcap_lib_version_string
);
2047 #else /* HAVE_VERSION_H */
2050 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2053 static const char pcap_version_string_packet_dll_fmt
[] =
2054 PCAP_VERSION_STRING
" (packet.dll version %s)";
2056 pcap_lib_version(void)
2058 char *packet_version_string
;
2059 size_t full_pcap_version_string_len
;
2060 char *full_pcap_version_string
;
2062 if (pcap_lib_version_string
== NULL
) {
2064 * Generate the version string. Report the packet.dll
2067 * The -2 is for the %s in the format string, which will
2068 * be replaced by packet_version_string.
2070 packet_version_string
= PacketGetVersion();
2071 full_pcap_version_string_len
=
2072 (sizeof pcap_version_string_packet_dll_fmt
- 2) +
2073 strlen(packet_version_string
);
2074 full_pcap_version_string
= malloc(full_pcap_version_string_len
);
2075 if (full_pcap_version_string
== NULL
)
2077 pcap_snprintf(full_pcap_version_string
,
2078 full_pcap_version_string_len
,
2079 pcap_version_string_packet_dll_fmt
,
2080 packet_version_string
);
2081 pcap_lib_version_string
= full_pcap_version_string
;
2083 return (pcap_lib_version_string
);
2085 #endif /* HAVE_VERSION_H */