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