Updates to Tomato RAF including NGINX && PHP
[tomato.git] / release / src / router / libpcap / pcap-win32.c
blob7fe1cb8a111e1a67b7fd9e7d491f495faf9bf300
1 /*
2 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2008 CACE Technologies, Davis (California)
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
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
18 * permission.
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 #ifndef lint
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)";
37 #endif
39 #include <pcap-int.h>
40 #include <Packet32.h>
41 #ifdef __MINGW32__
42 #ifdef __MINGW64__
43 #include <ntddndis.h>
44 #else /*__MINGW64__*/
45 #include <ddk/ntddndis.h>
46 #include <ddk/ndis.h>
47 #endif /*__MINGW64__*/
48 #else /*__MINGW32__*/
49 #include <ntddndis.h>
50 #endif /*__MINGW32__*/
51 #ifdef HAVE_DAG_API
52 #include <dagnew.h>
53 #include <dagapi.h>
54 #endif /* HAVE_DAG_API */
55 #ifdef __MINGW32__
56 int* _errno();
57 #define errno (*_errno())
58 #endif /* __MINGW32__ */
60 #ifdef HAVE_REMOTE
61 #include <pcap-remote.h>
62 #endif /* HAVE_REMOTE */
64 static int pcap_setfilter_win32_npf(pcap_t *, struct bpf_program *);
65 static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
66 static int pcap_getnonblock_win32(pcap_t *, char *);
67 static int pcap_setnonblock_win32(pcap_t *, int, char *);
69 /*dimension of the buffer in the pcap_t structure*/
70 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
72 /*dimension of the buffer in the kernel driver NPF */
73 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
75 /* Equivalent to ntohs(), but a lot faster under Windows */
76 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
79 * Header that the WinPcap driver associates to the packets.
80 * Once was in bpf.h
82 struct bpf_hdr {
83 struct timeval bh_tstamp; /* time stamp */
84 bpf_u_int32 bh_caplen; /* length of captured portion */
85 bpf_u_int32 bh_datalen; /* original length of packet */
86 u_short bh_hdrlen; /* length of bpf header (this struct
87 plus alignment padding) */
90 CRITICAL_SECTION g_PcapCompileCriticalSection;
92 BOOL WINAPI DllMain(
93 HANDLE hinstDLL,
94 DWORD dwReason,
95 LPVOID lpvReserved
98 if (dwReason == DLL_PROCESS_ATTACH)
100 InitializeCriticalSection(&g_PcapCompileCriticalSection);
103 return TRUE;
106 /* Start winsock */
107 int
108 wsockinit()
110 WORD wVersionRequested;
111 WSADATA wsaData;
112 int err;
113 wVersionRequested = MAKEWORD( 1, 1);
114 err = WSAStartup( wVersionRequested, &wsaData );
115 if ( err != 0 )
117 return -1;
119 return 0;
123 static int
124 pcap_stats_win32(pcap_t *p, struct pcap_stat *ps)
127 if(PacketGetStats(p->adapter, (struct bpf_stat*)ps) != TRUE){
128 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "PacketGetStats error: %s", pcap_win32strerror());
129 return -1;
132 return 0;
135 /* Set the dimension of the kernel-level capture buffer */
136 static int
137 pcap_setbuff_win32(pcap_t *p, int dim)
139 #ifdef HAVE_REMOTE
140 if (p->rmt_clientside)
142 /* Currently, this is a bug: the capture buffer cannot be set with remote capture */
143 return 0;
145 #endif /* HAVE_REMOTE */
147 if(PacketSetBuff(p->adapter,dim)==FALSE)
149 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
150 return -1;
152 return 0;
155 /* Set the driver working mode */
156 static int
157 pcap_setmode_win32(pcap_t *p, int mode)
159 if(PacketSetMode(p->adapter,mode)==FALSE)
161 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
162 return -1;
165 return 0;
168 /*set the minimum amount of data that will release a read call*/
169 static int
170 pcap_setmintocopy_win32(pcap_t *p, int size)
172 if(PacketSetMinToCopy(p->adapter, size)==FALSE)
174 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
175 return -1;
177 return 0;
180 static int
181 pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
183 int cc;
184 int n = 0;
185 register u_char *bp, *ep;
187 #ifdef HAVE_REMOTE
188 static int samp_npkt; // parameter needed for sampling, with '1 out of N' method has been requested
189 static struct timeval samp_time; // parameter needed for sampling, with '1 every N ms' method has been requested
190 #endif /* HAVE_REMOTE */
192 cc = p->cc;
193 if (p->cc == 0) {
195 * Has "pcap_breakloop()" been called?
197 if (p->break_loop) {
199 * Yes - clear the flag that indicates that it
200 * has, and return -2 to indicate that we were
201 * told to break out of the loop.
203 p->break_loop = 0;
204 return (-2);
207 /* capture the packets */
208 if(PacketReceivePacket(p->adapter,p->Packet,TRUE)==FALSE){
209 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
210 return (-1);
213 cc = p->Packet->ulBytesReceived;
215 bp = p->Packet->Buffer;
217 else
218 bp = p->bp;
221 * Loop through each packet.
223 #define bhp ((struct bpf_hdr *)bp)
224 ep = bp + cc;
225 while (1) {
226 register int caplen, hdrlen;
229 * Has "pcap_breakloop()" been called?
230 * If so, return immediately - if we haven't read any
231 * packets, clear the flag and return -2 to indicate
232 * that we were told to break out of the loop, otherwise
233 * leave the flag set, so that the *next* call will break
234 * out of the loop without having read any packets, and
235 * return the number of packets we've processed so far.
237 if (p->break_loop) {
238 if (n == 0) {
239 p->break_loop = 0;
240 return (-2);
241 } else {
242 p->bp = bp;
243 p->cc = ep - bp;
244 return (n);
247 if (bp >= ep)
248 break;
250 caplen = bhp->bh_caplen;
251 hdrlen = bhp->bh_hdrlen;
253 #ifdef HAVE_REMOTE
254 if (p->rmt_samp.method == PCAP_SAMP_1_EVERY_N)
256 samp_npkt= (samp_npkt + 1) % p->rmt_samp.value;
258 // Discard all packets that are not '1 out of N'
259 if (samp_npkt != 0)
261 bp += BPF_WORDALIGN(caplen + hdrlen);
262 continue;
266 if (p->rmt_samp.method == PCAP_SAMP_FIRST_AFTER_N_MS)
268 struct pcap_pkthdr *pkt_header= (struct pcap_pkthdr*) bp;
270 // Check if the timestamp of the arrived packet is smaller than our target time
271 if ( (pkt_header->ts.tv_sec < samp_time.tv_sec) ||
272 ( (pkt_header->ts.tv_sec == samp_time.tv_sec) && (pkt_header->ts.tv_usec < samp_time.tv_usec) ) )
274 bp += BPF_WORDALIGN(caplen + hdrlen);
275 continue;
278 // The arrived packet is suitable for being sent to the remote host
279 // So, let's update the target time
280 samp_time.tv_usec= pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
281 if (samp_time.tv_usec > 1000000)
283 samp_time.tv_sec= pkt_header->ts.tv_sec + samp_time.tv_usec / 1000000;
284 samp_time.tv_usec= samp_time.tv_usec % 1000000;
287 #endif /* HAVE_REMOTE */
290 * XXX A bpf_hdr matches a pcap_pkthdr.
292 (*callback)(user, (struct pcap_pkthdr*)bp, bp + hdrlen);
293 bp += Packet_WORDALIGN(caplen + hdrlen);
294 if (++n >= cnt && cnt > 0) {
295 p->bp = bp;
296 p->cc = ep - bp;
297 return (n);
300 #undef bhp
301 p->cc = 0;
302 return (n);
305 #ifdef HAVE_DAG_API
306 static int
307 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
309 u_char *dp = NULL;
310 int packet_len = 0, caplen = 0;
311 struct pcap_pkthdr pcap_header;
312 u_char *endofbuf;
313 int n = 0;
314 dag_record_t *header;
315 unsigned erf_record_len;
316 ULONGLONG ts;
317 int cc;
318 unsigned swt;
319 unsigned dfp = p->adapter->DagFastProcess;
321 cc = p->cc;
322 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
324 /* Get new packets from the network */
325 if(PacketReceivePacket(p->adapter, p->Packet, TRUE)==FALSE){
326 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
327 return (-1);
330 cc = p->Packet->ulBytesReceived;
331 if(cc == 0)
332 /* The timeout has expired but we no packets arrived */
333 return 0;
334 header = (dag_record_t*)p->adapter->DagBuffer;
336 else
337 header = (dag_record_t*)p->bp;
339 endofbuf = (char*)header + cc;
342 * Cycle through the packets
346 erf_record_len = SWAPS(header->rlen);
347 if((char*)header + erf_record_len > endofbuf)
348 break;
350 /* Increase the number of captured packets */
351 p->md.stat.ps_recv++;
353 /* Find the beginning of the packet */
354 dp = ((u_char *)header) + dag_record_size;
356 /* Determine actual packet len */
357 switch(header->type)
359 case TYPE_ATM:
360 packet_len = ATM_SNAPLEN;
361 caplen = ATM_SNAPLEN;
362 dp += 4;
364 break;
366 case TYPE_ETH:
367 swt = SWAPS(header->wlen);
368 packet_len = swt - (p->md.dag_fcs_bits);
369 caplen = erf_record_len - dag_record_size - 2;
370 if (caplen > packet_len)
372 caplen = packet_len;
374 dp += 2;
376 break;
378 case TYPE_HDLC_POS:
379 swt = SWAPS(header->wlen);
380 packet_len = swt - (p->md.dag_fcs_bits);
381 caplen = erf_record_len - dag_record_size;
382 if (caplen > packet_len)
384 caplen = packet_len;
387 break;
390 if(caplen > p->snapshot)
391 caplen = p->snapshot;
394 * Has "pcap_breakloop()" been called?
395 * If so, return immediately - if we haven't read any
396 * packets, clear the flag and return -2 to indicate
397 * that we were told to break out of the loop, otherwise
398 * leave the flag set, so that the *next* call will break
399 * out of the loop without having read any packets, and
400 * return the number of packets we've processed so far.
402 if (p->break_loop)
404 if (n == 0)
406 p->break_loop = 0;
407 return (-2);
409 else
411 p->bp = (char*)header;
412 p->cc = endofbuf - (char*)header;
413 return (n);
417 if(!dfp)
419 /* convert between timestamp formats */
420 ts = header->ts;
421 pcap_header.ts.tv_sec = (int)(ts >> 32);
422 ts = (ts & 0xffffffffi64) * 1000000;
423 ts += 0x80000000; /* rounding */
424 pcap_header.ts.tv_usec = (int)(ts >> 32);
425 if (pcap_header.ts.tv_usec >= 1000000) {
426 pcap_header.ts.tv_usec -= 1000000;
427 pcap_header.ts.tv_sec++;
431 /* No underlaying filtering system. We need to filter on our own */
432 if (p->fcode.bf_insns)
434 if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
436 /* Move to next packet */
437 header = (dag_record_t*)((char*)header + erf_record_len);
438 continue;
442 /* Fill the header for the user suppplied callback function */
443 pcap_header.caplen = caplen;
444 pcap_header.len = packet_len;
446 /* Call the callback function */
447 (*callback)(user, &pcap_header, dp);
449 /* Move to next packet */
450 header = (dag_record_t*)((char*)header + erf_record_len);
452 /* Stop if the number of packets requested by user has been reached*/
453 if (++n >= cnt && cnt > 0)
455 p->bp = (char*)header;
456 p->cc = endofbuf - (char*)header;
457 return (n);
460 while((u_char*)header < endofbuf);
462 return 1;
464 #endif /* HAVE_DAG_API */
466 /* Send a packet to the network */
467 static int
468 pcap_inject_win32(pcap_t *p, const void *buf, size_t size){
469 LPPACKET PacketToSend;
471 PacketToSend=PacketAllocatePacket();
473 if (PacketToSend == NULL)
475 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketAllocatePacket failed");
476 return -1;
479 PacketInitPacket(PacketToSend,(PVOID)buf,size);
480 if(PacketSendPacket(p->adapter,PacketToSend,TRUE) == FALSE){
481 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
482 PacketFreePacket(PacketToSend);
483 return -1;
486 PacketFreePacket(PacketToSend);
489 * We assume it all got sent if "PacketSendPacket()" succeeded.
490 * "pcap_inject()" is expected to return the number of bytes
491 * sent.
493 return size;
496 static void
497 pcap_cleanup_win32(pcap_t *p)
499 if (p->adapter != NULL) {
500 PacketCloseAdapter(p->adapter);
501 p->adapter = NULL;
503 if (p->Packet) {
504 PacketFreePacket(p->Packet);
505 p->Packet = NULL;
507 pcap_cleanup_live_common(p);
510 static int
511 pcap_activate_win32(pcap_t *p)
513 NetType type;
515 #ifdef HAVE_REMOTE
516 char host[PCAP_BUF_SIZE + 1];
517 char port[PCAP_BUF_SIZE + 1];
518 char name[PCAP_BUF_SIZE + 1];
519 int srctype;
520 int opensource_remote_result;
523 Retrofit; we have to make older applications compatible with the remote capture
524 So, we're calling the pcap_open_remote() from here, that is a very dirty thing.
525 Obviously, we cannot exploit all the new features; for instance, we cannot
526 send authentication, we cannot use a UDP data connection, and so on.
528 if (pcap_parsesrcstr(p->opt.source, &srctype, host, port, name, p->errbuf) )
529 return PCAP_ERROR;
531 if (srctype == PCAP_SRC_IFREMOTE)
533 opensource_remote_result = pcap_opensource_remote(p, NULL);
535 if (opensource_remote_result != 0)
536 return opensource_remote_result;
538 p->rmt_flags= (p->opt.promisc) ? PCAP_OPENFLAG_PROMISCUOUS : 0;
540 return 0;
543 if (srctype == PCAP_SRC_IFLOCAL)
546 * If it starts with rpcap://, cut down the string
548 if (strncmp(p->opt.source, PCAP_SRC_IF_STRING, strlen(PCAP_SRC_IF_STRING)) == 0)
550 size_t len = strlen(p->opt.source) - strlen(PCAP_SRC_IF_STRING) + 1;
551 char *new_string;
553 * allocate a new string and free the old one
555 if (len > 0)
557 new_string = (char*)malloc(len);
558 if (new_string != NULL)
560 char *tmp;
561 strcpy(new_string, p->opt.source + strlen(PCAP_SRC_IF_STRING));
562 tmp = p->opt.source;
563 p->opt.source = new_string;
564 free(tmp);
570 #endif /* HAVE_REMOTE */
572 if (p->opt.rfmon) {
574 * No monitor mode on Windows. It could be done on
575 * Vista with drivers that support the native 802.11
576 * mechanism and monitor mode.
578 return (PCAP_ERROR_RFMON_NOTSUP);
581 /* Init WinSock */
582 wsockinit();
584 p->adapter = PacketOpenAdapter(p->opt.source);
586 if (p->adapter == NULL)
588 /* Adapter detected but we are not able to open it. Return failure. */
589 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Error opening adapter: %s", pcap_win32strerror());
590 return PCAP_ERROR;
593 /*get network type*/
594 if(PacketGetNetType (p->adapter,&type) == FALSE)
596 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Cannot determine the network type: %s", pcap_win32strerror());
597 goto bad;
600 /*Set the linktype*/
601 switch (type.LinkType)
603 case NdisMediumWan:
604 p->linktype = DLT_EN10MB;
605 break;
607 case NdisMedium802_3:
608 p->linktype = DLT_EN10MB;
610 * This is (presumably) a real Ethernet capture; give it a
611 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
612 * that an application can let you choose it, in case you're
613 * capturing DOCSIS traffic that a Cisco Cable Modem
614 * Termination System is putting out onto an Ethernet (it
615 * doesn't put an Ethernet header onto the wire, it puts raw
616 * DOCSIS frames out on the wire inside the low-level
617 * Ethernet framing).
619 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
621 * If that fails, just leave the list empty.
623 if (p->dlt_list != NULL) {
624 p->dlt_list[0] = DLT_EN10MB;
625 p->dlt_list[1] = DLT_DOCSIS;
626 p->dlt_count = 2;
628 break;
630 case NdisMediumFddi:
631 p->linktype = DLT_FDDI;
632 break;
634 case NdisMedium802_5:
635 p->linktype = DLT_IEEE802;
636 break;
638 case NdisMediumArcnetRaw:
639 p->linktype = DLT_ARCNET;
640 break;
642 case NdisMediumArcnet878_2:
643 p->linktype = DLT_ARCNET;
644 break;
646 case NdisMediumAtm:
647 p->linktype = DLT_ATM_RFC1483;
648 break;
650 case NdisMediumCHDLC:
651 p->linktype = DLT_CHDLC;
652 break;
654 case NdisMediumPPPSerial:
655 p->linktype = DLT_PPP_SERIAL;
656 break;
658 case NdisMediumNull:
659 p->linktype = DLT_NULL;
660 break;
662 case NdisMediumBare80211:
663 p->linktype = DLT_IEEE802_11;
664 break;
666 case NdisMediumRadio80211:
667 p->linktype = DLT_IEEE802_11_RADIO;
668 break;
670 case NdisMediumPpi:
671 p->linktype = DLT_PPI;
672 break;
674 default:
675 p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/
676 break;
679 /* Set promiscuous mode */
680 if (p->opt.promisc)
683 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
685 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
686 goto bad;
689 else
691 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL) == FALSE)
693 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
694 goto bad;
698 /* Set the buffer size */
699 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
701 /* allocate Packet structure used during the capture */
702 if((p->Packet = PacketAllocatePacket())==NULL)
704 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to allocate the PACKET structure");
705 goto bad;
708 if(!(p->adapter->Flags & INFO_FLAG_DAG_CARD))
711 * Traditional Adapter
714 * If the buffer size wasn't explicitly set, default to
715 * WIN32_DEFAULT_USER_BUFFER_SIZE.
717 if (p->opt.buffer_size == 0)
718 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
720 if(PacketSetBuff(p->adapter,p->opt.buffer_size)==FALSE)
722 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
723 goto bad;
726 p->buffer = (u_char *)malloc(p->bufsize);
727 if (p->buffer == NULL)
729 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
730 goto bad;
733 PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize);
735 /* tell the driver to copy the buffer only if it contains at least 16K */
736 if(PacketSetMinToCopy(p->adapter,16000)==FALSE)
738 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,"Error calling PacketSetMinToCopy: %s", pcap_win32strerror());
739 goto bad;
742 else
743 #ifdef HAVE_DAG_API
746 * Dag Card
748 LONG status;
749 HKEY dagkey;
750 DWORD lptype;
751 DWORD lpcbdata;
752 int postype = 0;
753 char keyname[512];
755 snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
756 "SYSTEM\\CurrentControlSet\\Services\\DAG",
757 strstr(_strlwr(p->opt.source), "dag"));
760 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
761 if(status != ERROR_SUCCESS)
762 break;
764 status = RegQueryValueEx(dagkey,
765 "PosType",
766 NULL,
767 &lptype,
768 (char*)&postype,
769 &lpcbdata);
771 if(status != ERROR_SUCCESS)
773 postype = 0;
776 RegCloseKey(dagkey);
778 while(FALSE);
781 p->snapshot = PacketSetSnapLen(p->adapter, snaplen);
783 /* Set the length of the FCS associated to any packet. This value
784 * will be subtracted to the packet length */
785 p->md.dag_fcs_bits = p->adapter->DagFcsLen;
787 #else
788 goto bad;
789 #endif /* HAVE_DAG_API */
791 PacketSetReadTimeout(p->adapter, p->md.timeout);
793 #ifdef HAVE_DAG_API
794 if(p->adapter->Flags & INFO_FLAG_DAG_CARD)
796 /* install dag specific handlers for read and setfilter */
797 p->read_op = pcap_read_win32_dag;
798 p->setfilter_op = pcap_setfilter_win32_dag;
800 else
802 #endif /* HAVE_DAG_API */
803 /* install traditional npf handlers for read and setfilter */
804 p->read_op = pcap_read_win32_npf;
805 p->setfilter_op = pcap_setfilter_win32_npf;
806 #ifdef HAVE_DAG_API
808 #endif /* HAVE_DAG_API */
809 p->setdirection_op = NULL; /* Not implemented. */
810 /* XXX - can this be implemented on some versions of Windows? */
811 p->inject_op = pcap_inject_win32;
812 p->set_datalink_op = NULL; /* can't change data link type */
813 p->getnonblock_op = pcap_getnonblock_win32;
814 p->setnonblock_op = pcap_setnonblock_win32;
815 p->stats_op = pcap_stats_win32;
816 p->setbuff_op = pcap_setbuff_win32;
817 p->setmode_op = pcap_setmode_win32;
818 p->setmintocopy_op = pcap_setmintocopy_win32;
819 p->cleanup_op = pcap_cleanup_win32;
821 return (0);
822 bad:
823 pcap_cleanup_win32(p);
824 return (PCAP_ERROR);
827 pcap_t *
828 pcap_create(const char *device, char *ebuf)
830 pcap_t *p;
832 if (strlen(device) == 1)
835 * It's probably a unicode string
836 * Convert to ascii and pass it to pcap_create_common
838 * This wonderful hack is needed because pcap_lookupdev still returns
839 * unicode strings, and it's used by windump when no device is specified
840 * in the command line
842 size_t length;
843 char* deviceAscii;
845 length = wcslen((wchar_t*)device);
847 deviceAscii = (char*)malloc(length + 1);
849 if (deviceAscii == NULL)
851 snprintf(ebuf, PCAP_ERRBUF_SIZE, "Malloc failed");
852 return NULL;
855 snprintf(deviceAscii, length + 1, "%ws", (wchar_t*)device);
856 p = pcap_create_common(deviceAscii, ebuf);
857 free(deviceAscii);
859 else
861 p = pcap_create_common(device, ebuf);
864 if (p == NULL)
865 return (NULL);
867 p->activate_op = pcap_activate_win32;
868 return (p);
871 static int
872 pcap_setfilter_win32_npf(pcap_t *p, struct bpf_program *fp)
874 if(PacketSetBpf(p->adapter,fp)==FALSE){
876 * Kernel filter not installed.
877 * XXX - fall back on userland filtering, as is done
878 * on other platforms?
880 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "Driver error: cannot set bpf filter: %s", pcap_win32strerror());
881 return (-1);
885 * Discard any previously-received packets, as they might have
886 * passed whatever filter was formerly in effect, but might
887 * not pass this filter (BIOCSETF discards packets buffered
888 * in the kernel, so you can lose packets in any case).
890 p->cc = 0;
891 return (0);
895 * We filter at user level, since the kernel driver does't process the packets
897 static int
898 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
900 if(!fp)
902 strncpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
903 return -1;
906 /* Install a user level filter */
907 if (install_bpf_program(p, fp) < 0)
909 snprintf(p->errbuf, sizeof(p->errbuf),
910 "setfilter, unable to install the filter: %s", pcap_strerror(errno));
911 return -1;
914 p->md.use_bpf = 0;
916 return (0);
919 static int
920 pcap_getnonblock_win32(pcap_t *p, char *errbuf)
923 * XXX - if there were a PacketGetReadTimeout() call, we
924 * would use it, and return 1 if the timeout is -1
925 * and 0 otherwise.
927 return (p->nonblock);
930 static int
931 pcap_setnonblock_win32(pcap_t *p, int nonblock, char *errbuf)
933 int newtimeout;
935 if (nonblock) {
937 * Set the read timeout to -1 for non-blocking mode.
939 newtimeout = -1;
940 } else {
942 * Restore the timeout set when the device was opened.
943 * (Note that this may be -1, in which case we're not
944 * really leaving non-blocking mode.)
946 newtimeout = p->md.timeout;
948 if (!PacketSetReadTimeout(p->adapter, newtimeout)) {
949 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
950 "PacketSetReadTimeout: %s", pcap_win32strerror());
951 return (-1);
953 p->nonblock = (newtimeout == -1);
954 return (0);
957 /*platform-dependent routine to add devices other than NDIS interfaces*/
959 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
961 return (0);