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