]> The Tcpdump Group git mirrors - libpcap/blob - pcap-npf.c
Just define NDIS_STATUS_NOT_SUPPORTED directly.
[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 /* Old-school MinGW have these headers in a different place.
45 */
46 #if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
47 #include <ddk/ntddndis.h>
48 #include <ddk/ndis.h>
49 #else
50 #include <ntddndis.h> /* MSVC/TDM-MinGW/MinGW64 */
51 #endif
52
53 #ifdef HAVE_DAG_API
54 #include <dagnew.h>
55 #include <dagapi.h>
56 #endif /* HAVE_DAG_API */
57
58 static int pcap_setfilter_win32_npf(pcap_t *, struct bpf_program *);
59 static int pcap_setfilter_win32_dag(pcap_t *, struct bpf_program *);
60 static int pcap_getnonblock_win32(pcap_t *);
61 static int pcap_setnonblock_win32(pcap_t *, int);
62
63 /*dimension of the buffer in the pcap_t structure*/
64 #define WIN32_DEFAULT_USER_BUFFER_SIZE 256000
65
66 /*dimension of the buffer in the kernel driver NPF */
67 #define WIN32_DEFAULT_KERNEL_BUFFER_SIZE 1000000
68
69 /* Equivalent to ntohs(), but a lot faster under Windows */
70 #define SWAPS(_X) ((_X & 0xff) << 8) | (_X >> 8)
71
72 /*
73 * Private data for capturing on WinPcap devices.
74 */
75 struct pcap_win {
76 ADAPTER *adapter; /* the packet32 ADAPTER for the device */
77 int nonblock;
78 int rfmon_selfstart; /* a flag tells whether the monitor mode is set by itself */
79 int filtering_in_kernel; /* using kernel filter */
80
81 #ifdef HAVE_DAG_API
82 int dag_fcs_bits; /* Number of checksum bits from link layer */
83 #endif
84
85 #ifdef ENABLE_REMOTE
86 int samp_npkt; /* parameter needed for sampling, with '1 out of N' method has been requested */
87 struct timeval samp_time; /* parameter needed for sampling, with '1 every N ms' method has been requested */
88 #endif
89 };
90
91 /*
92 * Define stub versions of the monitor-mode support routines if this
93 * isn't Npcap. HAVE_NPCAP_PACKET_API is defined by Npcap but not
94 * WinPcap.
95 */
96 #ifndef HAVE_NPCAP_PACKET_API
97 static int
98 PacketIsMonitorModeSupported(PCHAR AdapterName _U_)
99 {
100 /*
101 * We don't support monitor mode.
102 */
103 return (0);
104 }
105
106 static int
107 PacketSetMonitorMode(PCHAR AdapterName _U_, int mode _U_)
108 {
109 /*
110 * This should never be called, as PacketIsMonitorModeSupported()
111 * will return 0, meaning "we don't support monitor mode, so
112 * don't try to turn it on or off".
113 */
114 return (0);
115 }
116
117 static int
118 PacketGetMonitorMode(PCHAR AdapterName _U_)
119 {
120 /*
121 * This should fail, so that pcap_activate_win32() returns
122 * PCAP_ERROR_RFMON_NOTSUP if our caller requested monitor
123 * mode.
124 */
125 return (-1);
126 }
127 #endif
128
129 /*
130 * Sigh. PacketRequest() will have made a DeviceIoControl()
131 * call to the NPF driver to perform the OID request, with a
132 * BIOCQUERYOID ioctl. It looks as if the returned status
133 * will be an NDIS_STATUS_ value, but those aren't defined
134 * in any userland header.
135 *
136 * So we define them here.
137 */
138 #define NDIS_STATUS_INVALID_OID 0xc0010017
139 #define NDIS_STATUS_NOT_SUPPORTED 0xc00000bb /* STATUS_NOT_SUPPORTED */
140 #define NDIS_STATUS_NOT_RECOGNIZED 0x00010001
141
142 static int
143 oid_get_request(ADAPTER *adapter, bpf_u_int32 oid, void *data, size_t *lenp,
144 char *errbuf)
145 {
146 PACKET_OID_DATA *oid_data_arg;
147
148 /*
149 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
150 * It should be big enough to hold "*lenp" bytes of data; it
151 * will actually be slightly larger, as PACKET_OID_DATA has a
152 * 1-byte data array at the end, standing in for the variable-length
153 * data that's actually there.
154 */
155 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
156 if (oid_data_arg == NULL) {
157 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
158 "Couldn't allocate argument buffer for PacketRequest");
159 return (PCAP_ERROR);
160 }
161
162 /*
163 * No need to copy the data - we're doing a fetch.
164 */
165 oid_data_arg->Oid = oid;
166 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
167 if (!PacketRequest(adapter, FALSE, oid_data_arg)) {
168 int status;
169 DWORD request_error;
170 char errmsgbuf[PCAP_ERRBUF_SIZE+1];
171
172 request_error = GetLastError();
173 if (request_error == NDIS_STATUS_INVALID_OID ||
174 request_error == NDIS_STATUS_NOT_SUPPORTED ||
175 request_error == NDIS_STATUS_NOT_RECOGNIZED)
176 status = PCAP_ERROR_OPERATION_NOTSUP;
177 else
178 status = PCAP_ERROR;
179 pcap_win32_err_to_str(request_error, errmsgbuf);
180 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
181 "Error calling PacketRequest: %s", errmsgbuf);
182 free(oid_data_arg);
183 return (status);
184 }
185
186 /*
187 * Get the length actually supplied.
188 */
189 *lenp = oid_data_arg->Length;
190
191 /*
192 * Copy back the data we fetched.
193 */
194 memcpy(data, oid_data_arg->Data, *lenp);
195 free(oid_data_arg);
196 return (0);
197 }
198
199 static int
200 pcap_stats_win32(pcap_t *p, struct pcap_stat *ps)
201 {
202 struct pcap_win *pw = p->priv;
203 struct bpf_stat bstats;
204 char errbuf[PCAP_ERRBUF_SIZE+1];
205
206 /*
207 * Try to get statistics.
208 *
209 * (Please note - "struct pcap_stat" is *not* the same as
210 * WinPcap's "struct bpf_stat". It might currently have the
211 * same layout, but let's not cheat.
212 *
213 * Note also that we don't fill in ps_capt, as we might have
214 * been called by code compiled against an earlier version of
215 * WinPcap that didn't have ps_capt, in which case filling it
216 * in would stomp on whatever comes after the structure passed
217 * to us.
218 */
219 if (!PacketGetStats(pw->adapter, &bstats)) {
220 pcap_win32_err_to_str(GetLastError(), errbuf);
221 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
222 "PacketGetStats error: %s", errbuf);
223 return (-1);
224 }
225 ps->ps_recv = bstats.bs_recv;
226 ps->ps_drop = bstats.bs_drop;
227
228 /*
229 * XXX - PacketGetStats() doesn't fill this in, so we just
230 * return 0.
231 */
232 #if 0
233 ps->ps_ifdrop = bstats.ps_ifdrop;
234 #else
235 ps->ps_ifdrop = 0;
236 #endif
237
238 return (0);
239 }
240
241 /*
242 * Win32-only routine for getting statistics.
243 *
244 * This way is definitely safer than passing the pcap_stat * from the userland.
245 * In fact, there could happen than the user allocates a variable which is not
246 * big enough for the new structure, and the library will write in a zone
247 * which is not allocated to this variable.
248 *
249 * In this way, we're pretty sure we are writing on memory allocated to this
250 * variable.
251 *
252 * XXX - but this is the wrong way to handle statistics. Instead, we should
253 * have an API that returns data in a form like the Options section of a
254 * pcapng Interface Statistics Block:
255 *
256 * http://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
257 *
258 * which would let us add new statistics straightforwardly and indicate which
259 * statistics we are and are *not* providing, rather than having to provide
260 * possibly-bogus values for statistics we can't provide.
261 */
262 struct pcap_stat *
263 pcap_stats_ex_win32(pcap_t *p, int *pcap_stat_size)
264 {
265 struct pcap_win *pw = p->priv;
266 struct bpf_stat bstats;
267 char errbuf[PCAP_ERRBUF_SIZE+1];
268
269 *pcap_stat_size = sizeof (p->stat);
270
271 /*
272 * Try to get statistics.
273 *
274 * (Please note - "struct pcap_stat" is *not* the same as
275 * WinPcap's "struct bpf_stat". It might currently have the
276 * same layout, but let's not cheat.)
277 */
278 if (!PacketGetStatsEx(pw->adapter, &bstats)) {
279 pcap_win32_err_to_str(GetLastError(), errbuf);
280 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
281 "PacketGetStatsEx error: %s", errbuf);
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 #ifdef ENABLE_REMOTE
288 p->stat.ps_capt = bstats.bs_capt;
289 #endif
290 return (&p->stat);
291 }
292
293 /* Set the dimension of the kernel-level capture buffer */
294 static int
295 pcap_setbuff_win32(pcap_t *p, int dim)
296 {
297 struct pcap_win *pw = p->priv;
298
299 if(PacketSetBuff(pw->adapter,dim)==FALSE)
300 {
301 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
302 return (-1);
303 }
304 return (0);
305 }
306
307 /* Set the driver working mode */
308 static int
309 pcap_setmode_win32(pcap_t *p, int mode)
310 {
311 struct pcap_win *pw = p->priv;
312
313 if(PacketSetMode(pw->adapter,mode)==FALSE)
314 {
315 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: working mode not recognized");
316 return (-1);
317 }
318
319 return (0);
320 }
321
322 /*set the minimum amount of data that will release a read call*/
323 static int
324 pcap_setmintocopy_win32(pcap_t *p, int size)
325 {
326 struct pcap_win *pw = p->priv;
327
328 if(PacketSetMinToCopy(pw->adapter, size)==FALSE)
329 {
330 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: unable to set the requested mintocopy size");
331 return (-1);
332 }
333 return (0);
334 }
335
336 static HANDLE
337 pcap_getevent_win32(pcap_t *p)
338 {
339 struct pcap_win *pw = p->priv;
340
341 return (PacketGetReadEvent(pw->adapter));
342 }
343
344 static int
345 pcap_oid_get_request_win32(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
346 {
347 struct pcap_win *pw = p->priv;
348
349 return (oid_get_request(pw->adapter, oid, data, lenp, p->errbuf));
350 }
351
352 static int
353 pcap_oid_set_request_win32(pcap_t *p, bpf_u_int32 oid, const void *data,
354 size_t *lenp)
355 {
356 struct pcap_win *pw = p->priv;
357 PACKET_OID_DATA *oid_data_arg;
358 char errbuf[PCAP_ERRBUF_SIZE+1];
359
360 /*
361 * Allocate a PACKET_OID_DATA structure to hand to PacketRequest().
362 * It should be big enough to hold "*lenp" bytes of data; it
363 * will actually be slightly larger, as PACKET_OID_DATA has a
364 * 1-byte data array at the end, standing in for the variable-length
365 * data that's actually there.
366 */
367 oid_data_arg = malloc(sizeof (PACKET_OID_DATA) + *lenp);
368 if (oid_data_arg == NULL) {
369 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
370 "Couldn't allocate argument buffer for PacketRequest");
371 return (PCAP_ERROR);
372 }
373
374 oid_data_arg->Oid = oid;
375 oid_data_arg->Length = (ULONG)(*lenp); /* XXX - check for ridiculously large value? */
376 memcpy(oid_data_arg->Data, data, *lenp);
377 if (!PacketRequest(pw->adapter, TRUE, oid_data_arg)) {
378 pcap_win32_err_to_str(GetLastError(), errbuf);
379 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
380 "Error calling PacketRequest: %s", errbuf);
381 free(oid_data_arg);
382 return (PCAP_ERROR);
383 }
384
385 /*
386 * Get the length actually copied.
387 */
388 *lenp = oid_data_arg->Length;
389
390 /*
391 * No need to copy the data - we're doing a set.
392 */
393 free(oid_data_arg);
394 return (0);
395 }
396
397 static u_int
398 pcap_sendqueue_transmit_win32(pcap_t *p, pcap_send_queue *queue, int sync)
399 {
400 struct pcap_win *pw = p->priv;
401 u_int res;
402 char errbuf[PCAP_ERRBUF_SIZE+1];
403
404 if (pw->adapter==NULL) {
405 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
406 "Cannot transmit a queue to an offline capture or to a TurboCap port");
407 return (0);
408 }
409
410 res = PacketSendPackets(pw->adapter,
411 queue->buffer,
412 queue->len,
413 (BOOLEAN)sync);
414
415 if(res != queue->len){
416 pcap_win32_err_to_str(GetLastError(), errbuf);
417 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
418 "Error opening adapter: %s", errbuf);
419 }
420
421 return (res);
422 }
423
424 static int
425 pcap_setuserbuffer_win32(pcap_t *p, int size)
426 {
427 unsigned char *new_buff;
428
429 if (size<=0) {
430 /* Bogus parameter */
431 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
432 "Error: invalid size %d",size);
433 return (-1);
434 }
435
436 /* Allocate the buffer */
437 new_buff=(unsigned char*)malloc(sizeof(char)*size);
438
439 if (!new_buff) {
440 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
441 "Error: not enough memory");
442 return (-1);
443 }
444
445 free(p->buffer);
446
447 p->buffer=new_buff;
448 p->bufsize=size;
449
450 return (0);
451 }
452
453 static int
454 pcap_live_dump_win32(pcap_t *p, char *filename, int maxsize, int maxpacks)
455 {
456 struct pcap_win *pw = p->priv;
457 BOOLEAN res;
458
459 /* Set the packet driver in dump mode */
460 res = PacketSetMode(pw->adapter, PACKET_MODE_DUMP);
461 if(res == FALSE){
462 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
463 "Error setting dump mode");
464 return (-1);
465 }
466
467 /* Set the name of the dump file */
468 res = PacketSetDumpName(pw->adapter, filename, (int)strlen(filename));
469 if(res == FALSE){
470 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
471 "Error setting kernel dump file name");
472 return (-1);
473 }
474
475 /* Set the limits of the dump file */
476 res = PacketSetDumpLimits(pw->adapter, maxsize, maxpacks);
477 if(res == FALSE) {
478 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
479 "Error setting dump limit");
480 return (-1);
481 }
482
483 return (0);
484 }
485
486 static int
487 pcap_live_dump_ended_win32(pcap_t *p, int sync)
488 {
489 struct pcap_win *pw = p->priv;
490
491 return (PacketIsDumpEnded(pw->adapter, (BOOLEAN)sync));
492 }
493
494 static PAirpcapHandle
495 pcap_get_airpcap_handle_win32(pcap_t *p)
496 {
497 #ifdef HAVE_AIRPCAP_API
498 struct pcap_win *pw = p->priv;
499
500 return (PacketGetAirPcapHandle(pw->adapter));
501 #else
502 return (NULL);
503 #endif /* HAVE_AIRPCAP_API */
504 }
505
506 static int
507 pcap_read_win32_npf(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
508 {
509 PACKET Packet;
510 int cc;
511 int n = 0;
512 register u_char *bp, *ep;
513 u_char *datap;
514 struct pcap_win *pw = p->priv;
515
516 cc = p->cc;
517 if (p->cc == 0) {
518 /*
519 * Has "pcap_breakloop()" been called?
520 */
521 if (p->break_loop) {
522 /*
523 * Yes - clear the flag that indicates that it
524 * has, and return PCAP_ERROR_BREAK to indicate
525 * that we were told to break out of the loop.
526 */
527 p->break_loop = 0;
528 return (PCAP_ERROR_BREAK);
529 }
530
531 /*
532 * Capture the packets.
533 *
534 * The PACKET structure had a bunch of extra stuff for
535 * Windows 9x/Me, but the only interesting data in it
536 * in the versions of Windows that we support is just
537 * a copy of p->buffer, a copy of p->buflen, and the
538 * actual number of bytes read returned from
539 * PacketReceivePacket(), none of which has to be
540 * retained from call to call, so we just keep one on
541 * the stack.
542 */
543 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
544 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
545 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
546 return (PCAP_ERROR);
547 }
548
549 cc = Packet.ulBytesReceived;
550
551 bp = p->buffer;
552 }
553 else
554 bp = p->bp;
555
556 /*
557 * Loop through each packet.
558 */
559 #define bhp ((struct bpf_hdr *)bp)
560 ep = bp + cc;
561 for (;;) {
562 register int caplen, hdrlen;
563
564 /*
565 * Has "pcap_breakloop()" been called?
566 * If so, return immediately - if we haven't read any
567 * packets, clear the flag and return PCAP_ERROR_BREAK
568 * to indicate that we were told to break out of the loop,
569 * otherwise leave the flag set, so that the *next* call
570 * will break out of the loop without having read any
571 * packets, and return the number of packets we've
572 * processed so far.
573 */
574 if (p->break_loop) {
575 if (n == 0) {
576 p->break_loop = 0;
577 return (PCAP_ERROR_BREAK);
578 } else {
579 p->bp = bp;
580 p->cc = (int) (ep - bp);
581 return (n);
582 }
583 }
584 if (bp >= ep)
585 break;
586
587 caplen = bhp->bh_caplen;
588 hdrlen = bhp->bh_hdrlen;
589 datap = bp + hdrlen;
590
591 /*
592 * Short-circuit evaluation: if using BPF filter
593 * in kernel, no need to do it now - we already know
594 * the packet passed the filter.
595 *
596 * XXX - bpf_filter() should always return TRUE if
597 * handed a null pointer for the program, but it might
598 * just try to "run" the filter, so we check here.
599 */
600 if (pw->filtering_in_kernel ||
601 p->fcode.bf_insns == NULL ||
602 bpf_filter(p->fcode.bf_insns, datap, bhp->bh_datalen, caplen)) {
603 #ifdef ENABLE_REMOTE
604 switch (p->rmt_samp.method) {
605
606 case PCAP_SAMP_1_EVERY_N:
607 pw->samp_npkt = (pw->samp_npkt + 1) % p->rmt_samp.value;
608
609 /* Discard all packets that are not '1 out of N' */
610 if (pw->samp_npkt != 0) {
611 bp += Packet_WORDALIGN(caplen + hdrlen);
612 continue;
613 }
614 break;
615
616 case PCAP_SAMP_FIRST_AFTER_N_MS:
617 {
618 struct pcap_pkthdr *pkt_header = (struct pcap_pkthdr*) bp;
619
620 /*
621 * Check if the timestamp of the arrived
622 * packet is smaller than our target time.
623 */
624 if (pkt_header->ts.tv_sec < pw->samp_time.tv_sec ||
625 (pkt_header->ts.tv_sec == pw->samp_time.tv_sec && pkt_header->ts.tv_usec < pw->samp_time.tv_usec)) {
626 bp += Packet_WORDALIGN(caplen + hdrlen);
627 continue;
628 }
629
630 /*
631 * The arrived packet is suitable for being
632 * delivered to our caller, so let's update
633 * the target time.
634 */
635 pw->samp_time.tv_usec = pkt_header->ts.tv_usec + p->rmt_samp.value * 1000;
636 if (pw->samp_time.tv_usec > 1000000) {
637 pw->samp_time.tv_sec = pkt_header->ts.tv_sec + pw->samp_time.tv_usec / 1000000;
638 pw->samp_time.tv_usec = pw->samp_time.tv_usec % 1000000;
639 }
640 }
641 }
642 #endif /* ENABLE_REMOTE */
643
644 /*
645 * XXX A bpf_hdr matches a pcap_pkthdr.
646 */
647 (*callback)(user, (struct pcap_pkthdr*)bp, datap);
648 bp += Packet_WORDALIGN(caplen + hdrlen);
649 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt)) {
650 p->bp = bp;
651 p->cc = (int) (ep - bp);
652 return (n);
653 }
654 } else {
655 /*
656 * Skip this packet.
657 */
658 bp += Packet_WORDALIGN(caplen + hdrlen);
659 }
660 }
661 #undef bhp
662 p->cc = 0;
663 return (n);
664 }
665
666 #ifdef HAVE_DAG_API
667 static int
668 pcap_read_win32_dag(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
669 {
670 struct pcap_win *pw = p->priv;
671 PACKET Packet;
672 u_char *dp = NULL;
673 int packet_len = 0, caplen = 0;
674 struct pcap_pkthdr pcap_header;
675 u_char *endofbuf;
676 int n = 0;
677 dag_record_t *header;
678 unsigned erf_record_len;
679 ULONGLONG ts;
680 int cc;
681 unsigned swt;
682 unsigned dfp = pw->adapter->DagFastProcess;
683
684 cc = p->cc;
685 if (cc == 0) /* Get new packets only if we have processed all the ones of the previous read */
686 {
687 /*
688 * Get new packets from the network.
689 *
690 * The PACKET structure had a bunch of extra stuff for
691 * Windows 9x/Me, but the only interesting data in it
692 * in the versions of Windows that we support is just
693 * a copy of p->buffer, a copy of p->buflen, and the
694 * actual number of bytes read returned from
695 * PacketReceivePacket(), none of which has to be
696 * retained from call to call, so we just keep one on
697 * the stack.
698 */
699 PacketInitPacket(&Packet, (BYTE *)p->buffer, p->bufsize);
700 if (!PacketReceivePacket(pw->adapter, &Packet, TRUE)) {
701 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "read error: PacketReceivePacket failed");
702 return (-1);
703 }
704
705 cc = Packet.ulBytesReceived;
706 if(cc == 0)
707 /* The timeout has expired but we no packets arrived */
708 return (0);
709 header = (dag_record_t*)pw->adapter->DagBuffer;
710 }
711 else
712 header = (dag_record_t*)p->bp;
713
714 endofbuf = (char*)header + cc;
715
716 /*
717 * Cycle through the packets
718 */
719 do
720 {
721 erf_record_len = SWAPS(header->rlen);
722 if((char*)header + erf_record_len > endofbuf)
723 break;
724
725 /* Increase the number of captured packets */
726 p->stat.ps_recv++;
727
728 /* Find the beginning of the packet */
729 dp = ((u_char *)header) + dag_record_size;
730
731 /* Determine actual packet len */
732 switch(header->type)
733 {
734 case TYPE_ATM:
735 packet_len = ATM_SNAPLEN;
736 caplen = ATM_SNAPLEN;
737 dp += 4;
738
739 break;
740
741 case TYPE_ETH:
742 swt = SWAPS(header->wlen);
743 packet_len = swt - (pw->dag_fcs_bits);
744 caplen = erf_record_len - dag_record_size - 2;
745 if (caplen > packet_len)
746 {
747 caplen = packet_len;
748 }
749 dp += 2;
750
751 break;
752
753 case TYPE_HDLC_POS:
754 swt = SWAPS(header->wlen);
755 packet_len = swt - (pw->dag_fcs_bits);
756 caplen = erf_record_len - dag_record_size;
757 if (caplen > packet_len)
758 {
759 caplen = packet_len;
760 }
761
762 break;
763 }
764
765 if(caplen > p->snapshot)
766 caplen = p->snapshot;
767
768 /*
769 * Has "pcap_breakloop()" been called?
770 * If so, return immediately - if we haven't read any
771 * packets, clear the flag and return -2 to indicate
772 * that we were told to break out of the loop, otherwise
773 * leave the flag set, so that the *next* call will break
774 * out of the loop without having read any packets, and
775 * return the number of packets we've processed so far.
776 */
777 if (p->break_loop)
778 {
779 if (n == 0)
780 {
781 p->break_loop = 0;
782 return (-2);
783 }
784 else
785 {
786 p->bp = (char*)header;
787 p->cc = endofbuf - (char*)header;
788 return (n);
789 }
790 }
791
792 if(!dfp)
793 {
794 /* convert between timestamp formats */
795 ts = header->ts;
796 pcap_header.ts.tv_sec = (int)(ts >> 32);
797 ts = (ts & 0xffffffffi64) * 1000000;
798 ts += 0x80000000; /* rounding */
799 pcap_header.ts.tv_usec = (int)(ts >> 32);
800 if (pcap_header.ts.tv_usec >= 1000000) {
801 pcap_header.ts.tv_usec -= 1000000;
802 pcap_header.ts.tv_sec++;
803 }
804 }
805
806 /* No underlaying filtering system. We need to filter on our own */
807 if (p->fcode.bf_insns)
808 {
809 if (bpf_filter(p->fcode.bf_insns, dp, packet_len, caplen) == 0)
810 {
811 /* Move to next packet */
812 header = (dag_record_t*)((char*)header + erf_record_len);
813 continue;
814 }
815 }
816
817 /* Fill the header for the user suppplied callback function */
818 pcap_header.caplen = caplen;
819 pcap_header.len = packet_len;
820
821 /* Call the callback function */
822 (*callback)(user, &pcap_header, dp);
823
824 /* Move to next packet */
825 header = (dag_record_t*)((char*)header + erf_record_len);
826
827 /* Stop if the number of packets requested by user has been reached*/
828 if (++n >= cnt && !PACKET_COUNT_IS_UNLIMITED(cnt))
829 {
830 p->bp = (char*)header;
831 p->cc = endofbuf - (char*)header;
832 return (n);
833 }
834 }
835 while((u_char*)header < endofbuf);
836
837 return (1);
838 }
839 #endif /* HAVE_DAG_API */
840
841 /* Send a packet to the network */
842 static int
843 pcap_inject_win32(pcap_t *p, const void *buf, size_t size)
844 {
845 struct pcap_win *pw = p->priv;
846 PACKET pkt;
847
848 PacketInitPacket(&pkt, (PVOID)buf, size);
849 if(PacketSendPacket(pw->adapter,&pkt,TRUE) == FALSE) {
850 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "send error: PacketSendPacket failed");
851 return (-1);
852 }
853
854 /*
855 * We assume it all got sent if "PacketSendPacket()" succeeded.
856 * "pcap_inject()" is expected to return the number of bytes
857 * sent.
858 */
859 return ((int)size);
860 }
861
862 static void
863 pcap_cleanup_win32(pcap_t *p)
864 {
865 struct pcap_win *pw = p->priv;
866
867 if (pw->adapter != NULL) {
868 PacketCloseAdapter(pw->adapter);
869 pw->adapter = NULL;
870 }
871 if (pw->rfmon_selfstart)
872 {
873 PacketSetMonitorMode(p->opt.device, 0);
874 }
875 pcap_cleanup_live_common(p);
876 }
877
878 static int
879 pcap_activate_win32(pcap_t *p)
880 {
881 struct pcap_win *pw = p->priv;
882 NetType type;
883 int res;
884 char errbuf[PCAP_ERRBUF_SIZE+1];
885
886 if (p->opt.rfmon) {
887 /*
888 * Monitor mode is supported on Windows Vista and later.
889 */
890 if (PacketGetMonitorMode(p->opt.device) == 1)
891 {
892 pw->rfmon_selfstart = 0;
893 }
894 else
895 {
896 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
897 {
898 pw->rfmon_selfstart = 0;
899 // Monitor mode is not supported.
900 if (res == 0)
901 {
902 return PCAP_ERROR_RFMON_NOTSUP;
903 }
904 else
905 {
906 return PCAP_ERROR;
907 }
908 }
909 else
910 {
911 pw->rfmon_selfstart = 1;
912 }
913 }
914 }
915
916 /* Init WinSock */
917 pcap_wsockinit();
918
919 pw->adapter = PacketOpenAdapter(p->opt.device);
920
921 if (pw->adapter == NULL)
922 {
923 /* Adapter detected but we are not able to open it. Return failure. */
924 pcap_win32_err_to_str(GetLastError(), errbuf);
925 if (pw->rfmon_selfstart)
926 {
927 PacketSetMonitorMode(p->opt.device, 0);
928 }
929 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
930 "Error opening adapter: %s", errbuf);
931 return (PCAP_ERROR);
932 }
933
934 /*get network type*/
935 if(PacketGetNetType (pw->adapter,&type) == FALSE)
936 {
937 pcap_win32_err_to_str(GetLastError(), errbuf);
938 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
939 "Cannot determine the network type: %s", errbuf);
940 goto bad;
941 }
942
943 /*Set the linktype*/
944 switch (type.LinkType)
945 {
946 case NdisMediumWan:
947 p->linktype = DLT_EN10MB;
948 break;
949
950 case NdisMedium802_3:
951 p->linktype = DLT_EN10MB;
952 /*
953 * This is (presumably) a real Ethernet capture; give it a
954 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
955 * that an application can let you choose it, in case you're
956 * capturing DOCSIS traffic that a Cisco Cable Modem
957 * Termination System is putting out onto an Ethernet (it
958 * doesn't put an Ethernet header onto the wire, it puts raw
959 * DOCSIS frames out on the wire inside the low-level
960 * Ethernet framing).
961 */
962 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
963 /*
964 * If that fails, just leave the list empty.
965 */
966 if (p->dlt_list != NULL) {
967 p->dlt_list[0] = DLT_EN10MB;
968 p->dlt_list[1] = DLT_DOCSIS;
969 p->dlt_count = 2;
970 }
971 break;
972
973 case NdisMediumFddi:
974 p->linktype = DLT_FDDI;
975 break;
976
977 case NdisMedium802_5:
978 p->linktype = DLT_IEEE802;
979 break;
980
981 case NdisMediumArcnetRaw:
982 p->linktype = DLT_ARCNET;
983 break;
984
985 case NdisMediumArcnet878_2:
986 p->linktype = DLT_ARCNET;
987 break;
988
989 case NdisMediumAtm:
990 p->linktype = DLT_ATM_RFC1483;
991 break;
992
993 case NdisMediumCHDLC:
994 p->linktype = DLT_CHDLC;
995 break;
996
997 case NdisMediumPPPSerial:
998 p->linktype = DLT_PPP_SERIAL;
999 break;
1000
1001 case NdisMediumNull:
1002 p->linktype = DLT_NULL;
1003 break;
1004
1005 case NdisMediumBare80211:
1006 p->linktype = DLT_IEEE802_11;
1007 break;
1008
1009 case NdisMediumRadio80211:
1010 p->linktype = DLT_IEEE802_11_RADIO;
1011 break;
1012
1013 case NdisMediumPpi:
1014 p->linktype = DLT_PPI;
1015 break;
1016
1017 default:
1018 p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/
1019 break;
1020 }
1021
1022 /*
1023 * Turn a negative snapshot value (invalid), a snapshot value of
1024 * 0 (unspecified), or a value bigger than the normal maximum
1025 * value, into the maximum allowed value.
1026 *
1027 * If some application really *needs* a bigger snapshot
1028 * length, we should just increase MAXIMUM_SNAPLEN.
1029 */
1030 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1031 p->snapshot = MAXIMUM_SNAPLEN;
1032
1033 /* Set promiscuous mode */
1034 if (p->opt.promisc)
1035 {
1036
1037 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1038 {
1039 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
1040 goto bad;
1041 }
1042 }
1043 else
1044 {
1045 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_ALL_LOCAL) == FALSE)
1046 {
1047 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
1048 goto bad;
1049 }
1050 }
1051
1052 /* Set the buffer size */
1053 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1054
1055 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1056 {
1057 /*
1058 * Traditional Adapter
1059 */
1060 /*
1061 * If the buffer size wasn't explicitly set, default to
1062 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1063 */
1064 if (p->opt.buffer_size == 0)
1065 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1066
1067 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1068 {
1069 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1070 goto bad;
1071 }
1072
1073 p->buffer = malloc(p->bufsize);
1074 if (p->buffer == NULL)
1075 {
1076 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1077 errno, "malloc");
1078 goto bad;
1079 }
1080
1081 if (p->opt.immediate)
1082 {
1083 /* tell the driver to copy the buffer as soon as data arrives */
1084 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1085 {
1086 pcap_win32_err_to_str(GetLastError(), errbuf);
1087 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1088 "Error calling PacketSetMinToCopy: %s",
1089 errbuf);
1090 goto bad;
1091 }
1092 }
1093 else
1094 {
1095 /* tell the driver to copy the buffer only if it contains at least 16K */
1096 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1097 {
1098 pcap_win32_err_to_str(GetLastError(), errbuf);
1099 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1100 "Error calling PacketSetMinToCopy: %s",
1101 errbuf);
1102 goto bad;
1103 }
1104 }
1105 } else {
1106 /*
1107 * Dag Card
1108 */
1109 #ifdef HAVE_DAG_API
1110 /*
1111 * We have DAG support.
1112 */
1113 LONG status;
1114 HKEY dagkey;
1115 DWORD lptype;
1116 DWORD lpcbdata;
1117 int postype = 0;
1118 char keyname[512];
1119
1120 pcap_snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1121 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1122 strstr(_strlwr(p->opt.device), "dag"));
1123 do
1124 {
1125 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1126 if(status != ERROR_SUCCESS)
1127 break;
1128
1129 status = RegQueryValueEx(dagkey,
1130 "PosType",
1131 NULL,
1132 &lptype,
1133 (char*)&postype,
1134 &lpcbdata);
1135
1136 if(status != ERROR_SUCCESS)
1137 {
1138 postype = 0;
1139 }
1140
1141 RegCloseKey(dagkey);
1142 }
1143 while(FALSE);
1144
1145
1146 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1147
1148 /* Set the length of the FCS associated to any packet. This value
1149 * will be subtracted to the packet length */
1150 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1151 #else /* HAVE_DAG_API */
1152 /*
1153 * No DAG support.
1154 */
1155 goto bad;
1156 #endif /* HAVE_DAG_API */
1157 }
1158
1159 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1160
1161 /* disable loopback capture if requested */
1162 if (p->opt.nocapture_local)
1163 {
1164 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1165 {
1166 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1167 "Unable to disable the capture of loopback packets.");
1168 goto bad;
1169 }
1170 }
1171
1172 #ifdef HAVE_DAG_API
1173 if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1174 {
1175 /* install dag specific handlers for read and setfilter */
1176 p->read_op = pcap_read_win32_dag;
1177 p->setfilter_op = pcap_setfilter_win32_dag;
1178 }
1179 else
1180 {
1181 #endif /* HAVE_DAG_API */
1182 /* install traditional npf handlers for read and setfilter */
1183 p->read_op = pcap_read_win32_npf;
1184 p->setfilter_op = pcap_setfilter_win32_npf;
1185 #ifdef HAVE_DAG_API
1186 }
1187 #endif /* HAVE_DAG_API */
1188 p->setdirection_op = NULL; /* Not implemented. */
1189 /* XXX - can this be implemented on some versions of Windows? */
1190 p->inject_op = pcap_inject_win32;
1191 p->set_datalink_op = NULL; /* can't change data link type */
1192 p->getnonblock_op = pcap_getnonblock_win32;
1193 p->setnonblock_op = pcap_setnonblock_win32;
1194 p->stats_op = pcap_stats_win32;
1195 p->stats_ex_op = pcap_stats_ex_win32;
1196 p->setbuff_op = pcap_setbuff_win32;
1197 p->setmode_op = pcap_setmode_win32;
1198 p->setmintocopy_op = pcap_setmintocopy_win32;
1199 p->getevent_op = pcap_getevent_win32;
1200 p->oid_get_request_op = pcap_oid_get_request_win32;
1201 p->oid_set_request_op = pcap_oid_set_request_win32;
1202 p->sendqueue_transmit_op = pcap_sendqueue_transmit_win32;
1203 p->setuserbuffer_op = pcap_setuserbuffer_win32;
1204 p->live_dump_op = pcap_live_dump_win32;
1205 p->live_dump_ended_op = pcap_live_dump_ended_win32;
1206 p->get_airpcap_handle_op = pcap_get_airpcap_handle_win32;
1207 p->cleanup_op = pcap_cleanup_win32;
1208
1209 /*
1210 * XXX - this is only done because WinPcap supported
1211 * pcap_fileno() returning the hFile HANDLE from the
1212 * ADAPTER structure. We make no general guarantees
1213 * that the caller can do anything useful with it.
1214 *
1215 * (Not that we make any general guarantee of that
1216 * sort on UN*X, either, any more, given that not
1217 * all capture devices are regular OS network
1218 * interfaces.)
1219 */
1220 p->handle = pw->adapter->hFile;
1221
1222 return (0);
1223 bad:
1224 pcap_cleanup_win32(p);
1225 return (PCAP_ERROR);
1226 }
1227
1228 /*
1229 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1230 */
1231 static int
1232 pcap_can_set_rfmon_win32(pcap_t *p)
1233 {
1234 return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1235 }
1236
1237 pcap_t *
1238 pcap_create_interface(const char *device _U_, char *ebuf)
1239 {
1240 pcap_t *p;
1241
1242 p = pcap_create_common(ebuf, sizeof(struct pcap_win));
1243 if (p == NULL)
1244 return (NULL);
1245
1246 p->activate_op = pcap_activate_win32;
1247 p->can_set_rfmon_op = pcap_can_set_rfmon_win32;
1248 return (p);
1249 }
1250
1251 static int
1252 pcap_setfilter_win32_npf(pcap_t *p, struct bpf_program *fp)
1253 {
1254 struct pcap_win *pw = p->priv;
1255
1256 if(PacketSetBpf(pw->adapter,fp)==FALSE){
1257 /*
1258 * Kernel filter not installed.
1259 *
1260 * XXX - we don't know whether this failed because:
1261 *
1262 * the kernel rejected the filter program as invalid,
1263 * in which case we should fall back on userland
1264 * filtering;
1265 *
1266 * the kernel rejected the filter program as too big,
1267 * in which case we should again fall back on
1268 * userland filtering;
1269 *
1270 * there was some other problem, in which case we
1271 * should probably report an error.
1272 *
1273 * For NPF devices, the Win32 status will be
1274 * STATUS_INVALID_DEVICE_REQUEST for invalid
1275 * filters, but I don't know what it'd be for
1276 * other problems, and for some other devices
1277 * it might not be set at all.
1278 *
1279 * So we just fall back on userland filtering in
1280 * all cases.
1281 */
1282
1283 /*
1284 * install_bpf_program() validates the program.
1285 *
1286 * XXX - what if we already have a filter in the kernel?
1287 */
1288 if (install_bpf_program(p, fp) < 0)
1289 return (-1);
1290 pw->filtering_in_kernel = 0; /* filtering in userland */
1291 return (0);
1292 }
1293
1294 /*
1295 * It worked.
1296 */
1297 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1298
1299 /*
1300 * Discard any previously-received packets, as they might have
1301 * passed whatever filter was formerly in effect, but might
1302 * not pass this filter (BIOCSETF discards packets buffered
1303 * in the kernel, so you can lose packets in any case).
1304 */
1305 p->cc = 0;
1306 return (0);
1307 }
1308
1309 /*
1310 * We filter at user level, since the kernel driver does't process the packets
1311 */
1312 static int
1313 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1314
1315 if(!fp)
1316 {
1317 strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1318 return (-1);
1319 }
1320
1321 /* Install a user level filter */
1322 if (install_bpf_program(p, fp) < 0)
1323 return (-1);
1324
1325 return (0);
1326 }
1327
1328 static int
1329 pcap_getnonblock_win32(pcap_t *p)
1330 {
1331 struct pcap_win *pw = p->priv;
1332
1333 /*
1334 * XXX - if there were a PacketGetReadTimeout() call, we
1335 * would use it, and return 1 if the timeout is -1
1336 * and 0 otherwise.
1337 */
1338 return (pw->nonblock);
1339 }
1340
1341 static int
1342 pcap_setnonblock_win32(pcap_t *p, int nonblock)
1343 {
1344 struct pcap_win *pw = p->priv;
1345 int newtimeout;
1346 char win_errbuf[PCAP_ERRBUF_SIZE+1];
1347
1348 if (nonblock) {
1349 /*
1350 * Set the packet buffer timeout to -1 for non-blocking
1351 * mode.
1352 */
1353 newtimeout = -1;
1354 } else {
1355 /*
1356 * Restore the timeout set when the device was opened.
1357 * (Note that this may be -1, in which case we're not
1358 * really leaving non-blocking mode. However, although
1359 * the timeout argument to pcap_set_timeout() and
1360 * pcap_open_live() is an int, you're not supposed to
1361 * supply a negative value, so that "shouldn't happen".)
1362 */
1363 newtimeout = p->opt.timeout;
1364 }
1365 if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1366 pcap_win32_err_to_str(GetLastError(), win_errbuf);
1367 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1368 "PacketSetReadTimeout: %s", win_errbuf);
1369 return (-1);
1370 }
1371 pw->nonblock = (newtimeout == -1);
1372 return (0);
1373 }
1374
1375 static int
1376 pcap_add_if_win32(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
1377 const char *description, char *errbuf)
1378 {
1379 pcap_if_t *curdev;
1380 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1381 LONG if_addr_size;
1382 int res = 0;
1383
1384 if_addr_size = MAX_NETWORK_ADDRESSES;
1385
1386 /*
1387 * Add an entry for this interface, with no addresses.
1388 */
1389 curdev = add_dev(devlistp, name, flags, description, errbuf);
1390 if (curdev == NULL) {
1391 /*
1392 * Failure.
1393 */
1394 return (-1);
1395 }
1396
1397 /*
1398 * Get the list of addresses for the interface.
1399 */
1400 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1401 /*
1402 * Failure.
1403 *
1404 * We don't return an error, because this can happen with
1405 * NdisWan interfaces, and we want to supply them even
1406 * if we can't supply their addresses.
1407 *
1408 * We return an entry with an empty address list.
1409 */
1410 return (0);
1411 }
1412
1413 /*
1414 * Now add the addresses.
1415 */
1416 while (if_addr_size-- > 0) {
1417 /*
1418 * "curdev" is an entry for this interface; add an entry for
1419 * this address to its list of addresses.
1420 */
1421 res = add_addr_to_dev(curdev,
1422 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1423 sizeof (struct sockaddr_storage),
1424 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1425 sizeof (struct sockaddr_storage),
1426 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1427 sizeof (struct sockaddr_storage),
1428 NULL,
1429 0,
1430 errbuf);
1431 if (res == -1) {
1432 /*
1433 * Failure.
1434 */
1435 break;
1436 }
1437 }
1438
1439 return (res);
1440 }
1441
1442 int
1443 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
1444 {
1445 char *name_copy;
1446 ADAPTER *adapter;
1447 int status;
1448 size_t len;
1449 #ifdef OID_GEN_PHYSICAL_MEDIUM
1450 NDIS_PHYSICAL_MEDIUM phys_medium;
1451 bpf_u_int32 gen_physical_medium_oids[] = {
1452 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1453 OID_GEN_PHYSICAL_MEDIUM_EX,
1454 #endif
1455 OID_GEN_PHYSICAL_MEDIUM
1456 };
1457 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1458 size_t i;
1459 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1460 #ifdef OID_GEN_MEDIA_CONNECT_STATUS_EX
1461 NET_IF_MEDIA_CONNECT_STATE connect_state_ex;
1462 #endif
1463 int connect_state;
1464
1465 if (*flags & PCAP_IF_LOOPBACK) {
1466 /*
1467 * Loopback interface, so the connection status doesn't
1468 * apply. and it's not wireless (or wired, for that
1469 * matter...).
1470 */
1471 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1472 return (0);
1473 }
1474
1475 /*
1476 * We need to open the adapter to get this information.
1477 *
1478 * XXX - PacketOpenAdapter() takes a non-const pointer
1479 * as an argument, so we make a copy of the argument and
1480 * pass that to it.
1481 */
1482 name_copy = strdup(name);
1483 adapter = PacketOpenAdapter(name_copy);
1484 free(name_copy);
1485 if (adapter == NULL) {
1486 /*
1487 * Give up; if they try to open this device, it'll fail.
1488 */
1489 return (0);
1490 }
1491
1492 /*
1493 * Get the network type.
1494 */
1495 #ifdef OID_GEN_PHYSICAL_MEDIUM
1496 /*
1497 * Try the OIDs we have for this, in order.
1498 */
1499 for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
1500 len = sizeof (phys_medium);
1501 status = oid_get_request(adapter, gen_physical_medium_oids[i],
1502 &phys_medium, &len, errbuf);
1503 if (status == PCAP_ERROR) {
1504 /*
1505 * Failed with a hard error.
1506 */
1507 PacketCloseAdapter(adapter);
1508 return (-1);
1509 }
1510 if (status == 0) {
1511 /*
1512 * Success.
1513 */
1514 break;
1515 }
1516 /*
1517 * Failed with "I don't support that OID", so try the
1518 * next one, if we have a next one.
1519 */
1520 }
1521 if (status == 0) {
1522 /*
1523 * We got the physical medium.
1524 */
1525 switch (phys_medium) {
1526
1527 case NdisPhysicalMediumWirelessLan:
1528 case NdisPhysicalMediumWirelessWan:
1529 case NdisPhysicalMediumNative802_11:
1530 case NdisPhysicalMediumBluetooth:
1531 case NdisPhysicalMediumUWB:
1532 case NdisPhysicalMediumIrda:
1533 /*
1534 * Wireless.
1535 */
1536 *flags |= PCAP_IF_WIRELESS;
1537 break;
1538 }
1539 }
1540 #endif
1541
1542 /*
1543 * Get the connection status.
1544 */
1545 #ifdef OID_GEN_MEDIA_CONNECT_STATUS_EX
1546 len = sizeof(connect_state_ex);
1547 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS_EX,
1548 &connect_state_ex, &len, errbuf);
1549 if (status == PCAP_ERROR) {
1550 /*
1551 * Fatal error.
1552 */
1553 PacketCloseAdapter(adapter);
1554 return (-1);
1555 }
1556 if (status == 0) {
1557 switch (connect_state_ex) {
1558
1559 case MediaConnectStateConnected:
1560 /*
1561 * It's connected.
1562 */
1563 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
1564 break;
1565
1566 case MediaConnectStateDisconnected:
1567 /*
1568 * It's disconnected.
1569 */
1570 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
1571 break;
1572 }
1573 }
1574 #else
1575 /*
1576 * OID_GEN_MEDIA_CONNECT_STATUS_EX isn't supported because it's
1577 * not in our SDK.
1578 */
1579 status = PCAP_ERROR_OPERATION_NOTSUP;
1580 #endif
1581 if (status == PCAP_ERROR_OPERATION_NOTSUP) {
1582 /*
1583 * OK, OID_GEN_MEDIA_CONNECT_STATUS_EX isn't supported,
1584 * try OID_GEN_MEDIA_CONNECT_STATUS.
1585 */
1586 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
1587 &connect_state, &len, errbuf);
1588 if (status == PCAP_ERROR) {
1589 /*
1590 * Fatal error.
1591 */
1592 PacketCloseAdapter(adapter);
1593 return (-1);
1594 }
1595 if (status == 0) {
1596 switch (connect_state) {
1597
1598 case NdisMediaStateConnected:
1599 /*
1600 * It's connected.
1601 */
1602 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
1603 break;
1604
1605 case NdisMediaStateDisconnected:
1606 /*
1607 * It's disconnected.
1608 */
1609 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
1610 break;
1611 }
1612 }
1613 }
1614 PacketCloseAdapter(adapter);
1615 return (0);
1616 }
1617
1618 int
1619 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
1620 {
1621 int ret = 0;
1622 const char *desc;
1623 char *AdaptersName;
1624 ULONG NameLength;
1625 char *name;
1626 char our_errbuf[PCAP_ERRBUF_SIZE+1];
1627
1628 /*
1629 * Find out how big a buffer we need.
1630 *
1631 * This call should always return FALSE; if the error is
1632 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1633 * the size of the buffer we need, otherwise there's a
1634 * problem, and NameLength should be set to 0.
1635 *
1636 * It shouldn't require NameLength to be set, but,
1637 * at least as of WinPcap 4.1.3, it checks whether
1638 * NameLength is big enough before it checks for a
1639 * NULL buffer argument, so, while it'll still do
1640 * the right thing if NameLength is uninitialized and
1641 * whatever junk happens to be there is big enough
1642 * (because the pointer argument will be null), it's
1643 * still reading an uninitialized variable.
1644 */
1645 NameLength = 0;
1646 if (!PacketGetAdapterNames(NULL, &NameLength))
1647 {
1648 DWORD last_error = GetLastError();
1649
1650 if (last_error != ERROR_INSUFFICIENT_BUFFER)
1651 {
1652 pcap_win32_err_to_str(last_error, our_errbuf);
1653 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1654 "PacketGetAdapterNames: %s", our_errbuf);
1655 return (-1);
1656 }
1657 }
1658
1659 if (NameLength <= 0)
1660 return 0;
1661 AdaptersName = (char*) malloc(NameLength);
1662 if (AdaptersName == NULL)
1663 {
1664 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
1665 return (-1);
1666 }
1667
1668 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
1669 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1670 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "PacketGetAdapterNames: %s",
1671 our_errbuf);
1672 free(AdaptersName);
1673 return (-1);
1674 }
1675
1676 /*
1677 * "PacketGetAdapterNames()" returned a list of
1678 * null-terminated ASCII interface name strings,
1679 * terminated by a null string, followed by a list
1680 * of null-terminated ASCII interface description
1681 * strings, terminated by a null string.
1682 * This means there are two ASCII nulls at the end
1683 * of the first list.
1684 *
1685 * Find the end of the first list; that's the
1686 * beginning of the second list.
1687 */
1688 desc = &AdaptersName[0];
1689 while (*desc != '\0' || *(desc + 1) != '\0')
1690 desc++;
1691
1692 /*
1693 * Found it - "desc" points to the first of the two
1694 * nulls at the end of the list of names, so the
1695 * first byte of the list of descriptions is two bytes
1696 * after it.
1697 */
1698 desc += 2;
1699
1700 /*
1701 * Loop over the elements in the first list.
1702 */
1703 name = &AdaptersName[0];
1704 while (*name != '\0') {
1705 bpf_u_int32 flags = 0;
1706 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1707 /*
1708 * Is this a loopback interface?
1709 */
1710 if (PacketIsLoopbackAdapter(name)) {
1711 /* Yes */
1712 flags |= PCAP_IF_LOOPBACK;
1713 }
1714 #endif
1715
1716 /*
1717 * XXX - get the link state here.
1718 * Does the OID we want depend on NDIS 5 vs. NDIS 6?
1719 * If so, that means that there should be a packet.dll
1720 * API for this.
1721 * Set the appropriate bits in flags.
1722 */
1723
1724 /*
1725 * Add an entry for this interface.
1726 */
1727 if (pcap_add_if_win32(devlistp, name, flags, desc,
1728 errbuf) == -1) {
1729 /*
1730 * Failure.
1731 */
1732 ret = -1;
1733 break;
1734 }
1735 name += strlen(name) + 1;
1736 desc += strlen(desc) + 1;
1737 }
1738
1739 free(AdaptersName);
1740 return (ret);
1741 }
1742
1743 /*
1744 * Return the name of a network interface attached to the system, or NULL
1745 * if none can be found. The interface must be configured up; the
1746 * lowest unit number is preferred; loopback is ignored.
1747 *
1748 * In the best of all possible worlds, this would be the same as on
1749 * UN*X, but there may be software that expects this to return a
1750 * full list of devices after the first device.
1751 */
1752 #define ADAPTERSNAME_LEN 8192
1753 char *
1754 pcap_lookupdev(char *errbuf)
1755 {
1756 DWORD dwVersion;
1757 DWORD dwWindowsMajorVersion;
1758 char our_errbuf[PCAP_ERRBUF_SIZE+1];
1759
1760 #pragma warning (push)
1761 #pragma warning (disable: 4996) /* disable MSVC's GetVersion() deprecated warning here */
1762 dwVersion = GetVersion(); /* get the OS version */
1763 #pragma warning (pop)
1764 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
1765
1766 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
1767 /*
1768 * Windows 95, 98, ME.
1769 */
1770 ULONG NameLength = ADAPTERSNAME_LEN;
1771 static char AdaptersName[ADAPTERSNAME_LEN];
1772
1773 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
1774 return (AdaptersName);
1775 else
1776 return NULL;
1777 } else {
1778 /*
1779 * Windows NT (NT 4.0 and later).
1780 * Convert the names to Unicode for backward compatibility.
1781 */
1782 ULONG NameLength = ADAPTERSNAME_LEN;
1783 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
1784 size_t BufferSpaceLeft;
1785 char *tAstr;
1786 WCHAR *Unameptr;
1787 char *Adescptr;
1788 size_t namelen, i;
1789 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
1790 int NAdapts = 0;
1791
1792 if(TAdaptersName == NULL)
1793 {
1794 (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
1795 return NULL;
1796 }
1797
1798 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
1799 {
1800 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1801 (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1802 "PacketGetAdapterNames: %s", our_errbuf);
1803 free(TAdaptersName);
1804 return NULL;
1805 }
1806
1807
1808 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
1809 tAstr = (char*)TAdaptersName;
1810 Unameptr = AdaptersName;
1811
1812 /*
1813 * Convert the device names to Unicode into AdapterName.
1814 */
1815 do {
1816 /*
1817 * Length of the name, including the terminating
1818 * NUL.
1819 */
1820 namelen = strlen(tAstr) + 1;
1821
1822 /*
1823 * Do we have room for the name in the Unicode
1824 * buffer?
1825 */
1826 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
1827 /*
1828 * No.
1829 */
1830 goto quit;
1831 }
1832 BufferSpaceLeft -= namelen * sizeof(WCHAR);
1833
1834 /*
1835 * Copy the name, converting ASCII to Unicode.
1836 * namelen includes the NUL, so we copy it as
1837 * well.
1838 */
1839 for (i = 0; i < namelen; i++)
1840 *Unameptr++ = *tAstr++;
1841
1842 /*
1843 * Count this adapter.
1844 */
1845 NAdapts++;
1846 } while (namelen != 1);
1847
1848 /*
1849 * Copy the descriptions, but don't convert them from
1850 * ASCII to Unicode.
1851 */
1852 Adescptr = (char *)Unameptr;
1853 while(NAdapts--)
1854 {
1855 size_t desclen;
1856
1857 desclen = strlen(tAstr) + 1;
1858
1859 /*
1860 * Do we have room for the name in the Unicode
1861 * buffer?
1862 */
1863 if (BufferSpaceLeft < desclen) {
1864 /*
1865 * No.
1866 */
1867 goto quit;
1868 }
1869
1870 /*
1871 * Just copy the ASCII string.
1872 * namelen includes the NUL, so we copy it as
1873 * well.
1874 */
1875 memcpy(Adescptr, tAstr, desclen);
1876 Adescptr += desclen;
1877 tAstr += desclen;
1878 BufferSpaceLeft -= desclen;
1879 }
1880
1881 quit:
1882 free(TAdaptersName);
1883 return (char *)(AdaptersName);
1884 }
1885 }
1886
1887 /*
1888 * We can't use the same code that we use on UN*X, as that's doing
1889 * UN*X-specific calls.
1890 *
1891 * We don't just fetch the entire list of devices, search for the
1892 * particular device, and use its first IPv4 address, as that's too
1893 * much work to get just one device's netmask.
1894 */
1895 int
1896 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
1897 char *errbuf)
1898 {
1899 /*
1900 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
1901 * in order to skip non IPv4 (i.e. IPv6 addresses)
1902 */
1903 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1904 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
1905 struct sockaddr_in *t_addr;
1906 LONG i;
1907
1908 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
1909 *netp = *maskp = 0;
1910 return (0);
1911 }
1912
1913 for(i = 0; i < if_addr_size; i++)
1914 {
1915 if(if_addrs[i].IPAddress.ss_family == AF_INET)
1916 {
1917 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
1918 *netp = t_addr->sin_addr.S_un.S_addr;
1919 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
1920 *maskp = t_addr->sin_addr.S_un.S_addr;
1921
1922 *netp &= *maskp;
1923 return (0);
1924 }
1925
1926 }
1927
1928 *netp = *maskp = 0;
1929 return (0);
1930 }
1931
1932 static const char *pcap_lib_version_string;
1933
1934 #ifdef HAVE_VERSION_H
1935 /*
1936 * libpcap being built for Windows, as part of a WinPcap/Npcap source
1937 * tree. Include version.h from that source tree to get the WinPcap/Npcap
1938 * version.
1939 *
1940 * XXX - it'd be nice if we could somehow generate the WinPcap version number
1941 * when building WinPcap. (It'd be nice to do so for the packet.dll version
1942 * number as well.)
1943 */
1944 #include "../../version.h"
1945
1946 static const char pcap_version_string[] =
1947 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
1948 static const char pcap_version_string_packet_dll_fmt[] =
1949 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING;
1950
1951 const char *
1952 pcap_lib_version(void)
1953 {
1954 char *packet_version_string;
1955 size_t full_pcap_version_string_len;
1956 char *full_pcap_version_string;
1957
1958 if (pcap_lib_version_string == NULL) {
1959 /*
1960 * Generate the version string.
1961 */
1962 packet_version_string = PacketGetVersion();
1963 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
1964 /*
1965 * WinPcap version string and packet.dll version
1966 * string are the same; just report the WinPcap
1967 * version.
1968 */
1969 pcap_lib_version_string = pcap_version_string;
1970 } else {
1971 /*
1972 * WinPcap version string and packet.dll version
1973 * string are different; that shouldn't be the
1974 * case (the two libraries should come from the
1975 * same version of WinPcap), so we report both
1976 * versions.
1977 *
1978 * The -2 is for the %s in the format string,
1979 * which will be replaced by packet_version_string.
1980 */
1981 full_pcap_version_string_len =
1982 (sizeof pcap_version_string_packet_dll_fmt - 2) +
1983 strlen(packet_version_string);
1984 full_pcap_version_string = malloc(full_pcap_version_string_len);
1985 if (full_pcap_version_string == NULL)
1986 return (NULL);
1987 pcap_snprintf(full_pcap_version_string,
1988 full_pcap_version_string_len,
1989 pcap_version_string_packet_dll_fmt,
1990 packet_version_string);
1991 }
1992 pcap_lib_version_string = full_pcap_version_string;
1993 }
1994 return (pcap_lib_version_string);
1995 }
1996
1997 #else /* HAVE_VERSION_H */
1998
1999 /*
2000 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2001 * tree.
2002 */
2003 static const char pcap_version_string_packet_dll_fmt[] =
2004 PCAP_VERSION_STRING " (packet.dll version %s)";
2005 const char *
2006 pcap_lib_version(void)
2007 {
2008 char *packet_version_string;
2009 size_t full_pcap_version_string_len;
2010 char *full_pcap_version_string;
2011
2012 if (pcap_lib_version_string == NULL) {
2013 /*
2014 * Generate the version string. Report the packet.dll
2015 * version.
2016 *
2017 * The -2 is for the %s in the format string, which will
2018 * be replaced by packet_version_string.
2019 */
2020 packet_version_string = PacketGetVersion();
2021 full_pcap_version_string_len =
2022 (sizeof pcap_version_string_packet_dll_fmt - 2) +
2023 strlen(packet_version_string);
2024 full_pcap_version_string = malloc(full_pcap_version_string_len);
2025 if (full_pcap_version_string == NULL)
2026 return (NULL);
2027 pcap_snprintf(full_pcap_version_string,
2028 full_pcap_version_string_len,
2029 pcap_version_string_packet_dll_fmt,
2030 packet_version_string);
2031 pcap_lib_version_string = full_pcap_version_string;
2032 }
2033 return (pcap_lib_version_string);
2034 }
2035 #endif /* HAVE_VERSION_H */