]> The Tcpdump Group git mirrors - libpcap/blob - pcap-win32.c
5445d696457ac87fdb92a3541ca02b032b35a3ec
[libpcap] / pcap-win32.c
1 /*
2 * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
3 * Copyright (c) 2005 - 2010 CACE Technologies, Davis (California)
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
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.
19 *
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.
31 *
32 */
33
34 #include <pcap-int.h>
35 #include <Packet32.h>
36 #ifdef __MINGW32__
37 #ifdef __MINGW64__
38 #include <ntddndis.h>
39 #else /*__MINGW64__*/
40 #include <ddk/ntddndis.h>
41 #include <ddk/ndis.h>
42 #endif /*__MINGW64__*/
43 #else /*__MINGW32__*/
44 #include <ntddndis.h>
45 #endif /*__MINGW32__*/
46 #ifdef HAVE_DAG_API
47 #include <dagnew.h>
48 #include <dagapi.h>
49 #endif /* HAVE_DAG_API */
50 #ifdef __MINGW32__
51 int* _errno();
52 #define errno (*_errno())
53 #endif /* __MINGW32__ */
54
55 #include "pcap-tc.h"
56
57 static int pcap_setfilter_win32_npf(pcap_t *, struct bpf_program *);
58 static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
59 static int pcap_getnonblock_win32(pcap_t *, char *);
60 static int pcap_setnonblock_win32(pcap_t *, int, char *);
61
62 /*dimension of the buffer in the pcap_t structure*/
63 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
64
65 /*dimension of the buffer in the kernel driver NPF */
66 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
67
68 /* Equivalent to ntohs(), but a lot faster under Windows */
69 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
70
71 /*
72 * Private data for capturing on WinPcap devices.
73 */
74 struct pcap_win {
75 int nonblock;
76
77 int filtering_in_kernel; /* using kernel filter */
78
79 #ifdef HAVE_DAG_API
80 int dag_fcs_bits; /* Number of checksum bits from link layer */
81 #endif
82 };
83
84 CRITICAL_SECTION g_PcapCompileCriticalSection;
85
86 BOOL WINAPI DllMain(
87 HANDLE hinstDLL,
88 DWORD dwReason,
89 LPVOID lpvReserved
90 )
91 {
92 if (dwReason == DLL_PROCESS_ATTACH)
93 {
94 InitializeCriticalSection(&g_PcapCompileCriticalSection);
95 }
96
97 return TRUE;
98 }
99
100 /* Start winsock */
101 int
102 wsockinit()
103 {
104 WORD wVersionRequested;
105 WSADATA wsaData;
106 static int err = -1;
107 static int done = 0;
108
109 if (done)
110 return err;
111
112 wVersionRequested = MAKEWORD( 1, 1);
113 err = WSAStartup( wVersionRequested, &wsaData );
114 atexit ((void(*)(void))WSACleanup);
115 InitializeCriticalSection(&g_PcapCompileCriticalSection);
116 done = 1;
117
118 if ( err != 0 )
119 err = -1;
120 return err;
121 }
122
123 int pcap_wsockinit()
124 {
125 return wsockinit();
126 }
127
128 static int
129 pcap_stats_win32(pcap_t *p, struct pcap_stat *ps)
130 {
131 struct pcap_win *pw = p->priv;
132 struct bpf_stat bstats;
133 char errbuf[PCAP_ERRBUF_SIZE+1];
134
135 /*
136 * Try to get statistics.
137 *
138 * (Please note - "struct pcap_stat" is *not* the same as
139 * WinPcap's "struct bpf_stat". It might currently have the
140 * same layout, but let's not cheat.
141 *
142 * Note also that we don't fill in ps_capt, as we might have
143 * been called by code compiled against an earlier version of
144 * WinPcap that didn't have ps_capt, in which case filling it
145 * in would stomp on whatever comes after the structure passed
146 * to us.
147 */
148 if (!PacketGetStats(p->adapter, &bstats)) {
149 pcap_win32_err_to_str(GetLastError(), errbuf);
150 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
151 "PacketGetStats error: %s", errbuf);
152 return -1;
153 }
154 ps->ps_recv = bstats.bs_recv;
155 ps->ps_drop = bstats.bs_drop;
156 ps->ps_ifdrop = bstats.ps_ifdrop;
157
158 return 0;
159 }
160
161 /*
162 * Win32-only routine for getting statistics.
163 *
164 * This way is definitely safer than passing the pcap_stat * from the userland.
165 * In fact, there could happen than the user allocates a variable which is not
166 * big enough for the new structure, and the library will write in a zone
167 * which is not allocated to this variable.
168 *
169 * In this way, we're pretty sure we are writing on memory allocated to this
170 * variable.
171 *
172 * XXX - but this is the wrong way to handle statistics. Instead, we should
173 * have an API that returns data in a form like the Options section of a
174 * pcapng Interface Statistics Block:
175 *
176 * 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
177 *
178 * which would let us add new statistics straightforwardly and indicate which
179 * statistics we are and are *not* providing, rather than having to provide
180 * possibly-bogus values for statistics we can't provide.
181 */
182 struct pcap_stat *
183 pcap_stats_ex_win32(pcap_t *p, int *pcap_stat_size)
184 {
185 struct bpf_stat bstats;
186 char errbuf[PCAP_ERRBUF_SIZE+1];
187
188 *pcap_stat_size = sizeof (p->stat);
189
190 /*
191 * Try to get statistics.
192 *
193 * (Please note - "struct pcap_stat" is *not* the same as
194 * WinPcap's "struct bpf_stat". It might currently have the
195 * same layout, but let's not cheat.)
196 */
197 if (!PacketGetStatsEx(p->adapter, &bstats)) {
198 pcap_win32_err_to_str(GetLastError(), errbuf);
199 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
200 "PacketGetStatsEx error: %s", errbuf);
201 return NULL;
202 }
203 p->stat.ps_recv = bstats.bs_recv;
204 p->stat.ps_drop = bstats.bs_drop;
205 p->stat.ps_ifdrop = bstats.ps_ifdrop;
206 p->stat.ps_capt = bstats.bs_capt;
207 return (&p->stat);
208 }
209
210 /* Set the dimension of the kernel-level capture buffer */
211 static int
212 pcap_setbuff_win32(pcap_t *p, int dim)
213 {
214 if(PacketSetBuff(p->adapter,dim)==FALSE)
215 {
216 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
217 return -1;
218 }
219 return 0;
220 }
221
222 /* Set the driver working mode */
223 static int
224 pcap_setmode_win32(pcap_t *p, int mode)
225 {
226 if(PacketSetMode(p->adapter,mode)==FALSE)
227 {
228 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
229 return -1;
230 }
231
232 return 0;
233 }
234
235 /*set the minimum amount of data that will release a read call*/
236 static int
237 pcap_setmintocopy_win32(pcap_t *p, int size)
238 {
239 if(PacketSetMinToCopy(p->adapter, size)==FALSE)
240 {
241 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
242 return -1;
243 }
244 return 0;
245 }
246
247 static HANDLE
248 pcap_getevent_win32(pcap_t *p)
249 {
250 return PacketGetReadEvent(p->adapter);
251 }
252
253 static int
254 pcap_oid_get_request_win32(pcap_t *p, pcap_oid_data_t *data)
255 {
256 char errbuf[PCAP_ERRBUF_SIZE+1];
257
258 if (!PacketRequest(p->adapter, FALSE, data)) {
259 pcap_win32_err_to_str(GetLastError(), errbuf);
260 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
261 "Error calling PacketRequest: %s", errbuf);
262 return PCAP_ERROR;
263 }
264 return 0;
265 }
266
267 static int
268 pcap_oid_set_request_win32(pcap_t *p, pcap_oid_data_t *data)
269 {
270 char errbuf[PCAP_ERRBUF_SIZE+1];
271
272 if (!PacketRequest(p->adapter, TRUE, data)) {
273 pcap_win32_err_to_str(GetLastError(), errbuf);
274 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
275 "Error calling PacketRequest: %s", errbuf);
276 return PCAP_ERROR;
277 }
278 return 0;
279 }
280
281 static u_int
282 pcap_sendqueue_transmit_win32(pcap_t *p, pcap_send_queue *queue, int sync)
283 {
284 u_int res;
285 char errbuf[PCAP_ERRBUF_SIZE+1];
286
287 if (p->adapter==NULL) {
288 sprintf(p->errbuf, "Cannot transmit a queue to an offline capture or to a TurboCap port");
289 return 0;
290 }
291
292 res = PacketSendPackets(p->adapter,
293 queue->buffer,
294 queue->len,
295 (BOOLEAN)sync);
296
297 if(res != queue->len){
298 pcap_win32_err_to_str(GetLastError(), errbuf);
299 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
300 "Error opening adapter: %s", errbuf);
301 }
302
303 return res;
304 }
305
306 static int
307 pcap_setuserbuffer_win32(pcap_t *p, int size)
308 {
309 unsigned char *new_buff;
310
311 if (size<=0) {
312 /* Bogus parameter */
313 sprintf(p->errbuf,"Error: invalid size %d",size);
314 return -1;
315 }
316
317 /* Allocate the buffer */
318 new_buff=(unsigned char*)malloc(sizeof(char)*size);
319
320 if (!new_buff) {
321 sprintf(p->errbuf,"Error: not enough memory");
322 return -1;
323 }
324
325 free(p->buffer);
326
327 p->buffer=new_buff;
328 p->bufsize=size;
329
330 /* Associate the buffer with the capture packet */
331 PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize);
332
333 return 0;
334 }
335
336 static int
337 pcap_live_dump_win32(pcap_t *p, char *filename, int maxsize, int maxpacks)
338 {
339 BOOLEAN res;
340
341 /* Set the packet driver in dump mode */
342 res = PacketSetMode(p->adapter, PACKET_MODE_DUMP);
343 if(res == FALSE){
344 sprintf(p->errbuf, "Error setting dump mode");
345 return -1;
346 }
347
348 /* Set the name of the dump file */
349 res = PacketSetDumpName(p->adapter, filename, strlen(filename));
350 if(res == FALSE){
351 sprintf(p->errbuf, "Error setting kernel dump file name");
352 return -1;
353 }
354
355 /* Set the limits of the dump file */
356 res = PacketSetDumpLimits(p->adapter, maxsize, maxpacks);
357
358 return 0;
359 }
360
361 static int
362 pcap_live_dump_ended_win32(pcap_t *p, int sync)
363 {
364 return PacketIsDumpEnded(p->adapter, (BOOLEAN)sync);
365 }
366
367 static PAirpcapHandle
368 pcap_get_airpcap_handle_win32(pcap_t *p)
369 {
370 #ifdef HAVE_AIRPCAP_API
371 return PacketGetAirPcapHandle(p->adapter);
372 #else
373 return NULL;
374 #endif /* HAVE_AIRPCAP_API */
375 }
376
377 static int
378 pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
379 {
380 int cc;
381 int n = 0;
382 register u_char *bp, *ep;
383 u_char *datap;
384 struct pcap_win *pw = p->priv;
385
386 cc = p->cc;
387 if (p->cc == 0) {
388 /*
389 * Has "pcap_breakloop()" been called?
390 */
391 if (p->break_loop) {
392 /*
393 * Yes - clear the flag that indicates that it
394 * has, and return PCAP_ERROR_BREAK to indicate
395 * that we were told to break out of the loop.
396 */
397 p->break_loop = 0;
398 return (PCAP_ERROR_BREAK);
399 }
400
401 /* capture the packets */
402 if(PacketReceivePacket(p->adapter,p->Packet,TRUE)==FALSE){
403 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
404 return (PCAP_ERROR);
405 }
406
407 cc = p->Packet->ulBytesReceived;
408
409 bp = p->Packet->Buffer;
410 }
411 else
412 bp = p->bp;
413
414 /*
415 * Loop through each packet.
416 */
417 #define bhp ((struct bpf_hdr *)bp)
418 ep = bp + cc;
419 while (1) {
420 register int caplen, hdrlen;
421
422 /*
423 * Has "pcap_breakloop()" been called?
424 * If so, return immediately - if we haven't read any
425 * packets, clear the flag and return PCAP_ERROR_BREAK
426 * to indicate that we were told to break out of the loop,
427 * otherwise leave the flag set, so that the *next* call
428 * will break out of the loop without having read any
429 * packets, and return the number of packets we've
430 * processed so far.
431 */
432 if (p->break_loop) {
433 if (n == 0) {
434 p->break_loop = 0;
435 return (PCAP_ERROR_BREAK);
436 } else {
437 p->bp = bp;
438 p->cc = ep - bp;
439 return (n);
440 }
441 }
442 if (bp >= ep)
443 break;
444
445 caplen = bhp->bh_caplen;
446 hdrlen = bhp->bh_hdrlen;
447 datap = bp + hdrlen;
448
449 /*
450 * Short-circuit evaluation: if using BPF filter
451 * in kernel, no need to do it now - we already know
452 * the packet passed the filter.
453 *
454 * XXX - bpf_filter() should always return TRUE if
455 * handed a null pointer for the program, but it might
456 * just try to "run" the filter, so we check here.
457 */
458 if (pw->filtering_in_kernel ||
459 p->fcode.bf_insns == NULL ||
460 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
461 /*
462 * XXX A bpf_hdr matches a pcap_pkthdr.
463 */
464 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
465 bp += Packet_WORDALIGN(caplen + hdrlen);
466 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
467 p->bp = bp;
468 p->cc = ep - bp;
469 return (n);
470 }
471 } else {
472 /*
473 * Skip this packet.
474 */
475 bp += Packet_WORDALIGN(caplen + hdrlen);
476 }
477 }
478 #undef bhp
479 p->cc = 0;
480 return (n);
481 }
482
483 #ifdef HAVE_DAG_API
484 static int
485 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
486 {
487 struct pcap_win *pw = p->priv;
488 u_char *dp = NULL;
489 int packet_len = 0, caplen = 0;
490 struct pcap_pkthdr pcap_header;
491 u_char *endofbuf;
492 int n = 0;
493 dag_record_t *header;
494 unsigned erf_record_len;
495 ULONGLONG ts;
496 int cc;
497 unsigned swt;
498 unsigned dfp = p->adapter->DagFastProcess;
499
500 cc = p->cc;
501 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
502 {
503 /* Get new packets from the network */
504 if(PacketReceivePacket(p->adapter, p->Packet, TRUE)==FALSE){
505 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
506 return (-1);
507 }
508
509 cc = p->Packet->ulBytesReceived;
510 if(cc == 0)
511 /* The timeout has expired but we no packets arrived */
512 return 0;
513 header = (dag_record_t*)p->adapter->DagBuffer;
514 }
515 else
516 header = (dag_record_t*)p->bp;
517
518 endofbuf = (char*)header + cc;
519
520 /*
521 * Cycle through the packets
522 */
523 do
524 {
525 erf_record_len = SWAPS(header->rlen);
526 if((char*)header + erf_record_len > endofbuf)
527 break;
528
529 /* Increase the number of captured packets */
530 p->stat.ps_recv++;
531
532 /* Find the beginning of the packet */
533 dp = ((u_char *)header) + dag_record_size;
534
535 /* Determine actual packet len */
536 switch(header->type)
537 {
538 case TYPE_ATM:
539 packet_len = ATM_SNAPLEN;
540 caplen = ATM_SNAPLEN;
541 dp += 4;
542
543 break;
544
545 case TYPE_ETH:
546 swt = SWAPS(header->wlen);
547 packet_len = swt - (pw->dag_fcs_bits);
548 caplen = erf_record_len - dag_record_size - 2;
549 if (caplen > packet_len)
550 {
551 caplen = packet_len;
552 }
553 dp += 2;
554
555 break;
556
557 case TYPE_HDLC_POS:
558 swt = SWAPS(header->wlen);
559 packet_len = swt - (pw->dag_fcs_bits);
560 caplen = erf_record_len - dag_record_size;
561 if (caplen > packet_len)
562 {
563 caplen = packet_len;
564 }
565
566 break;
567 }
568
569 if(caplen > p->snapshot)
570 caplen = p->snapshot;
571
572 /*
573 * Has "pcap_breakloop()" been called?
574 * If so, return immediately - if we haven't read any
575 * packets, clear the flag and return -2 to indicate
576 * that we were told to break out of the loop, otherwise
577 * leave the flag set, so that the *next* call will break
578 * out of the loop without having read any packets, and
579 * return the number of packets we've processed so far.
580 */
581 if (p->break_loop)
582 {
583 if (n == 0)
584 {
585 p->break_loop = 0;
586 return (-2);
587 }
588 else
589 {
590 p->bp = (char*)header;
591 p->cc = endofbuf - (char*)header;
592 return (n);
593 }
594 }
595
596 if(!dfp)
597 {
598 /* convert between timestamp formats */
599 ts = header->ts;
600 pcap_header.ts.tv_sec = (int)(ts >> 32);
601 ts = (ts & 0xffffffffi64) * 1000000;
602 ts += 0x80000000; /* rounding */
603 pcap_header.ts.tv_usec = (int)(ts >> 32);
604 if (pcap_header.ts.tv_usec >= 1000000) {
605 pcap_header.ts.tv_usec -= 1000000;
606 pcap_header.ts.tv_sec++;
607 }
608 }
609
610 /* No underlaying filtering system. We need to filter on our own */
611 if (p->fcode.bf_insns)
612 {
613 if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
614 {
615 /* Move to next packet */
616 header = (dag_record_t*)((char*)header + erf_record_len);
617 continue;
618 }
619 }
620
621 /* Fill the header for the user suppplied callback function */
622 pcap_header.caplen = caplen;
623 pcap_header.len = packet_len;
624
625 /* Call the callback function */
626 (*callback)(user, &pcap_header, dp);
627
628 /* Move to next packet */
629 header = (dag_record_t*)((char*)header + erf_record_len);
630
631 /* Stop if the number of packets requested by user has been reached*/
632 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
633 {
634 p->bp = (char*)header;
635 p->cc = endofbuf - (char*)header;
636 return (n);
637 }
638 }
639 while((u_char*)header < endofbuf);
640
641 return 1;
642 }
643 #endif /* HAVE_DAG_API */
644
645 /* Send a packet to the network */
646 static int
647 pcap_inject_win32(pcap_t *p, const void *buf, size_t size){
648 LPPACKET PacketToSend;
649
650 PacketToSend=PacketAllocatePacket();
651
652 if (PacketToSend == NULL)
653 {
654 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketAllocatePacket failed");
655 return -1;
656 }
657
658 PacketInitPacket(PacketToSend,(PVOID)buf,size);
659 if(PacketSendPacket(p->adapter,PacketToSend,TRUE) == FALSE){
660 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
661 PacketFreePacket(PacketToSend);
662 return -1;
663 }
664
665 PacketFreePacket(PacketToSend);
666
667 /*
668 * We assume it all got sent if "PacketSendPacket()" succeeded.
669 * "pcap_inject()" is expected to return the number of bytes
670 * sent.
671 */
672 return size;
673 }
674
675 static void
676 pcap_cleanup_win32(pcap_t *p)
677 {
678 if (p->adapter != NULL) {
679 PacketCloseAdapter(p->adapter);
680 p->adapter = NULL;
681 }
682 if (p->Packet) {
683 PacketFreePacket(p->Packet);
684 p->Packet = NULL;
685 }
686 pcap_cleanup_live_common(p);
687 }
688
689 static int
690 pcap_activate_win32(pcap_t *p)
691 {
692 struct pcap_win *pw = p->priv;
693 NetType type;
694 char errbuf[PCAP_ERRBUF_SIZE+1];
695
696 if (p->opt.rfmon) {
697 /*
698 * No monitor mode on Windows. It could be done on
699 * Vista with drivers that support the native 802.11
700 * mechanism and monitor mode.
701 */
702 return (PCAP_ERROR_RFMON_NOTSUP);
703 }
704
705 /* Init WinSock */
706 wsockinit();
707
708 p->adapter = PacketOpenAdapter(p->opt.source);
709
710 if (p->adapter == NULL)
711 {
712 /* Adapter detected but we are not able to open it. Return failure. */
713 pcap_win32_err_to_str(GetLastError(), errbuf);
714 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
715 "Error opening adapter: %s", errbuf);
716 return PCAP_ERROR;
717 }
718
719 /*get network type*/
720 if(PacketGetNetType (p->adapter,&type) == FALSE)
721 {
722 pcap_win32_err_to_str(GetLastError(), errbuf);
723 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
724 "Cannot determine the network type: %s", errbuf);
725 goto bad;
726 }
727
728 /*Set the linktype*/
729 switch (type.LinkType)
730 {
731 case NdisMediumWan:
732 p->linktype = DLT_EN10MB;
733 break;
734
735 case NdisMedium802_3:
736 p->linktype = DLT_EN10MB;
737 /*
738 * This is (presumably) a real Ethernet capture; give it a
739 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
740 * that an application can let you choose it, in case you're
741 * capturing DOCSIS traffic that a Cisco Cable Modem
742 * Termination System is putting out onto an Ethernet (it
743 * doesn't put an Ethernet header onto the wire, it puts raw
744 * DOCSIS frames out on the wire inside the low-level
745 * Ethernet framing).
746 */
747 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
748 /*
749 * If that fails, just leave the list empty.
750 */
751 if (p->dlt_list != NULL) {
752 p->dlt_list[0] = DLT_EN10MB;
753 p->dlt_list[1] = DLT_DOCSIS;
754 p->dlt_count = 2;
755 }
756 break;
757
758 case NdisMediumFddi:
759 p->linktype = DLT_FDDI;
760 break;
761
762 case NdisMedium802_5:
763 p->linktype = DLT_IEEE802;
764 break;
765
766 case NdisMediumArcnetRaw:
767 p->linktype = DLT_ARCNET;
768 break;
769
770 case NdisMediumArcnet878_2:
771 p->linktype = DLT_ARCNET;
772 break;
773
774 case NdisMediumAtm:
775 p->linktype = DLT_ATM_RFC1483;
776 break;
777
778 case NdisMediumCHDLC:
779 p->linktype = DLT_CHDLC;
780 break;
781
782 case NdisMediumPPPSerial:
783 p->linktype = DLT_PPP_SERIAL;
784 break;
785
786 case NdisMediumNull:
787 p->linktype = DLT_NULL;
788 break;
789
790 case NdisMediumBare80211:
791 p->linktype = DLT_IEEE802_11;
792 break;
793
794 case NdisMediumRadio80211:
795 p->linktype = DLT_IEEE802_11_RADIO;
796 break;
797
798 case NdisMediumPpi:
799 p->linktype = DLT_PPI;
800 break;
801
802 default:
803 p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/
804 break;
805 }
806
807 /* Set promiscuous mode */
808 if (p->opt.promisc)
809 {
810
811 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
812 {
813 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
814 goto bad;
815 }
816 }
817 else
818 {
819 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL) == FALSE)
820 {
821 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
822 goto bad;
823 }
824 }
825
826 /* Set the buffer size */
827 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
828
829 /* allocate Packet structure used during the capture */
830 if((p->Packet = PacketAllocatePacket())==NULL)
831 {
832 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to allocate the PACKET structure");
833 goto bad;
834 }
835
836 if(!(p->adapter->Flags & INFO_FLAG_DAG_CARD))
837 {
838 /*
839 * Traditional Adapter
840 */
841 /*
842 * If the buffer size wasn't explicitly set, default to
843 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
844 */
845 if (p->opt.buffer_size == 0)
846 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
847
848 if(PacketSetBuff(p->adapter,p->opt.buffer_size)==FALSE)
849 {
850 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
851 goto bad;
852 }
853
854 p->buffer = malloc(p->bufsize);
855 if (p->buffer == NULL)
856 {
857 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
858 goto bad;
859 }
860
861 PacketInitPacket(p->Packet,(BYTE*)p->buffer,p->bufsize);
862
863 if (p->opt.immediate)
864 {
865 /* tell the driver to copy the buffer as soon as data arrives */
866 if(PacketSetMinToCopy(p->adapter,0)==FALSE)
867 {
868 pcap_win32_err_to_str(GetLastError(), errbuf);
869 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
870 "Error calling PacketSetMinToCopy: %s",
871 errbuf);
872 goto bad;
873 }
874 }
875 else
876 {
877 /* tell the driver to copy the buffer only if it contains at least 16K */
878 if(PacketSetMinToCopy(p->adapter,16000)==FALSE)
879 {
880 pcap_win32_err_to_str(GetLastError(), errbuf);
881 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
882 "Error calling PacketSetMinToCopy: %s",
883 errbuf);
884 goto bad;
885 }
886 }
887 }
888 else
889 #ifdef HAVE_DAG_API
890 {
891 /*
892 * Dag Card
893 */
894 LONG status;
895 HKEY dagkey;
896 DWORD lptype;
897 DWORD lpcbdata;
898 int postype = 0;
899 char keyname[512];
900
901 snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
902 "SYSTEM\\CurrentControlSet\\Services\\DAG",
903 strstr(_strlwr(p->opt.source), "dag"));
904 do
905 {
906 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
907 if(status != ERROR_SUCCESS)
908 break;
909
910 status = RegQueryValueEx(dagkey,
911 "PosType",
912 NULL,
913 &lptype,
914 (char*)&postype,
915 &lpcbdata);
916
917 if(status != ERROR_SUCCESS)
918 {
919 postype = 0;
920 }
921
922 RegCloseKey(dagkey);
923 }
924 while(FALSE);
925
926
927 p->snapshot = PacketSetSnapLen(p->adapter, snaplen);
928
929 /* Set the length of the FCS associated to any packet. This value
930 * will be subtracted to the packet length */
931 pw->dag_fcs_bits = p->adapter->DagFcsLen;
932 }
933 #else
934 goto bad;
935 #endif /* HAVE_DAG_API */
936
937 PacketSetReadTimeout(p->adapter, p->opt.timeout);
938
939 #ifdef HAVE_DAG_API
940 if(p->adapter->Flags & INFO_FLAG_DAG_CARD)
941 {
942 /* install dag specific handlers for read and setfilter */
943 p->read_op = pcap_read_win32_dag;
944 p->setfilter_op = pcap_setfilter_win32_dag;
945 }
946 else
947 {
948 #endif /* HAVE_DAG_API */
949 /* install traditional npf handlers for read and setfilter */
950 p->read_op = pcap_read_win32_npf;
951 p->setfilter_op = pcap_setfilter_win32_npf;
952 #ifdef HAVE_DAG_API
953 }
954 #endif /* HAVE_DAG_API */
955 p->setdirection_op = NULL; /* Not implemented. */
956 /* XXX - can this be implemented on some versions of Windows? */
957 p->inject_op = pcap_inject_win32;
958 p->set_datalink_op = NULL; /* can't change data link type */
959 p->getnonblock_op = pcap_getnonblock_win32;
960 p->setnonblock_op = pcap_setnonblock_win32;
961 p->stats_op = pcap_stats_win32;
962 p->stats_ex_op = pcap_stats_ex_win32;
963 p->setbuff_op = pcap_setbuff_win32;
964 p->setmode_op = pcap_setmode_win32;
965 p->setmintocopy_op = pcap_setmintocopy_win32;
966 p->getevent_op = pcap_getevent_win32;
967 p->oid_get_request_op = pcap_oid_get_request_win32;
968 p->oid_set_request_op = pcap_oid_set_request_win32;
969 p->sendqueue_transmit_op = pcap_sendqueue_transmit_win32;
970 p->live_dump_op = pcap_live_dump_win32;
971 p->live_dump_ended_op = pcap_live_dump_ended_win32;
972 p->get_airpcap_handle_op = pcap_get_airpcap_handle_win32;
973 p->cleanup_op = pcap_cleanup_win32;
974
975 return (0);
976 bad:
977 pcap_cleanup_win32(p);
978 return (PCAP_ERROR);
979 }
980
981 pcap_t *
982 pcap_create_interface(const char *device, char *ebuf)
983 {
984 pcap_t *p;
985
986 if (strlen(device) == 1)
987 {
988 /*
989 * It's probably a unicode string
990 * Convert to ascii and pass it to pcap_create_common
991 *
992 * This wonderful hack is needed because pcap_lookupdev still returns
993 * unicode strings, and it's used by windump when no device is specified
994 * in the command line
995 */
996 size_t length;
997 char* deviceAscii;
998
999 length = wcslen((wchar_t*)device);
1000
1001 deviceAscii = (char*)malloc(length + 1);
1002
1003 if (deviceAscii == NULL)
1004 {
1005 snprintf(ebuf, PCAP_ERRBUF_SIZE, "Malloc failed");
1006 return NULL;
1007 }
1008
1009 snprintf(deviceAscii, length + 1, "%ws", (wchar_t*)device);
1010 p = pcap_create_common(deviceAscii, ebuf, sizeof (struct pcap_win));
1011 free(deviceAscii);
1012 }
1013 else
1014 {
1015 p = pcap_create_common(device, ebuf, sizeof (struct pcap_win));
1016 }
1017
1018 if (p == NULL)
1019 return (NULL);
1020
1021 p->activate_op = pcap_activate_win32;
1022 return (p);
1023 }
1024
1025 static int
1026 pcap_setfilter_win32_npf(pcap_t *p, struct bpf_program *fp)
1027 {
1028 struct pcap_win *pw = p->priv;
1029
1030 if(PacketSetBpf(p->adapter,fp)==FALSE){
1031 /*
1032 * Kernel filter not installed.
1033 *
1034 * XXX - we don't know whether this failed because:
1035 *
1036 * the kernel rejected the filter program as invalid,
1037 * in which case we should fall back on userland
1038 * filtering;
1039 *
1040 * the kernel rejected the filter program as too big,
1041 * in which case we should again fall back on
1042 * userland filtering;
1043 *
1044 * there was some other problem, in which case we
1045 * should probably report an error.
1046 *
1047 * For NPF devices, the Win32 status will be
1048 * STATUS_INVALID_DEVICE_REQUEST for invalid
1049 * filters, but I don't know what it'd be for
1050 * other problems, and for some other devices
1051 * it might not be set at all.
1052 *
1053 * So we just fall back on userland filtering in
1054 * all cases.
1055 */
1056
1057 /*
1058 * install_bpf_program() validates the program.
1059 *
1060 * XXX - what if we already have a filter in the kernel?
1061 */
1062 if (install_bpf_program(p, fp) < 0)
1063 return (-1);
1064 pw->filtering_in_kernel = 0; /* filtering in userland */
1065 return (0);
1066 }
1067
1068 /*
1069 * It worked.
1070 */
1071 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1072
1073 /*
1074 * Discard any previously-received packets, as they might have
1075 * passed whatever filter was formerly in effect, but might
1076 * not pass this filter (BIOCSETF discards packets buffered
1077 * in the kernel, so you can lose packets in any case).
1078 */
1079 p->cc = 0;
1080 return (0);
1081 }
1082
1083 /*
1084 * We filter at user level, since the kernel driver does't process the packets
1085 */
1086 static int
1087 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1088
1089 if(!fp)
1090 {
1091 strncpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1092 return -1;
1093 }
1094
1095 /* Install a user level filter */
1096 if (install_bpf_program(p, fp) < 0)
1097 {
1098 snprintf(p->errbuf, sizeof(p->errbuf),
1099 "setfilter, unable to install the filter: %s", pcap_strerror(errno));
1100 return -1;
1101 }
1102
1103 return (0);
1104 }
1105
1106 static int
1107 pcap_getnonblock_win32(pcap_t *p, char *errbuf)
1108 {
1109 struct pcap_win *pw = p->priv;
1110
1111 /*
1112 * XXX - if there were a PacketGetReadTimeout() call, we
1113 * would use it, and return 1 if the timeout is -1
1114 * and 0 otherwise.
1115 */
1116 return (pw->nonblock);
1117 }
1118
1119 static int
1120 pcap_setnonblock_win32(pcap_t *p, int nonblock, char *errbuf)
1121 {
1122 struct pcap_win *pw = p->priv;
1123 int newtimeout;
1124 char errbuf[PCAP_ERRBUF_SIZE+1];
1125
1126 if (nonblock) {
1127 /*
1128 * Set the read timeout to -1 for non-blocking mode.
1129 */
1130 newtimeout = -1;
1131 } else {
1132 /*
1133 * Restore the timeout set when the device was opened.
1134 * (Note that this may be -1, in which case we're not
1135 * really leaving non-blocking mode.)
1136 */
1137 newtimeout = p->opt.timeout;
1138 }
1139 if (!PacketSetReadTimeout(p->adapter, newtimeout)) {
1140 pcap_win32_err_to_str(GetLastError(), errbuf);
1141 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1142 "PacketSetReadTimeout: %s", errbuf);
1143 return (-1);
1144 }
1145 pw->nonblock = (newtimeout == -1);
1146 return (0);
1147 }