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