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