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 - pcap_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 pcap_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 (pcap_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
, int 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 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1038 * protocols and all packets indicated by the NIC" but if no protocol
1039 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1040 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1041 * capture incoming frames.
1043 if (PacketSetHwFilter(pw
->adapter
,
1044 NDIS_PACKET_TYPE_ALL_LOCAL
|
1045 NDIS_PACKET_TYPE_DIRECTED
|
1046 NDIS_PACKET_TYPE_BROADCAST
|
1047 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1049 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1054 /* Set the buffer size */
1055 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1057 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1060 * Traditional Adapter
1063 * If the buffer size wasn't explicitly set, default to
1064 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1066 if (p
->opt
.buffer_size
== 0)
1067 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1069 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1071 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1075 p
->buffer
= malloc(p
->bufsize
);
1076 if (p
->buffer
== NULL
)
1078 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1083 if (p
->opt
.immediate
)
1085 /* tell the driver to copy the buffer as soon as data arrives */
1086 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1088 pcap_win32_err_to_str(GetLastError(), errbuf
);
1089 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1090 "Error calling PacketSetMinToCopy: %s",
1097 /* tell the driver to copy the buffer only if it contains at least 16K */
1098 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1100 pcap_win32_err_to_str(GetLastError(), errbuf
);
1101 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1102 "Error calling PacketSetMinToCopy: %s",
1113 * We have DAG support.
1122 pcap_snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1123 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1124 strstr(_strlwr(p
->opt
.device
), "dag"));
1127 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1128 if(status
!= ERROR_SUCCESS
)
1131 status
= RegQueryValueEx(dagkey
,
1138 if(status
!= ERROR_SUCCESS
)
1143 RegCloseKey(dagkey
);
1148 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1150 /* Set the length of the FCS associated to any packet. This value
1151 * will be subtracted to the packet length */
1152 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1153 #else /* HAVE_DAG_API */
1158 #endif /* HAVE_DAG_API */
1161 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1163 /* disable loopback capture if requested */
1164 if (p
->opt
.nocapture_local
)
1166 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1168 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1169 "Unable to disable the capture of loopback packets.");
1175 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1177 /* install dag specific handlers for read and setfilter */
1178 p
->read_op
= pcap_read_win32_dag
;
1179 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1183 #endif /* HAVE_DAG_API */
1184 /* install traditional npf handlers for read and setfilter */
1185 p
->read_op
= pcap_read_npf
;
1186 p
->setfilter_op
= pcap_setfilter_npf
;
1189 #endif /* HAVE_DAG_API */
1190 p
->setdirection_op
= NULL
; /* Not implemented. */
1191 /* XXX - can this be implemented on some versions of Windows? */
1192 p
->inject_op
= pcap_inject_npf
;
1193 p
->set_datalink_op
= NULL
; /* can't change data link type */
1194 p
->getnonblock_op
= pcap_getnonblock_npf
;
1195 p
->setnonblock_op
= pcap_setnonblock_npf
;
1196 p
->stats_op
= pcap_stats_npf
;
1197 p
->stats_ex_op
= pcap_stats_ex_npf
;
1198 p
->setbuff_op
= pcap_setbuff_npf
;
1199 p
->setmode_op
= pcap_setmode_npf
;
1200 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1201 p
->getevent_op
= pcap_getevent_npf
;
1202 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1203 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1204 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1205 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1206 p
->live_dump_op
= pcap_live_dump_npf
;
1207 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1208 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1209 p
->cleanup_op
= pcap_cleanup_npf
;
1212 * XXX - this is only done because WinPcap supported
1213 * pcap_fileno() returning the hFile HANDLE from the
1214 * ADAPTER structure. We make no general guarantees
1215 * that the caller can do anything useful with it.
1217 * (Not that we make any general guarantee of that
1218 * sort on UN*X, either, any more, given that not
1219 * all capture devices are regular OS network
1222 p
->handle
= pw
->adapter
->hFile
;
1226 pcap_cleanup_npf(p
);
1227 return (PCAP_ERROR
);
1231 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1234 pcap_can_set_rfmon_npf(pcap_t
*p
)
1236 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1240 pcap_create_interface(const char *device _U_
, char *ebuf
)
1244 p
= pcap_create_common(ebuf
, sizeof(struct pcap_win
));
1248 p
->activate_op
= pcap_activate_npf
;
1249 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1254 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1256 struct pcap_win
*pw
= p
->priv
;
1258 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1260 * Kernel filter not installed.
1262 * XXX - we don't know whether this failed because:
1264 * the kernel rejected the filter program as invalid,
1265 * in which case we should fall back on userland
1268 * the kernel rejected the filter program as too big,
1269 * in which case we should again fall back on
1270 * userland filtering;
1272 * there was some other problem, in which case we
1273 * should probably report an error.
1275 * For NPF devices, the Win32 status will be
1276 * STATUS_INVALID_DEVICE_REQUEST for invalid
1277 * filters, but I don't know what it'd be for
1278 * other problems, and for some other devices
1279 * it might not be set at all.
1281 * So we just fall back on userland filtering in
1286 * install_bpf_program() validates the program.
1288 * XXX - what if we already have a filter in the kernel?
1290 if (install_bpf_program(p
, fp
) < 0)
1292 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1299 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1302 * Discard any previously-received packets, as they might have
1303 * passed whatever filter was formerly in effect, but might
1304 * not pass this filter (BIOCSETF discards packets buffered
1305 * in the kernel, so you can lose packets in any case).
1312 * We filter at user level, since the kernel driver does't process the packets
1315 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1319 pcap_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1323 /* Install a user level filter */
1324 if (install_bpf_program(p
, fp
) < 0)
1331 pcap_getnonblock_npf(pcap_t
*p
)
1333 struct pcap_win
*pw
= p
->priv
;
1336 * XXX - if there were a PacketGetReadTimeout() call, we
1337 * would use it, and return 1 if the timeout is -1
1340 return (pw
->nonblock
);
1344 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1346 struct pcap_win
*pw
= p
->priv
;
1348 char win_errbuf
[PCAP_ERRBUF_SIZE
+1];
1352 * Set the packet buffer timeout to -1 for non-blocking
1358 * Restore the timeout set when the device was opened.
1359 * (Note that this may be -1, in which case we're not
1360 * really leaving non-blocking mode. However, although
1361 * the timeout argument to pcap_set_timeout() and
1362 * pcap_open_live() is an int, you're not supposed to
1363 * supply a negative value, so that "shouldn't happen".)
1365 newtimeout
= p
->opt
.timeout
;
1367 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1368 pcap_win32_err_to_str(GetLastError(), win_errbuf
);
1369 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1370 "PacketSetReadTimeout: %s", win_errbuf
);
1373 pw
->nonblock
= (newtimeout
== -1);
1378 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1379 const char *description
, char *errbuf
)
1382 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1386 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1389 * Add an entry for this interface, with no addresses.
1391 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1392 if (curdev
== NULL
) {
1400 * Get the list of addresses for the interface.
1402 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1406 * We don't return an error, because this can happen with
1407 * NdisWan interfaces, and we want to supply them even
1408 * if we can't supply their addresses.
1410 * We return an entry with an empty address list.
1416 * Now add the addresses.
1418 while (if_addr_size
-- > 0) {
1420 * "curdev" is an entry for this interface; add an entry for
1421 * this address to its list of addresses.
1423 res
= add_addr_to_dev(curdev
,
1424 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1425 sizeof (struct sockaddr_storage
),
1426 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1427 sizeof (struct sockaddr_storage
),
1428 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1429 sizeof (struct sockaddr_storage
),
1445 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1451 NDIS_HARDWARE_STATUS hardware_status
;
1452 #ifdef OID_GEN_PHYSICAL_MEDIUM
1453 NDIS_PHYSICAL_MEDIUM phys_medium
;
1454 bpf_u_int32 gen_physical_medium_oids
[] = {
1455 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1456 OID_GEN_PHYSICAL_MEDIUM_EX
,
1458 OID_GEN_PHYSICAL_MEDIUM
1460 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1462 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1463 #ifdef OID_GEN_LINK_STATE
1464 NDIS_LINK_STATE link_state
;
1468 if (*flags
& PCAP_IF_LOOPBACK
) {
1470 * Loopback interface, so the connection status doesn't
1471 * apply. and it's not wireless (or wired, for that
1472 * matter...). We presume it's up and running.
1474 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1479 * We need to open the adapter to get this information.
1481 * XXX - PacketOpenAdapter() takes a non-const pointer
1482 * as an argument, so we make a copy of the argument and
1485 name_copy
= strdup(name
);
1486 adapter
= PacketOpenAdapter(name_copy
);
1488 if (adapter
== NULL
) {
1490 * Give up; if they try to open this device, it'll fail.
1495 #ifdef HAVE_AIRPCAP_API
1497 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1498 * Just set these flags (and none of the '*flags' entered with).
1500 if (PacketGetAirPcapHandle(adapter
)) {
1502 * Must be "up" and "running" if the above if succeeded.
1504 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1507 * An airpcap device is a wireless device (duh!)
1509 *flags
|= PCAP_IF_WIRELESS
;
1512 * A "network assosiation state" makes no sense for airpcap.
1514 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1515 PacketCloseAdapter(adapter
);
1521 * Get the hardware status, and derive "up" and "running" from
1524 len
= sizeof (hardware_status
);
1525 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1526 &hardware_status
, &len
, errbuf
);
1528 switch (hardware_status
) {
1530 case NdisHardwareStatusReady
:
1532 * "Available and capable of sending and receiving
1533 * data over the wire", so up and running.
1535 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1538 case NdisHardwareStatusInitializing
:
1539 case NdisHardwareStatusReset
:
1541 * "Initializing" or "Resetting", so up, but
1544 *flags
|= PCAP_IF_UP
;
1547 case NdisHardwareStatusClosing
:
1548 case NdisHardwareStatusNotReady
:
1550 * "Closing" or "Not ready", so neither up nor
1557 * Can't get the hardware status, so assume both up and
1560 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1564 * Get the network type.
1566 #ifdef OID_GEN_PHYSICAL_MEDIUM
1568 * Try the OIDs we have for this, in order.
1570 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1571 len
= sizeof (phys_medium
);
1572 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1573 &phys_medium
, &len
, errbuf
);
1581 * Failed. We can't determine whether it failed
1582 * because that particular OID isn't supported
1583 * or because some other problem occurred, so we
1584 * just drive on and try the next OID.
1589 * We got the physical medium.
1591 switch (phys_medium
) {
1593 case NdisPhysicalMediumWirelessLan
:
1594 case NdisPhysicalMediumWirelessWan
:
1595 case NdisPhysicalMediumNative802_11
:
1596 case NdisPhysicalMediumBluetooth
:
1597 case NdisPhysicalMediumUWB
:
1598 case NdisPhysicalMediumIrda
:
1602 *flags
|= PCAP_IF_WIRELESS
;
1615 * Get the connection status.
1617 #ifdef OID_GEN_LINK_STATE
1618 len
= sizeof(link_state
);
1619 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
1623 * NOTE: this also gives us the receive and transmit
1626 switch (link_state
.MediaConnectState
) {
1628 case MediaConnectStateConnected
:
1632 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1635 case MediaConnectStateDisconnected
:
1637 * It's disconnected.
1639 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1645 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1651 * OK, OID_GEN_LINK_STATE didn't work, try
1652 * OID_GEN_MEDIA_CONNECT_STATUS.
1654 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1655 &connect_status
, &len
, errbuf
);
1657 switch (connect_status
) {
1659 case NdisMediaStateConnected
:
1663 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1666 case NdisMediaStateDisconnected
:
1668 * It's disconnected.
1670 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1675 PacketCloseAdapter(adapter
);
1680 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1687 char our_errbuf
[PCAP_ERRBUF_SIZE
+1];
1690 * Find out how big a buffer we need.
1692 * This call should always return FALSE; if the error is
1693 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1694 * the size of the buffer we need, otherwise there's a
1695 * problem, and NameLength should be set to 0.
1697 * It shouldn't require NameLength to be set, but,
1698 * at least as of WinPcap 4.1.3, it checks whether
1699 * NameLength is big enough before it checks for a
1700 * NULL buffer argument, so, while it'll still do
1701 * the right thing if NameLength is uninitialized and
1702 * whatever junk happens to be there is big enough
1703 * (because the pointer argument will be null), it's
1704 * still reading an uninitialized variable.
1707 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1709 DWORD last_error
= GetLastError();
1711 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1713 pcap_win32_err_to_str(last_error
, our_errbuf
);
1714 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1715 "PacketGetAdapterNames: %s", our_errbuf
);
1720 if (NameLength
<= 0)
1722 AdaptersName
= (char*) malloc(NameLength
);
1723 if (AdaptersName
== NULL
)
1725 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1729 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1730 pcap_win32_err_to_str(GetLastError(), our_errbuf
);
1731 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "PacketGetAdapterNames: %s",
1738 * "PacketGetAdapterNames()" returned a list of
1739 * null-terminated ASCII interface name strings,
1740 * terminated by a null string, followed by a list
1741 * of null-terminated ASCII interface description
1742 * strings, terminated by a null string.
1743 * This means there are two ASCII nulls at the end
1744 * of the first list.
1746 * Find the end of the first list; that's the
1747 * beginning of the second list.
1749 desc
= &AdaptersName
[0];
1750 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1754 * Found it - "desc" points to the first of the two
1755 * nulls at the end of the list of names, so the
1756 * first byte of the list of descriptions is two bytes
1762 * Loop over the elements in the first list.
1764 name
= &AdaptersName
[0];
1765 while (*name
!= '\0') {
1766 bpf_u_int32 flags
= 0;
1767 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1769 * Is this a loopback interface?
1771 if (PacketIsLoopbackAdapter(name
)) {
1773 flags
|= PCAP_IF_LOOPBACK
;
1777 * Get additional flags.
1779 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1788 * Add an entry for this interface.
1790 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1798 name
+= strlen(name
) + 1;
1799 desc
+= strlen(desc
) + 1;
1807 * Return the name of a network interface attached to the system, or NULL
1808 * if none can be found. The interface must be configured up; the
1809 * lowest unit number is preferred; loopback is ignored.
1811 * In the best of all possible worlds, this would be the same as on
1812 * UN*X, but there may be software that expects this to return a
1813 * full list of devices after the first device.
1815 #define ADAPTERSNAME_LEN 8192
1817 pcap_lookupdev(char *errbuf
)
1820 DWORD dwWindowsMajorVersion
;
1821 char our_errbuf
[PCAP_ERRBUF_SIZE
+1];
1823 #pragma warning (push)
1824 #pragma warning (disable: 4996) /* disable MSVC's GetVersion() deprecated warning here */
1825 dwVersion
= GetVersion(); /* get the OS version */
1826 #pragma warning (pop)
1827 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1829 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1831 * Windows 95, 98, ME.
1833 ULONG NameLength
= ADAPTERSNAME_LEN
;
1834 static char AdaptersName
[ADAPTERSNAME_LEN
];
1836 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1837 return (AdaptersName
);
1842 * Windows NT (NT 4.0 and later).
1843 * Convert the names to Unicode for backward compatibility.
1845 ULONG NameLength
= ADAPTERSNAME_LEN
;
1846 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1847 size_t BufferSpaceLeft
;
1852 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
1855 if(TAdaptersName
== NULL
)
1857 (void)pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
1861 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
1863 pcap_win32_err_to_str(GetLastError(), our_errbuf
);
1864 (void)pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1865 "PacketGetAdapterNames: %s", our_errbuf
);
1866 free(TAdaptersName
);
1871 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
1872 tAstr
= (char*)TAdaptersName
;
1873 Unameptr
= AdaptersName
;
1876 * Convert the device names to Unicode into AdapterName.
1880 * Length of the name, including the terminating
1883 namelen
= strlen(tAstr
) + 1;
1886 * Do we have room for the name in the Unicode
1889 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
1895 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
1898 * Copy the name, converting ASCII to Unicode.
1899 * namelen includes the NUL, so we copy it as
1902 for (i
= 0; i
< namelen
; i
++)
1903 *Unameptr
++ = *tAstr
++;
1906 * Count this adapter.
1909 } while (namelen
!= 1);
1912 * Copy the descriptions, but don't convert them from
1915 Adescptr
= (char *)Unameptr
;
1920 desclen
= strlen(tAstr
) + 1;
1923 * Do we have room for the name in the Unicode
1926 if (BufferSpaceLeft
< desclen
) {
1934 * Just copy the ASCII string.
1935 * namelen includes the NUL, so we copy it as
1938 memcpy(Adescptr
, tAstr
, desclen
);
1939 Adescptr
+= desclen
;
1941 BufferSpaceLeft
-= desclen
;
1945 free(TAdaptersName
);
1946 return (char *)(AdaptersName
);
1951 * We can't use the same code that we use on UN*X, as that's doing
1952 * UN*X-specific calls.
1954 * We don't just fetch the entire list of devices, search for the
1955 * particular device, and use its first IPv4 address, as that's too
1956 * much work to get just one device's netmask.
1959 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
1963 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
1964 * in order to skip non IPv4 (i.e. IPv6 addresses)
1966 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1967 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
1968 struct sockaddr_in
*t_addr
;
1971 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
1976 for(i
= 0; i
< if_addr_size
; i
++)
1978 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
1980 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
1981 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
1982 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
1983 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
1995 static const char *pcap_lib_version_string
;
1997 #ifdef HAVE_VERSION_H
1999 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2000 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2003 * XXX - it'd be nice if we could somehow generate the WinPcap version number
2004 * when building WinPcap. (It'd be nice to do so for the packet.dll version
2007 #include "../../version.h"
2009 static const char pcap_version_string
[] =
2010 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2011 static const char pcap_version_string_packet_dll_fmt
[] =
2012 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
;
2015 pcap_lib_version(void)
2017 char *packet_version_string
;
2018 size_t full_pcap_version_string_len
;
2019 char *full_pcap_version_string
;
2021 if (pcap_lib_version_string
== NULL
) {
2023 * Generate the version string.
2025 packet_version_string
= PacketGetVersion();
2026 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2028 * WinPcap version string and packet.dll version
2029 * string are the same; just report the WinPcap
2032 pcap_lib_version_string
= pcap_version_string
;
2035 * WinPcap version string and packet.dll version
2036 * string are different; that shouldn't be the
2037 * case (the two libraries should come from the
2038 * same version of WinPcap), so we report both
2041 * The -2 is for the %s in the format string,
2042 * which will be replaced by packet_version_string.
2044 full_pcap_version_string_len
=
2045 (sizeof pcap_version_string_packet_dll_fmt
- 2) +
2046 strlen(packet_version_string
);
2047 full_pcap_version_string
= malloc(full_pcap_version_string_len
);
2048 if (full_pcap_version_string
== NULL
)
2050 pcap_snprintf(full_pcap_version_string
,
2051 full_pcap_version_string_len
,
2052 pcap_version_string_packet_dll_fmt
,
2053 packet_version_string
);
2055 pcap_lib_version_string
= full_pcap_version_string
;
2057 return (pcap_lib_version_string
);
2060 #else /* HAVE_VERSION_H */
2063 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2066 static const char pcap_version_string_packet_dll_fmt
[] =
2067 PCAP_VERSION_STRING
" (packet.dll version %s)";
2069 pcap_lib_version(void)
2071 char *packet_version_string
;
2072 size_t full_pcap_version_string_len
;
2073 char *full_pcap_version_string
;
2075 if (pcap_lib_version_string
== NULL
) {
2077 * Generate the version string. Report the packet.dll
2080 * The -2 is for the %s in the format string, which will
2081 * be replaced by packet_version_string.
2083 packet_version_string
= PacketGetVersion();
2084 full_pcap_version_string_len
=
2085 (sizeof pcap_version_string_packet_dll_fmt
- 2) +
2086 strlen(packet_version_string
);
2087 full_pcap_version_string
= malloc(full_pcap_version_string_len
);
2088 if (full_pcap_version_string
== NULL
)
2090 pcap_snprintf(full_pcap_version_string
,
2091 full_pcap_version_string_len
,
2092 pcap_version_string_packet_dll_fmt
,
2093 packet_version_string
);
2094 pcap_lib_version_string
= full_pcap_version_string
;
2096 return (pcap_lib_version_string
);
2098 #endif /* HAVE_VERSION_H */