]> The Tcpdump Group git mirrors - libpcap/blob - pcap-npf.c
Revert "findalldevstest: temporary test to see if this squelches Valgrind warnings."
[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 #ifdef HAVE_NPCAP_PACKET_API
449 /*
450 * Kernel dump mode isn't supported in Npcap; calls to PacketSetDumpName(),
451 * PacketSetDumpLimits(), and PacketIsDumpEnded() will get compile-time
452 * deprecation warnings.
453 *
454 * Avoid calling them; just return errors indicating that kernel dump
455 * mode isn't supported in Npcap.
456 */
457 static int
458 pcap_live_dump_npf(pcap_t *p, char *filename _U_, int maxsize _U_,
459 int maxpacks _U_)
460 {
461 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
462 "Npcap doesn't support kernel dump mode");
463 return (-1);
464 }
465 static int
466 pcap_live_dump_ended_npf(pcap_t *p, int sync)
467 {
468 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
469 "Npcap doesn't support kernel dump mode");
470 return (-1);
471 }
472 #else /* HAVE_NPCAP_PACKET_API */
473 static int
474 pcap_live_dump_npf(pcap_t *p, char *filename, int maxsize, int maxpacks)
475 {
476 struct pcap_win *pw = p->priv;
477 BOOLEAN res;
478
479 /* Set the packet driver in dump mode */
480 res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
481 if(res == FALSE){
482 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
483 "Error setting dump mode");
484 return (-1);
485 }
486
487 /* Set the name of the dump file */
488 res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
489 if(res == FALSE){
490 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
491 "Error setting kernel dump file name");
492 return (-1);
493 }
494
495 /* Set the limits of the dump file */
496 res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
497 if(res == FALSE) {
498 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
499 "Error setting dump limit");
500 return (-1);
501 }
502
503 return (0);
504 }
505
506 static int
507 pcap_live_dump_ended_npf(pcap_t *p, int sync)
508 {
509 struct pcap_win *pw = p->priv;
510
511 return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
512 }
513 #endif /* HAVE_NPCAP_PACKET_API */
514
515 #ifdef HAVE_AIRPCAP_API
516 static PAirpcapHandle
517 pcap_get_airpcap_handle_npf(pcap_t *p)
518 {
519 struct pcap_win *pw = p->priv;
520
521 return (PacketGetAirPcapHandle(pw->adapter));
522 }
523 #else /* HAVE_AIRPCAP_API */
524 static PAirpcapHandle
525 pcap_get_airpcap_handle_npf(pcap_t *p _U_)
526 {
527 return (NULL);
528 }
529 #endif /* HAVE_AIRPCAP_API */
530
531 static int
532 pcap_read_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
533 {
534 PACKET Packet;
535 int cc;
536 int n;
537 register u_char *bp, *ep;
538 u_char *datap;
539 struct pcap_win *pw = p->priv;
540
541 cc = p->cc;
542 if (cc == 0) {
543 /*
544 * Has "pcap_breakloop()" been called?
545 */
546 if (p->break_loop) {
547 /*
548 * Yes - clear the flag that indicates that it
549 * has, and return PCAP_ERROR_BREAK to indicate
550 * that we were told to break out of the loop.
551 */
552 p->break_loop = 0;
553 return (PCAP_ERROR_BREAK);
554 }
555
556 /*
557 * Capture the packets.
558 *
559 * The PACKET structure had a bunch of extra stuff for
560 * Windows 9x/Me, but the only interesting data in it
561 * in the versions of Windows that we support is just
562 * a copy of p->buffer, a copy of p->buflen, and the
563 * actual number of bytes read returned from
564 * PacketReceivePacket(), none of which has to be
565 * retained from call to call, so we just keep one on
566 * the stack.
567 */
568 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
569 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
570 /*
571 * Did the device go away?
572 * If so, the error we get can either be
573 * ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
574 */
575 DWORD errcode = GetLastError();
576
577 if (errcode == ERROR_GEN_FAILURE ||
578 errcode == ERROR_DEVICE_REMOVED) {
579 /*
580 * The device on which we're capturing
581 * went away, or it became unusable
582 * by NPF due to a suspend/resume.
583 *
584 * ERROR_GEN_FAILURE comes from
585 * STATUS_UNSUCCESSFUL, as well as some
586 * other NT status codes that the Npcap
587 * driver is unlikely to return.
588 * XXX - hopefully no other error
589 * conditions are indicated by this.
590 *
591 * ERROR_DEVICE_REMOVED comes from
592 * STATUS_DEVICE_REMOVED.
593 *
594 * We report the Windows status code
595 * name and the corresponding NT status
596 * code name, for the benefit of attempts
597 * to debug cases where this error is
598 * reported when the device *wasn't*
599 * removed, either because it's not
600 * removable, it's removable but wasn't
601 * removed, or it's a device that doesn't
602 * correspond to a physical device.
603 *
604 * XXX - we really should return an
605 * appropriate error for that, but
606 * pcap_dispatch() etc. aren't
607 * documented as having error returns
608 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
609 */
610 const char *errcode_msg;
611
612 if (errcode == ERROR_GEN_FAILURE)
613 errcode_msg = "ERROR_GEN_FAILURE/STATUS_UNSUCCESSFUL";
614 else
615 errcode_msg = "ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED";
616 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
617 "The interface disappeared (error code %s)",
618 errcode_msg);
619 } else {
620 pcap_fmt_errmsg_for_win32_err(p->errbuf,
621 PCAP_ERRBUF_SIZE, errcode,
622 "PacketReceivePacket error");
623 }
624 return (PCAP_ERROR);
625 }
626
627 cc = Packet.ulBytesReceived;
628
629 bp = p->buffer;
630 }
631 else
632 bp = p->bp;
633
634 /*
635 * Loop through each packet.
636 */
637 #define bhp ((struct bpf_hdr *)bp)
638 n = 0;
639 ep = bp + cc;
640 for (;;) {
641 register u_int caplen, hdrlen;
642
643 /*
644 * Has "pcap_breakloop()" been called?
645 * If so, return immediately - if we haven't read any
646 * packets, clear the flag and return PCAP_ERROR_BREAK
647 * to indicate that we were told to break out of the loop,
648 * otherwise leave the flag set, so that the *next* call
649 * will break out of the loop without having read any
650 * packets, and return the number of packets we've
651 * processed so far.
652 */
653 if (p->break_loop) {
654 if (n == 0) {
655 p->break_loop = 0;
656 return (PCAP_ERROR_BREAK);
657 } else {
658 p->bp = bp;
659 p->cc = (int) (ep - bp);
660 return (n);
661 }
662 }
663 if (bp >= ep)
664 break;
665
666 caplen = bhp->bh_caplen;
667 hdrlen = bhp->bh_hdrlen;
668 datap = bp + hdrlen;
669
670 /*
671 * Short-circuit evaluation: if using BPF filter
672 * in kernel, no need to do it now - we already know
673 * the packet passed the filter.
674 *
675 * XXX - pcap_filter() should always return TRUE if
676 * handed a null pointer for the program, but it might
677 * just try to "run" the filter, so we check here.
678 */
679 if (pw->filtering_in_kernel ||
680 p->fcode.bf_insns == NULL ||
681 pcap_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
682 #ifdef ENABLE_REMOTE
683 switch (p->rmt_samp.method) {
684
685 case PCAP_SAMP_1_EVERY_N:
686 pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
687
688 /* Discard all packets that are not '1 out of N' */
689 if (pw->samp_npkt != 0) {
690 bp += Packet_WORDALIGN(caplen + hdrlen);
691 continue;
692 }
693 break;
694
695 case PCAP_SAMP_FIRST_AFTER_N_MS:
696 {
697 struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
698
699 /*
700 * Check if the timestamp of the arrived
701 * packet is smaller than our target time.
702 */
703 if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
704 (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
705 bp += Packet_WORDALIGN(caplen + hdrlen);
706 continue;
707 }
708
709 /*
710 * The arrived packet is suitable for being
711 * delivered to our caller, so let's update
712 * the target time.
713 */
714 pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
715 if (pw->samp_time.tv_usec > 1000000) {
716 pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
717 pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
718 }
719 }
720 }
721 #endif /* ENABLE_REMOTE */
722
723 /*
724 * XXX A bpf_hdr matches a pcap_pkthdr.
725 */
726 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
727 bp += Packet_WORDALIGN(caplen + hdrlen);
728 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
729 p->bp = bp;
730 p->cc = (int) (ep - bp);
731 return (n);
732 }
733 } else {
734 /*
735 * Skip this packet.
736 */
737 bp += Packet_WORDALIGN(caplen + hdrlen);
738 }
739 }
740 #undef bhp
741 p->cc = 0;
742 return (n);
743 }
744
745 #ifdef HAVE_DAG_API
746 static int
747 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
748 {
749 struct pcap_win *pw = p->priv;
750 PACKET Packet;
751 u_char *dp = NULL;
752 int packet_len = 0, caplen = 0;
753 struct pcap_pkthdr pcap_header;
754 u_char *endofbuf;
755 int n = 0;
756 dag_record_t *header;
757 unsigned erf_record_len;
758 ULONGLONG ts;
759 int cc;
760 unsigned swt;
761 unsigned dfp = pw->adapter->DagFastProcess;
762
763 cc = p->cc;
764 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
765 {
766 /*
767 * Get new packets from the network.
768 *
769 * The PACKET structure had a bunch of extra stuff for
770 * Windows 9x/Me, but the only interesting data in it
771 * in the versions of Windows that we support is just
772 * a copy of p->buffer, a copy of p->buflen, and the
773 * actual number of bytes read returned from
774 * PacketReceivePacket(), none of which has to be
775 * retained from call to call, so we just keep one on
776 * the stack.
777 */
778 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
779 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
780 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
781 return (-1);
782 }
783
784 cc = Packet.ulBytesReceived;
785 if(cc == 0)
786 /* The timeout has expired but we no packets arrived */
787 return (0);
788 header = (dag_record_t*)pw->adapter->DagBuffer;
789 }
790 else
791 header = (dag_record_t*)p->bp;
792
793 endofbuf = (char*)header + cc;
794
795 /*
796 * Cycle through the packets
797 */
798 do
799 {
800 erf_record_len = SWAPS(header->rlen);
801 if((char*)header + erf_record_len > endofbuf)
802 break;
803
804 /* Increase the number of captured packets */
805 p->stat.ps_recv++;
806
807 /* Find the beginning of the packet */
808 dp = ((u_char *)header) + dag_record_size;
809
810 /* Determine actual packet len */
811 switch(header->type)
812 {
813 case TYPE_ATM:
814 packet_len = ATM_SNAPLEN;
815 caplen = ATM_SNAPLEN;
816 dp += 4;
817
818 break;
819
820 case TYPE_ETH:
821 swt = SWAPS(header->wlen);
822 packet_len = swt - (pw->dag_fcs_bits);
823 caplen = erf_record_len - dag_record_size - 2;
824 if (caplen > packet_len)
825 {
826 caplen = packet_len;
827 }
828 dp += 2;
829
830 break;
831
832 case TYPE_HDLC_POS:
833 swt = SWAPS(header->wlen);
834 packet_len = swt - (pw->dag_fcs_bits);
835 caplen = erf_record_len - dag_record_size;
836 if (caplen > packet_len)
837 {
838 caplen = packet_len;
839 }
840
841 break;
842 }
843
844 if(caplen > p->snapshot)
845 caplen = p->snapshot;
846
847 /*
848 * Has "pcap_breakloop()" been called?
849 * If so, return immediately - if we haven't read any
850 * packets, clear the flag and return -2 to indicate
851 * that we were told to break out of the loop, otherwise
852 * leave the flag set, so that the *next* call will break
853 * out of the loop without having read any packets, and
854 * return the number of packets we've processed so far.
855 */
856 if (p->break_loop)
857 {
858 if (n == 0)
859 {
860 p->break_loop = 0;
861 return (-2);
862 }
863 else
864 {
865 p->bp = (char*)header;
866 p->cc = endofbuf - (char*)header;
867 return (n);
868 }
869 }
870
871 if(!dfp)
872 {
873 /* convert between timestamp formats */
874 ts = header->ts;
875 pcap_header.ts.tv_sec = (int)(ts >> 32);
876 ts = (ts & 0xffffffffi64) * 1000000;
877 ts += 0x80000000; /* rounding */
878 pcap_header.ts.tv_usec = (int)(ts >> 32);
879 if (pcap_header.ts.tv_usec >= 1000000) {
880 pcap_header.ts.tv_usec -= 1000000;
881 pcap_header.ts.tv_sec++;
882 }
883 }
884
885 /* No underlaying filtering system. We need to filter on our own */
886 if (p->fcode.bf_insns)
887 {
888 if (pcap_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
889 {
890 /* Move to next packet */
891 header = (dag_record_t*)((char*)header + erf_record_len);
892 continue;
893 }
894 }
895
896 /* Fill the header for the user suppplied callback function */
897 pcap_header.caplen = caplen;
898 pcap_header.len = packet_len;
899
900 /* Call the callback function */
901 (*callback)(user, &pcap_header, dp);
902
903 /* Move to next packet */
904 header = (dag_record_t*)((char*)header + erf_record_len);
905
906 /* Stop if the number of packets requested by user has been reached*/
907 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
908 {
909 p->bp = (char*)header;
910 p->cc = endofbuf - (char*)header;
911 return (n);
912 }
913 }
914 while((u_char*)header < endofbuf);
915
916 return (1);
917 }
918 #endif /* HAVE_DAG_API */
919
920 /* Send a packet to the network */
921 static int
922 pcap_inject_npf(pcap_t *p, const void *buf, int size)
923 {
924 struct pcap_win *pw = p->priv;
925 PACKET pkt;
926
927 PacketInitPacket(&pkt, (PVOID)buf, size);
928 if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
929 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
930 GetLastError(), "send error: PacketSendPacket failed");
931 return (-1);
932 }
933
934 /*
935 * We assume it all got sent if "PacketSendPacket()" succeeded.
936 * "pcap_inject()" is expected to return the number of bytes
937 * sent.
938 */
939 return (size);
940 }
941
942 static void
943 pcap_cleanup_npf(pcap_t *p)
944 {
945 struct pcap_win *pw = p->priv;
946
947 if (pw->adapter != NULL) {
948 PacketCloseAdapter(pw->adapter);
949 pw->adapter = NULL;
950 }
951 if (pw->rfmon_selfstart)
952 {
953 PacketSetMonitorMode(p->opt.device, 0);
954 }
955 pcap_cleanup_live_common(p);
956 }
957
958 static void
959 pcap_breakloop_npf(pcap_t *p)
960 {
961 pcap_breakloop_common(p);
962 struct pcap_win *pw = p->priv;
963
964 /* XXX - what if this fails? */
965 SetEvent(PacketGetReadEvent(pw->adapter));
966 }
967
968 /*
969 * Vendor-specific error codes.
970 *
971 * These are NTSTATUS values:
972 *
973 * https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/87fba13e-bf06-450e-83b1-9241dc81e781
974 *
975 * with the "Customer" bit set. If a driver returns them, they are not
976 * mapped to Windows error values in userland; they're returned by
977 * GetLastError().
978 *
979 * Attempting to set non-promiscuous mode on a Microsoft Surface Pro's
980 * Mobile Broadband Adapter returns an error; that error can safely be
981 * ignored, as it's always in non-promiscuous mode.
982 *
983 * It is likely that there are other devices which throw spurious errors,
984 * at which point this will need refactoring to efficiently check against
985 * a list, but for now we can just check this one value.
986 */
987 #define NPF_SURFACE_MOBILE_NONPROMISC 0xe00000bb
988
989 static int
990 pcap_activate_npf(pcap_t *p)
991 {
992 struct pcap_win *pw = p->priv;
993 NetType type;
994 int res;
995 int status = 0;
996 struct bpf_insn total_insn;
997 struct bpf_program total_prog;
998
999 if (p->opt.rfmon) {
1000 /*
1001 * Monitor mode is supported on Windows Vista and later.
1002 */
1003 if (PacketGetMonitorMode(p->opt.device) == 1)
1004 {
1005 pw->rfmon_selfstart = 0;
1006 }
1007 else
1008 {
1009 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
1010 {
1011 pw->rfmon_selfstart = 0;
1012 // Monitor mode is not supported.
1013 if (res == 0)
1014 {
1015 return PCAP_ERROR_RFMON_NOTSUP;
1016 }
1017 else
1018 {
1019 return PCAP_ERROR;
1020 }
1021 }
1022 else
1023 {
1024 pw->rfmon_selfstart = 1;
1025 }
1026 }
1027 }
1028
1029 /* Init Winsock if it hasn't already been initialized */
1030 pcap_wsockinit();
1031
1032 pw->adapter = PacketOpenAdapter(p->opt.device);
1033
1034 if (pw->adapter == NULL)
1035 {
1036 DWORD errcode = GetLastError();
1037
1038 /*
1039 * What error did we get when trying to open the adapter?
1040 */
1041 switch (errcode) {
1042
1043 case ERROR_BAD_UNIT:
1044 /*
1045 * There's no such device.
1046 */
1047 return (PCAP_ERROR_NO_SUCH_DEVICE);
1048
1049 case ERROR_ACCESS_DENIED:
1050 /*
1051 * There is, but we don't have permission to
1052 * use it.
1053 */
1054 return (PCAP_ERROR_PERM_DENIED);
1055
1056 default:
1057 /*
1058 * Unknown - report details.
1059 */
1060 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1061 errcode, "Error opening adapter");
1062 if (pw->rfmon_selfstart)
1063 {
1064 PacketSetMonitorMode(p->opt.device, 0);
1065 }
1066 return (PCAP_ERROR);
1067 }
1068 }
1069
1070 /*get network type*/
1071 if(PacketGetNetType (pw->adapter,&type) == FALSE)
1072 {
1073 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1074 GetLastError(), "Cannot determine the network type");
1075 goto bad;
1076 }
1077
1078 /*Set the linktype*/
1079 switch (type.LinkType)
1080 {
1081 /*
1082 * NDIS-defined medium types.
1083 */
1084 case NdisMedium802_3:
1085 p->linktype = DLT_EN10MB;
1086 /*
1087 * This is (presumably) a real Ethernet capture; give it a
1088 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1089 * that an application can let you choose it, in case you're
1090 * capturing DOCSIS traffic that a Cisco Cable Modem
1091 * Termination System is putting out onto an Ethernet (it
1092 * doesn't put an Ethernet header onto the wire, it puts raw
1093 * DOCSIS frames out on the wire inside the low-level
1094 * Ethernet framing).
1095 */
1096 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1097 /*
1098 * If that fails, just leave the list empty.
1099 */
1100 if (p->dlt_list != NULL) {
1101 p->dlt_list[0] = DLT_EN10MB;
1102 p->dlt_list[1] = DLT_DOCSIS;
1103 p->dlt_count = 2;
1104 }
1105 break;
1106
1107 case NdisMedium802_5:
1108 /*
1109 * Token Ring.
1110 */
1111 p->linktype = DLT_IEEE802;
1112 break;
1113
1114 case NdisMediumFddi:
1115 p->linktype = DLT_FDDI;
1116 break;
1117
1118 case NdisMediumWan:
1119 p->linktype = DLT_EN10MB;
1120 break;
1121
1122 case NdisMediumArcnetRaw:
1123 p->linktype = DLT_ARCNET;
1124 break;
1125
1126 case NdisMediumArcnet878_2:
1127 p->linktype = DLT_ARCNET;
1128 break;
1129
1130 case NdisMediumAtm:
1131 p->linktype = DLT_ATM_RFC1483;
1132 break;
1133
1134 case NdisMediumWirelessWan:
1135 p->linktype = DLT_RAW;
1136 break;
1137
1138 case NdisMediumIP:
1139 p->linktype = DLT_RAW;
1140 break;
1141
1142 /*
1143 * Npcap-defined medium types.
1144 */
1145 case NdisMediumNull:
1146 p->linktype = DLT_NULL;
1147 break;
1148
1149 case NdisMediumCHDLC:
1150 p->linktype = DLT_CHDLC;
1151 break;
1152
1153 case NdisMediumPPPSerial:
1154 p->linktype = DLT_PPP_SERIAL;
1155 break;
1156
1157 case NdisMediumBare80211:
1158 p->linktype = DLT_IEEE802_11;
1159 break;
1160
1161 case NdisMediumRadio80211:
1162 p->linktype = DLT_IEEE802_11_RADIO;
1163 break;
1164
1165 case NdisMediumPpi:
1166 p->linktype = DLT_PPI;
1167 break;
1168
1169 default:
1170 /*
1171 * An unknown medium type is assumed to supply Ethernet
1172 * headers; if not, the user will have to report it,
1173 * so that the medium type and link-layer header type
1174 * can be determined. If we were to fail here, we
1175 * might get the link-layer type in the error, but
1176 * the user wouldn't get a capture, so we wouldn't
1177 * be able to determine the link-layer type; we report
1178 * a warning with the link-layer type, so at least
1179 * some programs will report the warning.
1180 */
1181 p->linktype = DLT_EN10MB;
1182 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1183 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1184 type.LinkType);
1185 status = PCAP_WARNING;
1186 break;
1187 }
1188
1189 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1190 /*
1191 * Set the timestamp type.
1192 * (Yes, we require PacketGetTimestampModes(), not just
1193 * PacketSetTimestampMode(). If we have the former, we
1194 * have the latter, unless somebody's using a version
1195 * of Npcap that they've hacked to provide the former
1196 * but not the latter; if they've done that, either
1197 * they're confused or they're trolling us.)
1198 */
1199 switch (p->opt.tstamp_type) {
1200
1201 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED:
1202 /*
1203 * Better than low-res, but *not* synchronized with
1204 * the OS clock.
1205 */
1206 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION))
1207 {
1208 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1209 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1210 goto bad;
1211 }
1212 break;
1213
1214 case PCAP_TSTAMP_HOST_LOWPREC:
1215 /*
1216 * Low-res, but synchronized with the OS clock.
1217 */
1218 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME))
1219 {
1220 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1221 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1222 goto bad;
1223 }
1224 break;
1225
1226 case PCAP_TSTAMP_HOST_HIPREC:
1227 /*
1228 * High-res, and synchronized with the OS clock.
1229 */
1230 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE))
1231 {
1232 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1233 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1234 goto bad;
1235 }
1236 break;
1237
1238 case PCAP_TSTAMP_HOST:
1239 /*
1240 * XXX - do whatever the default is, for now.
1241 * Set to the highest resolution that's synchronized
1242 * with the system clock?
1243 */
1244 break;
1245 }
1246 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1247
1248 /*
1249 * Turn a negative snapshot value (invalid), a snapshot value of
1250 * 0 (unspecified), or a value bigger than the normal maximum
1251 * value, into the maximum allowed value.
1252 *
1253 * If some application really *needs* a bigger snapshot
1254 * length, we should just increase MAXIMUM_SNAPLEN.
1255 */
1256 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1257 p->snapshot = MAXIMUM_SNAPLEN;
1258
1259 /* Set promiscuous mode */
1260 if (p->opt.promisc)
1261 {
1262
1263 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1264 {
1265 DWORD errcode = GetLastError();
1266
1267 /*
1268 * Suppress spurious error generated by non-compiant
1269 * MS Surface mobile adapters.
1270 *
1271 * If we knew that this meant "promiscuous mode
1272 * isn't supported", we could add a "promiscuous
1273 * mode isn't supported" error code and return
1274 * that, but:
1275 *
1276 * 1) we don't know that it means that
1277 * rather than meaning "we reject attempts
1278 * to set the filter, even though the NDIS
1279 * specifications say you shouldn't do that"
1280 *
1281 * and
1282 *
1283 * 2) other interface types that don't
1284 * support promiscuous mode, at least
1285 * on UN*Xes, just silently ignore
1286 * attempts to set promiscuous mode
1287 *
1288 * and rejecting it with an error could disrupt
1289 * attempts to capture, as many programs (tcpdump,
1290 * *shark) default to promiscuous mode.
1291 */
1292 if (errcode != NPF_SURFACE_MOBILE_NONPROMISC)
1293 {
1294 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1295 PCAP_ERRBUF_SIZE, errcode,
1296 "failed to set hardware filter to promiscuous mode");
1297 goto bad;
1298 }
1299 }
1300 }
1301 else
1302 {
1303 /*
1304 * NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by
1305 * installed protocols and all packets indicated by the NIC",
1306 * but if no protocol drivers (like TCP/IP) are installed,
1307 * NDIS_PACKET_TYPE_DIRECTED, NDIS_PACKET_TYPE_BROADCAST,
1308 * and NDIS_PACKET_TYPE_MULTICAST are needed to capture
1309 * incoming frames.
1310 */
1311 if (PacketSetHwFilter(pw->adapter,
1312 NDIS_PACKET_TYPE_ALL_LOCAL |
1313 NDIS_PACKET_TYPE_DIRECTED |
1314 NDIS_PACKET_TYPE_BROADCAST |
1315 NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1316 {
1317 DWORD errcode = GetLastError();
1318
1319 /*
1320 * Suppress spurious error generated by non-compiant
1321 * MS Surface mobile adapters.
1322 */
1323 if (errcode != NPF_SURFACE_MOBILE_NONPROMISC)
1324 {
1325 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1326 PCAP_ERRBUF_SIZE, errcode,
1327 "failed to set hardware filter to non-promiscuous mode");
1328 goto bad;
1329 }
1330 }
1331 }
1332
1333 /* Set the buffer size */
1334 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1335
1336 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1337 {
1338 /*
1339 * Traditional Adapter
1340 */
1341 /*
1342 * If the buffer size wasn't explicitly set, default to
1343 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1344 */
1345 if (p->opt.buffer_size == 0)
1346 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1347
1348 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1349 {
1350 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1351 goto bad;
1352 }
1353
1354 p->buffer = malloc(p->bufsize);
1355 if (p->buffer == NULL)
1356 {
1357 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1358 errno, "malloc");
1359 goto bad;
1360 }
1361
1362 if (p->opt.immediate)
1363 {
1364 /* tell the driver to copy the buffer as soon as data arrives */
1365 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1366 {
1367 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1368 PCAP_ERRBUF_SIZE, GetLastError(),
1369 "Error calling PacketSetMinToCopy");
1370 goto bad;
1371 }
1372 }
1373 else
1374 {
1375 /* tell the driver to copy the buffer only if it contains at least 16K */
1376 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1377 {
1378 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1379 PCAP_ERRBUF_SIZE, GetLastError(),
1380 "Error calling PacketSetMinToCopy");
1381 goto bad;
1382 }
1383 }
1384 } else {
1385 /*
1386 * Dag Card
1387 */
1388 #ifdef HAVE_DAG_API
1389 /*
1390 * We have DAG support.
1391 */
1392 LONG status;
1393 HKEY dagkey;
1394 DWORD lptype;
1395 DWORD lpcbdata;
1396 int postype = 0;
1397 char keyname[512];
1398
1399 snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1400 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1401 strstr(_strlwr(p->opt.device), "dag"));
1402 do
1403 {
1404 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1405 if(status != ERROR_SUCCESS)
1406 break;
1407
1408 status = RegQueryValueEx(dagkey,
1409 "PosType",
1410 NULL,
1411 &lptype,
1412 (char*)&postype,
1413 &lpcbdata);
1414
1415 if(status != ERROR_SUCCESS)
1416 {
1417 postype = 0;
1418 }
1419
1420 RegCloseKey(dagkey);
1421 }
1422 while(FALSE);
1423
1424
1425 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1426
1427 /* Set the length of the FCS associated to any packet. This value
1428 * will be subtracted to the packet length */
1429 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1430 #else /* HAVE_DAG_API */
1431 /*
1432 * No DAG support.
1433 */
1434 goto bad;
1435 #endif /* HAVE_DAG_API */
1436 }
1437
1438 /*
1439 * If there's no filter program installed, there's
1440 * no indication to the kernel of what the snapshot
1441 * length should be, so no snapshotting is done.
1442 *
1443 * Therefore, when we open the device, we install
1444 * an "accept everything" filter with the specified
1445 * snapshot length.
1446 */
1447 total_insn.code = (u_short)(BPF_RET | BPF_K);
1448 total_insn.jt = 0;
1449 total_insn.jf = 0;
1450 total_insn.k = p->snapshot;
1451
1452 total_prog.bf_len = 1;
1453 total_prog.bf_insns = &total_insn;
1454 if (!PacketSetBpf(pw->adapter, &total_prog)) {
1455 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1456 GetLastError(), "PacketSetBpf");
1457 status = PCAP_ERROR;
1458 goto bad;
1459 }
1460
1461 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1462
1463 /* disable loopback capture if requested */
1464 if (p->opt.nocapture_local)
1465 {
1466 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1467 {
1468 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1469 "Unable to disable the capture of loopback packets.");
1470 goto bad;
1471 }
1472 }
1473
1474 #ifdef HAVE_DAG_API
1475 if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1476 {
1477 /* install dag specific handlers for read and setfilter */
1478 p->read_op = pcap_read_win32_dag;
1479 p->setfilter_op = pcap_setfilter_win32_dag;
1480 }
1481 else
1482 {
1483 #endif /* HAVE_DAG_API */
1484 /* install traditional npf handlers for read and setfilter */
1485 p->read_op = pcap_read_npf;
1486 p->setfilter_op = pcap_setfilter_npf;
1487 #ifdef HAVE_DAG_API
1488 }
1489 #endif /* HAVE_DAG_API */
1490 p->setdirection_op = NULL; /* Not implemented. */
1491 /* XXX - can this be implemented on some versions of Windows? */
1492 p->inject_op = pcap_inject_npf;
1493 p->set_datalink_op = NULL; /* can't change data link type */
1494 p->getnonblock_op = pcap_getnonblock_npf;
1495 p->setnonblock_op = pcap_setnonblock_npf;
1496 p->stats_op = pcap_stats_npf;
1497 p->breakloop_op = pcap_breakloop_npf;
1498 p->stats_ex_op = pcap_stats_ex_npf;
1499 p->setbuff_op = pcap_setbuff_npf;
1500 p->setmode_op = pcap_setmode_npf;
1501 p->setmintocopy_op = pcap_setmintocopy_npf;
1502 p->getevent_op = pcap_getevent_npf;
1503 p->oid_get_request_op = pcap_oid_get_request_npf;
1504 p->oid_set_request_op = pcap_oid_set_request_npf;
1505 p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1506 p->setuserbuffer_op = pcap_setuserbuffer_npf;
1507 p->live_dump_op = pcap_live_dump_npf;
1508 p->live_dump_ended_op = pcap_live_dump_ended_npf;
1509 p->get_airpcap_handle_op = pcap_get_airpcap_handle_npf;
1510 p->cleanup_op = pcap_cleanup_npf;
1511
1512 /*
1513 * XXX - this is only done because WinPcap supported
1514 * pcap_fileno() returning the hFile HANDLE from the
1515 * ADAPTER structure. We make no general guarantees
1516 * that the caller can do anything useful with it.
1517 *
1518 * (Not that we make any general guarantee of that
1519 * sort on UN*X, either, any more, given that not
1520 * all capture devices are regular OS network
1521 * interfaces.)
1522 */
1523 p->handle = pw->adapter->hFile;
1524
1525 return (status);
1526 bad:
1527 pcap_cleanup_npf(p);
1528 return (PCAP_ERROR);
1529 }
1530
1531 /*
1532 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1533 */
1534 static int
1535 pcap_can_set_rfmon_npf(pcap_t *p)
1536 {
1537 return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1538 }
1539
1540 pcap_t *
1541 pcap_create_interface(const char *device _U_, char *ebuf)
1542 {
1543 pcap_t *p;
1544 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1545 char *device_copy = NULL;
1546 ADAPTER *adapter = NULL;
1547 ULONG num_ts_modes;
1548 BOOL ret;
1549 DWORD error = ERROR_SUCCESS;
1550 ULONG *modes = NULL;
1551 #endif
1552
1553 p = PCAP_CREATE_COMMON(ebuf, struct pcap_win);
1554 if (p == NULL)
1555 return (NULL);
1556
1557 p->activate_op = pcap_activate_npf;
1558 p->can_set_rfmon_op = pcap_can_set_rfmon_npf;
1559
1560 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1561 do {
1562 /* Must fill out ebuf to signal an error at end of do/while */
1563 ebuf[0] = '\0';
1564 /*
1565 * First, find out how many time stamp modes we have.
1566 * To do that, we have to open the adapter.
1567 *
1568 * XXX - PacketOpenAdapter() takes a non-const pointer
1569 * as an argument, so we make a copy of the argument and
1570 * pass that to it.
1571 */
1572 device_copy = strdup(device);
1573 if (device_copy == NULL) {
1574 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1575 break;
1576 }
1577
1578 adapter = PacketOpenAdapter(device_copy);
1579 if (adapter == NULL)
1580 {
1581 error = GetLastError();
1582 /* If we can't open the device now, we won't be able to later, either. */
1583 pcap_fmt_errmsg_for_win32_err(ebuf, PCAP_ERRBUF_SIZE,
1584 error, "Error opening adapter");
1585 break;
1586 }
1587 /*
1588 * Get the total number of time stamp modes.
1589 *
1590 * The buffer for PacketGetTimestampModes() is
1591 * a sequence of 1 or more ULONGs. What's
1592 * passed to PacketGetTimestampModes() should have
1593 * the total number of ULONGs in the first ULONG;
1594 * what's returned *from* PacketGetTimestampModes()
1595 * has the total number of time stamp modes in
1596 * the first ULONG.
1597 *
1598 * Yes, that means if there are N time stamp
1599 * modes, the first ULONG should be set to N+1
1600 * on input, and will be set to N on output.
1601 *
1602 * We first make a call to PacketGetTimestampModes()
1603 * with a pointer to a single ULONG set to 1; the
1604 * call should fail with ERROR_MORE_DATA (unless
1605 * there are *no* modes, but that should never
1606 * happen), and that ULONG should be set to the
1607 * number of modes.
1608 */
1609 num_ts_modes = 1;
1610 ret = PacketGetTimestampModes(adapter, &num_ts_modes);
1611 if (!ret) {
1612 /*
1613 * OK, it failed. Did it fail with
1614 * ERROR_MORE_DATA?
1615 */
1616 error = GetLastError();
1617 if (error != ERROR_MORE_DATA) {
1618 /*
1619 * No, did it fail with ERROR_INVALID_FUNCTION?
1620 */
1621 if (error == ERROR_INVALID_FUNCTION) {
1622 /*
1623 * This is probably due to
1624 * the driver with which Packet.dll
1625 * communicates being older, or
1626 * being a WinPcap driver, so
1627 * that it doesn't support
1628 * BIOCGTIMESTAMPMODES.
1629 *
1630 * Tell the user to try uninstalling
1631 * Npcap - and WinPcap if installed -
1632 * and re-installing it, to flush
1633 * out all older drivers.
1634 */
1635 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1636 "PacketGetTimestampModes() failed with ERROR_INVALID_FUNCTION; try uninstalling Npcap, and WinPcap if installed, and re-installing it from npcap.com");
1637 break;
1638 }
1639
1640 /*
1641 * No, some other error. Fail.
1642 */
1643 pcap_fmt_errmsg_for_win32_err(ebuf,
1644 PCAP_ERRBUF_SIZE, error,
1645 "Error calling PacketGetTimestampModes");
1646 break;
1647 }
1648 }
1649 /* else (ret == TRUE)
1650 * Unexpected success. Let's act like we got ERROR_MORE_DATA.
1651 * If it doesn't work, we'll hit some other error condition farther on.
1652 */
1653
1654 /* If the driver reports no modes supported *and*
1655 * ERROR_MORE_DATA, something is seriously wrong.
1656 * We *could* ignore the error and continue without supporting
1657 * settable timestamp modes, but that would hide a bug.
1658 */
1659 if (num_ts_modes == 0) {
1660 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1661 "PacketGetTimestampModes() reports 0 modes supported.");
1662 break;
1663 }
1664
1665 /*
1666 * Yes, so we now know how many types to fetch.
1667 *
1668 * The buffer needs to have one ULONG for the
1669 * count and num_ts_modes ULONGs for the
1670 * num_ts_modes time stamp types.
1671 */
1672 modes = (ULONG *)malloc((1 + num_ts_modes) * sizeof(ULONG));
1673 if (modes == NULL) {
1674 /* Out of memory. */
1675 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1676 break;
1677 }
1678 modes[0] = 1 + num_ts_modes;
1679 if (!PacketGetTimestampModes(adapter, modes)) {
1680 pcap_fmt_errmsg_for_win32_err(ebuf,
1681 PCAP_ERRBUF_SIZE, GetLastError(),
1682 "Error calling PacketGetTimestampModes");
1683 break;
1684 }
1685 if (modes[0] != num_ts_modes) {
1686 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1687 "First PacketGetTimestampModes() call gives %lu modes, second call gives %lu modes",
1688 num_ts_modes, modes[0]);
1689 break;
1690 }
1691
1692 /*
1693 * Allocate a buffer big enough for
1694 * PCAP_TSTAMP_HOST (default) plus
1695 * the explicitly specified modes.
1696 */
1697 p->tstamp_type_list = malloc((1 + num_ts_modes) * sizeof(u_int));
1698 if (p->tstamp_type_list == NULL) {
1699 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno, "malloc");
1700 break;
1701 }
1702 u_int num_ts_types = 0;
1703 p->tstamp_type_list[num_ts_types] =
1704 PCAP_TSTAMP_HOST;
1705 num_ts_types++;
1706 for (ULONG i = 0; i < num_ts_modes; i++) {
1707 switch (modes[i + 1]) {
1708
1709 case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION:
1710 /*
1711 * Better than low-res,
1712 * but *not* synchronized
1713 * with the OS clock.
1714 */
1715 p->tstamp_type_list[num_ts_types] =
1716 PCAP_TSTAMP_HOST_HIPREC_UNSYNCED;
1717 num_ts_types++;
1718 break;
1719
1720 case TIMESTAMPMODE_QUERYSYSTEMTIME:
1721 /*
1722 * Low-res, but synchronized
1723 * with the OS clock.
1724 */
1725 p->tstamp_type_list[num_ts_types] =
1726 PCAP_TSTAMP_HOST_LOWPREC;
1727 num_ts_types++;
1728 break;
1729
1730 case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE:
1731 /*
1732 * High-res, and synchronized
1733 * with the OS clock.
1734 */
1735 p->tstamp_type_list[num_ts_types] =
1736 PCAP_TSTAMP_HOST_HIPREC;
1737 num_ts_types++;
1738 break;
1739
1740 default:
1741 /*
1742 * Unknown, so we can't
1743 * report it.
1744 */
1745 break;
1746 }
1747 }
1748 p->tstamp_type_count = num_ts_types;
1749 } while (0);
1750
1751 /* Clean up temporary allocations */
1752 if (device_copy != NULL) {
1753 free(device_copy);
1754 }
1755 if (modes != NULL) {
1756 free(modes);
1757 }
1758 if (adapter != NULL) {
1759 PacketCloseAdapter(adapter);
1760 }
1761
1762 /* Error condition signaled by ebuf containing an error message */
1763 if (ebuf[0] != '\0') {
1764 /* Undo any changes. Must not use pcap_close()
1765 * since none of the ops have been set. */
1766 if (p->tstamp_type_list != NULL) {
1767 free(p->tstamp_type_list);
1768 }
1769 free(p);
1770 p = NULL;
1771 }
1772 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1773
1774 return (p);
1775 }
1776
1777 static int
1778 pcap_setfilter_npf(pcap_t *p, struct bpf_program *fp)
1779 {
1780 struct pcap_win *pw = p->priv;
1781
1782 if(PacketSetBpf(pw->adapter,fp)==FALSE){
1783 /*
1784 * Kernel filter not installed.
1785 *
1786 * XXX - we don't know whether this failed because:
1787 *
1788 * the kernel rejected the filter program as invalid,
1789 * in which case we should fall back on userland
1790 * filtering;
1791 *
1792 * the kernel rejected the filter program as too big,
1793 * in which case we should again fall back on
1794 * userland filtering;
1795 *
1796 * there was some other problem, in which case we
1797 * should probably report an error.
1798 *
1799 * For NPF devices, the Win32 status will be
1800 * STATUS_INVALID_DEVICE_REQUEST for invalid
1801 * filters, but I don't know what it'd be for
1802 * other problems, and for some other devices
1803 * it might not be set at all.
1804 *
1805 * So we just fall back on userland filtering in
1806 * all cases.
1807 */
1808
1809 /*
1810 * install_bpf_program() validates the program.
1811 *
1812 * XXX - what if we already have a filter in the kernel?
1813 */
1814 if (install_bpf_program(p, fp) < 0)
1815 return (-1);
1816 pw->filtering_in_kernel = 0; /* filtering in userland */
1817 return (0);
1818 }
1819
1820 /*
1821 * It worked.
1822 */
1823 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1824
1825 /*
1826 * Discard any previously-received packets, as they might have
1827 * passed whatever filter was formerly in effect, but might
1828 * not pass this filter (BIOCSETF discards packets buffered
1829 * in the kernel, so you can lose packets in any case).
1830 */
1831 p->cc = 0;
1832 return (0);
1833 }
1834
1835 /*
1836 * We filter at user level, since the kernel driver doesn't process the packets
1837 */
1838 static int
1839 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1840
1841 if(!fp)
1842 {
1843 pcap_strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1844 return (-1);
1845 }
1846
1847 /* Install a user level filter */
1848 if (install_bpf_program(p, fp) < 0)
1849 return (-1);
1850
1851 return (0);
1852 }
1853
1854 static int
1855 pcap_getnonblock_npf(pcap_t *p)
1856 {
1857 struct pcap_win *pw = p->priv;
1858
1859 /*
1860 * XXX - if there were a PacketGetReadTimeout() call, we
1861 * would use it, and return 1 if the timeout is -1
1862 * and 0 otherwise.
1863 */
1864 return (pw->nonblock);
1865 }
1866
1867 static int
1868 pcap_setnonblock_npf(pcap_t *p, int nonblock)
1869 {
1870 struct pcap_win *pw = p->priv;
1871 int newtimeout;
1872
1873 if (nonblock) {
1874 /*
1875 * Set the packet buffer timeout to -1 for non-blocking
1876 * mode.
1877 */
1878 newtimeout = -1;
1879 } else {
1880 /*
1881 * Restore the timeout set when the device was opened.
1882 * (Note that this may be -1, in which case we're not
1883 * really leaving non-blocking mode. However, although
1884 * the timeout argument to pcap_set_timeout() and
1885 * pcap_open_live() is an int, you're not supposed to
1886 * supply a negative value, so that "shouldn't happen".)
1887 */
1888 newtimeout = p->opt.timeout;
1889 }
1890 if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1891 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1892 GetLastError(), "PacketSetReadTimeout");
1893 return (-1);
1894 }
1895 pw->nonblock = (newtimeout == -1);
1896 return (0);
1897 }
1898
1899 static int
1900 pcap_add_if_npf(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
1901 const char *description, char *errbuf)
1902 {
1903 pcap_if_t *curdev;
1904 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1905 LONG if_addr_size;
1906 int res = 0;
1907
1908 if_addr_size = MAX_NETWORK_ADDRESSES;
1909
1910 /*
1911 * Add an entry for this interface, with no addresses.
1912 */
1913 curdev = add_dev(devlistp, name, flags, description, errbuf);
1914 if (curdev == NULL) {
1915 /*
1916 * Failure.
1917 */
1918 return (-1);
1919 }
1920
1921 /*
1922 * Get the list of addresses for the interface.
1923 */
1924 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1925 /*
1926 * Failure.
1927 *
1928 * We don't return an error, because this can happen with
1929 * NdisWan interfaces, and we want to supply them even
1930 * if we can't supply their addresses.
1931 *
1932 * We return an entry with an empty address list.
1933 */
1934 return (0);
1935 }
1936
1937 /*
1938 * Now add the addresses.
1939 */
1940 while (if_addr_size-- > 0) {
1941 /*
1942 * "curdev" is an entry for this interface; add an entry for
1943 * this address to its list of addresses.
1944 */
1945 res = add_addr_to_dev(curdev,
1946 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1947 sizeof (struct sockaddr_storage),
1948 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1949 sizeof (struct sockaddr_storage),
1950 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1951 sizeof (struct sockaddr_storage),
1952 NULL,
1953 0,
1954 errbuf);
1955 if (res == -1) {
1956 /*
1957 * Failure.
1958 */
1959 break;
1960 }
1961 }
1962
1963 return (res);
1964 }
1965
1966 static int
1967 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
1968 {
1969 char *name_copy;
1970 ADAPTER *adapter;
1971 int status;
1972 size_t len;
1973 NDIS_HARDWARE_STATUS hardware_status;
1974 #ifdef OID_GEN_PHYSICAL_MEDIUM
1975 NDIS_PHYSICAL_MEDIUM phys_medium;
1976 bpf_u_int32 gen_physical_medium_oids[] = {
1977 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1978 OID_GEN_PHYSICAL_MEDIUM_EX,
1979 #endif
1980 OID_GEN_PHYSICAL_MEDIUM
1981 };
1982 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1983 size_t i;
1984 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1985 #ifdef OID_GEN_LINK_STATE
1986 NDIS_LINK_STATE link_state;
1987 #endif
1988 int connect_status;
1989
1990 if (*flags & PCAP_IF_LOOPBACK) {
1991 /*
1992 * Loopback interface, so the connection status doesn't
1993 * apply. and it's not wireless (or wired, for that
1994 * matter...). We presume it's up and running.
1995 */
1996 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING | PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1997 return (0);
1998 }
1999
2000 /*
2001 * We need to open the adapter to get this information.
2002 *
2003 * XXX - PacketOpenAdapter() takes a non-const pointer
2004 * as an argument, so we make a copy of the argument and
2005 * pass that to it.
2006 */
2007 name_copy = strdup(name);
2008 adapter = PacketOpenAdapter(name_copy);
2009 free(name_copy);
2010 if (adapter == NULL) {
2011 /*
2012 * Give up; if they try to open this device, it'll fail.
2013 */
2014 return (0);
2015 }
2016
2017 #ifdef HAVE_AIRPCAP_API
2018 /*
2019 * Airpcap.sys do not support the below 'OID_GEN_x' values.
2020 * Just set these flags (and none of the '*flags' entered with).
2021 */
2022 if (PacketGetAirPcapHandle(adapter)) {
2023 /*
2024 * Must be "up" and "running" if the above if succeeded.
2025 */
2026 *flags = PCAP_IF_UP | PCAP_IF_RUNNING;
2027
2028 /*
2029 * An airpcap device is a wireless device (duh!)
2030 */
2031 *flags |= PCAP_IF_WIRELESS;
2032
2033 /*
2034 * A "network assosiation state" makes no sense for airpcap.
2035 */
2036 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2037 PacketCloseAdapter(adapter);
2038 return (0);
2039 }
2040 #endif
2041
2042 /*
2043 * Get the hardware status, and derive "up" and "running" from
2044 * that.
2045 */
2046 len = sizeof (hardware_status);
2047 status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
2048 &hardware_status, &len, errbuf);
2049 if (status == 0) {
2050 switch (hardware_status) {
2051
2052 case NdisHardwareStatusReady:
2053 /*
2054 * "Available and capable of sending and receiving
2055 * data over the wire", so up and running.
2056 */
2057 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
2058 break;
2059
2060 case NdisHardwareStatusInitializing:
2061 case NdisHardwareStatusReset:
2062 /*
2063 * "Initializing" or "Resetting", so up, but
2064 * not running.
2065 */
2066 *flags |= PCAP_IF_UP;
2067 break;
2068
2069 case NdisHardwareStatusClosing:
2070 case NdisHardwareStatusNotReady:
2071 /*
2072 * "Closing" or "Not ready", so neither up nor
2073 * running.
2074 */
2075 break;
2076
2077 default:
2078 /*
2079 * Unknown.
2080 */
2081 break;
2082 }
2083 } else {
2084 /*
2085 * Can't get the hardware status, so assume both up and
2086 * running.
2087 */
2088 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
2089 }
2090
2091 /*
2092 * Get the network type.
2093 */
2094 #ifdef OID_GEN_PHYSICAL_MEDIUM
2095 /*
2096 * Try the OIDs we have for this, in order.
2097 */
2098 for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
2099 len = sizeof (phys_medium);
2100 status = oid_get_request(adapter, gen_physical_medium_oids[i],
2101 &phys_medium, &len, errbuf);
2102 if (status == 0) {
2103 /*
2104 * Success.
2105 */
2106 break;
2107 }
2108 /*
2109 * Failed. We can't determine whether it failed
2110 * because that particular OID isn't supported
2111 * or because some other problem occurred, so we
2112 * just drive on and try the next OID.
2113 */
2114 }
2115 if (status == 0) {
2116 /*
2117 * We got the physical medium.
2118 *
2119 * XXX - we might want to check for NdisPhysicalMediumWiMax
2120 * and NdisPhysicalMediumNative802_15_4 being
2121 * part of the enum, and check for those in the "wireless"
2122 * case.
2123 */
2124 DIAG_OFF_ENUM_SWITCH
2125 switch (phys_medium) {
2126
2127 case NdisPhysicalMediumWirelessLan:
2128 case NdisPhysicalMediumWirelessWan:
2129 case NdisPhysicalMediumNative802_11:
2130 case NdisPhysicalMediumBluetooth:
2131 case NdisPhysicalMediumUWB:
2132 case NdisPhysicalMediumIrda:
2133 /*
2134 * Wireless.
2135 */
2136 *flags |= PCAP_IF_WIRELESS;
2137 break;
2138
2139 default:
2140 /*
2141 * Not wireless or unknown
2142 */
2143 break;
2144 }
2145 DIAG_ON_ENUM_SWITCH
2146 }
2147 #endif
2148
2149 /*
2150 * Get the connection status.
2151 */
2152 #ifdef OID_GEN_LINK_STATE
2153 len = sizeof(link_state);
2154 status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
2155 &len, errbuf);
2156 if (status == 0) {
2157 /*
2158 * NOTE: this also gives us the receive and transmit
2159 * link state.
2160 */
2161 switch (link_state.MediaConnectState) {
2162
2163 case MediaConnectStateConnected:
2164 /*
2165 * It's connected.
2166 */
2167 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2168 break;
2169
2170 case MediaConnectStateDisconnected:
2171 /*
2172 * It's disconnected.
2173 */
2174 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2175 break;
2176
2177 case MediaConnectStateUnknown:
2178 default:
2179 /*
2180 * It's unknown whether it's connected or not.
2181 */
2182 break;
2183 }
2184 }
2185 #else
2186 /*
2187 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2188 */
2189 status = -1;
2190 #endif
2191 if (status == -1) {
2192 /*
2193 * OK, OID_GEN_LINK_STATE didn't work, try
2194 * OID_GEN_MEDIA_CONNECT_STATUS.
2195 */
2196 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
2197 &connect_status, &len, errbuf);
2198 if (status == 0) {
2199 switch (connect_status) {
2200
2201 case NdisMediaStateConnected:
2202 /*
2203 * It's connected.
2204 */
2205 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2206 break;
2207
2208 case NdisMediaStateDisconnected:
2209 /*
2210 * It's disconnected.
2211 */
2212 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2213 break;
2214 }
2215 }
2216 }
2217 PacketCloseAdapter(adapter);
2218 return (0);
2219 }
2220
2221 int
2222 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2223 {
2224 int ret = 0;
2225 const char *desc;
2226 char *AdaptersName;
2227 ULONG NameLength;
2228 char *name;
2229
2230 /*
2231 * Find out how big a buffer we need.
2232 *
2233 * This call should always return FALSE; if the error is
2234 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2235 * the size of the buffer we need, otherwise there's a
2236 * problem, and NameLength should be set to 0.
2237 *
2238 * It shouldn't require NameLength to be set, but,
2239 * at least as of WinPcap 4.1.3, it checks whether
2240 * NameLength is big enough before it checks for a
2241 * NULL buffer argument, so, while it'll still do
2242 * the right thing if NameLength is uninitialized and
2243 * whatever junk happens to be there is big enough
2244 * (because the pointer argument will be null), it's
2245 * still reading an uninitialized variable.
2246 */
2247 NameLength = 0;
2248 if (!PacketGetAdapterNames(NULL, &NameLength))
2249 {
2250 DWORD last_error = GetLastError();
2251
2252 if (last_error != ERROR_INSUFFICIENT_BUFFER)
2253 {
2254 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2255 last_error, "PacketGetAdapterNames");
2256 return (-1);
2257 }
2258 }
2259
2260 if (NameLength <= 0)
2261 return 0;
2262 AdaptersName = (char*) malloc(NameLength);
2263 if (AdaptersName == NULL)
2264 {
2265 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
2266 return (-1);
2267 }
2268
2269 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
2270 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2271 GetLastError(), "PacketGetAdapterNames");
2272 free(AdaptersName);
2273 return (-1);
2274 }
2275
2276 /*
2277 * "PacketGetAdapterNames()" returned a list of
2278 * null-terminated ASCII interface name strings,
2279 * terminated by a null string, followed by a list
2280 * of null-terminated ASCII interface description
2281 * strings, terminated by a null string.
2282 * This means there are two ASCII nulls at the end
2283 * of the first list.
2284 *
2285 * Find the end of the first list; that's the
2286 * beginning of the second list.
2287 */
2288 desc = &AdaptersName[0];
2289 while (*desc != '\0' || *(desc + 1) != '\0')
2290 desc++;
2291
2292 /*
2293 * Found it - "desc" points to the first of the two
2294 * nulls at the end of the list of names, so the
2295 * first byte of the list of descriptions is two bytes
2296 * after it.
2297 */
2298 desc += 2;
2299
2300 /*
2301 * Loop over the elements in the first list.
2302 */
2303 name = &AdaptersName[0];
2304 while (*name != '\0') {
2305 bpf_u_int32 flags = 0;
2306
2307 #ifdef HAVE_AIRPCAP_API
2308 /*
2309 * Is this an AirPcap device?
2310 * If so, ignore it; it'll get added later, by the
2311 * AirPcap code.
2312 */
2313 if (device_is_airpcap(name, errbuf) == 1) {
2314 name += strlen(name) + 1;
2315 desc += strlen(desc) + 1;
2316 continue;
2317 }
2318 #endif
2319
2320 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2321 /*
2322 * Is this a loopback interface?
2323 */
2324 if (PacketIsLoopbackAdapter(name)) {
2325 /* Yes */
2326 flags |= PCAP_IF_LOOPBACK;
2327 }
2328 #endif
2329 /*
2330 * Get additional flags.
2331 */
2332 if (get_if_flags(name, &flags, errbuf) == -1) {
2333 /*
2334 * Failure.
2335 */
2336 ret = -1;
2337 break;
2338 }
2339
2340 /*
2341 * Add an entry for this interface.
2342 */
2343 if (pcap_add_if_npf(devlistp, name, flags, desc,
2344 errbuf) == -1) {
2345 /*
2346 * Failure.
2347 */
2348 ret = -1;
2349 break;
2350 }
2351 name += strlen(name) + 1;
2352 desc += strlen(desc) + 1;
2353 }
2354
2355 free(AdaptersName);
2356 return (ret);
2357 }
2358
2359 /*
2360 * Return the name of a network interface attached to the system, or NULL
2361 * if none can be found. The interface must be configured up; the
2362 * lowest unit number is preferred; loopback is ignored.
2363 *
2364 * In the best of all possible worlds, this would be the same as on
2365 * UN*X, but there may be software that expects this to return a
2366 * full list of devices after the first device.
2367 */
2368 #define ADAPTERSNAME_LEN 8192
2369 char *
2370 pcap_lookupdev(char *errbuf)
2371 {
2372 DWORD dwVersion;
2373 DWORD dwWindowsMajorVersion;
2374
2375 /*
2376 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2377 * it may return UTF-16 strings, for backwards-compatibility
2378 * reasons, and we're also disabling the hack to make that work,
2379 * for not-going-past-the-end-of-a-string reasons, and 2) we
2380 * want its behavior to be consistent.
2381 *
2382 * In addition, it's not thread-safe, so we've marked it as
2383 * deprecated.
2384 */
2385 if (pcap_new_api) {
2386 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2387 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2388 return (NULL);
2389 }
2390
2391 /* disable MSVC's GetVersion() deprecated warning here */
2392 DIAG_OFF_DEPRECATION
2393 dwVersion = GetVersion(); /* get the OS version */
2394 DIAG_ON_DEPRECATION
2395 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
2396
2397 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
2398 /*
2399 * Windows 95, 98, ME.
2400 */
2401 ULONG NameLength = ADAPTERSNAME_LEN;
2402 static char AdaptersName[ADAPTERSNAME_LEN];
2403
2404 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
2405 return (AdaptersName);
2406 else
2407 return NULL;
2408 } else {
2409 /*
2410 * Windows NT (NT 4.0 and later).
2411 * Convert the names to Unicode for backward compatibility.
2412 */
2413 ULONG NameLength = ADAPTERSNAME_LEN;
2414 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
2415 size_t BufferSpaceLeft;
2416 char *tAstr;
2417 WCHAR *Unameptr;
2418 char *Adescptr;
2419 size_t namelen, i;
2420 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
2421 int NAdapts = 0;
2422
2423 if(TAdaptersName == NULL)
2424 {
2425 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
2426 return NULL;
2427 }
2428
2429 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
2430 {
2431 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2432 GetLastError(), "PacketGetAdapterNames");
2433 free(TAdaptersName);
2434 return NULL;
2435 }
2436
2437
2438 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
2439 tAstr = (char*)TAdaptersName;
2440 Unameptr = AdaptersName;
2441
2442 /*
2443 * Convert the device names to Unicode into AdapterName.
2444 */
2445 do {
2446 /*
2447 * Length of the name, including the terminating
2448 * NUL.
2449 */
2450 namelen = strlen(tAstr) + 1;
2451
2452 /*
2453 * Do we have room for the name in the Unicode
2454 * buffer?
2455 */
2456 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
2457 /*
2458 * No.
2459 */
2460 goto quit;
2461 }
2462 BufferSpaceLeft -= namelen * sizeof(WCHAR);
2463
2464 /*
2465 * Copy the name, converting ASCII to Unicode.
2466 * namelen includes the NUL, so we copy it as
2467 * well.
2468 */
2469 for (i = 0; i < namelen; i++)
2470 *Unameptr++ = *tAstr++;
2471
2472 /*
2473 * Count this adapter.
2474 */
2475 NAdapts++;
2476 } while (namelen != 1);
2477
2478 /*
2479 * Copy the descriptions, but don't convert them from
2480 * ASCII to Unicode.
2481 */
2482 Adescptr = (char *)Unameptr;
2483 while(NAdapts--)
2484 {
2485 size_t desclen;
2486
2487 desclen = strlen(tAstr) + 1;
2488
2489 /*
2490 * Do we have room for the name in the Unicode
2491 * buffer?
2492 */
2493 if (BufferSpaceLeft < desclen) {
2494 /*
2495 * No.
2496 */
2497 goto quit;
2498 }
2499
2500 /*
2501 * Just copy the ASCII string.
2502 * namelen includes the NUL, so we copy it as
2503 * well.
2504 */
2505 memcpy(Adescptr, tAstr, desclen);
2506 Adescptr += desclen;
2507 tAstr += desclen;
2508 BufferSpaceLeft -= desclen;
2509 }
2510
2511 quit:
2512 free(TAdaptersName);
2513 return (char *)(AdaptersName);
2514 }
2515 }
2516
2517 /*
2518 * We can't use the same code that we use on UN*X, as that's doing
2519 * UN*X-specific calls.
2520 *
2521 * We don't just fetch the entire list of devices, search for the
2522 * particular device, and use its first IPv4 address, as that's too
2523 * much work to get just one device's netmask.
2524 */
2525 int
2526 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
2527 char *errbuf)
2528 {
2529 /*
2530 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2531 * in order to skip non IPv4 (i.e. IPv6 addresses)
2532 */
2533 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2534 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
2535 struct sockaddr_in *t_addr;
2536 LONG i;
2537
2538 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
2539 *netp = *maskp = 0;
2540 return (0);
2541 }
2542
2543 for(i = 0; i < if_addr_size; i++)
2544 {
2545 if(if_addrs[i].IPAddress.ss_family == AF_INET)
2546 {
2547 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
2548 *netp = t_addr->sin_addr.S_un.S_addr;
2549 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
2550 *maskp = t_addr->sin_addr.S_un.S_addr;
2551
2552 *netp &= *maskp;
2553 return (0);
2554 }
2555
2556 }
2557
2558 *netp = *maskp = 0;
2559 return (0);
2560 }
2561
2562 static const char *pcap_lib_version_string;
2563
2564 #ifdef HAVE_VERSION_H
2565 /*
2566 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2567 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2568 * version.
2569 *
2570 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2571 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2572 * for the packet.dll version number as well.)
2573 */
2574 #include "../../version.h"
2575
2576 static const char pcap_version_string[] =
2577 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2578
2579 const char *
2580 pcap_lib_version(void)
2581 {
2582 if (pcap_lib_version_string == NULL) {
2583 /*
2584 * Generate the version string.
2585 */
2586 const char *packet_version_string = PacketGetVersion();
2587
2588 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2589 /*
2590 * WinPcap/Npcap version string and packet.dll version
2591 * string are the same; just report the WinPcap/Npcap
2592 * version.
2593 */
2594 pcap_lib_version_string = pcap_version_string;
2595 } else {
2596 /*
2597 * WinPcap/Npcap version string and packet.dll version
2598 * string are different; that shouldn't be the
2599 * case (the two libraries should come from the
2600 * same version of WinPcap/Npcap), so we report both
2601 * versions.
2602 */
2603 char *full_pcap_version_string;
2604
2605 if (pcap_asprintf(&full_pcap_version_string,
2606 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING,
2607 packet_version_string) != -1) {
2608 /* Success */
2609 pcap_lib_version_string = full_pcap_version_string;
2610 }
2611 }
2612 }
2613 return (pcap_lib_version_string);
2614 }
2615
2616 #else /* HAVE_VERSION_H */
2617
2618 /*
2619 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2620 * tree.
2621 */
2622 const char *
2623 pcap_lib_version(void)
2624 {
2625 if (pcap_lib_version_string == NULL) {
2626 /*
2627 * Generate the version string. Report the packet.dll
2628 * version.
2629 */
2630 char *full_pcap_version_string;
2631
2632 if (pcap_asprintf(&full_pcap_version_string,
2633 PCAP_VERSION_STRING " (packet.dll version %s)",
2634 PacketGetVersion()) != -1) {
2635 /* Success */
2636 pcap_lib_version_string = full_pcap_version_string;
2637 }
2638 }
2639 return (pcap_lib_version_string);
2640 }
2641 #endif /* HAVE_VERSION_H */