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