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