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
45 /* Old-school MinGW have these headers in a different place.
47 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
48 #include <ddk/ntddndis.h>
51 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
57 #endif /* HAVE_DAG_API */
59 #include "diag-control.h"
61 #include "pcap-airpcap.h"
63 static int pcap_setfilter_npf(pcap_t
*, struct bpf_program
*);
64 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
65 static int pcap_getnonblock_npf(pcap_t
*);
66 static int pcap_setnonblock_npf(pcap_t
*, int);
68 /*dimension of the buffer in the pcap_t structure*/
69 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
71 /*dimension of the buffer in the kernel driver NPF */
72 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
74 /* Equivalent to ntohs(), but a lot faster under Windows */
75 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
78 * Private data for capturing on WinPcap/Npcap devices.
81 ADAPTER
*adapter
; /* the packet32 ADAPTER for the device */
83 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
84 int filtering_in_kernel
; /* using kernel filter */
87 int dag_fcs_bits
; /* Number of checksum bits from link layer */
91 int samp_npkt
; /* parameter needed for sampling, with '1 out of N' method has been requested */
92 struct timeval samp_time
; /* parameter needed for sampling, with '1 every N ms' method has been requested */
97 * Define stub versions of the monitor-mode support routines if this
98 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
101 #ifndef HAVE_NPCAP_PACKET_API
103 PacketIsMonitorModeSupported(PCHAR AdapterName _U_
)
106 * We don't support monitor mode.
112 PacketSetMonitorMode(PCHAR AdapterName _U_
, int mode _U_
)
115 * This should never be called, as PacketIsMonitorModeSupported()
116 * will return 0, meaning "we don't support monitor mode, so
117 * don't try to turn it on or off".
123 PacketGetMonitorMode(PCHAR AdapterName _U_
)
126 * This should fail, so that pcap_activate_npf() returns
127 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
135 * Sigh. PacketRequest() will have made a DeviceIoControl()
136 * call to the NPF driver to perform the OID request, with a
137 * BIOCQUERYOID ioctl. The kernel code should get back one
138 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
139 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
140 * supported by the OS or the driver, but that doesn't seem
141 * to make it to the caller of PacketRequest() in a
144 #define NDIS_STATUS_INVALID_OID 0xc0010017
145 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
146 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
149 oid_get_request(ADAPTER
*adapter
, bpf_u_int32 oid
, void *data
, size_t *lenp
,
152 PACKET_OID_DATA
*oid_data_arg
;
155 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
156 * It should be big enough to hold "*lenp" bytes of data; it
157 * will actually be slightly larger, as PACKET_OID_DATA has a
158 * 1-byte data array at the end, standing in for the variable-length
159 * data that's actually there.
161 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
162 if (oid_data_arg
== NULL
) {
163 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
164 "Couldn't allocate argument buffer for PacketRequest");
169 * No need to copy the data - we're doing a fetch.
171 oid_data_arg
->Oid
= oid
;
172 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
173 if (!PacketRequest(adapter
, FALSE
, oid_data_arg
)) {
174 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
175 GetLastError(), "Error calling PacketRequest");
181 * Get the length actually supplied.
183 *lenp
= oid_data_arg
->Length
;
186 * Copy back the data we fetched.
188 memcpy(data
, oid_data_arg
->Data
, *lenp
);
194 pcap_stats_npf(pcap_t
*p
, struct pcap_stat
*ps
)
196 struct pcap_win
*pw
= p
->priv
;
197 struct bpf_stat bstats
;
200 * Try to get statistics.
202 * (Please note - "struct pcap_stat" is *not* the same as
203 * WinPcap's "struct bpf_stat". It might currently have the
204 * same layout, but let's not cheat.
206 * Note also that we don't fill in ps_capt, as we might have
207 * been called by code compiled against an earlier version of
208 * WinPcap that didn't have ps_capt, in which case filling it
209 * in would stomp on whatever comes after the structure passed
212 if (!PacketGetStats(pw
->adapter
, &bstats
)) {
213 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
214 GetLastError(), "PacketGetStats error");
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 * 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
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.
254 static struct pcap_stat
*
255 pcap_stats_ex_npf(pcap_t
*p
, int *pcap_stat_size
)
257 struct pcap_win
*pw
= p
->priv
;
258 struct bpf_stat bstats
;
260 *pcap_stat_size
= sizeof (p
->stat
);
263 * Try to get statistics.
265 * (Please note - "struct pcap_stat" is *not* the same as
266 * WinPcap's "struct bpf_stat". It might currently have the
267 * same layout, but let's not cheat.)
269 if (!PacketGetStatsEx(pw
->adapter
, &bstats
)) {
270 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
271 GetLastError(), "PacketGetStatsEx error");
274 p
->stat
.ps_recv
= bstats
.bs_recv
;
275 p
->stat
.ps_drop
= bstats
.bs_drop
;
276 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
278 * Just in case this is ever compiled for a target other than
279 * Windows, which is somewhere between extemely unlikely and
283 p
->stat
.ps_capt
= bstats
.bs_capt
;
288 /* Set the dimension of the kernel-level capture buffer */
290 pcap_setbuff_npf(pcap_t
*p
, int dim
)
292 struct pcap_win
*pw
= p
->priv
;
294 if(PacketSetBuff(pw
->adapter
,dim
)==FALSE
)
296 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
302 /* Set the driver working mode */
304 pcap_setmode_npf(pcap_t
*p
, int mode
)
306 struct pcap_win
*pw
= p
->priv
;
308 if(PacketSetMode(pw
->adapter
,mode
)==FALSE
)
310 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
317 /*set the minimum amount of data that will release a read call*/
319 pcap_setmintocopy_npf(pcap_t
*p
, int size
)
321 struct pcap_win
*pw
= p
->priv
;
323 if(PacketSetMinToCopy(pw
->adapter
, size
)==FALSE
)
325 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
332 pcap_getevent_npf(pcap_t
*p
)
334 struct pcap_win
*pw
= p
->priv
;
336 return (PacketGetReadEvent(pw
->adapter
));
340 pcap_oid_get_request_npf(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
342 struct pcap_win
*pw
= p
->priv
;
344 return (oid_get_request(pw
->adapter
, oid
, data
, lenp
, p
->errbuf
));
348 pcap_oid_set_request_npf(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
351 struct pcap_win
*pw
= p
->priv
;
352 PACKET_OID_DATA
*oid_data_arg
;
355 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
356 * It should be big enough to hold "*lenp" bytes of data; it
357 * will actually be slightly larger, as PACKET_OID_DATA has a
358 * 1-byte data array at the end, standing in for the variable-length
359 * data that's actually there.
361 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
362 if (oid_data_arg
== NULL
) {
363 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
364 "Couldn't allocate argument buffer for PacketRequest");
368 oid_data_arg
->Oid
= oid
;
369 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
370 memcpy(oid_data_arg
->Data
, data
, *lenp
);
371 if (!PacketRequest(pw
->adapter
, TRUE
, oid_data_arg
)) {
372 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
373 GetLastError(), "Error calling PacketRequest");
379 * Get the length actually copied.
381 *lenp
= oid_data_arg
->Length
;
384 * No need to copy the data - we're doing a set.
391 pcap_sendqueue_transmit_npf(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
393 struct pcap_win
*pw
= p
->priv
;
396 res
= PacketSendPackets(pw
->adapter
,
401 if(res
!= queue
->len
){
402 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
403 GetLastError(), "Error queueing packets");
410 pcap_setuserbuffer_npf(pcap_t
*p
, int size
)
412 unsigned char *new_buff
;
415 /* Bogus parameter */
416 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
417 "Error: invalid size %d",size
);
421 /* Allocate the buffer */
422 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
425 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
426 "Error: not enough memory");
439 pcap_live_dump_npf(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
441 struct pcap_win
*pw
= p
->priv
;
444 /* Set the packet driver in dump mode */
445 res
= PacketSetMode(pw
->adapter
, PACKET_MODE_DUMP
);
447 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
448 "Error setting dump mode");
452 /* Set the name of the dump file */
453 res
= PacketSetDumpName(pw
->adapter
, filename
, (int)strlen(filename
));
455 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
456 "Error setting kernel dump file name");
460 /* Set the limits of the dump file */
461 res
= PacketSetDumpLimits(pw
->adapter
, maxsize
, maxpacks
);
463 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
464 "Error setting dump limit");
472 pcap_live_dump_ended_npf(pcap_t
*p
, int sync
)
474 struct pcap_win
*pw
= p
->priv
;
476 return (PacketIsDumpEnded(pw
->adapter
, (BOOLEAN
)sync
));
479 #ifdef HAVE_AIRPCAP_API
480 static PAirpcapHandle
481 pcap_get_airpcap_handle_npf(pcap_t
*p
)
483 struct pcap_win
*pw
= p
->priv
;
485 return (PacketGetAirPcapHandle(pw
->adapter
));
487 #else /* HAVE_AIRPCAP_API */
488 static PAirpcapHandle
489 pcap_get_airpcap_handle_npf(pcap_t
*p _U_
)
493 #endif /* HAVE_AIRPCAP_API */
496 pcap_read_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
501 register u_char
*bp
, *ep
;
503 struct pcap_win
*pw
= p
->priv
;
508 * Has "pcap_breakloop()" been called?
512 * Yes - clear the flag that indicates that it
513 * has, and return PCAP_ERROR_BREAK to indicate
514 * that we were told to break out of the loop.
517 return (PCAP_ERROR_BREAK
);
521 * Capture the packets.
523 * The PACKET structure had a bunch of extra stuff for
524 * Windows 9x/Me, but the only interesting data in it
525 * in the versions of Windows that we support is just
526 * a copy of p->buffer, a copy of p->buflen, and the
527 * actual number of bytes read returned from
528 * PacketReceivePacket(), none of which has to be
529 * retained from call to call, so we just keep one on
532 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
533 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
535 * Did the device go away?
536 * If so, the error we get is ERROR_GEN_FAILURE.
538 DWORD errcode
= GetLastError();
540 if (errcode
== ERROR_GEN_FAILURE
) {
542 * The device on which we're capturing
543 * went away, or it became unusable
544 * by NPF due to a suspend/resume.
546 * XXX - hopefully no other error
547 * conditions are indicated by this.
549 * XXX - we really should return an
550 * appropriate error for that, but
551 * pcap_dispatch() etc. aren't
552 * documented as having error returns
553 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
555 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
556 "The interface disappeared");
558 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
559 PCAP_ERRBUF_SIZE
, errcode
,
560 "PacketReceivePacket error");
565 cc
= Packet
.ulBytesReceived
;
573 * Loop through each packet.
575 #define bhp ((struct bpf_hdr *)bp)
579 register u_int caplen
, hdrlen
;
582 * Has "pcap_breakloop()" been called?
583 * If so, return immediately - if we haven't read any
584 * packets, clear the flag and return PCAP_ERROR_BREAK
585 * to indicate that we were told to break out of the loop,
586 * otherwise leave the flag set, so that the *next* call
587 * will break out of the loop without having read any
588 * packets, and return the number of packets we've
594 return (PCAP_ERROR_BREAK
);
597 p
->cc
= (int) (ep
- bp
);
604 caplen
= bhp
->bh_caplen
;
605 hdrlen
= bhp
->bh_hdrlen
;
609 * Short-circuit evaluation: if using BPF filter
610 * in kernel, no need to do it now - we already know
611 * the packet passed the filter.
613 * XXX - pcap_filter() should always return TRUE if
614 * handed a null pointer for the program, but it might
615 * just try to "run" the filter, so we check here.
617 if (pw
->filtering_in_kernel
||
618 p
->fcode
.bf_insns
== NULL
||
619 pcap_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
621 switch (p
->rmt_samp
.method
) {
623 case PCAP_SAMP_1_EVERY_N
:
624 pw
->samp_npkt
= (pw
->samp_npkt
+ 1) % p
->rmt_samp
.value
;
626 /* Discard all packets that are not '1 out of N' */
627 if (pw
->samp_npkt
!= 0) {
628 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
633 case PCAP_SAMP_FIRST_AFTER_N_MS
:
635 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
638 * Check if the timestamp of the arrived
639 * packet is smaller than our target time.
641 if (pkt_header
->ts
.tv_sec
< pw
->samp_time
.tv_sec
||
642 (pkt_header
->ts
.tv_sec
== pw
->samp_time
.tv_sec
&& pkt_header
->ts
.tv_usec
< pw
->samp_time
.tv_usec
)) {
643 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
648 * The arrived packet is suitable for being
649 * delivered to our caller, so let's update
652 pw
->samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
653 if (pw
->samp_time
.tv_usec
> 1000000) {
654 pw
->samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ pw
->samp_time
.tv_usec
/ 1000000;
655 pw
->samp_time
.tv_usec
= pw
->samp_time
.tv_usec
% 1000000;
659 #endif /* ENABLE_REMOTE */
662 * XXX A bpf_hdr matches a pcap_pkthdr.
664 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
665 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
666 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
668 p
->cc
= (int) (ep
- bp
);
675 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
685 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
687 struct pcap_win
*pw
= p
->priv
;
690 int packet_len
= 0, caplen
= 0;
691 struct pcap_pkthdr pcap_header
;
694 dag_record_t
*header
;
695 unsigned erf_record_len
;
699 unsigned dfp
= pw
->adapter
->DagFastProcess
;
702 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
705 * Get new packets from the network.
707 * The PACKET structure had a bunch of extra stuff for
708 * Windows 9x/Me, but the only interesting data in it
709 * in the versions of Windows that we support is just
710 * a copy of p->buffer, a copy of p->buflen, and the
711 * actual number of bytes read returned from
712 * PacketReceivePacket(), none of which has to be
713 * retained from call to call, so we just keep one on
716 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
717 if (!PacketReceivePacket(pw
->adapter
, &Packet
, TRUE
)) {
718 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
722 cc
= Packet
.ulBytesReceived
;
724 /* The timeout has expired but we no packets arrived */
726 header
= (dag_record_t
*)pw
->adapter
->DagBuffer
;
729 header
= (dag_record_t
*)p
->bp
;
731 endofbuf
= (char*)header
+ cc
;
734 * Cycle through the packets
738 erf_record_len
= SWAPS(header
->rlen
);
739 if((char*)header
+ erf_record_len
> endofbuf
)
742 /* Increase the number of captured packets */
745 /* Find the beginning of the packet */
746 dp
= ((u_char
*)header
) + dag_record_size
;
748 /* Determine actual packet len */
752 packet_len
= ATM_SNAPLEN
;
753 caplen
= ATM_SNAPLEN
;
759 swt
= SWAPS(header
->wlen
);
760 packet_len
= swt
- (pw
->dag_fcs_bits
);
761 caplen
= erf_record_len
- dag_record_size
- 2;
762 if (caplen
> packet_len
)
771 swt
= SWAPS(header
->wlen
);
772 packet_len
= swt
- (pw
->dag_fcs_bits
);
773 caplen
= erf_record_len
- dag_record_size
;
774 if (caplen
> packet_len
)
782 if(caplen
> p
->snapshot
)
783 caplen
= p
->snapshot
;
786 * Has "pcap_breakloop()" been called?
787 * If so, return immediately - if we haven't read any
788 * packets, clear the flag and return -2 to indicate
789 * that we were told to break out of the loop, otherwise
790 * leave the flag set, so that the *next* call will break
791 * out of the loop without having read any packets, and
792 * return the number of packets we've processed so far.
803 p
->bp
= (char*)header
;
804 p
->cc
= endofbuf
- (char*)header
;
811 /* convert between timestamp formats */
813 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
814 ts
= (ts
& 0xffffffffi
64) * 1000000;
815 ts
+= 0x80000000; /* rounding */
816 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
817 if (pcap_header
.ts
.tv_usec
>= 1000000) {
818 pcap_header
.ts
.tv_usec
-= 1000000;
819 pcap_header
.ts
.tv_sec
++;
823 /* No underlaying filtering system. We need to filter on our own */
824 if (p
->fcode
.bf_insns
)
826 if (pcap_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
828 /* Move to next packet */
829 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
834 /* Fill the header for the user suppplied callback function */
835 pcap_header
.caplen
= caplen
;
836 pcap_header
.len
= packet_len
;
838 /* Call the callback function */
839 (*callback
)(user
, &pcap_header
, dp
);
841 /* Move to next packet */
842 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
844 /* Stop if the number of packets requested by user has been reached*/
845 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
847 p
->bp
= (char*)header
;
848 p
->cc
= endofbuf
- (char*)header
;
852 while((u_char
*)header
< endofbuf
);
856 #endif /* HAVE_DAG_API */
858 /* Send a packet to the network */
860 pcap_inject_npf(pcap_t
*p
, const void *buf
, int size
)
862 struct pcap_win
*pw
= p
->priv
;
865 PacketInitPacket(&pkt
, (PVOID
)buf
, size
);
866 if(PacketSendPacket(pw
->adapter
,&pkt
,TRUE
) == FALSE
) {
867 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
872 * We assume it all got sent if "PacketSendPacket()" succeeded.
873 * "pcap_inject()" is expected to return the number of bytes
880 pcap_cleanup_npf(pcap_t
*p
)
882 struct pcap_win
*pw
= p
->priv
;
884 if (pw
->adapter
!= NULL
) {
885 PacketCloseAdapter(pw
->adapter
);
888 if (pw
->rfmon_selfstart
)
890 PacketSetMonitorMode(p
->opt
.device
, 0);
892 pcap_cleanup_live_common(p
);
896 pcap_breakloop_npf(pcap_t
*p
)
898 pcap_breakloop_common(p
);
899 struct pcap_win
*pw
= p
->priv
;
901 /* XXX - what if this fails? */
902 SetEvent(PacketGetReadEvent(pw
->adapter
));
906 pcap_activate_npf(pcap_t
*p
)
908 struct pcap_win
*pw
= p
->priv
;
915 * Monitor mode is supported on Windows Vista and later.
917 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
919 pw
->rfmon_selfstart
= 0;
923 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
925 pw
->rfmon_selfstart
= 0;
926 // Monitor mode is not supported.
929 return PCAP_ERROR_RFMON_NOTSUP
;
938 pw
->rfmon_selfstart
= 1;
943 /* Init Winsock if it hasn't already been initialized */
946 pw
->adapter
= PacketOpenAdapter(p
->opt
.device
);
948 if (pw
->adapter
== NULL
)
950 DWORD errcode
= GetLastError();
953 * What error did we get when trying to open the adapter?
959 * There's no such device.
961 return (PCAP_ERROR_NO_SUCH_DEVICE
);
963 case ERROR_ACCESS_DENIED
:
965 * There is, but we don't have permission to
968 return (PCAP_ERROR_PERM_DENIED
);
972 * Unknown - report details.
974 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
975 errcode
, "Error opening adapter");
976 if (pw
->rfmon_selfstart
)
978 PacketSetMonitorMode(p
->opt
.device
, 0);
985 if(PacketGetNetType (pw
->adapter
,&type
) == FALSE
)
987 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
988 GetLastError(), "Cannot determine the network type");
993 switch (type
.LinkType
)
996 p
->linktype
= DLT_EN10MB
;
999 case NdisMedium802_3
:
1000 p
->linktype
= DLT_EN10MB
;
1002 * This is (presumably) a real Ethernet capture; give it a
1003 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1004 * that an application can let you choose it, in case you're
1005 * capturing DOCSIS traffic that a Cisco Cable Modem
1006 * Termination System is putting out onto an Ethernet (it
1007 * doesn't put an Ethernet header onto the wire, it puts raw
1008 * DOCSIS frames out on the wire inside the low-level
1009 * Ethernet framing).
1011 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
1013 * If that fails, just leave the list empty.
1015 if (p
->dlt_list
!= NULL
) {
1016 p
->dlt_list
[0] = DLT_EN10MB
;
1017 p
->dlt_list
[1] = DLT_DOCSIS
;
1022 case NdisMediumFddi
:
1023 p
->linktype
= DLT_FDDI
;
1026 case NdisMedium802_5
:
1027 p
->linktype
= DLT_IEEE802
;
1030 case NdisMediumArcnetRaw
:
1031 p
->linktype
= DLT_ARCNET
;
1034 case NdisMediumArcnet878_2
:
1035 p
->linktype
= DLT_ARCNET
;
1039 p
->linktype
= DLT_ATM_RFC1483
;
1042 case NdisMediumCHDLC
:
1043 p
->linktype
= DLT_CHDLC
;
1046 case NdisMediumPPPSerial
:
1047 p
->linktype
= DLT_PPP_SERIAL
;
1050 case NdisMediumNull
:
1051 p
->linktype
= DLT_NULL
;
1054 case NdisMediumBare80211
:
1055 p
->linktype
= DLT_IEEE802_11
;
1058 case NdisMediumRadio80211
:
1059 p
->linktype
= DLT_IEEE802_11_RADIO
;
1063 p
->linktype
= DLT_PPI
;
1066 case NdisMediumWirelessWan
:
1067 p
->linktype
= DLT_RAW
;
1072 * An unknown medium type is assumed to supply Ethernet
1073 * headers; if not, the user will have to report it,
1074 * so that the medium type and link-layer header type
1075 * can be determined. If we were to fail here, we
1076 * might get the link-layer type in the error, but
1077 * the user wouldn't get a capture, so we wouldn't
1078 * be able to determine the link-layer type; we report
1079 * a warning with the link-layer type, so at least
1080 * some programs will report the warning.
1082 p
->linktype
= DLT_EN10MB
;
1083 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1084 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1086 status
= PCAP_WARNING
;
1091 * Turn a negative snapshot value (invalid), a snapshot value of
1092 * 0 (unspecified), or a value bigger than the normal maximum
1093 * value, into the maximum allowed value.
1095 * If some application really *needs* a bigger snapshot
1096 * length, we should just increase MAXIMUM_SNAPLEN.
1098 if (p
->snapshot
<= 0 || p
->snapshot
> MAXIMUM_SNAPLEN
)
1099 p
->snapshot
= MAXIMUM_SNAPLEN
;
1101 /* Set promiscuous mode */
1105 if (PacketSetHwFilter(pw
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1107 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1113 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1114 * protocols and all packets indicated by the NIC" but if no protocol
1115 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1116 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1117 * capture incoming frames.
1119 if (PacketSetHwFilter(pw
->adapter
,
1120 NDIS_PACKET_TYPE_ALL_LOCAL
|
1121 NDIS_PACKET_TYPE_DIRECTED
|
1122 NDIS_PACKET_TYPE_BROADCAST
|
1123 NDIS_PACKET_TYPE_MULTICAST
) == FALSE
)
1125 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1130 /* Set the buffer size */
1131 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1133 if(!(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1136 * Traditional Adapter
1139 * If the buffer size wasn't explicitly set, default to
1140 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1142 if (p
->opt
.buffer_size
== 0)
1143 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1145 if(PacketSetBuff(pw
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1147 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1151 p
->buffer
= malloc(p
->bufsize
);
1152 if (p
->buffer
== NULL
)
1154 pcap_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1159 if (p
->opt
.immediate
)
1161 /* tell the driver to copy the buffer as soon as data arrives */
1162 if(PacketSetMinToCopy(pw
->adapter
,0)==FALSE
)
1164 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1165 PCAP_ERRBUF_SIZE
, GetLastError(),
1166 "Error calling PacketSetMinToCopy");
1172 /* tell the driver to copy the buffer only if it contains at least 16K */
1173 if(PacketSetMinToCopy(pw
->adapter
,16000)==FALSE
)
1175 pcap_fmt_errmsg_for_win32_err(p
->errbuf
,
1176 PCAP_ERRBUF_SIZE
, GetLastError(),
1177 "Error calling PacketSetMinToCopy");
1187 * We have DAG support.
1196 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1197 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1198 strstr(_strlwr(p
->opt
.device
), "dag"));
1201 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1202 if(status
!= ERROR_SUCCESS
)
1205 status
= RegQueryValueEx(dagkey
,
1212 if(status
!= ERROR_SUCCESS
)
1217 RegCloseKey(dagkey
);
1222 p
->snapshot
= PacketSetSnapLen(pw
->adapter
, p
->snapshot
);
1224 /* Set the length of the FCS associated to any packet. This value
1225 * will be subtracted to the packet length */
1226 pw
->dag_fcs_bits
= pw
->adapter
->DagFcsLen
;
1227 #else /* HAVE_DAG_API */
1232 #endif /* HAVE_DAG_API */
1235 PacketSetReadTimeout(pw
->adapter
, p
->opt
.timeout
);
1237 /* disable loopback capture if requested */
1238 if (p
->opt
.nocapture_local
)
1240 if (!PacketSetLoopbackBehavior(pw
->adapter
, NPF_DISABLE_LOOPBACK
))
1242 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1243 "Unable to disable the capture of loopback packets.");
1249 if(pw
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1251 /* install dag specific handlers for read and setfilter */
1252 p
->read_op
= pcap_read_win32_dag
;
1253 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1257 #endif /* HAVE_DAG_API */
1258 /* install traditional npf handlers for read and setfilter */
1259 p
->read_op
= pcap_read_npf
;
1260 p
->setfilter_op
= pcap_setfilter_npf
;
1263 #endif /* HAVE_DAG_API */
1264 p
->setdirection_op
= NULL
; /* Not implemented. */
1265 /* XXX - can this be implemented on some versions of Windows? */
1266 p
->inject_op
= pcap_inject_npf
;
1267 p
->set_datalink_op
= NULL
; /* can't change data link type */
1268 p
->getnonblock_op
= pcap_getnonblock_npf
;
1269 p
->setnonblock_op
= pcap_setnonblock_npf
;
1270 p
->stats_op
= pcap_stats_npf
;
1271 p
->breakloop_op
= pcap_breakloop_npf
;
1272 p
->stats_ex_op
= pcap_stats_ex_npf
;
1273 p
->setbuff_op
= pcap_setbuff_npf
;
1274 p
->setmode_op
= pcap_setmode_npf
;
1275 p
->setmintocopy_op
= pcap_setmintocopy_npf
;
1276 p
->getevent_op
= pcap_getevent_npf
;
1277 p
->oid_get_request_op
= pcap_oid_get_request_npf
;
1278 p
->oid_set_request_op
= pcap_oid_set_request_npf
;
1279 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_npf
;
1280 p
->setuserbuffer_op
= pcap_setuserbuffer_npf
;
1281 p
->live_dump_op
= pcap_live_dump_npf
;
1282 p
->live_dump_ended_op
= pcap_live_dump_ended_npf
;
1283 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_npf
;
1284 p
->cleanup_op
= pcap_cleanup_npf
;
1287 * XXX - this is only done because WinPcap supported
1288 * pcap_fileno() returning the hFile HANDLE from the
1289 * ADAPTER structure. We make no general guarantees
1290 * that the caller can do anything useful with it.
1292 * (Not that we make any general guarantee of that
1293 * sort on UN*X, either, any more, given that not
1294 * all capture devices are regular OS network
1297 p
->handle
= pw
->adapter
->hFile
;
1301 pcap_cleanup_npf(p
);
1302 return (PCAP_ERROR
);
1306 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1309 pcap_can_set_rfmon_npf(pcap_t
*p
)
1311 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1315 pcap_create_interface(const char *device _U_
, char *ebuf
)
1319 p
= PCAP_CREATE_COMMON(ebuf
, struct pcap_win
);
1323 p
->activate_op
= pcap_activate_npf
;
1324 p
->can_set_rfmon_op
= pcap_can_set_rfmon_npf
;
1329 pcap_setfilter_npf(pcap_t
*p
, struct bpf_program
*fp
)
1331 struct pcap_win
*pw
= p
->priv
;
1333 if(PacketSetBpf(pw
->adapter
,fp
)==FALSE
){
1335 * Kernel filter not installed.
1337 * XXX - we don't know whether this failed because:
1339 * the kernel rejected the filter program as invalid,
1340 * in which case we should fall back on userland
1343 * the kernel rejected the filter program as too big,
1344 * in which case we should again fall back on
1345 * userland filtering;
1347 * there was some other problem, in which case we
1348 * should probably report an error.
1350 * For NPF devices, the Win32 status will be
1351 * STATUS_INVALID_DEVICE_REQUEST for invalid
1352 * filters, but I don't know what it'd be for
1353 * other problems, and for some other devices
1354 * it might not be set at all.
1356 * So we just fall back on userland filtering in
1361 * install_bpf_program() validates the program.
1363 * XXX - what if we already have a filter in the kernel?
1365 if (install_bpf_program(p
, fp
) < 0)
1367 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1374 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1377 * Discard any previously-received packets, as they might have
1378 * passed whatever filter was formerly in effect, but might
1379 * not pass this filter (BIOCSETF discards packets buffered
1380 * in the kernel, so you can lose packets in any case).
1387 * We filter at user level, since the kernel driver does't process the packets
1390 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1394 pcap_strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1398 /* Install a user level filter */
1399 if (install_bpf_program(p
, fp
) < 0)
1406 pcap_getnonblock_npf(pcap_t
*p
)
1408 struct pcap_win
*pw
= p
->priv
;
1411 * XXX - if there were a PacketGetReadTimeout() call, we
1412 * would use it, and return 1 if the timeout is -1
1415 return (pw
->nonblock
);
1419 pcap_setnonblock_npf(pcap_t
*p
, int nonblock
)
1421 struct pcap_win
*pw
= p
->priv
;
1426 * Set the packet buffer timeout to -1 for non-blocking
1432 * Restore the timeout set when the device was opened.
1433 * (Note that this may be -1, in which case we're not
1434 * really leaving non-blocking mode. However, although
1435 * the timeout argument to pcap_set_timeout() and
1436 * pcap_open_live() is an int, you're not supposed to
1437 * supply a negative value, so that "shouldn't happen".)
1439 newtimeout
= p
->opt
.timeout
;
1441 if (!PacketSetReadTimeout(pw
->adapter
, newtimeout
)) {
1442 pcap_fmt_errmsg_for_win32_err(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1443 GetLastError(), "PacketSetReadTimeout");
1446 pw
->nonblock
= (newtimeout
== -1);
1451 pcap_add_if_npf(pcap_if_list_t
*devlistp
, char *name
, bpf_u_int32 flags
,
1452 const char *description
, char *errbuf
)
1455 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1459 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1462 * Add an entry for this interface, with no addresses.
1464 curdev
= add_dev(devlistp
, name
, flags
, description
, errbuf
);
1465 if (curdev
== NULL
) {
1473 * Get the list of addresses for the interface.
1475 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1479 * We don't return an error, because this can happen with
1480 * NdisWan interfaces, and we want to supply them even
1481 * if we can't supply their addresses.
1483 * We return an entry with an empty address list.
1489 * Now add the addresses.
1491 while (if_addr_size
-- > 0) {
1493 * "curdev" is an entry for this interface; add an entry for
1494 * this address to its list of addresses.
1496 res
= add_addr_to_dev(curdev
,
1497 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1498 sizeof (struct sockaddr_storage
),
1499 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1500 sizeof (struct sockaddr_storage
),
1501 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1502 sizeof (struct sockaddr_storage
),
1518 get_if_flags(const char *name
, bpf_u_int32
*flags
, char *errbuf
)
1524 NDIS_HARDWARE_STATUS hardware_status
;
1525 #ifdef OID_GEN_PHYSICAL_MEDIUM
1526 NDIS_PHYSICAL_MEDIUM phys_medium
;
1527 bpf_u_int32 gen_physical_medium_oids
[] = {
1528 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1529 OID_GEN_PHYSICAL_MEDIUM_EX
,
1531 OID_GEN_PHYSICAL_MEDIUM
1533 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1535 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1536 #ifdef OID_GEN_LINK_STATE
1537 NDIS_LINK_STATE link_state
;
1541 if (*flags
& PCAP_IF_LOOPBACK
) {
1543 * Loopback interface, so the connection status doesn't
1544 * apply. and it's not wireless (or wired, for that
1545 * matter...). We presume it's up and running.
1547 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
| PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1552 * We need to open the adapter to get this information.
1554 * XXX - PacketOpenAdapter() takes a non-const pointer
1555 * as an argument, so we make a copy of the argument and
1558 name_copy
= strdup(name
);
1559 adapter
= PacketOpenAdapter(name_copy
);
1561 if (adapter
== NULL
) {
1563 * Give up; if they try to open this device, it'll fail.
1568 #ifdef HAVE_AIRPCAP_API
1570 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1571 * Just set these flags (and none of the '*flags' entered with).
1573 if (PacketGetAirPcapHandle(adapter
)) {
1575 * Must be "up" and "running" if the above if succeeded.
1577 *flags
= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1580 * An airpcap device is a wireless device (duh!)
1582 *flags
|= PCAP_IF_WIRELESS
;
1585 * A "network assosiation state" makes no sense for airpcap.
1587 *flags
|= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
;
1588 PacketCloseAdapter(adapter
);
1594 * Get the hardware status, and derive "up" and "running" from
1597 len
= sizeof (hardware_status
);
1598 status
= oid_get_request(adapter
, OID_GEN_HARDWARE_STATUS
,
1599 &hardware_status
, &len
, errbuf
);
1601 switch (hardware_status
) {
1603 case NdisHardwareStatusReady
:
1605 * "Available and capable of sending and receiving
1606 * data over the wire", so up and running.
1608 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1611 case NdisHardwareStatusInitializing
:
1612 case NdisHardwareStatusReset
:
1614 * "Initializing" or "Resetting", so up, but
1617 *flags
|= PCAP_IF_UP
;
1620 case NdisHardwareStatusClosing
:
1621 case NdisHardwareStatusNotReady
:
1623 * "Closing" or "Not ready", so neither up nor
1636 * Can't get the hardware status, so assume both up and
1639 *flags
|= PCAP_IF_UP
| PCAP_IF_RUNNING
;
1643 * Get the network type.
1645 #ifdef OID_GEN_PHYSICAL_MEDIUM
1647 * Try the OIDs we have for this, in order.
1649 for (i
= 0; i
< N_GEN_PHYSICAL_MEDIUM_OIDS
; i
++) {
1650 len
= sizeof (phys_medium
);
1651 status
= oid_get_request(adapter
, gen_physical_medium_oids
[i
],
1652 &phys_medium
, &len
, errbuf
);
1660 * Failed. We can't determine whether it failed
1661 * because that particular OID isn't supported
1662 * or because some other problem occurred, so we
1663 * just drive on and try the next OID.
1668 * We got the physical medium.
1670 switch (phys_medium
) {
1672 case NdisPhysicalMediumWirelessLan
:
1673 case NdisPhysicalMediumWirelessWan
:
1674 case NdisPhysicalMediumNative802_11
:
1675 case NdisPhysicalMediumBluetooth
:
1676 case NdisPhysicalMediumUWB
:
1677 case NdisPhysicalMediumIrda
:
1681 *flags
|= PCAP_IF_WIRELESS
;
1694 * Get the connection status.
1696 #ifdef OID_GEN_LINK_STATE
1697 len
= sizeof(link_state
);
1698 status
= oid_get_request(adapter
, OID_GEN_LINK_STATE
, &link_state
,
1702 * NOTE: this also gives us the receive and transmit
1705 switch (link_state
.MediaConnectState
) {
1707 case MediaConnectStateConnected
:
1711 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1714 case MediaConnectStateDisconnected
:
1716 * It's disconnected.
1718 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1723 * It's unknown whether it's connected or not.
1730 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1736 * OK, OID_GEN_LINK_STATE didn't work, try
1737 * OID_GEN_MEDIA_CONNECT_STATUS.
1739 status
= oid_get_request(adapter
, OID_GEN_MEDIA_CONNECT_STATUS
,
1740 &connect_status
, &len
, errbuf
);
1742 switch (connect_status
) {
1744 case NdisMediaStateConnected
:
1748 *flags
|= PCAP_IF_CONNECTION_STATUS_CONNECTED
;
1751 case NdisMediaStateDisconnected
:
1753 * It's disconnected.
1755 *flags
|= PCAP_IF_CONNECTION_STATUS_DISCONNECTED
;
1760 PacketCloseAdapter(adapter
);
1765 pcap_platform_finddevs(pcap_if_list_t
*devlistp
, char *errbuf
)
1774 * Find out how big a buffer we need.
1776 * This call should always return FALSE; if the error is
1777 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1778 * the size of the buffer we need, otherwise there's a
1779 * problem, and NameLength should be set to 0.
1781 * It shouldn't require NameLength to be set, but,
1782 * at least as of WinPcap 4.1.3, it checks whether
1783 * NameLength is big enough before it checks for a
1784 * NULL buffer argument, so, while it'll still do
1785 * the right thing if NameLength is uninitialized and
1786 * whatever junk happens to be there is big enough
1787 * (because the pointer argument will be null), it's
1788 * still reading an uninitialized variable.
1791 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1793 DWORD last_error
= GetLastError();
1795 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1797 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1798 last_error
, "PacketGetAdapterNames");
1803 if (NameLength
<= 0)
1805 AdaptersName
= (char*) malloc(NameLength
);
1806 if (AdaptersName
== NULL
)
1808 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1812 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1813 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1814 GetLastError(), "PacketGetAdapterNames");
1820 * "PacketGetAdapterNames()" returned a list of
1821 * null-terminated ASCII interface name strings,
1822 * terminated by a null string, followed by a list
1823 * of null-terminated ASCII interface description
1824 * strings, terminated by a null string.
1825 * This means there are two ASCII nulls at the end
1826 * of the first list.
1828 * Find the end of the first list; that's the
1829 * beginning of the second list.
1831 desc
= &AdaptersName
[0];
1832 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1836 * Found it - "desc" points to the first of the two
1837 * nulls at the end of the list of names, so the
1838 * first byte of the list of descriptions is two bytes
1844 * Loop over the elements in the first list.
1846 name
= &AdaptersName
[0];
1847 while (*name
!= '\0') {
1848 bpf_u_int32 flags
= 0;
1850 #ifdef HAVE_AIRPCAP_API
1852 * Is this an AirPcap device?
1853 * If so, ignore it; it'll get added later, by the
1856 if (device_is_airpcap(name
, errbuf
) == 1) {
1857 name
+= strlen(name
) + 1;
1858 desc
+= strlen(desc
) + 1;
1863 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1865 * Is this a loopback interface?
1867 if (PacketIsLoopbackAdapter(name
)) {
1869 flags
|= PCAP_IF_LOOPBACK
;
1873 * Get additional flags.
1875 if (get_if_flags(name
, &flags
, errbuf
) == -1) {
1884 * Add an entry for this interface.
1886 if (pcap_add_if_npf(devlistp
, name
, flags
, desc
,
1894 name
+= strlen(name
) + 1;
1895 desc
+= strlen(desc
) + 1;
1903 * Return the name of a network interface attached to the system, or NULL
1904 * if none can be found. The interface must be configured up; the
1905 * lowest unit number is preferred; loopback is ignored.
1907 * In the best of all possible worlds, this would be the same as on
1908 * UN*X, but there may be software that expects this to return a
1909 * full list of devices after the first device.
1911 #define ADAPTERSNAME_LEN 8192
1913 pcap_lookupdev(char *errbuf
)
1916 DWORD dwWindowsMajorVersion
;
1919 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1920 * it may return UTF-16 strings, for backwards-compatibility
1921 * reasons, and we're also disabling the hack to make that work,
1922 * for not-going-past-the-end-of-a-string reasons, and 2) we
1923 * want its behavior to be consistent.
1925 * In addition, it's not thread-safe, so we've marked it as
1929 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1930 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1934 /* disable MSVC's GetVersion() deprecated warning here */
1935 DIAG_OFF_DEPRECATION
1936 dwVersion
= GetVersion(); /* get the OS version */
1938 dwWindowsMajorVersion
= (DWORD
)(LOBYTE(LOWORD(dwVersion
)));
1940 if (dwVersion
>= 0x80000000 && dwWindowsMajorVersion
>= 4) {
1942 * Windows 95, 98, ME.
1944 ULONG NameLength
= ADAPTERSNAME_LEN
;
1945 static char AdaptersName
[ADAPTERSNAME_LEN
];
1947 if (PacketGetAdapterNames(AdaptersName
,&NameLength
) )
1948 return (AdaptersName
);
1953 * Windows NT (NT 4.0 and later).
1954 * Convert the names to Unicode for backward compatibility.
1956 ULONG NameLength
= ADAPTERSNAME_LEN
;
1957 static WCHAR AdaptersName
[ADAPTERSNAME_LEN
];
1958 size_t BufferSpaceLeft
;
1963 WCHAR
*TAdaptersName
= (WCHAR
*)malloc(ADAPTERSNAME_LEN
* sizeof(WCHAR
));
1966 if(TAdaptersName
== NULL
)
1968 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "memory allocation failure");
1972 if ( !PacketGetAdapterNames((PTSTR
)TAdaptersName
,&NameLength
) )
1974 pcap_fmt_errmsg_for_win32_err(errbuf
, PCAP_ERRBUF_SIZE
,
1975 GetLastError(), "PacketGetAdapterNames");
1976 free(TAdaptersName
);
1981 BufferSpaceLeft
= ADAPTERSNAME_LEN
* sizeof(WCHAR
);
1982 tAstr
= (char*)TAdaptersName
;
1983 Unameptr
= AdaptersName
;
1986 * Convert the device names to Unicode into AdapterName.
1990 * Length of the name, including the terminating
1993 namelen
= strlen(tAstr
) + 1;
1996 * Do we have room for the name in the Unicode
1999 if (BufferSpaceLeft
< namelen
* sizeof(WCHAR
)) {
2005 BufferSpaceLeft
-= namelen
* sizeof(WCHAR
);
2008 * Copy the name, converting ASCII to Unicode.
2009 * namelen includes the NUL, so we copy it as
2012 for (i
= 0; i
< namelen
; i
++)
2013 *Unameptr
++ = *tAstr
++;
2016 * Count this adapter.
2019 } while (namelen
!= 1);
2022 * Copy the descriptions, but don't convert them from
2025 Adescptr
= (char *)Unameptr
;
2030 desclen
= strlen(tAstr
) + 1;
2033 * Do we have room for the name in the Unicode
2036 if (BufferSpaceLeft
< desclen
) {
2044 * Just copy the ASCII string.
2045 * namelen includes the NUL, so we copy it as
2048 memcpy(Adescptr
, tAstr
, desclen
);
2049 Adescptr
+= desclen
;
2051 BufferSpaceLeft
-= desclen
;
2055 free(TAdaptersName
);
2056 return (char *)(AdaptersName
);
2060 /* XXX - see if *this* gets a de-constification warning */
2062 extern const char *pcap_xyzzy_version(void);
2065 pcap_xyzzy_version(void)
2068 * Generate the version string.
2070 char *packet_version_string
= PacketGetVersion();
2071 char *packet_LPCSTR
= PacketGetLPCSTR();
2072 char *packet_const_char_star
= PacketGetConstCharStar();
2073 char *full_pcap_version_string
;
2075 if (pcap_asprintf(&full_pcap_version_string
,
2076 "blah blah blah %s %s %s",
2077 packet_version_string
,
2078 packet_LPCSTR
, packet_const_char_star
) != -1) {
2080 return (full_pcap_version_string
);
2086 * We can't use the same code that we use on UN*X, as that's doing
2087 * UN*X-specific calls.
2089 * We don't just fetch the entire list of devices, search for the
2090 * particular device, and use its first IPv4 address, as that's too
2091 * much work to get just one device's netmask.
2094 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
2098 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2099 * in order to skip non IPv4 (i.e. IPv6 addresses)
2101 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
2102 LONG if_addr_size
= MAX_NETWORK_ADDRESSES
;
2103 struct sockaddr_in
*t_addr
;
2106 if (!PacketGetNetInfoEx((void *)device
, if_addrs
, &if_addr_size
)) {
2111 for(i
= 0; i
< if_addr_size
; i
++)
2113 if(if_addrs
[i
].IPAddress
.ss_family
== AF_INET
)
2115 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].IPAddress
);
2116 *netp
= t_addr
->sin_addr
.S_un
.S_addr
;
2117 t_addr
= (struct sockaddr_in
*) &(if_addrs
[i
].SubnetMask
);
2118 *maskp
= t_addr
->sin_addr
.S_un
.S_addr
;
2130 static const char *pcap_lib_version_string
;
2132 #ifdef HAVE_VERSION_H
2134 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2135 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2138 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2139 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2140 * for the packet.dll version number as well.)
2142 #include "../../version.h"
2144 static const char pcap_version_string
[] =
2145 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
", based on " PCAP_VERSION_STRING
;
2148 pcap_lib_version(void)
2150 if (pcap_lib_version_string
== NULL
) {
2152 * Generate the version string.
2154 char *packet_version_string
= PacketGetVersion();
2155 char *packet_LPCSTR
= PacketGetLPCSTR();
2156 char *packet_const_char_star
= PacketGetConstCharStar();
2158 if (strcmp(WINPCAP_VER_STRING
, packet_version_string
) == 0) {
2160 * WinPcap/Npcap version string and packet.dll version
2161 * string are the same; just report the WinPcap/Npcap
2164 pcap_lib_version_string
= pcap_version_string
;
2167 * WinPcap/Npcap version string and packet.dll version
2168 * string are different; that shouldn't be the
2169 * case (the two libraries should come from the
2170 * same version of WinPcap/Npcap), so we report both
2173 char *full_pcap_version_string
;
2175 if (pcap_asprintf(&full_pcap_version_string
,
2176 WINPCAP_PRODUCT_NAME
" version " WINPCAP_VER_STRING
" (packet.dll version %s), based on " PCAP_VERSION_STRING
" blah blah blah %s %s",
2177 packet_version_string
,
2178 packet_LPCSTR
, packet_const_char_star
) != -1) {
2180 pcap_lib_version_string
= full_pcap_version_string
;
2184 return (pcap_lib_version_string
);
2187 #else /* HAVE_VERSION_H */
2190 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2194 pcap_lib_version(void)
2196 if (pcap_lib_version_string
== NULL
) {
2198 * Generate the version string. Report the packet.dll
2201 char *full_pcap_version_string
;
2203 if (pcap_asprintf(&full_pcap_version_string
,
2204 PCAP_VERSION_STRING
" (packet.dll version %s)",
2205 PacketGetVersion()) != -1) {
2207 pcap_lib_version_string
= full_pcap_version_string
;
2210 return (pcap_lib_version_string
);
2212 #endif /* HAVE_VERSION_H */