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