2 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2010 CACE Technologies, Davis (California)
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the Politecnico di Torino, CACE Technologies
16 * nor the names of its contributors may be used to endorse or promote
17 * products derived from this software without specific prior written
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
44 /* Old-school MinGW have these headers in a different place.
46 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
47 #include <ddk/ntddndis.h>
50 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
56 #endif /* HAVE_DAG_API */
58 #include "diag-control.h"
60 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
61 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
62 static int pcap_getnonblock_npf(pcap_t
*);
63 static int pcap_setnonblock_npf(pcap_t
*, int);
65 /*dimension of the buffer in the pcap_t structure*/
66 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
68 /*dimension of the buffer in the kernel driver NPF */
69 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
71 /* Equivalent to ntohs(), but a lot faster under Windows */
72 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
75 * Private data for capturing on WinPcap/Npcap devices.
78 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
80 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
81 int filtering_in_kernel
; /* using kernel filter */
84 int dag_fcs_bits
; /* Number of checksum bits from link layer */
88 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
89 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
94 * Define stub versions of the monitor-mode support routines if this
95 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
98 #ifndef HAVE_NPCAP_PACKET_API
100 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
103 * We don't support monitor mode.
109 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
112 * This should never be called, as PacketIsMonitorModeSupported()
113 * will return 0, meaning "we don't support monitor mode, so
114 * don't try to turn it on or off".
120 PacketGetMonitorMode(PCHAR AdapterName _U_
)
123 * This should fail, so that pcap_activate_npf() returns
124 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
132 * Sigh. PacketRequest() will have made a DeviceIoControl()
133 * call to the NPF driver to perform the OID request, with a
134 * BIOCQUERYOID ioctl. The kernel code should get back one
135 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
136 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
137 * supported by the OS or the driver, but that doesn't seem
138 * to make it to the caller of PacketRequest() in a
141 #define NDIS_STATUS_INVALID_OID 0xc0010017
142 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
143 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
146 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
149 PACKET_OID_DATA
*oid_data_arg
;
152 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
153 * It should be big enough to hold "*lenp" bytes of data; it
154 * will actually be slightly larger, as PACKET_OID_DATA has a
155 * 1-byte data array at the end, standing in for the variable-length
156 * data that's actually there.
158 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
159 if (oid_data_arg
== NULL
) {
160 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
161 "Couldn't allocate argument buffer for PacketRequest");
166 * No need to copy the data - we're doing a fetch.
168 oid_data_arg
->Oid
= oid
;
169 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
170 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
171 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
172 GetLastError(), "Error calling PacketRequest");
178 * Get the length actually supplied.
180 *lenp
= oid_data_arg
->Length
;
183 * Copy back the data we fetched.
185 memcpy(data
, oid_data_arg
->Data
, *lenp
);
191 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
193 struct pcap_win
*pw
= p
->priv
;
194 struct bpf_stat bstats
;
197 * Try to get statistics.
199 * (Please note - "struct pcap_stat" is *not* the same as
200 * WinPcap's "struct bpf_stat". It might currently have the
201 * same layout, but let's not cheat.
203 * Note also that we don't fill in ps_capt, as we might have
204 * been called by code compiled against an earlier version of
205 * WinPcap that didn't have ps_capt, in which case filling it
206 * in would stomp on whatever comes after the structure passed
209 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
210 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
211 GetLastError(), "PacketGetStats error");
214 ps
->ps_recv
= bstats
.bs_recv
;
215 ps
->ps_drop
= bstats
.bs_drop
;
218 * XXX - PacketGetStats() doesn't fill this in, so we just
222 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
231 * Win32-only routine for getting statistics.
233 * This way is definitely safer than passing the pcap_stat * from the userland.
234 * In fact, there could happen than the user allocates a variable which is not
235 * big enough for the new structure, and the library will write in a zone
236 * which is not allocated to this variable.
238 * In this way, we're pretty sure we are writing on memory allocated to this
241 * XXX - but this is the wrong way to handle statistics. Instead, we should
242 * have an API that returns data in a form like the Options section of a
243 * pcapng Interface Statistics Block:
245 * https://xml2rfc.tools.ietf.org/cgi-bin/xml2rfc.cgi?url=https://raw.githubusercontent.com/pcapng/pcapng/master/draft-tuexen-opsawg-pcapng.xml&modeAsFormat=html/ascii&type=ascii#rfc.section.4.6
247 * which would let us add new statistics straightforwardly and indicate which
248 * statistics we are and are *not* providing, rather than having to provide
249 * possibly-bogus values for statistics we can't provide.
251 static struct pcap_stat
*
252 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
254 struct pcap_win
*pw
= p
->priv
;
255 struct bpf_stat bstats
;
257 *pcap_stat_size
= sizeof (p
->stat
);
260 * Try to get statistics.
262 * (Please note - "struct pcap_stat" is *not* the same as
263 * WinPcap's "struct bpf_stat". It might currently have the
264 * same layout, but let's not cheat.)
266 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
267 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
268 GetLastError(), "PacketGetStatsEx error");
271 p
->stat
.ps_recv
= bstats
.bs_recv
;
272 p
->stat
.ps_drop
= bstats
.bs_drop
;
273 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
275 p
->stat
.ps_capt
= bstats
.bs_capt
;
280 /* Set the dimension of the kernel-level capture buffer */
282 pcap_setbuff_npf(pcap_t
*p
, int dim
)
284 struct pcap_win
*pw
= p
->priv
;
286 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
288 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
294 /* Set the driver working mode */
296 pcap_setmode_npf(pcap_t
*p
, int mode
)
298 struct pcap_win
*pw
= p
->priv
;
300 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
302 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
309 /*set the minimum amount of data that will release a read call*/
311 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
313 struct pcap_win
*pw
= p
->priv
;
315 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
317 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
324 pcap_getevent_npf(pcap_t
*p
)
326 struct pcap_win
*pw
= p
->priv
;
328 return (PacketGetReadEvent(pw
->adapter
));
332 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
334 struct pcap_win
*pw
= p
->priv
;
336 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
340 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
343 struct pcap_win
*pw
= p
->priv
;
344 PACKET_OID_DATA
*oid_data_arg
;
347 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
348 * It should be big enough to hold "*lenp" bytes of data; it
349 * will actually be slightly larger, as PACKET_OID_DATA has a
350 * 1-byte data array at the end, standing in for the variable-length
351 * data that's actually there.
353 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
354 if (oid_data_arg
== NULL
) {
355 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
356 "Couldn't allocate argument buffer for PacketRequest");
360 oid_data_arg
->Oid
= oid
;
361 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
362 memcpy(oid_data_arg
->Data
, data
, *lenp
);
363 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
364 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
365 GetLastError(), "Error calling PacketRequest");
371 * Get the length actually copied.
373 *lenp
= oid_data_arg
->Length
;
376 * No need to copy the data - we're doing a set.
383 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
385 struct pcap_win
*pw
= p
->priv
;
388 if (pw
->adapter
==NULL
) {
389 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
390 "Cannot transmit a queue to an offline capture or to a TurboCap port");
394 res
= PacketSendPackets(pw
->adapter
,
399 if(res
!= queue
->len
){
400 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
401 GetLastError(), "Error opening adapter");
408 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
410 unsigned char *new_buff
;
413 /* Bogus parameter */
414 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
415 "Error: invalid size %d",size
);
419 /* Allocate the buffer */
420 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
423 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
424 "Error: not enough memory");
437 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
439 struct pcap_win
*pw
= p
->priv
;
442 /* Set the packet driver in dump mode */
443 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
445 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
446 "Error setting dump mode");
450 /* Set the name of the dump file */
451 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
453 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
454 "Error setting kernel dump file name");
458 /* Set the limits of the dump file */
459 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
461 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
462 "Error setting dump limit");
470 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
472 struct pcap_win
*pw
= p
->priv
;
474 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
477 #ifdef HAVE_AIRPCAP_API
478 static PAirpcapHandle
479 pcap_get_airpcap_handle_npf(pcap_t
*p
)
481 struct pcap_win
*pw
= p
->priv
;
483 return (PacketGetAirPcapHandle(pw
->adapter
));
485 #else /* HAVE_AIRPCAP_API */
486 static PAirpcapHandle
487 pcap_get_airpcap_handle_npf(pcap_t
*p _U_
)
491 #endif /* HAVE_AIRPCAP_API */
494 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
499 register u_char
*bp
, *ep
;
501 struct pcap_win
*pw
= p
->priv
;
506 * Has "pcap_breakloop()" been called?
510 * Yes - clear the flag that indicates that it
511 * has, and return PCAP_ERROR_BREAK to indicate
512 * that we were told to break out of the loop.
515 return (PCAP_ERROR_BREAK
);
519 * Capture the packets.
521 * The PACKET structure had a bunch of extra stuff for
522 * Windows 9x/Me, but the only interesting data in it
523 * in the versions of Windows that we support is just
524 * a copy of p->buffer, a copy of p->buflen, and the
525 * actual number of bytes read returned from
526 * PacketReceivePacket(), none of which has to be
527 * retained from call to call, so we just keep one on
530 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
531 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
533 * Did the device go away?
534 * If so, the error we get is ERROR_GEN_FAILURE.
536 DWORD errcode
= GetLastError();
538 if (errcode
== ERROR_GEN_FAILURE
) {
540 * The device on which we're capturing
541 * went away, or it became unusable
542 * by NPF due to a suspend/resume.
544 * XXX - hopefully no other error
545 * conditions are indicated by this.
547 * XXX - we really should return an
548 * appropriate error for that, but
549 * pcap_dispatch() etc. aren't
550 * documented as having error returns
551 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
553 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
554 "The interface disappeared");
556 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
557 PCAP_ERRBUF_SIZE
, errcode
,
558 "PacketReceivePacket error");
563 cc
= Packet
.ulBytesReceived
;
571 * Loop through each packet.
573 #define bhp ((struct bpf_hdr *)bp)
576 register int caplen
, hdrlen
;
579 * Has "pcap_breakloop()" been called?
580 * If so, return immediately - if we haven't read any
581 * packets, clear the flag and return PCAP_ERROR_BREAK
582 * to indicate that we were told to break out of the loop,
583 * otherwise leave the flag set, so that the *next* call
584 * will break out of the loop without having read any
585 * packets, and return the number of packets we've
591 return (PCAP_ERROR_BREAK
);
594 p
->cc
= (int) (ep
- bp
);
601 caplen
= bhp
->bh_caplen
;
602 hdrlen
= bhp
->bh_hdrlen
;
606 * Short-circuit evaluation: if using BPF filter
607 * in kernel, no need to do it now - we already know
608 * the packet passed the filter.
610 * XXX - pcap_filter() should always return TRUE if
611 * handed a null pointer for the program, but it might
612 * just try to "run" the filter, so we check here.
614 if (pw
->filtering_in_kernel
||
615 p
->fcode
.bf_insns
== NULL
||
616 pcap_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
618 switch (p
->rmt_samp
.method
) {
620 case PCAP_SAMP_1_EVERY_N
:
621 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
623 /* Discard all packets that are not '1 out of N' */
624 if (pw
->samp_npkt
!= 0) {
625 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
630 case PCAP_SAMP_FIRST_AFTER_N_MS
:
632 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
635 * Check if the timestamp of the arrived
636 * packet is smaller than our target time.
638 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
639 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
640 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
645 * The arrived packet is suitable for being
646 * delivered to our caller, so let's update
649 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
650 if (pw
->samp_time
.tv_usec
> 1000000) {
651 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
652 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
656 #endif /* ENABLE_REMOTE */
659 * XXX A bpf_hdr matches a pcap_pkthdr.
661 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
662 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
663 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
665 p
->cc
= (int) (ep
- bp
);
672 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
682 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
684 struct pcap_win
*pw
= p
->priv
;
687 int packet_len
= 0, caplen
= 0;
688 struct pcap_pkthdr pcap_header
;
691 dag_record_t
*header
;
692 unsigned erf_record_len
;
696 unsigned dfp
= pw
->adapter
->DagFastProcess
;
699 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
702 * Get new packets from the network.
704 * The PACKET structure had a bunch of extra stuff for
705 * Windows 9x/Me, but the only interesting data in it
706 * in the versions of Windows that we support is just
707 * a copy of p->buffer, a copy of p->buflen, and the
708 * actual number of bytes read returned from
709 * PacketReceivePacket(), none of which has to be
710 * retained from call to call, so we just keep one on
713 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
714 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
715 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
719 cc
= Packet
.ulBytesReceived
;
721 /* The timeout has expired but we no packets arrived */
723 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
726 header
= (dag_record_t
*)p
->bp
;
728 endofbuf
= (char*)header
+ cc
;
731 * Cycle through the packets
735 erf_record_len
= SWAPS(header
->rlen
);
736 if((char*)header
+ erf_record_len
> endofbuf
)
739 /* Increase the number of captured packets */
742 /* Find the beginning of the packet */
743 dp
= ((u_char
*)header
) + dag_record_size
;
745 /* Determine actual packet len */
749 packet_len
= ATM_SNAPLEN
;
750 caplen
= ATM_SNAPLEN
;
756 swt
= SWAPS(header
->wlen
);
757 packet_len
= swt
- (pw
->dag_fcs_bits
);
758 caplen
= erf_record_len
- dag_record_size
- 2;
759 if (caplen
> packet_len
)
768 swt
= SWAPS(header
->wlen
);
769 packet_len
= swt
- (pw
->dag_fcs_bits
);
770 caplen
= erf_record_len
- dag_record_size
;
771 if (caplen
> packet_len
)
779 if(caplen
> p
->snapshot
)
780 caplen
= p
->snapshot
;
783 * Has "pcap_breakloop()" been called?
784 * If so, return immediately - if we haven't read any
785 * packets, clear the flag and return -2 to indicate
786 * that we were told to break out of the loop, otherwise
787 * leave the flag set, so that the *next* call will break
788 * out of the loop without having read any packets, and
789 * return the number of packets we've processed so far.
800 p
->bp
= (char*)header
;
801 p
->cc
= endofbuf
- (char*)header
;
808 /* convert between timestamp formats */
810 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
811 ts
= (ts
& 0xffffffffi
64) * 1000000;
812 ts
+= 0x80000000; /* rounding */
813 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
814 if (pcap_header
.ts
.tv_usec
>= 1000000) {
815 pcap_header
.ts
.tv_usec
-= 1000000;
816 pcap_header
.ts
.tv_sec
++;
820 /* No underlaying filtering system. We need to filter on our own */
821 if (p
->fcode
.bf_insns
)
823 if (pcap_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
825 /* Move to next packet */
826 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
831 /* Fill the header for the user suppplied callback function */
832 pcap_header
.caplen
= caplen
;
833 pcap_header
.len
= packet_len
;
835 /* Call the callback function */
836 (*callback
)(user
, &pcap_header
, dp
);
838 /* Move to next packet */
839 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
841 /* Stop if the number of packets requested by user has been reached*/
842 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
844 p
->bp
= (char*)header
;
845 p
->cc
= endofbuf
- (char*)header
;
849 while((u_char
*)header
< endofbuf
);
853 #endif /* HAVE_DAG_API */
855 /* Send a packet to the network */
857 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
859 struct pcap_win
*pw
= p
->priv
;
862 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
863 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
864 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
869 * We assume it all got sent if "PacketSendPacket()" succeeded.
870 * "pcap_inject()" is expected to return the number of bytes
877 pcap_cleanup_npf(pcap_t
*p
)
879 struct pcap_win
*pw
= p
->priv
;
881 if (pw
->adapter
!= NULL
) {
882 PacketCloseAdapter(pw
->adapter
);
885 if (pw
->rfmon_selfstart
)
887 PacketSetMonitorMode(p
->opt
.device
, 0);
889 pcap_cleanup_live_common(p
);
893 pcap_breakloop_npf(pcap_t
*p
)
895 pcap_breakloop_common(p
);
896 struct pcap_win
*pw
= p
->priv
;
898 /* XXX - what if this fails? */
899 SetEvent(PacketGetReadEvent(pw
->adapter
));
903 pcap_activate_npf(pcap_t
*p
)
905 struct pcap_win
*pw
= p
->priv
;
912 * Monitor mode is supported on Windows Vista and later.
914 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
916 pw
->rfmon_selfstart
= 0;
920 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
922 pw
->rfmon_selfstart
= 0;
923 // Monitor mode is not supported.
926 return PCAP_ERROR_RFMON_NOTSUP
;
935 pw
->rfmon_selfstart
= 1;
940 /* Init Winsock if it hasn't already been initialized */
943 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
945 if (pw
->adapter
== NULL
)
947 DWORD errcode
= GetLastError();
950 * What error did we get when trying to open the adapter?
956 * There's no such device.
958 return (PCAP_ERROR_NO_SUCH_DEVICE
);
960 case ERROR_ACCESS_DENIED
:
962 * There is, but we don't have permission to
965 return (PCAP_ERROR_PERM_DENIED
);
969 * Unknown - report details.
971 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
972 errcode
, "Error opening adapter");
973 if (pw
->rfmon_selfstart
)
975 PacketSetMonitorMode(p
->opt
.device
, 0);
982 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
984 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
985 GetLastError(), "Cannot determine the network type");
990 switch (type
.LinkType
)
993 p
->linktype
= DLT_EN10MB
;
996 case NdisMedium802_3
:
997 p
->linktype
= DLT_EN10MB
;
999 * This is (presumably) a real Ethernet capture; give it a
1000 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1001 * that an application can let you choose it, in case you're
1002 * capturing DOCSIS traffic that a Cisco Cable Modem
1003 * Termination System is putting out onto an Ethernet (it
1004 * doesn't put an Ethernet header onto the wire, it puts raw
1005 * DOCSIS frames out on the wire inside the low-level
1006 * Ethernet framing).
1008 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1010 * If that fails, just leave the list empty.
1012 if (p
->dlt_list
!= NULL
) {
1013 p
->dlt_list
[0] = DLT_EN10MB
;
1014 p
->dlt_list
[1] = DLT_DOCSIS
;
1019 case NdisMediumFddi
:
1020 p
->linktype
= DLT_FDDI
;
1023 case NdisMedium802_5
:
1024 p
->linktype
= DLT_IEEE802
;
1027 case NdisMediumArcnetRaw
:
1028 p
->linktype
= DLT_ARCNET
;
1031 case NdisMediumArcnet878_2
:
1032 p
->linktype
= DLT_ARCNET
;
1036 p
->linktype
= DLT_ATM_RFC1483
;
1039 case NdisMediumCHDLC
:
1040 p
->linktype
= DLT_CHDLC
;
1043 case NdisMediumPPPSerial
:
1044 p
->linktype
= DLT_PPP_SERIAL
;
1047 case NdisMediumNull
:
1048 p
->linktype
= DLT_NULL
;
1051 case NdisMediumBare80211
:
1052 p
->linktype
= DLT_IEEE802_11
;
1055 case NdisMediumRadio80211
:
1056 p
->linktype
= DLT_IEEE802_11_RADIO
;
1060 p
->linktype
= DLT_PPI
;
1063 case NdisMediumWirelessWan
:
1064 p
->linktype
= DLT_RAW
;
1069 * An unknown medium type is assumed to supply Ethernet
1070 * headers; if not, the user will have to report it,
1071 * so that the medium type and link-layer header type
1072 * can be determined. If we were to fail here, we
1073 * might get the link-layer type in the error, but
1074 * the user wouldn't get a capture, so we wouldn't
1075 * be able to determine the link-layer type; we report
1076 * a warning with the link-layer type, so at least
1077 * some programs will report the warning.
1079 p
->linktype
= DLT_EN10MB
;
1080 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1081 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1083 status
= PCAP_WARNING
;
1088 * Turn a negative snapshot value (invalid), a snapshot value of
1089 * 0 (unspecified), or a value bigger than the normal maximum
1090 * value, into the maximum allowed value.
1092 * If some application really *needs* a bigger snapshot
1093 * length, we should just increase MAXIMUM_SNAPLEN.
1095 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1096 p
->snapshot
= MAXIMUM_SNAPLEN
;
1098 /* Set promiscuous mode */
1102 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1104 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1110 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1111 * protocols and all packets indicated by the NIC" but if no protocol
1112 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1113 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1114 * capture incoming frames.
1116 if (PacketSetHwFilter(pw
->adapter
,
1117 NDIS_PACKET_TYPE_ALL_LOCAL
|
1118 NDIS_PACKET_TYPE_DIRECTED
|
1119 NDIS_PACKET_TYPE_BROADCAST
|
1120 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1122 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1127 /* Set the buffer size */
1128 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1130 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1133 * Traditional Adapter
1136 * If the buffer size wasn't explicitly set, default to
1137 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1139 if (p
->opt
.buffer_size
== 0)
1140 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1142 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1144 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1148 p
->buffer
= malloc(p
->bufsize
);
1149 if (p
->buffer
== NULL
)
1151 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1156 if (p
->opt
.immediate
)
1158 /* tell the driver to copy the buffer as soon as data arrives */
1159 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1161 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1162 PCAP_ERRBUF_SIZE
, GetLastError(),
1163 "Error calling PacketSetMinToCopy");
1169 /* tell the driver to copy the buffer only if it contains at least 16K */
1170 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1172 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1173 PCAP_ERRBUF_SIZE
, GetLastError(),
1174 "Error calling PacketSetMinToCopy");
1184 * We have DAG support.
1193 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1194 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1195 strstr(_strlwr(p
->opt
.device
), "dag"));
1198 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1199 if(status
!= ERROR_SUCCESS
)
1202 status
= RegQueryValueEx(dagkey
,
1209 if(status
!= ERROR_SUCCESS
)
1214 RegCloseKey(dagkey
);
1219 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1221 /* Set the length of the FCS associated to any packet. This value
1222 * will be subtracted to the packet length */
1223 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1224 #else /* HAVE_DAG_API */
1229 #endif /* HAVE_DAG_API */
1232 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1234 /* disable loopback capture if requested */
1235 if (p
->opt
.nocapture_local
)
1237 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1239 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1240 "Unable to disable the capture of loopback packets.");
1246 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1248 /* install dag specific handlers for read and setfilter */
1249 p
->read_op
= pcap_read_win32_dag
;
1250 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1254 #endif /* HAVE_DAG_API */
1255 /* install traditional npf handlers for read and setfilter */
1256 p
->read_op
= pcap_read_npf
;
1257 p
->setfilter_op
= pcap_setfilter_npf
;
1260 #endif /* HAVE_DAG_API */
1261 p
->setdirection_op
= NULL
; /* Not implemented. */
1262 /* XXX - can this be implemented on some versions of Windows? */
1263 p
->inject_op
= pcap_inject_npf
;
1264 p
->set_datalink_op
= NULL
; /* can't change data link type */
1265 p
->getnonblock_op
= pcap_getnonblock_npf
;
1266 p
->setnonblock_op
= pcap_setnonblock_npf
;
1267 p
->stats_op
= pcap_stats_npf
;
1268 p
->breakloop_op
= pcap_breakloop_npf
;
1269 p
->stats_ex_op
= pcap_stats_ex_npf
;
1270 p
->setbuff_op
= pcap_setbuff_npf
;
1271 p
->setmode_op
= pcap_setmode_npf
;
1272 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1273 p
->getevent_op
= pcap_getevent_npf
;
1274 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1275 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1276 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1277 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1278 p
->live_dump_op
= pcap_live_dump_npf
;
1279 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1280 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1281 p
->cleanup_op
= pcap_cleanup_npf
;
1284 * XXX - this is only done because WinPcap supported
1285 * pcap_fileno() returning the hFile HANDLE from the
1286 * ADAPTER structure. We make no general guarantees
1287 * that the caller can do anything useful with it.
1289 * (Not that we make any general guarantee of that
1290 * sort on UN*X, either, any more, given that not
1291 * all capture devices are regular OS network
1294 p
->handle
= pw
->adapter
->hFile
;
1298 pcap_cleanup_npf(p
);
1299 return (PCAP_ERROR
);
1303 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1306 pcap_can_set_rfmon_npf(pcap_t
*p
)
1308 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1312 pcap_create_interface(const char *device _U_
, char *ebuf
)
1316 p
= pcap_create_common(ebuf
, sizeof(struct pcap_win
));
1320 p
->activate_op
= pcap_activate_npf
;
1321 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1326 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1328 struct pcap_win
*pw
= p
->priv
;
1330 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1332 * Kernel filter not installed.
1334 * XXX - we don't know whether this failed because:
1336 * the kernel rejected the filter program as invalid,
1337 * in which case we should fall back on userland
1340 * the kernel rejected the filter program as too big,
1341 * in which case we should again fall back on
1342 * userland filtering;
1344 * there was some other problem, in which case we
1345 * should probably report an error.
1347 * For NPF devices, the Win32 status will be
1348 * STATUS_INVALID_DEVICE_REQUEST for invalid
1349 * filters, but I don't know what it'd be for
1350 * other problems, and for some other devices
1351 * it might not be set at all.
1353 * So we just fall back on userland filtering in
1358 * install_bpf_program() validates the program.
1360 * XXX - what if we already have a filter in the kernel?
1362 if (install_bpf_program(p
, fp
) < 0)
1364 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1371 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1374 * Discard any previously-received packets, as they might have
1375 * passed whatever filter was formerly in effect, but might
1376 * not pass this filter (BIOCSETF discards packets buffered
1377 * in the kernel, so you can lose packets in any case).
1384 * We filter at user level, since the kernel driver does't process the packets
1387 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1391 pcap_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1395 /* Install a user level filter */
1396 if (install_bpf_program(p
, fp
) < 0)
1403 pcap_getnonblock_npf(pcap_t
*p
)
1405 struct pcap_win
*pw
= p
->priv
;
1408 * XXX - if there were a PacketGetReadTimeout() call, we
1409 * would use it, and return 1 if the timeout is -1
1412 return (pw
->nonblock
);
1416 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1418 struct pcap_win
*pw
= p
->priv
;
1423 * Set the packet buffer timeout to -1 for non-blocking
1429 * Restore the timeout set when the device was opened.
1430 * (Note that this may be -1, in which case we're not
1431 * really leaving non-blocking mode. However, although
1432 * the timeout argument to pcap_set_timeout() and
1433 * pcap_open_live() is an int, you're not supposed to
1434 * supply a negative value, so that "shouldn't happen".)
1436 newtimeout
= p
->opt
.timeout
;
1438 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1439 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1440 GetLastError(), "PacketSetReadTimeout");
1443 pw
->nonblock
= (newtimeout
== -1);
1448 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1449 const char *description
, char *errbuf
)
1452 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1456 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1459 * Add an entry for this interface, with no addresses.
1461 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1462 if (curdev
== NULL
) {
1470 * Get the list of addresses for the interface.
1472 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1476 * We don't return an error, because this can happen with
1477 * NdisWan interfaces, and we want to supply them even
1478 * if we can't supply their addresses.
1480 * We return an entry with an empty address list.
1486 * Now add the addresses.
1488 while (if_addr_size
-- > 0) {
1490 * "curdev" is an entry for this interface; add an entry for
1491 * this address to its list of addresses.
1493 res
= add_addr_to_dev(curdev
,
1494 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1495 sizeof (struct sockaddr_storage
),
1496 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1497 sizeof (struct sockaddr_storage
),
1498 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1499 sizeof (struct sockaddr_storage
),
1515 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1521 NDIS_HARDWARE_STATUS hardware_status
;
1522 #ifdef OID_GEN_PHYSICAL_MEDIUM
1523 NDIS_PHYSICAL_MEDIUM phys_medium
;
1524 bpf_u_int32 gen_physical_medium_oids
[] = {
1525 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1526 OID_GEN_PHYSICAL_MEDIUM_EX
,
1528 OID_GEN_PHYSICAL_MEDIUM
1530 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1532 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1533 #ifdef OID_GEN_LINK_STATE
1534 NDIS_LINK_STATE link_state
;
1538 if (*flags
& PCAP_IF_LOOPBACK
) {
1540 * Loopback interface, so the connection status doesn't
1541 * apply. and it's not wireless (or wired, for that
1542 * matter...). We presume it's up and running.
1544 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1549 * We need to open the adapter to get this information.
1551 * XXX - PacketOpenAdapter() takes a non-const pointer
1552 * as an argument, so we make a copy of the argument and
1555 name_copy
= strdup(name
);
1556 adapter
= PacketOpenAdapter(name_copy
);
1558 if (adapter
== NULL
) {
1560 * Give up; if they try to open this device, it'll fail.
1565 #ifdef HAVE_AIRPCAP_API
1567 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1568 * Just set these flags (and none of the '*flags' entered with).
1570 if (PacketGetAirPcapHandle(adapter
)) {
1572 * Must be "up" and "running" if the above if succeeded.
1574 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1577 * An airpcap device is a wireless device (duh!)
1579 *flags
|= PCAP_IF_WIRELESS
;
1582 * A "network assosiation state" makes no sense for airpcap.
1584 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1585 PacketCloseAdapter(adapter
);
1591 * Get the hardware status, and derive "up" and "running" from
1594 len
= sizeof (hardware_status
);
1595 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1596 &hardware_status
, &len
, errbuf
);
1598 switch (hardware_status
) {
1600 case NdisHardwareStatusReady
:
1602 * "Available and capable of sending and receiving
1603 * data over the wire", so up and running.
1605 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1608 case NdisHardwareStatusInitializing
:
1609 case NdisHardwareStatusReset
:
1611 * "Initializing" or "Resetting", so up, but
1614 *flags
|= PCAP_IF_UP
;
1617 case NdisHardwareStatusClosing
:
1618 case NdisHardwareStatusNotReady
:
1620 * "Closing" or "Not ready", so neither up nor
1633 * Can't get the hardware status, so assume both up and
1636 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1640 * Get the network type.
1642 #ifdef OID_GEN_PHYSICAL_MEDIUM
1644 * Try the OIDs we have for this, in order.
1646 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1647 len
= sizeof (phys_medium
);
1648 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1649 &phys_medium
, &len
, errbuf
);
1657 * Failed. We can't determine whether it failed
1658 * because that particular OID isn't supported
1659 * or because some other problem occurred, so we
1660 * just drive on and try the next OID.
1665 * We got the physical medium.
1667 switch (phys_medium
) {
1669 case NdisPhysicalMediumWirelessLan
:
1670 case NdisPhysicalMediumWirelessWan
:
1671 case NdisPhysicalMediumNative802_11
:
1672 case NdisPhysicalMediumBluetooth
:
1673 case NdisPhysicalMediumUWB
:
1674 case NdisPhysicalMediumIrda
:
1678 *flags
|= PCAP_IF_WIRELESS
;
1691 * Get the connection status.
1693 #ifdef OID_GEN_LINK_STATE
1694 len
= sizeof(link_state
);
1695 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
1699 * NOTE: this also gives us the receive and transmit
1702 switch (link_state
.MediaConnectState
) {
1704 case MediaConnectStateConnected
:
1708 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1711 case MediaConnectStateDisconnected
:
1713 * It's disconnected.
1715 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1720 * It's unknown whether it's connected or not.
1727 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1733 * OK, OID_GEN_LINK_STATE didn't work, try
1734 * OID_GEN_MEDIA_CONNECT_STATUS.
1736 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1737 &connect_status
, &len
, errbuf
);
1739 switch (connect_status
) {
1741 case NdisMediaStateConnected
:
1745 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1748 case NdisMediaStateDisconnected
:
1750 * It's disconnected.
1752 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1757 PacketCloseAdapter(adapter
);
1762 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1771 * Find out how big a buffer we need.
1773 * This call should always return FALSE; if the error is
1774 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1775 * the size of the buffer we need, otherwise there's a
1776 * problem, and NameLength should be set to 0.
1778 * It shouldn't require NameLength to be set, but,
1779 * at least as of WinPcap 4.1.3, it checks whether
1780 * NameLength is big enough before it checks for a
1781 * NULL buffer argument, so, while it'll still do
1782 * the right thing if NameLength is uninitialized and
1783 * whatever junk happens to be there is big enough
1784 * (because the pointer argument will be null), it's
1785 * still reading an uninitialized variable.
1788 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1790 DWORD last_error
= GetLastError();
1792 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1794 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1795 last_error
, "PacketGetAdapterNames");
1800 if (NameLength
<= 0)
1802 AdaptersName
= (char*) malloc(NameLength
);
1803 if (AdaptersName
== NULL
)
1805 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1809 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1810 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1811 GetLastError(), "PacketGetAdapterNames");
1817 * "PacketGetAdapterNames()" returned a list of
1818 * null-terminated ASCII interface name strings,
1819 * terminated by a null string, followed by a list
1820 * of null-terminated ASCII interface description
1821 * strings, terminated by a null string.
1822 * This means there are two ASCII nulls at the end
1823 * of the first list.
1825 * Find the end of the first list; that's the
1826 * beginning of the second list.
1828 desc
= &AdaptersName
[0];
1829 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1833 * Found it - "desc" points to the first of the two
1834 * nulls at the end of the list of names, so the
1835 * first byte of the list of descriptions is two bytes
1841 * Loop over the elements in the first list.
1843 name
= &AdaptersName
[0];
1844 while (*name
!= '\0') {
1845 bpf_u_int32 flags
= 0;
1846 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1848 * Is this a loopback interface?
1850 if (PacketIsLoopbackAdapter(name
)) {
1852 flags
|= PCAP_IF_LOOPBACK
;
1856 * Get additional flags.
1858 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1867 * Add an entry for this interface.
1869 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1877 name
+= strlen(name
) + 1;
1878 desc
+= strlen(desc
) + 1;
1886 * Return the name of a network interface attached to the system, or NULL
1887 * if none can be found. The interface must be configured up; the
1888 * lowest unit number is preferred; loopback is ignored.
1890 * In the best of all possible worlds, this would be the same as on
1891 * UN*X, but there may be software that expects this to return a
1892 * full list of devices after the first device.
1894 #define ADAPTERSNAME_LEN 8192
1896 pcap_lookupdev(char *errbuf
)
1899 DWORD dwWindowsMajorVersion
;
1902 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1903 * it may return UTF-16 strings, for backwards-compatibility
1904 * reasons, and we're also disabling the hack to make that work,
1905 * for not-going-past-the-end-of-a-string reasons, and 2) we
1906 * want its behavior to be consistent.
1908 * In addition, it's not thread-safe, so we've marked it as
1912 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1913 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1917 /* disable MSVC's GetVersion() deprecated warning here */
1918 DIAG_OFF_DEPRECATION
1919 dwVersion
= GetVersion(); /* get the OS version */
1921 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1923 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1925 * Windows 95, 98, ME.
1927 ULONG NameLength
= ADAPTERSNAME_LEN
;
1928 static char AdaptersName
[ADAPTERSNAME_LEN
];
1930 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1931 return (AdaptersName
);
1936 * Windows NT (NT 4.0 and later).
1937 * Convert the names to Unicode for backward compatibility.
1939 ULONG NameLength
= ADAPTERSNAME_LEN
;
1940 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1941 size_t BufferSpaceLeft
;
1946 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
1949 if(TAdaptersName
== NULL
)
1951 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
1955 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
1957 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1958 GetLastError(), "PacketGetAdapterNames");
1959 free(TAdaptersName
);
1964 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
1965 tAstr
= (char*)TAdaptersName
;
1966 Unameptr
= AdaptersName
;
1969 * Convert the device names to Unicode into AdapterName.
1973 * Length of the name, including the terminating
1976 namelen
= strlen(tAstr
) + 1;
1979 * Do we have room for the name in the Unicode
1982 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
1988 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
1991 * Copy the name, converting ASCII to Unicode.
1992 * namelen includes the NUL, so we copy it as
1995 for (i
= 0; i
< namelen
; i
++)
1996 *Unameptr
++ = *tAstr
++;
1999 * Count this adapter.
2002 } while (namelen
!= 1);
2005 * Copy the descriptions, but don't convert them from
2008 Adescptr
= (char *)Unameptr
;
2013 desclen
= strlen(tAstr
) + 1;
2016 * Do we have room for the name in the Unicode
2019 if (BufferSpaceLeft
< desclen
) {
2027 * Just copy the ASCII string.
2028 * namelen includes the NUL, so we copy it as
2031 memcpy(Adescptr
, tAstr
, desclen
);
2032 Adescptr
+= desclen
;
2034 BufferSpaceLeft
-= desclen
;
2038 free(TAdaptersName
);
2039 return (char *)(AdaptersName
);
2044 * We can't use the same code that we use on UN*X, as that's doing
2045 * UN*X-specific calls.
2047 * We don't just fetch the entire list of devices, search for the
2048 * particular device, and use its first IPv4 address, as that's too
2049 * much work to get just one device's netmask.
2052 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2056 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2057 * in order to skip non IPv4 (i.e. IPv6 addresses)
2059 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2060 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2061 struct sockaddr_in
*t_addr
;
2064 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2069 for(i
= 0; i
< if_addr_size
; i
++)
2071 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2073 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2074 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2075 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2076 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2088 static const char *pcap_lib_version_string
;
2090 #ifdef HAVE_VERSION_H
2092 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2093 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2096 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2097 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2098 * for the packet.dll version number as well.)
2100 #include "../../version.h"
2102 static const char pcap_version_string
[] =
2103 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2106 pcap_lib_version(void)
2108 if (pcap_lib_version_string
== NULL
) {
2110 * Generate the version string.
2112 char *packet_version_string
= PacketGetVersion();
2114 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2116 * WinPcap/Npcap version string and packet.dll version
2117 * string are the same; just report the WinPcap/Npcap
2120 pcap_lib_version_string
= pcap_version_string
;
2123 * WinPcap/Npcap version string and packet.dll version
2124 * string are different; that shouldn't be the
2125 * case (the two libraries should come from the
2126 * same version of WinPcap/Npcap), so we report both
2129 char *full_pcap_version_string
;
2131 if (pcap_asprintf(&full_pcap_version_string
,
2132 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
,
2133 packet_version_string
) != -1) {
2135 pcap_lib_version_string
= full_pcap_version_string
;
2139 return (pcap_lib_version_string
);
2142 #else /* HAVE_VERSION_H */
2145 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2149 pcap_lib_version(void)
2151 if (pcap_lib_version_string
== NULL
) {
2153 * Generate the version string. Report the packet.dll
2156 char *full_pcap_version_string
;
2158 if (pcap_asprintf(&full_pcap_version_string
,
2159 PCAP_VERSION_STRING
" (packet.dll version %s)",
2160 PacketGetVersion()) != -1) {
2162 pcap_lib_version_string
= full_pcap_version_string
;
2165 return (pcap_lib_version_string
);
2167 #endif /* HAVE_VERSION_H */