]> The Tcpdump Group git mirrors - libpcap/blob - pcap-npf.c
DWORD is unsigned; print it as such.
[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 /*
45 * XXX - Packet32.h defines bpf_program, so we can't include
46 * <pcap/bpf.h>, which also defines it; that's why we define
47 * PCAP_DONT_INCLUDE_PCAP_BPF_H,
48 *
49 * However, no header in the WinPcap or Npcap SDKs defines the
50 * macros for BPF code, so we have to define them ourselves.
51 */
52 #define BPF_RET 0x06
53 #define BPF_K 0x00
54
55 /* Old-school MinGW have these headers in a different place.
56 */
57 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
58 #include <ddk/ntddndis.h>
59 #include <ddk/ndis.h>
60 #else
61 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
62 #endif
63
64 #ifdef HAVE_DAG_API
65 #include <dagnew.h>
66 #include <dagapi.h>
67 #endif /* HAVE_DAG_API */
68
69 #include "diag-control.h"
70
71 #include "pcap-airpcap.h"
72
73 static int pcap_setfilter_npf(pcap_t *, struct bpf_program *);
74 static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
75 static int pcap_getnonblock_npf(pcap_t *);
76 static int pcap_setnonblock_npf(pcap_t *, int);
77
78 /*dimension of the buffer in the pcap_t structure*/
79 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
80
81 /*dimension of the buffer in the kernel driver NPF */
82 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
83
84 /* Equivalent to ntohs(), but a lot faster under Windows */
85 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
86
87 /*
88 * Private data for capturing on WinPcap/Npcap devices.
89 */
90 struct pcap_win {
91 ADAPTER *adapter; /* the packet32 ADAPTER for the device */
92 int nonblock;
93 int rfmon_selfstart; /* a flag tells whether the monitor mode is set by itself */
94 int filtering_in_kernel; /* using kernel filter */
95
96 #ifdef HAVE_DAG_API
97 int dag_fcs_bits; /* Number of checksum bits from link layer */
98 #endif
99
100 #ifdef ENABLE_REMOTE
101 int samp_npkt; /* parameter needed for sampling, with '1 out of N' method has been requested */
102 struct timeval samp_time; /* parameter needed for sampling, with '1 every N ms' method has been requested */
103 #endif
104 };
105
106 /*
107 * Define stub versions of the monitor-mode support routines if this
108 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
109 * WinPcap.
110 */
111 #ifndef HAVE_NPCAP_PACKET_API
112 static int
113 PacketIsMonitorModeSupported(PCHAR AdapterName _U_)
114 {
115 /*
116 * We don't support monitor mode.
117 */
118 return (0);
119 }
120
121 static int
122 PacketSetMonitorMode(PCHAR AdapterName _U_, int mode _U_)
123 {
124 /*
125 * This should never be called, as PacketIsMonitorModeSupported()
126 * will return 0, meaning "we don't support monitor mode, so
127 * don't try to turn it on or off".
128 */
129 return (0);
130 }
131
132 static int
133 PacketGetMonitorMode(PCHAR AdapterName _U_)
134 {
135 /*
136 * This should fail, so that pcap_activate_npf() returns
137 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
138 * mode.
139 */
140 return (-1);
141 }
142 #endif
143
144 /*
145 * Sigh. PacketRequest() will have made a DeviceIoControl()
146 * call to the NPF driver to perform the OID request, with a
147 * BIOCQUERYOID ioctl. The kernel code should get back one
148 * of NDIS_STATUS_INVALID_OID, NDIS_STATUS_NOT_SUPPORTED,
149 * or NDIS_STATUS_NOT_RECOGNIZED if the OID request isn't
150 * supported by the OS or the driver, but that doesn't seem
151 * to make it to the caller of PacketRequest() in a
152 * reliable fashion.
153 */
154 #define NDIS_STATUS_INVALID_OID 0xc0010017
155 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
156 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
157
158 static int
159 oid_get_request(ADAPTER *adapter, bpf_u_int32 oid, void *data, size_t *lenp,
160 char *errbuf)
161 {
162 PACKET_OID_DATA *oid_data_arg;
163
164 /*
165 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
166 * It should be big enough to hold "*lenp" bytes of data; it
167 * will actually be slightly larger, as PACKET_OID_DATA has a
168 * 1-byte data array at the end, standing in for the variable-length
169 * data that's actually there.
170 */
171 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
172 if (oid_data_arg == NULL) {
173 snprintf(errbuf, PCAP_ERRBUF_SIZE,
174 "Couldn't allocate argument buffer for PacketRequest");
175 return (PCAP_ERROR);
176 }
177
178 /*
179 * No need to copy the data - we're doing a fetch.
180 */
181 oid_data_arg->Oid = oid;
182 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
183 if (!PacketRequest(adapter, FALSE, oid_data_arg)) {
184 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
185 GetLastError(), "Error calling PacketRequest");
186 free(oid_data_arg);
187 return (-1);
188 }
189
190 /*
191 * Get the length actually supplied.
192 */
193 *lenp = oid_data_arg->Length;
194
195 /*
196 * Copy back the data we fetched.
197 */
198 memcpy(data, oid_data_arg->Data, *lenp);
199 free(oid_data_arg);
200 return (0);
201 }
202
203 static int
204 pcap_stats_npf(pcap_t *p, struct pcap_stat *ps)
205 {
206 struct pcap_win *pw = p->priv;
207 struct bpf_stat bstats;
208
209 /*
210 * Try to get statistics.
211 *
212 * (Please note - "struct pcap_stat" is *not* the same as
213 * WinPcap's "struct bpf_stat". It might currently have the
214 * same layout, but let's not cheat.
215 *
216 * Note also that we don't fill in ps_capt, as we might have
217 * been called by code compiled against an earlier version of
218 * WinPcap that didn't have ps_capt, in which case filling it
219 * in would stomp on whatever comes after the structure passed
220 * to us.
221 */
222 if (!PacketGetStats(pw->adapter, &bstats)) {
223 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
224 GetLastError(), "PacketGetStats error");
225 return (-1);
226 }
227 ps->ps_recv = bstats.bs_recv;
228 ps->ps_drop = bstats.bs_drop;
229
230 /*
231 * XXX - PacketGetStats() doesn't fill this in, so we just
232 * return 0.
233 */
234 #if 0
235 ps->ps_ifdrop = bstats.ps_ifdrop;
236 #else
237 ps->ps_ifdrop = 0;
238 #endif
239
240 return (0);
241 }
242
243 /*
244 * Win32-only routine for getting statistics.
245 *
246 * This way is definitely safer than passing the pcap_stat * from the userland.
247 * In fact, there could happen than the user allocates a variable which is not
248 * big enough for the new structure, and the library will write in a zone
249 * which is not allocated to this variable.
250 *
251 * In this way, we're pretty sure we are writing on memory allocated to this
252 * variable.
253 *
254 * XXX - but this is the wrong way to handle statistics. Instead, we should
255 * have an API that returns data in a form like the Options section of a
256 * pcapng Interface Statistics Block:
257 *
258 * https://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
259 *
260 * which would let us add new statistics straightforwardly and indicate which
261 * statistics we are and are *not* providing, rather than having to provide
262 * possibly-bogus values for statistics we can't provide.
263 */
264 static struct pcap_stat *
265 pcap_stats_ex_npf(pcap_t *p, int *pcap_stat_size)
266 {
267 struct pcap_win *pw = p->priv;
268 struct bpf_stat bstats;
269
270 *pcap_stat_size = sizeof (p->stat);
271
272 /*
273 * Try to get statistics.
274 *
275 * (Please note - "struct pcap_stat" is *not* the same as
276 * WinPcap's "struct bpf_stat". It might currently have the
277 * same layout, but let's not cheat.)
278 */
279 if (!PacketGetStatsEx(pw->adapter, &bstats)) {
280 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
281 GetLastError(), "PacketGetStatsEx error");
282 return (NULL);
283 }
284 p->stat.ps_recv = bstats.bs_recv;
285 p->stat.ps_drop = bstats.bs_drop;
286 p->stat.ps_ifdrop = bstats.ps_ifdrop;
287 /*
288 * Just in case this is ever compiled for a target other than
289 * Windows, which is somewhere between extremely unlikely and
290 * impossible.
291 */
292 #ifdef _WIN32
293 p->stat.ps_capt = bstats.bs_capt;
294 #endif
295 return (&p->stat);
296 }
297
298 /* Set the dimension of the kernel-level capture buffer */
299 static int
300 pcap_setbuff_npf(pcap_t *p, int dim)
301 {
302 struct pcap_win *pw = p->priv;
303
304 if(PacketSetBuff(pw->adapter,dim)==FALSE)
305 {
306 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
307 return (-1);
308 }
309 return (0);
310 }
311
312 /* Set the driver working mode */
313 static int
314 pcap_setmode_npf(pcap_t *p, int mode)
315 {
316 struct pcap_win *pw = p->priv;
317
318 if(PacketSetMode(pw->adapter,mode)==FALSE)
319 {
320 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
321 return (-1);
322 }
323
324 return (0);
325 }
326
327 /*set the minimum amount of data that will release a read call*/
328 static int
329 pcap_setmintocopy_npf(pcap_t *p, int size)
330 {
331 struct pcap_win *pw = p->priv;
332
333 if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
334 {
335 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
336 return (-1);
337 }
338 return (0);
339 }
340
341 static HANDLE
342 pcap_getevent_npf(pcap_t *p)
343 {
344 struct pcap_win *pw = p->priv;
345
346 return (PacketGetReadEvent(pw->adapter));
347 }
348
349 static int
350 pcap_oid_get_request_npf(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
351 {
352 struct pcap_win *pw = p->priv;
353
354 return (oid_get_request(pw->adapter, oid, data, lenp, p->errbuf));
355 }
356
357 static int
358 pcap_oid_set_request_npf(pcap_t *p, bpf_u_int32 oid, const void *data,
359 size_t *lenp)
360 {
361 struct pcap_win *pw = p->priv;
362 PACKET_OID_DATA *oid_data_arg;
363
364 /*
365 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
366 * It should be big enough to hold "*lenp" bytes of data; it
367 * will actually be slightly larger, as PACKET_OID_DATA has a
368 * 1-byte data array at the end, standing in for the variable-length
369 * data that's actually there.
370 */
371 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
372 if (oid_data_arg == NULL) {
373 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
374 "Couldn't allocate argument buffer for PacketRequest");
375 return (PCAP_ERROR);
376 }
377
378 oid_data_arg->Oid = oid;
379 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
380 memcpy(oid_data_arg->Data, data, *lenp);
381 if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
382 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
383 GetLastError(), "Error calling PacketRequest");
384 free(oid_data_arg);
385 return (PCAP_ERROR);
386 }
387
388 /*
389 * Get the length actually copied.
390 */
391 *lenp = oid_data_arg->Length;
392
393 /*
394 * No need to copy the data - we're doing a set.
395 */
396 free(oid_data_arg);
397 return (0);
398 }
399
400 static u_int
401 pcap_sendqueue_transmit_npf(pcap_t *p, pcap_send_queue *queue, int sync)
402 {
403 struct pcap_win *pw = p->priv;
404 u_int res;
405
406 res = PacketSendPackets(pw->adapter,
407 queue->buffer,
408 queue->len,
409 (BOOLEAN)sync);
410
411 if(res != queue->len){
412 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
413 GetLastError(), "Error queueing packets");
414 }
415
416 return (res);
417 }
418
419 static int
420 pcap_setuserbuffer_npf(pcap_t *p, int size)
421 {
422 unsigned char *new_buff;
423
424 if (size<=0) {
425 /* Bogus parameter */
426 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
427 "Error: invalid size %d",size);
428 return (-1);
429 }
430
431 /* Allocate the buffer */
432 new_buff=(unsigned char*)malloc(sizeof(char)*size);
433
434 if (!new_buff) {
435 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
436 "Error: not enough memory");
437 return (-1);
438 }
439
440 free(p->buffer);
441
442 p->buffer=new_buff;
443 p->bufsize=size;
444
445 return (0);
446 }
447
448 static int
449 pcap_live_dump_npf(pcap_t *p, char *filename, int maxsize, int maxpacks)
450 {
451 struct pcap_win *pw = p->priv;
452 BOOLEAN res;
453
454 /* Set the packet driver in dump mode */
455 res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
456 if(res == FALSE){
457 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
458 "Error setting dump mode");
459 return (-1);
460 }
461
462 /* Set the name of the dump file */
463 res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
464 if(res == FALSE){
465 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
466 "Error setting kernel dump file name");
467 return (-1);
468 }
469
470 /* Set the limits of the dump file */
471 res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
472 if(res == FALSE) {
473 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
474 "Error setting dump limit");
475 return (-1);
476 }
477
478 return (0);
479 }
480
481 static int
482 pcap_live_dump_ended_npf(pcap_t *p, int sync)
483 {
484 struct pcap_win *pw = p->priv;
485
486 return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
487 }
488
489 #ifdef HAVE_AIRPCAP_API
490 static PAirpcapHandle
491 pcap_get_airpcap_handle_npf(pcap_t *p)
492 {
493 struct pcap_win *pw = p->priv;
494
495 return (PacketGetAirPcapHandle(pw->adapter));
496 }
497 #else /* HAVE_AIRPCAP_API */
498 static PAirpcapHandle
499 pcap_get_airpcap_handle_npf(pcap_t *p _U_)
500 {
501 return (NULL);
502 }
503 #endif /* HAVE_AIRPCAP_API */
504
505 static int
506 pcap_read_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
507 {
508 PACKET Packet;
509 int cc;
510 int n;
511 register u_char *bp, *ep;
512 u_char *datap;
513 struct pcap_win *pw = p->priv;
514
515 cc = p->cc;
516 if (cc == 0) {
517 /*
518 * Has "pcap_breakloop()" been called?
519 */
520 if (p->break_loop) {
521 /*
522 * Yes - clear the flag that indicates that it
523 * has, and return PCAP_ERROR_BREAK to indicate
524 * that we were told to break out of the loop.
525 */
526 p->break_loop = 0;
527 return (PCAP_ERROR_BREAK);
528 }
529
530 /*
531 * Capture the packets.
532 *
533 * The PACKET structure had a bunch of extra stuff for
534 * Windows 9x/Me, but the only interesting data in it
535 * in the versions of Windows that we support is just
536 * a copy of p->buffer, a copy of p->buflen, and the
537 * actual number of bytes read returned from
538 * PacketReceivePacket(), none of which has to be
539 * retained from call to call, so we just keep one on
540 * the stack.
541 */
542 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
543 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
544 /*
545 * Did the device go away?
546 * If so, the error we get can either be
547 * ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
548 */
549 DWORD errcode = GetLastError();
550
551 if (errcode == ERROR_GEN_FAILURE ||
552 errcode == ERROR_DEVICE_REMOVED) {
553 /*
554 * The device on which we're capturing
555 * went away, or it became unusable
556 * by NPF due to a suspend/resume.
557 *
558 * ERROR_GEN_FAILURE comes from
559 * STATUS_UNSUCCESSFUL, as well as some
560 * other NT status codes that the Npcap
561 * driver is unlikely to return.
562 * XXX - hopefully no other error
563 * conditions are indicated by this.
564 *
565 * ERROR_DEVICE_REMOVED comes from
566 * STATUS_DEVICE_REMOVED.
567 *
568 * We report the error code for the
569 * benefit of attempts to debug cases
570 * where this error is reported when
571 * the device *wasn't* removed, either
572 * because it's not removable, it's
573 * removable but wasn't removed, or
574 * it's a device that doesn't correspond
575 * to a physical device.
576 *
577 * XXX - we really should return an
578 * appropriate error for that, but
579 * pcap_dispatch() etc. aren't
580 * documented as having error returns
581 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
582 */
583 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
584 "The interface disappeared (error code %u)",
585 errcode);
586 } else {
587 pcap_fmt_errmsg_for_win32_err(p->errbuf,
588 PCAP_ERRBUF_SIZE, errcode,
589 "PacketReceivePacket error");
590 }
591 return (PCAP_ERROR);
592 }
593
594 cc = Packet.ulBytesReceived;
595
596 bp = p->buffer;
597 }
598 else
599 bp = p->bp;
600
601 /*
602 * Loop through each packet.
603 */
604 #define bhp ((struct bpf_hdr *)bp)
605 n = 0;
606 ep = bp + cc;
607 for (;;) {
608 register u_int caplen, hdrlen;
609
610 /*
611 * Has "pcap_breakloop()" been called?
612 * If so, return immediately - if we haven't read any
613 * packets, clear the flag and return PCAP_ERROR_BREAK
614 * to indicate that we were told to break out of the loop,
615 * otherwise leave the flag set, so that the *next* call
616 * will break out of the loop without having read any
617 * packets, and return the number of packets we've
618 * processed so far.
619 */
620 if (p->break_loop) {
621 if (n == 0) {
622 p->break_loop = 0;
623 return (PCAP_ERROR_BREAK);
624 } else {
625 p->bp = bp;
626 p->cc = (int) (ep - bp);
627 return (n);
628 }
629 }
630 if (bp >= ep)
631 break;
632
633 caplen = bhp->bh_caplen;
634 hdrlen = bhp->bh_hdrlen;
635 datap = bp + hdrlen;
636
637 /*
638 * Short-circuit evaluation: if using BPF filter
639 * in kernel, no need to do it now - we already know
640 * the packet passed the filter.
641 *
642 * XXX - pcap_filter() should always return TRUE if
643 * handed a null pointer for the program, but it might
644 * just try to "run" the filter, so we check here.
645 */
646 if (pw->filtering_in_kernel ||
647 p->fcode.bf_insns == NULL ||
648 pcap_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
649 #ifdef ENABLE_REMOTE
650 switch (p->rmt_samp.method) {
651
652 case PCAP_SAMP_1_EVERY_N:
653 pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
654
655 /* Discard all packets that are not '1 out of N' */
656 if (pw->samp_npkt != 0) {
657 bp += Packet_WORDALIGN(caplen + hdrlen);
658 continue;
659 }
660 break;
661
662 case PCAP_SAMP_FIRST_AFTER_N_MS:
663 {
664 struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
665
666 /*
667 * Check if the timestamp of the arrived
668 * packet is smaller than our target time.
669 */
670 if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
671 (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
672 bp += Packet_WORDALIGN(caplen + hdrlen);
673 continue;
674 }
675
676 /*
677 * The arrived packet is suitable for being
678 * delivered to our caller, so let's update
679 * the target time.
680 */
681 pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
682 if (pw->samp_time.tv_usec > 1000000) {
683 pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
684 pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
685 }
686 }
687 }
688 #endif /* ENABLE_REMOTE */
689
690 /*
691 * XXX A bpf_hdr matches a pcap_pkthdr.
692 */
693 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
694 bp += Packet_WORDALIGN(caplen + hdrlen);
695 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
696 p->bp = bp;
697 p->cc = (int) (ep - bp);
698 return (n);
699 }
700 } else {
701 /*
702 * Skip this packet.
703 */
704 bp += Packet_WORDALIGN(caplen + hdrlen);
705 }
706 }
707 #undef bhp
708 p->cc = 0;
709 return (n);
710 }
711
712 #ifdef HAVE_DAG_API
713 static int
714 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
715 {
716 struct pcap_win *pw = p->priv;
717 PACKET Packet;
718 u_char *dp = NULL;
719 int packet_len = 0, caplen = 0;
720 struct pcap_pkthdr pcap_header;
721 u_char *endofbuf;
722 int n = 0;
723 dag_record_t *header;
724 unsigned erf_record_len;
725 ULONGLONG ts;
726 int cc;
727 unsigned swt;
728 unsigned dfp = pw->adapter->DagFastProcess;
729
730 cc = p->cc;
731 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
732 {
733 /*
734 * Get new packets from the network.
735 *
736 * The PACKET structure had a bunch of extra stuff for
737 * Windows 9x/Me, but the only interesting data in it
738 * in the versions of Windows that we support is just
739 * a copy of p->buffer, a copy of p->buflen, and the
740 * actual number of bytes read returned from
741 * PacketReceivePacket(), none of which has to be
742 * retained from call to call, so we just keep one on
743 * the stack.
744 */
745 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
746 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
747 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
748 return (-1);
749 }
750
751 cc = Packet.ulBytesReceived;
752 if(cc == 0)
753 /* The timeout has expired but we no packets arrived */
754 return (0);
755 header = (dag_record_t*)pw->adapter->DagBuffer;
756 }
757 else
758 header = (dag_record_t*)p->bp;
759
760 endofbuf = (char*)header + cc;
761
762 /*
763 * Cycle through the packets
764 */
765 do
766 {
767 erf_record_len = SWAPS(header->rlen);
768 if((char*)header + erf_record_len > endofbuf)
769 break;
770
771 /* Increase the number of captured packets */
772 p->stat.ps_recv++;
773
774 /* Find the beginning of the packet */
775 dp = ((u_char *)header) + dag_record_size;
776
777 /* Determine actual packet len */
778 switch(header->type)
779 {
780 case TYPE_ATM:
781 packet_len = ATM_SNAPLEN;
782 caplen = ATM_SNAPLEN;
783 dp += 4;
784
785 break;
786
787 case TYPE_ETH:
788 swt = SWAPS(header->wlen);
789 packet_len = swt - (pw->dag_fcs_bits);
790 caplen = erf_record_len - dag_record_size - 2;
791 if (caplen > packet_len)
792 {
793 caplen = packet_len;
794 }
795 dp += 2;
796
797 break;
798
799 case TYPE_HDLC_POS:
800 swt = SWAPS(header->wlen);
801 packet_len = swt - (pw->dag_fcs_bits);
802 caplen = erf_record_len - dag_record_size;
803 if (caplen > packet_len)
804 {
805 caplen = packet_len;
806 }
807
808 break;
809 }
810
811 if(caplen > p->snapshot)
812 caplen = p->snapshot;
813
814 /*
815 * Has "pcap_breakloop()" been called?
816 * If so, return immediately - if we haven't read any
817 * packets, clear the flag and return -2 to indicate
818 * that we were told to break out of the loop, otherwise
819 * leave the flag set, so that the *next* call will break
820 * out of the loop without having read any packets, and
821 * return the number of packets we've processed so far.
822 */
823 if (p->break_loop)
824 {
825 if (n == 0)
826 {
827 p->break_loop = 0;
828 return (-2);
829 }
830 else
831 {
832 p->bp = (char*)header;
833 p->cc = endofbuf - (char*)header;
834 return (n);
835 }
836 }
837
838 if(!dfp)
839 {
840 /* convert between timestamp formats */
841 ts = header->ts;
842 pcap_header.ts.tv_sec = (int)(ts >> 32);
843 ts = (ts & 0xffffffffi64) * 1000000;
844 ts += 0x80000000; /* rounding */
845 pcap_header.ts.tv_usec = (int)(ts >> 32);
846 if (pcap_header.ts.tv_usec >= 1000000) {
847 pcap_header.ts.tv_usec -= 1000000;
848 pcap_header.ts.tv_sec++;
849 }
850 }
851
852 /* No underlaying filtering system. We need to filter on our own */
853 if (p->fcode.bf_insns)
854 {
855 if (pcap_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
856 {
857 /* Move to next packet */
858 header = (dag_record_t*)((char*)header + erf_record_len);
859 continue;
860 }
861 }
862
863 /* Fill the header for the user suppplied callback function */
864 pcap_header.caplen = caplen;
865 pcap_header.len = packet_len;
866
867 /* Call the callback function */
868 (*callback)(user, &pcap_header, dp);
869
870 /* Move to next packet */
871 header = (dag_record_t*)((char*)header + erf_record_len);
872
873 /* Stop if the number of packets requested by user has been reached*/
874 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
875 {
876 p->bp = (char*)header;
877 p->cc = endofbuf - (char*)header;
878 return (n);
879 }
880 }
881 while((u_char*)header < endofbuf);
882
883 return (1);
884 }
885 #endif /* HAVE_DAG_API */
886
887 /* Send a packet to the network */
888 static int
889 pcap_inject_npf(pcap_t *p, const void *buf, int size)
890 {
891 struct pcap_win *pw = p->priv;
892 PACKET pkt;
893
894 PacketInitPacket(&pkt, (PVOID)buf, size);
895 if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
896 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
897 return (-1);
898 }
899
900 /*
901 * We assume it all got sent if "PacketSendPacket()" succeeded.
902 * "pcap_inject()" is expected to return the number of bytes
903 * sent.
904 */
905 return (size);
906 }
907
908 static void
909 pcap_cleanup_npf(pcap_t *p)
910 {
911 struct pcap_win *pw = p->priv;
912
913 if (pw->adapter != NULL) {
914 PacketCloseAdapter(pw->adapter);
915 pw->adapter = NULL;
916 }
917 if (pw->rfmon_selfstart)
918 {
919 PacketSetMonitorMode(p->opt.device, 0);
920 }
921 pcap_cleanup_live_common(p);
922 }
923
924 static void
925 pcap_breakloop_npf(pcap_t *p)
926 {
927 pcap_breakloop_common(p);
928 struct pcap_win *pw = p->priv;
929
930 /* XXX - what if this fails? */
931 SetEvent(PacketGetReadEvent(pw->adapter));
932 }
933
934 static int
935 pcap_activate_npf(pcap_t *p)
936 {
937 struct pcap_win *pw = p->priv;
938 NetType type;
939 int res;
940 int status = 0;
941 struct bpf_insn total_insn;
942 struct bpf_program total_prog;
943
944 if (p->opt.rfmon) {
945 /*
946 * Monitor mode is supported on Windows Vista and later.
947 */
948 if (PacketGetMonitorMode(p->opt.device) == 1)
949 {
950 pw->rfmon_selfstart = 0;
951 }
952 else
953 {
954 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
955 {
956 pw->rfmon_selfstart = 0;
957 // Monitor mode is not supported.
958 if (res == 0)
959 {
960 return PCAP_ERROR_RFMON_NOTSUP;
961 }
962 else
963 {
964 return PCAP_ERROR;
965 }
966 }
967 else
968 {
969 pw->rfmon_selfstart = 1;
970 }
971 }
972 }
973
974 /* Init Winsock if it hasn't already been initialized */
975 pcap_wsockinit();
976
977 pw->adapter = PacketOpenAdapter(p->opt.device);
978
979 if (pw->adapter == NULL)
980 {
981 DWORD errcode = GetLastError();
982
983 /*
984 * What error did we get when trying to open the adapter?
985 */
986 switch (errcode) {
987
988 case ERROR_BAD_UNIT:
989 /*
990 * There's no such device.
991 */
992 return (PCAP_ERROR_NO_SUCH_DEVICE);
993
994 case ERROR_ACCESS_DENIED:
995 /*
996 * There is, but we don't have permission to
997 * use it.
998 */
999 return (PCAP_ERROR_PERM_DENIED);
1000
1001 default:
1002 /*
1003 * Unknown - report details.
1004 */
1005 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1006 errcode, "Error opening adapter");
1007 if (pw->rfmon_selfstart)
1008 {
1009 PacketSetMonitorMode(p->opt.device, 0);
1010 }
1011 return (PCAP_ERROR);
1012 }
1013 }
1014
1015 /*get network type*/
1016 if(PacketGetNetType (pw->adapter,&type) == FALSE)
1017 {
1018 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1019 GetLastError(), "Cannot determine the network type");
1020 goto bad;
1021 }
1022
1023 /*Set the linktype*/
1024 switch (type.LinkType)
1025 {
1026 case NdisMediumWan:
1027 p->linktype = DLT_EN10MB;
1028 break;
1029
1030 case NdisMedium802_3:
1031 p->linktype = DLT_EN10MB;
1032 /*
1033 * This is (presumably) a real Ethernet capture; give it a
1034 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1035 * that an application can let you choose it, in case you're
1036 * capturing DOCSIS traffic that a Cisco Cable Modem
1037 * Termination System is putting out onto an Ethernet (it
1038 * doesn't put an Ethernet header onto the wire, it puts raw
1039 * DOCSIS frames out on the wire inside the low-level
1040 * Ethernet framing).
1041 */
1042 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1043 /*
1044 * If that fails, just leave the list empty.
1045 */
1046 if (p->dlt_list != NULL) {
1047 p->dlt_list[0] = DLT_EN10MB;
1048 p->dlt_list[1] = DLT_DOCSIS;
1049 p->dlt_count = 2;
1050 }
1051 break;
1052
1053 case NdisMediumFddi:
1054 p->linktype = DLT_FDDI;
1055 break;
1056
1057 case NdisMedium802_5:
1058 p->linktype = DLT_IEEE802;
1059 break;
1060
1061 case NdisMediumArcnetRaw:
1062 p->linktype = DLT_ARCNET;
1063 break;
1064
1065 case NdisMediumArcnet878_2:
1066 p->linktype = DLT_ARCNET;
1067 break;
1068
1069 case NdisMediumAtm:
1070 p->linktype = DLT_ATM_RFC1483;
1071 break;
1072
1073 case NdisMediumCHDLC:
1074 p->linktype = DLT_CHDLC;
1075 break;
1076
1077 case NdisMediumPPPSerial:
1078 p->linktype = DLT_PPP_SERIAL;
1079 break;
1080
1081 case NdisMediumNull:
1082 p->linktype = DLT_NULL;
1083 break;
1084
1085 case NdisMediumBare80211:
1086 p->linktype = DLT_IEEE802_11;
1087 break;
1088
1089 case NdisMediumRadio80211:
1090 p->linktype = DLT_IEEE802_11_RADIO;
1091 break;
1092
1093 case NdisMediumPpi:
1094 p->linktype = DLT_PPI;
1095 break;
1096
1097 case NdisMediumWirelessWan:
1098 p->linktype = DLT_RAW;
1099 break;
1100
1101 default:
1102 /*
1103 * An unknown medium type is assumed to supply Ethernet
1104 * headers; if not, the user will have to report it,
1105 * so that the medium type and link-layer header type
1106 * can be determined. If we were to fail here, we
1107 * might get the link-layer type in the error, but
1108 * the user wouldn't get a capture, so we wouldn't
1109 * be able to determine the link-layer type; we report
1110 * a warning with the link-layer type, so at least
1111 * some programs will report the warning.
1112 */
1113 p->linktype = DLT_EN10MB;
1114 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1115 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1116 type.LinkType);
1117 status = PCAP_WARNING;
1118 break;
1119 }
1120
1121 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1122 /*
1123 * Set the timestamp type.
1124 * (Yes, we require PacketGetTimestampModes(), not just
1125 * PacketSetTimestampMode(). If we have the former, we
1126 * have the latter, unless somebody's using a version
1127 * of Npcap that they've hacked to provide the former
1128 * but not the latter; if they've done that, either
1129 * they're confused or they're trolling us.)
1130 */
1131 switch (p->opt.tstamp_type) {
1132
1133 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED:
1134 /*
1135 * Better than low-res, but *not* synchronized with
1136 * the OS clock.
1137 */
1138 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION))
1139 {
1140 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1141 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1142 goto bad;
1143 }
1144 break;
1145
1146 case PCAP_TSTAMP_HOST_LOWPREC:
1147 /*
1148 * Low-res, but synchronized with the OS clock.
1149 */
1150 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME))
1151 {
1152 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1153 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1154 goto bad;
1155 }
1156 break;
1157
1158 case PCAP_TSTAMP_HOST_HIPREC:
1159 /*
1160 * High-res, and synchronized with the OS clock.
1161 */
1162 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE))
1163 {
1164 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1165 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1166 goto bad;
1167 }
1168 break;
1169
1170 case PCAP_TSTAMP_HOST:
1171 /*
1172 * XXX - do whatever the default is, for now.
1173 * Set to the highest resolution that's synchronized
1174 * with the system clock?
1175 */
1176 break;
1177 }
1178 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1179
1180 /*
1181 * Turn a negative snapshot value (invalid), a snapshot value of
1182 * 0 (unspecified), or a value bigger than the normal maximum
1183 * value, into the maximum allowed value.
1184 *
1185 * If some application really *needs* a bigger snapshot
1186 * length, we should just increase MAXIMUM_SNAPLEN.
1187 */
1188 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1189 p->snapshot = MAXIMUM_SNAPLEN;
1190
1191 /* Set promiscuous mode */
1192 if (p->opt.promisc)
1193 {
1194
1195 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1196 {
1197 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1198 PCAP_ERRBUF_SIZE, GetLastError(),
1199 "failed to set hardware filter to promiscuous mode");
1200 goto bad;
1201 }
1202 }
1203 else
1204 {
1205 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1206 * protocols and all packets indicated by the NIC" but if no protocol
1207 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1208 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1209 * capture incoming frames.
1210 */
1211 if (PacketSetHwFilter(pw->adapter,
1212 NDIS_PACKET_TYPE_ALL_LOCAL |
1213 NDIS_PACKET_TYPE_DIRECTED |
1214 NDIS_PACKET_TYPE_BROADCAST |
1215 NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1216 {
1217 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1218 PCAP_ERRBUF_SIZE, GetLastError(),
1219 "failed to set hardware filter to non-promiscuous mode");
1220 goto bad;
1221 }
1222 }
1223
1224 /* Set the buffer size */
1225 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1226
1227 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1228 {
1229 /*
1230 * Traditional Adapter
1231 */
1232 /*
1233 * If the buffer size wasn't explicitly set, default to
1234 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1235 */
1236 if (p->opt.buffer_size == 0)
1237 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1238
1239 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1240 {
1241 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1242 goto bad;
1243 }
1244
1245 p->buffer = malloc(p->bufsize);
1246 if (p->buffer == NULL)
1247 {
1248 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1249 errno, "malloc");
1250 goto bad;
1251 }
1252
1253 if (p->opt.immediate)
1254 {
1255 /* tell the driver to copy the buffer as soon as data arrives */
1256 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1257 {
1258 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1259 PCAP_ERRBUF_SIZE, GetLastError(),
1260 "Error calling PacketSetMinToCopy");
1261 goto bad;
1262 }
1263 }
1264 else
1265 {
1266 /* tell the driver to copy the buffer only if it contains at least 16K */
1267 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1268 {
1269 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1270 PCAP_ERRBUF_SIZE, GetLastError(),
1271 "Error calling PacketSetMinToCopy");
1272 goto bad;
1273 }
1274 }
1275 } else {
1276 /*
1277 * Dag Card
1278 */
1279 #ifdef HAVE_DAG_API
1280 /*
1281 * We have DAG support.
1282 */
1283 LONG status;
1284 HKEY dagkey;
1285 DWORD lptype;
1286 DWORD lpcbdata;
1287 int postype = 0;
1288 char keyname[512];
1289
1290 snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1291 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1292 strstr(_strlwr(p->opt.device), "dag"));
1293 do
1294 {
1295 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1296 if(status != ERROR_SUCCESS)
1297 break;
1298
1299 status = RegQueryValueEx(dagkey,
1300 "PosType",
1301 NULL,
1302 &lptype,
1303 (char*)&postype,
1304 &lpcbdata);
1305
1306 if(status != ERROR_SUCCESS)
1307 {
1308 postype = 0;
1309 }
1310
1311 RegCloseKey(dagkey);
1312 }
1313 while(FALSE);
1314
1315
1316 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1317
1318 /* Set the length of the FCS associated to any packet. This value
1319 * will be subtracted to the packet length */
1320 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1321 #else /* HAVE_DAG_API */
1322 /*
1323 * No DAG support.
1324 */
1325 goto bad;
1326 #endif /* HAVE_DAG_API */
1327 }
1328
1329 /*
1330 * If there's no filter program installed, there's
1331 * no indication to the kernel of what the snapshot
1332 * length should be, so no snapshotting is done.
1333 *
1334 * Therefore, when we open the device, we install
1335 * an "accept everything" filter with the specified
1336 * snapshot length.
1337 */
1338 total_insn.code = (u_short)(BPF_RET | BPF_K);
1339 total_insn.jt = 0;
1340 total_insn.jf = 0;
1341 total_insn.k = p->snapshot;
1342
1343 total_prog.bf_len = 1;
1344 total_prog.bf_insns = &total_insn;
1345 if (!PacketSetBpf(pw->adapter, &total_prog)) {
1346 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1347 GetLastError(), "PacketSetBpf");
1348 status = PCAP_ERROR;
1349 goto bad;
1350 }
1351
1352 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1353
1354 /* disable loopback capture if requested */
1355 if (p->opt.nocapture_local)
1356 {
1357 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1358 {
1359 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1360 "Unable to disable the capture of loopback packets.");
1361 goto bad;
1362 }
1363 }
1364
1365 #ifdef HAVE_DAG_API
1366 if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1367 {
1368 /* install dag specific handlers for read and setfilter */
1369 p->read_op = pcap_read_win32_dag;
1370 p->setfilter_op = pcap_setfilter_win32_dag;
1371 }
1372 else
1373 {
1374 #endif /* HAVE_DAG_API */
1375 /* install traditional npf handlers for read and setfilter */
1376 p->read_op = pcap_read_npf;
1377 p->setfilter_op = pcap_setfilter_npf;
1378 #ifdef HAVE_DAG_API
1379 }
1380 #endif /* HAVE_DAG_API */
1381 p->setdirection_op = NULL; /* Not implemented. */
1382 /* XXX - can this be implemented on some versions of Windows? */
1383 p->inject_op = pcap_inject_npf;
1384 p->set_datalink_op = NULL; /* can't change data link type */
1385 p->getnonblock_op = pcap_getnonblock_npf;
1386 p->setnonblock_op = pcap_setnonblock_npf;
1387 p->stats_op = pcap_stats_npf;
1388 p->breakloop_op = pcap_breakloop_npf;
1389 p->stats_ex_op = pcap_stats_ex_npf;
1390 p->setbuff_op = pcap_setbuff_npf;
1391 p->setmode_op = pcap_setmode_npf;
1392 p->setmintocopy_op = pcap_setmintocopy_npf;
1393 p->getevent_op = pcap_getevent_npf;
1394 p->oid_get_request_op = pcap_oid_get_request_npf;
1395 p->oid_set_request_op = pcap_oid_set_request_npf;
1396 p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1397 p->setuserbuffer_op = pcap_setuserbuffer_npf;
1398 p->live_dump_op = pcap_live_dump_npf;
1399 p->live_dump_ended_op = pcap_live_dump_ended_npf;
1400 p->get_airpcap_handle_op = pcap_get_airpcap_handle_npf;
1401 p->cleanup_op = pcap_cleanup_npf;
1402
1403 /*
1404 * XXX - this is only done because WinPcap supported
1405 * pcap_fileno() returning the hFile HANDLE from the
1406 * ADAPTER structure. We make no general guarantees
1407 * that the caller can do anything useful with it.
1408 *
1409 * (Not that we make any general guarantee of that
1410 * sort on UN*X, either, any more, given that not
1411 * all capture devices are regular OS network
1412 * interfaces.)
1413 */
1414 p->handle = pw->adapter->hFile;
1415
1416 return (status);
1417 bad:
1418 pcap_cleanup_npf(p);
1419 return (PCAP_ERROR);
1420 }
1421
1422 /*
1423 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1424 */
1425 static int
1426 pcap_can_set_rfmon_npf(pcap_t *p)
1427 {
1428 return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1429 }
1430
1431 pcap_t *
1432 pcap_create_interface(const char *device _U_, char *ebuf)
1433 {
1434 pcap_t *p;
1435 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1436 char *device_copy;
1437 ADAPTER *adapter;
1438 ULONG num_ts_modes;
1439 BOOL ret;
1440 DWORD error;
1441 ULONG *modes;
1442 #endif
1443
1444 p = PCAP_CREATE_COMMON(ebuf, struct pcap_win);
1445 if (p == NULL)
1446 return (NULL);
1447
1448 p->activate_op = pcap_activate_npf;
1449 p->can_set_rfmon_op = pcap_can_set_rfmon_npf;
1450
1451 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1452 /*
1453 * First, find out how many time stamp modes we have.
1454 * To do that, we have to open the adapter.
1455 *
1456 * XXX - PacketOpenAdapter() takes a non-const pointer
1457 * as an argument, so we make a copy of the argument and
1458 * pass that to it.
1459 */
1460 device_copy = strdup(device);
1461 adapter = PacketOpenAdapter(device_copy);
1462 free(device_copy);
1463 if (adapter != NULL)
1464 {
1465 /*
1466 * Get the total number of time stamp modes.
1467 *
1468 * The buffer for PacketGetTimestampModes() is
1469 * a sequence of 1 or more ULONGs. What's
1470 * passed to PacketGetTimestampModes() should have
1471 * the total number of ULONGs in the first ULONG;
1472 * what's returned *from* PacketGetTimestampModes()
1473 * has the total number of time stamp modes in
1474 * the first ULONG.
1475 *
1476 * Yes, that means if there are N time stamp
1477 * modes, the first ULONG should be set to N+1
1478 * on input, and will be set to N on output.
1479 *
1480 * We first make a call to PacketGetTimestampModes()
1481 * with a pointer to a single ULONG set to 1; the
1482 * call should fail with ERROR_MORE_DATA (unless
1483 * there are *no* modes, but that should never
1484 * happen), and that ULONG should be set to the
1485 * number of modes.
1486 */
1487 num_ts_modes = 1;
1488 ret = PacketGetTimestampModes(adapter, &num_ts_modes);
1489 if (!ret) {
1490 /*
1491 * OK, it failed. Did it fail with
1492 * ERROR_MORE_DATA?
1493 */
1494 error = GetLastError();
1495 if (error != ERROR_MORE_DATA) {
1496 /*
1497 * No, some other error. Fail.
1498 */
1499 pcap_fmt_errmsg_for_win32_err(ebuf,
1500 PCAP_ERRBUF_SIZE, GetLastError(),
1501 "Error calling PacketGetTimestampModes");
1502 pcap_close(p);
1503 return (NULL);
1504 }
1505
1506 /*
1507 * Yes, so we now know how many types to fetch.
1508 *
1509 * The buffer needs to have one ULONG for the
1510 * count and num_ts_modes ULONGs for the
1511 * num_ts_modes time stamp types.
1512 */
1513 modes = (ULONG *)malloc((1 + num_ts_modes) * sizeof(ULONG));
1514 if (modes == NULL) {
1515 /* Out of memory. */
1516 /* XXX SET ebuf */
1517 pcap_close(p);
1518 return (NULL);
1519 }
1520 modes[0] = 1 + num_ts_modes;
1521 if (!PacketGetTimestampModes(adapter, modes)) {
1522 pcap_fmt_errmsg_for_win32_err(ebuf,
1523 PCAP_ERRBUF_SIZE, GetLastError(),
1524 "Error calling PacketGetTimestampModes");
1525 free(modes);
1526 pcap_close(p);
1527 return (NULL);
1528 }
1529 if (modes[0] != num_ts_modes) {
1530 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1531 "First PacketGetTimestampModes() call gives %lu modes, second call gives %u modes",
1532 num_ts_modes, modes[0]);
1533 free(modes);
1534 pcap_close(p);
1535 return (NULL);
1536 }
1537 if (num_ts_modes != 0) {
1538 u_int num_ts_types;
1539
1540 /*
1541 * Allocate a buffer big enough for
1542 * PCAP_TSTAMP_HOST (default) plus
1543 * the explicitly specified modes.
1544 */
1545 p->tstamp_type_list = malloc((1 + modes[0]) * sizeof(u_int));
1546 if (p->tstamp_type_list == NULL) {
1547 /* XXX SET ebuf */
1548 free(modes);
1549 pcap_close(p);
1550 return (NULL);
1551 }
1552 num_ts_types = 0;
1553 p->tstamp_type_list[num_ts_types] =
1554 PCAP_TSTAMP_HOST;
1555 num_ts_types++;
1556 for (ULONG i = 0; i < modes[0]; i++) {
1557 switch (modes[i + 1]) {
1558
1559 case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION:
1560 /*
1561 * Better than low-res,
1562 * but *not* synchronized
1563 * with the OS clock.
1564 */
1565 p->tstamp_type_list[num_ts_types] =
1566 PCAP_TSTAMP_HOST_HIPREC_UNSYNCED;
1567 num_ts_types++;
1568 break;
1569
1570 case TIMESTAMPMODE_QUERYSYSTEMTIME:
1571 /*
1572 * Low-res, but synchronized
1573 * with the OS clock.
1574 */
1575 p->tstamp_type_list[num_ts_types] =
1576 PCAP_TSTAMP_HOST_LOWPREC;
1577 num_ts_types++;
1578 break;
1579
1580 case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE:
1581 /*
1582 * High-res, and synchronized
1583 * with the OS clock.
1584 */
1585 p->tstamp_type_list[num_ts_types] =
1586 PCAP_TSTAMP_HOST_HIPREC;
1587 num_ts_types++;
1588 break;
1589
1590 default:
1591 /*
1592 * Unknown, so we can't
1593 * report it.
1594 */
1595 break;
1596 }
1597 }
1598 p->tstamp_type_count = num_ts_types;
1599 free(modes);
1600 }
1601 }
1602 PacketCloseAdapter(adapter);
1603 }
1604 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1605
1606 return (p);
1607 }
1608
1609 static int
1610 pcap_setfilter_npf(pcap_t *p, struct bpf_program *fp)
1611 {
1612 struct pcap_win *pw = p->priv;
1613
1614 if(PacketSetBpf(pw->adapter,fp)==FALSE){
1615 /*
1616 * Kernel filter not installed.
1617 *
1618 * XXX - we don't know whether this failed because:
1619 *
1620 * the kernel rejected the filter program as invalid,
1621 * in which case we should fall back on userland
1622 * filtering;
1623 *
1624 * the kernel rejected the filter program as too big,
1625 * in which case we should again fall back on
1626 * userland filtering;
1627 *
1628 * there was some other problem, in which case we
1629 * should probably report an error.
1630 *
1631 * For NPF devices, the Win32 status will be
1632 * STATUS_INVALID_DEVICE_REQUEST for invalid
1633 * filters, but I don't know what it'd be for
1634 * other problems, and for some other devices
1635 * it might not be set at all.
1636 *
1637 * So we just fall back on userland filtering in
1638 * all cases.
1639 */
1640
1641 /*
1642 * install_bpf_program() validates the program.
1643 *
1644 * XXX - what if we already have a filter in the kernel?
1645 */
1646 if (install_bpf_program(p, fp) < 0)
1647 return (-1);
1648 pw->filtering_in_kernel = 0; /* filtering in userland */
1649 return (0);
1650 }
1651
1652 /*
1653 * It worked.
1654 */
1655 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1656
1657 /*
1658 * Discard any previously-received packets, as they might have
1659 * passed whatever filter was formerly in effect, but might
1660 * not pass this filter (BIOCSETF discards packets buffered
1661 * in the kernel, so you can lose packets in any case).
1662 */
1663 p->cc = 0;
1664 return (0);
1665 }
1666
1667 /*
1668 * We filter at user level, since the kernel driver doesn't process the packets
1669 */
1670 static int
1671 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1672
1673 if(!fp)
1674 {
1675 pcap_strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1676 return (-1);
1677 }
1678
1679 /* Install a user level filter */
1680 if (install_bpf_program(p, fp) < 0)
1681 return (-1);
1682
1683 return (0);
1684 }
1685
1686 static int
1687 pcap_getnonblock_npf(pcap_t *p)
1688 {
1689 struct pcap_win *pw = p->priv;
1690
1691 /*
1692 * XXX - if there were a PacketGetReadTimeout() call, we
1693 * would use it, and return 1 if the timeout is -1
1694 * and 0 otherwise.
1695 */
1696 return (pw->nonblock);
1697 }
1698
1699 static int
1700 pcap_setnonblock_npf(pcap_t *p, int nonblock)
1701 {
1702 struct pcap_win *pw = p->priv;
1703 int newtimeout;
1704
1705 if (nonblock) {
1706 /*
1707 * Set the packet buffer timeout to -1 for non-blocking
1708 * mode.
1709 */
1710 newtimeout = -1;
1711 } else {
1712 /*
1713 * Restore the timeout set when the device was opened.
1714 * (Note that this may be -1, in which case we're not
1715 * really leaving non-blocking mode. However, although
1716 * the timeout argument to pcap_set_timeout() and
1717 * pcap_open_live() is an int, you're not supposed to
1718 * supply a negative value, so that "shouldn't happen".)
1719 */
1720 newtimeout = p->opt.timeout;
1721 }
1722 if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1723 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1724 GetLastError(), "PacketSetReadTimeout");
1725 return (-1);
1726 }
1727 pw->nonblock = (newtimeout == -1);
1728 return (0);
1729 }
1730
1731 static int
1732 pcap_add_if_npf(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
1733 const char *description, char *errbuf)
1734 {
1735 pcap_if_t *curdev;
1736 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1737 LONG if_addr_size;
1738 int res = 0;
1739
1740 if_addr_size = MAX_NETWORK_ADDRESSES;
1741
1742 /*
1743 * Add an entry for this interface, with no addresses.
1744 */
1745 curdev = add_dev(devlistp, name, flags, description, errbuf);
1746 if (curdev == NULL) {
1747 /*
1748 * Failure.
1749 */
1750 return (-1);
1751 }
1752
1753 /*
1754 * Get the list of addresses for the interface.
1755 */
1756 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1757 /*
1758 * Failure.
1759 *
1760 * We don't return an error, because this can happen with
1761 * NdisWan interfaces, and we want to supply them even
1762 * if we can't supply their addresses.
1763 *
1764 * We return an entry with an empty address list.
1765 */
1766 return (0);
1767 }
1768
1769 /*
1770 * Now add the addresses.
1771 */
1772 while (if_addr_size-- > 0) {
1773 /*
1774 * "curdev" is an entry for this interface; add an entry for
1775 * this address to its list of addresses.
1776 */
1777 res = add_addr_to_dev(curdev,
1778 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1779 sizeof (struct sockaddr_storage),
1780 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1781 sizeof (struct sockaddr_storage),
1782 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1783 sizeof (struct sockaddr_storage),
1784 NULL,
1785 0,
1786 errbuf);
1787 if (res == -1) {
1788 /*
1789 * Failure.
1790 */
1791 break;
1792 }
1793 }
1794
1795 return (res);
1796 }
1797
1798 static int
1799 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
1800 {
1801 char *name_copy;
1802 ADAPTER *adapter;
1803 int status;
1804 size_t len;
1805 NDIS_HARDWARE_STATUS hardware_status;
1806 #ifdef OID_GEN_PHYSICAL_MEDIUM
1807 NDIS_PHYSICAL_MEDIUM phys_medium;
1808 bpf_u_int32 gen_physical_medium_oids[] = {
1809 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1810 OID_GEN_PHYSICAL_MEDIUM_EX,
1811 #endif
1812 OID_GEN_PHYSICAL_MEDIUM
1813 };
1814 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1815 size_t i;
1816 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1817 #ifdef OID_GEN_LINK_STATE
1818 NDIS_LINK_STATE link_state;
1819 #endif
1820 int connect_status;
1821
1822 if (*flags & PCAP_IF_LOOPBACK) {
1823 /*
1824 * Loopback interface, so the connection status doesn't
1825 * apply. and it's not wireless (or wired, for that
1826 * matter...). We presume it's up and running.
1827 */
1828 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING | PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1829 return (0);
1830 }
1831
1832 /*
1833 * We need to open the adapter to get this information.
1834 *
1835 * XXX - PacketOpenAdapter() takes a non-const pointer
1836 * as an argument, so we make a copy of the argument and
1837 * pass that to it.
1838 */
1839 name_copy = strdup(name);
1840 adapter = PacketOpenAdapter(name_copy);
1841 free(name_copy);
1842 if (adapter == NULL) {
1843 /*
1844 * Give up; if they try to open this device, it'll fail.
1845 */
1846 return (0);
1847 }
1848
1849 #ifdef HAVE_AIRPCAP_API
1850 /*
1851 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1852 * Just set these flags (and none of the '*flags' entered with).
1853 */
1854 if (PacketGetAirPcapHandle(adapter)) {
1855 /*
1856 * Must be "up" and "running" if the above if succeeded.
1857 */
1858 *flags = PCAP_IF_UP | PCAP_IF_RUNNING;
1859
1860 /*
1861 * An airpcap device is a wireless device (duh!)
1862 */
1863 *flags |= PCAP_IF_WIRELESS;
1864
1865 /*
1866 * A "network assosiation state" makes no sense for airpcap.
1867 */
1868 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1869 PacketCloseAdapter(adapter);
1870 return (0);
1871 }
1872 #endif
1873
1874 /*
1875 * Get the hardware status, and derive "up" and "running" from
1876 * that.
1877 */
1878 len = sizeof (hardware_status);
1879 status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
1880 &hardware_status, &len, errbuf);
1881 if (status == 0) {
1882 switch (hardware_status) {
1883
1884 case NdisHardwareStatusReady:
1885 /*
1886 * "Available and capable of sending and receiving
1887 * data over the wire", so up and running.
1888 */
1889 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1890 break;
1891
1892 case NdisHardwareStatusInitializing:
1893 case NdisHardwareStatusReset:
1894 /*
1895 * "Initializing" or "Resetting", so up, but
1896 * not running.
1897 */
1898 *flags |= PCAP_IF_UP;
1899 break;
1900
1901 case NdisHardwareStatusClosing:
1902 case NdisHardwareStatusNotReady:
1903 /*
1904 * "Closing" or "Not ready", so neither up nor
1905 * running.
1906 */
1907 break;
1908
1909 default:
1910 /*
1911 * Unknown.
1912 */
1913 break;
1914 }
1915 } else {
1916 /*
1917 * Can't get the hardware status, so assume both up and
1918 * running.
1919 */
1920 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1921 }
1922
1923 /*
1924 * Get the network type.
1925 */
1926 #ifdef OID_GEN_PHYSICAL_MEDIUM
1927 /*
1928 * Try the OIDs we have for this, in order.
1929 */
1930 for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
1931 len = sizeof (phys_medium);
1932 status = oid_get_request(adapter, gen_physical_medium_oids[i],
1933 &phys_medium, &len, errbuf);
1934 if (status == 0) {
1935 /*
1936 * Success.
1937 */
1938 break;
1939 }
1940 /*
1941 * Failed. We can't determine whether it failed
1942 * because that particular OID isn't supported
1943 * or because some other problem occurred, so we
1944 * just drive on and try the next OID.
1945 */
1946 }
1947 if (status == 0) {
1948 /*
1949 * We got the physical medium.
1950 *
1951 * XXX - we might want to check for NdisPhysicalMediumWiMax
1952 * and NdisPhysicalMediumNative802_15_4 being
1953 * part of the enum, and check for those in the "wireless"
1954 * case.
1955 */
1956 DIAG_OFF_ENUM_SWITCH
1957 switch (phys_medium) {
1958
1959 case NdisPhysicalMediumWirelessLan:
1960 case NdisPhysicalMediumWirelessWan:
1961 case NdisPhysicalMediumNative802_11:
1962 case NdisPhysicalMediumBluetooth:
1963 case NdisPhysicalMediumUWB:
1964 case NdisPhysicalMediumIrda:
1965 /*
1966 * Wireless.
1967 */
1968 *flags |= PCAP_IF_WIRELESS;
1969 break;
1970
1971 default:
1972 /*
1973 * Not wireless or unknown
1974 */
1975 break;
1976 }
1977 DIAG_ON_ENUM_SWITCH
1978 }
1979 #endif
1980
1981 /*
1982 * Get the connection status.
1983 */
1984 #ifdef OID_GEN_LINK_STATE
1985 len = sizeof(link_state);
1986 status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
1987 &len, errbuf);
1988 if (status == 0) {
1989 /*
1990 * NOTE: this also gives us the receive and transmit
1991 * link state.
1992 */
1993 switch (link_state.MediaConnectState) {
1994
1995 case MediaConnectStateConnected:
1996 /*
1997 * It's connected.
1998 */
1999 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2000 break;
2001
2002 case MediaConnectStateDisconnected:
2003 /*
2004 * It's disconnected.
2005 */
2006 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2007 break;
2008
2009 case MediaConnectStateUnknown:
2010 default:
2011 /*
2012 * It's unknown whether it's connected or not.
2013 */
2014 break;
2015 }
2016 }
2017 #else
2018 /*
2019 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2020 */
2021 status = -1;
2022 #endif
2023 if (status == -1) {
2024 /*
2025 * OK, OID_GEN_LINK_STATE didn't work, try
2026 * OID_GEN_MEDIA_CONNECT_STATUS.
2027 */
2028 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
2029 &connect_status, &len, errbuf);
2030 if (status == 0) {
2031 switch (connect_status) {
2032
2033 case NdisMediaStateConnected:
2034 /*
2035 * It's connected.
2036 */
2037 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2038 break;
2039
2040 case NdisMediaStateDisconnected:
2041 /*
2042 * It's disconnected.
2043 */
2044 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2045 break;
2046 }
2047 }
2048 }
2049 PacketCloseAdapter(adapter);
2050 return (0);
2051 }
2052
2053 int
2054 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2055 {
2056 int ret = 0;
2057 const char *desc;
2058 char *AdaptersName;
2059 ULONG NameLength;
2060 char *name;
2061
2062 /*
2063 * Find out how big a buffer we need.
2064 *
2065 * This call should always return FALSE; if the error is
2066 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2067 * the size of the buffer we need, otherwise there's a
2068 * problem, and NameLength should be set to 0.
2069 *
2070 * It shouldn't require NameLength to be set, but,
2071 * at least as of WinPcap 4.1.3, it checks whether
2072 * NameLength is big enough before it checks for a
2073 * NULL buffer argument, so, while it'll still do
2074 * the right thing if NameLength is uninitialized and
2075 * whatever junk happens to be there is big enough
2076 * (because the pointer argument will be null), it's
2077 * still reading an uninitialized variable.
2078 */
2079 NameLength = 0;
2080 if (!PacketGetAdapterNames(NULL, &NameLength))
2081 {
2082 DWORD last_error = GetLastError();
2083
2084 if (last_error != ERROR_INSUFFICIENT_BUFFER)
2085 {
2086 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2087 last_error, "PacketGetAdapterNames");
2088 return (-1);
2089 }
2090 }
2091
2092 if (NameLength <= 0)
2093 return 0;
2094 AdaptersName = (char*) malloc(NameLength);
2095 if (AdaptersName == NULL)
2096 {
2097 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
2098 return (-1);
2099 }
2100
2101 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
2102 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2103 GetLastError(), "PacketGetAdapterNames");
2104 free(AdaptersName);
2105 return (-1);
2106 }
2107
2108 /*
2109 * "PacketGetAdapterNames()" returned a list of
2110 * null-terminated ASCII interface name strings,
2111 * terminated by a null string, followed by a list
2112 * of null-terminated ASCII interface description
2113 * strings, terminated by a null string.
2114 * This means there are two ASCII nulls at the end
2115 * of the first list.
2116 *
2117 * Find the end of the first list; that's the
2118 * beginning of the second list.
2119 */
2120 desc = &AdaptersName[0];
2121 while (*desc != '\0' || *(desc + 1) != '\0')
2122 desc++;
2123
2124 /*
2125 * Found it - "desc" points to the first of the two
2126 * nulls at the end of the list of names, so the
2127 * first byte of the list of descriptions is two bytes
2128 * after it.
2129 */
2130 desc += 2;
2131
2132 /*
2133 * Loop over the elements in the first list.
2134 */
2135 name = &AdaptersName[0];
2136 while (*name != '\0') {
2137 bpf_u_int32 flags = 0;
2138
2139 #ifdef HAVE_AIRPCAP_API
2140 /*
2141 * Is this an AirPcap device?
2142 * If so, ignore it; it'll get added later, by the
2143 * AirPcap code.
2144 */
2145 if (device_is_airpcap(name, errbuf) == 1) {
2146 name += strlen(name) + 1;
2147 desc += strlen(desc) + 1;
2148 continue;
2149 }
2150 #endif
2151
2152 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2153 /*
2154 * Is this a loopback interface?
2155 */
2156 if (PacketIsLoopbackAdapter(name)) {
2157 /* Yes */
2158 flags |= PCAP_IF_LOOPBACK;
2159 }
2160 #endif
2161 /*
2162 * Get additional flags.
2163 */
2164 if (get_if_flags(name, &flags, errbuf) == -1) {
2165 /*
2166 * Failure.
2167 */
2168 ret = -1;
2169 break;
2170 }
2171
2172 /*
2173 * Add an entry for this interface.
2174 */
2175 if (pcap_add_if_npf(devlistp, name, flags, desc,
2176 errbuf) == -1) {
2177 /*
2178 * Failure.
2179 */
2180 ret = -1;
2181 break;
2182 }
2183 name += strlen(name) + 1;
2184 desc += strlen(desc) + 1;
2185 }
2186
2187 free(AdaptersName);
2188 return (ret);
2189 }
2190
2191 /*
2192 * Return the name of a network interface attached to the system, or NULL
2193 * if none can be found. The interface must be configured up; the
2194 * lowest unit number is preferred; loopback is ignored.
2195 *
2196 * In the best of all possible worlds, this would be the same as on
2197 * UN*X, but there may be software that expects this to return a
2198 * full list of devices after the first device.
2199 */
2200 #define ADAPTERSNAME_LEN 8192
2201 char *
2202 pcap_lookupdev(char *errbuf)
2203 {
2204 DWORD dwVersion;
2205 DWORD dwWindowsMajorVersion;
2206
2207 /*
2208 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2209 * it may return UTF-16 strings, for backwards-compatibility
2210 * reasons, and we're also disabling the hack to make that work,
2211 * for not-going-past-the-end-of-a-string reasons, and 2) we
2212 * want its behavior to be consistent.
2213 *
2214 * In addition, it's not thread-safe, so we've marked it as
2215 * deprecated.
2216 */
2217 if (pcap_new_api) {
2218 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2219 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2220 return (NULL);
2221 }
2222
2223 /* disable MSVC's GetVersion() deprecated warning here */
2224 DIAG_OFF_DEPRECATION
2225 dwVersion = GetVersion(); /* get the OS version */
2226 DIAG_ON_DEPRECATION
2227 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
2228
2229 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
2230 /*
2231 * Windows 95, 98, ME.
2232 */
2233 ULONG NameLength = ADAPTERSNAME_LEN;
2234 static char AdaptersName[ADAPTERSNAME_LEN];
2235
2236 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
2237 return (AdaptersName);
2238 else
2239 return NULL;
2240 } else {
2241 /*
2242 * Windows NT (NT 4.0 and later).
2243 * Convert the names to Unicode for backward compatibility.
2244 */
2245 ULONG NameLength = ADAPTERSNAME_LEN;
2246 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
2247 size_t BufferSpaceLeft;
2248 char *tAstr;
2249 WCHAR *Unameptr;
2250 char *Adescptr;
2251 size_t namelen, i;
2252 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
2253 int NAdapts = 0;
2254
2255 if(TAdaptersName == NULL)
2256 {
2257 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
2258 return NULL;
2259 }
2260
2261 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
2262 {
2263 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2264 GetLastError(), "PacketGetAdapterNames");
2265 free(TAdaptersName);
2266 return NULL;
2267 }
2268
2269
2270 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
2271 tAstr = (char*)TAdaptersName;
2272 Unameptr = AdaptersName;
2273
2274 /*
2275 * Convert the device names to Unicode into AdapterName.
2276 */
2277 do {
2278 /*
2279 * Length of the name, including the terminating
2280 * NUL.
2281 */
2282 namelen = strlen(tAstr) + 1;
2283
2284 /*
2285 * Do we have room for the name in the Unicode
2286 * buffer?
2287 */
2288 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
2289 /*
2290 * No.
2291 */
2292 goto quit;
2293 }
2294 BufferSpaceLeft -= namelen * sizeof(WCHAR);
2295
2296 /*
2297 * Copy the name, converting ASCII to Unicode.
2298 * namelen includes the NUL, so we copy it as
2299 * well.
2300 */
2301 for (i = 0; i < namelen; i++)
2302 *Unameptr++ = *tAstr++;
2303
2304 /*
2305 * Count this adapter.
2306 */
2307 NAdapts++;
2308 } while (namelen != 1);
2309
2310 /*
2311 * Copy the descriptions, but don't convert them from
2312 * ASCII to Unicode.
2313 */
2314 Adescptr = (char *)Unameptr;
2315 while(NAdapts--)
2316 {
2317 size_t desclen;
2318
2319 desclen = strlen(tAstr) + 1;
2320
2321 /*
2322 * Do we have room for the name in the Unicode
2323 * buffer?
2324 */
2325 if (BufferSpaceLeft < desclen) {
2326 /*
2327 * No.
2328 */
2329 goto quit;
2330 }
2331
2332 /*
2333 * Just copy the ASCII string.
2334 * namelen includes the NUL, so we copy it as
2335 * well.
2336 */
2337 memcpy(Adescptr, tAstr, desclen);
2338 Adescptr += desclen;
2339 tAstr += desclen;
2340 BufferSpaceLeft -= desclen;
2341 }
2342
2343 quit:
2344 free(TAdaptersName);
2345 return (char *)(AdaptersName);
2346 }
2347 }
2348
2349 /*
2350 * We can't use the same code that we use on UN*X, as that's doing
2351 * UN*X-specific calls.
2352 *
2353 * We don't just fetch the entire list of devices, search for the
2354 * particular device, and use its first IPv4 address, as that's too
2355 * much work to get just one device's netmask.
2356 */
2357 int
2358 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
2359 char *errbuf)
2360 {
2361 /*
2362 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2363 * in order to skip non IPv4 (i.e. IPv6 addresses)
2364 */
2365 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2366 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
2367 struct sockaddr_in *t_addr;
2368 LONG i;
2369
2370 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
2371 *netp = *maskp = 0;
2372 return (0);
2373 }
2374
2375 for(i = 0; i < if_addr_size; i++)
2376 {
2377 if(if_addrs[i].IPAddress.ss_family == AF_INET)
2378 {
2379 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
2380 *netp = t_addr->sin_addr.S_un.S_addr;
2381 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
2382 *maskp = t_addr->sin_addr.S_un.S_addr;
2383
2384 *netp &= *maskp;
2385 return (0);
2386 }
2387
2388 }
2389
2390 *netp = *maskp = 0;
2391 return (0);
2392 }
2393
2394 static const char *pcap_lib_version_string;
2395
2396 #ifdef HAVE_VERSION_H
2397 /*
2398 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2399 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2400 * version.
2401 *
2402 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2403 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2404 * for the packet.dll version number as well.)
2405 */
2406 #include "../../version.h"
2407
2408 static const char pcap_version_string[] =
2409 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2410
2411 const char *
2412 pcap_lib_version(void)
2413 {
2414 if (pcap_lib_version_string == NULL) {
2415 /*
2416 * Generate the version string.
2417 */
2418 const char *packet_version_string = PacketGetVersion();
2419
2420 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2421 /*
2422 * WinPcap/Npcap version string and packet.dll version
2423 * string are the same; just report the WinPcap/Npcap
2424 * version.
2425 */
2426 pcap_lib_version_string = pcap_version_string;
2427 } else {
2428 /*
2429 * WinPcap/Npcap version string and packet.dll version
2430 * string are different; that shouldn't be the
2431 * case (the two libraries should come from the
2432 * same version of WinPcap/Npcap), so we report both
2433 * versions.
2434 */
2435 char *full_pcap_version_string;
2436
2437 if (pcap_asprintf(&full_pcap_version_string,
2438 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING,
2439 packet_version_string) != -1) {
2440 /* Success */
2441 pcap_lib_version_string = full_pcap_version_string;
2442 }
2443 }
2444 }
2445 return (pcap_lib_version_string);
2446 }
2447
2448 #else /* HAVE_VERSION_H */
2449
2450 /*
2451 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2452 * tree.
2453 */
2454 const char *
2455 pcap_lib_version(void)
2456 {
2457 if (pcap_lib_version_string == NULL) {
2458 /*
2459 * Generate the version string. Report the packet.dll
2460 * version.
2461 */
2462 char *full_pcap_version_string;
2463
2464 if (pcap_asprintf(&full_pcap_version_string,
2465 PCAP_VERSION_STRING " (packet.dll version %s)",
2466 PacketGetVersion()) != -1) {
2467 /* Success */
2468 pcap_lib_version_string = full_pcap_version_string;
2469 }
2470 }
2471 return (pcap_lib_version_string);
2472 }
2473 #endif /* HAVE_VERSION_H */