2 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2008 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.
40 #include <ddk/ntddndis.h>
42 #endif /*__MINGW64__*/
45 #endif /*__MINGW32__*/
49 #endif /* HAVE_DAG_API */
52 #define errno (*_errno())
53 #endif /* __MINGW32__ */
55 static int pcap_setfilter_win32_npf(pcap_t
*, struct bpf_program
*);
56 static int pcap_setfilter_win32_dag(pcap_t
*, struct bpf_program
*);
57 static int pcap_getnonblock_win32(pcap_t
*, char *);
58 static int pcap_setnonblock_win32(pcap_t
*, int, char *);
60 /*dimension of the buffer in the pcap_t structure*/
61 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
63 /*dimension of the buffer in the kernel driver NPF */
64 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
66 /* Equivalent to ntohs(), but a lot faster under Windows */
67 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
70 * Private data for capturing on WinPcap devices.
75 int filtering_in_kernel
; /* using kernel filter */
78 int dag_fcs_bits
; /* Number of checksum bits from link layer */
83 * Header that the WinPcap driver associates to the packets.
87 struct timeval bh_tstamp
; /* time stamp */
88 bpf_u_int32 bh_caplen
; /* length of captured portion */
89 bpf_u_int32 bh_datalen
; /* original length of packet */
90 u_short bh_hdrlen
; /* length of bpf header (this struct
91 plus alignment padding) */
94 CRITICAL_SECTION g_PcapCompileCriticalSection
;
102 if (dwReason
== DLL_PROCESS_ATTACH
)
104 InitializeCriticalSection(&g_PcapCompileCriticalSection
);
114 WORD wVersionRequested
;
122 wVersionRequested
= MAKEWORD( 1, 1);
123 err
= WSAStartup( wVersionRequested
, &wsaData
);
124 atexit ((void(*)(void))WSACleanup
);
125 InitializeCriticalSection(&g_PcapCompileCriticalSection
);
139 pcap_stats_win32(pcap_t
*p
, struct pcap_stat
*ps
)
142 if(PacketGetStats(p
->adapter
, (struct bpf_stat
*)ps
) != TRUE
){
143 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "PacketGetStats error: %s", pcap_win32strerror());
150 /* Set the dimension of the kernel-level capture buffer */
152 pcap_setbuff_win32(pcap_t
*p
, int dim
)
154 if(PacketSetBuff(p
->adapter
,dim
)==FALSE
)
156 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
162 /* Set the driver working mode */
164 pcap_setmode_win32(pcap_t
*p
, int mode
)
166 if(PacketSetMode(p
->adapter
,mode
)==FALSE
)
168 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
175 /*set the minimum amount of data that will release a read call*/
177 pcap_setmintocopy_win32(pcap_t
*p
, int size
)
179 if(PacketSetMinToCopy(p
->adapter
, size
)==FALSE
)
181 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");
187 /*return the Adapter for a pcap_t*/
189 pcap_getadapter_win32(pcap_t
*p
)
195 pcap_read_win32_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
199 register u_char
*bp
, *ep
;
201 struct pcap_win
*pw
= p
->priv
;
206 * Has "pcap_breakloop()" been called?
210 * Yes - clear the flag that indicates that it
211 * has, and return PCAP_ERROR_BREAK to indicate
212 * that we were told to break out of the loop.
215 return (PCAP_ERROR_BREAK
);
218 /* capture the packets */
219 if(PacketReceivePacket(p
->adapter
,p
->Packet
,TRUE
)==FALSE
){
220 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
224 cc
= p
->Packet
->ulBytesReceived
;
226 bp
= p
->Packet
->Buffer
;
232 * Loop through each packet.
234 #define bhp ((struct bpf_hdr *)bp)
237 register int caplen
, hdrlen
;
240 * Has "pcap_breakloop()" been called?
241 * If so, return immediately - if we haven't read any
242 * packets, clear the flag and return PCAP_ERROR_BREAK
243 * to indicate that we were told to break out of the loop,
244 * otherwise leave the flag set, so that the *next* call
245 * will break out of the loop without having read any
246 * packets, and return the number of packets we've
252 return (PCAP_ERROR_BREAK
);
262 caplen
= bhp
->bh_caplen
;
263 hdrlen
= bhp
->bh_hdrlen
;
267 * Short-circuit evaluation: if using BPF filter
268 * in kernel, no need to do it now - we already know
269 * the packet passed the filter.
271 * XXX - bpf_filter() should always return TRUE if
272 * handed a null pointer for the program, but it might
273 * just try to "run" the filter, so we check here.
275 if (pw
->filtering_in_kernel
||
276 p
->fcode
.bf_insns
== NULL
||
277 bpf_filter(p
->fcode
.bf_insns
, datap
, bhp
->bh_datalen
, caplen
)) {
279 * XXX A bpf_hdr matches a pcap_pkthdr.
281 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, datap
);
282 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
283 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
)) {
292 bp
+= Packet_WORDALIGN(caplen
+ hdrlen
);
302 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
304 struct pcap_win
*pw
= p
->priv
;
306 int packet_len
= 0, caplen
= 0;
307 struct pcap_pkthdr pcap_header
;
310 dag_record_t
*header
;
311 unsigned erf_record_len
;
315 unsigned dfp
= p
->adapter
->DagFastProcess
;
318 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
320 /* Get new packets from the network */
321 if(PacketReceivePacket(p
->adapter
, p
->Packet
, TRUE
)==FALSE
){
322 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
326 cc
= p
->Packet
->ulBytesReceived
;
328 /* The timeout has expired but we no packets arrived */
330 header
= (dag_record_t
*)p
->adapter
->DagBuffer
;
333 header
= (dag_record_t
*)p
->bp
;
335 endofbuf
= (char*)header
+ cc
;
338 * Cycle through the packets
342 erf_record_len
= SWAPS(header
->rlen
);
343 if((char*)header
+ erf_record_len
> endofbuf
)
346 /* Increase the number of captured packets */
349 /* Find the beginning of the packet */
350 dp
= ((u_char
*)header
) + dag_record_size
;
352 /* Determine actual packet len */
356 packet_len
= ATM_SNAPLEN
;
357 caplen
= ATM_SNAPLEN
;
363 swt
= SWAPS(header
->wlen
);
364 packet_len
= swt
- (pw
->dag_fcs_bits
);
365 caplen
= erf_record_len
- dag_record_size
- 2;
366 if (caplen
> packet_len
)
375 swt
= SWAPS(header
->wlen
);
376 packet_len
= swt
- (pw
->dag_fcs_bits
);
377 caplen
= erf_record_len
- dag_record_size
;
378 if (caplen
> packet_len
)
386 if(caplen
> p
->snapshot
)
387 caplen
= p
->snapshot
;
390 * Has "pcap_breakloop()" been called?
391 * If so, return immediately - if we haven't read any
392 * packets, clear the flag and return -2 to indicate
393 * that we were told to break out of the loop, otherwise
394 * leave the flag set, so that the *next* call will break
395 * out of the loop without having read any packets, and
396 * return the number of packets we've processed so far.
407 p
->bp
= (char*)header
;
408 p
->cc
= endofbuf
- (char*)header
;
415 /* convert between timestamp formats */
417 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
418 ts
= (ts
& 0xffffffffi
64) * 1000000;
419 ts
+= 0x80000000; /* rounding */
420 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
421 if (pcap_header
.ts
.tv_usec
>= 1000000) {
422 pcap_header
.ts
.tv_usec
-= 1000000;
423 pcap_header
.ts
.tv_sec
++;
427 /* No underlaying filtering system. We need to filter on our own */
428 if (p
->fcode
.bf_insns
)
430 if (bpf_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
432 /* Move to next packet */
433 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
438 /* Fill the header for the user suppplied callback function */
439 pcap_header
.caplen
= caplen
;
440 pcap_header
.len
= packet_len
;
442 /* Call the callback function */
443 (*callback
)(user
, &pcap_header
, dp
);
445 /* Move to next packet */
446 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
448 /* Stop if the number of packets requested by user has been reached*/
449 if (++n
>= cnt
&& !PACKET_COUNT_IS_UNLIMITED(cnt
))
451 p
->bp
= (char*)header
;
452 p
->cc
= endofbuf
- (char*)header
;
456 while((u_char
*)header
< endofbuf
);
460 #endif /* HAVE_DAG_API */
462 /* Send a packet to the network */
464 pcap_inject_win32(pcap_t
*p
, const void *buf
, size_t size
){
465 LPPACKET PacketToSend
;
467 PacketToSend
=PacketAllocatePacket();
469 if (PacketToSend
== NULL
)
471 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketAllocatePacket failed");
475 PacketInitPacket(PacketToSend
,(PVOID
)buf
,size
);
476 if(PacketSendPacket(p
->adapter
,PacketToSend
,TRUE
) == FALSE
){
477 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
478 PacketFreePacket(PacketToSend
);
482 PacketFreePacket(PacketToSend
);
485 * We assume it all got sent if "PacketSendPacket()" succeeded.
486 * "pcap_inject()" is expected to return the number of bytes
493 pcap_cleanup_win32(pcap_t
*p
)
495 if (p
->adapter
!= NULL
) {
496 PacketCloseAdapter(p
->adapter
);
500 PacketFreePacket(p
->Packet
);
503 pcap_cleanup_live_common(p
);
507 pcap_activate_win32(pcap_t
*p
)
509 struct pcap_win
*pw
= p
->priv
;
514 * No monitor mode on Windows. It could be done on
515 * Vista with drivers that support the native 802.11
516 * mechanism and monitor mode.
518 return (PCAP_ERROR_RFMON_NOTSUP
);
524 p
->adapter
= PacketOpenAdapter(p
->opt
.source
);
526 if (p
->adapter
== NULL
)
528 /* Adapter detected but we are not able to open it. Return failure. */
529 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "Error opening adapter: %s", pcap_win32strerror());
534 if(PacketGetNetType (p
->adapter
,&type
) == FALSE
)
536 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "Cannot determine the network type: %s", pcap_win32strerror());
541 switch (type
.LinkType
)
544 p
->linktype
= DLT_EN10MB
;
547 case NdisMedium802_3
:
548 p
->linktype
= DLT_EN10MB
;
550 * This is (presumably) a real Ethernet capture; give it a
551 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
552 * that an application can let you choose it, in case you're
553 * capturing DOCSIS traffic that a Cisco Cable Modem
554 * Termination System is putting out onto an Ethernet (it
555 * doesn't put an Ethernet header onto the wire, it puts raw
556 * DOCSIS frames out on the wire inside the low-level
559 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
561 * If that fails, just leave the list empty.
563 if (p
->dlt_list
!= NULL
) {
564 p
->dlt_list
[0] = DLT_EN10MB
;
565 p
->dlt_list
[1] = DLT_DOCSIS
;
571 p
->linktype
= DLT_FDDI
;
574 case NdisMedium802_5
:
575 p
->linktype
= DLT_IEEE802
;
578 case NdisMediumArcnetRaw
:
579 p
->linktype
= DLT_ARCNET
;
582 case NdisMediumArcnet878_2
:
583 p
->linktype
= DLT_ARCNET
;
587 p
->linktype
= DLT_ATM_RFC1483
;
590 case NdisMediumCHDLC
:
591 p
->linktype
= DLT_CHDLC
;
594 case NdisMediumPPPSerial
:
595 p
->linktype
= DLT_PPP_SERIAL
;
599 p
->linktype
= DLT_NULL
;
602 case NdisMediumBare80211
:
603 p
->linktype
= DLT_IEEE802_11
;
606 case NdisMediumRadio80211
:
607 p
->linktype
= DLT_IEEE802_11_RADIO
;
611 p
->linktype
= DLT_PPI
;
615 p
->linktype
= DLT_EN10MB
; /*an unknown adapter is assumed to be ethernet*/
619 /* Set promiscuous mode */
623 if (PacketSetHwFilter(p
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
) == FALSE
)
625 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to promiscuous mode");
631 if (PacketSetHwFilter(p
->adapter
,NDIS_PACKET_TYPE_ALL_LOCAL
) == FALSE
)
633 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to set hardware filter to non-promiscuous mode");
638 /* Set the buffer size */
639 p
->bufsize
= WIN32_DEFAULT_USER_BUFFER_SIZE
;
641 /* allocate Packet structure used during the capture */
642 if((p
->Packet
= PacketAllocatePacket())==NULL
)
644 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "failed to allocate the PACKET structure");
648 if(!(p
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
651 * Traditional Adapter
654 * If the buffer size wasn't explicitly set, default to
655 * WIN32_DEFAULT_USER_BUFFER_SIZE.
657 if (p
->opt
.buffer_size
== 0)
658 p
->opt
.buffer_size
= WIN32_DEFAULT_KERNEL_BUFFER_SIZE
;
660 if(PacketSetBuff(p
->adapter
,p
->opt
.buffer_size
)==FALSE
)
662 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
666 p
->buffer
= (u_char
*)malloc(p
->bufsize
);
667 if (p
->buffer
== NULL
)
669 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "malloc: %s", pcap_strerror(errno
));
673 PacketInitPacket(p
->Packet
,(BYTE
*)p
->buffer
,p
->bufsize
);
675 if (p
->opt
.immediate
)
677 /* tell the driver to copy the buffer as soon as data arrives */
678 if(PacketSetMinToCopy(p
->adapter
,0)==FALSE
)
680 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,"Error calling PacketSetMinToCopy: %s", pcap_win32strerror());
686 /* tell the driver to copy the buffer only if it contains at least 16K */
687 if(PacketSetMinToCopy(p
->adapter
,16000)==FALSE
)
689 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,"Error calling PacketSetMinToCopy: %s", pcap_win32strerror());
707 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
708 "SYSTEM\\CurrentControlSet\\Services\\DAG",
709 strstr(_strlwr(p
->opt
.source
), "dag"));
712 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
713 if(status
!= ERROR_SUCCESS
)
716 status
= RegQueryValueEx(dagkey
,
723 if(status
!= ERROR_SUCCESS
)
733 p
->snapshot
= PacketSetSnapLen(p
->adapter
, snaplen
);
735 /* Set the length of the FCS associated to any packet. This value
736 * will be subtracted to the packet length */
737 pw
->dag_fcs_bits
= p
->adapter
->DagFcsLen
;
741 #endif /* HAVE_DAG_API */
743 PacketSetReadTimeout(p
->adapter
, p
->opt
.timeout
);
746 if(p
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
748 /* install dag specific handlers for read and setfilter */
749 p
->read_op
= pcap_read_win32_dag
;
750 p
->setfilter_op
= pcap_setfilter_win32_dag
;
754 #endif /* HAVE_DAG_API */
755 /* install traditional npf handlers for read and setfilter */
756 p
->read_op
= pcap_read_win32_npf
;
757 p
->setfilter_op
= pcap_setfilter_win32_npf
;
760 #endif /* HAVE_DAG_API */
761 p
->setdirection_op
= NULL
; /* Not implemented. */
762 /* XXX - can this be implemented on some versions of Windows? */
763 p
->inject_op
= pcap_inject_win32
;
764 p
->set_datalink_op
= NULL
; /* can't change data link type */
765 p
->getnonblock_op
= pcap_getnonblock_win32
;
766 p
->setnonblock_op
= pcap_setnonblock_win32
;
767 p
->stats_op
= pcap_stats_win32
;
768 p
->setbuff_op
= pcap_setbuff_win32
;
769 p
->setmode_op
= pcap_setmode_win32
;
770 p
->setmintocopy_op
= pcap_setmintocopy_win32
;
771 p
->getadapter_op
= pcap_getadapter_win32
;
772 p
->cleanup_op
= pcap_cleanup_win32
;
776 pcap_cleanup_win32(p
);
781 pcap_create_interface(const char *device
, char *ebuf
)
785 if (strlen(device
) == 1)
788 * It's probably a unicode string
789 * Convert to ascii and pass it to pcap_create_common
791 * This wonderful hack is needed because pcap_lookupdev still returns
792 * unicode strings, and it's used by windump when no device is specified
793 * in the command line
798 length
= wcslen((wchar_t*)device
);
800 deviceAscii
= (char*)malloc(length
+ 1);
802 if (deviceAscii
== NULL
)
804 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "Malloc failed");
808 snprintf(deviceAscii
, length
+ 1, "%ws", (wchar_t*)device
);
809 p
= pcap_create_common(deviceAscii
, ebuf
, sizeof (struct pcap_win
));
814 p
= pcap_create_common(device
, ebuf
, sizeof (struct pcap_win
));
820 p
->activate_op
= pcap_activate_win32
;
825 pcap_setfilter_win32_npf(pcap_t
*p
, struct bpf_program
*fp
)
827 struct pcap_win
*pw
= p
->priv
;
829 if(PacketSetBpf(p
->adapter
,fp
)==FALSE
){
831 * Kernel filter not installed.
833 * XXX - we don't know whether this failed because:
835 * the kernel rejected the filter program as invalid,
836 * in which case we should fall back on userland
839 * the kernel rejected the filter program as too big,
840 * in which case we should again fall back on
841 * userland filtering;
843 * there was some other problem, in which case we
844 * should probably report an error.
846 * For NPF devices, the Win32 status will be
847 * STATUS_INVALID_DEVICE_REQUEST for invalid
848 * filters, but I don't know what it'd be for
849 * other problems, and for some other devices
850 * it might not be set at all.
852 * So we just fall back on userland filtering in
857 * install_bpf_program() validates the program.
859 * XXX - what if we already have a filter in the kernel?
861 if (install_bpf_program(p
, fp
) < 0)
863 pw
->filtering_in_kernel
= 0; /* filtering in userland */
870 pw
->filtering_in_kernel
= 1; /* filtering in the kernel */
873 * Discard any previously-received packets, as they might have
874 * passed whatever filter was formerly in effect, but might
875 * not pass this filter (BIOCSETF discards packets buffered
876 * in the kernel, so you can lose packets in any case).
883 * We filter at user level, since the kernel driver does't process the packets
886 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
890 strncpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
894 /* Install a user level filter */
895 if (install_bpf_program(p
, fp
) < 0)
897 snprintf(p
->errbuf
, sizeof(p
->errbuf
),
898 "setfilter, unable to install the filter: %s", pcap_strerror(errno
));
906 pcap_getnonblock_win32(pcap_t
*p
, char *errbuf
)
908 struct pcap_win
*pw
= p
->priv
;
911 * XXX - if there were a PacketGetReadTimeout() call, we
912 * would use it, and return 1 if the timeout is -1
915 return (pw
->nonblock
);
919 pcap_setnonblock_win32(pcap_t
*p
, int nonblock
, char *errbuf
)
921 struct pcap_win
*pw
= p
->priv
;
926 * Set the read timeout to -1 for non-blocking mode.
931 * Restore the timeout set when the device was opened.
932 * (Note that this may be -1, in which case we're not
933 * really leaving non-blocking mode.)
935 newtimeout
= p
->opt
.timeout
;
937 if (!PacketSetReadTimeout(p
->adapter
, newtimeout
)) {
938 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
939 "PacketSetReadTimeout: %s", pcap_win32strerror());
942 pw
->nonblock
= (newtimeout
== -1);
946 /*platform-dependent routine to add devices other than NDIS interfaces*/
948 pcap_platform_finddevs(pcap_if_t
**alldevsp
, char *errbuf
)