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