wlantest: Add preliminary version of IEEE 802.11 protocol testing tool
[mech_eap.git] / wlantest / readpcap.c
1 /*
2  * PCAP capture file reader
3  * Copyright (c) 2010, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14
15 #include "utils/includes.h"
16 #include <pcap/pcap.h>
17
18 #include "utils/common.h"
19 #include "wlantest.h"
20
21
22 int read_cap_file(struct wlantest *wt, const char *fname)
23 {
24         char errbuf[PCAP_ERRBUF_SIZE];
25         pcap_t *pcap;
26         unsigned int count = 0;
27         struct pcap_pkthdr *hdr;
28         const u_char *data;
29         int res;
30
31         pcap = pcap_open_offline(fname, errbuf);
32         if (pcap == NULL) {
33                 wpa_printf(MSG_ERROR, "Failed to read pcap file '%s': %s",
34                            fname, errbuf);
35                 return -1;
36         }
37
38         for (;;) {
39                 res = pcap_next_ex(pcap, &hdr, &data);
40                 if (res == -2)
41                         break; /* No more packets */
42                 if (res == -1) {
43                         wpa_printf(MSG_INFO, "pcap_next_ex failure: %s",
44                                    pcap_geterr(pcap));
45                         break;
46                 }
47                 if (res != 1) {
48                         wpa_printf(MSG_INFO, "Unexpected pcap_next_ex return "
49                                    "value %d", res);
50                         break;
51                 }
52
53                 /* Packet was read without problems */
54                 wpa_printf(MSG_EXCESSIVE, "pcap hdr: ts=%d.%06d "
55                            "len=%u/%u",
56                            (int) hdr->ts.tv_sec, (int) hdr->ts.tv_usec,
57                            hdr->caplen, hdr->len);
58                 if (hdr->caplen < hdr->len) {
59                         wpa_printf(MSG_DEBUG, "pcap: Dropped incomplete frame "
60                                    "(%u/%u captured)",
61                                    hdr->caplen, hdr->len);
62                         continue;
63                 }
64                 count++;
65                 wlantest_process(wt, data, hdr->caplen);
66         }
67
68         pcap_close(pcap);
69
70         wpa_printf(MSG_DEBUG, "Read %s: %u packets", fname, count);
71
72         return 0;
73 }