1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! PCAP file format
//!
//! See
//! [https://wiki.wireshark.org/Development/LibpcapFileFormat](https://wiki.wireshark.org/Development/LibpcapFileFormat)
//! for details.
//!
//! There are 2 main ways of parsing a PCAP file. The first method is to use
//! [`parse_pcap`](fn.parse_pcap.html). This method requires to load the entire
//! file to memory, and thus may not be good for large files.
//!
//! The [`PcapCapture`](struct.PcapCapture.html) implements the
//! [`Capture`](../trait.Capture.html) trait to provide generic methods. However,
//! this trait also reads the entire file.
//!
//! The second method is to first parse the PCAP header
//! using [`parse_pcap_header`](fn.parse_pcap_header.html), then
//! loop over [`parse_pcap_frame`](fn.parse_pcap_frame.html) to get the data.
//! This can be used in a streaming parser.


use nom::{IResult,le_u16,le_u32,le_i32};
use cookie_factory::GenError;

use packet::{Linktype,Packet,PacketHeader};
use capture::Capture;

/// PCAP global header
#[derive(Debug,PartialEq)]
pub struct PcapHeader {
    /// File format and byte ordering. If equal to `0xa1b2c3d4` then the rest of
    /// the file uses native byte ordering. If `0xd4c3b2a1` (swapped), then all
    /// following fields will have to be swapped too.
    pub magic_number: u32,
    /// Version major number (currently 2)
    pub version_major: u16,
    /// Version minor number (currently 4)
    pub version_minor: u16,
    /// The correction time in seconds between GMT (UTC) and the local timezone of the following packet header timestamps
    pub thiszone: i32,
    /// In theory, the accuracy of time stamps in the capture; in practice, all tools set it to 0
    pub sigfigs: u32,
    /// max len of captured packets, in octets
    pub snaplen: u32,
    /// Data link type
    pub network: i32
}


impl PcapHeader {
    pub fn new() -> PcapHeader {
        PcapHeader{
            magic_number: 0xa1b2c3d4, // native order
            version_major: 2,
            version_minor: 4,
            thiszone: 0,
            sigfigs: 0,
            snaplen: 0,
            network: 1 // default: LINKTYPE_ETHERNET
        }
    }

    pub fn to_string(&self) -> Vec<u8> {
        let mut mem : [u8;24] = [0; 24];

        let r = do_gen!(
            (&mut mem,0),
            gen_le_u32!(self.magic_number) >>
            gen_le_u16!(self.version_major) >>
            gen_le_u16!(self.version_minor) >>
            gen_le_i32!(self.thiszone) >>
            gen_le_u32!(self.sigfigs) >>
            gen_le_u32!(self.snaplen) >>
            gen_le_u32!(self.network)
            );
        match r {
            Ok((s,_)) => {
                let mut v = Vec::new();
                v.extend_from_slice(s);
                v
            },
            Err(e) => panic!("error {:?}", e),
        }
    }
}

/// Generic interface for PCAP file access
pub struct PcapCapture<'a> {
    pub header: PcapHeader,

    pub blocks: Vec<Packet<'a>>,
}

impl<'a> PcapCapture<'a> {
    pub fn from_file(i: &[u8]) -> Result<PcapCapture,IResult<&[u8],PcapCapture>> {
        match parse_pcap(i) {
            Ok((_, pcap)) => Ok(pcap),
            e             => Err(e)
        }
    }
}

impl<'a> Capture for PcapCapture<'a> {
    fn get_datalink(&self) -> Linktype {
        Linktype(self.header.network)
    }

    fn get_snaplen(&self) -> u32 {
        self.header.snaplen
    }

    fn iter_packets<'b>(&'b self) -> Box<Iterator<Item=Packet> + 'b> {
        Box::new(self.blocks.iter().cloned())
    }
}




/// Parse the entire file
///
/// Note: this requires the file to be fully loaded to memory.
pub fn parse_pcap(i: &[u8]) -> IResult<&[u8],PcapCapture> {
    do_parse!(
        i,
        hdr:    parse_pcap_header >>
        blocks: many0!(complete!(parse_pcap_frame)) >>
        (
            PcapCapture{
                header: hdr,
                blocks: blocks
            }
        )
    )
}

/// Read the PCAP global header
///
/// The global header contains the PCAP description and options
pub fn parse_pcap_header(i: &[u8]) -> IResult<&[u8],PcapHeader> {
    do_parse!(
        i,
        magic:   verify!(le_u32, |x| x == 0xa1b2c3d4 || x == 0xd4c3b2a1) >>
        major:   le_u16 >>
        minor:   le_u16 >>
        zone:    le_i32 >>
        sigfigs: le_u32 >>
        snaplen: le_u32 >>
        network: le_i32 >>
        (
            PcapHeader {
                magic_number: magic,
                version_major: major,
                version_minor: minor,
                thiszone: zone,
                sigfigs: sigfigs,
                snaplen: snaplen,
                network: network
            }
        )
    )
}

/// Read a PCAP record header and data
///
/// Each PCAP record starts with a small header, and is followed by packet data.
/// The packet data format depends on the LinkType.
pub fn parse_pcap_frame(i: &[u8]) -> IResult<&[u8],Packet> {
    do_parse!(
        i,
        ts_sec:  le_u32 >>
        ts_usec: le_u32 >>
        caplen:  le_u32 >>
        len:     le_u32 >>
        data:    take!(caplen) >>
        (
            Packet {
                header: PacketHeader {
                    ts_sec: ts_sec,
                    ts_usec: ts_usec,
                    caplen: caplen,
                    len: len
                },
                data: data
            }
        )
    )
}