]> The Tcpdump Group git mirrors - libpcap/blob - pcap-npf.c
Fix Bison detection for minor version 0. [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 #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 static int
943 pcap_activate_npf(pcap_t *p)
944 {
945 struct pcap_win *pw = p->priv;
946 NetType type;
947 int res;
948 int status = 0;
949 struct bpf_insn total_insn;
950 struct bpf_program total_prog;
951
952 if (p->opt.rfmon) {
953 /*
954 * Monitor mode is supported on Windows Vista and later.
955 */
956 if (PacketGetMonitorMode(p->opt.device) == 1)
957 {
958 pw->rfmon_selfstart = 0;
959 }
960 else
961 {
962 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
963 {
964 pw->rfmon_selfstart = 0;
965 // Monitor mode is not supported.
966 if (res == 0)
967 {
968 return PCAP_ERROR_RFMON_NOTSUP;
969 }
970 else
971 {
972 return PCAP_ERROR;
973 }
974 }
975 else
976 {
977 pw->rfmon_selfstart = 1;
978 }
979 }
980 }
981
982 /* Init Winsock if it hasn't already been initialized */
983 pcap_wsockinit();
984
985 pw->adapter = PacketOpenAdapter(p->opt.device);
986
987 if (pw->adapter == NULL)
988 {
989 DWORD errcode = GetLastError();
990
991 /*
992 * What error did we get when trying to open the adapter?
993 */
994 switch (errcode) {
995
996 case ERROR_BAD_UNIT:
997 /*
998 * There's no such device.
999 */
1000 return (PCAP_ERROR_NO_SUCH_DEVICE);
1001
1002 case ERROR_ACCESS_DENIED:
1003 /*
1004 * There is, but we don't have permission to
1005 * use it.
1006 */
1007 return (PCAP_ERROR_PERM_DENIED);
1008
1009 default:
1010 /*
1011 * Unknown - report details.
1012 */
1013 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1014 errcode, "Error opening adapter");
1015 if (pw->rfmon_selfstart)
1016 {
1017 PacketSetMonitorMode(p->opt.device, 0);
1018 }
1019 return (PCAP_ERROR);
1020 }
1021 }
1022
1023 /*get network type*/
1024 if(PacketGetNetType (pw->adapter,&type) == FALSE)
1025 {
1026 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1027 GetLastError(), "Cannot determine the network type");
1028 goto bad;
1029 }
1030
1031 /*Set the linktype*/
1032 switch (type.LinkType)
1033 {
1034 case NdisMediumWan:
1035 p->linktype = DLT_EN10MB;
1036 break;
1037
1038 case NdisMedium802_3:
1039 p->linktype = DLT_EN10MB;
1040 /*
1041 * This is (presumably) a real Ethernet capture; give it a
1042 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1043 * that an application can let you choose it, in case you're
1044 * capturing DOCSIS traffic that a Cisco Cable Modem
1045 * Termination System is putting out onto an Ethernet (it
1046 * doesn't put an Ethernet header onto the wire, it puts raw
1047 * DOCSIS frames out on the wire inside the low-level
1048 * Ethernet framing).
1049 */
1050 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1051 /*
1052 * If that fails, just leave the list empty.
1053 */
1054 if (p->dlt_list != NULL) {
1055 p->dlt_list[0] = DLT_EN10MB;
1056 p->dlt_list[1] = DLT_DOCSIS;
1057 p->dlt_count = 2;
1058 }
1059 break;
1060
1061 case NdisMediumFddi:
1062 p->linktype = DLT_FDDI;
1063 break;
1064
1065 case NdisMedium802_5:
1066 p->linktype = DLT_IEEE802;
1067 break;
1068
1069 case NdisMediumArcnetRaw:
1070 p->linktype = DLT_ARCNET;
1071 break;
1072
1073 case NdisMediumArcnet878_2:
1074 p->linktype = DLT_ARCNET;
1075 break;
1076
1077 case NdisMediumAtm:
1078 p->linktype = DLT_ATM_RFC1483;
1079 break;
1080
1081 case NdisMediumCHDLC:
1082 p->linktype = DLT_CHDLC;
1083 break;
1084
1085 case NdisMediumPPPSerial:
1086 p->linktype = DLT_PPP_SERIAL;
1087 break;
1088
1089 case NdisMediumNull:
1090 p->linktype = DLT_NULL;
1091 break;
1092
1093 case NdisMediumBare80211:
1094 p->linktype = DLT_IEEE802_11;
1095 break;
1096
1097 case NdisMediumRadio80211:
1098 p->linktype = DLT_IEEE802_11_RADIO;
1099 break;
1100
1101 case NdisMediumPpi:
1102 p->linktype = DLT_PPI;
1103 break;
1104
1105 case NdisMediumWirelessWan:
1106 p->linktype = DLT_RAW;
1107 break;
1108
1109 default:
1110 /*
1111 * An unknown medium type is assumed to supply Ethernet
1112 * headers; if not, the user will have to report it,
1113 * so that the medium type and link-layer header type
1114 * can be determined. If we were to fail here, we
1115 * might get the link-layer type in the error, but
1116 * the user wouldn't get a capture, so we wouldn't
1117 * be able to determine the link-layer type; we report
1118 * a warning with the link-layer type, so at least
1119 * some programs will report the warning.
1120 */
1121 p->linktype = DLT_EN10MB;
1122 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1123 "Unknown NdisMedium value %d, defaulting to DLT_EN10MB",
1124 type.LinkType);
1125 status = PCAP_WARNING;
1126 break;
1127 }
1128
1129 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1130 /*
1131 * Set the timestamp type.
1132 * (Yes, we require PacketGetTimestampModes(), not just
1133 * PacketSetTimestampMode(). If we have the former, we
1134 * have the latter, unless somebody's using a version
1135 * of Npcap that they've hacked to provide the former
1136 * but not the latter; if they've done that, either
1137 * they're confused or they're trolling us.)
1138 */
1139 switch (p->opt.tstamp_type) {
1140
1141 case PCAP_TSTAMP_HOST_HIPREC_UNSYNCED:
1142 /*
1143 * Better than low-res, but *not* synchronized with
1144 * the OS clock.
1145 */
1146 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_SINGLE_SYNCHRONIZATION))
1147 {
1148 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1149 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_SINGLE_SYNCHRONIZATION");
1150 goto bad;
1151 }
1152 break;
1153
1154 case PCAP_TSTAMP_HOST_LOWPREC:
1155 /*
1156 * Low-res, but synchronized with the OS clock.
1157 */
1158 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME))
1159 {
1160 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1161 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME");
1162 goto bad;
1163 }
1164 break;
1165
1166 case PCAP_TSTAMP_HOST_HIPREC:
1167 /*
1168 * High-res, and synchronized with the OS clock.
1169 */
1170 if (!PacketSetTimestampMode(pw->adapter, TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE))
1171 {
1172 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1173 GetLastError(), "Cannot set the time stamp mode to TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE");
1174 goto bad;
1175 }
1176 break;
1177
1178 case PCAP_TSTAMP_HOST:
1179 /*
1180 * XXX - do whatever the default is, for now.
1181 * Set to the highest resolution that's synchronized
1182 * with the system clock?
1183 */
1184 break;
1185 }
1186 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1187
1188 /*
1189 * Turn a negative snapshot value (invalid), a snapshot value of
1190 * 0 (unspecified), or a value bigger than the normal maximum
1191 * value, into the maximum allowed value.
1192 *
1193 * If some application really *needs* a bigger snapshot
1194 * length, we should just increase MAXIMUM_SNAPLEN.
1195 */
1196 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1197 p->snapshot = MAXIMUM_SNAPLEN;
1198
1199 /* Set promiscuous mode */
1200 if (p->opt.promisc)
1201 {
1202
1203 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1204 {
1205 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1206 PCAP_ERRBUF_SIZE, GetLastError(),
1207 "failed to set hardware filter to promiscuous mode");
1208 goto bad;
1209 }
1210 }
1211 else
1212 {
1213 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1214 * protocols and all packets indicated by the NIC" but if no protocol
1215 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1216 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1217 * capture incoming frames.
1218 */
1219 if (PacketSetHwFilter(pw->adapter,
1220 NDIS_PACKET_TYPE_ALL_LOCAL |
1221 NDIS_PACKET_TYPE_DIRECTED |
1222 NDIS_PACKET_TYPE_BROADCAST |
1223 NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1224 {
1225 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1226 PCAP_ERRBUF_SIZE, GetLastError(),
1227 "failed to set hardware filter to non-promiscuous mode");
1228 goto bad;
1229 }
1230 }
1231
1232 /* Set the buffer size */
1233 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1234
1235 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1236 {
1237 /*
1238 * Traditional Adapter
1239 */
1240 /*
1241 * If the buffer size wasn't explicitly set, default to
1242 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1243 */
1244 if (p->opt.buffer_size == 0)
1245 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1246
1247 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1248 {
1249 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1250 goto bad;
1251 }
1252
1253 p->buffer = malloc(p->bufsize);
1254 if (p->buffer == NULL)
1255 {
1256 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1257 errno, "malloc");
1258 goto bad;
1259 }
1260
1261 if (p->opt.immediate)
1262 {
1263 /* tell the driver to copy the buffer as soon as data arrives */
1264 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1265 {
1266 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1267 PCAP_ERRBUF_SIZE, GetLastError(),
1268 "Error calling PacketSetMinToCopy");
1269 goto bad;
1270 }
1271 }
1272 else
1273 {
1274 /* tell the driver to copy the buffer only if it contains at least 16K */
1275 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1276 {
1277 pcap_fmt_errmsg_for_win32_err(p->errbuf,
1278 PCAP_ERRBUF_SIZE, GetLastError(),
1279 "Error calling PacketSetMinToCopy");
1280 goto bad;
1281 }
1282 }
1283 } else {
1284 /*
1285 * Dag Card
1286 */
1287 #ifdef HAVE_DAG_API
1288 /*
1289 * We have DAG support.
1290 */
1291 LONG status;
1292 HKEY dagkey;
1293 DWORD lptype;
1294 DWORD lpcbdata;
1295 int postype = 0;
1296 char keyname[512];
1297
1298 snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1299 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1300 strstr(_strlwr(p->opt.device), "dag"));
1301 do
1302 {
1303 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1304 if(status != ERROR_SUCCESS)
1305 break;
1306
1307 status = RegQueryValueEx(dagkey,
1308 "PosType",
1309 NULL,
1310 &lptype,
1311 (char*)&postype,
1312 &lpcbdata);
1313
1314 if(status != ERROR_SUCCESS)
1315 {
1316 postype = 0;
1317 }
1318
1319 RegCloseKey(dagkey);
1320 }
1321 while(FALSE);
1322
1323
1324 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1325
1326 /* Set the length of the FCS associated to any packet. This value
1327 * will be subtracted to the packet length */
1328 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1329 #else /* HAVE_DAG_API */
1330 /*
1331 * No DAG support.
1332 */
1333 goto bad;
1334 #endif /* HAVE_DAG_API */
1335 }
1336
1337 /*
1338 * If there's no filter program installed, there's
1339 * no indication to the kernel of what the snapshot
1340 * length should be, so no snapshotting is done.
1341 *
1342 * Therefore, when we open the device, we install
1343 * an "accept everything" filter with the specified
1344 * snapshot length.
1345 */
1346 total_insn.code = (u_short)(BPF_RET | BPF_K);
1347 total_insn.jt = 0;
1348 total_insn.jf = 0;
1349 total_insn.k = p->snapshot;
1350
1351 total_prog.bf_len = 1;
1352 total_prog.bf_insns = &total_insn;
1353 if (!PacketSetBpf(pw->adapter, &total_prog)) {
1354 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1355 GetLastError(), "PacketSetBpf");
1356 status = PCAP_ERROR;
1357 goto bad;
1358 }
1359
1360 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1361
1362 /* disable loopback capture if requested */
1363 if (p->opt.nocapture_local)
1364 {
1365 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1366 {
1367 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1368 "Unable to disable the capture of loopback packets.");
1369 goto bad;
1370 }
1371 }
1372
1373 #ifdef HAVE_DAG_API
1374 if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1375 {
1376 /* install dag specific handlers for read and setfilter */
1377 p->read_op = pcap_read_win32_dag;
1378 p->setfilter_op = pcap_setfilter_win32_dag;
1379 }
1380 else
1381 {
1382 #endif /* HAVE_DAG_API */
1383 /* install traditional npf handlers for read and setfilter */
1384 p->read_op = pcap_read_npf;
1385 p->setfilter_op = pcap_setfilter_npf;
1386 #ifdef HAVE_DAG_API
1387 }
1388 #endif /* HAVE_DAG_API */
1389 p->setdirection_op = NULL; /* Not implemented. */
1390 /* XXX - can this be implemented on some versions of Windows? */
1391 p->inject_op = pcap_inject_npf;
1392 p->set_datalink_op = NULL; /* can't change data link type */
1393 p->getnonblock_op = pcap_getnonblock_npf;
1394 p->setnonblock_op = pcap_setnonblock_npf;
1395 p->stats_op = pcap_stats_npf;
1396 p->breakloop_op = pcap_breakloop_npf;
1397 p->stats_ex_op = pcap_stats_ex_npf;
1398 p->setbuff_op = pcap_setbuff_npf;
1399 p->setmode_op = pcap_setmode_npf;
1400 p->setmintocopy_op = pcap_setmintocopy_npf;
1401 p->getevent_op = pcap_getevent_npf;
1402 p->oid_get_request_op = pcap_oid_get_request_npf;
1403 p->oid_set_request_op = pcap_oid_set_request_npf;
1404 p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1405 p->setuserbuffer_op = pcap_setuserbuffer_npf;
1406 p->live_dump_op = pcap_live_dump_npf;
1407 p->live_dump_ended_op = pcap_live_dump_ended_npf;
1408 p->get_airpcap_handle_op = pcap_get_airpcap_handle_npf;
1409 p->cleanup_op = pcap_cleanup_npf;
1410
1411 /*
1412 * XXX - this is only done because WinPcap supported
1413 * pcap_fileno() returning the hFile HANDLE from the
1414 * ADAPTER structure. We make no general guarantees
1415 * that the caller can do anything useful with it.
1416 *
1417 * (Not that we make any general guarantee of that
1418 * sort on UN*X, either, any more, given that not
1419 * all capture devices are regular OS network
1420 * interfaces.)
1421 */
1422 p->handle = pw->adapter->hFile;
1423
1424 return (status);
1425 bad:
1426 pcap_cleanup_npf(p);
1427 return (PCAP_ERROR);
1428 }
1429
1430 /*
1431 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1432 */
1433 static int
1434 pcap_can_set_rfmon_npf(pcap_t *p)
1435 {
1436 return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1437 }
1438
1439 pcap_t *
1440 pcap_create_interface(const char *device _U_, char *ebuf)
1441 {
1442 pcap_t *p;
1443 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1444 char *device_copy;
1445 ADAPTER *adapter;
1446 ULONG num_ts_modes;
1447 BOOL ret;
1448 DWORD error;
1449 ULONG *modes;
1450 #endif
1451
1452 p = PCAP_CREATE_COMMON(ebuf, struct pcap_win);
1453 if (p == NULL)
1454 return (NULL);
1455
1456 p->activate_op = pcap_activate_npf;
1457 p->can_set_rfmon_op = pcap_can_set_rfmon_npf;
1458
1459 #ifdef HAVE_PACKET_GET_TIMESTAMP_MODES
1460 /*
1461 * First, find out how many time stamp modes we have.
1462 * To do that, we have to open the adapter.
1463 *
1464 * XXX - PacketOpenAdapter() takes a non-const pointer
1465 * as an argument, so we make a copy of the argument and
1466 * pass that to it.
1467 */
1468 device_copy = strdup(device);
1469 adapter = PacketOpenAdapter(device_copy);
1470 free(device_copy);
1471 if (adapter != NULL)
1472 {
1473 /*
1474 * Get the total number of time stamp modes.
1475 *
1476 * The buffer for PacketGetTimestampModes() is
1477 * a sequence of 1 or more ULONGs. What's
1478 * passed to PacketGetTimestampModes() should have
1479 * the total number of ULONGs in the first ULONG;
1480 * what's returned *from* PacketGetTimestampModes()
1481 * has the total number of time stamp modes in
1482 * the first ULONG.
1483 *
1484 * Yes, that means if there are N time stamp
1485 * modes, the first ULONG should be set to N+1
1486 * on input, and will be set to N on output.
1487 *
1488 * We first make a call to PacketGetTimestampModes()
1489 * with a pointer to a single ULONG set to 1; the
1490 * call should fail with ERROR_MORE_DATA (unless
1491 * there are *no* modes, but that should never
1492 * happen), and that ULONG should be set to the
1493 * number of modes.
1494 */
1495 num_ts_modes = 1;
1496 ret = PacketGetTimestampModes(adapter, &num_ts_modes);
1497 if (!ret) {
1498 /*
1499 * OK, it failed. Did it fail with
1500 * ERROR_MORE_DATA?
1501 */
1502 error = GetLastError();
1503 if (error != ERROR_MORE_DATA) {
1504 /*
1505 * No, some other error. Fail.
1506 */
1507 pcap_fmt_errmsg_for_win32_err(ebuf,
1508 PCAP_ERRBUF_SIZE, GetLastError(),
1509 "Error calling PacketGetTimestampModes");
1510 pcap_close(p);
1511 return (NULL);
1512 }
1513
1514 /*
1515 * Yes, so we now know how many types to fetch.
1516 *
1517 * The buffer needs to have one ULONG for the
1518 * count and num_ts_modes ULONGs for the
1519 * num_ts_modes time stamp types.
1520 */
1521 modes = (ULONG *)malloc((1 + num_ts_modes) * sizeof(ULONG));
1522 if (modes == NULL) {
1523 /* Out of memory. */
1524 /* XXX SET ebuf */
1525 pcap_close(p);
1526 return (NULL);
1527 }
1528 modes[0] = 1 + num_ts_modes;
1529 if (!PacketGetTimestampModes(adapter, modes)) {
1530 pcap_fmt_errmsg_for_win32_err(ebuf,
1531 PCAP_ERRBUF_SIZE, GetLastError(),
1532 "Error calling PacketGetTimestampModes");
1533 free(modes);
1534 pcap_close(p);
1535 return (NULL);
1536 }
1537 if (modes[0] != num_ts_modes) {
1538 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1539 "First PacketGetTimestampModes() call gives %lu modes, second call gives %lu modes",
1540 num_ts_modes, modes[0]);
1541 free(modes);
1542 pcap_close(p);
1543 return (NULL);
1544 }
1545 if (num_ts_modes != 0) {
1546 u_int num_ts_types;
1547
1548 /*
1549 * Allocate a buffer big enough for
1550 * PCAP_TSTAMP_HOST (default) plus
1551 * the explicitly specified modes.
1552 */
1553 p->tstamp_type_list = malloc((1 + modes[0]) * sizeof(u_int));
1554 if (p->tstamp_type_list == NULL) {
1555 /* XXX SET ebuf */
1556 free(modes);
1557 pcap_close(p);
1558 return (NULL);
1559 }
1560 num_ts_types = 0;
1561 p->tstamp_type_list[num_ts_types] =
1562 PCAP_TSTAMP_HOST;
1563 num_ts_types++;
1564 for (ULONG i = 0; i < modes[0]; i++) {
1565 switch (modes[i + 1]) {
1566
1567 case TIMESTAMPMODE_SINGLE_SYNCHRONIZATION:
1568 /*
1569 * Better than low-res,
1570 * but *not* synchronized
1571 * with the OS clock.
1572 */
1573 p->tstamp_type_list[num_ts_types] =
1574 PCAP_TSTAMP_HOST_HIPREC_UNSYNCED;
1575 num_ts_types++;
1576 break;
1577
1578 case TIMESTAMPMODE_QUERYSYSTEMTIME:
1579 /*
1580 * Low-res, but synchronized
1581 * with the OS clock.
1582 */
1583 p->tstamp_type_list[num_ts_types] =
1584 PCAP_TSTAMP_HOST_LOWPREC;
1585 num_ts_types++;
1586 break;
1587
1588 case TIMESTAMPMODE_QUERYSYSTEMTIME_PRECISE:
1589 /*
1590 * High-res, and synchronized
1591 * with the OS clock.
1592 */
1593 p->tstamp_type_list[num_ts_types] =
1594 PCAP_TSTAMP_HOST_HIPREC;
1595 num_ts_types++;
1596 break;
1597
1598 default:
1599 /*
1600 * Unknown, so we can't
1601 * report it.
1602 */
1603 break;
1604 }
1605 }
1606 p->tstamp_type_count = num_ts_types;
1607 free(modes);
1608 }
1609 }
1610 PacketCloseAdapter(adapter);
1611 }
1612 #endif /* HAVE_PACKET_GET_TIMESTAMP_MODES */
1613
1614 return (p);
1615 }
1616
1617 static int
1618 pcap_setfilter_npf(pcap_t *p, struct bpf_program *fp)
1619 {
1620 struct pcap_win *pw = p->priv;
1621
1622 if(PacketSetBpf(pw->adapter,fp)==FALSE){
1623 /*
1624 * Kernel filter not installed.
1625 *
1626 * XXX - we don't know whether this failed because:
1627 *
1628 * the kernel rejected the filter program as invalid,
1629 * in which case we should fall back on userland
1630 * filtering;
1631 *
1632 * the kernel rejected the filter program as too big,
1633 * in which case we should again fall back on
1634 * userland filtering;
1635 *
1636 * there was some other problem, in which case we
1637 * should probably report an error.
1638 *
1639 * For NPF devices, the Win32 status will be
1640 * STATUS_INVALID_DEVICE_REQUEST for invalid
1641 * filters, but I don't know what it'd be for
1642 * other problems, and for some other devices
1643 * it might not be set at all.
1644 *
1645 * So we just fall back on userland filtering in
1646 * all cases.
1647 */
1648
1649 /*
1650 * install_bpf_program() validates the program.
1651 *
1652 * XXX - what if we already have a filter in the kernel?
1653 */
1654 if (install_bpf_program(p, fp) < 0)
1655 return (-1);
1656 pw->filtering_in_kernel = 0; /* filtering in userland */
1657 return (0);
1658 }
1659
1660 /*
1661 * It worked.
1662 */
1663 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1664
1665 /*
1666 * Discard any previously-received packets, as they might have
1667 * passed whatever filter was formerly in effect, but might
1668 * not pass this filter (BIOCSETF discards packets buffered
1669 * in the kernel, so you can lose packets in any case).
1670 */
1671 p->cc = 0;
1672 return (0);
1673 }
1674
1675 /*
1676 * We filter at user level, since the kernel driver doesn't process the packets
1677 */
1678 static int
1679 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1680
1681 if(!fp)
1682 {
1683 pcap_strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1684 return (-1);
1685 }
1686
1687 /* Install a user level filter */
1688 if (install_bpf_program(p, fp) < 0)
1689 return (-1);
1690
1691 return (0);
1692 }
1693
1694 static int
1695 pcap_getnonblock_npf(pcap_t *p)
1696 {
1697 struct pcap_win *pw = p->priv;
1698
1699 /*
1700 * XXX - if there were a PacketGetReadTimeout() call, we
1701 * would use it, and return 1 if the timeout is -1
1702 * and 0 otherwise.
1703 */
1704 return (pw->nonblock);
1705 }
1706
1707 static int
1708 pcap_setnonblock_npf(pcap_t *p, int nonblock)
1709 {
1710 struct pcap_win *pw = p->priv;
1711 int newtimeout;
1712
1713 if (nonblock) {
1714 /*
1715 * Set the packet buffer timeout to -1 for non-blocking
1716 * mode.
1717 */
1718 newtimeout = -1;
1719 } else {
1720 /*
1721 * Restore the timeout set when the device was opened.
1722 * (Note that this may be -1, in which case we're not
1723 * really leaving non-blocking mode. However, although
1724 * the timeout argument to pcap_set_timeout() and
1725 * pcap_open_live() is an int, you're not supposed to
1726 * supply a negative value, so that "shouldn't happen".)
1727 */
1728 newtimeout = p->opt.timeout;
1729 }
1730 if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1731 pcap_fmt_errmsg_for_win32_err(p->errbuf, PCAP_ERRBUF_SIZE,
1732 GetLastError(), "PacketSetReadTimeout");
1733 return (-1);
1734 }
1735 pw->nonblock = (newtimeout == -1);
1736 return (0);
1737 }
1738
1739 static int
1740 pcap_add_if_npf(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
1741 const char *description, char *errbuf)
1742 {
1743 pcap_if_t *curdev;
1744 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1745 LONG if_addr_size;
1746 int res = 0;
1747
1748 if_addr_size = MAX_NETWORK_ADDRESSES;
1749
1750 /*
1751 * Add an entry for this interface, with no addresses.
1752 */
1753 curdev = add_dev(devlistp, name, flags, description, errbuf);
1754 if (curdev == NULL) {
1755 /*
1756 * Failure.
1757 */
1758 return (-1);
1759 }
1760
1761 /*
1762 * Get the list of addresses for the interface.
1763 */
1764 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1765 /*
1766 * Failure.
1767 *
1768 * We don't return an error, because this can happen with
1769 * NdisWan interfaces, and we want to supply them even
1770 * if we can't supply their addresses.
1771 *
1772 * We return an entry with an empty address list.
1773 */
1774 return (0);
1775 }
1776
1777 /*
1778 * Now add the addresses.
1779 */
1780 while (if_addr_size-- > 0) {
1781 /*
1782 * "curdev" is an entry for this interface; add an entry for
1783 * this address to its list of addresses.
1784 */
1785 res = add_addr_to_dev(curdev,
1786 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1787 sizeof (struct sockaddr_storage),
1788 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1789 sizeof (struct sockaddr_storage),
1790 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1791 sizeof (struct sockaddr_storage),
1792 NULL,
1793 0,
1794 errbuf);
1795 if (res == -1) {
1796 /*
1797 * Failure.
1798 */
1799 break;
1800 }
1801 }
1802
1803 return (res);
1804 }
1805
1806 static int
1807 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
1808 {
1809 char *name_copy;
1810 ADAPTER *adapter;
1811 int status;
1812 size_t len;
1813 NDIS_HARDWARE_STATUS hardware_status;
1814 #ifdef OID_GEN_PHYSICAL_MEDIUM
1815 NDIS_PHYSICAL_MEDIUM phys_medium;
1816 bpf_u_int32 gen_physical_medium_oids[] = {
1817 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1818 OID_GEN_PHYSICAL_MEDIUM_EX,
1819 #endif
1820 OID_GEN_PHYSICAL_MEDIUM
1821 };
1822 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1823 size_t i;
1824 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1825 #ifdef OID_GEN_LINK_STATE
1826 NDIS_LINK_STATE link_state;
1827 #endif
1828 int connect_status;
1829
1830 if (*flags & PCAP_IF_LOOPBACK) {
1831 /*
1832 * Loopback interface, so the connection status doesn't
1833 * apply. and it's not wireless (or wired, for that
1834 * matter...). We presume it's up and running.
1835 */
1836 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING | PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1837 return (0);
1838 }
1839
1840 /*
1841 * We need to open the adapter to get this information.
1842 *
1843 * XXX - PacketOpenAdapter() takes a non-const pointer
1844 * as an argument, so we make a copy of the argument and
1845 * pass that to it.
1846 */
1847 name_copy = strdup(name);
1848 adapter = PacketOpenAdapter(name_copy);
1849 free(name_copy);
1850 if (adapter == NULL) {
1851 /*
1852 * Give up; if they try to open this device, it'll fail.
1853 */
1854 return (0);
1855 }
1856
1857 #ifdef HAVE_AIRPCAP_API
1858 /*
1859 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1860 * Just set these flags (and none of the '*flags' entered with).
1861 */
1862 if (PacketGetAirPcapHandle(adapter)) {
1863 /*
1864 * Must be "up" and "running" if the above if succeeded.
1865 */
1866 *flags = PCAP_IF_UP | PCAP_IF_RUNNING;
1867
1868 /*
1869 * An airpcap device is a wireless device (duh!)
1870 */
1871 *flags |= PCAP_IF_WIRELESS;
1872
1873 /*
1874 * A "network assosiation state" makes no sense for airpcap.
1875 */
1876 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1877 PacketCloseAdapter(adapter);
1878 return (0);
1879 }
1880 #endif
1881
1882 /*
1883 * Get the hardware status, and derive "up" and "running" from
1884 * that.
1885 */
1886 len = sizeof (hardware_status);
1887 status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
1888 &hardware_status, &len, errbuf);
1889 if (status == 0) {
1890 switch (hardware_status) {
1891
1892 case NdisHardwareStatusReady:
1893 /*
1894 * "Available and capable of sending and receiving
1895 * data over the wire", so up and running.
1896 */
1897 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1898 break;
1899
1900 case NdisHardwareStatusInitializing:
1901 case NdisHardwareStatusReset:
1902 /*
1903 * "Initializing" or "Resetting", so up, but
1904 * not running.
1905 */
1906 *flags |= PCAP_IF_UP;
1907 break;
1908
1909 case NdisHardwareStatusClosing:
1910 case NdisHardwareStatusNotReady:
1911 /*
1912 * "Closing" or "Not ready", so neither up nor
1913 * running.
1914 */
1915 break;
1916
1917 default:
1918 /*
1919 * Unknown.
1920 */
1921 break;
1922 }
1923 } else {
1924 /*
1925 * Can't get the hardware status, so assume both up and
1926 * running.
1927 */
1928 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1929 }
1930
1931 /*
1932 * Get the network type.
1933 */
1934 #ifdef OID_GEN_PHYSICAL_MEDIUM
1935 /*
1936 * Try the OIDs we have for this, in order.
1937 */
1938 for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
1939 len = sizeof (phys_medium);
1940 status = oid_get_request(adapter, gen_physical_medium_oids[i],
1941 &phys_medium, &len, errbuf);
1942 if (status == 0) {
1943 /*
1944 * Success.
1945 */
1946 break;
1947 }
1948 /*
1949 * Failed. We can't determine whether it failed
1950 * because that particular OID isn't supported
1951 * or because some other problem occurred, so we
1952 * just drive on and try the next OID.
1953 */
1954 }
1955 if (status == 0) {
1956 /*
1957 * We got the physical medium.
1958 *
1959 * XXX - we might want to check for NdisPhysicalMediumWiMax
1960 * and NdisPhysicalMediumNative802_15_4 being
1961 * part of the enum, and check for those in the "wireless"
1962 * case.
1963 */
1964 DIAG_OFF_ENUM_SWITCH
1965 switch (phys_medium) {
1966
1967 case NdisPhysicalMediumWirelessLan:
1968 case NdisPhysicalMediumWirelessWan:
1969 case NdisPhysicalMediumNative802_11:
1970 case NdisPhysicalMediumBluetooth:
1971 case NdisPhysicalMediumUWB:
1972 case NdisPhysicalMediumIrda:
1973 /*
1974 * Wireless.
1975 */
1976 *flags |= PCAP_IF_WIRELESS;
1977 break;
1978
1979 default:
1980 /*
1981 * Not wireless or unknown
1982 */
1983 break;
1984 }
1985 DIAG_ON_ENUM_SWITCH
1986 }
1987 #endif
1988
1989 /*
1990 * Get the connection status.
1991 */
1992 #ifdef OID_GEN_LINK_STATE
1993 len = sizeof(link_state);
1994 status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
1995 &len, errbuf);
1996 if (status == 0) {
1997 /*
1998 * NOTE: this also gives us the receive and transmit
1999 * link state.
2000 */
2001 switch (link_state.MediaConnectState) {
2002
2003 case MediaConnectStateConnected:
2004 /*
2005 * It's connected.
2006 */
2007 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2008 break;
2009
2010 case MediaConnectStateDisconnected:
2011 /*
2012 * It's disconnected.
2013 */
2014 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2015 break;
2016
2017 case MediaConnectStateUnknown:
2018 default:
2019 /*
2020 * It's unknown whether it's connected or not.
2021 */
2022 break;
2023 }
2024 }
2025 #else
2026 /*
2027 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
2028 */
2029 status = -1;
2030 #endif
2031 if (status == -1) {
2032 /*
2033 * OK, OID_GEN_LINK_STATE didn't work, try
2034 * OID_GEN_MEDIA_CONNECT_STATUS.
2035 */
2036 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
2037 &connect_status, &len, errbuf);
2038 if (status == 0) {
2039 switch (connect_status) {
2040
2041 case NdisMediaStateConnected:
2042 /*
2043 * It's connected.
2044 */
2045 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2046 break;
2047
2048 case NdisMediaStateDisconnected:
2049 /*
2050 * It's disconnected.
2051 */
2052 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2053 break;
2054 }
2055 }
2056 }
2057 PacketCloseAdapter(adapter);
2058 return (0);
2059 }
2060
2061 int
2062 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2063 {
2064 int ret = 0;
2065 const char *desc;
2066 char *AdaptersName;
2067 ULONG NameLength;
2068 char *name;
2069
2070 /*
2071 * Find out how big a buffer we need.
2072 *
2073 * This call should always return FALSE; if the error is
2074 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
2075 * the size of the buffer we need, otherwise there's a
2076 * problem, and NameLength should be set to 0.
2077 *
2078 * It shouldn't require NameLength to be set, but,
2079 * at least as of WinPcap 4.1.3, it checks whether
2080 * NameLength is big enough before it checks for a
2081 * NULL buffer argument, so, while it'll still do
2082 * the right thing if NameLength is uninitialized and
2083 * whatever junk happens to be there is big enough
2084 * (because the pointer argument will be null), it's
2085 * still reading an uninitialized variable.
2086 */
2087 NameLength = 0;
2088 if (!PacketGetAdapterNames(NULL, &NameLength))
2089 {
2090 DWORD last_error = GetLastError();
2091
2092 if (last_error != ERROR_INSUFFICIENT_BUFFER)
2093 {
2094 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2095 last_error, "PacketGetAdapterNames");
2096 return (-1);
2097 }
2098 }
2099
2100 if (NameLength <= 0)
2101 return 0;
2102 AdaptersName = (char*) malloc(NameLength);
2103 if (AdaptersName == NULL)
2104 {
2105 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
2106 return (-1);
2107 }
2108
2109 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
2110 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2111 GetLastError(), "PacketGetAdapterNames");
2112 free(AdaptersName);
2113 return (-1);
2114 }
2115
2116 /*
2117 * "PacketGetAdapterNames()" returned a list of
2118 * null-terminated ASCII interface name strings,
2119 * terminated by a null string, followed by a list
2120 * of null-terminated ASCII interface description
2121 * strings, terminated by a null string.
2122 * This means there are two ASCII nulls at the end
2123 * of the first list.
2124 *
2125 * Find the end of the first list; that's the
2126 * beginning of the second list.
2127 */
2128 desc = &AdaptersName[0];
2129 while (*desc != '\0' || *(desc + 1) != '\0')
2130 desc++;
2131
2132 /*
2133 * Found it - "desc" points to the first of the two
2134 * nulls at the end of the list of names, so the
2135 * first byte of the list of descriptions is two bytes
2136 * after it.
2137 */
2138 desc += 2;
2139
2140 /*
2141 * Loop over the elements in the first list.
2142 */
2143 name = &AdaptersName[0];
2144 while (*name != '\0') {
2145 bpf_u_int32 flags = 0;
2146
2147 #ifdef HAVE_AIRPCAP_API
2148 /*
2149 * Is this an AirPcap device?
2150 * If so, ignore it; it'll get added later, by the
2151 * AirPcap code.
2152 */
2153 if (device_is_airpcap(name, errbuf) == 1) {
2154 name += strlen(name) + 1;
2155 desc += strlen(desc) + 1;
2156 continue;
2157 }
2158 #endif
2159
2160 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
2161 /*
2162 * Is this a loopback interface?
2163 */
2164 if (PacketIsLoopbackAdapter(name)) {
2165 /* Yes */
2166 flags |= PCAP_IF_LOOPBACK;
2167 }
2168 #endif
2169 /*
2170 * Get additional flags.
2171 */
2172 if (get_if_flags(name, &flags, errbuf) == -1) {
2173 /*
2174 * Failure.
2175 */
2176 ret = -1;
2177 break;
2178 }
2179
2180 /*
2181 * Add an entry for this interface.
2182 */
2183 if (pcap_add_if_npf(devlistp, name, flags, desc,
2184 errbuf) == -1) {
2185 /*
2186 * Failure.
2187 */
2188 ret = -1;
2189 break;
2190 }
2191 name += strlen(name) + 1;
2192 desc += strlen(desc) + 1;
2193 }
2194
2195 free(AdaptersName);
2196 return (ret);
2197 }
2198
2199 /*
2200 * Return the name of a network interface attached to the system, or NULL
2201 * if none can be found. The interface must be configured up; the
2202 * lowest unit number is preferred; loopback is ignored.
2203 *
2204 * In the best of all possible worlds, this would be the same as on
2205 * UN*X, but there may be software that expects this to return a
2206 * full list of devices after the first device.
2207 */
2208 #define ADAPTERSNAME_LEN 8192
2209 char *
2210 pcap_lookupdev(char *errbuf)
2211 {
2212 DWORD dwVersion;
2213 DWORD dwWindowsMajorVersion;
2214
2215 /*
2216 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
2217 * it may return UTF-16 strings, for backwards-compatibility
2218 * reasons, and we're also disabling the hack to make that work,
2219 * for not-going-past-the-end-of-a-string reasons, and 2) we
2220 * want its behavior to be consistent.
2221 *
2222 * In addition, it's not thread-safe, so we've marked it as
2223 * deprecated.
2224 */
2225 if (pcap_new_api) {
2226 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2227 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
2228 return (NULL);
2229 }
2230
2231 /* disable MSVC's GetVersion() deprecated warning here */
2232 DIAG_OFF_DEPRECATION
2233 dwVersion = GetVersion(); /* get the OS version */
2234 DIAG_ON_DEPRECATION
2235 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
2236
2237 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
2238 /*
2239 * Windows 95, 98, ME.
2240 */
2241 ULONG NameLength = ADAPTERSNAME_LEN;
2242 static char AdaptersName[ADAPTERSNAME_LEN];
2243
2244 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
2245 return (AdaptersName);
2246 else
2247 return NULL;
2248 } else {
2249 /*
2250 * Windows NT (NT 4.0 and later).
2251 * Convert the names to Unicode for backward compatibility.
2252 */
2253 ULONG NameLength = ADAPTERSNAME_LEN;
2254 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
2255 size_t BufferSpaceLeft;
2256 char *tAstr;
2257 WCHAR *Unameptr;
2258 char *Adescptr;
2259 size_t namelen, i;
2260 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
2261 int NAdapts = 0;
2262
2263 if(TAdaptersName == NULL)
2264 {
2265 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
2266 return NULL;
2267 }
2268
2269 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
2270 {
2271 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
2272 GetLastError(), "PacketGetAdapterNames");
2273 free(TAdaptersName);
2274 return NULL;
2275 }
2276
2277
2278 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
2279 tAstr = (char*)TAdaptersName;
2280 Unameptr = AdaptersName;
2281
2282 /*
2283 * Convert the device names to Unicode into AdapterName.
2284 */
2285 do {
2286 /*
2287 * Length of the name, including the terminating
2288 * NUL.
2289 */
2290 namelen = strlen(tAstr) + 1;
2291
2292 /*
2293 * Do we have room for the name in the Unicode
2294 * buffer?
2295 */
2296 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
2297 /*
2298 * No.
2299 */
2300 goto quit;
2301 }
2302 BufferSpaceLeft -= namelen * sizeof(WCHAR);
2303
2304 /*
2305 * Copy the name, converting ASCII to Unicode.
2306 * namelen includes the NUL, so we copy it as
2307 * well.
2308 */
2309 for (i = 0; i < namelen; i++)
2310 *Unameptr++ = *tAstr++;
2311
2312 /*
2313 * Count this adapter.
2314 */
2315 NAdapts++;
2316 } while (namelen != 1);
2317
2318 /*
2319 * Copy the descriptions, but don't convert them from
2320 * ASCII to Unicode.
2321 */
2322 Adescptr = (char *)Unameptr;
2323 while(NAdapts--)
2324 {
2325 size_t desclen;
2326
2327 desclen = strlen(tAstr) + 1;
2328
2329 /*
2330 * Do we have room for the name in the Unicode
2331 * buffer?
2332 */
2333 if (BufferSpaceLeft < desclen) {
2334 /*
2335 * No.
2336 */
2337 goto quit;
2338 }
2339
2340 /*
2341 * Just copy the ASCII string.
2342 * namelen includes the NUL, so we copy it as
2343 * well.
2344 */
2345 memcpy(Adescptr, tAstr, desclen);
2346 Adescptr += desclen;
2347 tAstr += desclen;
2348 BufferSpaceLeft -= desclen;
2349 }
2350
2351 quit:
2352 free(TAdaptersName);
2353 return (char *)(AdaptersName);
2354 }
2355 }
2356
2357 /*
2358 * We can't use the same code that we use on UN*X, as that's doing
2359 * UN*X-specific calls.
2360 *
2361 * We don't just fetch the entire list of devices, search for the
2362 * particular device, and use its first IPv4 address, as that's too
2363 * much work to get just one device's netmask.
2364 */
2365 int
2366 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
2367 char *errbuf)
2368 {
2369 /*
2370 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
2371 * in order to skip non IPv4 (i.e. IPv6 addresses)
2372 */
2373 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
2374 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
2375 struct sockaddr_in *t_addr;
2376 LONG i;
2377
2378 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
2379 *netp = *maskp = 0;
2380 return (0);
2381 }
2382
2383 for(i = 0; i < if_addr_size; i++)
2384 {
2385 if(if_addrs[i].IPAddress.ss_family == AF_INET)
2386 {
2387 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
2388 *netp = t_addr->sin_addr.S_un.S_addr;
2389 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
2390 *maskp = t_addr->sin_addr.S_un.S_addr;
2391
2392 *netp &= *maskp;
2393 return (0);
2394 }
2395
2396 }
2397
2398 *netp = *maskp = 0;
2399 return (0);
2400 }
2401
2402 static const char *pcap_lib_version_string;
2403
2404 #ifdef HAVE_VERSION_H
2405 /*
2406 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2407 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2408 * version.
2409 *
2410 * XXX - it'd be nice if we could somehow generate the WinPcap/Npcap version
2411 * number when building as part of WinPcap/Npcap. (It'd be nice to do so
2412 * for the packet.dll version number as well.)
2413 */
2414 #include "../../version.h"
2415
2416 static const char pcap_version_string[] =
2417 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2418
2419 const char *
2420 pcap_lib_version(void)
2421 {
2422 if (pcap_lib_version_string == NULL) {
2423 /*
2424 * Generate the version string.
2425 */
2426 const char *packet_version_string = PacketGetVersion();
2427
2428 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2429 /*
2430 * WinPcap/Npcap version string and packet.dll version
2431 * string are the same; just report the WinPcap/Npcap
2432 * version.
2433 */
2434 pcap_lib_version_string = pcap_version_string;
2435 } else {
2436 /*
2437 * WinPcap/Npcap version string and packet.dll version
2438 * string are different; that shouldn't be the
2439 * case (the two libraries should come from the
2440 * same version of WinPcap/Npcap), so we report both
2441 * versions.
2442 */
2443 char *full_pcap_version_string;
2444
2445 if (pcap_asprintf(&full_pcap_version_string,
2446 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING,
2447 packet_version_string) != -1) {
2448 /* Success */
2449 pcap_lib_version_string = full_pcap_version_string;
2450 }
2451 }
2452 }
2453 return (pcap_lib_version_string);
2454 }
2455
2456 #else /* HAVE_VERSION_H */
2457
2458 /*
2459 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2460 * tree.
2461 */
2462 const char *
2463 pcap_lib_version(void)
2464 {
2465 if (pcap_lib_version_string == NULL) {
2466 /*
2467 * Generate the version string. Report the packet.dll
2468 * version.
2469 */
2470 char *full_pcap_version_string;
2471
2472 if (pcap_asprintf(&full_pcap_version_string,
2473 PCAP_VERSION_STRING " (packet.dll version %s)",
2474 PacketGetVersion()) != -1) {
2475 /* Success */
2476 pcap_lib_version_string = full_pcap_version_string;
2477 }
2478 }
2479 return (pcap_lib_version_string);
2480 }
2481 #endif /* HAVE_VERSION_H */