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