]> The Tcpdump Group git mirrors - libpcap/blob - pcap-win32.c
Don't have pcap_create_common() set opt.device.
[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 *lenp)
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 "*lenp" 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) + *lenp);
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)(*lenp); /* 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 * Get the length actually supplied.
291 */
292 *lenp = oid_data_arg->Length;
293
294 /*
295 * Copy back the data we fetched.
296 */
297 memcpy(data, oid_data_arg->Data, *lenp);
298 free(oid_data_arg);
299 return (0);
300 }
301
302 static int
303 pcap_oid_set_request_win32(pcap_t *p, bpf_u_int32 oid, const void *data,
304 size_t *lenp)
305 {
306 PACKET_OID_DATA *oid_data_arg;
307 char errbuf[PCAP_ERRBUF_SIZE+1];
308
309 /*
310 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
311 * It should be big enough to hold "*lenp" bytes of data; it
312 * will actually be slightly larger, as PACKET_OID_DATA has a
313 * 1-byte data array at the end, standing in for the variable-length
314 * data that's actually there.
315 */
316 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
317 if (oid_data_arg == NULL) {
318 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
319 "Couldn't allocate argument buffer for PacketRequest");
320 return (PCAP_ERROR);
321 }
322
323 oid_data_arg->Oid = oid;
324 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
325 memcpy(oid_data_arg->Data, data, *lenp);
326 if (!PacketRequest(p->adapter, TRUE, oid_data_arg)) {
327 pcap_win32_err_to_str(GetLastError(), errbuf);
328 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
329 "Error calling PacketRequest: %s", errbuf);
330 free(oid_data_arg);
331 return (PCAP_ERROR);
332 }
333
334 /*
335 * Get the length actually copied.
336 */
337 *lenp = oid_data_arg->Length;
338
339 /*
340 * No need to copy the data - we're doing a set.
341 */
342 free(oid_data_arg);
343 return (0);
344 }
345
346 static u_int
347 pcap_sendqueue_transmit_win32(pcap_t *p, pcap_send_queue *queue, int sync)
348 {
349 u_int res;
350 char errbuf[PCAP_ERRBUF_SIZE+1];
351
352 if (p->adapter==NULL) {
353 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
354 "Cannot transmit a queue to an offline capture or to a TurboCap port");
355 return (0);
356 }
357
358 res = PacketSendPackets(p->adapter,
359 queue->buffer,
360 queue->len,
361 (BOOLEAN)sync);
362
363 if(res != queue->len){
364 pcap_win32_err_to_str(GetLastError(), errbuf);
365 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
366 "Error opening adapter: %s", errbuf);
367 }
368
369 return (res);
370 }
371
372 static int
373 pcap_setuserbuffer_win32(pcap_t *p, int size)
374 {
375 unsigned char *new_buff;
376
377 if (size<=0) {
378 /* Bogus parameter */
379 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
380 "Error: invalid size %d",size);
381 return (-1);
382 }
383
384 /* Allocate the buffer */
385 new_buff=(unsigned char*)malloc(sizeof(char)*size);
386
387 if (!new_buff) {
388 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
389 "Error: not enough memory");
390 return (-1);
391 }
392
393 free(p->buffer);
394
395 p->buffer=new_buff;
396 p->bufsize=size;
397
398 return (0);
399 }
400
401 static int
402 pcap_live_dump_win32(pcap_t *p, char *filename, int maxsize, int maxpacks)
403 {
404 BOOLEAN res;
405
406 /* Set the packet driver in dump mode */
407 res = PacketSetMode(p->adapter, PACKET_MODE_DUMP);
408 if(res == FALSE){
409 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
410 "Error setting dump mode");
411 return (-1);
412 }
413
414 /* Set the name of the dump file */
415 res = PacketSetDumpName(p->adapter, filename, (int)strlen(filename));
416 if(res == FALSE){
417 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
418 "Error setting kernel dump file name");
419 return (-1);
420 }
421
422 /* Set the limits of the dump file */
423 res = PacketSetDumpLimits(p->adapter, maxsize, maxpacks);
424
425 return (0);
426 }
427
428 static int
429 pcap_live_dump_ended_win32(pcap_t *p, int sync)
430 {
431 return (PacketIsDumpEnded(p->adapter, (BOOLEAN)sync));
432 }
433
434 static PAirpcapHandle
435 pcap_get_airpcap_handle_win32(pcap_t *p)
436 {
437 #ifdef HAVE_AIRPCAP_API
438 return (PacketGetAirPcapHandle(p->adapter));
439 #else
440 return (NULL);
441 #endif /* HAVE_AIRPCAP_API */
442 }
443
444 static int
445 pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
446 {
447 PACKET Packet;
448 int cc;
449 int n = 0;
450 register u_char *bp, *ep;
451 u_char *datap;
452 struct pcap_win *pw = p->priv;
453
454 cc = p->cc;
455 if (p->cc == 0) {
456 /*
457 * Has "pcap_breakloop()" been called?
458 */
459 if (p->break_loop) {
460 /*
461 * Yes - clear the flag that indicates that it
462 * has, and return PCAP_ERROR_BREAK to indicate
463 * that we were told to break out of the loop.
464 */
465 p->break_loop = 0;
466 return (PCAP_ERROR_BREAK);
467 }
468
469 /*
470 * Capture the packets.
471 *
472 * The PACKET structure had a bunch of extra stuff for
473 * Windows 9x/Me, but the only interesting data in it
474 * in the versions of Windows that we support is just
475 * a copy of p->buffer, a copy of p->buflen, and the
476 * actual number of bytes read returned from
477 * PacketReceivePacket(), none of which has to be
478 * retained from call to call, so we just keep one on
479 * the stack.
480 */
481 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
482 if (!PacketReceivePacket(p->adapter, &Packet, TRUE)) {
483 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
484 return (PCAP_ERROR);
485 }
486
487 cc = Packet.ulBytesReceived;
488
489 bp = p->buffer;
490 }
491 else
492 bp = p->bp;
493
494 /*
495 * Loop through each packet.
496 */
497 #define bhp ((struct bpf_hdr *)bp)
498 ep = bp + cc;
499 while (1) {
500 register int caplen, hdrlen;
501
502 /*
503 * Has "pcap_breakloop()" been called?
504 * If so, return immediately - if we haven't read any
505 * packets, clear the flag and return PCAP_ERROR_BREAK
506 * to indicate that we were told to break out of the loop,
507 * otherwise leave the flag set, so that the *next* call
508 * will break out of the loop without having read any
509 * packets, and return the number of packets we've
510 * processed so far.
511 */
512 if (p->break_loop) {
513 if (n == 0) {
514 p->break_loop = 0;
515 return (PCAP_ERROR_BREAK);
516 } else {
517 p->bp = bp;
518 p->cc = ep - bp;
519 return (n);
520 }
521 }
522 if (bp >= ep)
523 break;
524
525 caplen = bhp->bh_caplen;
526 hdrlen = bhp->bh_hdrlen;
527 datap = bp + hdrlen;
528
529 /*
530 * Short-circuit evaluation: if using BPF filter
531 * in kernel, no need to do it now - we already know
532 * the packet passed the filter.
533 *
534 * XXX - bpf_filter() should always return TRUE if
535 * handed a null pointer for the program, but it might
536 * just try to "run" the filter, so we check here.
537 */
538 if (pw->filtering_in_kernel ||
539 p->fcode.bf_insns == NULL ||
540 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
541 /*
542 * XXX A bpf_hdr matches a pcap_pkthdr.
543 */
544 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
545 bp += Packet_WORDALIGN(caplen + hdrlen);
546 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
547 p->bp = bp;
548 p->cc = ep - bp;
549 return (n);
550 }
551 } else {
552 /*
553 * Skip this packet.
554 */
555 bp += Packet_WORDALIGN(caplen + hdrlen);
556 }
557 }
558 #undef bhp
559 p->cc = 0;
560 return (n);
561 }
562
563 #ifdef HAVE_DAG_API
564 static int
565 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
566 {
567 struct pcap_win *pw = p->priv;
568 PACKET Packet;
569 u_char *dp = NULL;
570 int packet_len = 0, caplen = 0;
571 struct pcap_pkthdr pcap_header;
572 u_char *endofbuf;
573 int n = 0;
574 dag_record_t *header;
575 unsigned erf_record_len;
576 ULONGLONG ts;
577 int cc;
578 unsigned swt;
579 unsigned dfp = p->adapter->DagFastProcess;
580
581 cc = p->cc;
582 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
583 {
584 /*
585 * Get new packets from the network.
586 *
587 * The PACKET structure had a bunch of extra stuff for
588 * Windows 9x/Me, but the only interesting data in it
589 * in the versions of Windows that we support is just
590 * a copy of p->buffer, a copy of p->buflen, and the
591 * actual number of bytes read returned from
592 * PacketReceivePacket(), none of which has to be
593 * retained from call to call, so we just keep one on
594 * the stack.
595 */
596 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
597 if (!PacketReceivePacket(p->adapter, &Packet, TRUE)) {
598 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
599 return (-1);
600 }
601
602 cc = Packet.ulBytesReceived;
603 if(cc == 0)
604 /* The timeout has expired but we no packets arrived */
605 return (0);
606 header = (dag_record_t*)p->adapter->DagBuffer;
607 }
608 else
609 header = (dag_record_t*)p->bp;
610
611 endofbuf = (char*)header + cc;
612
613 /*
614 * Cycle through the packets
615 */
616 do
617 {
618 erf_record_len = SWAPS(header->rlen);
619 if((char*)header + erf_record_len > endofbuf)
620 break;
621
622 /* Increase the number of captured packets */
623 p->stat.ps_recv++;
624
625 /* Find the beginning of the packet */
626 dp = ((u_char *)header) + dag_record_size;
627
628 /* Determine actual packet len */
629 switch(header->type)
630 {
631 case TYPE_ATM:
632 packet_len = ATM_SNAPLEN;
633 caplen = ATM_SNAPLEN;
634 dp += 4;
635
636 break;
637
638 case TYPE_ETH:
639 swt = SWAPS(header->wlen);
640 packet_len = swt - (pw->dag_fcs_bits);
641 caplen = erf_record_len - dag_record_size - 2;
642 if (caplen > packet_len)
643 {
644 caplen = packet_len;
645 }
646 dp += 2;
647
648 break;
649
650 case TYPE_HDLC_POS:
651 swt = SWAPS(header->wlen);
652 packet_len = swt - (pw->dag_fcs_bits);
653 caplen = erf_record_len - dag_record_size;
654 if (caplen > packet_len)
655 {
656 caplen = packet_len;
657 }
658
659 break;
660 }
661
662 if(caplen > p->snapshot)
663 caplen = p->snapshot;
664
665 /*
666 * Has "pcap_breakloop()" been called?
667 * If so, return immediately - if we haven't read any
668 * packets, clear the flag and return -2 to indicate
669 * that we were told to break out of the loop, otherwise
670 * leave the flag set, so that the *next* call will break
671 * out of the loop without having read any packets, and
672 * return the number of packets we've processed so far.
673 */
674 if (p->break_loop)
675 {
676 if (n == 0)
677 {
678 p->break_loop = 0;
679 return (-2);
680 }
681 else
682 {
683 p->bp = (char*)header;
684 p->cc = endofbuf - (char*)header;
685 return (n);
686 }
687 }
688
689 if(!dfp)
690 {
691 /* convert between timestamp formats */
692 ts = header->ts;
693 pcap_header.ts.tv_sec = (int)(ts >> 32);
694 ts = (ts & 0xffffffffi64) * 1000000;
695 ts += 0x80000000; /* rounding */
696 pcap_header.ts.tv_usec = (int)(ts >> 32);
697 if (pcap_header.ts.tv_usec >= 1000000) {
698 pcap_header.ts.tv_usec -= 1000000;
699 pcap_header.ts.tv_sec++;
700 }
701 }
702
703 /* No underlaying filtering system. We need to filter on our own */
704 if (p->fcode.bf_insns)
705 {
706 if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
707 {
708 /* Move to next packet */
709 header = (dag_record_t*)((char*)header + erf_record_len);
710 continue;
711 }
712 }
713
714 /* Fill the header for the user suppplied callback function */
715 pcap_header.caplen = caplen;
716 pcap_header.len = packet_len;
717
718 /* Call the callback function */
719 (*callback)(user, &pcap_header, dp);
720
721 /* Move to next packet */
722 header = (dag_record_t*)((char*)header + erf_record_len);
723
724 /* Stop if the number of packets requested by user has been reached*/
725 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
726 {
727 p->bp = (char*)header;
728 p->cc = endofbuf - (char*)header;
729 return (n);
730 }
731 }
732 while((u_char*)header < endofbuf);
733
734 return (1);
735 }
736 #endif /* HAVE_DAG_API */
737
738 /* Send a packet to the network */
739 static int
740 pcap_inject_win32(pcap_t *p, const void *buf, size_t size){
741 LPPACKET PacketToSend;
742
743 PacketToSend=PacketAllocatePacket();
744
745 if (PacketToSend == NULL)
746 {
747 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketAllocatePacket failed");
748 return (-1);
749 }
750
751 PacketInitPacket(PacketToSend, (PVOID)buf, (UINT)size);
752 if(PacketSendPacket(p->adapter,PacketToSend,TRUE) == FALSE){
753 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
754 PacketFreePacket(PacketToSend);
755 return (-1);
756 }
757
758 PacketFreePacket(PacketToSend);
759
760 /*
761 * We assume it all got sent if "PacketSendPacket()" succeeded.
762 * "pcap_inject()" is expected to return the number of bytes
763 * sent.
764 */
765 return ((int)size);
766 }
767
768 static void
769 pcap_cleanup_win32(pcap_t *p)
770 {
771 if (p->adapter != NULL) {
772 PacketCloseAdapter(p->adapter);
773 p->adapter = NULL;
774 }
775 pcap_cleanup_live_common(p);
776 }
777
778 static int
779 pcap_activate_win32(pcap_t *p)
780 {
781 #ifdef HAVE_DAG_API
782 struct pcap_win *pw = p->priv;
783 #endif
784 NetType type;
785 char errbuf[PCAP_ERRBUF_SIZE+1];
786
787 if (p->opt.rfmon) {
788 /*
789 * No monitor mode on Windows. It could be done on
790 * Vista with drivers that support the native 802.11
791 * mechanism and monitor mode.
792 */
793 return (PCAP_ERROR_RFMON_NOTSUP);
794 }
795
796 /* Init WinSock */
797 wsockinit();
798
799 p->adapter = PacketOpenAdapter(p->opt.device);
800
801 if (p->adapter == NULL)
802 {
803 /* Adapter detected but we are not able to open it. Return failure. */
804 pcap_win32_err_to_str(GetLastError(), errbuf);
805 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
806 "Error opening adapter: %s", errbuf);
807 return (PCAP_ERROR);
808 }
809
810 /*get network type*/
811 if(PacketGetNetType (p->adapter,&type) == FALSE)
812 {
813 pcap_win32_err_to_str(GetLastError(), errbuf);
814 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
815 "Cannot determine the network type: %s", errbuf);
816 goto bad;
817 }
818
819 /*Set the linktype*/
820 switch (type.LinkType)
821 {
822 case NdisMediumWan:
823 p->linktype = DLT_EN10MB;
824 break;
825
826 case NdisMedium802_3:
827 p->linktype = DLT_EN10MB;
828 /*
829 * This is (presumably) a real Ethernet capture; give it a
830 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
831 * that an application can let you choose it, in case you're
832 * capturing DOCSIS traffic that a Cisco Cable Modem
833 * Termination System is putting out onto an Ethernet (it
834 * doesn't put an Ethernet header onto the wire, it puts raw
835 * DOCSIS frames out on the wire inside the low-level
836 * Ethernet framing).
837 */
838 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
839 /*
840 * If that fails, just leave the list empty.
841 */
842 if (p->dlt_list != NULL) {
843 p->dlt_list[0] = DLT_EN10MB;
844 p->dlt_list[1] = DLT_DOCSIS;
845 p->dlt_count = 2;
846 }
847 break;
848
849 case NdisMediumFddi:
850 p->linktype = DLT_FDDI;
851 break;
852
853 case NdisMedium802_5:
854 p->linktype = DLT_IEEE802;
855 break;
856
857 case NdisMediumArcnetRaw:
858 p->linktype = DLT_ARCNET;
859 break;
860
861 case NdisMediumArcnet878_2:
862 p->linktype = DLT_ARCNET;
863 break;
864
865 case NdisMediumAtm:
866 p->linktype = DLT_ATM_RFC1483;
867 break;
868
869 case NdisMediumCHDLC:
870 p->linktype = DLT_CHDLC;
871 break;
872
873 case NdisMediumPPPSerial:
874 p->linktype = DLT_PPP_SERIAL;
875 break;
876
877 case NdisMediumNull:
878 p->linktype = DLT_NULL;
879 break;
880
881 case NdisMediumBare80211:
882 p->linktype = DLT_IEEE802_11;
883 break;
884
885 case NdisMediumRadio80211:
886 p->linktype = DLT_IEEE802_11_RADIO;
887 break;
888
889 case NdisMediumPpi:
890 p->linktype = DLT_PPI;
891 break;
892
893 default:
894 p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/
895 break;
896 }
897
898 /* Set promiscuous mode */
899 if (p->opt.promisc)
900 {
901
902 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
903 {
904 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
905 goto bad;
906 }
907 }
908 else
909 {
910 if (PacketSetHwFilter(p->adapter,NDIS_PACKET_TYPE_ALL_LOCAL) == FALSE)
911 {
912 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
913 goto bad;
914 }
915 }
916
917 /* Set the buffer size */
918 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
919
920 if(!(p->adapter->Flags & INFO_FLAG_DAG_CARD))
921 {
922 /*
923 * Traditional Adapter
924 */
925 /*
926 * If the buffer size wasn't explicitly set, default to
927 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
928 */
929 if (p->opt.buffer_size == 0)
930 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
931
932 if(PacketSetBuff(p->adapter,p->opt.buffer_size)==FALSE)
933 {
934 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
935 goto bad;
936 }
937
938 p->buffer = malloc(p->bufsize);
939 if (p->buffer == NULL)
940 {
941 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
942 goto bad;
943 }
944
945 if (p->opt.immediate)
946 {
947 /* tell the driver to copy the buffer as soon as data arrives */
948 if(PacketSetMinToCopy(p->adapter,0)==FALSE)
949 {
950 pcap_win32_err_to_str(GetLastError(), errbuf);
951 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
952 "Error calling PacketSetMinToCopy: %s",
953 errbuf);
954 goto bad;
955 }
956 }
957 else
958 {
959 /* tell the driver to copy the buffer only if it contains at least 16K */
960 if(PacketSetMinToCopy(p->adapter,16000)==FALSE)
961 {
962 pcap_win32_err_to_str(GetLastError(), errbuf);
963 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
964 "Error calling PacketSetMinToCopy: %s",
965 errbuf);
966 goto bad;
967 }
968 }
969 }
970 else
971 #ifdef HAVE_DAG_API
972 {
973 /*
974 * Dag Card
975 */
976 LONG status;
977 HKEY dagkey;
978 DWORD lptype;
979 DWORD lpcbdata;
980 int postype = 0;
981 char keyname[512];
982
983 pcap_snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
984 "SYSTEM\\CurrentControlSet\\Services\\DAG",
985 strstr(_strlwr(p->opt.device), "dag"));
986 do
987 {
988 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
989 if(status != ERROR_SUCCESS)
990 break;
991
992 status = RegQueryValueEx(dagkey,
993 "PosType",
994 NULL,
995 &lptype,
996 (char*)&postype,
997 &lpcbdata);
998
999 if(status != ERROR_SUCCESS)
1000 {
1001 postype = 0;
1002 }
1003
1004 RegCloseKey(dagkey);
1005 }
1006 while(FALSE);
1007
1008
1009 p->snapshot = PacketSetSnapLen(p->adapter, snaplen);
1010
1011 /* Set the length of the FCS associated to any packet. This value
1012 * will be subtracted to the packet length */
1013 pw->dag_fcs_bits = p->adapter->DagFcsLen;
1014 }
1015 #else
1016 goto bad;
1017 #endif /* HAVE_DAG_API */
1018
1019 PacketSetReadTimeout(p->adapter, p->opt.timeout);
1020
1021 #ifdef HAVE_DAG_API
1022 if(p->adapter->Flags & INFO_FLAG_DAG_CARD)
1023 {
1024 /* install dag specific handlers for read and setfilter */
1025 p->read_op = pcap_read_win32_dag;
1026 p->setfilter_op = pcap_setfilter_win32_dag;
1027 }
1028 else
1029 {
1030 #endif /* HAVE_DAG_API */
1031 /* install traditional npf handlers for read and setfilter */
1032 p->read_op = pcap_read_win32_npf;
1033 p->setfilter_op = pcap_setfilter_win32_npf;
1034 #ifdef HAVE_DAG_API
1035 }
1036 #endif /* HAVE_DAG_API */
1037 p->setdirection_op = NULL; /* Not implemented. */
1038 /* XXX - can this be implemented on some versions of Windows? */
1039 p->inject_op = pcap_inject_win32;
1040 p->set_datalink_op = NULL; /* can't change data link type */
1041 p->getnonblock_op = pcap_getnonblock_win32;
1042 p->setnonblock_op = pcap_setnonblock_win32;
1043 p->stats_op = pcap_stats_win32;
1044 p->stats_ex_op = pcap_stats_ex_win32;
1045 p->setbuff_op = pcap_setbuff_win32;
1046 p->setmode_op = pcap_setmode_win32;
1047 p->setmintocopy_op = pcap_setmintocopy_win32;
1048 p->getevent_op = pcap_getevent_win32;
1049 p->oid_get_request_op = pcap_oid_get_request_win32;
1050 p->oid_set_request_op = pcap_oid_set_request_win32;
1051 p->sendqueue_transmit_op = pcap_sendqueue_transmit_win32;
1052 p->setuserbuffer_op = pcap_setuserbuffer_win32;
1053 p->live_dump_op = pcap_live_dump_win32;
1054 p->live_dump_ended_op = pcap_live_dump_ended_win32;
1055 p->get_airpcap_handle_op = pcap_get_airpcap_handle_win32;
1056 p->cleanup_op = pcap_cleanup_win32;
1057
1058 return (0);
1059 bad:
1060 pcap_cleanup_win32(p);
1061 return (PCAP_ERROR);
1062 }
1063
1064 pcap_t *
1065 pcap_create_interface(char *ebuf)
1066 {
1067 pcap_t *p;
1068
1069 p = pcap_create_common(ebuf, sizeof (struct pcap_win));
1070 if (p == NULL)
1071 return (NULL);
1072
1073 p->activate_op = pcap_activate_win32;
1074 return (p);
1075 }
1076
1077 static int
1078 pcap_setfilter_win32_npf(pcap_t *p, struct bpf_program *fp)
1079 {
1080 struct pcap_win *pw = p->priv;
1081
1082 if(PacketSetBpf(p->adapter,fp)==FALSE){
1083 /*
1084 * Kernel filter not installed.
1085 *
1086 * XXX - we don't know whether this failed because:
1087 *
1088 * the kernel rejected the filter program as invalid,
1089 * in which case we should fall back on userland
1090 * filtering;
1091 *
1092 * the kernel rejected the filter program as too big,
1093 * in which case we should again fall back on
1094 * userland filtering;
1095 *
1096 * there was some other problem, in which case we
1097 * should probably report an error.
1098 *
1099 * For NPF devices, the Win32 status will be
1100 * STATUS_INVALID_DEVICE_REQUEST for invalid
1101 * filters, but I don't know what it'd be for
1102 * other problems, and for some other devices
1103 * it might not be set at all.
1104 *
1105 * So we just fall back on userland filtering in
1106 * all cases.
1107 */
1108
1109 /*
1110 * install_bpf_program() validates the program.
1111 *
1112 * XXX - what if we already have a filter in the kernel?
1113 */
1114 if (install_bpf_program(p, fp) < 0)
1115 return (-1);
1116 pw->filtering_in_kernel = 0; /* filtering in userland */
1117 return (0);
1118 }
1119
1120 /*
1121 * It worked.
1122 */
1123 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1124
1125 /*
1126 * Discard any previously-received packets, as they might have
1127 * passed whatever filter was formerly in effect, but might
1128 * not pass this filter (BIOCSETF discards packets buffered
1129 * in the kernel, so you can lose packets in any case).
1130 */
1131 p->cc = 0;
1132 return (0);
1133 }
1134
1135 /*
1136 * We filter at user level, since the kernel driver does't process the packets
1137 */
1138 static int
1139 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1140
1141 if(!fp)
1142 {
1143 strncpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1144 return (-1);
1145 }
1146
1147 /* Install a user level filter */
1148 if (install_bpf_program(p, fp) < 0)
1149 {
1150 pcap_snprintf(p->errbuf, sizeof(p->errbuf),
1151 "setfilter, unable to install the filter: %s", pcap_strerror(errno));
1152 return (-1);
1153 }
1154
1155 return (0);
1156 }
1157
1158 static int
1159 pcap_getnonblock_win32(pcap_t *p, char *errbuf)
1160 {
1161 struct pcap_win *pw = p->priv;
1162
1163 /*
1164 * XXX - if there were a PacketGetReadTimeout() call, we
1165 * would use it, and return 1 if the timeout is -1
1166 * and 0 otherwise.
1167 */
1168 return (pw->nonblock);
1169 }
1170
1171 static int
1172 pcap_setnonblock_win32(pcap_t *p, int nonblock, char *errbuf)
1173 {
1174 struct pcap_win *pw = p->priv;
1175 int newtimeout;
1176 char win_errbuf[PCAP_ERRBUF_SIZE+1];
1177
1178 if (nonblock) {
1179 /*
1180 * Set the read timeout to -1 for non-blocking mode.
1181 */
1182 newtimeout = -1;
1183 } else {
1184 /*
1185 * Restore the timeout set when the device was opened.
1186 * (Note that this may be -1, in which case we're not
1187 * really leaving non-blocking mode. However, although
1188 * the timeout argument to pcap_set_timeout() and
1189 * pcap_open_live() is an int, you're not supposed to
1190 * supply a negative value, so that "shouldn't happen".)
1191 */
1192 newtimeout = p->opt.timeout;
1193 }
1194 if (!PacketSetReadTimeout(p->adapter, newtimeout)) {
1195 pcap_win32_err_to_str(GetLastError(), win_errbuf);
1196 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1197 "PacketSetReadTimeout: %s", win_errbuf);
1198 return (-1);
1199 }
1200 pw->nonblock = (newtimeout == -1);
1201 return (0);
1202 }
1203
1204 static int
1205 pcap_add_if_win32(pcap_if_t **devlist, char *name, bpf_u_int32 flags,
1206 const char *description, char *errbuf)
1207 {
1208 pcap_if_t *curdev;
1209 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1210 LONG if_addr_size;
1211 int res = 0;
1212
1213 if_addr_size = MAX_NETWORK_ADDRESSES;
1214
1215 /*
1216 * Add an entry for this interface, with no addresses.
1217 */
1218 if (add_or_find_if(&curdev, devlist, name, flags, description,
1219 errbuf) == -1) {
1220 /*
1221 * Failure.
1222 */
1223 return (-1);
1224 }
1225
1226 /*
1227 * Get the list of addresses for the interface.
1228 */
1229 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1230 /*
1231 * Failure.
1232 *
1233 * We don't return an error, because this can happen with
1234 * NdisWan interfaces, and we want to supply them even
1235 * if we can't supply their addresses.
1236 *
1237 * We return an entry with an empty address list.
1238 */
1239 return (0);
1240 }
1241
1242 /*
1243 * Now add the addresses.
1244 */
1245 while (if_addr_size-- > 0) {
1246 /*
1247 * "curdev" is an entry for this interface; add an entry for
1248 * this address to its list of addresses.
1249 */
1250 if(curdev == NULL)
1251 break;
1252 res = add_addr_to_dev(curdev,
1253 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1254 sizeof (struct sockaddr_storage),
1255 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1256 sizeof (struct sockaddr_storage),
1257 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1258 sizeof (struct sockaddr_storage),
1259 NULL,
1260 0,
1261 errbuf);
1262 if (res == -1) {
1263 /*
1264 * Failure.
1265 */
1266 break;
1267 }
1268 }
1269
1270 return (res);
1271 }
1272
1273 int
1274 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
1275 {
1276 pcap_if_t *devlist = NULL;
1277 int ret = 0;
1278 const char *desc;
1279 char *AdaptersName;
1280 ULONG NameLength;
1281 char *name;
1282 char our_errbuf[PCAP_ERRBUF_SIZE+1];
1283
1284 /*
1285 * Find out how big a buffer we need.
1286 *
1287 * This call should always return FALSE; if the error is
1288 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1289 * the size of the buffer we need, otherwise there's a
1290 * problem, and NameLength should be set to 0.
1291 *
1292 * It shouldn't require NameLength to be set, but,
1293 * at least as of WinPcap 4.1.3, it checks whether
1294 * NameLength is big enough before it checks for a
1295 * NULL buffer argument, so, while it'll still do
1296 * the right thing if NameLength is uninitialized and
1297 * whatever junk happens to be there is big enough
1298 * (because the pointer argument will be null), it's
1299 * still reading an uninitialized variable.
1300 */
1301 NameLength = 0;
1302 if (!PacketGetAdapterNames(NULL, &NameLength))
1303 {
1304 DWORD last_error = GetLastError();
1305
1306 if (last_error != ERROR_INSUFFICIENT_BUFFER)
1307 {
1308 pcap_win32_err_to_str(last_error, our_errbuf);
1309 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1310 "PacketGetAdapterNames: %s", our_errbuf);
1311 return (-1);
1312 }
1313 }
1314
1315 if (NameLength > 0)
1316 AdaptersName = (char*) malloc(NameLength);
1317 else
1318 {
1319 *alldevsp = NULL;
1320 return 0;
1321 }
1322 if (AdaptersName == NULL)
1323 {
1324 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
1325 return (-1);
1326 }
1327
1328 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
1329 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1330 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "PacketGetAdapterNames: %s",
1331 our_errbuf);
1332 free(AdaptersName);
1333 return (-1);
1334 }
1335
1336 /*
1337 * "PacketGetAdapterNames()" returned a list of
1338 * null-terminated ASCII interface name strings,
1339 * terminated by a null string, followed by a list
1340 * of null-terminated ASCII interface description
1341 * strings, terminated by a null string.
1342 * This means there are two ASCII nulls at the end
1343 * of the first list.
1344 *
1345 * Find the end of the first list; that's the
1346 * beginning of the second list.
1347 */
1348 desc = &AdaptersName[0];
1349 while (*desc != '\0' || *(desc + 1) != '\0')
1350 desc++;
1351
1352 /*
1353 * Found it - "desc" points to the first of the two
1354 * nulls at the end of the list of names, so the
1355 * first byte of the list of descriptions is two bytes
1356 * after it.
1357 */
1358 desc += 2;
1359
1360 /*
1361 * Loop over the elements in the first list.
1362 */
1363 name = &AdaptersName[0];
1364 while (*name != '\0') {
1365 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1366 bpf_u_int32 flags = 0;
1367 pcap_t p;
1368
1369 /*
1370 * Is this a loopback interface?
1371 * XXX - it'd be best if there were a way to get a list
1372 * of interfaces *and* flags, including "Up" and "Running"
1373 * as well as "loopback", without having to open the
1374 * interfaces.
1375 */
1376 p = pcap_open_live(name, 68, 0, 0, errbuf);
1377 if (p != NULL) {
1378 if (PacketIsLoopbackAdapter(p->adapter)) {
1379 /* Yes */
1380 flags |= PCAP_IF_LOOPBACK;
1381 }
1382 pcap_close(p);
1383 }
1384 #endif
1385
1386 /*
1387 * Add an entry for this interface.
1388 */
1389 if (pcap_add_if_win32(&devlist, name, flags, desc,
1390 errbuf) == -1) {
1391 /*
1392 * Failure.
1393 */
1394 ret = -1;
1395 break;
1396 }
1397 name += strlen(name) + 1;
1398 desc += strlen(desc) + 1;
1399 }
1400
1401 if (ret == -1) {
1402 /*
1403 * We had an error; free the list we've been constructing.
1404 */
1405 if (devlist != NULL) {
1406 pcap_freealldevs(devlist);
1407 devlist = NULL;
1408 }
1409 }
1410
1411 *alldevsp = devlist;
1412 free(AdaptersName);
1413 return (ret);
1414 }