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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
extern crate serde;
#[macro_use] extern crate serde_derive;

extern crate num;
#[macro_use] extern crate num_derive;

pub mod stream_read;
pub mod stream_write;

use std::fmt;
use std::fs::File;
use std::io::BufReader;
use std::net::{TcpListener, TcpStream, UdpSocket, SocketAddrV4};
use std::error::Error;
use std::str::FromStr;

use bytes::BytesMut;

use crate::stream_write::*;
use crate::stream_read::*;


/// The stream settings are all the settings for all stream types
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StreamSettings {
    #[serde(default)]
    pub file: FileSettings,

    #[serde(default)]
    pub tcp_client: TcpClientSettings,

    #[serde(default)]
    pub tcp_server: TcpServerSettings,

    #[serde(default)]
    pub udp: UdpSettings,
}

impl StreamSettings {
    pub fn open_input(&self, input_option: &StreamOption) -> Result<ReadStream, String> {
        let result;

        match input_option {
            StreamOption::File => {
                result = self.file.open_read_stream();
            },

            StreamOption::TcpClient => {
                result = self.tcp_client.open_read_stream();
            },

            StreamOption::TcpServer => {
                result = self.tcp_server.open_read_stream();
            },

            StreamOption::Udp => {
                result = self.udp.open_read_stream();
            },
        }

        result
    }

    pub fn open_output(&self, output_option: &StreamOption) -> Result<WriteStream, String> {
        let result: Result<WriteStream, String>;

        match output_option {
            StreamOption::File => {
                result = self.file.open_write_stream();
            },

            StreamOption::TcpClient => {
                result = self.tcp_client.open_write_stream();
            },

            StreamOption::TcpServer => {
                result = self.tcp_server.open_write_stream();
            },

            StreamOption::Udp => {
                result = self.udp.open_write_stream();
            },
        }

        result
    }
}


/// The stream option identifies the desired stream type for reading or writing
#[derive(FromPrimitive, Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
pub enum StreamOption {
    /// The stream is a file
    File = 1,
    /// The stream is a TCP client with a given port
    TcpClient = 2,
    /// The stream is a TCP server with a given port
    TcpServer = 3,
    /// The stream is a UDP socket with a given port
    Udp = 4,
}

/* Input Streams */
/// The file settings are everything needed to open and read from a file as an input or output
/// stream
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileSettings {
    pub file_name: String,
}

impl Default for FileSettings {
    fn default() -> Self {
        FileSettings { file_name: "data.bin".to_string() }
    }
}

impl fmt::Display for FileSettings {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "file:{}", self.file_name)
    }
}

impl FromStr for FileSettings {
    type Err = StreamSettingsParseError;
    fn from_str(s: &str) -> Result<FileSettings, StreamSettingsParseError> {
        let prefix = "file:";
        if s.starts_with(prefix) {
            Ok(FileSettings { file_name: s[prefix.len()..].to_string() })
        } else {
            Err(StreamSettingsParseError(()))
        }
    }
}

impl FileSettings {
    pub fn open_read_stream(&self) -> Result<ReadStream, String> {
        let result = File::open(self.file_name.clone())
                       .map(|file| ReadStream::File(BufReader::new(file)))
                       .map_err(|err| format!("File open error for reading: {}", err));

        return result;
    }

    pub fn open_write_stream(&self) -> Result<WriteStream, String> {
        let result = File::create(self.file_name.clone())
                        .map(|outfile| WriteStream::File(outfile))
                        .map_err(|err| format!("File open error for writing: {}", err));

        return result;
    }
}

/// The tcp client settings are everything needed to open and read from a tcp socket as an input or output
/// stream as a tcp client
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TcpClientSettings {
    pub port: u16,
    pub ip: String,
}

impl Default for TcpClientSettings {
    fn default() -> Self {
        TcpClientSettings { port: 8000,
                            ip: "127.0.0.1".to_string()
        }
    }
}

impl fmt::Display for TcpClientSettings {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "tcp_client:{}:{}", self.ip, self.port)
    }
}

impl FromStr for TcpClientSettings {
    type Err = StreamSettingsParseError;
    fn from_str(s: &str) -> Result<TcpClientSettings, StreamSettingsParseError> {
        let prefix = "tcp_client:";
        if s.starts_with(prefix) {
            let mut parts = s[prefix.len()..].split(':');
            let addr = parts.next().ok_or(StreamSettingsParseError(()))?;
            let port_str = parts.next().ok_or(StreamSettingsParseError(()))?;
            let port = port_str.parse::<u16>().map_err(|_| StreamSettingsParseError(()))?;
            Ok(TcpClientSettings { ip: addr.to_string(), port: port })
        } else {
            Err(StreamSettingsParseError(()))
        }
    }
}

impl TcpClientSettings {
    pub fn open_read_stream(&self) -> Result<ReadStream, String> {
        let addr = SocketAddrV4::new(self.ip.parse().unwrap(),
                                     self.port);
        let result = TcpStream::connect(&addr)
                       .map(|sock| ReadStream::Tcp(sock))
                       .map_err(|err| format!("TCP Client Open Error: {}", err));

        return result;
    }

    pub fn open_write_stream(&self) -> Result<WriteStream, String> {
        let addr = SocketAddrV4::new(self.ip.parse().unwrap(),
                                     self.port);

        let result = TcpStream::connect(&addr)
                       .map(|sock| WriteStream::Tcp(sock))
                       .map_err(|err| format!("TCP Client Open Error: {}", err));

        return result;
    }
}

/// The tcp server settings are everything needed to open and read from a tcp socket as an input or output
/// stream as a tcp server
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TcpServerSettings {
    pub port: u16,
    pub ip: String,
}

impl Default for TcpServerSettings {
    fn default() -> Self {
        TcpServerSettings { port: 8000,
                            ip: "127.0.0.1".to_string()
        }
    }
}

impl fmt::Display for TcpServerSettings {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "tcp_server:{}:{}", self.ip, self.port)
    }
}

impl FromStr for TcpServerSettings {
    type Err = StreamSettingsParseError;
    fn from_str(s: &str) -> Result<TcpServerSettings, StreamSettingsParseError> {
        let prefix = "tcp_client:";
        if s.starts_with(prefix) {
            let mut parts = s[prefix.len()..].split(':');
            let addr = parts.next().ok_or(StreamSettingsParseError(()))?;
            let port_str = parts.next().ok_or(StreamSettingsParseError(()))?;
            let port = port_str.parse::<u16>().map_err(|_| StreamSettingsParseError(()))?;
            Ok(TcpServerSettings { ip: addr.to_string(), port: port })
        } else {
            Err(StreamSettingsParseError(()))
        }
    }
}

impl TcpServerSettings {
    pub fn open_read_stream(&self) -> Result<ReadStream, String> {
        let addr = SocketAddrV4::new(self.ip.parse().unwrap(), self.port);
        let listener = TcpListener::bind(&addr).unwrap();
        let (sock, _) = listener.accept().map_err(|err| format!("TCP Server Open Error: {}", err))?;
        return Ok(ReadStream::Tcp(sock));
    }

    pub fn open_write_stream(&self) -> Result<WriteStream, String> {
        let addr = SocketAddrV4::new(self.ip.parse().unwrap(), self.port);
        let listener = TcpListener::bind(&addr).unwrap();

        let result = listener.accept()
                             .map(|(sock, _)| WriteStream::Tcp(sock))
                             .map_err(|err| format!("TCP Server Open Error: {}", err));

        return result;
    }
}

/// The udp settings are everything needed to open a UDP socket and use it as an input or output
/// stream
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UdpSettings {
    pub port: u16,
    pub ip: String,
}

impl Default for UdpSettings {
    fn default() -> Self {
        UdpSettings { port: 8001,
                      ip: "127.0.0.1".to_string()
        }
    }
}

impl fmt::Display for UdpSettings {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "udp:{}:{}", self.ip, self.port)
    }
}

impl FromStr for UdpSettings {
    type Err = StreamSettingsParseError;
    fn from_str(s: &str) -> Result<UdpSettings, StreamSettingsParseError> {
        let prefix = "tcp_client:";
        if s.starts_with(prefix) {
            let mut parts = s[prefix.len()..].split(':');
            let addr = parts.next().ok_or(StreamSettingsParseError(()))?;
            let port_str = parts.next().ok_or(StreamSettingsParseError(()))?;
            let port = port_str.parse::<u16>().map_err(|_| StreamSettingsParseError(()))?;
            Ok(UdpSettings { ip: addr.to_string(), port: port })
        } else {
            Err(StreamSettingsParseError(()))
        }
    }
}


impl UdpSettings {
    pub fn open_read_stream(&self) -> Result<ReadStream, String> {
        let sock = UdpSocket::bind("0.0.0.0:0").map_err(|_err| "Couldn't bind to udp address/port")?;
        return Ok(ReadStream::Udp(sock));
    }

    pub fn open_write_stream(&self) -> Result<WriteStream, String> {
        let result;

        match self.ip.parse() {
            Ok(ip_addr) => {
                let addr = SocketAddrV4::new(ip_addr, self.port);

                result = UdpSocket::bind("0.0.0.0:0")
                         .map(|udp_sock| WriteStream::Udp((udp_sock, addr)))
                         .map_err(|err| format!("Could not open UDP socket for writing: {}", err));
            },

            Err(e) => {
                result = Err(format!("Could not parse ip ({}): {}", self.ip, e));
            },
        }

        return result;
    }
}


/* Input/Output Streams */
/// A read stream is a source of bytes.
///
/// This enum allows a caller to return a read stream without using
/// trait objects.
#[derive(Debug)]
pub enum ReadStream {
    File(BufReader<File>),
    Udp(UdpSocket),
    Tcp(TcpStream),
    Null,
}

impl Default for ReadStream {
    fn default() -> ReadStream {
        return ReadStream::Null;
    }
}

impl ReadStream {
    pub fn stream_read(&mut self,
                       bytes: &mut BytesMut,
                       num_bytes: usize) -> Result<usize, String> {

        let result: Result<usize, String>;

        match self {
            ReadStream::File(ref mut file) => {
                result = file.read_bytes(bytes, num_bytes);
            },

            ReadStream::Udp(udp_sock) => {
                // for UDP we just read a message
                result = udp_sock.read_bytes(bytes, num_bytes);
            },

            ReadStream::Tcp(tcp_stream) => {
                result = tcp_stream.read_bytes(bytes, num_bytes);
            },

            ReadStream::Null => {
                // TODO is this an error, or should it just always return no bytes?
                result = Err("Reading a Null Stream! This should not happen!".to_string());
            },
        }

        result
    }
}


/// A write stream, wrapped in an enum to allow multiple write streams to be
/// returned from functions while still allowing the calling function to 
/// defer the choice of stream.
///
/// This is the closed, static way to do this- the open, dynamic way would
/// be trait objects.
#[derive(Debug)]
pub enum WriteStream {
    File(File),
    Udp((UdpSocket, SocketAddrV4)),
    Tcp(TcpStream),
    Null,
}

impl WriteStream {
    pub fn stream_send(&mut self, packet: &Vec<u8>) -> Result<usize, String> {
        let result;

        match self {
            WriteStream::File(file) => {
                result = file.write_bytes(&packet);
            },

            WriteStream::Udp(udp_stream) => {
                result = udp_stream.write_bytes(&packet);
            },

            WriteStream::Tcp(tcp_stream) => {
                result = tcp_stream.write_bytes(&packet);
            },

            WriteStream::Null => {
                // TODO should this be a sink like /dev/null, and 'write' all bytes, or
                // should it write 0 bytes?
                result = Ok(0);
            },
        }

        return result;
    }
}

impl Default for WriteStream {
    fn default() -> WriteStream {
        return WriteStream::Null;
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamSettingsParseError(());

impl fmt::Display for StreamSettingsParseError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str(self.description())
    }
}

impl Error for StreamSettingsParseError {
    fn description(&self) -> &str {
        "error parsing stream settings"
    }
}