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