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