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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
use std::fmt::Display;
use std::result;
use std::str::FromStr;

use super::packet::{Error, Result};
use super::packetreader;
use super::packetwriter;


// Options. RFC-2347.
#[derive(Debug)]
pub struct Options {
    pub blksize:    Option<u16>,  // 8-65464 inclusive. RFC-2348.
    pub timeout:    Option<u8>,   // 1-255 seconds, inclusive. RFC-2349.
    pub tsize:      Option<u64>,  // 0 for query. RFC-2349.
    pub windowsize: Option<u16>,  // 1-65535. RFC-7440.
}


impl Options {

    pub fn new() -> Options {
        Options{
            blksize: None,
            timeout: None,
            tsize: None,
            windowsize: None,
        }
    }

    pub fn is_set(&self) -> bool {
        self.blksize.is_some() || self.timeout.is_some() ||
            self.tsize.is_some() || self.windowsize.is_some()
    }

    pub fn read<'a>
        (reader: &mut packetreader::PacketReader<'a>)
         -> Result<Self>
    {
        match reader.take_remaining() {
            Ok(buffer) => match Self::parse(buffer) {
                Ok(options) => Ok(options),
                Err(error) => Err(Error::InvalidOptions(error)),
            },
            Err(error) => Err(Error::ReadError(error)),
        }
    }

    pub fn write
        (self, writer: &mut packetwriter::PacketWriter)
        -> Result<()>
    {
        if let Some(blksize) = self.blksize {
            writer.put_string("blksize")?;
            writer.put_string(&blksize.to_string())?;
        };
        if let Some(timeout) = self.timeout {
            writer.put_string("timeout")?;
            writer.put_string(&timeout.to_string())?;
        };
        if let Some(tsize) = self.tsize {
            writer.put_string("tsize")?;
            writer.put_string(&tsize.to_string())?;
        };
        if let Some(windowsize) = self.windowsize {
            writer.put_string("windowsize")?;
            writer.put_string(&windowsize.to_string())?;
        };
        Ok(())
    }

    pub fn parse<'a>(buf: &'a [u8]) -> result::Result<Self, String> {
        let mut container = Self::new();
        let mut options = OptionStringIter::new(buf);
        loop {
            match options.next() {
                OptionString::Terminated(option) => {
                    let option = &String::from_utf8_lossy(option);
                    match options.next() {
                        OptionString::Terminated(value) => {
                            let value = &String::from_utf8_lossy(value);
                            try!(container.parse_option(option, value));
                        },
                        OptionString::Unterminated(value) => {
                            let value = &String::from_utf8_lossy(value);
                            return Err(format!(
                                "Option {} has unterminated value {}",
                                option, value));
                        },
                        OptionString::None => {
                            return Err(format!(
                                "Option {} has no corresponding value",
                                option));
                        },
                    };
                },
                OptionString::Unterminated(option) => {
                    let option = &String::from_utf8_lossy(option);
                    return Err(format!(
                        "Option {} is unterminated",
                        option));
                },
                OptionString::None => {
                    return Ok(container);
                },
            };
        };
    }

    fn parse_option
        (&mut self, option: &str, value: &str) -> result::Result<(), String>
    {
        match option.to_lowercase().as_ref() {
            "blksize" => self.blksize = Some(
                try!(Options::parse_blksize(value))),
            "timeout" => self.timeout = Some(
                try!(Options::parse_timeout(value))),
            "tsize" => self.tsize = Some(
                try!(Options::parse_tsize(value))),
            "windowsize" => self.windowsize = Some(
                try!(Options::parse_windowsize(value))),
            _ => {
                // Ignore, as advised in RFC-2347.
                // TODO: Record or log unrecognised options?
            },
        };
        Ok(())
    }

    fn parse_blksize(value: &str) -> result::Result<u16, String> {
        Options::parse_value("blksize", value)
    }

    fn parse_timeout(value: &str) -> result::Result<u8, String> {
        Options::parse_value("timeout", value)
    }

    fn parse_tsize(value: &str) -> result::Result<u64, String> {
        Options::parse_value("tsize", value)
    }

    fn parse_windowsize(value: &str) -> result::Result<u16, String> {
        Options::parse_value("windowsize", value)
    }

    fn parse_value<T: FromStr>
        (option: &str, value: &str) -> result::Result<T, String>
        where <T as FromStr>::Err: Display
    {
        match T::from_str(value) {
            Ok(value) => Ok(value),
            Err(error) => Err(format!(
                "Invalid {} value {:?}: {}", option, value, error))
        }
    }

}


#[cfg(test)]
mod test_options {

    use super::Options;

    #[test]
    fn test_creating_new_options() {
        let options = Options::new();
        assert_eq!(options.blksize, None);
        assert_eq!(options.timeout, None);
        assert_eq!(options.tsize, None);
        assert_eq!(options.windowsize, None);
    }

    #[test]
    fn test_parsing_blksize() {
        assert_eq!(Options::parse_blksize("123"), Ok(123u16));
        assert_eq!(
            Options::parse_blksize("foo"), Err(
                ("Invalid blksize value \"foo\": ".to_string() +
                 "invalid digit found in string")));
        assert_eq!(
            Options::parse_blksize("65536"), Err(
                ("Invalid blksize value \"65536\": ".to_string() +
                 "number too large to fit in target type")));
    }

    #[test]
    fn test_parsing_timeout() {
        assert_eq!(Options::parse_timeout("123"), Ok(123u8));
        assert_eq!(
            Options::parse_timeout("foo"), Err(
                ("Invalid timeout value \"foo\": ".to_string() +
                 "invalid digit found in string")));
        assert_eq!(
            Options::parse_timeout("256"), Err(
                ("Invalid timeout value \"256\": ".to_string() +
                 "number too large to fit in target type")));
    }

    #[test]
    fn test_parsing_tsize() {
        assert_eq!(Options::parse_tsize("123"), Ok(123u64));
        assert_eq!(
            Options::parse_tsize("foo"), Err(
                ("Invalid tsize value \"foo\": ".to_string() +
                 "invalid digit found in string")));
        assert_eq!(
            Options::parse_tsize("18446744073709551616"), Err(
                ("Invalid tsize value \"18446744073709551616\": ".to_string() +
                 "number too large to fit in target type")));
    }

    #[test]
    fn test_parsing_windowsize() {
        assert_eq!(Options::parse_windowsize("123"), Ok(123u16));
        assert_eq!(
            Options::parse_windowsize("foo"), Err(
                ("Invalid windowsize value \"foo\": ".to_string() +
                 "invalid digit found in string")));
        assert_eq!(
            Options::parse_windowsize("65536"), Err(
                ("Invalid windowsize value \"65536\": ".to_string() +
                 "number too large to fit in target type")));
    }

    #[test]
    fn test_parsing_options() {
        let buf = "blksize\067\0timeout\076\0tsize\098\0windowsize\0429\0".as_bytes();
        let options = Options::parse(buf).unwrap();
        assert_eq!(options.blksize, Some(67));
        assert_eq!(options.timeout, Some(76));
        assert_eq!(options.tsize, Some(98));
        assert_eq!(options.windowsize, Some(429));
    }

    #[test]
    fn test_parsing_empty_options() {
        let buf = "".as_bytes();
        let options = Options::parse(buf).unwrap();
        assert_eq!(options.blksize, None);
        assert_eq!(options.timeout, None);
        assert_eq!(options.tsize, None);
        assert_eq!(options.windowsize, None);
    }

    #[test]
    fn test_parsing_incorrectly_terminated_option_results_in_error() {
        let buf = "blksize".as_bytes();  // No trailing null byte.
        assert_eq!(
            Options::parse(buf).unwrap_err(),
            "Option blksize is unterminated");
    }

    #[test]
    fn test_parsing_incorrectly_terminated_value_results_in_error() {
        let buf = "blksize\067".as_bytes();  // No trailing null byte.
        assert_eq!(
            Options::parse(buf).unwrap_err(),
            "Option blksize has unterminated value 67");
    }

    #[test]
    fn test_parsing_option_without_value_results_in_error() {
        let buf = "foo\0".as_bytes();
        assert_eq!(
            Options::parse(buf).unwrap_err(),
            "Option foo has no corresponding value");
    }

    #[test]
    fn test_parsing_option_with_empty_value_results_in_error() {
        let buf = "blksize\0\0".as_bytes();
        assert_eq!(
            Options::parse(buf).unwrap_err(),
            "Invalid blksize value \"\": ".to_string() +
                "cannot parse integer from empty string");
    }

}


#[derive(Debug,PartialEq)]
enum OptionString<'a> {
    Terminated(&'a [u8]),
    Unterminated(&'a [u8]),
    None,
}


#[derive(Debug)]
struct OptionStringIter<'a> {
    buf: &'a [u8],
    pos: usize,
}


impl<'a> OptionStringIter<'a> {

    fn new(buf: &'a [u8]) -> OptionStringIter<'a> {
        OptionStringIter{buf: buf, pos: 0}
    }

    fn next(&mut self) -> OptionString<'a> {
        for index in self.pos..self.buf.len() {
            if self.buf[index] == 0u8 {
                let cstr = &self.buf[self.pos..index];
                self.pos = index + 1;
                return OptionString::Terminated(cstr);
            }
        }
        if self.buf.len() > self.pos {
            let cstr = &self.buf[self.pos..];
            self.pos = self.buf.len();
            return OptionString::Unterminated(cstr);
        }
        else {
            return OptionString::None;
        }
    }

}


#[cfg(test)]
mod test_option_string {

    use super::OptionString;
    use super::OptionStringIter;

    #[test]
    fn test_split() {
        let buf = "one\0two\0three".as_bytes();
        let mut iter = OptionStringIter::new(buf);
        assert_eq!(iter.next(), OptionString::Terminated("one".as_bytes()));
        assert_eq!(iter.next(), OptionString::Terminated("two".as_bytes()));
        assert_eq!(iter.next(), OptionString::Unterminated("three".as_bytes()));
        assert_eq!(iter.next(), OptionString::None);
    }

    #[test]
    fn test_split_unterminated() {
        let buf = "one".as_bytes();
        let mut iter = OptionStringIter::new(buf);
        assert_eq!(iter.next(), OptionString::Unterminated("one".as_bytes()));
        assert_eq!(iter.next(), OptionString::None);
    }

    #[test]
    fn test_split_with_empty() {
        let buf = "one\0\0three".as_bytes();
        let mut iter = OptionStringIter::new(buf);
        assert_eq!(iter.next(), OptionString::Terminated("one".as_bytes()));
        assert_eq!(iter.next(), OptionString::Terminated("".as_bytes()));
        assert_eq!(iter.next(), OptionString::Unterminated("three".as_bytes()));
        assert_eq!(iter.next(), OptionString::None);
    }

    #[test]
    fn test_split_empty() {
        let buf = "".as_bytes();
        let mut iter = OptionStringIter::new(buf);
        assert_eq!(iter.next(), OptionString::None);
    }

}