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