]> The Tcpdump Group git mirrors - libpcap/blob - pcap-npf.c
Merge pull request #826 from catenacyber/doublefree
[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 * reliable 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 - pcap_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 pcap_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 (pcap_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, int 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 (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 void
871 pcap_breakloop_npf(pcap_t *p)
872 {
873 pcap_breakloop_common(p);
874 struct pcap_win *pw = p->priv;
875
876 /* XXX - what if this fails? */
877 SetEvent(PacketGetReadEvent(pw->adapter));
878 }
879
880 static int
881 pcap_activate_npf(pcap_t *p)
882 {
883 struct pcap_win *pw = p->priv;
884 NetType type;
885 int res;
886 char errbuf[PCAP_ERRBUF_SIZE+1];
887
888 if (p->opt.rfmon) {
889 /*
890 * Monitor mode is supported on Windows Vista and later.
891 */
892 if (PacketGetMonitorMode(p->opt.device) == 1)
893 {
894 pw->rfmon_selfstart = 0;
895 }
896 else
897 {
898 if ((res = PacketSetMonitorMode(p->opt.device, 1)) != 1)
899 {
900 pw->rfmon_selfstart = 0;
901 // Monitor mode is not supported.
902 if (res == 0)
903 {
904 return PCAP_ERROR_RFMON_NOTSUP;
905 }
906 else
907 {
908 return PCAP_ERROR;
909 }
910 }
911 else
912 {
913 pw->rfmon_selfstart = 1;
914 }
915 }
916 }
917
918 /* Init WinSock */
919 pcap_wsockinit();
920
921 pw->adapter = PacketOpenAdapter(p->opt.device);
922
923 if (pw->adapter == NULL)
924 {
925 /* Adapter detected but we are not able to open it. Return failure. */
926 pcap_win32_err_to_str(GetLastError(), errbuf);
927 if (pw->rfmon_selfstart)
928 {
929 PacketSetMonitorMode(p->opt.device, 0);
930 }
931 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
932 "Error opening adapter: %s", errbuf);
933 return (PCAP_ERROR);
934 }
935
936 /*get network type*/
937 if(PacketGetNetType (pw->adapter,&type) == FALSE)
938 {
939 pcap_win32_err_to_str(GetLastError(), errbuf);
940 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
941 "Cannot determine the network type: %s", errbuf);
942 goto bad;
943 }
944
945 /*Set the linktype*/
946 switch (type.LinkType)
947 {
948 case NdisMediumWan:
949 p->linktype = DLT_EN10MB;
950 break;
951
952 case NdisMedium802_3:
953 p->linktype = DLT_EN10MB;
954 /*
955 * This is (presumably) a real Ethernet capture; give it a
956 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
957 * that an application can let you choose it, in case you're
958 * capturing DOCSIS traffic that a Cisco Cable Modem
959 * Termination System is putting out onto an Ethernet (it
960 * doesn't put an Ethernet header onto the wire, it puts raw
961 * DOCSIS frames out on the wire inside the low-level
962 * Ethernet framing).
963 */
964 p->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
965 /*
966 * If that fails, just leave the list empty.
967 */
968 if (p->dlt_list != NULL) {
969 p->dlt_list[0] = DLT_EN10MB;
970 p->dlt_list[1] = DLT_DOCSIS;
971 p->dlt_count = 2;
972 }
973 break;
974
975 case NdisMediumFddi:
976 p->linktype = DLT_FDDI;
977 break;
978
979 case NdisMedium802_5:
980 p->linktype = DLT_IEEE802;
981 break;
982
983 case NdisMediumArcnetRaw:
984 p->linktype = DLT_ARCNET;
985 break;
986
987 case NdisMediumArcnet878_2:
988 p->linktype = DLT_ARCNET;
989 break;
990
991 case NdisMediumAtm:
992 p->linktype = DLT_ATM_RFC1483;
993 break;
994
995 case NdisMediumCHDLC:
996 p->linktype = DLT_CHDLC;
997 break;
998
999 case NdisMediumPPPSerial:
1000 p->linktype = DLT_PPP_SERIAL;
1001 break;
1002
1003 case NdisMediumNull:
1004 p->linktype = DLT_NULL;
1005 break;
1006
1007 case NdisMediumBare80211:
1008 p->linktype = DLT_IEEE802_11;
1009 break;
1010
1011 case NdisMediumRadio80211:
1012 p->linktype = DLT_IEEE802_11_RADIO;
1013 break;
1014
1015 case NdisMediumPpi:
1016 p->linktype = DLT_PPI;
1017 break;
1018
1019 #ifdef NdisMediumWirelessWan
1020 case NdisMediumWirelessWan:
1021 p->linktype = DLT_RAW;
1022 break;
1023 #endif
1024
1025 default:
1026 p->linktype = DLT_EN10MB; /*an unknown adapter is assumed to be ethernet*/
1027 break;
1028 }
1029
1030 /*
1031 * Turn a negative snapshot value (invalid), a snapshot value of
1032 * 0 (unspecified), or a value bigger than the normal maximum
1033 * value, into the maximum allowed value.
1034 *
1035 * If some application really *needs* a bigger snapshot
1036 * length, we should just increase MAXIMUM_SNAPLEN.
1037 */
1038 if (p->snapshot <= 0 || p->snapshot > MAXIMUM_SNAPLEN)
1039 p->snapshot = MAXIMUM_SNAPLEN;
1040
1041 /* Set promiscuous mode */
1042 if (p->opt.promisc)
1043 {
1044
1045 if (PacketSetHwFilter(pw->adapter,NDIS_PACKET_TYPE_PROMISCUOUS) == FALSE)
1046 {
1047 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to promiscuous mode");
1048 goto bad;
1049 }
1050 }
1051 else
1052 {
1053 /* NDIS_PACKET_TYPE_ALL_LOCAL selects "All packets sent by installed
1054 * protocols and all packets indicated by the NIC" but if no protocol
1055 * drivers (like TCP/IP) are installed, NDIS_PACKET_TYPE_DIRECTED,
1056 * NDIS_PACKET_TYPE_BROADCAST, and NDIS_PACKET_TYPE_MULTICAST are needed to
1057 * capture incoming frames.
1058 */
1059 if (PacketSetHwFilter(pw->adapter,
1060 NDIS_PACKET_TYPE_ALL_LOCAL |
1061 NDIS_PACKET_TYPE_DIRECTED |
1062 NDIS_PACKET_TYPE_BROADCAST |
1063 NDIS_PACKET_TYPE_MULTICAST) == FALSE)
1064 {
1065 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "failed to set hardware filter to non-promiscuous mode");
1066 goto bad;
1067 }
1068 }
1069
1070 /* Set the buffer size */
1071 p->bufsize = WIN32_DEFAULT_USER_BUFFER_SIZE;
1072
1073 if(!(pw->adapter->Flags & INFO_FLAG_DAG_CARD))
1074 {
1075 /*
1076 * Traditional Adapter
1077 */
1078 /*
1079 * If the buffer size wasn't explicitly set, default to
1080 * WIN32_DEFAULT_KERNEL_BUFFER_SIZE.
1081 */
1082 if (p->opt.buffer_size == 0)
1083 p->opt.buffer_size = WIN32_DEFAULT_KERNEL_BUFFER_SIZE;
1084
1085 if(PacketSetBuff(pw->adapter,p->opt.buffer_size)==FALSE)
1086 {
1087 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "driver error: not enough memory to allocate the kernel buffer");
1088 goto bad;
1089 }
1090
1091 p->buffer = malloc(p->bufsize);
1092 if (p->buffer == NULL)
1093 {
1094 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
1095 errno, "malloc");
1096 goto bad;
1097 }
1098
1099 if (p->opt.immediate)
1100 {
1101 /* tell the driver to copy the buffer as soon as data arrives */
1102 if(PacketSetMinToCopy(pw->adapter,0)==FALSE)
1103 {
1104 pcap_win32_err_to_str(GetLastError(), errbuf);
1105 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1106 "Error calling PacketSetMinToCopy: %s",
1107 errbuf);
1108 goto bad;
1109 }
1110 }
1111 else
1112 {
1113 /* tell the driver to copy the buffer only if it contains at least 16K */
1114 if(PacketSetMinToCopy(pw->adapter,16000)==FALSE)
1115 {
1116 pcap_win32_err_to_str(GetLastError(), errbuf);
1117 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1118 "Error calling PacketSetMinToCopy: %s",
1119 errbuf);
1120 goto bad;
1121 }
1122 }
1123 } else {
1124 /*
1125 * Dag Card
1126 */
1127 #ifdef HAVE_DAG_API
1128 /*
1129 * We have DAG support.
1130 */
1131 LONG status;
1132 HKEY dagkey;
1133 DWORD lptype;
1134 DWORD lpcbdata;
1135 int postype = 0;
1136 char keyname[512];
1137
1138 pcap_snprintf(keyname, sizeof(keyname), "%s\\CardParams\\%s",
1139 "SYSTEM\\CurrentControlSet\\Services\\DAG",
1140 strstr(_strlwr(p->opt.device), "dag"));
1141 do
1142 {
1143 status = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_READ, &dagkey);
1144 if(status != ERROR_SUCCESS)
1145 break;
1146
1147 status = RegQueryValueEx(dagkey,
1148 "PosType",
1149 NULL,
1150 &lptype,
1151 (char*)&postype,
1152 &lpcbdata);
1153
1154 if(status != ERROR_SUCCESS)
1155 {
1156 postype = 0;
1157 }
1158
1159 RegCloseKey(dagkey);
1160 }
1161 while(FALSE);
1162
1163
1164 p->snapshot = PacketSetSnapLen(pw->adapter, p->snapshot);
1165
1166 /* Set the length of the FCS associated to any packet. This value
1167 * will be subtracted to the packet length */
1168 pw->dag_fcs_bits = pw->adapter->DagFcsLen;
1169 #else /* HAVE_DAG_API */
1170 /*
1171 * No DAG support.
1172 */
1173 goto bad;
1174 #endif /* HAVE_DAG_API */
1175 }
1176
1177 PacketSetReadTimeout(pw->adapter, p->opt.timeout);
1178
1179 /* disable loopback capture if requested */
1180 if (p->opt.nocapture_local)
1181 {
1182 if (!PacketSetLoopbackBehavior(pw->adapter, NPF_DISABLE_LOOPBACK))
1183 {
1184 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1185 "Unable to disable the capture of loopback packets.");
1186 goto bad;
1187 }
1188 }
1189
1190 #ifdef HAVE_DAG_API
1191 if(pw->adapter->Flags & INFO_FLAG_DAG_CARD)
1192 {
1193 /* install dag specific handlers for read and setfilter */
1194 p->read_op = pcap_read_win32_dag;
1195 p->setfilter_op = pcap_setfilter_win32_dag;
1196 }
1197 else
1198 {
1199 #endif /* HAVE_DAG_API */
1200 /* install traditional npf handlers for read and setfilter */
1201 p->read_op = pcap_read_npf;
1202 p->setfilter_op = pcap_setfilter_npf;
1203 #ifdef HAVE_DAG_API
1204 }
1205 #endif /* HAVE_DAG_API */
1206 p->setdirection_op = NULL; /* Not implemented. */
1207 /* XXX - can this be implemented on some versions of Windows? */
1208 p->inject_op = pcap_inject_npf;
1209 p->set_datalink_op = NULL; /* can't change data link type */
1210 p->getnonblock_op = pcap_getnonblock_npf;
1211 p->setnonblock_op = pcap_setnonblock_npf;
1212 p->stats_op = pcap_stats_npf;
1213 p->breakloop_op = pcap_breakloop_npf;
1214 p->stats_ex_op = pcap_stats_ex_npf;
1215 p->setbuff_op = pcap_setbuff_npf;
1216 p->setmode_op = pcap_setmode_npf;
1217 p->setmintocopy_op = pcap_setmintocopy_npf;
1218 p->getevent_op = pcap_getevent_npf;
1219 p->oid_get_request_op = pcap_oid_get_request_npf;
1220 p->oid_set_request_op = pcap_oid_set_request_npf;
1221 p->sendqueue_transmit_op = pcap_sendqueue_transmit_npf;
1222 p->setuserbuffer_op = pcap_setuserbuffer_npf;
1223 p->live_dump_op = pcap_live_dump_npf;
1224 p->live_dump_ended_op = pcap_live_dump_ended_npf;
1225 p->get_airpcap_handle_op = pcap_get_airpcap_handle_npf;
1226 p->cleanup_op = pcap_cleanup_npf;
1227
1228 /*
1229 * XXX - this is only done because WinPcap supported
1230 * pcap_fileno() returning the hFile HANDLE from the
1231 * ADAPTER structure. We make no general guarantees
1232 * that the caller can do anything useful with it.
1233 *
1234 * (Not that we make any general guarantee of that
1235 * sort on UN*X, either, any more, given that not
1236 * all capture devices are regular OS network
1237 * interfaces.)
1238 */
1239 p->handle = pw->adapter->hFile;
1240
1241 return (0);
1242 bad:
1243 pcap_cleanup_npf(p);
1244 return (PCAP_ERROR);
1245 }
1246
1247 /*
1248 * Check if rfmon mode is supported on the pcap_t for Windows systems.
1249 */
1250 static int
1251 pcap_can_set_rfmon_npf(pcap_t *p)
1252 {
1253 return (PacketIsMonitorModeSupported(p->opt.device) == 1);
1254 }
1255
1256 pcap_t *
1257 pcap_create_interface(const char *device _U_, char *ebuf)
1258 {
1259 pcap_t *p;
1260
1261 p = pcap_create_common(ebuf, sizeof(struct pcap_win));
1262 if (p == NULL)
1263 return (NULL);
1264
1265 p->activate_op = pcap_activate_npf;
1266 p->can_set_rfmon_op = pcap_can_set_rfmon_npf;
1267 return (p);
1268 }
1269
1270 static int
1271 pcap_setfilter_npf(pcap_t *p, struct bpf_program *fp)
1272 {
1273 struct pcap_win *pw = p->priv;
1274
1275 if(PacketSetBpf(pw->adapter,fp)==FALSE){
1276 /*
1277 * Kernel filter not installed.
1278 *
1279 * XXX - we don't know whether this failed because:
1280 *
1281 * the kernel rejected the filter program as invalid,
1282 * in which case we should fall back on userland
1283 * filtering;
1284 *
1285 * the kernel rejected the filter program as too big,
1286 * in which case we should again fall back on
1287 * userland filtering;
1288 *
1289 * there was some other problem, in which case we
1290 * should probably report an error.
1291 *
1292 * For NPF devices, the Win32 status will be
1293 * STATUS_INVALID_DEVICE_REQUEST for invalid
1294 * filters, but I don't know what it'd be for
1295 * other problems, and for some other devices
1296 * it might not be set at all.
1297 *
1298 * So we just fall back on userland filtering in
1299 * all cases.
1300 */
1301
1302 /*
1303 * install_bpf_program() validates the program.
1304 *
1305 * XXX - what if we already have a filter in the kernel?
1306 */
1307 if (install_bpf_program(p, fp) < 0)
1308 return (-1);
1309 pw->filtering_in_kernel = 0; /* filtering in userland */
1310 return (0);
1311 }
1312
1313 /*
1314 * It worked.
1315 */
1316 pw->filtering_in_kernel = 1; /* filtering in the kernel */
1317
1318 /*
1319 * Discard any previously-received packets, as they might have
1320 * passed whatever filter was formerly in effect, but might
1321 * not pass this filter (BIOCSETF discards packets buffered
1322 * in the kernel, so you can lose packets in any case).
1323 */
1324 p->cc = 0;
1325 return (0);
1326 }
1327
1328 /*
1329 * We filter at user level, since the kernel driver does't process the packets
1330 */
1331 static int
1332 pcap_setfilter_win32_dag(pcap_t *p, struct bpf_program *fp) {
1333
1334 if(!fp)
1335 {
1336 pcap_strlcpy(p->errbuf, "setfilter: No filter specified", sizeof(p->errbuf));
1337 return (-1);
1338 }
1339
1340 /* Install a user level filter */
1341 if (install_bpf_program(p, fp) < 0)
1342 return (-1);
1343
1344 return (0);
1345 }
1346
1347 static int
1348 pcap_getnonblock_npf(pcap_t *p)
1349 {
1350 struct pcap_win *pw = p->priv;
1351
1352 /*
1353 * XXX - if there were a PacketGetReadTimeout() call, we
1354 * would use it, and return 1 if the timeout is -1
1355 * and 0 otherwise.
1356 */
1357 return (pw->nonblock);
1358 }
1359
1360 static int
1361 pcap_setnonblock_npf(pcap_t *p, int nonblock)
1362 {
1363 struct pcap_win *pw = p->priv;
1364 int newtimeout;
1365 char win_errbuf[PCAP_ERRBUF_SIZE+1];
1366
1367 if (nonblock) {
1368 /*
1369 * Set the packet buffer timeout to -1 for non-blocking
1370 * mode.
1371 */
1372 newtimeout = -1;
1373 } else {
1374 /*
1375 * Restore the timeout set when the device was opened.
1376 * (Note that this may be -1, in which case we're not
1377 * really leaving non-blocking mode. However, although
1378 * the timeout argument to pcap_set_timeout() and
1379 * pcap_open_live() is an int, you're not supposed to
1380 * supply a negative value, so that "shouldn't happen".)
1381 */
1382 newtimeout = p->opt.timeout;
1383 }
1384 if (!PacketSetReadTimeout(pw->adapter, newtimeout)) {
1385 pcap_win32_err_to_str(GetLastError(), win_errbuf);
1386 pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
1387 "PacketSetReadTimeout: %s", win_errbuf);
1388 return (-1);
1389 }
1390 pw->nonblock = (newtimeout == -1);
1391 return (0);
1392 }
1393
1394 static int
1395 pcap_add_if_npf(pcap_if_list_t *devlistp, char *name, bpf_u_int32 flags,
1396 const char *description, char *errbuf)
1397 {
1398 pcap_if_t *curdev;
1399 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1400 LONG if_addr_size;
1401 int res = 0;
1402
1403 if_addr_size = MAX_NETWORK_ADDRESSES;
1404
1405 /*
1406 * Add an entry for this interface, with no addresses.
1407 */
1408 curdev = add_dev(devlistp, name, flags, description, errbuf);
1409 if (curdev == NULL) {
1410 /*
1411 * Failure.
1412 */
1413 return (-1);
1414 }
1415
1416 /*
1417 * Get the list of addresses for the interface.
1418 */
1419 if (!PacketGetNetInfoEx((void *)name, if_addrs, &if_addr_size)) {
1420 /*
1421 * Failure.
1422 *
1423 * We don't return an error, because this can happen with
1424 * NdisWan interfaces, and we want to supply them even
1425 * if we can't supply their addresses.
1426 *
1427 * We return an entry with an empty address list.
1428 */
1429 return (0);
1430 }
1431
1432 /*
1433 * Now add the addresses.
1434 */
1435 while (if_addr_size-- > 0) {
1436 /*
1437 * "curdev" is an entry for this interface; add an entry for
1438 * this address to its list of addresses.
1439 */
1440 res = add_addr_to_dev(curdev,
1441 (struct sockaddr *)&if_addrs[if_addr_size].IPAddress,
1442 sizeof (struct sockaddr_storage),
1443 (struct sockaddr *)&if_addrs[if_addr_size].SubnetMask,
1444 sizeof (struct sockaddr_storage),
1445 (struct sockaddr *)&if_addrs[if_addr_size].Broadcast,
1446 sizeof (struct sockaddr_storage),
1447 NULL,
1448 0,
1449 errbuf);
1450 if (res == -1) {
1451 /*
1452 * Failure.
1453 */
1454 break;
1455 }
1456 }
1457
1458 return (res);
1459 }
1460
1461 static int
1462 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
1463 {
1464 char *name_copy;
1465 ADAPTER *adapter;
1466 int status;
1467 size_t len;
1468 NDIS_HARDWARE_STATUS hardware_status;
1469 #ifdef OID_GEN_PHYSICAL_MEDIUM
1470 NDIS_PHYSICAL_MEDIUM phys_medium;
1471 bpf_u_int32 gen_physical_medium_oids[] = {
1472 #ifdef OID_GEN_PHYSICAL_MEDIUM_EX
1473 OID_GEN_PHYSICAL_MEDIUM_EX,
1474 #endif
1475 OID_GEN_PHYSICAL_MEDIUM
1476 };
1477 #define N_GEN_PHYSICAL_MEDIUM_OIDS (sizeof gen_physical_medium_oids / sizeof gen_physical_medium_oids[0])
1478 size_t i;
1479 #endif /* OID_GEN_PHYSICAL_MEDIUM */
1480 #ifdef OID_GEN_LINK_STATE
1481 NDIS_LINK_STATE link_state;
1482 #endif
1483 int connect_status;
1484
1485 if (*flags & PCAP_IF_LOOPBACK) {
1486 /*
1487 * Loopback interface, so the connection status doesn't
1488 * apply. and it's not wireless (or wired, for that
1489 * matter...). We presume it's up and running.
1490 */
1491 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING | PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1492 return (0);
1493 }
1494
1495 /*
1496 * We need to open the adapter to get this information.
1497 *
1498 * XXX - PacketOpenAdapter() takes a non-const pointer
1499 * as an argument, so we make a copy of the argument and
1500 * pass that to it.
1501 */
1502 name_copy = strdup(name);
1503 adapter = PacketOpenAdapter(name_copy);
1504 free(name_copy);
1505 if (adapter == NULL) {
1506 /*
1507 * Give up; if they try to open this device, it'll fail.
1508 */
1509 return (0);
1510 }
1511
1512 #ifdef HAVE_AIRPCAP_API
1513 /*
1514 * Airpcap.sys do not support the below 'OID_GEN_x' values.
1515 * Just set these flags (and none of the '*flags' entered with).
1516 */
1517 if (PacketGetAirPcapHandle(adapter)) {
1518 /*
1519 * Must be "up" and "running" if the above if succeeded.
1520 */
1521 *flags = PCAP_IF_UP | PCAP_IF_RUNNING;
1522
1523 /*
1524 * An airpcap device is a wireless device (duh!)
1525 */
1526 *flags |= PCAP_IF_WIRELESS;
1527
1528 /*
1529 * A "network assosiation state" makes no sense for airpcap.
1530 */
1531 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
1532 PacketCloseAdapter(adapter);
1533 return (0);
1534 }
1535 #endif
1536
1537 /*
1538 * Get the hardware status, and derive "up" and "running" from
1539 * that.
1540 */
1541 len = sizeof (hardware_status);
1542 status = oid_get_request(adapter, OID_GEN_HARDWARE_STATUS,
1543 &hardware_status, &len, errbuf);
1544 if (status == 0) {
1545 switch (hardware_status) {
1546
1547 case NdisHardwareStatusReady:
1548 /*
1549 * "Available and capable of sending and receiving
1550 * data over the wire", so up and running.
1551 */
1552 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1553 break;
1554
1555 case NdisHardwareStatusInitializing:
1556 case NdisHardwareStatusReset:
1557 /*
1558 * "Initializing" or "Resetting", so up, but
1559 * not running.
1560 */
1561 *flags |= PCAP_IF_UP;
1562 break;
1563
1564 case NdisHardwareStatusClosing:
1565 case NdisHardwareStatusNotReady:
1566 /*
1567 * "Closing" or "Not ready", so neither up nor
1568 * running.
1569 */
1570 break;
1571 }
1572 } else {
1573 /*
1574 * Can't get the hardware status, so assume both up and
1575 * running.
1576 */
1577 *flags |= PCAP_IF_UP | PCAP_IF_RUNNING;
1578 }
1579
1580 /*
1581 * Get the network type.
1582 */
1583 #ifdef OID_GEN_PHYSICAL_MEDIUM
1584 /*
1585 * Try the OIDs we have for this, in order.
1586 */
1587 for (i = 0; i < N_GEN_PHYSICAL_MEDIUM_OIDS; i++) {
1588 len = sizeof (phys_medium);
1589 status = oid_get_request(adapter, gen_physical_medium_oids[i],
1590 &phys_medium, &len, errbuf);
1591 if (status == 0) {
1592 /*
1593 * Success.
1594 */
1595 break;
1596 }
1597 /*
1598 * Failed. We can't determine whether it failed
1599 * because that particular OID isn't supported
1600 * or because some other problem occurred, so we
1601 * just drive on and try the next OID.
1602 */
1603 }
1604 if (status == 0) {
1605 /*
1606 * We got the physical medium.
1607 */
1608 switch (phys_medium) {
1609
1610 case NdisPhysicalMediumWirelessLan:
1611 case NdisPhysicalMediumWirelessWan:
1612 case NdisPhysicalMediumNative802_11:
1613 case NdisPhysicalMediumBluetooth:
1614 case NdisPhysicalMediumUWB:
1615 case NdisPhysicalMediumIrda:
1616 /*
1617 * Wireless.
1618 */
1619 *flags |= PCAP_IF_WIRELESS;
1620 break;
1621
1622 default:
1623 /*
1624 * Not wireless.
1625 */
1626 break;
1627 }
1628 }
1629 #endif
1630
1631 /*
1632 * Get the connection status.
1633 */
1634 #ifdef OID_GEN_LINK_STATE
1635 len = sizeof(link_state);
1636 status = oid_get_request(adapter, OID_GEN_LINK_STATE, &link_state,
1637 &len, errbuf);
1638 if (status == 0) {
1639 /*
1640 * NOTE: this also gives us the receive and transmit
1641 * link state.
1642 */
1643 switch (link_state.MediaConnectState) {
1644
1645 case MediaConnectStateConnected:
1646 /*
1647 * It's connected.
1648 */
1649 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
1650 break;
1651
1652 case MediaConnectStateDisconnected:
1653 /*
1654 * It's disconnected.
1655 */
1656 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
1657 break;
1658 }
1659 }
1660 #else
1661 /*
1662 * OID_GEN_LINK_STATE isn't supported because it's not in our SDK.
1663 */
1664 status = -1;
1665 #endif
1666 if (status == -1) {
1667 /*
1668 * OK, OID_GEN_LINK_STATE didn't work, try
1669 * OID_GEN_MEDIA_CONNECT_STATUS.
1670 */
1671 status = oid_get_request(adapter, OID_GEN_MEDIA_CONNECT_STATUS,
1672 &connect_status, &len, errbuf);
1673 if (status == 0) {
1674 switch (connect_status) {
1675
1676 case NdisMediaStateConnected:
1677 /*
1678 * It's connected.
1679 */
1680 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
1681 break;
1682
1683 case NdisMediaStateDisconnected:
1684 /*
1685 * It's disconnected.
1686 */
1687 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
1688 break;
1689 }
1690 }
1691 }
1692 PacketCloseAdapter(adapter);
1693 return (0);
1694 }
1695
1696 int
1697 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
1698 {
1699 int ret = 0;
1700 const char *desc;
1701 char *AdaptersName;
1702 ULONG NameLength;
1703 char *name;
1704 char our_errbuf[PCAP_ERRBUF_SIZE+1];
1705
1706 /*
1707 * Find out how big a buffer we need.
1708 *
1709 * This call should always return FALSE; if the error is
1710 * ERROR_INSUFFICIENT_BUFFER, NameLength will be set to
1711 * the size of the buffer we need, otherwise there's a
1712 * problem, and NameLength should be set to 0.
1713 *
1714 * It shouldn't require NameLength to be set, but,
1715 * at least as of WinPcap 4.1.3, it checks whether
1716 * NameLength is big enough before it checks for a
1717 * NULL buffer argument, so, while it'll still do
1718 * the right thing if NameLength is uninitialized and
1719 * whatever junk happens to be there is big enough
1720 * (because the pointer argument will be null), it's
1721 * still reading an uninitialized variable.
1722 */
1723 NameLength = 0;
1724 if (!PacketGetAdapterNames(NULL, &NameLength))
1725 {
1726 DWORD last_error = GetLastError();
1727
1728 if (last_error != ERROR_INSUFFICIENT_BUFFER)
1729 {
1730 pcap_win32_err_to_str(last_error, our_errbuf);
1731 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1732 "PacketGetAdapterNames: %s", our_errbuf);
1733 return (-1);
1734 }
1735 }
1736
1737 if (NameLength <= 0)
1738 return 0;
1739 AdaptersName = (char*) malloc(NameLength);
1740 if (AdaptersName == NULL)
1741 {
1742 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Cannot allocate enough memory to list the adapters.");
1743 return (-1);
1744 }
1745
1746 if (!PacketGetAdapterNames(AdaptersName, &NameLength)) {
1747 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1748 pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "PacketGetAdapterNames: %s",
1749 our_errbuf);
1750 free(AdaptersName);
1751 return (-1);
1752 }
1753
1754 /*
1755 * "PacketGetAdapterNames()" returned a list of
1756 * null-terminated ASCII interface name strings,
1757 * terminated by a null string, followed by a list
1758 * of null-terminated ASCII interface description
1759 * strings, terminated by a null string.
1760 * This means there are two ASCII nulls at the end
1761 * of the first list.
1762 *
1763 * Find the end of the first list; that's the
1764 * beginning of the second list.
1765 */
1766 desc = &AdaptersName[0];
1767 while (*desc != '\0' || *(desc + 1) != '\0')
1768 desc++;
1769
1770 /*
1771 * Found it - "desc" points to the first of the two
1772 * nulls at the end of the list of names, so the
1773 * first byte of the list of descriptions is two bytes
1774 * after it.
1775 */
1776 desc += 2;
1777
1778 /*
1779 * Loop over the elements in the first list.
1780 */
1781 name = &AdaptersName[0];
1782 while (*name != '\0') {
1783 bpf_u_int32 flags = 0;
1784 #ifdef HAVE_PACKET_IS_LOOPBACK_ADAPTER
1785 /*
1786 * Is this a loopback interface?
1787 */
1788 if (PacketIsLoopbackAdapter(name)) {
1789 /* Yes */
1790 flags |= PCAP_IF_LOOPBACK;
1791 }
1792 #endif
1793 /*
1794 * Get additional flags.
1795 */
1796 if (get_if_flags(name, &flags, errbuf) == -1) {
1797 /*
1798 * Failure.
1799 */
1800 ret = -1;
1801 break;
1802 }
1803
1804 /*
1805 * Add an entry for this interface.
1806 */
1807 if (pcap_add_if_npf(devlistp, name, flags, desc,
1808 errbuf) == -1) {
1809 /*
1810 * Failure.
1811 */
1812 ret = -1;
1813 break;
1814 }
1815 name += strlen(name) + 1;
1816 desc += strlen(desc) + 1;
1817 }
1818
1819 free(AdaptersName);
1820 return (ret);
1821 }
1822
1823 /*
1824 * Return the name of a network interface attached to the system, or NULL
1825 * if none can be found. The interface must be configured up; the
1826 * lowest unit number is preferred; loopback is ignored.
1827 *
1828 * In the best of all possible worlds, this would be the same as on
1829 * UN*X, but there may be software that expects this to return a
1830 * full list of devices after the first device.
1831 */
1832 #define ADAPTERSNAME_LEN 8192
1833 char *
1834 pcap_lookupdev(char *errbuf)
1835 {
1836 DWORD dwVersion;
1837 DWORD dwWindowsMajorVersion;
1838 char our_errbuf[PCAP_ERRBUF_SIZE+1];
1839
1840 #pragma warning (push)
1841 #pragma warning (disable: 4996) /* disable MSVC's GetVersion() deprecated warning here */
1842 dwVersion = GetVersion(); /* get the OS version */
1843 #pragma warning (pop)
1844 dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
1845
1846 if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) {
1847 /*
1848 * Windows 95, 98, ME.
1849 */
1850 ULONG NameLength = ADAPTERSNAME_LEN;
1851 static char AdaptersName[ADAPTERSNAME_LEN];
1852
1853 if (PacketGetAdapterNames(AdaptersName,&NameLength) )
1854 return (AdaptersName);
1855 else
1856 return NULL;
1857 } else {
1858 /*
1859 * Windows NT (NT 4.0 and later).
1860 * Convert the names to Unicode for backward compatibility.
1861 */
1862 ULONG NameLength = ADAPTERSNAME_LEN;
1863 static WCHAR AdaptersName[ADAPTERSNAME_LEN];
1864 size_t BufferSpaceLeft;
1865 char *tAstr;
1866 WCHAR *Unameptr;
1867 char *Adescptr;
1868 size_t namelen, i;
1869 WCHAR *TAdaptersName = (WCHAR*)malloc(ADAPTERSNAME_LEN * sizeof(WCHAR));
1870 int NAdapts = 0;
1871
1872 if(TAdaptersName == NULL)
1873 {
1874 (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "memory allocation failure");
1875 return NULL;
1876 }
1877
1878 if ( !PacketGetAdapterNames((PTSTR)TAdaptersName,&NameLength) )
1879 {
1880 pcap_win32_err_to_str(GetLastError(), our_errbuf);
1881 (void)pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
1882 "PacketGetAdapterNames: %s", our_errbuf);
1883 free(TAdaptersName);
1884 return NULL;
1885 }
1886
1887
1888 BufferSpaceLeft = ADAPTERSNAME_LEN * sizeof(WCHAR);
1889 tAstr = (char*)TAdaptersName;
1890 Unameptr = AdaptersName;
1891
1892 /*
1893 * Convert the device names to Unicode into AdapterName.
1894 */
1895 do {
1896 /*
1897 * Length of the name, including the terminating
1898 * NUL.
1899 */
1900 namelen = strlen(tAstr) + 1;
1901
1902 /*
1903 * Do we have room for the name in the Unicode
1904 * buffer?
1905 */
1906 if (BufferSpaceLeft < namelen * sizeof(WCHAR)) {
1907 /*
1908 * No.
1909 */
1910 goto quit;
1911 }
1912 BufferSpaceLeft -= namelen * sizeof(WCHAR);
1913
1914 /*
1915 * Copy the name, converting ASCII to Unicode.
1916 * namelen includes the NUL, so we copy it as
1917 * well.
1918 */
1919 for (i = 0; i < namelen; i++)
1920 *Unameptr++ = *tAstr++;
1921
1922 /*
1923 * Count this adapter.
1924 */
1925 NAdapts++;
1926 } while (namelen != 1);
1927
1928 /*
1929 * Copy the descriptions, but don't convert them from
1930 * ASCII to Unicode.
1931 */
1932 Adescptr = (char *)Unameptr;
1933 while(NAdapts--)
1934 {
1935 size_t desclen;
1936
1937 desclen = strlen(tAstr) + 1;
1938
1939 /*
1940 * Do we have room for the name in the Unicode
1941 * buffer?
1942 */
1943 if (BufferSpaceLeft < desclen) {
1944 /*
1945 * No.
1946 */
1947 goto quit;
1948 }
1949
1950 /*
1951 * Just copy the ASCII string.
1952 * namelen includes the NUL, so we copy it as
1953 * well.
1954 */
1955 memcpy(Adescptr, tAstr, desclen);
1956 Adescptr += desclen;
1957 tAstr += desclen;
1958 BufferSpaceLeft -= desclen;
1959 }
1960
1961 quit:
1962 free(TAdaptersName);
1963 return (char *)(AdaptersName);
1964 }
1965 }
1966
1967 /*
1968 * We can't use the same code that we use on UN*X, as that's doing
1969 * UN*X-specific calls.
1970 *
1971 * We don't just fetch the entire list of devices, search for the
1972 * particular device, and use its first IPv4 address, as that's too
1973 * much work to get just one device's netmask.
1974 */
1975 int
1976 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
1977 char *errbuf)
1978 {
1979 /*
1980 * We need only the first IPv4 address, so we must scan the array returned by PacketGetNetInfo()
1981 * in order to skip non IPv4 (i.e. IPv6 addresses)
1982 */
1983 npf_if_addr if_addrs[MAX_NETWORK_ADDRESSES];
1984 LONG if_addr_size = MAX_NETWORK_ADDRESSES;
1985 struct sockaddr_in *t_addr;
1986 LONG i;
1987
1988 if (!PacketGetNetInfoEx((void *)device, if_addrs, &if_addr_size)) {
1989 *netp = *maskp = 0;
1990 return (0);
1991 }
1992
1993 for(i = 0; i < if_addr_size; i++)
1994 {
1995 if(if_addrs[i].IPAddress.ss_family == AF_INET)
1996 {
1997 t_addr = (struct sockaddr_in *) &(if_addrs[i].IPAddress);
1998 *netp = t_addr->sin_addr.S_un.S_addr;
1999 t_addr = (struct sockaddr_in *) &(if_addrs[i].SubnetMask);
2000 *maskp = t_addr->sin_addr.S_un.S_addr;
2001
2002 *netp &= *maskp;
2003 return (0);
2004 }
2005
2006 }
2007
2008 *netp = *maskp = 0;
2009 return (0);
2010 }
2011
2012 static const char *pcap_lib_version_string;
2013
2014 #ifdef HAVE_VERSION_H
2015 /*
2016 * libpcap being built for Windows, as part of a WinPcap/Npcap source
2017 * tree. Include version.h from that source tree to get the WinPcap/Npcap
2018 * version.
2019 *
2020 * XXX - it'd be nice if we could somehow generate the WinPcap version number
2021 * when building WinPcap. (It'd be nice to do so for the packet.dll version
2022 * number as well.)
2023 */
2024 #include "../../version.h"
2025
2026 static const char pcap_version_string[] =
2027 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING ", based on " PCAP_VERSION_STRING;
2028
2029 const char *
2030 pcap_lib_version(void)
2031 {
2032 if (pcap_lib_version_string == NULL) {
2033 /*
2034 * Generate the version string.
2035 */
2036 char *packet_version_string = PacketGetVersion();
2037
2038 if (strcmp(WINPCAP_VER_STRING, packet_version_string) == 0) {
2039 /*
2040 * WinPcap version string and packet.dll version
2041 * string are the same; just report the WinPcap
2042 * version.
2043 */
2044 pcap_lib_version_string = pcap_version_string;
2045 } else {
2046 /*
2047 * WinPcap version string and packet.dll version
2048 * string are different; that shouldn't be the
2049 * case (the two libraries should come from the
2050 * same version of WinPcap), so we report both
2051 * versions.
2052 */
2053 char *full_pcap_version_string;
2054
2055 if (pcap_asprintf(&full_pcap_version_string,
2056 WINPCAP_PRODUCT_NAME " version " WINPCAP_VER_STRING " (packet.dll version %s), based on " PCAP_VERSION_STRING,
2057 packet_version_string) != -1) {
2058 /* Success */
2059 pcap_lib_version_string = full_pcap_version_string;
2060 }
2061 }
2062 }
2063 return (pcap_lib_version_string);
2064 }
2065
2066 #else /* HAVE_VERSION_H */
2067
2068 /*
2069 * libpcap being built for Windows, not as part of a WinPcap/Npcap source
2070 * tree.
2071 */
2072 const char *
2073 pcap_lib_version(void)
2074 {
2075 if (pcap_lib_version_string == NULL) {
2076 /*
2077 * Generate the version string. Report the packet.dll
2078 * version.
2079 */
2080 char *full_pcap_version_string;
2081
2082 if (pcap_asprintf(&full_pcap_version_string,
2083 PCAP_VERSION_STRING " (packet.dll version %s)",
2084 PacketGetVersion()) != -1) {
2085 /* Success */
2086 pcap_lib_version_string = full_pcap_version_string;
2087 }
2088 }
2089 return (pcap_lib_version_string);
2090 }
2091 #endif /* HAVE_VERSION_H */