]> The Tcpdump Group git mirrors - libpcap/blob - pcap-npf.c
CI: Call print_so_deps() on rpcapd in remote enabled build
[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 #ifndef PACKET_OID_DATA_LENGTH
189 #define PACKET_OID_DATA_LENGTH(_DataLength) \
190 (offsetof(PACKET_OID_DATA, Data) + _DataLength)
191 #endif
192 static int
193 oid_get_request(ADAPTER *adapter, bpf_u_int32 oid, void *data, size_t *lenp,
194 char *errbuf)
195 {
196 PACKET_OID_DATA *oid_data_arg;
197
198 /*
199 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
200 * It should be big enough to hold "*lenp" bytes of data;
201 */
202 oid_data_arg = malloc(PACKET_OID_DATA_LENGTH(*lenp));
203 if (oid_data_arg == NULL) {
204 snprintf(errbuf, PCAP_ERRBUF_SIZE,
205 "Couldn't allocate argument buffer for PacketRequest");
206 return (PCAP_ERROR);
207 }
208
209 /*
210 * No need to copy the data - we're doing a fetch.
211 */
212 oid_data_arg->Oid = oid;
213 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
214 if (!PacketRequest(adapter, FALSE, oid_data_arg)) {
215 pcapint_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
216 GetLastError(), "Error calling PacketRequest");
217 free(oid_data_arg);
218 return (-1);
219 }
220
221 /*
222 * Get the length actually supplied.
223 */
224 *lenp = oid_data_arg->Length;
225
226 /*
227 * Copy back the data we fetched.
228 */
229 memcpy(data, oid_data_arg->Data, *lenp);
230 free(oid_data_arg);
231 return (0);
232 }
233
234 static int
235 pcap_stats_npf(pcap_t *p, struct pcap_stat *ps)
236 {
237 struct pcap_win *pw = p->priv;
238 struct bpf_stat bstats;
239
240 /*
241 * Try to get statistics.
242 *
243 * (Please note - "struct pcap_stat" is *not* the same as
244 * WinPcap's "struct bpf_stat". It might currently have the
245 * same layout, but let's not cheat.
246 *
247 * Note also that we don't fill in ps_capt, as we might have
248 * been called by code compiled against an earlier version of
249 * WinPcap that didn't have ps_capt, in which case filling it
250 * in would stomp on whatever comes after the structure passed
251 * to us.
252 */
253 if (!PacketGetStats(pw->adapter, &bstats)) {
254 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
255 GetLastError(), "PacketGetStats error");
256 return (-1);
257 }
258 ps->ps_recv = bstats.bs_recv;
259 ps->ps_drop = bstats.bs_drop;
260
261 /*
262 * XXX - PacketGetStats() doesn't fill this in, so we just
263 * return 0.
264 */
265 #if 0
266 ps->ps_ifdrop = bstats.ps_ifdrop;
267 #else
268 ps->ps_ifdrop = 0;
269 #endif
270
271 return (0);
272 }
273
274 /*
275 * Win32-only routine for getting statistics.
276 *
277 * This way is definitely safer than passing the pcap_stat * from the userland.
278 * In fact, there could happen than the user allocates a variable which is not
279 * big enough for the new structure, and the library will write in a zone
280 * which is not allocated to this variable.
281 *
282 * In this way, we're pretty sure we are writing on memory allocated to this
283 * variable.
284 *
285 * XXX - but this is the wrong way to handle statistics. Instead, we should
286 * have an API that returns data in a form like the Options section of a
287 * pcapng Interface Statistics Block:
288 *
289 * 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
290 *
291 * which would let us add new statistics straightforwardly and indicate which
292 * statistics we are and are *not* providing, rather than having to provide
293 * possibly-bogus values for statistics we can't provide.
294 */
295 static struct pcap_stat *
296 pcap_stats_ex_npf(pcap_t *p, int *pcap_stat_size)
297 {
298 struct pcap_win *pw = p->priv;
299 struct bpf_stat bstats;
300
301 *pcap_stat_size = sizeof (p->stat);
302
303 /*
304 * Try to get statistics.
305 *
306 * (Please note - "struct pcap_stat" is *not* the same as
307 * WinPcap's "struct bpf_stat". It might currently have the
308 * same layout, but let's not cheat.)
309 */
310 if (!PacketGetStatsEx(pw->adapter, &bstats)) {
311 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
312 GetLastError(), "PacketGetStatsEx error");
313 return (NULL);
314 }
315 p->stat.ps_recv = bstats.bs_recv;
316 p->stat.ps_drop = bstats.bs_drop;
317 p->stat.ps_ifdrop = bstats.ps_ifdrop;
318 /*
319 * Just in case this is ever compiled for a target other than
320 * Windows, which is somewhere between extremely unlikely and
321 * impossible.
322 */
323 #ifdef _WIN32
324 p->stat.ps_capt = bstats.bs_capt;
325 #endif
326 return (&p->stat);
327 }
328
329 /* Set the dimension of the kernel-level capture buffer */
330 static int
331 pcap_setbuff_npf(pcap_t *p, int dim)
332 {
333 struct pcap_win *pw = p->priv;
334
335 if(PacketSetBuff(pw->adapter,dim)==FALSE)
336 {
337 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
338 return (-1);
339 }
340 return (0);
341 }
342
343 /* Set the driver working mode */
344 static int
345 pcap_setmode_npf(pcap_t *p, int mode)
346 {
347 struct pcap_win *pw = p->priv;
348
349 if(PacketSetMode(pw->adapter,mode)==FALSE)
350 {
351 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
352 return (-1);
353 }
354
355 return (0);
356 }
357
358 /*set the minimum amount of data that will release a read call*/
359 static int
360 pcap_setmintocopy_npf(pcap_t *p, int size)
361 {
362 struct pcap_win *pw = p->priv;
363
364 if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
365 {
366 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
367 return (-1);
368 }
369 return (0);
370 }
371
372 static HANDLE
373 pcap_getevent_npf(pcap_t *p)
374 {
375 struct pcap_win *pw = p->priv;
376
377 return (PacketGetReadEvent(pw->adapter));
378 }
379
380 static int
381 pcap_oid_get_request_npf(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
382 {
383 struct pcap_win *pw = p->priv;
384
385 return (oid_get_request(pw->adapter, oid, data, lenp, p->errbuf));
386 }
387
388 static int
389 pcap_oid_set_request_npf(pcap_t *p, bpf_u_int32 oid, const void *data,
390 size_t *lenp)
391 {
392 struct pcap_win *pw = p->priv;
393 PACKET_OID_DATA *oid_data_arg;
394
395 /*
396 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
397 * It should be big enough to hold "*lenp" bytes of data;
398 */
399 oid_data_arg = malloc(PACKET_OID_DATA_LENGTH(*lenp));
400 if (oid_data_arg == NULL) {
401 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
402 "Couldn't allocate argument buffer for PacketRequest");
403 return (PCAP_ERROR);
404 }
405
406 oid_data_arg->Oid = oid;
407 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
408 memcpy(oid_data_arg->Data, data, *lenp);
409 if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
410 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
411 GetLastError(), "Error calling PacketRequest");
412 free(oid_data_arg);
413 return (PCAP_ERROR);
414 }
415
416 /*
417 * Get the length actually copied.
418 */
419 *lenp = oid_data_arg->Length;
420
421 /*
422 * No need to copy the data - we're doing a set.
423 */
424 free(oid_data_arg);
425 return (0);
426 }
427
428 static u_int
429 pcap_sendqueue_transmit_npf(pcap_t *p, pcap_send_queue *queue, int sync)
430 {
431 struct pcap_win *pw = p->priv;
432 u_int res;
433
434 res = PacketSendPackets(pw->adapter,
435 queue->buffer,
436 queue->len,
437 (BOOLEAN)sync);
438
439 if(res != queue->len){
440 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
441 GetLastError(), "Error queueing packets");
442 }
443
444 return (res);
445 }
446
447 static int
448 pcap_setuserbuffer_npf(pcap_t *p, int size)
449 {
450 unsigned char *new_buff;
451
452 if (size<=0) {
453 /* Bogus parameter */
454 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
455 "Error: invalid size %d",size);
456 return (-1);
457 }
458
459 /* Allocate the buffer */
460 new_buff=(unsigned char*)malloc(sizeof(char)*size);
461
462 if (!new_buff) {
463 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
464 "Error: not enough memory");
465 return (-1);
466 }
467
468 free(p->buffer);
469
470 p->buffer=new_buff;
471 p->bufsize=size;
472
473 return (0);
474 }
475
476 #ifdef HAVE_NPCAP_PACKET_API
477 /*
478 * Kernel dump mode isn't supported in Npcap; calls to PacketSetDumpName(),
479 * PacketSetDumpLimits(), and PacketIsDumpEnded() will get compile-time
480 * deprecation warnings.
481 *
482 * Avoid calling them; just return errors indicating that kernel dump
483 * mode isn't supported in Npcap.
484 */
485 static int
486 pcap_live_dump_npf(pcap_t *p, char *filename _U_, int maxsize _U_,
487 int maxpacks _U_)
488 {
489 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
490 "Npcap doesn't support kernel dump mode");
491 return (-1);
492 }
493 static int
494 pcap_live_dump_ended_npf(pcap_t *p, int sync)
495 {
496 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
497 "Npcap doesn't support kernel dump mode");
498 return (-1);
499 }
500 #else /* HAVE_NPCAP_PACKET_API */
501 static int
502 pcap_live_dump_npf(pcap_t *p, char *filename, int maxsize, int maxpacks)
503 {
504 struct pcap_win *pw = p->priv;
505 BOOLEAN res;
506
507 /* Set the packet driver in dump mode */
508 res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
509 if(res == FALSE){
510 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
511 "Error setting dump mode");
512 return (-1);
513 }
514
515 /* Set the name of the dump file */
516 res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
517 if(res == FALSE){
518 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
519 "Error setting kernel dump file name");
520 return (-1);
521 }
522
523 /* Set the limits of the dump file */
524 res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
525 if(res == FALSE) {
526 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
527 "Error setting dump limit");
528 return (-1);
529 }
530
531 return (0);
532 }
533
534 static int
535 pcap_live_dump_ended_npf(pcap_t *p, int sync)
536 {
537 struct pcap_win *pw = p->priv;
538
539 return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
540 }
541 #endif /* HAVE_NPCAP_PACKET_API */
542
543 static int
544 pcap_read_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
545 {
546 PACKET Packet;
547 u_int cc;
548 int n;
549 register u_char *bp, *ep;
550 u_char *datap;
551 struct pcap_win *pw = p->priv;
552
553 cc = p->cc;
554 if (cc == 0) {
555 /*
556 * Has "pcap_breakloop()" been called?
557 */
558 if (p->break_loop) {
559 /*
560 * Yes - clear the flag that indicates that it
561 * has, and return PCAP_ERROR_BREAK to indicate
562 * that we were told to break out of the loop.
563 */
564 p->break_loop = 0;
565 return (PCAP_ERROR_BREAK);
566 }
567
568 /*
569 * Capture the packets.
570 *
571 * The PACKET structure had a bunch of extra stuff for
572 * Windows 9x/Me, but the only interesting data in it
573 * in the versions of Windows that we support is just
574 * a copy of p->buffer, a copy of p->buflen, and the
575 * actual number of bytes read returned from
576 * PacketReceivePacket(), none of which has to be
577 * retained from call to call, so we just keep one on
578 * the stack.
579 */
580 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
581 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
582 /*
583 * Did the device go away?
584 * If so, the error we get can either be
585 * ERROR_GEN_FAILURE or ERROR_DEVICE_REMOVED.
586 */
587 DWORD errcode = GetLastError();
588
589 if (errcode == ERROR_GEN_FAILURE ||
590 errcode == ERROR_DEVICE_REMOVED) {
591 /*
592 * The device on which we're capturing
593 * went away, or it became unusable
594 * by NPF due to a suspend/resume.
595 *
596 * ERROR_GEN_FAILURE comes from
597 * STATUS_UNSUCCESSFUL, as well as some
598 * other NT status codes that the Npcap
599 * driver is unlikely to return.
600 * XXX - hopefully no other error
601 * conditions are indicated by this.
602 *
603 * ERROR_DEVICE_REMOVED comes from
604 * STATUS_DEVICE_REMOVED.
605 *
606 * We report the Windows status code
607 * name and the corresponding NT status
608 * code name, for the benefit of attempts
609 * to debug cases where this error is
610 * reported when the device *wasn't*
611 * removed, either because it's not
612 * removable, it's removable but wasn't
613 * removed, or it's a device that doesn't
614 * correspond to a physical device.
615 *
616 * XXX - we really should return an
617 * appropriate error for that, but
618 * pcap_dispatch() etc. aren't
619 * documented as having error returns
620 * other than PCAP_ERROR or PCAP_ERROR_BREAK.
621 */
622 const char *errcode_msg;
623
624 if (errcode == ERROR_GEN_FAILURE)
625 errcode_msg = "ERROR_GEN_FAILURE/STATUS_UNSUCCESSFUL";
626 else
627 errcode_msg = "ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED";
628 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
629 "The interface disappeared (error code %s)",
630 errcode_msg);
631 } else {
632 pcapint_fmt_errmsg_for_win32_err(p->errbuf,
633 PCAP_ERRBUF_SIZE, errcode,
634 "PacketReceivePacket error");
635 }
636 return (PCAP_ERROR);
637 }
638
639 cc = Packet.ulBytesReceived;
640
641 bp = p->buffer;
642 }
643 else
644 bp = p->bp;
645
646 /*
647 * Loop through each packet.
648 *
649 * This assumes that a single buffer of packets will have
650 * <= INT_MAX packets, so the packet count doesn't overflow.
651 */
652 #define bhp ((struct bpf_hdr *)bp)
653 n = 0;
654 ep = bp + cc;
655 for (;;) {
656 register u_int caplen, hdrlen;
657 size_t packet_bytes;
658
659 /*
660 * Has "pcap_breakloop()" been called?
661 * If so, return immediately - if we haven't read any
662 * packets, clear the flag and return PCAP_ERROR_BREAK
663 * to indicate that we were told to break out of the loop,
664 * otherwise leave the flag set, so that the *next* call
665 * will break out of the loop without having read any
666 * packets, and return the number of packets we've
667 * processed so far.
668 */
669 if (p->break_loop) {
670 if (n == 0) {
671 p->break_loop = 0;
672 return (PCAP_ERROR_BREAK);
673 } else {
674 p->bp = bp;
675 p->cc = (u_int) (ep - bp);
676 return (n);
677 }
678 }
679 if (bp >= ep)
680 break;
681
682 caplen = bhp->bh_caplen;
683 hdrlen = bhp->bh_hdrlen;
684 datap = bp + hdrlen;
685
686 /*
687 * Compute the number of bytes for this packet in
688 * the buffer.
689 *
690 * That's the sum of the header length and the packet
691 * data length plus, if this is not the last packet,
692 * the padding required to align the next packet on
693 * the appropriate boundary.
694 *
695 * That means that it should be the minimum of the
696 * number of bytes left in the buffer and the
697 * rounded-up sum of the header and packet data lengths.
698 */
699 packet_bytes = min((u_int)(ep - bp), Packet_WORDALIGN(caplen + hdrlen));
700
701 /*
702 * Short-circuit evaluation: if using BPF filter
703 * in kernel, no need to do it now - we already know
704 * the packet passed the filter.
705 *
706 * XXX - pcapint_filter() should always return TRUE if
707 * handed a null pointer for the program, but it might
708 * just try to "run" the filter, so we check here.
709 */
710 if (pw->filtering_in_kernel ||
711 p->fcode.bf_insns == NULL ||
712 pcapint_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
713 #ifdef ENABLE_REMOTE
714 switch (p->rmt_samp.method) {
715
716 case PCAP_SAMP_1_EVERY_N:
717 pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
718
719 /* Discard all packets that are not '1 out of N' */
720 if (pw->samp_npkt != 0) {
721 bp += packet_bytes;
722 continue;
723 }
724 break;
725
726 case PCAP_SAMP_FIRST_AFTER_N_MS:
727 {
728 struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
729
730 /*
731 * Check if the timestamp of the arrived
732 * packet is smaller than our target time.
733 */
734 if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
735 (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
736 bp += packet_bytes;
737 continue;
738 }
739
740 /*
741 * The arrived packet is suitable for being
742 * delivered to our caller, so let's update
743 * the target time.
744 */
745 pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
746 if (pw->samp_time.tv_usec > 1000000) {
747 pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
748 pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
749 }
750 }
751 }
752 #endif /* ENABLE_REMOTE */
753
754 /*
755 * XXX A bpf_hdr matches a pcap_pkthdr.
756 */
757 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
758 bp += packet_bytes;
759 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
760 p->bp = bp;
761 p->cc = (u_int) (ep - bp);
762 return (n);
763 }
764 } else {
765 /*
766 * Skip this packet.
767 */
768 bp += packet_bytes;
769 }
770 }
771 #undef bhp
772 p->cc = 0;
773 return (n);
774 }
775
776 /* Send a packet to the network */
777 static int
778 pcap_inject_npf(pcap_t *p, const void *buf, int size)
779 {
780 struct pcap_win *pw = p->priv;
781 PACKET pkt;
782
783 PacketInitPacket(&pkt, (PVOID)buf, size);
784 if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
785 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
786 GetLastError(), "send error: PacketSendPacket failed");
787 return (-1);
788 }
789
790 /*
791 * We assume it all got sent if "PacketSendPacket()" succeeded.
792 * "pcap_inject()" is expected to return the number of bytes
793 * sent.
794 */
795 return (size);
796 }
797
798 static void
799 pcap_cleanup_npf(pcap_t *p)
800 {
801 struct pcap_win *pw = p->priv;
802
803 if (pw->adapter != NULL) {
804 PacketCloseAdapter(pw->adapter);
805 pw->adapter = NULL;
806 }
807 if (pw->rfmon_selfstart)
808 {
809 PacketSetMonitorMode(p->opt.device, 0);
810 }
811 pcapint_cleanup_live_common(p);
812 }
813
814 static void
815 pcap_breakloop_npf(pcap_t *p)
816 {
817 pcapint_breakloop_common(p);
818 struct pcap_win *pw = p->priv;
819
820 /* XXX - what if this fails? */
821 SetEvent(PacketGetReadEvent(pw->adapter));
822 }
823
824 static int
825 pcap_activate_npf(pcap_t *p)
826 {
827 struct pcap_win *pw = p->priv;
828 NetType type;
829 int res;
830 int status = 0;
831 struct bpf_insn total_insn;
832 struct bpf_program total_prog;
833 #ifdef HAVE_PACKET_GET_INFO
834 char oid_data_buf[PACKET_OID_DATA_LENGTH(sizeof(ULONG))] = {0};
835 PACKET_OID_DATA *oid_data_arg = (PACKET_OID_DATA *)oid_data_buf;
836 #endif
837
838 if (p->opt.rfmon) {
839 /*
840 * Monitor mode is supported on Windows Vista and later.
841 */
842 if (PacketGetMonitorMode(p->opt.device) == 1)
843 {
844 pw->rfmon_selfstart = 0;
845 }
846 else
847 {
848 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
849 {
850 pw->rfmon_selfstart = 0;
851 // Monitor mode is not supported.
852 if (res == 0)
853 {
854 return PCAP_ERROR_RFMON_NOTSUP;
855 }
856 else
857 {
858 return PCAP_ERROR;
859 }
860 }
861 else
862 {
863 pw->rfmon_selfstart = 1;
864 }
865 }
866 }
867
868 pw->adapter = PacketOpenAdapter(p->opt.device);
869
870 if (pw->adapter == NULL)
871 {
872 DWORD errcode = GetLastError();
873
874 /*
875 * What error did we get when trying to open the adapter?
876 */
877 switch (errcode) {
878
879 case ERROR_BAD_UNIT:
880 /*
881 * There's no such device.
882 * There's nothing to add, so clear the error
883 * message.
884 */
885 p->errbuf[0] = '\0';
886 return (PCAP_ERROR_NO_SUCH_DEVICE);
887
888 case ERROR_ACCESS_DENIED:
889 /*
890 * There is, but we don't have permission to
891 * use it.
892 *
893 * XXX - we currently get ERROR_BAD_UNIT if the
894 * user says "no" to the UAC prompt.
895 */
896 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
897 "The helper program for \"Admin-only Mode\" must be allowed to make changes to your device");
898 return (PCAP_ERROR_PERM_DENIED);
899
900 default:
901 /*
902 * Unknown - report details.
903 */
904 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
905 errcode, "Error opening adapter");
906 if (pw->rfmon_selfstart)
907 {
908 PacketSetMonitorMode(p->opt.device, 0);
909 }
910 return (PCAP_ERROR);
911 }
912 }
913
914 /*get network type*/
915 if(PacketGetNetType (pw->adapter,&type) == FALSE)
916 {
917 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
918 GetLastError(), "Cannot determine the network type");
919 goto bad;
920 }
921
922 /*Set the linktype*/
923 switch (type.LinkType)
924 {
925 /*
926 * NDIS-defined medium types.
927 */
928 case NdisMedium802_3:
929 p->linktype = DLT_EN10MB;
930 /*
931 * This is (presumably) a real Ethernet capture; give it a
932 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
933 * that an application can let you choose it, in case you're
934 * capturing DOCSIS traffic that a Cisco Cable Modem
935 * Termination System is putting out onto an Ethernet (it
936 * doesn't put an Ethernet header onto the wire, it puts raw
937 * DOCSIS frames out on the wire inside the low-level
938 * Ethernet framing).
939 */
940 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
941 if (p->dlt_list == NULL)
942 {
943 pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
944 errno, "malloc");
945 goto bad;
946 }
947 p->dlt_list[0] = DLT_EN10MB;
948 p->dlt_list[1] = DLT_DOCSIS;
949 p->dlt_count = 2;
950 break;
951
952 case NdisMedium802_5:
953 /*
954 * Token Ring.
955 */
956 p->linktype = DLT_IEEE802;
957 break;
958
959 case NdisMediumFddi:
960 p->linktype = DLT_FDDI;
961 break;
962
963 case NdisMediumWan:
964 p->linktype = DLT_EN10MB;
965 break;
966
967 case NdisMediumArcnetRaw:
968 p->linktype = DLT_ARCNET;
969 break;
970
971 case NdisMediumArcnet878_2:
972 p->linktype = DLT_ARCNET;
973 break;
974
975 case NdisMediumAtm:
976 p->linktype = DLT_ATM_RFC1483;
977 break;
978
979 case NdisMediumWirelessWan:
980 p->linktype = DLT_RAW;
981 break;
982
983 case NdisMediumIP:
984 p->linktype = DLT_RAW;
985 break;
986
987 /*
988 * Npcap-defined medium types.
989 */
990 case NdisMediumNull:
991 p->linktype = DLT_NULL;
992 break;
993
994 case NdisMediumCHDLC:
995 p->linktype = DLT_CHDLC;
996 break;
997
998 case NdisMediumPPPSerial:
999 p->linktype = DLT_PPP_SERIAL;
1000 break;
1001
1002 case NdisMediumBare80211:
1003 p->linktype = DLT_IEEE802_11;
1004 break;
1005
1006 case NdisMediumRadio80211:
1007 p->linktype = DLT_IEEE802_11_RADIO;
1008 break;
1009
1010 case NdisMediumPpi:
1011 p->linktype = DLT_PPI;
1012 break;
1013
1014 default:
1015 /*
1016 * An unknown medium type is assumed to supply Ethernet
1017 * headers; if not, the user will have to report it,
1018 * so that the medium type and link-layer header type
1019 * can be determined. If we were to fail here, we
1020 * might get the link-layer type in the error, but
1021 * the user wouldn't get a capture, so we wouldn't
1022 * be able to determine the link-layer type; we report
1023 * a warning with the link-layer type, so at least
1024 * some programs will report the warning.
1025 */
1026 p->linktype = DLT_EN10MB;
1027 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1028 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1029 type.LinkType);
1030 status = PCAP_WARNING;
1031 break;
1032 }
1033
1034 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1035 /*
1036 * Set the timestamp type.
1037 * (Yes, we require PacketGetTimestampModes(), not just
1038 * PacketSetTimestampMode(). If we have the former, we
1039 * have the latter, unless somebody's using a version
1040 * of Npcap that they've hacked to provide the former
1041 * but not the latter; if they've done that, either
1042 * they're confused or they're trolling us.)
1043 */
1044 switch (p->opt.tstamp_type) {
1045
1046 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED:
1047 /*
1048 * Better than low-res, but *not* synchronized with
1049 * the OS clock.
1050 */
1051 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION))
1052 {
1053 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1054 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1055 goto bad;
1056 }
1057 break;
1058
1059 case PCAP_TSTAMP_HOST_LOWPREC:
1060 /*
1061 * Low-res, but synchronized with the OS clock.
1062 */
1063 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME))
1064 {
1065 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1066 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1067 goto bad;
1068 }
1069 break;
1070
1071 case PCAP_TSTAMP_HOST_HIPREC:
1072 /*
1073 * High-res, and synchronized with the OS clock.
1074 */
1075 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE))
1076 {
1077 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1078 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1079 goto bad;
1080 }
1081 break;
1082
1083 case PCAP_TSTAMP_HOST:
1084 /*
1085 * XXX - do whatever the default is, for now.
1086 * Set to the highest resolution that's synchronized
1087 * with the system clock?
1088 */
1089 break;
1090 }
1091 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1092
1093 #if defined(HAVE_PACKET_GET_INFO) && defined(NPF_GETINFO_BPFEXT) && defined(SKF_AD_VLAN_TAG_PRESENT)
1094
1095 /* Can we generate special code for VLAN checks? */
1096 oid_data_arg->Oid = NPF_GETINFO_BPFEXT;
1097 oid_data_arg->Length = sizeof(ULONG);
1098 if (PacketGetInfo(pw->adapter, oid_data_arg)) {
1099 if (*((ULONG *)oid_data_arg->Data) >= SKF_AD_VLAN_TAG_PRESENT) {
1100 /* Yes, we can. Request that we do so. */
1101 p->bpf_codegen_flags |= BPF_SPECIAL_VLAN_HANDLING;
1102 }
1103 }
1104 else {
1105 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1106 GetLastError(), "Error calling PacketGetInfo");
1107 }
1108 #endif /* HAVE_PACKET_GET_INFO */
1109
1110 /*
1111 * Turn a negative snapshot value (invalid), a snapshot value of
1112 * 0 (unspecified), or a value bigger than the normal maximum
1113 * value, into the maximum allowed value.
1114 *
1115 * If some application really *needs* a bigger snapshot
1116 * length, we should just increase MAXIMUM_SNAPLEN.
1117 */
1118 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1119 p->snapshot = MAXIMUM_SNAPLEN;
1120
1121 /* Set promiscuous mode */
1122 if (p->opt.promisc)
1123 {
1124 /*
1125 * For future reference, in case we ever want to query
1126 * whether an adapter supports promiscuous mode, that
1127 * would be done on Windows by querying the value
1128 * of the OID_GEN_SUPPORTED_PACKET_FILTERS OID.
1129 */
1130 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1131 {
1132 DWORD errcode = GetLastError();
1133
1134 /*
1135 * Suppress spurious error generated by non-compliant
1136 * MS Surface mobile adapters that appear to
1137 * return NDIS_STATUS_NOT_SUPPORTED for attempts
1138 * to set the hardware filter.
1139 *
1140 * It appears to be reporting NDIS_STATUS_NOT_SUPPORTED,
1141 * but with the NT status value "Customer" bit set;
1142 * the Npcap NPF driver sets that bit in some cases.
1143 *
1144 * If we knew that this meant "promiscuous mode
1145 * isn't supported", we could add a "promiscuous
1146 * mode isn't supported" error code and return
1147 * that, but:
1148 *
1149 * 1) we don't know that it means that
1150 * rather than meaning "we reject attempts
1151 * to set the filter, even though the NDIS
1152 * specifications say you shouldn't do that"
1153 *
1154 * and
1155 *
1156 * 2) other interface types that don't
1157 * support promiscuous mode, at least
1158 * on UN*Xes, just silently ignore
1159 * attempts to set promiscuous mode
1160 *
1161 * and rejecting it with an error could disrupt
1162 * attempts to capture, as many programs (tcpdump,
1163 * *shark) default to promiscuous mode.
1164 *
1165 * Alternatively, we could return the "promiscuous
1166 * mode not supported" *warning* value, so that
1167 * correct code will either ignore it or report
1168 * it and continue capturing. (This may require
1169 * a pcap_init() flag to request that return
1170 * value, so that old incorrect programs that
1171 * assume a non-zero return from pcap_activate()
1172 * is an error don't break.)
1173 *
1174 * We check here for ERROR_NOT_SUPPORTED, which
1175 * is what NDIS_STATUS_NOT_SUPPORTED (which is
1176 * the same value as the NTSTATUS value
1177 * STATUS_NOT_SUPPORTED) gets mapped to, as
1178 * well as NDIS_STATUS_NOT_SUPPORTED with the
1179 * "Customer" bit set.
1180 */
1181 if (errcode != ERROR_NOT_SUPPORTED &&
1182 errcode != (NDIS_STATUS_NOT_SUPPORTED|NT_STATUS_CUSTOMER_DEFINED))
1183 {
1184 pcapint_fmt_errmsg_for_win32_err(p->errbuf,
1185 PCAP_ERRBUF_SIZE, errcode,
1186 "failed to set hardware filter to promiscuous mode");
1187 goto bad;
1188 }
1189 }
1190 }
1191 else
1192 {
1193 /*
1194 * NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by
1195 * installed protocols and all packets indicated by the NIC",
1196 * but if no protocol drivers (like TCP/IP) are installed,
1197 * NDIS_PACKET_TYPE_DIRECTED, NDIS_PACKET_TYPE_BROADCAST,
1198 * and NDIS_PACKET_TYPE_MULTICAST are needed to capture
1199 * incoming frames.
1200 */
1201 if (PacketSetHwFilter(pw->adapter,
1202 NDIS_PACKET_TYPE_ALL_LOCAL |
1203 NDIS_PACKET_TYPE_DIRECTED |
1204 NDIS_PACKET_TYPE_BROADCAST |
1205 NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1206 {
1207 DWORD errcode = GetLastError();
1208
1209 /*
1210 * Suppress spurious error generated by non-compliant
1211 * MS Surface mobile adapters.
1212 */
1213 if (errcode != (NDIS_STATUS_NOT_SUPPORTED|NT_STATUS_CUSTOMER_DEFINED))
1214 {
1215 pcapint_fmt_errmsg_for_win32_err(p->errbuf,
1216 PCAP_ERRBUF_SIZE, errcode,
1217 "failed to set hardware filter to non-promiscuous mode");
1218 goto bad;
1219 }
1220 }
1221 }
1222
1223 /* Set the buffer size */
1224 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1225
1226 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1227 {
1228 /*
1229 * Traditional Adapter
1230 */
1231 /*
1232 * If the buffer size wasn't explicitly set, default to
1233 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1234 */
1235 if (p->opt.buffer_size == 0)
1236 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1237
1238 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1239 {
1240 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1241 goto bad;
1242 }
1243
1244 p->buffer = malloc(p->bufsize);
1245 if (p->buffer == NULL)
1246 {
1247 pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1248 errno, "malloc");
1249 goto bad;
1250 }
1251
1252 if (p->opt.immediate)
1253 {
1254 /* tell the driver to copy the buffer as soon as data arrives */
1255 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1256 {
1257 pcapint_fmt_errmsg_for_win32_err(p->errbuf,
1258 PCAP_ERRBUF_SIZE, GetLastError(),
1259 "Error calling PacketSetMinToCopy");
1260 goto bad;
1261 }
1262 }
1263 else
1264 {
1265 /* tell the driver to copy the buffer only if it contains at least 16K */
1266 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1267 {
1268 pcapint_fmt_errmsg_for_win32_err(p->errbuf,
1269 PCAP_ERRBUF_SIZE, GetLastError(),
1270 "Error calling PacketSetMinToCopy");
1271 goto bad;
1272 }
1273 }
1274 } else {
1275 goto bad;
1276 }
1277
1278 /*
1279 * If there's no filter program installed, there's
1280 * no indication to the kernel of what the snapshot
1281 * length should be, so no snapshotting is done.
1282 *
1283 * Therefore, when we open the device, we install
1284 * an "accept everything" filter with the specified
1285 * snapshot length.
1286 */
1287 total_insn.code = (u_short)(BPF_RET | BPF_K);
1288 total_insn.jt = 0;
1289 total_insn.jf = 0;
1290 total_insn.k = p->snapshot;
1291
1292 total_prog.bf_len = 1;
1293 total_prog.bf_insns = &total_insn;
1294 if (!PacketSetBpf(pw->adapter, &total_prog)) {
1295 pcapint_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1296 GetLastError(), "PacketSetBpf");
1297 status = PCAP_ERROR;
1298 goto bad;
1299 }
1300
1301 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1302
1303 /* disable loopback capture if requested */
1304 if (p->opt.nocapture_local)
1305 {
1306 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1307 {
1308 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1309 "Unable to disable the capture of loopback packets.");
1310 goto bad;
1311 }
1312 }
1313
1314 /* install traditional npf handlers for read and setfilter */
1315 p->read_op = pcap_read_npf;
1316 p->setfilter_op = pcap_setfilter_npf;
1317 p->setdirection_op = NULL; /* Not implemented. */
1318 /* XXX - can this be implemented on some versions of Windows? */
1319 p->inject_op = pcap_inject_npf;
1320 p->set_datalink_op = NULL; /* can't change data link type */
1321 p->getnonblock_op = pcap_getnonblock_npf;
1322 p->setnonblock_op = pcap_setnonblock_npf;
1323 p->stats_op = pcap_stats_npf;
1324 p->breakloop_op = pcap_breakloop_npf;
1325 p->stats_ex_op = pcap_stats_ex_npf;
1326 p->setbuff_op = pcap_setbuff_npf;
1327 p->setmode_op = pcap_setmode_npf;
1328 p->setmintocopy_op = pcap_setmintocopy_npf;
1329 p->getevent_op = pcap_getevent_npf;
1330 p->oid_get_request_op = pcap_oid_get_request_npf;
1331 p->oid_set_request_op = pcap_oid_set_request_npf;
1332 p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1333 p->setuserbuffer_op = pcap_setuserbuffer_npf;
1334 p->live_dump_op = pcap_live_dump_npf;
1335 p->live_dump_ended_op = pcap_live_dump_ended_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 /*
1905 * Get the hardware status, and derive "up" and "running" from
1906 * that.
1907 */
1908 len = sizeof (hardware_status);
1909 status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
1910 &hardware_status, &len, errbuf);
1911 if (status == 0) {
1912 switch (hardware_status) {
1913
1914 case NdisHardwareStatusReady:
1915 /*
1916 * "Available and capable of sending and receiving
1917 * data over the wire", so up and running.
1918 */
1919 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1920 break;
1921
1922 case NdisHardwareStatusInitializing:
1923 case NdisHardwareStatusReset:
1924 /*
1925 * "Initializing" or "Resetting", so up, but
1926 * not running.
1927 */
1928 *flags |= PCAP_IF_UP;
1929 break;
1930
1931 case NdisHardwareStatusClosing:
1932 case NdisHardwareStatusNotReady:
1933 /*
1934 * "Closing" or "Not ready", so neither up nor
1935 * running.
1936 */
1937 break;
1938
1939 default:
1940 /*
1941 * Unknown.
1942 */
1943 break;
1944 }
1945 } else {
1946 /*
1947 * Can't get the hardware status, so assume both up and
1948 * running.
1949 */
1950 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1951 }
1952
1953 /*
1954 * Get the network type.
1955 */
1956 #ifdef OID_GEN_PHYSICAL_MEDIUM
1957 /*
1958 * Try the OIDs we have for this, in order.
1959 */
1960 for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
1961 len = sizeof (phys_medium);
1962 status = oid_get_request(adapter, gen_physical_medium_oids[i],
1963 &phys_medium, &len, errbuf);
1964 if (status == 0) {
1965 /*
1966 * Success.
1967 */
1968 break;
1969 }
1970 /*
1971 * Failed. We can't determine whether it failed
1972 * because that particular OID isn't supported
1973 * or because some other problem occurred, so we
1974 * just drive on and try the next OID.
1975 */
1976 }
1977 if (status == 0) {
1978 /*
1979 * We got the physical medium.
1980 *
1981 * XXX - we might want to check for NdisPhysicalMediumWiMax
1982 * and NdisPhysicalMediumNative802_15_4 being
1983 * part of the enum, and check for those in the "wireless"
1984 * case.
1985 */
1986 DIAG_OFF_ENUM_SWITCH
1987 switch (phys_medium) {
1988
1989 case NdisPhysicalMediumWirelessLan:
1990 case NdisPhysicalMediumWirelessWan:
1991 case NdisPhysicalMediumNative802_11:
1992 case NdisPhysicalMediumBluetooth:
1993 case NdisPhysicalMediumUWB:
1994 case NdisPhysicalMediumIrda:
1995 /*
1996 * Wireless.
1997 */
1998 *flags |= PCAP_IF_WIRELESS;
1999 break;
2000
2001 default:
2002 /*
2003 * Not wireless or unknown
2004 */
2005 break;
2006 }
2007 DIAG_ON_ENUM_SWITCH
2008 }
2009 #endif
2010
2011 /*
2012 * Get the connection status.
2013 */
2014 #ifdef OID_GEN_LINK_STATE
2015 len = sizeof(link_state);
2016 status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
2017 &len, errbuf);
2018 if (status == 0) {
2019 /*
2020 * NOTE: this also gives us the receive and transmit
2021 * link state.
2022 */
2023 switch (link_state.MediaConnectState) {
2024
2025 case MediaConnectStateConnected:
2026 /*
2027 * It's connected.
2028 */
2029 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2030 break;
2031
2032 case MediaConnectStateDisconnected:
2033 /*
2034 * It's disconnected.
2035 */
2036 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2037 break;
2038
2039 case MediaConnectStateUnknown:
2040 default:
2041 /*
2042 * It's unknown whether it's connected or not.
2043 */
2044 break;
2045 }
2046 }
2047 #else
2048 /*
2049 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2050 */
2051 status = -1;
2052 #endif
2053 if (status == -1) {
2054 /*
2055 * OK, OID_GEN_LINK_STATE didn't work, try
2056 * OID_GEN_MEDIA_CONNECT_STATUS.
2057 */
2058 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
2059 &connect_status, &len, errbuf);
2060 if (status == 0) {
2061 switch (connect_status) {
2062
2063 case NdisMediaStateConnected:
2064 /*
2065 * It's connected.
2066 */
2067 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2068 break;
2069
2070 case NdisMediaStateDisconnected:
2071 /*
2072 * It's disconnected.
2073 */
2074 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2075 break;
2076 }
2077 }
2078 }
2079 PacketCloseAdapter(adapter);
2080 return (0);
2081 }
2082
2083 int
2084 pcapint_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2085 {
2086 int ret = 0;
2087 const char *desc;
2088 char *AdaptersName;
2089 ULONG NameLength;
2090 char *name;
2091
2092 /*
2093 * Find out how big a buffer we need.
2094 *
2095 * This call should always return FALSE; if the error is
2096 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2097 * the size of the buffer we need, otherwise there's a
2098 * problem, and NameLength should be set to 0.
2099 *
2100 * It shouldn't require NameLength to be set, but,
2101 * at least as of WinPcap 4.1.3, it checks whether
2102 * NameLength is big enough before it checks for a
2103 * NULL buffer argument, so, while it'll still do
2104 * the right thing if NameLength is uninitialized and
2105 * whatever junk happens to be there is big enough
2106 * (because the pointer argument will be null), it's
2107 * still reading an uninitialized variable.
2108 */
2109 NameLength = 0;
2110 if (!PacketGetAdapterNames(NULL, &NameLength))
2111 {
2112 DWORD last_error = GetLastError();
2113
2114 if (last_error != ERROR_INSUFFICIENT_BUFFER)
2115 {
2116 pcapint_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2117 last_error, "PacketGetAdapterNames");
2118 return (-1);
2119 }
2120 }
2121
2122 if (NameLength <= 0)
2123 return 0;
2124 AdaptersName = (char*) malloc(NameLength);
2125 if (AdaptersName == NULL)
2126 {
2127 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
2128 return (-1);
2129 }
2130
2131 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
2132 pcapint_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2133 GetLastError(), "PacketGetAdapterNames");
2134 free(AdaptersName);
2135 return (-1);
2136 }
2137
2138 /*
2139 * "PacketGetAdapterNames()" returned a list of
2140 * null-terminated ASCII interface name strings,
2141 * terminated by a null string, followed by a list
2142 * of null-terminated ASCII interface description
2143 * strings, terminated by a null string.
2144 * This means there are two ASCII nulls at the end
2145 * of the first list.
2146 *
2147 * Find the end of the first list; that's the
2148 * beginning of the second list.
2149 */
2150 desc = &AdaptersName[0];
2151 while (*desc != '\0' || *(desc + 1) != '\0')
2152 desc++;
2153
2154 /*
2155 * Found it - "desc" points to the first of the two
2156 * nulls at the end of the list of names, so the
2157 * first byte of the list of descriptions is two bytes
2158 * after it.
2159 */
2160 desc += 2;
2161
2162 /*
2163 * Loop over the elements in the first list.
2164 */
2165 name = &AdaptersName[0];
2166 while (*name != '\0') {
2167 bpf_u_int32 flags = 0;
2168
2169 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2170 /*
2171 * Is this a loopback interface?
2172 */
2173 if (PacketIsLoopbackAdapter(name)) {
2174 /* Yes */
2175 flags |= PCAP_IF_LOOPBACK;
2176 }
2177 #endif
2178 /*
2179 * Get additional flags.
2180 */
2181 if (get_if_flags(name, &flags, errbuf) == -1) {
2182 /*
2183 * Failure.
2184 */
2185 ret = -1;
2186 break;
2187 }
2188
2189 /*
2190 * Add an entry for this interface.
2191 */
2192 if (pcap_add_if_npf(devlistp, name, flags, desc,
2193 errbuf) == -1) {
2194 /*
2195 * Failure.
2196 */
2197 ret = -1;
2198 break;
2199 }
2200 name += strlen(name) + 1;
2201 desc += strlen(desc) + 1;
2202 }
2203
2204 free(AdaptersName);
2205 return (ret);
2206 }
2207
2208 /*
2209 * Return the name of a network interface attached to the system, or NULL
2210 * if none can be found. The interface must be configured up; the
2211 * lowest unit number is preferred; loopback is ignored.
2212 *
2213 * In the best of all possible worlds, this would be the same as on
2214 * UN*X, but there may be software that expects this to return a
2215 * full list of devices after the first device.
2216 */
2217 #define ADAPTERSNAME_LEN 8192
2218 char *
2219 pcap_lookupdev(char *errbuf)
2220 {
2221 DWORD dwVersion;
2222 DWORD dwWindowsMajorVersion;
2223
2224 /*
2225 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2226 * it may return UTF-16 strings, for backwards-compatibility
2227 * reasons, and we're also disabling the hack to make that work,
2228 * for not-going-past-the-end-of-a-string reasons, and 2) we
2229 * want its behavior to be consistent.
2230 *
2231 * In addition, it's not thread-safe, so we've marked it as
2232 * deprecated.
2233 */
2234 if (pcapint_new_api) {
2235 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2236 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2237 return (NULL);
2238 }
2239
2240 /* disable MSVC's GetVersion() deprecated warning here */
2241 DIAG_OFF_DEPRECATION
2242 dwVersion = GetVersion(); /* get the OS version */
2243 DIAG_ON_DEPRECATION
2244 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
2245
2246 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
2247 /*
2248 * Windows 95, 98, ME.
2249 */
2250 ULONG NameLength = ADAPTERSNAME_LEN;
2251 static char AdaptersName[ADAPTERSNAME_LEN];
2252
2253 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
2254 return (AdaptersName);
2255 else
2256 return NULL;
2257 } else {
2258 /*
2259 * Windows NT (NT 4.0 and later).
2260 * Convert the names to Unicode for backward compatibility.
2261 */
2262 ULONG NameLength = ADAPTERSNAME_LEN;
2263 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
2264 size_t BufferSpaceLeft;
2265 char *tAstr;
2266 WCHAR *Unameptr;
2267 char *Adescptr;
2268 size_t namelen, i;
2269 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
2270 int NAdapts = 0;
2271
2272 if(TAdaptersName == NULL)
2273 {
2274 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
2275 return NULL;
2276 }
2277
2278 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
2279 {
2280 pcapint_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2281 GetLastError(), "PacketGetAdapterNames");
2282 free(TAdaptersName);
2283 return NULL;
2284 }
2285
2286
2287 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
2288 tAstr = (char*)TAdaptersName;
2289 Unameptr = AdaptersName;
2290
2291 /*
2292 * Convert the device names to Unicode into AdapterName.
2293 */
2294 do {
2295 /*
2296 * Length of the name, including the terminating
2297 * NUL.
2298 */
2299 namelen = strlen(tAstr) + 1;
2300
2301 /*
2302 * Do we have room for the name in the Unicode
2303 * buffer?
2304 */
2305 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
2306 /*
2307 * No.
2308 */
2309 goto quit;
2310 }
2311 BufferSpaceLeft -= namelen * sizeof(WCHAR);
2312
2313 /*
2314 * Copy the name, converting ASCII to Unicode.
2315 * namelen includes the NUL, so we copy it as
2316 * well.
2317 */
2318 for (i = 0; i < namelen; i++)
2319 *Unameptr++ = *tAstr++;
2320
2321 /*
2322 * Count this adapter.
2323 */
2324 NAdapts++;
2325 } while (namelen != 1);
2326
2327 /*
2328 * Copy the descriptions, but don't convert them from
2329 * ASCII to Unicode.
2330 */
2331 Adescptr = (char *)Unameptr;
2332 while(NAdapts--)
2333 {
2334 size_t desclen;
2335
2336 desclen = strlen(tAstr) + 1;
2337
2338 /*
2339 * Do we have room for the name in the Unicode
2340 * buffer?
2341 */
2342 if (BufferSpaceLeft < desclen) {
2343 /*
2344 * No.
2345 */
2346 goto quit;
2347 }
2348
2349 /*
2350 * Just copy the ASCII string.
2351 * namelen includes the NUL, so we copy it as
2352 * well.
2353 */
2354 memcpy(Adescptr, tAstr, desclen);
2355 Adescptr += desclen;
2356 tAstr += desclen;
2357 BufferSpaceLeft -= desclen;
2358 }
2359
2360 quit:
2361 free(TAdaptersName);
2362 return (char *)(AdaptersName);
2363 }
2364 }
2365
2366 /*
2367 * We can't use the same code that we use on UN*X, as that's doing
2368 * UN*X-specific calls.
2369 *
2370 * We don't just fetch the entire list of devices, search for the
2371 * particular device, and use its first IPv4 address, as that's too
2372 * much work to get just one device's netmask.
2373 */
2374 int
2375 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
2376 char *errbuf)
2377 {
2378 /*
2379 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2380 * in order to skip non IPv4 (i.e. IPv6 addresses)
2381 */
2382 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2383 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
2384 struct sockaddr_in *t_addr;
2385 LONG i;
2386
2387 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
2388 *netp = *maskp = 0;
2389 return (0);
2390 }
2391
2392 for(i = 0; i < if_addr_size; i++)
2393 {
2394 if(if_addrs[i].IPAddress.ss_family == AF_INET)
2395 {
2396 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
2397 *netp = t_addr->sin_addr.S_un.S_addr;
2398 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
2399 *maskp = t_addr->sin_addr.S_un.S_addr;
2400
2401 *netp &= *maskp;
2402 return (0);
2403 }
2404
2405 }
2406
2407 *netp = *maskp = 0;
2408 return (0);
2409 }
2410
2411 static const char *pcap_lib_version_string;
2412
2413 #ifdef HAVE_VERSION_H
2414 /*
2415 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2416 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2417 * version.
2418 *
2419 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2420 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2421 * for the packet.dll version number as well.)
2422 */
2423 #include "../../version.h"
2424
2425 static const char pcap_version_string[] =
2426 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2427
2428 const char *
2429 pcap_lib_version(void)
2430 {
2431 if (pcap_lib_version_string == NULL) {
2432 /*
2433 * Generate the version string.
2434 */
2435 const char *packet_version_string = PacketGetVersion();
2436
2437 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2438 /*
2439 * WinPcap/Npcap version string and packet.dll version
2440 * string are the same; just report the WinPcap/Npcap
2441 * version.
2442 */
2443 pcap_lib_version_string = pcap_version_string;
2444 } else {
2445 /*
2446 * WinPcap/Npcap version string and packet.dll version
2447 * string are different; that shouldn't be the
2448 * case (the two libraries should come from the
2449 * same version of WinPcap/Npcap), so we report both
2450 * versions.
2451 */
2452 char *full_pcap_version_string;
2453
2454 if (pcapint_asprintf(&full_pcap_version_string,
2455 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING,
2456 packet_version_string) != -1) {
2457 /* Success */
2458 pcap_lib_version_string = full_pcap_version_string;
2459 }
2460 }
2461 }
2462 return (pcap_lib_version_string);
2463 }
2464
2465 #else /* HAVE_VERSION_H */
2466
2467 /*
2468 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2469 * tree.
2470 */
2471 const char *
2472 pcap_lib_version(void)
2473 {
2474 if (pcap_lib_version_string == NULL) {
2475 /*
2476 * Generate the version string. Report the packet.dll
2477 * version.
2478 */
2479 char *full_pcap_version_string;
2480
2481 if (pcapint_asprintf(&full_pcap_version_string,
2482 PCAP_VERSION_STRING " (packet.dll version %s)",
2483 PacketGetVersion()) != -1) {
2484 /* Success */
2485 pcap_lib_version_string = full_pcap_version_string;
2486 }
2487 }
2488 return (pcap_lib_version_string);
2489 }
2490 #endif /* HAVE_VERSION_H */