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
//! Format Specification
//!
//! The format for serializing SAWP API Calls is a series of consecutive
//! self-contained messages.
//!
//! The messages are of the following msgpack type where `N` is the total number
//! messages ranging from two to infinity.
//!
//! | message | type  | description           |
//! |---------|-------|-----------------------|
//! | 1       | int   | version number        |
//! | 2..N    | call  | call structure fields |
//!
//! Calls are stored in seperate messages to allow for a streaming format. Users
//! _do not_ have to store the entire SAWP "file" into memory. Messages can be
//! parsed asynchronously.
//!
//! This format is subject to change and other applications should not attempt
//! to parse it. Use this library instead for encoding and decoding instead.

use crate::error::{Error, ErrorKind, Result};
use crate::Version;
use std::io::{Read, Write};

// Direction of a chunk of data or gap.
#[derive(Serialize, Deserialize, Debug, PartialEq, Copy, Clone)]
pub enum Direction {
    Unknown,
    ToServer,
    ToClient,
}

/// A chunk of input data to parse.
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Data {
    direction: Direction,
    data: Vec<u8>,
}

/// Identifies a missing chunk of input data.
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct Gap {
    direction: Direction,
    gap: usize,
}

/// A list of all API calls we want to expose.
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub enum Call {
    /// Parse the input data.
    Parse(Data),
    /// Identify a gap.
    Gap(Gap),
}

/// Reads the expected format from a source.
pub struct Reader<R: Read> {
    inner: R,
}

impl<R: Read> Reader<R> {
    /// Creates a new reader.
    ///
    /// This will fail if the version in the format doesn't match the current
    /// version of this module.
    pub fn new(inner: R) -> Result<Self> {
        let mut reader = Reader { inner };
        let expected_version = crate::version();
        let actual_version: Version = rmp_serde::from_read(&mut reader.inner)?;
        if expected_version != actual_version {
            return Err(Error::new(ErrorKind::VersionMismatch((
                expected_version,
                actual_version,
            ))));
        }
        Ok(reader)
    }
}

impl<R: Read> std::iter::Iterator for Reader<R> {
    type Item = Call;

    fn next(&mut self) -> Option<Self::Item> {
        rmp_serde::from_read(&mut self.inner).ok()
    }
}

/// Writes serialized API calls to a sink.
pub struct Writer<W: Write> {
    inner: W,
}

impl<W: Write> Writer<W> {
    /// Creates a writer.
    pub fn new(inner: W) -> Result<Self> {
        let mut writer = Writer { inner };
        writer.version()?;
        Ok(writer)
    }

    /// Writes the format version number.
    fn version(&mut self) -> Result<()> {
        let bytes = rmp_serde::to_vec(&crate::version())?;
        self.inner.write_all(&bytes)?;
        Ok(())
    }

    /// Writes the parse API call.
    pub fn parse(&mut self, direction: Direction, data: &[u8]) -> Result<()> {
        let call = Call::Parse(Data {
            direction,
            data: data.to_vec(),
        });
        let bytes = rmp_serde::to_vec(&call)?;
        self.inner.write_all(&bytes)?;
        Ok(())
    }

    /// Writes the gap API call.
    pub fn gap(&mut self, direction: Direction, gap: usize) -> Result<()> {
        let call = Call::Gap(Gap { direction, gap });
        let bytes = rmp_serde::to_vec(&call)?;
        self.inner.write_all(&bytes)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_read_write() {
        let data = b"GET /index.php HTTP/1.1\r\n\r\n";
        let gap = 10;

        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer).expect("failed to create writer");
        writer.parse(Direction::ToServer, data).unwrap();
        writer.gap(Direction::ToServer, gap).unwrap();

        let buffer = std::io::Cursor::new(buffer);
        let reader = Reader::new(buffer).expect("failed to create reader");
        let result: Vec<Call> = reader.collect();
        let expected: Vec<Call> = vec![
            Call::Parse(Data {
                direction: Direction::ToServer,
                data: data.to_vec(),
            }),
            Call::Gap(Gap {
                direction: Direction::ToServer,
                gap,
            }),
        ];
        assert_eq!(expected, result);
    }

    #[should_panic(expected = "VersionMismatch")]
    #[test]
    fn test_version_mismatch() {
        // Test a version number that is off by one
        let wrong_version = crate::version() + 1;
        let bytes = rmp_serde::to_vec(&wrong_version).unwrap();
        let buffer = std::io::Cursor::new(bytes);
        let _ = Reader::new(buffer).unwrap();
    }

    #[test]
    fn test_corrupt_bytes() {
        let data = b"GET /index.php HTTP/1.1\r\n\r\n";
        let gap = 10;

        let mut buffer = Vec::new();
        let mut writer = Writer::new(&mut buffer).expect("failed to create writer");
        writer.parse(Direction::ToServer, data).unwrap();
        writer.gap(Direction::ToServer, gap).unwrap();

        // Process everything but the last byte.
        let buffer = std::io::Cursor::new(&buffer[..buffer.len() - 1]);
        let reader = Reader::new(buffer).expect("failed to create reader");
        let calls: Vec<Call> = reader.collect();

        // Errors are ignored and the iterator will end prematurely
        assert_eq!(calls.len(), 1);
    }
}