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