2 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2006 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.
35 static const char rcsid
[] _U_
=
36 "@(#) $Header: /tcpdump/master/libpcap/pcap-win32.c,v 1.25.2.5 2006/08/09 19:18:41 gianluca Exp $ (LBL)";
45 #endif /* HAVE_DAG_API */
48 #define errno (*_errno())
49 #endif /* __MINGW32__ */
52 #include <pcap-remote.h>
53 #endif /* HAVE_REMOTE */
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 #define PcapBufSize 256000 /*dimension of the buffer in the pcap_t structure*/
61 #define SIZE_BUF 1000000
63 /* Equivalent to ntohs(), but a lot faster under Windows */
64 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
67 * Header that the WinPcap driver associates to the packets.
71 struct timeval bh_tstamp
; /* time stamp */
72 bpf_u_int32 bh_caplen
; /* length of captured portion */
73 bpf_u_int32 bh_datalen
; /* original length of packet */
74 u_short bh_hdrlen
; /* length of bpf header (this struct
75 plus alignment padding) */
82 WORD wVersionRequested
;
85 wVersionRequested
= MAKEWORD( 1, 1);
86 err
= WSAStartup( wVersionRequested
, &wsaData
);
96 pcap_stats_win32(pcap_t
*p
, struct pcap_stat
*ps
)
99 if(PacketGetStats(p
->adapter
, (struct bpf_stat
*)ps
) != TRUE
){
100 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "PacketGetStats error: %s", pcap_win32strerror());
108 pcap_read_win32_npf(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
112 register u_char
*bp
, *ep
;
115 static int samp_npkt
; // parameter needed for sampling, with '1 out of N' method has been requested
116 static struct timeval samp_time
; // parameter needed for sampling, with '1 every N ms' method has been requested
117 #endif /* HAVE_REMOTE */
122 * Has "pcap_breakloop()" been called?
126 * Yes - clear the flag that indicates that it
127 * has, and return -2 to indicate that we were
128 * told to break out of the loop.
134 /* capture the packets */
135 if(PacketReceivePacket(p
->adapter
,p
->Packet
,TRUE
)==FALSE
){
136 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
140 cc
= p
->Packet
->ulBytesReceived
;
142 bp
= p
->Packet
->Buffer
;
148 * Loop through each packet.
150 #define bhp ((struct bpf_hdr *)bp)
153 register int caplen
, hdrlen
;
156 * Has "pcap_breakloop()" been called?
157 * If so, return immediately - if we haven't read any
158 * packets, clear the flag and return -2 to indicate
159 * that we were told to break out of the loop, otherwise
160 * leave the flag set, so that the *next* call will break
161 * out of the loop without having read any packets, and
162 * return the number of packets we've processed so far.
177 caplen
= bhp
->bh_caplen
;
178 hdrlen
= bhp
->bh_hdrlen
;
181 if (p
->rmt_samp
.method
== PCAP_SAMP_1_EVERY_N
)
183 samp_npkt
= (samp_npkt
+ 1) % p
->rmt_samp
.value
;
185 // Discard all packets that are not '1 out of N'
188 bp
+= BPF_WORDALIGN(caplen
+ hdrlen
);
193 if (p
->rmt_samp
.method
== PCAP_SAMP_FIRST_AFTER_N_MS
)
195 struct pcap_pkthdr
*pkt_header
= (struct pcap_pkthdr
*) bp
;
197 // Check if the timestamp of the arrived packet is smaller than our target time
198 if ( (pkt_header
->ts
.tv_sec
< samp_time
.tv_sec
) ||
199 ( (pkt_header
->ts
.tv_sec
== samp_time
.tv_sec
) && (pkt_header
->ts
.tv_usec
< samp_time
.tv_usec
) ) )
201 bp
+= BPF_WORDALIGN(caplen
+ hdrlen
);
205 // The arrived packet is suitable for being sent to the remote host
206 // So, let's update the target time
207 samp_time
.tv_usec
= pkt_header
->ts
.tv_usec
+ p
->rmt_samp
.value
* 1000;
208 if (samp_time
.tv_usec
> 1000000)
210 samp_time
.tv_sec
= pkt_header
->ts
.tv_sec
+ samp_time
.tv_usec
/ 1000000;
211 samp_time
.tv_usec
= samp_time
.tv_usec
% 1000000;
214 #endif /* HAVE_REMOTE */
217 * XXX A bpf_hdr matches a pcap_pkthdr.
219 (*callback
)(user
, (struct pcap_pkthdr
*)bp
, bp
+ hdrlen
);
220 bp
+= BPF_WORDALIGN(caplen
+ hdrlen
);
221 if (++n
>= cnt
&& cnt
> 0) {
234 pcap_read_win32_dag(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
237 int packet_len
= 0, caplen
= 0;
238 struct pcap_pkthdr pcap_header
;
241 dag_record_t
*header
;
242 unsigned erf_record_len
;
246 unsigned dfp
= p
->adapter
->DagFastProcess
;
249 if (cc
== 0) /* Get new packets only if we have processed all the ones of the previous read */
251 /* Get new packets from the network */
252 if(PacketReceivePacket(p
->adapter
, p
->Packet
, TRUE
)==FALSE
){
253 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "read error: PacketReceivePacket failed");
257 cc
= p
->Packet
->ulBytesReceived
;
259 /* The timeout has expired but we no packets arrived */
261 header
= (dag_record_t
*)p
->adapter
->DagBuffer
;
264 header
= (dag_record_t
*)p
->bp
;
266 endofbuf
= (char*)header
+ cc
;
269 * Cycle through the packets
273 erf_record_len
= SWAPS(header
->rlen
);
274 if((char*)header
+ erf_record_len
> endofbuf
)
277 /* Increase the number of captured packets */
278 p
->md
.stat
.ps_recv
++;
280 /* Find the beginning of the packet */
281 dp
= ((u_char
*)header
) + dag_record_size
;
283 /* Determine actual packet len */
287 packet_len
= ATM_SNAPLEN
;
288 caplen
= ATM_SNAPLEN
;
294 swt
= SWAPS(header
->wlen
);
295 packet_len
= swt
- (p
->md
.dag_fcs_bits
);
296 caplen
= erf_record_len
- dag_record_size
- 2;
297 if (caplen
> packet_len
)
306 swt
= SWAPS(header
->wlen
);
307 packet_len
= swt
- (p
->md
.dag_fcs_bits
);
308 caplen
= erf_record_len
- dag_record_size
;
309 if (caplen
> packet_len
)
317 if(caplen
> p
->snapshot
)
318 caplen
= p
->snapshot
;
321 * Has "pcap_breakloop()" been called?
322 * If so, return immediately - if we haven't read any
323 * packets, clear the flag and return -2 to indicate
324 * that we were told to break out of the loop, otherwise
325 * leave the flag set, so that the *next* call will break
326 * out of the loop without having read any packets, and
327 * return the number of packets we've processed so far.
338 p
->bp
= (char*)header
;
339 p
->cc
= endofbuf
- (char*)header
;
346 /* convert between timestamp formats */
348 pcap_header
.ts
.tv_sec
= (int)(ts
>> 32);
349 ts
= (ts
& 0xffffffffi
64) * 1000000;
350 ts
+= 0x80000000; /* rounding */
351 pcap_header
.ts
.tv_usec
= (int)(ts
>> 32);
352 if (pcap_header
.ts
.tv_usec
>= 1000000) {
353 pcap_header
.ts
.tv_usec
-= 1000000;
354 pcap_header
.ts
.tv_sec
++;
358 /* No underlaying filtering system. We need to filter on our own */
359 if (p
->fcode
.bf_insns
)
361 if (bpf_filter(p
->fcode
.bf_insns
, dp
, packet_len
, caplen
) == 0)
363 /* Move to next packet */
364 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
369 /* Fill the header for the user suppplied callback function */
370 pcap_header
.caplen
= caplen
;
371 pcap_header
.len
= packet_len
;
373 /* Call the callback function */
374 (*callback
)(user
, &pcap_header
, dp
);
376 /* Move to next packet */
377 header
= (dag_record_t
*)((char*)header
+ erf_record_len
);
379 /* Stop if the number of packets requested by user has been reached*/
380 if (++n
>= cnt
&& cnt
> 0)
382 p
->bp
= (char*)header
;
383 p
->cc
= endofbuf
- (char*)header
;
387 while((u_char
*)header
< endofbuf
);
391 #endif /* HAVE_DAG_API */
393 /* Send a packet to the network */
395 pcap_inject_win32(pcap_t
*p
, const void *buf
, size_t size
){
396 LPPACKET PacketToSend
;
398 PacketToSend
=PacketAllocatePacket();
400 if (PacketToSend
== NULL
)
402 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketAllocatePacket failed");
406 PacketInitPacket(PacketToSend
,(PVOID
)buf
,size
);
407 if(PacketSendPacket(p
->adapter
,PacketToSend
,TRUE
) == FALSE
){
408 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "send error: PacketSendPacket failed");
409 PacketFreePacket(PacketToSend
);
413 PacketFreePacket(PacketToSend
);
416 * We assume it all got sent if "PacketSendPacket()" succeeded.
417 * "pcap_inject()" is expected to return the number of bytes
424 pcap_close_win32(pcap_t
*p
)
426 pcap_close_common(p
);
427 if (p
->adapter
!= NULL
) {
428 PacketCloseAdapter(p
->adapter
);
432 PacketFreePacket(p
->Packet
);
438 pcap_open_live(const char *device
, int snaplen
, int promisc
, int to_ms
,
445 char host
[PCAP_BUF_SIZE
+ 1];
446 char port
[PCAP_BUF_SIZE
+ 1];
447 char name
[PCAP_BUF_SIZE
+ 1];
451 Retrofit; we have to make older applications compatible with the remote capture
452 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
453 Obviously, we cannot exploit all the new features; for instance, we cannot
454 send authentication, we cannot use a UDP data connection, and so on.
456 if (pcap_parsesrcstr(device
, &srctype
, host
, port
, name
, ebuf
) )
459 if (srctype
== PCAP_SRC_IFREMOTE
)
461 p
= pcap_opensource_remote(device
, NULL
, ebuf
);
466 p
->snapshot
= snaplen
;
468 p
->rmt_flags
= (promisc
) ? PCAP_OPENFLAG_PROMISCUOUS
: 0;
472 #endif /* HAVE_REMOTE */
477 p
= (pcap_t
*)malloc(sizeof(*p
));
480 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s", pcap_strerror(errno
));
483 memset(p
, 0, sizeof(*p
));
486 p
->adapter
= PacketOpenAdapter((char*)device
);
488 if (p
->adapter
== NULL
)
491 /* Adapter detected but we are not able to open it. Return failure. */
492 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "Error opening adapter: %s", pcap_win32strerror());
497 if(PacketGetNetType (p
->adapter
,&type
) == FALSE
)
499 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "Cannot determine the network type: %s", pcap_win32strerror());
504 switch (type
.LinkType
)
507 p
->linktype
= DLT_EN10MB
;
510 case NdisMedium802_3
:
511 p
->linktype
= DLT_EN10MB
;
513 * This is (presumably) a real Ethernet capture; give it a
514 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
515 * that an application can let you choose it, in case you're
516 * capturing DOCSIS traffic that a Cisco Cable Modem
517 * Termination System is putting out onto an Ethernet (it
518 * doesn't put an Ethernet header onto the wire, it puts raw
519 * DOCSIS frames out on the wire inside the low-level
522 p
->dlt_list
= (u_int
*) malloc(sizeof(u_int
) * 2);
524 * If that fails, just leave the list empty.
526 if (p
->dlt_list
!= NULL
) {
527 p
->dlt_list
[0] = DLT_EN10MB
;
528 p
->dlt_list
[1] = DLT_DOCSIS
;
534 p
->linktype
= DLT_FDDI
;
537 case NdisMedium802_5
:
538 p
->linktype
= DLT_IEEE802
;
541 case NdisMediumArcnetRaw
:
542 p
->linktype
= DLT_ARCNET
;
545 case NdisMediumArcnet878_2
:
546 p
->linktype
= DLT_ARCNET
;
550 p
->linktype
= DLT_ATM_RFC1483
;
553 case NdisMediumCHDLC
:
554 p
->linktype
= DLT_CHDLC
;
557 case NdisMediumPPPSerial
:
558 p
->linktype
= DLT_PPP_SERIAL
;
562 p
->linktype
= DLT_NULL
;
565 case NdisMediumBare80211
:
566 p
->linktype
= DLT_IEEE802_11
;
569 case NdisMediumRadio80211
:
570 p
->linktype
= DLT_IEEE802_11_RADIO
;
574 p
->linktype
= DLT_EN10MB
; /*an unknown adapter is assumed to be ethernet*/
578 /* Set promisquous mode */
579 if (promisc
) PacketSetHwFilter(p
->adapter
,NDIS_PACKET_TYPE_PROMISCUOUS
);
580 else PacketSetHwFilter(p
->adapter
,NDIS_PACKET_TYPE_ALL_LOCAL
);
582 /* Set the buffer size */
583 p
->bufsize
= PcapBufSize
;
585 /* Store the timeout. Used by pcap_setnonblock() */
588 /* allocate Packet structure used during the capture */
589 if((p
->Packet
= PacketAllocatePacket())==NULL
)
591 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "failed to allocate the PACKET structure");
595 if(!(p
->adapter
->Flags
& INFO_FLAG_DAG_CARD
))
598 * Traditional Adapter
601 p
->buffer
= (u_char
*)malloc(PcapBufSize
);
602 if (p
->buffer
== NULL
)
604 snprintf(ebuf
, PCAP_ERRBUF_SIZE
, "malloc: %s", pcap_strerror(errno
));
608 PacketInitPacket(p
->Packet
,(BYTE
*)p
->buffer
,p
->bufsize
);
610 p
->snapshot
= snaplen
;
612 /* allocate the standard buffer in the driver */
613 if(PacketSetBuff( p
->adapter
, SIZE_BUF
)==FALSE
)
615 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,"driver error: not enough memory to allocate the kernel buffer\n");
619 /* tell the driver to copy the buffer only if it contains at least 16K */
620 if(PacketSetMinToCopy(p
->adapter
,16000)==FALSE
)
622 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,"Error calling PacketSetMinToCopy: %s\n", pcap_win32strerror());
639 snprintf(keyname
, sizeof(keyname
), "%s\\CardParams\\%s",
640 "SYSTEM\\CurrentControlSet\\Services\\DAG",
641 strstr(_strlwr((char*)device
), "dag"));
644 status
= RegOpenKeyEx(HKEY_LOCAL_MACHINE
, keyname
, 0, KEY_READ
, &dagkey
);
645 if(status
!= ERROR_SUCCESS
)
648 status
= RegQueryValueEx(dagkey
,
655 if(status
!= ERROR_SUCCESS
)
665 p
->snapshot
= PacketSetSnapLen(p
->adapter
, snaplen
);
667 /* Set the length of the FCS associated to any packet. This value
668 * will be subtracted to the packet length */
669 p
->md
.dag_fcs_bits
= p
->adapter
->DagFcsLen
;
673 #endif /* HAVE_DAG_API */
675 PacketSetReadTimeout(p
->adapter
, to_ms
);
678 if(p
->adapter
->Flags
& INFO_FLAG_DAG_CARD
)
680 /* install dag specific handlers for read and setfilter */
681 p
->read_op
= pcap_read_win32_dag
;
682 p
->setfilter_op
= pcap_setfilter_win32_dag
;
686 #endif /* HAVE_DAG_API */
687 /* install traditional npf handlers for read and setfilter */
688 p
->read_op
= pcap_read_win32_npf
;
689 p
->setfilter_op
= pcap_setfilter_win32_npf
;
692 #endif /* HAVE_DAG_API */
693 p
->setdirection_op
= NULL
; /* Not implemented. */
694 /* XXX - can this be implemented on some versions of Windows? */
695 p
->inject_op
= pcap_inject_win32
;
696 p
->set_datalink_op
= NULL
; /* can't change data link type */
697 p
->getnonblock_op
= pcap_getnonblock_win32
;
698 p
->setnonblock_op
= pcap_setnonblock_win32
;
699 p
->stats_op
= pcap_stats_win32
;
700 p
->close_op
= pcap_close_win32
;
705 PacketCloseAdapter(p
->adapter
);
706 if (p
->buffer
!= NULL
)
709 PacketFreePacket(p
->Packet
);
711 * Get rid of any link-layer type list we allocated.
713 if (p
->dlt_list
!= NULL
)
721 pcap_setfilter_win32_npf(pcap_t
*p
, struct bpf_program
*fp
)
723 if(PacketSetBpf(p
->adapter
,fp
)==FALSE
){
725 * Kernel filter not installed.
726 * XXX - fall back on userland filtering, as is done
727 * on other platforms?
729 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "Driver error: cannot set bpf filter: %s", pcap_win32strerror());
734 * Discard any previously-received packets, as they might have
735 * passed whatever filter was formerly in effect, but might
736 * not pass this filter (BIOCSETF discards packets buffered
737 * in the kernel, so you can lose packets in any case).
744 * We filter at user level, since the kernel driver does't process the packets
747 pcap_setfilter_win32_dag(pcap_t
*p
, struct bpf_program
*fp
) {
751 strncpy(p
->errbuf
, "setfilter: No filter specified", sizeof(p
->errbuf
));
755 /* Install a user level filter */
756 if (install_bpf_program(p
, fp
) < 0)
758 snprintf(p
->errbuf
, sizeof(p
->errbuf
),
759 "setfilter, unable to install the filter: %s", pcap_strerror(errno
));
769 pcap_getnonblock_win32(pcap_t
*p
, char *errbuf
)
772 * XXX - if there were a PacketGetReadTimeout() call, we
773 * would use it, and return 1 if the timeout is -1
776 return (p
->nonblock
);
780 pcap_setnonblock_win32(pcap_t
*p
, int nonblock
, char *errbuf
)
786 * Set the read timeout to -1 for non-blocking mode.
791 * Restore the timeout set when the device was opened.
792 * (Note that this may be -1, in which case we're not
793 * really leaving non-blocking mode.)
795 newtimeout
= p
->timeout
;
797 if (!PacketSetReadTimeout(p
->adapter
, newtimeout
)) {
798 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
799 "PacketSetReadTimeout: %s", pcap_win32strerror());
802 p
->nonblock
= (newtimeout
== -1);
806 /* Set the driver working mode */
808 pcap_setmode(pcap_t
*p
, int mode
){
810 if (p
->adapter
==NULL
)
812 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "impossible to set mode while reading from a file");
816 if(PacketSetMode(p
->adapter
,mode
)==FALSE
)
818 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: working mode not recognized");
825 /* Set the dimension of the kernel-level capture buffer */
827 pcap_setbuff(pcap_t
*p
, int dim
)
830 if (p
->rmt_clientside
)
832 /* Currently, this is a bug: the capture buffer cannot be set with remote capture */
835 #endif /* HAVE_REMOTE */
837 if (p
->adapter
==NULL
)
839 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "The kernel buffer size cannot be set while reading from a file");
843 if(PacketSetBuff(p
->adapter
,dim
)==FALSE
)
845 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: not enough memory to allocate the kernel buffer");
851 /*set the minimum amount of data that will release a read call*/
853 pcap_setmintocopy(pcap_t
*p
, int size
)
855 if (p
->adapter
==NULL
)
857 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "Impossible to set the mintocopy parameter on an offline capture");
861 if(PacketSetMinToCopy(p
->adapter
, size
)==FALSE
)
863 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "driver error: unable to set the requested mintocopy size");