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