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