]> The Tcpdump Group git mirrors - libpcap/blob - pcap-win32.c
Push pcap_lib_version() into the pcap-XXX.c files.
[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 *);
60 static int pcap_setnonblock_win32(pcap_t *, int);
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 ADAPTER *adapter; /* the packet32 ADAPTER for the device */
76 int nonblock;
77 int rfmon_selfstart; /* a flag tells whether the monitor mode is set by itself */
78 int filtering_in_kernel; /* using kernel filter */
79
80 #ifdef HAVE_DAG_API
81 int dag_fcs_bits; /* Number of checksum bits from link layer */
82 #endif
83
84 #ifdef HAVE_REMOTE
85 int samp_npkt; /* parameter needed for sampling, with '1 out of N' method has been requested */
86 struct timeval samp_time; /* parameter needed for sampling, with '1 every N ms' method has been requested */
87 #endif
88 };
89
90 BOOL WINAPI DllMain(
91 HANDLE hinstDLL,
92 DWORD dwReason,
93 LPVOID lpvReserved
94 )
95 {
96 return (TRUE);
97 }
98
99 /*
100 * Define stub versions of the monitor-mode support routines if this
101 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
102 * WinPcap.
103 */
104 #ifndef HAVE_NPCAP_PACKET_API
105 static int
106 PacketIsMonitorModeSupported(PCHAR AdapterName _U_)
107 {
108 /*
109 * We don't support monitor mode.
110 */
111 return (0);
112 }
113
114 static int
115 PacketSetMonitorMode(PCHAR AdapterName _U_, int mode _U_)
116 {
117 /*
118 * This should never be called, as PacketIsMonitorModeSupported()
119 * will return 0, meaning "we don't support monitor mode, so
120 * don't try to turn it on or off".
121 */
122 return (0);
123 }
124
125 static int
126 PacketGetMonitorMode(PCHAR AdapterName _U_)
127 {
128 /*
129 * This should fail, so that pcap_activate_win32() returns
130 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
131 * mode.
132 */
133 return (-1);
134 }
135 #endif
136
137 /* Start winsock */
138 int
139 wsockinit(void)
140 {
141 WORD wVersionRequested;
142 WSADATA wsaData;
143 static int err = -1;
144 static int done = 0;
145
146 if (done)
147 return (err);
148
149 wVersionRequested = MAKEWORD( 1, 1);
150 err = WSAStartup( wVersionRequested, &wsaData );
151 atexit ((void(*)(void))WSACleanup);
152 done = 1;
153
154 if ( err != 0 )
155 err = -1;
156 return (err);
157 }
158
159 int
160 pcap_wsockinit(void)
161 {
162 return (wsockinit());
163 }
164
165 static int
166 pcap_stats_win32(pcap_t *p, struct pcap_stat *ps)
167 {
168 struct pcap_win *pw = p->priv;
169 struct bpf_stat bstats;
170 char errbuf[PCAP_ERRBUF_SIZE+1];
171
172 /*
173 * Try to get statistics.
174 *
175 * (Please note - "struct pcap_stat" is *not* the same as
176 * WinPcap's "struct bpf_stat". It might currently have the
177 * same layout, but let's not cheat.
178 *
179 * Note also that we don't fill in ps_capt, as we might have
180 * been called by code compiled against an earlier version of
181 * WinPcap that didn't have ps_capt, in which case filling it
182 * in would stomp on whatever comes after the structure passed
183 * to us.
184 */
185 if (!PacketGetStats(pw->adapter, &bstats)) {
186 pcap_win32_err_to_str(GetLastError(), errbuf);
187 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
188 "PacketGetStats error: %s", errbuf);
189 return (-1);
190 }
191 ps->ps_recv = bstats.bs_recv;
192 ps->ps_drop = bstats.bs_drop;
193
194 /*
195 * XXX - PacketGetStats() doesn't fill this in, so we just
196 * return 0.
197 */
198 #if 0
199 ps->ps_ifdrop = bstats.ps_ifdrop;
200 #else
201 ps->ps_ifdrop = 0;
202 #endif
203
204 return (0);
205 }
206
207 /*
208 * Win32-only routine for getting statistics.
209 *
210 * This way is definitely safer than passing the pcap_stat * from the userland.
211 * In fact, there could happen than the user allocates a variable which is not
212 * big enough for the new structure, and the library will write in a zone
213 * which is not allocated to this variable.
214 *
215 * In this way, we're pretty sure we are writing on memory allocated to this
216 * variable.
217 *
218 * XXX - but this is the wrong way to handle statistics. Instead, we should
219 * have an API that returns data in a form like the Options section of a
220 * pcapng Interface Statistics Block:
221 *
222 * 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
223 *
224 * which would let us add new statistics straightforwardly and indicate which
225 * statistics we are and are *not* providing, rather than having to provide
226 * possibly-bogus values for statistics we can't provide.
227 */
228 struct pcap_stat *
229 pcap_stats_ex_win32(pcap_t *p, int *pcap_stat_size)
230 {
231 struct pcap_win *pw = p->priv;
232 struct bpf_stat bstats;
233 char errbuf[PCAP_ERRBUF_SIZE+1];
234
235 *pcap_stat_size = sizeof (p->stat);
236
237 /*
238 * Try to get statistics.
239 *
240 * (Please note - "struct pcap_stat" is *not* the same as
241 * WinPcap's "struct bpf_stat". It might currently have the
242 * same layout, but let's not cheat.)
243 */
244 if (!PacketGetStatsEx(pw->adapter, &bstats)) {
245 pcap_win32_err_to_str(GetLastError(), errbuf);
246 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
247 "PacketGetStatsEx error: %s", errbuf);
248 return (NULL);
249 }
250 p->stat.ps_recv = bstats.bs_recv;
251 p->stat.ps_drop = bstats.bs_drop;
252 p->stat.ps_ifdrop = bstats.ps_ifdrop;
253 #ifdef HAVE_REMOTE
254 p->stat.ps_capt = bstats.bs_capt;
255 #endif
256 return (&p->stat);
257 }
258
259 /* Set the dimension of the kernel-level capture buffer */
260 static int
261 pcap_setbuff_win32(pcap_t *p, int dim)
262 {
263 struct pcap_win *pw = p->priv;
264
265 if(PacketSetBuff(pw->adapter,dim)==FALSE)
266 {
267 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
268 return (-1);
269 }
270 return (0);
271 }
272
273 /* Set the driver working mode */
274 static int
275 pcap_setmode_win32(pcap_t *p, int mode)
276 {
277 struct pcap_win *pw = p->priv;
278
279 if(PacketSetMode(pw->adapter,mode)==FALSE)
280 {
281 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
282 return (-1);
283 }
284
285 return (0);
286 }
287
288 /*set the minimum amount of data that will release a read call*/
289 static int
290 pcap_setmintocopy_win32(pcap_t *p, int size)
291 {
292 struct pcap_win *pw = p->priv;
293
294 if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
295 {
296 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
297 return (-1);
298 }
299 return (0);
300 }
301
302 static HANDLE
303 pcap_getevent_win32(pcap_t *p)
304 {
305 struct pcap_win *pw = p->priv;
306
307 return (PacketGetReadEvent(pw->adapter));
308 }
309
310 static int
311 pcap_oid_get_request_win32(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
312 {
313 struct pcap_win *pw = p->priv;
314 PACKET_OID_DATA *oid_data_arg;
315 char errbuf[PCAP_ERRBUF_SIZE+1];
316
317 /*
318 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
319 * It should be big enough to hold "*lenp" bytes of data; it
320 * will actually be slightly larger, as PACKET_OID_DATA has a
321 * 1-byte data array at the end, standing in for the variable-length
322 * data that's actually there.
323 */
324 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
325 if (oid_data_arg == NULL) {
326 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
327 "Couldn't allocate argument buffer for PacketRequest");
328 return (PCAP_ERROR);
329 }
330
331 /*
332 * No need to copy the data - we're doing a fetch.
333 */
334 oid_data_arg->Oid = oid;
335 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
336 if (!PacketRequest(pw->adapter, FALSE, oid_data_arg)) {
337 pcap_win32_err_to_str(GetLastError(), errbuf);
338 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
339 "Error calling PacketRequest: %s", errbuf);
340 free(oid_data_arg);
341 return (PCAP_ERROR);
342 }
343
344 /*
345 * Get the length actually supplied.
346 */
347 *lenp = oid_data_arg->Length;
348
349 /*
350 * Copy back the data we fetched.
351 */
352 memcpy(data, oid_data_arg->Data, *lenp);
353 free(oid_data_arg);
354 return (0);
355 }
356
357 static int
358 pcap_oid_set_request_win32(pcap_t *p, bpf_u_int32 oid, const void *data,
359 size_t *lenp)
360 {
361 struct pcap_win *pw = p->priv;
362 PACKET_OID_DATA *oid_data_arg;
363 char errbuf[PCAP_ERRBUF_SIZE+1];
364
365 /*
366 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
367 * It should be big enough to hold "*lenp" bytes of data; it
368 * will actually be slightly larger, as PACKET_OID_DATA has a
369 * 1-byte data array at the end, standing in for the variable-length
370 * data that's actually there.
371 */
372 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
373 if (oid_data_arg == NULL) {
374 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
375 "Couldn't allocate argument buffer for PacketRequest");
376 return (PCAP_ERROR);
377 }
378
379 oid_data_arg->Oid = oid;
380 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
381 memcpy(oid_data_arg->Data, data, *lenp);
382 if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
383 pcap_win32_err_to_str(GetLastError(), errbuf);
384 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
385 "Error calling PacketRequest: %s", errbuf);
386 free(oid_data_arg);
387 return (PCAP_ERROR);
388 }
389
390 /*
391 * Get the length actually copied.
392 */
393 *lenp = oid_data_arg->Length;
394
395 /*
396 * No need to copy the data - we're doing a set.
397 */
398 free(oid_data_arg);
399 return (0);
400 }
401
402 static u_int
403 pcap_sendqueue_transmit_win32(pcap_t *p, pcap_send_queue *queue, int sync)
404 {
405 struct pcap_win *pw = p->priv;
406 u_int res;
407 char errbuf[PCAP_ERRBUF_SIZE+1];
408
409 if (pw->adapter==NULL) {
410 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
411 "Cannot transmit a queue to an offline capture or to a TurboCap port");
412 return (0);
413 }
414
415 res = PacketSendPackets(pw->adapter,
416 queue->buffer,
417 queue->len,
418 (BOOLEAN)sync);
419
420 if(res != queue->len){
421 pcap_win32_err_to_str(GetLastError(), errbuf);
422 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
423 "Error opening adapter: %s", errbuf);
424 }
425
426 return (res);
427 }
428
429 static int
430 pcap_setuserbuffer_win32(pcap_t *p, int size)
431 {
432 unsigned char *new_buff;
433
434 if (size<=0) {
435 /* Bogus parameter */
436 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
437 "Error: invalid size %d",size);
438 return (-1);
439 }
440
441 /* Allocate the buffer */
442 new_buff=(unsigned char*)malloc(sizeof(char)*size);
443
444 if (!new_buff) {
445 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
446 "Error: not enough memory");
447 return (-1);
448 }
449
450 free(p->buffer);
451
452 p->buffer=new_buff;
453 p->bufsize=size;
454
455 return (0);
456 }
457
458 static int
459 pcap_live_dump_win32(pcap_t *p, char *filename, int maxsize, int maxpacks)
460 {
461 struct pcap_win *pw = p->priv;
462 BOOLEAN res;
463
464 /* Set the packet driver in dump mode */
465 res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
466 if(res == FALSE){
467 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
468 "Error setting dump mode");
469 return (-1);
470 }
471
472 /* Set the name of the dump file */
473 res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
474 if(res == FALSE){
475 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
476 "Error setting kernel dump file name");
477 return (-1);
478 }
479
480 /* Set the limits of the dump file */
481 res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
482 if(res == FALSE) {
483 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
484 "Error setting dump limit");
485 return (-1);
486 }
487
488 return (0);
489 }
490
491 static int
492 pcap_live_dump_ended_win32(pcap_t *p, int sync)
493 {
494 struct pcap_win *pw = p->priv;
495
496 return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
497 }
498
499 static PAirpcapHandle
500 pcap_get_airpcap_handle_win32(pcap_t *p)
501 {
502 #ifdef HAVE_AIRPCAP_API
503 struct pcap_win *pw = p->priv;
504
505 return (PacketGetAirPcapHandle(pw->adapter));
506 #else
507 return (NULL);
508 #endif /* HAVE_AIRPCAP_API */
509 }
510
511 static int
512 pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
513 {
514 PACKET Packet;
515 int cc;
516 int n = 0;
517 register u_char *bp, *ep;
518 u_char *datap;
519 struct pcap_win *pw = p->priv;
520
521 cc = p->cc;
522 if (p->cc == 0) {
523 /*
524 * Has "pcap_breakloop()" been called?
525 */
526 if (p->break_loop) {
527 /*
528 * Yes - clear the flag that indicates that it
529 * has, and return PCAP_ERROR_BREAK to indicate
530 * that we were told to break out of the loop.
531 */
532 p->break_loop = 0;
533 return (PCAP_ERROR_BREAK);
534 }
535
536 /*
537 * Capture the packets.
538 *
539 * The PACKET structure had a bunch of extra stuff for
540 * Windows 9x/Me, but the only interesting data in it
541 * in the versions of Windows that we support is just
542 * a copy of p->buffer, a copy of p->buflen, and the
543 * actual number of bytes read returned from
544 * PacketReceivePacket(), none of which has to be
545 * retained from call to call, so we just keep one on
546 * the stack.
547 */
548 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
549 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
550 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
551 return (PCAP_ERROR);
552 }
553
554 cc = Packet.ulBytesReceived;
555
556 bp = p->buffer;
557 }
558 else
559 bp = p->bp;
560
561 /*
562 * Loop through each packet.
563 */
564 #define bhp ((struct bpf_hdr *)bp)
565 ep = bp + cc;
566 while (1) {
567 register int caplen, hdrlen;
568
569 /*
570 * Has "pcap_breakloop()" been called?
571 * If so, return immediately - if we haven't read any
572 * packets, clear the flag and return PCAP_ERROR_BREAK
573 * to indicate that we were told to break out of the loop,
574 * otherwise leave the flag set, so that the *next* call
575 * will break out of the loop without having read any
576 * packets, and return the number of packets we've
577 * processed so far.
578 */
579 if (p->break_loop) {
580 if (n == 0) {
581 p->break_loop = 0;
582 return (PCAP_ERROR_BREAK);
583 } else {
584 p->bp = bp;
585 p->cc = (int) (ep - bp);
586 return (n);
587 }
588 }
589 if (bp >= ep)
590 break;
591
592 caplen = bhp->bh_caplen;
593 hdrlen = bhp->bh_hdrlen;
594 datap = bp + hdrlen;
595
596 /*
597 * Short-circuit evaluation: if using BPF filter
598 * in kernel, no need to do it now - we already know
599 * the packet passed the filter.
600 *
601 * XXX - bpf_filter() should always return TRUE if
602 * handed a null pointer for the program, but it might
603 * just try to "run" the filter, so we check here.
604 */
605 if (pw->filtering_in_kernel ||
606 p->fcode.bf_insns == NULL ||
607 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
608 #ifdef HAVE_REMOTE
609 switch (p->rmt_samp.method) {
610
611 case PCAP_SAMP_1_EVERY_N:
612 pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
613
614 /* Discard all packets that are not '1 out of N' */
615 if (pw->samp_npkt != 0) {
616 bp += Packet_WORDALIGN(caplen + hdrlen);
617 continue;
618 }
619 break;
620
621 case PCAP_SAMP_FIRST_AFTER_N_MS:
622 {
623 struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
624
625 /*
626 * Check if the timestamp of the arrived
627 * packet is smaller than our target time.
628 */
629 if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
630 (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
631 bp += Packet_WORDALIGN(caplen + hdrlen);
632 continue;
633 }
634
635 /*
636 * The arrived packet is suitable for being
637 * delivered to our caller, so let's update
638 * the target time.
639 */
640 pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
641 if (pw->samp_time.tv_usec > 1000000) {
642 pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
643 pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
644 }
645 }
646 }
647 #endif /* HAVE_REMOTE */
648
649 /*
650 * XXX A bpf_hdr matches a pcap_pkthdr.
651 */
652 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
653 bp += Packet_WORDALIGN(caplen + hdrlen);
654 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
655 p->bp = bp;
656 p->cc = (int) (ep - bp);
657 return (n);
658 }
659 } else {
660 /*
661 * Skip this packet.
662 */
663 bp += Packet_WORDALIGN(caplen + hdrlen);
664 }
665 }
666 #undef bhp
667 p->cc = 0;
668 return (n);
669 }
670
671 #ifdef HAVE_DAG_API
672 static int
673 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
674 {
675 struct pcap_win *pw = p->priv;
676 PACKET Packet;
677 u_char *dp = NULL;
678 int packet_len = 0, caplen = 0;
679 struct pcap_pkthdr pcap_header;
680 u_char *endofbuf;
681 int n = 0;
682 dag_record_t *header;
683 unsigned erf_record_len;
684 ULONGLONG ts;
685 int cc;
686 unsigned swt;
687 unsigned dfp = pw->adapter->DagFastProcess;
688
689 cc = p->cc;
690 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
691 {
692 /*
693 * Get new packets from the network.
694 *
695 * The PACKET structure had a bunch of extra stuff for
696 * Windows 9x/Me, but the only interesting data in it
697 * in the versions of Windows that we support is just
698 * a copy of p->buffer, a copy of p->buflen, and the
699 * actual number of bytes read returned from
700 * PacketReceivePacket(), none of which has to be
701 * retained from call to call, so we just keep one on
702 * the stack.
703 */
704 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
705 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
706 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
707 return (-1);
708 }
709
710 cc = Packet.ulBytesReceived;
711 if(cc == 0)
712 /* The timeout has expired but we no packets arrived */
713 return (0);
714 header = (dag_record_t*)pw->adapter->DagBuffer;
715 }
716 else
717 header = (dag_record_t*)p->bp;
718
719 endofbuf = (char*)header + cc;
720
721 /*
722 * Cycle through the packets
723 */
724 do
725 {
726 erf_record_len = SWAPS(header->rlen);
727 if((char*)header + erf_record_len > endofbuf)
728 break;
729
730 /* Increase the number of captured packets */
731 p->stat.ps_recv++;
732
733 /* Find the beginning of the packet */
734 dp = ((u_char *)header) + dag_record_size;
735
736 /* Determine actual packet len */
737 switch(header->type)
738 {
739 case TYPE_ATM:
740 packet_len = ATM_SNAPLEN;
741 caplen = ATM_SNAPLEN;
742 dp += 4;
743
744 break;
745
746 case TYPE_ETH:
747 swt = SWAPS(header->wlen);
748 packet_len = swt - (pw->dag_fcs_bits);
749 caplen = erf_record_len - dag_record_size - 2;
750 if (caplen > packet_len)
751 {
752 caplen = packet_len;
753 }
754 dp += 2;
755
756 break;
757
758 case TYPE_HDLC_POS:
759 swt = SWAPS(header->wlen);
760 packet_len = swt - (pw->dag_fcs_bits);
761 caplen = erf_record_len - dag_record_size;
762 if (caplen > packet_len)
763 {
764 caplen = packet_len;
765 }
766
767 break;
768 }
769
770 if(caplen > p->snapshot)
771 caplen = p->snapshot;
772
773 /*
774 * Has "pcap_breakloop()" been called?
775 * If so, return immediately - if we haven't read any
776 * packets, clear the flag and return -2 to indicate
777 * that we were told to break out of the loop, otherwise
778 * leave the flag set, so that the *next* call will break
779 * out of the loop without having read any packets, and
780 * return the number of packets we've processed so far.
781 */
782 if (p->break_loop)
783 {
784 if (n == 0)
785 {
786 p->break_loop = 0;
787 return (-2);
788 }
789 else
790 {
791 p->bp = (char*)header;
792 p->cc = endofbuf - (char*)header;
793 return (n);
794 }
795 }
796
797 if(!dfp)
798 {
799 /* convert between timestamp formats */
800 ts = header->ts;
801 pcap_header.ts.tv_sec = (int)(ts >> 32);
802 ts = (ts & 0xffffffffi64) * 1000000;
803 ts += 0x80000000; /* rounding */
804 pcap_header.ts.tv_usec = (int)(ts >> 32);
805 if (pcap_header.ts.tv_usec >= 1000000) {
806 pcap_header.ts.tv_usec -= 1000000;
807 pcap_header.ts.tv_sec++;
808 }
809 }
810
811 /* No underlaying filtering system. We need to filter on our own */
812 if (p->fcode.bf_insns)
813 {
814 if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
815 {
816 /* Move to next packet */
817 header = (dag_record_t*)((char*)header + erf_record_len);
818 continue;
819 }
820 }
821
822 /* Fill the header for the user suppplied callback function */
823 pcap_header.caplen = caplen;
824 pcap_header.len = packet_len;
825
826 /* Call the callback function */
827 (*callback)(user, &pcap_header, dp);
828
829 /* Move to next packet */
830 header = (dag_record_t*)((char*)header + erf_record_len);
831
832 /* Stop if the number of packets requested by user has been reached*/
833 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
834 {
835 p->bp = (char*)header;
836 p->cc = endofbuf - (char*)header;
837 return (n);
838 }
839 }
840 while((u_char*)header < endofbuf);
841
842 return (1);
843 }
844 #endif /* HAVE_DAG_API */
845
846 /* Send a packet to the network */
847 static int
848 pcap_inject_win32(pcap_t *p, const void *buf, size_t size)
849 {
850 struct pcap_win *pw = p->priv;
851 PACKET pkt;
852
853 PacketInitPacket(&pkt, (PVOID)buf, size);
854 if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
855 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
856 return (-1);
857 }
858
859 /*
860 * We assume it all got sent if "PacketSendPacket()" succeeded.
861 * "pcap_inject()" is expected to return the number of bytes
862 * sent.
863 */
864 return ((int)size);
865 }
866
867 static void
868 pcap_cleanup_win32(pcap_t *p)
869 {
870 struct pcap_win *pw = p->priv;
871
872 if (pw->adapter != NULL) {
873 PacketCloseAdapter(pw->adapter);
874 pw->adapter = NULL;
875 }
876 if (pw->rfmon_selfstart)
877 {
878 PacketSetMonitorMode(p->opt.device, 0);
879 }
880 pcap_cleanup_live_common(p);
881 }
882
883 static int
884 pcap_activate_win32(pcap_t *p)
885 {
886 struct pcap_win *pw = p->priv;
887 NetType type;
888 int res;
889 char errbuf[PCAP_ERRBUF_SIZE+1];
890
891 if (p->opt.rfmon) {
892 /*
893 * Monitor mode is supported on Windows Vista and later.
894 */
895 if (PacketGetMonitorMode(p->opt.device) == 1)
896 {
897 pw->rfmon_selfstart = 0;
898 }
899 else
900 {
901 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
902 {
903 pw->rfmon_selfstart = 0;
904 // Monitor mode is not supported.
905 if (res == 0)
906 {
907 return PCAP_ERROR_RFMON_NOTSUP;
908 }
909 else
910 {
911 return PCAP_ERROR;
912 }
913 }
914 else
915 {
916 pw->rfmon_selfstart = 1;
917 }
918 }
919 }
920
921 /* Init WinSock */
922 wsockinit();
923
924 pw->adapter = PacketOpenAdapter(p->opt.device);
925
926 if (pw->adapter == NULL)
927 {
928 /* Adapter detected but we are not able to open it. Return failure. */
929 pcap_win32_err_to_str(GetLastError(), errbuf);
930 if (pw->rfmon_selfstart)
931 {
932 PacketSetMonitorMode(p->opt.device, 0);
933 }
934 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
935 "Error opening adapter: %s", errbuf);
936 return (PCAP_ERROR);
937 }
938
939 /*get network type*/
940 if(PacketGetNetType (pw->adapter,&type) == FALSE)
941 {
942 pcap_win32_err_to_str(GetLastError(), errbuf);
943 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
944 "Cannot determine the network type: %s", errbuf);
945 goto bad;
946 }
947
948 /*Set the linktype*/
949 switch (type.LinkType)
950 {
951 case NdisMediumWan:
952 p->linktype = DLT_EN10MB;
953 break;
954
955 case NdisMedium802_3:
956 p->linktype = DLT_EN10MB;
957 /*
958 * This is (presumably) a real Ethernet capture; give it a
959 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
960 * that an application can let you choose it, in case you're
961 * capturing DOCSIS traffic that a Cisco Cable Modem
962 * Termination System is putting out onto an Ethernet (it
963 * doesn't put an Ethernet header onto the wire, it puts raw
964 * DOCSIS frames out on the wire inside the low-level
965 * Ethernet framing).
966 */
967 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
968 /*
969 * If that fails, just leave the list empty.
970 */
971 if (p->dlt_list != NULL) {
972 p->dlt_list[0] = DLT_EN10MB;
973 p->dlt_list[1] = DLT_DOCSIS;
974 p->dlt_count = 2;
975 }
976 break;
977
978 case NdisMediumFddi:
979 p->linktype = DLT_FDDI;
980 break;
981
982 case NdisMedium802_5:
983 p->linktype = DLT_IEEE802;
984 break;
985
986 case NdisMediumArcnetRaw:
987 p->linktype = DLT_ARCNET;
988 break;
989
990 case NdisMediumArcnet878_2:
991 p->linktype = DLT_ARCNET;
992 break;
993
994 case NdisMediumAtm:
995 p->linktype = DLT_ATM_RFC1483;
996 break;
997
998 case NdisMediumCHDLC:
999 p->linktype = DLT_CHDLC;
1000 break;
1001
1002 case NdisMediumPPPSerial:
1003 p->linktype = DLT_PPP_SERIAL;
1004 break;
1005
1006 case NdisMediumNull:
1007 p->linktype = DLT_NULL;
1008 break;
1009
1010 case NdisMediumBare80211:
1011 p->linktype = DLT_IEEE802_11;
1012 break;
1013
1014 case NdisMediumRadio80211:
1015 p->linktype = DLT_IEEE802_11_RADIO;
1016 break;
1017
1018 case NdisMediumPpi:
1019 p->linktype = DLT_PPI;
1020 break;
1021
1022 default:
1023 p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/
1024 break;
1025 }
1026
1027 /*
1028 * Turn a negative snapshot value (invalid), a snapshot value of
1029 * 0 (unspecified), or a value bigger than the normal maximum
1030 * value, into the maximum allowed value.
1031 *
1032 * If some application really *needs* a bigger snapshot
1033 * length, we should just increase MAXIMUM_SNAPLEN.
1034 */
1035 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1036 p->snapshot = MAXIMUM_SNAPLEN;
1037
1038 /* Set promiscuous mode */
1039 if (p->opt.promisc)
1040 {
1041
1042 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1043 {
1044 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
1045 goto bad;
1046 }
1047 }
1048 else
1049 {
1050 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_ALL_LOCAL) == FALSE)
1051 {
1052 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
1053 goto bad;
1054 }
1055 }
1056
1057 /* Set the buffer size */
1058 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1059
1060 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1061 {
1062 /*
1063 * Traditional Adapter
1064 */
1065 /*
1066 * If the buffer size wasn't explicitly set, default to
1067 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1068 */
1069 if (p->opt.buffer_size == 0)
1070 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1071
1072 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1073 {
1074 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1075 goto bad;
1076 }
1077
1078 p->buffer = malloc(p->bufsize);
1079 if (p->buffer == NULL)
1080 {
1081 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "malloc: %s", pcap_strerror(errno));
1082 goto bad;
1083 }
1084
1085 if (p->opt.immediate)
1086 {
1087 /* tell the driver to copy the buffer as soon as data arrives */
1088 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1089 {
1090 pcap_win32_err_to_str(GetLastError(), errbuf);
1091 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1092 "Error calling PacketSetMinToCopy: %s",
1093 errbuf);
1094 goto bad;
1095 }
1096 }
1097 else
1098 {
1099 /* tell the driver to copy the buffer only if it contains at least 16K */
1100 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1101 {
1102 pcap_win32_err_to_str(GetLastError(), errbuf);
1103 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1104 "Error calling PacketSetMinToCopy: %s",
1105 errbuf);
1106 goto bad;
1107 }
1108 }
1109 } else {
1110 /*
1111 * Dag Card
1112 */
1113 #ifdef HAVE_DAG_API
1114 /*
1115 * We have DAG support.
1116 */
1117 LONG status;
1118 HKEY dagkey;
1119 DWORD lptype;
1120 DWORD lpcbdata;
1121 int postype = 0;
1122 char keyname[512];
1123
1124 pcap_snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1125 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1126 strstr(_strlwr(p->opt.device), "dag"));
1127 do
1128 {
1129 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1130 if(status != ERROR_SUCCESS)
1131 break;
1132
1133 status = RegQueryValueEx(dagkey,
1134 "PosType",
1135 NULL,
1136 &lptype,
1137 (char*)&postype,
1138 &lpcbdata);
1139
1140 if(status != ERROR_SUCCESS)
1141 {
1142 postype = 0;
1143 }
1144
1145 RegCloseKey(dagkey);
1146 }
1147 while(FALSE);
1148
1149
1150 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1151
1152 /* Set the length of the FCS associated to any packet. This value
1153 * will be subtracted to the packet length */
1154 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1155 #else /* HAVE_DAG_API */
1156 /*
1157 * No DAG support.
1158 */
1159 goto bad;
1160 #endif /* HAVE_DAG_API */
1161 }
1162
1163 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1164
1165 /* disable loopback capture if requested */
1166 if (p->opt.nocapture_local)
1167 {
1168 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1169 {
1170 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1171 "Unable to disable the capture of loopback packets.");
1172 goto bad;
1173 }
1174 }
1175
1176 #ifdef HAVE_DAG_API
1177 if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1178 {
1179 /* install dag specific handlers for read and setfilter */
1180 p->read_op = pcap_read_win32_dag;
1181 p->setfilter_op = pcap_setfilter_win32_dag;
1182 }
1183 else
1184 {
1185 #endif /* HAVE_DAG_API */
1186 /* install traditional npf handlers for read and setfilter */
1187 p->read_op = pcap_read_win32_npf;
1188 p->setfilter_op = pcap_setfilter_win32_npf;
1189 #ifdef HAVE_DAG_API
1190 }
1191 #endif /* HAVE_DAG_API */
1192 p->setdirection_op = NULL; /* Not implemented. */
1193 /* XXX - can this be implemented on some versions of Windows? */
1194 p->inject_op = pcap_inject_win32;
1195 p->set_datalink_op = NULL; /* can't change data link type */
1196 p->getnonblock_op = pcap_getnonblock_win32;
1197 p->setnonblock_op = pcap_setnonblock_win32;
1198 p->stats_op = pcap_stats_win32;
1199 p->stats_ex_op = pcap_stats_ex_win32;
1200 p->setbuff_op = pcap_setbuff_win32;
1201 p->setmode_op = pcap_setmode_win32;
1202 p->setmintocopy_op = pcap_setmintocopy_win32;
1203 p->getevent_op = pcap_getevent_win32;
1204 p->oid_get_request_op = pcap_oid_get_request_win32;
1205 p->oid_set_request_op = pcap_oid_set_request_win32;
1206 p->sendqueue_transmit_op = pcap_sendqueue_transmit_win32;
1207 p->setuserbuffer_op = pcap_setuserbuffer_win32;
1208 p->live_dump_op = pcap_live_dump_win32;
1209 p->live_dump_ended_op = pcap_live_dump_ended_win32;
1210 p->get_airpcap_handle_op = pcap_get_airpcap_handle_win32;
1211 p->cleanup_op = pcap_cleanup_win32;
1212
1213 /*
1214 * XXX - this is only done because WinPcap supported
1215 * pcap_fileno() returning the hFile HANDLE from the
1216 * ADAPTER structure. We make no general guarantees
1217 * that the caller can do anything useful with it.
1218 *
1219 * (Not that we make any general guarantee of that
1220 * sort on UN*X, either, any more, given that not
1221 * all capture devices are regular OS network
1222 * interfaces.)
1223 */
1224 p->handle = pw->adapter->hFile;
1225
1226 return (0);
1227 bad:
1228 pcap_cleanup_win32(p);
1229 return (PCAP_ERROR);
1230 }
1231
1232 /*
1233 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1234 */
1235 static int
1236 pcap_can_set_rfmon_win32(pcap_t *p)
1237 {
1238 return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1239 }
1240
1241 pcap_t *
1242 pcap_create_interface(const char *device _U_, char *ebuf)
1243 {
1244 pcap_t *p;
1245
1246 p = pcap_create_common(ebuf, sizeof(struct pcap_win));
1247 if (p == NULL)
1248 return (NULL);
1249
1250 p->activate_op = pcap_activate_win32;
1251 p->can_set_rfmon_op = pcap_can_set_rfmon_win32;
1252 return (p);
1253 }
1254
1255 static int
1256 pcap_setfilter_win32_npf(pcap_t *p, struct bpf_program *fp)
1257 {
1258 struct pcap_win *pw = p->priv;
1259
1260 if(PacketSetBpf(pw->adapter,fp)==FALSE){
1261 /*
1262 * Kernel filter not installed.
1263 *
1264 * XXX - we don't know whether this failed because:
1265 *
1266 * the kernel rejected the filter program as invalid,
1267 * in which case we should fall back on userland
1268 * filtering;
1269 *
1270 * the kernel rejected the filter program as too big,
1271 * in which case we should again fall back on
1272 * userland filtering;
1273 *
1274 * there was some other problem, in which case we
1275 * should probably report an error.
1276 *
1277 * For NPF devices, the Win32 status will be
1278 * STATUS_INVALID_DEVICE_REQUEST for invalid
1279 * filters, but I don't know what it'd be for
1280 * other problems, and for some other devices
1281 * it might not be set at all.
1282 *
1283 * So we just fall back on userland filtering in
1284 * all cases.
1285 */
1286
1287 /*
1288 * install_bpf_program() validates the program.
1289 *
1290 * XXX - what if we already have a filter in the kernel?
1291 */
1292 if (install_bpf_program(p, fp) < 0)
1293 return (-1);
1294 pw->filtering_in_kernel = 0; /* filtering in userland */
1295 return (0);
1296 }
1297
1298 /*
1299 * It worked.
1300 */
1301 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1302
1303 /*
1304 * Discard any previously-received packets, as they might have
1305 * passed whatever filter was formerly in effect, but might
1306 * not pass this filter (BIOCSETF discards packets buffered
1307 * in the kernel, so you can lose packets in any case).
1308 */
1309 p->cc = 0;
1310 return (0);
1311 }
1312
1313 /*
1314 * We filter at user level, since the kernel driver does't process the packets
1315 */
1316 static int
1317 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1318
1319 if(!fp)
1320 {
1321 strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1322 return (-1);
1323 }
1324
1325 /* Install a user level filter */
1326 if (install_bpf_program(p, fp) < 0)
1327 {
1328 pcap_snprintf(p->errbuf, sizeof(p->errbuf),
1329 "setfilter, unable to install the filter: %s", pcap_strerror(errno));
1330 return (-1);
1331 }
1332
1333 return (0);
1334 }
1335
1336 static int
1337 pcap_getnonblock_win32(pcap_t *p)
1338 {
1339 struct pcap_win *pw = p->priv;
1340
1341 /*
1342 * XXX - if there were a PacketGetReadTimeout() call, we
1343 * would use it, and return 1 if the timeout is -1
1344 * and 0 otherwise.
1345 */
1346 return (pw->nonblock);
1347 }
1348
1349 static int
1350 pcap_setnonblock_win32(pcap_t *p, int nonblock)
1351 {
1352 struct pcap_win *pw = p->priv;
1353 int newtimeout;
1354 char win_errbuf[PCAP_ERRBUF_SIZE+1];
1355
1356 if (nonblock) {
1357 /*
1358 * Set the packet buffer timeout to -1 for non-blocking
1359 * mode.
1360 */
1361 newtimeout = -1;
1362 } else {
1363 /*
1364 * Restore the timeout set when the device was opened.
1365 * (Note that this may be -1, in which case we're not
1366 * really leaving non-blocking mode. However, although
1367 * the timeout argument to pcap_set_timeout() and
1368 * pcap_open_live() is an int, you're not supposed to
1369 * supply a negative value, so that "shouldn't happen".)
1370 */
1371 newtimeout = p->opt.timeout;
1372 }
1373 if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1374 pcap_win32_err_to_str(GetLastError(), win_errbuf);
1375 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1376 "PacketSetReadTimeout: %s", win_errbuf);
1377 return (-1);
1378 }
1379 pw->nonblock = (newtimeout == -1);
1380 return (0);
1381 }
1382
1383 static int
1384 pcap_add_if_win32(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
1385 const char *description, char *errbuf)
1386 {
1387 pcap_if_t *curdev;
1388 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1389 LONG if_addr_size;
1390 int res = 0;
1391
1392 if_addr_size = MAX_NETWORK_ADDRESSES;
1393
1394 /*
1395 * Add an entry for this interface, with no addresses.
1396 */
1397 curdev = add_dev(devlistp, name, flags, description, errbuf);
1398 if (curdev == NULL) {
1399 /*
1400 * Failure.
1401 */
1402 return (-1);
1403 }
1404
1405 /*
1406 * Get the list of addresses for the interface.
1407 */
1408 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1409 /*
1410 * Failure.
1411 *
1412 * We don't return an error, because this can happen with
1413 * NdisWan interfaces, and we want to supply them even
1414 * if we can't supply their addresses.
1415 *
1416 * We return an entry with an empty address list.
1417 */
1418 return (0);
1419 }
1420
1421 /*
1422 * Now add the addresses.
1423 */
1424 while (if_addr_size-- > 0) {
1425 /*
1426 * "curdev" is an entry for this interface; add an entry for
1427 * this address to its list of addresses.
1428 */
1429 res = add_addr_to_dev(curdev,
1430 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1431 sizeof (struct sockaddr_storage),
1432 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1433 sizeof (struct sockaddr_storage),
1434 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1435 sizeof (struct sockaddr_storage),
1436 NULL,
1437 0,
1438 errbuf);
1439 if (res == -1) {
1440 /*
1441 * Failure.
1442 */
1443 break;
1444 }
1445 }
1446
1447 return (res);
1448 }
1449
1450 int
1451 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
1452 {
1453 int ret = 0;
1454 const char *desc;
1455 char *AdaptersName;
1456 ULONG NameLength;
1457 char *name;
1458 char our_errbuf[PCAP_ERRBUF_SIZE+1];
1459
1460 /*
1461 * Find out how big a buffer we need.
1462 *
1463 * This call should always return FALSE; if the error is
1464 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1465 * the size of the buffer we need, otherwise there's a
1466 * problem, and NameLength should be set to 0.
1467 *
1468 * It shouldn't require NameLength to be set, but,
1469 * at least as of WinPcap 4.1.3, it checks whether
1470 * NameLength is big enough before it checks for a
1471 * NULL buffer argument, so, while it'll still do
1472 * the right thing if NameLength is uninitialized and
1473 * whatever junk happens to be there is big enough
1474 * (because the pointer argument will be null), it's
1475 * still reading an uninitialized variable.
1476 */
1477 NameLength = 0;
1478 if (!PacketGetAdapterNames(NULL, &NameLength))
1479 {
1480 DWORD last_error = GetLastError();
1481
1482 if (last_error != ERROR_INSUFFICIENT_BUFFER)
1483 {
1484 pcap_win32_err_to_str(last_error, our_errbuf);
1485 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1486 "PacketGetAdapterNames: %s", our_errbuf);
1487 return (-1);
1488 }
1489 }
1490
1491 if (NameLength <= 0)
1492 return 0;
1493 AdaptersName = (char*) malloc(NameLength);
1494 if (AdaptersName == NULL)
1495 {
1496 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
1497 return (-1);
1498 }
1499
1500 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
1501 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1502 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "PacketGetAdapterNames: %s",
1503 our_errbuf);
1504 free(AdaptersName);
1505 return (-1);
1506 }
1507
1508 /*
1509 * "PacketGetAdapterNames()" returned a list of
1510 * null-terminated ASCII interface name strings,
1511 * terminated by a null string, followed by a list
1512 * of null-terminated ASCII interface description
1513 * strings, terminated by a null string.
1514 * This means there are two ASCII nulls at the end
1515 * of the first list.
1516 *
1517 * Find the end of the first list; that's the
1518 * beginning of the second list.
1519 */
1520 desc = &AdaptersName[0];
1521 while (*desc != '\0' || *(desc + 1) != '\0')
1522 desc++;
1523
1524 /*
1525 * Found it - "desc" points to the first of the two
1526 * nulls at the end of the list of names, so the
1527 * first byte of the list of descriptions is two bytes
1528 * after it.
1529 */
1530 desc += 2;
1531
1532 /*
1533 * Loop over the elements in the first list.
1534 */
1535 name = &AdaptersName[0];
1536 while (*name != '\0') {
1537 bpf_u_int32 flags = 0;
1538 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1539 /*
1540 * Is this a loopback interface?
1541 */
1542 if (PacketIsLoopbackAdapter(name)) {
1543 /* Yes */
1544 flags |= PCAP_IF_LOOPBACK;
1545 }
1546 #endif
1547
1548 /*
1549 * Add an entry for this interface.
1550 */
1551 if (pcap_add_if_win32(devlistp, name, flags, desc,
1552 errbuf) == -1) {
1553 /*
1554 * Failure.
1555 */
1556 ret = -1;
1557 break;
1558 }
1559 name += strlen(name) + 1;
1560 desc += strlen(desc) + 1;
1561 }
1562
1563 free(AdaptersName);
1564 return (ret);
1565 }
1566
1567 /*
1568 * Return the name of a network interface attached to the system, or NULL
1569 * if none can be found. The interface must be configured up; the
1570 * lowest unit number is preferred; loopback is ignored.
1571 *
1572 * In the best of all possible worlds, this would be the same as on
1573 * UN*X, but there may be software that expects this to return a
1574 * full list of devices after the first device.
1575 */
1576 #define ADAPTERSNAME_LEN 8192
1577 char *
1578 pcap_lookupdev(errbuf)
1579 register char *errbuf;
1580 {
1581 DWORD dwVersion;
1582 DWORD dwWindowsMajorVersion;
1583 char our_errbuf[PCAP_ERRBUF_SIZE+1];
1584
1585 #pragma warning (push)
1586 #pragma warning (disable: 4996) /* disable MSVC's GetVersion() deprecated warning here */
1587 dwVersion = GetVersion(); /* get the OS version */
1588 #pragma warning (pop)
1589 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
1590
1591 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
1592 /*
1593 * Windows 95, 98, ME.
1594 */
1595 ULONG NameLength = ADAPTERSNAME_LEN;
1596 static char AdaptersName[ADAPTERSNAME_LEN];
1597
1598 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
1599 return (AdaptersName);
1600 else
1601 return NULL;
1602 } else {
1603 /*
1604 * Windows NT (NT 4.0 and later).
1605 * Convert the names to Unicode for backward compatibility.
1606 */
1607 ULONG NameLength = ADAPTERSNAME_LEN;
1608 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
1609 size_t BufferSpaceLeft;
1610 char *tAstr;
1611 WCHAR *Unameptr;
1612 char *Adescptr;
1613 size_t namelen, i;
1614 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
1615 int NAdapts = 0;
1616
1617 if(TAdaptersName == NULL)
1618 {
1619 (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
1620 return NULL;
1621 }
1622
1623 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
1624 {
1625 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1626 (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1627 "PacketGetAdapterNames: %s", our_errbuf);
1628 free(TAdaptersName);
1629 return NULL;
1630 }
1631
1632
1633 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
1634 tAstr = (char*)TAdaptersName;
1635 Unameptr = AdaptersName;
1636
1637 /*
1638 * Convert the device names to Unicode into AdapterName.
1639 */
1640 do {
1641 /*
1642 * Length of the name, including the terminating
1643 * NUL.
1644 */
1645 namelen = strlen(tAstr) + 1;
1646
1647 /*
1648 * Do we have room for the name in the Unicode
1649 * buffer?
1650 */
1651 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
1652 /*
1653 * No.
1654 */
1655 goto quit;
1656 }
1657 BufferSpaceLeft -= namelen * sizeof(WCHAR);
1658
1659 /*
1660 * Copy the name, converting ASCII to Unicode.
1661 * namelen includes the NUL, so we copy it as
1662 * well.
1663 */
1664 for (i = 0; i < namelen; i++)
1665 *Unameptr++ = *tAstr++;
1666
1667 /*
1668 * Count this adapter.
1669 */
1670 NAdapts++;
1671 } while (namelen != 1);
1672
1673 /*
1674 * Copy the descriptions, but don't convert them from
1675 * ASCII to Unicode.
1676 */
1677 Adescptr = (char *)Unameptr;
1678 while(NAdapts--)
1679 {
1680 size_t desclen;
1681
1682 desclen = strlen(tAstr) + 1;
1683
1684 /*
1685 * Do we have room for the name in the Unicode
1686 * buffer?
1687 */
1688 if (BufferSpaceLeft < desclen) {
1689 /*
1690 * No.
1691 */
1692 goto quit;
1693 }
1694
1695 /*
1696 * Just copy the ASCII string.
1697 * namelen includes the NUL, so we copy it as
1698 * well.
1699 */
1700 memcpy(Adescptr, tAstr, desclen);
1701 Adescptr += desclen;
1702 tAstr += desclen;
1703 BufferSpaceLeft -= desclen;
1704 }
1705
1706 quit:
1707 free(TAdaptersName);
1708 return (char *)(AdaptersName);
1709 }
1710 }
1711
1712 /*
1713 * We can't use the same code that we use on UN*X, as that's doing
1714 * UN*X-specific calls.
1715 *
1716 * We don't just fetch the entire list of devices, search for the
1717 * particular device, and use its first IPv4 address, as that's too
1718 * much work to get just one device's netmask.
1719 */
1720 int
1721 pcap_lookupnet(device, netp, maskp, errbuf)
1722 register const char *device;
1723 register bpf_u_int32 *netp, *maskp;
1724 register char *errbuf;
1725 {
1726 /*
1727 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
1728 * in order to skip non IPv4 (i.e. IPv6 addresses)
1729 */
1730 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1731 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
1732 struct sockaddr_in *t_addr;
1733 LONG i;
1734
1735 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
1736 *netp = *maskp = 0;
1737 return (0);
1738 }
1739
1740 for(i = 0; i < if_addr_size; i++)
1741 {
1742 if(if_addrs[i].IPAddress.ss_family == AF_INET)
1743 {
1744 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
1745 *netp = t_addr->sin_addr.S_un.S_addr;
1746 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
1747 *maskp = t_addr->sin_addr.S_un.S_addr;
1748
1749 *netp &= *maskp;
1750 return (0);
1751 }
1752
1753 }
1754
1755 *netp = *maskp = 0;
1756 return (0);
1757 }
1758
1759 #include "pcap_version.h"
1760
1761 static const char *pcap_lib_version_string;
1762
1763 #ifdef HAVE_VERSION_H
1764 /*
1765 * libpcap being built for Windows, as part of a WinPcap/Npcap source
1766 * tree. Include version.h from that source tree to get the WinPcap/Npcap
1767 * version.
1768 *
1769 * XXX - it'd be nice if we could somehow generate the WinPcap version number
1770 * when building WinPcap. (It'd be nice to do so for the packet.dll version
1771 * number as well.)
1772 */
1773 #include "../../version.h"
1774
1775 static const char wpcap_version_string[] = WINPCAP_VER_STRING;
1776 static const char pcap_version_string_fmt[] =
1777 WINPCAP_PRODUCT_NAME " version %s, based on %s";
1778 static const char pcap_version_string_packet_dll_fmt[] =
1779 WINPCAP_PRODUCT_NAME " version %s (packet.dll version %s), based on %s";
1780
1781 const char *
1782 pcap_lib_version(void)
1783 {
1784 char *packet_version_string;
1785 size_t full_pcap_version_string_len;
1786 char *full_pcap_version_string;
1787
1788 if (pcap_lib_version_string == NULL) {
1789 /*
1790 * Generate the version string.
1791 */
1792 packet_version_string = PacketGetVersion();
1793 if (strcmp(wpcap_version_string, packet_version_string) == 0) {
1794 /*
1795 * WinPcap version string and packet.dll version
1796 * string are the same; just report the WinPcap
1797 * version.
1798 */
1799 full_pcap_version_string_len =
1800 (sizeof pcap_version_string_fmt - 4) +
1801 strlen(wpcap_version_string) +
1802 strlen(pcap_version_string);
1803 full_pcap_version_string =
1804 malloc(full_pcap_version_string_len);
1805 if (full_pcap_version_string == NULL)
1806 return (NULL);
1807 pcap_snprintf(full_pcap_version_string,
1808 full_pcap_version_string_len,
1809 pcap_version_string_fmt,
1810 wpcap_version_string,
1811 pcap_version_string);
1812 } else {
1813 /*
1814 * WinPcap version string and packet.dll version
1815 * string are different; that shouldn't be the
1816 * case (the two libraries should come from the
1817 * same version of WinPcap), so we report both
1818 * versions.
1819 */
1820 full_pcap_version_string_len =
1821 (sizeof pcap_version_string_packet_dll_fmt - 6) +
1822 strlen(wpcap_version_string) +
1823 strlen(packet_version_string) +
1824 strlen(pcap_version_string);
1825 full_pcap_version_string = malloc(full_pcap_version_string_len);
1826 if (full_pcap_version_string == NULL)
1827 return (NULL);
1828 pcap_snprintf(full_pcap_version_string,
1829 full_pcap_version_string_len,
1830 pcap_version_string_packet_dll_fmt,
1831 wpcap_version_string,
1832 packet_version_string,
1833 pcap_version_string);
1834 }
1835 pcap_lib_version_string = full_pcap_version_string;
1836 }
1837 return (pcap_lib_version_string);
1838 }
1839
1840 #else /* HAVE_VERSION_H */
1841
1842 /*
1843 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
1844 * tree.
1845 */
1846 static const char pcap_version_string_packet_dll_fmt[] =
1847 "%s (packet.dll version %s)";
1848 const char *
1849 pcap_lib_version(void)
1850 {
1851 char *packet_version_string;
1852 size_t full_pcap_version_string_len;
1853 char *full_pcap_version_string;
1854
1855 if (pcap_lib_version_string == NULL) {
1856 /*
1857 * Generate the version string. Report the packet.dll
1858 * version.
1859 */
1860 packet_version_string = PacketGetVersion();
1861 full_pcap_version_string_len =
1862 (sizeof pcap_version_string_packet_dll_fmt - 4) +
1863 strlen(pcap_version_string) +
1864 strlen(packet_version_string);
1865 full_pcap_version_string = malloc(full_pcap_version_string_len);
1866 if (full_pcap_version_string == NULL)
1867 return (NULL);
1868 pcap_snprintf(full_pcap_version_string,
1869 full_pcap_version_string_len,
1870 pcap_version_string_packet_dll_fmt,
1871 pcap_version_string,
1872 packet_version_string);
1873 pcap_lib_version_string = full_pcap_version_string;
1874 }
1875 return (pcap_lib_version_string);
1876 }
1877 #endif /* HAVE_VERSION_H */