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.
34 #define PCAP_DONT_INCLUDE_PCAP_BPF_H
42 #include <ddk/ntddndis.h>
44 #endif /*__MINGW64__*/
47 #endif /*__MINGW32__*/
51 #endif /* HAVE_DAG_API */
54 #define errno (*_errno())
55 #endif /* __MINGW32__ */
57 #include "pcap-rpcap.h"
58 #endif /* HAVE_REMOTE */
60 static int pcap_setfilter_win32_npf(pcap_t
*, struct bpf_program
*);
61 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
62 static int pcap_getnonblock_win32(pcap_t
*, char *);
63 static int pcap_setnonblock_win32(pcap_t
*, int, char *);
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 devices.
79 int rfmon_selfstart
; /* a flag tells whether the monitor mode is set by itself */
80 int filtering_in_kernel
; /* using kernel filter */
83 int dag_fcs_bits
; /* Number of checksum bits from link layer */
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_win32() returns
127 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
138 WORD wVersionRequested
;
146 wVersionRequested
= MAKEWORD( 1, 1);
147 err
= WSAStartup( wVersionRequested
, &wsaData
);
148 atexit ((void(*)(void))WSACleanup
);
159 return (wsockinit());
163 pcap_stats_win32(pcap_t
*p
, struct pcap_stat
*ps
)
165 struct bpf_stat bstats
;
166 char errbuf
[PCAP_ERRBUF_SIZE
+1];
169 * Try to get statistics.
171 * (Please note - "struct pcap_stat" is *not* the same as
172 * WinPcap's "struct bpf_stat". It might currently have the
173 * same layout, but let's not cheat.
175 * Note also that we don't fill in ps_capt, as we might have
176 * been called by code compiled against an earlier version of
177 * WinPcap that didn't have ps_capt, in which case filling it
178 * in would stomp on whatever comes after the structure passed
181 if (!PacketGetStats(p
->adapter
, &bstats
)) {
182 pcap_win32_err_to_str(GetLastError(), errbuf
);
183 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
184 "PacketGetStats error: %s", errbuf
);
187 ps
->ps_recv
= bstats
.bs_recv
;
188 ps
->ps_drop
= bstats
.bs_drop
;
191 * XXX - PacketGetStats() doesn't fill this in, so we just
195 ps
->ps_ifdrop
= bstats
.ps_ifdrop
;
204 * Win32-only routine for getting statistics.
206 * This way is definitely safer than passing the pcap_stat * from the userland.
207 * In fact, there could happen than the user allocates a variable which is not
208 * big enough for the new structure, and the library will write in a zone
209 * which is not allocated to this variable.
211 * In this way, we're pretty sure we are writing on memory allocated to this
214 * XXX - but this is the wrong way to handle statistics. Instead, we should
215 * have an API that returns data in a form like the Options section of a
216 * pcapng Interface Statistics Block:
218 * http://xml2rfc.tools.ietf.org/cgi-bin/xml2rfc.cgi?url=https://raw.githubusercontent.com/pcapng/pcapng/master/draft-tuexen-opsawg-pcapng.xml&modeAsFormat=html/ascii&type=ascii#rfc.section.4.6
220 * which would let us add new statistics straightforwardly and indicate which
221 * statistics we are and are *not* providing, rather than having to provide
222 * possibly-bogus values for statistics we can't provide.
225 pcap_stats_ex_win32(pcap_t
*p
, int *pcap_stat_size
)
227 struct bpf_stat bstats
;
228 char errbuf
[PCAP_ERRBUF_SIZE
+1];
230 *pcap_stat_size
= sizeof (p
->stat
);
233 * Try to get statistics.
235 * (Please note - "struct pcap_stat" is *not* the same as
236 * WinPcap's "struct bpf_stat". It might currently have the
237 * same layout, but let's not cheat.)
239 if (!PacketGetStatsEx(p
->adapter
, &bstats
)) {
240 pcap_win32_err_to_str(GetLastError(), errbuf
);
241 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
242 "PacketGetStatsEx error: %s", errbuf
);
245 p
->stat
.ps_recv
= bstats
.bs_recv
;
246 p
->stat
.ps_drop
= bstats
.bs_drop
;
247 p
->stat
.ps_ifdrop
= bstats
.ps_ifdrop
;
249 p
->stat
.ps_capt
= bstats
.bs_capt
;
254 /* Set the dimension of the kernel-level capture buffer */
256 pcap_setbuff_win32(pcap_t
*p
, int dim
)
258 if(PacketSetBuff(p
->adapter
,dim
)==FALSE
)
260 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
266 /* Set the driver working mode */
268 pcap_setmode_win32(pcap_t
*p
, int mode
)
270 if(PacketSetMode(p
->adapter
,mode
)==FALSE
)
272 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
279 /*set the minimum amount of data that will release a read call*/
281 pcap_setmintocopy_win32(pcap_t
*p
, int size
)
283 if(PacketSetMinToCopy(p
->adapter
, size
)==FALSE
)
285 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
292 pcap_getevent_win32(pcap_t
*p
)
294 return (PacketGetReadEvent(p
->adapter
));
298 pcap_oid_get_request_win32(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
300 PACKET_OID_DATA
*oid_data_arg
;
301 char errbuf
[PCAP_ERRBUF_SIZE
+1];
304 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
305 * It should be big enough to hold "*lenp" bytes of data; it
306 * will actually be slightly larger, as PACKET_OID_DATA has a
307 * 1-byte data array at the end, standing in for the variable-length
308 * data that's actually there.
310 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
311 if (oid_data_arg
== NULL
) {
312 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
313 "Couldn't allocate argument buffer for PacketRequest");
318 * No need to copy the data - we're doing a fetch.
320 oid_data_arg
->Oid
= oid
;
321 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
322 if (!PacketRequest(p
->adapter
, FALSE
, oid_data_arg
)) {
323 pcap_win32_err_to_str(GetLastError(), errbuf
);
324 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
325 "Error calling PacketRequest: %s", errbuf
);
331 * Get the length actually supplied.
333 *lenp
= oid_data_arg
->Length
;
336 * Copy back the data we fetched.
338 memcpy(data
, oid_data_arg
->Data
, *lenp
);
344 pcap_oid_set_request_win32(pcap_t
*p
, bpf_u_int32 oid
, const void *data
,
347 PACKET_OID_DATA
*oid_data_arg
;
348 char errbuf
[PCAP_ERRBUF_SIZE
+1];
351 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
352 * It should be big enough to hold "*lenp" bytes of data; it
353 * will actually be slightly larger, as PACKET_OID_DATA has a
354 * 1-byte data array at the end, standing in for the variable-length
355 * data that's actually there.
357 oid_data_arg
= malloc(sizeof (PACKET_OID_DATA
) + *lenp
);
358 if (oid_data_arg
== NULL
) {
359 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
360 "Couldn't allocate argument buffer for PacketRequest");
364 oid_data_arg
->Oid
= oid
;
365 oid_data_arg
->Length
= (ULONG
)(*lenp
); /* XXX - check for ridiculously large value? */
366 memcpy(oid_data_arg
->Data
, data
, *lenp
);
367 if (!PacketRequest(p
->adapter
, TRUE
, oid_data_arg
)) {
368 pcap_win32_err_to_str(GetLastError(), errbuf
);
369 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
370 "Error calling PacketRequest: %s", errbuf
);
376 * Get the length actually copied.
378 *lenp
= oid_data_arg
->Length
;
381 * No need to copy the data - we're doing a set.
388 pcap_sendqueue_transmit_win32(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
391 char errbuf
[PCAP_ERRBUF_SIZE
+1];
393 if (p
->adapter
==NULL
) {
394 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
395 "Cannot transmit a queue to an offline capture or to a TurboCap port");
399 res
= PacketSendPackets(p
->adapter
,
404 if(res
!= queue
->len
){
405 pcap_win32_err_to_str(GetLastError(), errbuf
);
406 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
407 "Error opening adapter: %s", errbuf
);
414 pcap_setuserbuffer_win32(pcap_t
*p
, int size
)
416 unsigned char *new_buff
;
419 /* Bogus parameter */
420 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
421 "Error: invalid size %d",size
);
425 /* Allocate the buffer */
426 new_buff
=(unsigned char*)malloc(sizeof(char)*size
);
429 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
430 "Error: not enough memory");
443 pcap_live_dump_win32(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
447 /* Set the packet driver in dump mode */
448 res
= PacketSetMode(p
->adapter
, PACKET_MODE_DUMP
);
450 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
451 "Error setting dump mode");
455 /* Set the name of the dump file */
456 res
= PacketSetDumpName(p
->adapter
, filename
, (int)strlen(filename
));
458 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
459 "Error setting kernel dump file name");
463 /* Set the limits of the dump file */
464 res
= PacketSetDumpLimits(p
->adapter
, maxsize
, maxpacks
);
470 pcap_live_dump_ended_win32(pcap_t
*p
, int sync
)
472 return (PacketIsDumpEnded(p
->adapter
, (BOOLEAN
)sync
));
475 static PAirpcapHandle
476 pcap_get_airpcap_handle_win32(pcap_t
*p
)
478 #ifdef HAVE_AIRPCAP_API
479 return (PacketGetAirPcapHandle(p
->adapter
));
482 #endif /* HAVE_AIRPCAP_API */
486 pcap_read_win32_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
491 register u_char
*bp
, *ep
;
493 struct pcap_win
*pw
= p
->priv
;
498 * Has "pcap_breakloop()" been called?
502 * Yes - clear the flag that indicates that it
503 * has, and return PCAP_ERROR_BREAK to indicate
504 * that we were told to break out of the loop.
507 return (PCAP_ERROR_BREAK
);
511 * Capture the packets.
513 * The PACKET structure had a bunch of extra stuff for
514 * Windows 9x/Me, but the only interesting data in it
515 * in the versions of Windows that we support is just
516 * a copy of p->buffer, a copy of p->buflen, and the
517 * actual number of bytes read returned from
518 * PacketReceivePacket(), none of which has to be
519 * retained from call to call, so we just keep one on
522 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
523 if (!PacketReceivePacket(p
->adapter
, &Packet
, TRUE
)) {
524 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
528 cc
= Packet
.ulBytesReceived
;
536 * Loop through each packet.
538 #define bhp ((struct bpf_hdr *)bp)
541 register int caplen
, hdrlen
;
544 * Has "pcap_breakloop()" been called?
545 * If so, return immediately - if we haven't read any
546 * packets, clear the flag and return PCAP_ERROR_BREAK
547 * to indicate that we were told to break out of the loop,
548 * otherwise leave the flag set, so that the *next* call
549 * will break out of the loop without having read any
550 * packets, and return the number of packets we've
556 return (PCAP_ERROR_BREAK
);
559 p
->cc
= (int) (ep
- bp
);
566 caplen
= bhp
->bh_caplen
;
567 hdrlen
= bhp
->bh_hdrlen
;
571 * Short-circuit evaluation: if using BPF filter
572 * in kernel, no need to do it now - we already know
573 * the packet passed the filter.
575 * XXX - bpf_filter() should always return TRUE if
576 * handed a null pointer for the program, but it might
577 * just try to "run" the filter, so we check here.
579 if (pw
->filtering_in_kernel
||
580 p
->fcode
.bf_insns
== NULL
||
581 bpf_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
583 * XXX A bpf_hdr matches a pcap_pkthdr.
585 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
586 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
587 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
589 p
->cc
= (int) (ep
- bp
);
596 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
606 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
608 struct pcap_win
*pw
= p
->priv
;
611 int packet_len
= 0, caplen
= 0;
612 struct pcap_pkthdr pcap_header
;
615 dag_record_t
*header
;
616 unsigned erf_record_len
;
620 unsigned dfp
= p
->adapter
->DagFastProcess
;
623 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
626 * Get new packets from the network.
628 * The PACKET structure had a bunch of extra stuff for
629 * Windows 9x/Me, but the only interesting data in it
630 * in the versions of Windows that we support is just
631 * a copy of p->buffer, a copy of p->buflen, and the
632 * actual number of bytes read returned from
633 * PacketReceivePacket(), none of which has to be
634 * retained from call to call, so we just keep one on
637 PacketInitPacket(&Packet
, (BYTE
*)p
->buffer
, p
->bufsize
);
638 if (!PacketReceivePacket(p
->adapter
, &Packet
, TRUE
)) {
639 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
643 cc
= Packet
.ulBytesReceived
;
645 /* The timeout has expired but we no packets arrived */
647 header
= (dag_record_t
*)p
->adapter
->DagBuffer
;
650 header
= (dag_record_t
*)p
->bp
;
652 endofbuf
= (char*)header
+ cc
;
655 * Cycle through the packets
659 erf_record_len
= SWAPS(header
->rlen
);
660 if((char*)header
+ erf_record_len
> endofbuf
)
663 /* Increase the number of captured packets */
666 /* Find the beginning of the packet */
667 dp
= ((u_char
*)header
) + dag_record_size
;
669 /* Determine actual packet len */
673 packet_len
= ATM_SNAPLEN
;
674 caplen
= ATM_SNAPLEN
;
680 swt
= SWAPS(header
->wlen
);
681 packet_len
= swt
- (pw
->dag_fcs_bits
);
682 caplen
= erf_record_len
- dag_record_size
- 2;
683 if (caplen
> packet_len
)
692 swt
= SWAPS(header
->wlen
);
693 packet_len
= swt
- (pw
->dag_fcs_bits
);
694 caplen
= erf_record_len
- dag_record_size
;
695 if (caplen
> packet_len
)
703 if(caplen
> p
->snapshot
)
704 caplen
= p
->snapshot
;
707 * Has "pcap_breakloop()" been called?
708 * If so, return immediately - if we haven't read any
709 * packets, clear the flag and return -2 to indicate
710 * that we were told to break out of the loop, otherwise
711 * leave the flag set, so that the *next* call will break
712 * out of the loop without having read any packets, and
713 * return the number of packets we've processed so far.
724 p
->bp
= (char*)header
;
725 p
->cc
= endofbuf
- (char*)header
;
732 /* convert between timestamp formats */
734 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
735 ts
= (ts
& 0xffffffffi
64) * 1000000;
736 ts
+= 0x80000000; /* rounding */
737 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
738 if (pcap_header
.ts
.tv_usec
>= 1000000) {
739 pcap_header
.ts
.tv_usec
-= 1000000;
740 pcap_header
.ts
.tv_sec
++;
744 /* No underlaying filtering system. We need to filter on our own */
745 if (p
->fcode
.bf_insns
)
747 if (bpf_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
749 /* Move to next packet */
750 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
755 /* Fill the header for the user suppplied callback function */
756 pcap_header
.caplen
= caplen
;
757 pcap_header
.len
= packet_len
;
759 /* Call the callback function */
760 (*callback
)(user
, &pcap_header
, dp
);
762 /* Move to next packet */
763 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
765 /* Stop if the number of packets requested by user has been reached*/
766 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
768 p
->bp
= (char*)header
;
769 p
->cc
= endofbuf
- (char*)header
;
773 while((u_char
*)header
< endofbuf
);
777 #endif /* HAVE_DAG_API */
779 /* Send a packet to the network */
781 pcap_inject_win32(pcap_t
*p
, const void *buf
, size_t size
){
782 LPPACKET PacketToSend
;
784 PacketToSend
=PacketAllocatePacket();
786 if (PacketToSend
== NULL
)
788 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketAllocatePacket failed");
792 PacketInitPacket(PacketToSend
, (PVOID
)buf
, (UINT
)size
);
793 if(PacketSendPacket(p
->adapter
,PacketToSend
,TRUE
) == FALSE
){
794 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
795 PacketFreePacket(PacketToSend
);
799 PacketFreePacket(PacketToSend
);
802 * We assume it all got sent if "PacketSendPacket()" succeeded.
803 * "pcap_inject()" is expected to return the number of bytes
810 pcap_cleanup_win32(pcap_t
*p
)
812 struct pcap_win
*pw
= p
->priv
;
813 if (p
->adapter
!= NULL
) {
814 PacketCloseAdapter(p
->adapter
);
817 if (pw
->rfmon_selfstart
)
819 PacketSetMonitorMode(p
->opt
.device
, 0);
821 pcap_cleanup_live_common(p
);
825 pcap_activate_win32(pcap_t
*p
)
827 struct pcap_win
*pw
= p
->priv
;
830 char errbuf
[PCAP_ERRBUF_SIZE
+1];
833 char host
[PCAP_BUF_SIZE
+ 1];
834 char port
[PCAP_BUF_SIZE
+ 1];
835 char name
[PCAP_BUF_SIZE
+ 1];
837 int opensource_remote_result
;
839 struct pcap_md
*md
; /* structure used when doing a remote live capture */
840 md
= (struct pcap_md
*) ((u_char
*)p
->priv
+ sizeof(struct pcap_win
));
843 Retrofit; we have to make older applications compatible with the remote capture
844 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
845 Obviously, we cannot exploit all the new features; for instance, we cannot
846 send authentication, we cannot use a UDP data connection, and so on.
848 if (pcap_parsesrcstr(p
->opt
.device
, &srctype
, host
, port
, name
, p
->errbuf
))
851 if (srctype
== PCAP_SRC_IFREMOTE
)
853 opensource_remote_result
= pcap_opensource_remote(p
, NULL
);
855 if (opensource_remote_result
!= 0)
856 return opensource_remote_result
;
858 md
->rmt_flags
= (p
->opt
.promisc
) ? PCAP_OPENFLAG_PROMISCUOUS
: 0;
863 if (srctype
== PCAP_SRC_IFLOCAL
)
866 * If it starts with rpcap://, cut down the string
868 if (strncmp(p
->opt
.device
, PCAP_SRC_IF_STRING
, strlen(PCAP_SRC_IF_STRING
)) == 0)
870 size_t len
= strlen(p
->opt
.device
) - strlen(PCAP_SRC_IF_STRING
) + 1;
873 * allocate a new string and free the old one
877 new_string
= (char*)malloc(len
);
878 if (new_string
!= NULL
)
881 strcpy_s(new_string
, len
, p
->opt
.device
+ strlen(PCAP_SRC_IF_STRING
));
883 p
->opt
.device
= new_string
;
890 #endif /* HAVE_REMOTE */
894 * Monitor mode is supported on Windows Vista and later.
896 if (PacketGetMonitorMode(p
->opt
.device
) == 1)
898 pw
->rfmon_selfstart
= 0;
902 if ((res
= PacketSetMonitorMode(p
->opt
.device
, 1)) != 1)
904 pw
->rfmon_selfstart
= 0;
905 // Monitor mode is not supported.
908 return PCAP_ERROR_RFMON_NOTSUP
;
917 pw
->rfmon_selfstart
= 1;
925 p
->adapter
= PacketOpenAdapter(p
->opt
.device
);
927 if (p
->adapter
== NULL
)
929 /* Adapter detected but we are not able to open it. Return failure. */
930 pcap_win32_err_to_str(GetLastError(), errbuf
);
931 if (pw
->rfmon_selfstart
)
933 PacketSetMonitorMode(p
->opt
.device
, 0);
935 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
936 "Error opening adapter: %s", errbuf
);
941 if(PacketGetNetType (p
->adapter
,&type
) == FALSE
)
943 pcap_win32_err_to_str(GetLastError(), errbuf
);
944 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
945 "Cannot determine the network type: %s", errbuf
);
950 switch (type
.LinkType
)
953 p
->linktype
= DLT_EN10MB
;
956 case NdisMedium802_3
:
957 p
->linktype
= DLT_EN10MB
;
959 * This is (presumably) a real Ethernet capture; give it a
960 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
961 * that an application can let you choose it, in case you're
962 * capturing DOCSIS traffic that a Cisco Cable Modem
963 * Termination System is putting out onto an Ethernet (it
964 * doesn't put an Ethernet header onto the wire, it puts raw
965 * DOCSIS frames out on the wire inside the low-level
968 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
970 * If that fails, just leave the list empty.
972 if (p
->dlt_list
!= NULL
) {
973 p
->dlt_list
[0] = DLT_EN10MB
;
974 p
->dlt_list
[1] = DLT_DOCSIS
;
980 p
->linktype
= DLT_FDDI
;
983 case NdisMedium802_5
:
984 p
->linktype
= DLT_IEEE802
;
987 case NdisMediumArcnetRaw
:
988 p
->linktype
= DLT_ARCNET
;
991 case NdisMediumArcnet878_2
:
992 p
->linktype
= DLT_ARCNET
;
996 p
->linktype
= DLT_ATM_RFC1483
;
999 case NdisMediumCHDLC
:
1000 p
->linktype
= DLT_CHDLC
;
1003 case NdisMediumPPPSerial
:
1004 p
->linktype
= DLT_PPP_SERIAL
;
1007 case NdisMediumNull
:
1008 p
->linktype
= DLT_NULL
;
1011 case NdisMediumBare80211
:
1012 p
->linktype
= DLT_IEEE802_11
;
1015 case NdisMediumRadio80211
:
1016 p
->linktype
= DLT_IEEE802_11_RADIO
;
1020 p
->linktype
= DLT_PPI
;
1024 p
->linktype
= DLT_EN10MB
; /*an unknown adapter is assumed to be ethernet*/
1028 /* Set promiscuous mode */
1032 if (PacketSetHwFilter(p
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
1034 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
1040 if (PacketSetHwFilter(p
->adapter
,NDIS_PACKET_TYPE_ALL_LOCAL
) == FALSE
)
1042 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
1047 /* Set the buffer size */
1048 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
1050 if(!(p
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
1053 * Traditional Adapter
1056 * If the buffer size wasn't explicitly set, default to
1057 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1059 if (p
->opt
.buffer_size
== 0)
1060 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
1062 if(PacketSetBuff(p
->adapter
,p
->opt
.buffer_size
)==FALSE
)
1064 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
1068 p
->buffer
= malloc(p
->bufsize
);
1069 if (p
->buffer
== NULL
)
1071 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "malloc: %s", pcap_strerror(errno
));
1075 if (p
->opt
.immediate
)
1077 /* tell the driver to copy the buffer as soon as data arrives */
1078 if(PacketSetMinToCopy(p
->adapter
,0)==FALSE
)
1080 pcap_win32_err_to_str(GetLastError(), errbuf
);
1081 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1082 "Error calling PacketSetMinToCopy: %s",
1089 /* tell the driver to copy the buffer only if it contains at least 16K */
1090 if(PacketSetMinToCopy(p
->adapter
,16000)==FALSE
)
1092 pcap_win32_err_to_str(GetLastError(), errbuf
);
1093 pcap_snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
1094 "Error calling PacketSetMinToCopy: %s",
1113 pcap_snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
1114 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1115 strstr(_strlwr(p
->opt
.device
), "dag"));
1118 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
1119 if(status
!= ERROR_SUCCESS
)
1122 status
= RegQueryValueEx(dagkey
,
1129 if(status
!= ERROR_SUCCESS
)
1134 RegCloseKey(dagkey
);
1139 p
->snapshot
= PacketSetSnapLen(p
->adapter
, snaplen
);
1141 /* Set the length of the FCS associated to any packet. This value
1142 * will be subtracted to the packet length */
1143 pw
->dag_fcs_bits
= p
->adapter
->DagFcsLen
;
1147 #endif /* HAVE_DAG_API */
1149 PacketSetReadTimeout(p
->adapter
, p
->opt
.timeout
);
1152 if(p
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
1154 /* install dag specific handlers for read and setfilter */
1155 p
->read_op
= pcap_read_win32_dag
;
1156 p
->setfilter_op
= pcap_setfilter_win32_dag
;
1160 #endif /* HAVE_DAG_API */
1161 /* install traditional npf handlers for read and setfilter */
1162 p
->read_op
= pcap_read_win32_npf
;
1163 p
->setfilter_op
= pcap_setfilter_win32_npf
;
1166 #endif /* HAVE_DAG_API */
1167 p
->setdirection_op
= NULL
; /* Not implemented. */
1168 /* XXX - can this be implemented on some versions of Windows? */
1169 p
->inject_op
= pcap_inject_win32
;
1170 p
->set_datalink_op
= NULL
; /* can't change data link type */
1171 p
->getnonblock_op
= pcap_getnonblock_win32
;
1172 p
->setnonblock_op
= pcap_setnonblock_win32
;
1173 p
->stats_op
= pcap_stats_win32
;
1174 p
->stats_ex_op
= pcap_stats_ex_win32
;
1175 p
->setbuff_op
= pcap_setbuff_win32
;
1176 p
->setmode_op
= pcap_setmode_win32
;
1177 p
->setmintocopy_op
= pcap_setmintocopy_win32
;
1178 p
->getevent_op
= pcap_getevent_win32
;
1179 p
->oid_get_request_op
= pcap_oid_get_request_win32
;
1180 p
->oid_set_request_op
= pcap_oid_set_request_win32
;
1181 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_win32
;
1182 p
->setuserbuffer_op
= pcap_setuserbuffer_win32
;
1183 p
->live_dump_op
= pcap_live_dump_win32
;
1184 p
->live_dump_ended_op
= pcap_live_dump_ended_win32
;
1185 p
->get_airpcap_handle_op
= pcap_get_airpcap_handle_win32
;
1186 p
->cleanup_op
= pcap_cleanup_win32
;
1190 pcap_cleanup_win32(p
);
1191 return (PCAP_ERROR
);
1195 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1198 pcap_can_set_rfmon_win32(pcap_t
*p
)
1200 return (PacketIsMonitorModeSupported(p
->opt
.device
) == 1);
1204 pcap_create_interface(const char *device _U_
, char *ebuf
)
1209 p
= pcap_create_common(ebuf
, sizeof(struct pcap_win
) + sizeof(struct pcap_md
));
1211 p
= pcap_create_common(ebuf
, sizeof(struct pcap_win
));
1212 #endif /* HAVE_REMOTE */
1216 p
->activate_op
= pcap_activate_win32
;
1217 p
->can_set_rfmon_op
= pcap_can_set_rfmon_win32
;
1222 pcap_setfilter_win32_npf(pcap_t
*p
, struct bpf_program
*fp
)
1224 struct pcap_win
*pw
= p
->priv
;
1226 if(PacketSetBpf(p
->adapter
,fp
)==FALSE
){
1228 * Kernel filter not installed.
1230 * XXX - we don't know whether this failed because:
1232 * the kernel rejected the filter program as invalid,
1233 * in which case we should fall back on userland
1236 * the kernel rejected the filter program as too big,
1237 * in which case we should again fall back on
1238 * userland filtering;
1240 * there was some other problem, in which case we
1241 * should probably report an error.
1243 * For NPF devices, the Win32 status will be
1244 * STATUS_INVALID_DEVICE_REQUEST for invalid
1245 * filters, but I don't know what it'd be for
1246 * other problems, and for some other devices
1247 * it might not be set at all.
1249 * So we just fall back on userland filtering in
1254 * install_bpf_program() validates the program.
1256 * XXX - what if we already have a filter in the kernel?
1258 if (install_bpf_program(p
, fp
) < 0)
1260 pw
->filtering_in_kernel
= 0; /* filtering in userland */
1267 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
1270 * Discard any previously-received packets, as they might have
1271 * passed whatever filter was formerly in effect, but might
1272 * not pass this filter (BIOCSETF discards packets buffered
1273 * in the kernel, so you can lose packets in any case).
1280 * We filter at user level, since the kernel driver does't process the packets
1283 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
1287 strlcpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
1291 /* Install a user level filter */
1292 if (install_bpf_program(p
, fp
) < 0)
1294 pcap_snprintf(p
->errbuf
, sizeof(p
->errbuf
),
1295 "setfilter, unable to install the filter: %s", pcap_strerror(errno
));
1303 pcap_getnonblock_win32(pcap_t
*p
, char *errbuf
)
1305 struct pcap_win
*pw
= p
->priv
;
1308 * XXX - if there were a PacketGetReadTimeout() call, we
1309 * would use it, and return 1 if the timeout is -1
1312 return (pw
->nonblock
);
1316 pcap_setnonblock_win32(pcap_t
*p
, int nonblock
, char *errbuf
)
1318 struct pcap_win
*pw
= p
->priv
;
1320 char win_errbuf
[PCAP_ERRBUF_SIZE
+1];
1324 * Set the read timeout to -1 for non-blocking mode.
1329 * Restore the timeout set when the device was opened.
1330 * (Note that this may be -1, in which case we're not
1331 * really leaving non-blocking mode. However, although
1332 * the timeout argument to pcap_set_timeout() and
1333 * pcap_open_live() is an int, you're not supposed to
1334 * supply a negative value, so that "shouldn't happen".)
1336 newtimeout
= p
->opt
.timeout
;
1338 if (!PacketSetReadTimeout(p
->adapter
, newtimeout
)) {
1339 pcap_win32_err_to_str(GetLastError(), win_errbuf
);
1340 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1341 "PacketSetReadTimeout: %s", win_errbuf
);
1344 pw
->nonblock
= (newtimeout
== -1);
1349 pcap_add_if_win32(pcap_if_t
**devlist
, char *name
, bpf_u_int32 flags
,
1350 const char *description
, char *errbuf
)
1353 npf_if_addr if_addrs
[MAX_NETWORK_ADDRESSES
];
1357 if_addr_size
= MAX_NETWORK_ADDRESSES
;
1360 * Add an entry for this interface, with no addresses.
1362 curdev
= add_dev(devlist
, name
, flags
, description
, errbuf
);
1363 if (curdev
== NULL
) {
1371 * Get the list of addresses for the interface.
1373 if (!PacketGetNetInfoEx((void *)name
, if_addrs
, &if_addr_size
)) {
1377 * We don't return an error, because this can happen with
1378 * NdisWan interfaces, and we want to supply them even
1379 * if we can't supply their addresses.
1381 * We return an entry with an empty address list.
1387 * Now add the addresses.
1389 while (if_addr_size
-- > 0) {
1391 * "curdev" is an entry for this interface; add an entry for
1392 * this address to its list of addresses.
1394 res
= add_addr_to_dev(curdev
,
1395 (struct sockaddr
*)&if_addrs
[if_addr_size
].IPAddress
,
1396 sizeof (struct sockaddr_storage
),
1397 (struct sockaddr
*)&if_addrs
[if_addr_size
].SubnetMask
,
1398 sizeof (struct sockaddr_storage
),
1399 (struct sockaddr
*)&if_addrs
[if_addr_size
].Broadcast
,
1400 sizeof (struct sockaddr_storage
),
1416 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)
1418 pcap_if_t
*devlist
= NULL
;
1424 char our_errbuf
[PCAP_ERRBUF_SIZE
+1];
1427 * Find out how big a buffer we need.
1429 * This call should always return FALSE; if the error is
1430 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1431 * the size of the buffer we need, otherwise there's a
1432 * problem, and NameLength should be set to 0.
1434 * It shouldn't require NameLength to be set, but,
1435 * at least as of WinPcap 4.1.3, it checks whether
1436 * NameLength is big enough before it checks for a
1437 * NULL buffer argument, so, while it'll still do
1438 * the right thing if NameLength is uninitialized and
1439 * whatever junk happens to be there is big enough
1440 * (because the pointer argument will be null), it's
1441 * still reading an uninitialized variable.
1444 if (!PacketGetAdapterNames(NULL
, &NameLength
))
1446 DWORD last_error
= GetLastError();
1448 if (last_error
!= ERROR_INSUFFICIENT_BUFFER
)
1450 pcap_win32_err_to_str(last_error
, our_errbuf
);
1451 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1452 "PacketGetAdapterNames: %s", our_errbuf
);
1458 AdaptersName
= (char*) malloc(NameLength
);
1464 if (AdaptersName
== NULL
)
1466 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Cannot allocate enough memory to list the adapters.");
1470 if (!PacketGetAdapterNames(AdaptersName
, &NameLength
)) {
1471 pcap_win32_err_to_str(GetLastError(), our_errbuf
);
1472 pcap_snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "PacketGetAdapterNames: %s",
1479 * "PacketGetAdapterNames()" returned a list of
1480 * null-terminated ASCII interface name strings,
1481 * terminated by a null string, followed by a list
1482 * of null-terminated ASCII interface description
1483 * strings, terminated by a null string.
1484 * This means there are two ASCII nulls at the end
1485 * of the first list.
1487 * Find the end of the first list; that's the
1488 * beginning of the second list.
1490 desc
= &AdaptersName
[0];
1491 while (*desc
!= '\0' || *(desc
+ 1) != '\0')
1495 * Found it - "desc" points to the first of the two
1496 * nulls at the end of the list of names, so the
1497 * first byte of the list of descriptions is two bytes
1503 * Loop over the elements in the first list.
1505 name
= &AdaptersName
[0];
1506 while (*name
!= '\0') {
1507 bpf_u_int32 flags
= 0;
1508 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1510 * Is this a loopback interface?
1512 if (PacketIsLoopbackAdapter(name
)) {
1514 flags
|= PCAP_IF_LOOPBACK
;
1519 * Add an entry for this interface.
1521 if (pcap_add_if_win32(&devlist
, name
, flags
, desc
,
1529 name
+= strlen(name
) + 1;
1530 desc
+= strlen(desc
) + 1;
1535 * We had an error; free the list we've been constructing.
1537 if (devlist
!= NULL
) {
1538 pcap_freealldevs(devlist
);
1543 *alldevsp
= devlist
;