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.
35 static const char rcsid[] _U_ =
36 "@(#) $Header: /tcpdump/master/libpcap/pcap-win32.c,v 1.42 2008-05-21 22:15:25 gianluca Exp $ (LBL)";
45 #include <ddk/ntddndis.h>
47 #endif /*__MINGW64__*/
50 #endif /*__MINGW32__*/
54 #endif /* HAVE_DAG_API */
57 #define errno (*_errno())
58 #endif /* __MINGW32__ */
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 * Header that the WinPcap driver associates to the packets.
79 struct timeval bh_tstamp; /* time stamp */
80 bpf_u_int32 bh_caplen; /* length of captured portion */
81 bpf_u_int32 bh_datalen; /* original length of packet */
82 u_short bh_hdrlen; /* length of bpf header (this struct
83 plus alignment padding) */
86 CRITICAL_SECTION g_PcapCompileCriticalSection;
94 if (dwReason == DLL_PROCESS_ATTACH)
96 InitializeCriticalSection(&g_PcapCompileCriticalSection);
106 WORD wVersionRequested;
109 wVersionRequested = MAKEWORD( 1, 1);
110 err = WSAStartup( wVersionRequested, &wsaData );
120 pcap_stats_win32(pcap_t *p, struct pcap_stat *ps)
123 if(PacketGetStats(p->adapter, (struct bpf_stat*)ps) != TRUE){
124 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "PacketGetStats error: %s", pcap_win32strerror());
131 /* Set the dimension of the kernel-level capture buffer */
133 pcap_setbuff_win32(pcap_t *p, int dim)
135 if(PacketSetBuff(p->adapter,dim)==FALSE)
137 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
143 /* Set the driver working mode */
145 pcap_setmode_win32(pcap_t *p, int mode)
147 if(PacketSetMode(p->adapter,mode)==FALSE)
149 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
156 /*set the minimum amount of data that will release a read call*/
158 pcap_setmintocopy_win32(pcap_t *p, int size)
160 if(PacketSetMinToCopy(p->adapter, size)==FALSE)
162 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
169 pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
173 register u_char *bp, *ep;
178 * Has "pcap_breakloop()" been called?
182 * Yes - clear the flag that indicates that it
183 * has, and return -2 to indicate that we were
184 * told to break out of the loop.
190 /* capture the packets */
191 if(PacketReceivePacket(p->adapter,p->Packet,TRUE)==FALSE){
192 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
196 cc = p->Packet->ulBytesReceived;
198 bp = p->Packet->Buffer;
204 * Loop through each packet.
206 #define bhp ((struct bpf_hdr *)bp)
209 register int caplen, hdrlen;
212 * Has "pcap_breakloop()" been called?
213 * If so, return immediately - if we haven't read any
214 * packets, clear the flag and return -2 to indicate
215 * that we were told to break out of the loop, otherwise
216 * leave the flag set, so that the *next* call will break
217 * out of the loop without having read any packets, and
218 * return the number of packets we've processed so far.
233 caplen = bhp->bh_caplen;
234 hdrlen = bhp->bh_hdrlen;
237 * XXX A bpf_hdr matches a pcap_pkthdr.
239 (*callback)(user, (struct pcap_pkthdr*)bp, bp + hdrlen);
240 bp += Packet_WORDALIGN(caplen + hdrlen);
241 if (++n >= cnt && cnt > 0) {
254 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
257 int packet_len = 0, caplen = 0;
258 struct pcap_pkthdr pcap_header;
261 dag_record_t *header;
262 unsigned erf_record_len;
266 unsigned dfp = p->adapter->DagFastProcess;
269 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
271 /* Get new packets from the network */
272 if(PacketReceivePacket(p->adapter, p->Packet, TRUE)==FALSE){
273 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
277 cc = p->Packet->ulBytesReceived;
279 /* The timeout has expired but we no packets arrived */
281 header = (dag_record_t*)p->adapter->DagBuffer;
284 header = (dag_record_t*)p->bp;
286 endofbuf = (char*)header + cc;
289 * Cycle through the packets
293 erf_record_len = SWAPS(header->rlen);
294 if((char*)header + erf_record_len > endofbuf)
297 /* Increase the number of captured packets */
298 p->md.stat.ps_recv++;
300 /* Find the beginning of the packet */
301 dp = ((u_char *)header) + dag_record_size;
303 /* Determine actual packet len */
307 packet_len = ATM_SNAPLEN;
308 caplen = ATM_SNAPLEN;
314 swt = SWAPS(header->wlen);
315 packet_len = swt - (p->md.dag_fcs_bits);
316 caplen = erf_record_len - dag_record_size - 2;
317 if (caplen > packet_len)
326 swt = SWAPS(header->wlen);
327 packet_len = swt - (p->md.dag_fcs_bits);
328 caplen = erf_record_len - dag_record_size;
329 if (caplen > packet_len)
337 if(caplen > p->snapshot)
338 caplen = p->snapshot;
341 * Has "pcap_breakloop()" been called?
342 * If so, return immediately - if we haven't read any
343 * packets, clear the flag and return -2 to indicate
344 * that we were told to break out of the loop, otherwise
345 * leave the flag set, so that the *next* call will break
346 * out of the loop without having read any packets, and
347 * return the number of packets we've processed so far.
358 p->bp = (char*)header;
359 p->cc = endofbuf - (char*)header;
366 /* convert between timestamp formats */
368 pcap_header.ts.tv_sec = (int)(ts >> 32);
369 ts = (ts & 0xffffffffi64) * 1000000;
370 ts += 0x80000000; /* rounding */
371 pcap_header.ts.tv_usec = (int)(ts >> 32);
372 if (pcap_header.ts.tv_usec >= 1000000) {
373 pcap_header.ts.tv_usec -= 1000000;
374 pcap_header.ts.tv_sec++;
378 /* No underlaying filtering system. We need to filter on our own */
379 if (p->fcode.bf_insns)
381 if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
383 /* Move to next packet */
384 header = (dag_record_t*)((char*)header + erf_record_len);
389 /* Fill the header for the user suppplied callback function */
390 pcap_header.caplen = caplen;
391 pcap_header.len = packet_len;
393 /* Call the callback function */
394 (*callback)(user, &pcap_header, dp);
396 /* Move to next packet */
397 header = (dag_record_t*)((char*)header + erf_record_len);
399 /* Stop if the number of packets requested by user has been reached*/
400 if (++n >= cnt && cnt > 0)
402 p->bp = (char*)header;
403 p->cc = endofbuf - (char*)header;
407 while((u_char*)header < endofbuf);
411 #endif /* HAVE_DAG_API */
413 /* Send a packet to the network */
415 pcap_inject_win32(pcap_t *p, const void *buf, size_t size){
416 LPPACKET PacketToSend;
418 PacketToSend=PacketAllocatePacket();
420 if (PacketToSend == NULL)
422 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketAllocatePacket failed");
426 PacketInitPacket(PacketToSend,(PVOID)buf,size);
427 if(PacketSendPacket(p->adapter,PacketToSend,TRUE) == FALSE){
428 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
429 PacketFreePacket(PacketToSend);
433 PacketFreePacket(PacketToSend);
436 * We assume it all got sent if "PacketSendPacket()" succeeded.
437 * "pcap_inject()" is expected to return the number of bytes
444 pcap_cleanup_win32(pcap_t *p)
446 if (p->adapter != NULL) {
447 PacketCloseAdapter(p->adapter);
451 PacketFreePacket(p->Packet);
454 pcap_cleanup_live_common(p);
458 pcap_activate_win32(pcap_t *p)
464 * No monitor mode on Windows. It could be done on
465 * Vista with drivers that support the native 802.11
466 * mechanism and monitor mode.
468 return (PCAP_ERROR_RFMON_NOTSUP);
474 p->adapter = PacketOpenAdapter(p->opt.source);
476 if (p->adapter == NULL)
478 /* Adapter detected but we are not able to open it. Return failure. */
479 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Error opening adapter: %s", pcap_win32strerror());
484 if(PacketGetNetType (p->adapter,&type) == FALSE)
486 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Cannot determine the network type: %s", pcap_win32strerror());
491 switch (type.LinkType)
494 p->linktype = DLT_EN10MB;
497 case NdisMedium802_3:
498 p->linktype = DLT_EN10MB;
500 * This is (presumably) a real Ethernet capture; give it a
501 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
502 * that an application can let you choose it, in case you're
503 * capturing DOCSIS traffic that a Cisco Cable Modem
504 * Termination System is putting out onto an Ethernet (it
505 * doesn't put an Ethernet header onto the wire, it puts raw
506 * DOCSIS frames out on the wire inside the low-level
509 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
511 * If that fails, just leave the list empty.
513 if (p->dlt_list != NULL) {
514 p->dlt_list[0] = DLT_EN10MB;
515 p->dlt_list[1] = DLT_DOCSIS;
521 p->linktype = DLT_FDDI;
524 case NdisMedium802_5:
525 p->linktype = DLT_IEEE802;
528 case NdisMediumArcnetRaw:
529 p->linktype = DLT_ARCNET;
532 case NdisMediumArcnet878_2:
533 p->linktype = DLT_ARCNET;
537 p->linktype = DLT_ATM_RFC1483;
540 case NdisMediumCHDLC:
541 p->linktype = DLT_CHDLC;
544 case NdisMediumPPPSerial:
545 p->linktype = DLT_PPP_SERIAL;
549 p->linktype = DLT_NULL;
552 case NdisMediumBare80211:
553 p->linktype = DLT_IEEE802_11;
556 case NdisMediumRadio80211:
557 p->linktype = DLT_IEEE802_11_RADIO;
561 p->linktype = DLT_PPI;
565 p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/
569 /* Set promiscuous mode */
573 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
575 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
581 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL) == FALSE)
583 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
588 /* Set the buffer size */
589 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
591 /* allocate Packet structure used during the capture */
592 if((p->Packet = PacketAllocatePacket())==NULL)
594 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to allocate the PACKET structure");
598 if(!(p->adapter->Flags & INFO_FLAG_DAG_CARD))
601 * Traditional Adapter
604 * If the buffer size wasn't explicitly set, default to
605 * WIN32_DEFAULT_USER_BUFFER_SIZE.
607 if (p->opt.buffer_size == 0)
608 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
610 if(PacketSetBuff(p->adapter,p->opt.buffer_size)==FALSE)
612 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
616 p->buffer = (u_char *)malloc(p->bufsize);
617 if (p->buffer == NULL)
619 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
623 PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize);
625 /* tell the driver to copy the buffer only if it contains at least 16K */
626 if(PacketSetMinToCopy(p->adapter,16000)==FALSE)
628 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,"Error calling PacketSetMinToCopy: %s", pcap_win32strerror());
645 snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
646 "SYSTEM\\CurrentControlSet\\Services\\DAG",
647 strstr(_strlwr(p->opt.source), "dag"));
650 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
651 if(status != ERROR_SUCCESS)
654 status = RegQueryValueEx(dagkey,
661 if(status != ERROR_SUCCESS)
671 p->snapshot = PacketSetSnapLen(p->adapter, snaplen);
673 /* Set the length of the FCS associated to any packet. This value
674 * will be subtracted to the packet length */
675 p->md.dag_fcs_bits = p->adapter->DagFcsLen;
679 #endif /* HAVE_DAG_API */
681 PacketSetReadTimeout(p->adapter, p->md.timeout);
684 if(p->adapter->Flags & INFO_FLAG_DAG_CARD)
686 /* install dag specific handlers for read and setfilter */
687 p->read_op = pcap_read_win32_dag;
688 p->setfilter_op = pcap_setfilter_win32_dag;
692 #endif /* HAVE_DAG_API */
693 /* install traditional npf handlers for read and setfilter */
694 p->read_op = pcap_read_win32_npf;
695 p->setfilter_op = pcap_setfilter_win32_npf;
698 #endif /* HAVE_DAG_API */
699 p->setdirection_op = NULL; /* Not implemented. */
700 /* XXX - can this be implemented on some versions of Windows? */
701 p->inject_op = pcap_inject_win32;
702 p->set_datalink_op = NULL; /* can't change data link type */
703 p->getnonblock_op = pcap_getnonblock_win32;
704 p->setnonblock_op = pcap_setnonblock_win32;
705 p->stats_op = pcap_stats_win32;
706 p->setbuff_op = pcap_setbuff_win32;
707 p->setmode_op = pcap_setmode_win32;
708 p->setmintocopy_op = pcap_setmintocopy_win32;
709 p->cleanup_op = pcap_cleanup_win32;
713 pcap_cleanup_win32(p);
718 pcap_create_interface(const char *device, char *ebuf)
722 if (strlen(device) == 1)
725 * It's probably a unicode string
726 * Convert to ascii and pass it to pcap_create_common
728 * This wonderful hack is needed because pcap_lookupdev still returns
729 * unicode strings, and it's used by windump when no device is specified
730 * in the command line
735 length = wcslen((wchar_t*)device);
737 deviceAscii = (char*)malloc(length + 1);
739 if (deviceAscii == NULL)
741 snprintf(ebuf, PCAP_ERRBUF_SIZE, "Malloc failed");
745 snprintf(deviceAscii, length + 1, "%ws", (wchar_t*)device);
746 p = pcap_create_common(deviceAscii, ebuf);
751 p = pcap_create_common(device, ebuf);
757 p->activate_op = pcap_activate_win32;
762 pcap_setfilter_win32_npf(pcap_t *p, struct bpf_program *fp)
764 if(PacketSetBpf(p->adapter,fp)==FALSE){
766 * Kernel filter not installed.
767 * XXX - fall back on userland filtering, as is done
768 * on other platforms?
770 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Driver error: cannot set bpf filter: %s", pcap_win32strerror());
775 * Discard any previously-received packets, as they might have
776 * passed whatever filter was formerly in effect, but might
777 * not pass this filter (BIOCSETF discards packets buffered
778 * in the kernel, so you can lose packets in any case).
785 * We filter at user level, since the kernel driver does't process the packets
788 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
792 strncpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
796 /* Install a user level filter */
797 if (install_bpf_program(p, fp) < 0)
799 snprintf(p->errbuf, sizeof(p->errbuf),
800 "setfilter, unable to install the filter: %s", pcap_strerror(errno));
810 pcap_getnonblock_win32(pcap_t *p, char *errbuf)
813 * XXX - if there were a PacketGetReadTimeout() call, we
814 * would use it, and return 1 if the timeout is -1
817 return (p->nonblock);
821 pcap_setnonblock_win32(pcap_t *p, int nonblock, char *errbuf)
827 * Set the read timeout to -1 for non-blocking mode.
832 * Restore the timeout set when the device was opened.
833 * (Note that this may be -1, in which case we're not
834 * really leaving non-blocking mode.)
836 newtimeout = p->md.timeout;
838 if (!PacketSetReadTimeout(p->adapter, newtimeout)) {
839 snprintf(errbuf, PCAP_ERRBUF_SIZE,
840 "PacketSetReadTimeout: %s", pcap_win32strerror());
843 p->nonblock = (newtimeout == -1);
847 /*platform-dependent routine to add devices other than NDIS interfaces*/
849 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)