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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
#![warn(missing_docs)]
//! `Mles utils` library is provided for Mles client and server implementations for easy handling of 
//! proper header and message structures.

/* This Source Code Form is subject to the terms of the Mozilla Public
*  License, v. 2.0. If a copy of the MPL was not distributed with this
*  file, You can obtain one at http://mozilla.org/MPL/2.0/. 
*
*  Copyright (C) 2017  Juhamatti Kuusisaari / Mles developers
* */

#[macro_use]
extern crate serde_derive;
extern crate serde_cbor;
extern crate serde_bytes;
extern crate byteorder;
extern crate siphasher;
extern crate rand;
extern crate tokio_core;
extern crate tokio_io;
extern crate futures;

mod server;
mod local_db;
mod frame;
mod peer;

use std::io::Cursor;
use byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use siphasher::sip::SipHasher;
use std::hash::{Hash, Hasher};
use std::net::TcpStream;
use std::io::Write;
use std::io::{Read, Error};

use std::net::{IpAddr, SocketAddr};

/// HDRL defines the size of the header including version, length and timestamp
pub const HDRL: usize = 8; 
/// CIDL defines the size of the connection id
pub const CIDL:  usize = 4; 
/// KEYL defines the size of the key
pub const KEYL: usize = 8; 
/// HDRKEYL defines the size of the header + key
pub const HDRKEYL: usize = HDRL + KEYL;

const KEEPALIVE: u64 = 5;

/// Msg structure
///
/// This structure defines the Mles interface value triplet (uid, channel, message). 
/// It is eventually serialized and deserialized by CBOR.
///
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Msg {
    uid:     String,
    channel: String,
    #[serde(with = "serde_bytes")]
    message: Vec<u8>,
}

impl Msg {
    /// Create a new Msg object with value triplet.
    ///
    /// # Example
    /// ```
    /// use mles_utils::Msg;
    ///
    /// let msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
    /// ```
    pub fn new(uid: String, channel: String, message: Vec<u8>) -> Msg {
        Msg {
            uid: uid,
            channel: channel,
            message: message
        }
    }

    /// Set uid for Msg object.
    ///
    /// # Example
    /// ```
    /// use mles_utils::Msg;
    ///
    /// let mut msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
    /// let msg = msg.set_uid("New uid".to_string());
    ///
    /// assert_eq!("New uid".to_string(), *msg.get_uid());
    /// ```
    pub fn set_uid(mut self, uid: String) -> Msg {
        self.uid = uid;
        self
    }

    /// Set channel for Msg object.
    ///
    /// # Example
    /// ```
    /// use mles_utils::Msg;
    ///
    /// let mut msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
    /// let msg = msg.set_channel("New channel".to_string());
    ///
    /// assert_eq!("New channel".to_string(), *msg.get_channel());
    /// ```
    pub fn set_channel(mut self, channel: String) -> Msg {
        self.channel = channel;
        self
    }

    /// Set message for Msg object.
    ///
    /// # Example
    /// ```
    /// use mles_utils::Msg;
    ///
    /// let mut msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
    /// let new_message: Vec<u8> = "New message".to_string().into_bytes();
    /// let msg = msg.set_message(new_message);
    /// ```
    pub fn set_message(mut self, message: Vec<u8>) -> Msg {
        self.message = message;
        self
    }

    /// Get uid for Msg object. See example for set uid.
    pub fn get_uid(&self) -> &String {
        &self.uid
    }

    /// Get channel for Msg object. See example for set channel.
    pub fn get_channel(&self) -> &String {
        &self.channel
    }

    /// Get message for Msg object.
    ///
    /// # Example
    /// ```
    /// use mles_utils::Msg;
    ///
    /// let mut msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
    /// let msg: &Vec<u8> = msg.get_message();
    /// ```
    pub fn get_message(&self) -> &Vec<u8> {
        &self.message
    }

    /// Get message len for Msg object.
    ///
    /// # Example
    /// ```
    /// use mles_utils::Msg;
    ///
    /// let mut msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
    /// let msg_len: usize = msg.get_message_len();
    /// ```
    pub fn get_message_len(&self) -> usize {
        self.message.len()
    }
}

/// Msg connection structure
///
/// This structure defines the Mles connection for simple synchronous connections. 
///
pub struct MsgConn {
    uid:     String,
    channel: String,
    key:     Option<u64>,
    stream:  Option<TcpStream>,
}

impl MsgConn {

    /// Create a new MsgConn object for a connection.
    ///
    /// # Example
    /// ```
    /// use mles_utils::MsgConn;
    ///
    /// let conn = MsgConn::new("My uid".to_string(), "My channel".to_string());
    /// ```
    pub fn new(uid: String, channel: String) -> MsgConn {
        MsgConn {
            uid: uid,
            channel: channel,
            key: None,
            stream: None
        }
    }

    /// Gets the defined uid.
    ///
    /// # Example
    /// ```
    /// use mles_utils::MsgConn;
    ///
    /// let conn = MsgConn::new("My uid".to_string(), "My channel".to_string());
    /// assert_eq!("My uid".to_string(), conn.get_uid());
    /// ```
    pub fn get_uid(&self) -> String {
        self.uid.clone()
    }

    /// Gets the defined channel.
    ///
    /// # Example
    /// ```
    /// use mles_utils::MsgConn;
    ///
    /// let conn = MsgConn::new("My uid".to_string(), "My channel".to_string());
    /// assert_eq!("My channel".to_string(), conn.get_channel());
    /// ```
    pub fn get_channel(&self) -> String {
        self.channel.clone()
    }

    /// Gets the defined key.
    ///
    /// # Example
    /// ```
    /// use mles_utils::MsgConn;
    ///
    /// //key is set only when connection is initiated..
    /// let conn = MsgConn::new("My uid".to_string(), "My channel".to_string());
    /// assert_eq!(true, conn.get_key().is_none());
    /// ```
    pub fn get_key(&self) -> Option<u64> {
        self.key
    }

    /// Connects to the defined address with a message.
    /// 
    pub fn connect_with_message(mut self, raddr: SocketAddr, msg: Vec<u8>) -> MsgConn {
        let msg = Msg::new(self.get_uid(), self.get_channel(), msg);
        match TcpStream::connect(raddr) {
            Ok(mut stream) => {
                let _val = stream.set_nodelay(true);

                if self.get_key().is_none() {
                    let mut keys = Vec::new();

                    let laddr = match stream.local_addr() {
                        Ok(laddr) => laddr,
                            Err(_) => {
                                let addr = "0.0.0.0:0";
                                addr.parse::<SocketAddr>().unwrap()
                            }
                    };
                    keys.push(addr2str(&laddr));
                    keys.push(self.get_uid());
                    keys.push(self.get_channel());
                    let key = do_hash(&keys);
                    self.key = Some(key);
                }
                let encoded_msg = message_encode(&msg);
                let key = self.get_key().unwrap();
                let keyv = write_key(key);
                let mut msgv = write_hdr(encoded_msg.len());
                msgv = write_cid_to_hdr(msgv);
                msgv.extend(keyv);
                msgv.extend(encoded_msg);
                stream.write(msgv.as_slice()).unwrap();
                self.stream = Some(stream);
                self
            },
            Err(_) => {
                println!("Could not connect to server {}", raddr);
                self
            },
        }
    }

    /// Connects to the defined address (without a message).
    /// 
    pub fn connect(self, raddr: SocketAddr) -> MsgConn {
        self.connect_with_message(raddr, Vec::new())
    }

    /// Send a message. Blocks until a message is sent.
    /// 
    /// # Errors
    /// If a message cannot be sent, stream is set to None.
    /// 
    pub fn send_message(mut self, msg: Vec<u8>) -> MsgConn {
        let encoded_msg = message_encode(&Msg::new(self.get_uid(), self.get_channel(), msg));
        let key = self.get_key().unwrap();
        let keyv = write_key(key);
        let mut msgv = write_hdr(encoded_msg.len());
        msgv = write_cid_to_hdr(msgv);
        msgv.extend(keyv);
        msgv.extend(encoded_msg);
        let mut stream = self.stream.unwrap();
        match stream.write(msgv.as_slice()) {
            Ok(0) => { 
                println!("Send zero");
                self.stream = None;
            },
            Ok(_) => self.stream = Some(stream),
            Err(err) => { 
                println!("Send error {}", err);
                self.stream = None;
            }
        }
        self
    }

    /// Reads a message with non-zero message content. Blocks until a message is received.
    /// 
    /// # Errors
    /// If message cannot be read, an empty message is returned.
    /// 
    pub fn read_message(mut self) -> (MsgConn, Vec<u8>) {
        let stream = self.stream.unwrap();
        loop {
            let tuple = read_n(&stream, HDRKEYL);
            let status = tuple.0;
            match status {
                Ok(0) => {
                    println!("Read failed: eof");
                    self.stream = None;
                    return (self, Vec::new());
                },
                _ => {}
            }
            let buf = tuple.1;
            if 0 == buf.len() {
                continue;
            }
            if read_hdr_type(buf.as_slice()) != 'M' as u32 {
                continue;
            }
            let hdr_len = read_hdr_len(buf.as_slice());
            if 0 == hdr_len {
                continue;
            }
            let tuple = read_n(&stream, hdr_len);
            let status = tuple.0;
            match status {
                Ok(0) => continue,
                _ =>  {}
            }
            let payload = tuple.1;
            if payload.len() != (hdr_len as usize) {
                continue;
            }
            let decoded_message = message_decode(payload.as_slice());
            if 0 == decoded_message.get_message_len() {
                continue;
            }
            self.stream = Some(stream);
            return (self, decoded_message.get_message().to_owned());
        }
    }

    /// Closes the connection.
    /// 
    pub fn close(mut self) -> MsgConn {
        if self.stream.is_some() {
            drop(self.stream.unwrap());
        }
        self.stream = None;
        self
    }
}

/// Encode Msg object to CBOR.
///
/// # Errors
/// If message cannot be encoded, an empty vector is returned.
///
/// # Example
/// ```
/// use mles_utils::{Msg, message_encode};
///
/// let msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
/// let encoded_msg: Vec<u8> = message_encode(&msg);
/// ```
#[inline]
pub fn message_encode(msg: &Msg) -> Vec<u8> {
    let encoded = serde_cbor::to_vec(msg);
    match encoded {
        Ok(encoded) => encoded,
        Err(err) => {
            println!("Error on encode: {}", err);
            Vec::new()
        }
    }
}

/// Decode CBOR byte string to Msg object.
///
/// # Errors
/// If message cannot be decoded, a Msg structure with empty items is returned.
///
/// # Example
/// ```
/// use mles_utils::{Msg, message_encode, message_decode};
///
/// let msg = Msg::new("My uid".to_string(), "My channel".to_string(), Vec::new());
/// let encoded_msg: Vec<u8> = message_encode(&msg);
/// let decoded_msg: Msg = message_decode(&encoded_msg);
/// ```
#[inline]
pub fn message_decode(slice: &[u8]) -> Msg {
    let value = serde_cbor::from_slice(slice);
    match value {
        Ok(value) => value,
        Err(err) => {
            println!("Error on decode: {}", err);
            Msg { uid: "".to_string(), channel: "".to_string(), message: Vec::new() } // return empty vec in case of error
        }
    }
}

/// Read received buffer header type.
///
/// # Errors
/// If input vector length is smaller than needed, zero is returned.
///
/// # Example
/// ```
/// use mles_utils::read_hdr_type;
///
/// let hdr: Vec<u8> = vec![77,1,2,3,0,0,0,0];
/// let hdr_type = read_hdr_type(&hdr);
/// assert_eq!('M' as u32, hdr_type);
/// ```
#[inline]
pub fn read_hdr_type(hdr: &[u8]) -> u32 { 
    if hdr.len() < HDRL {
        return 0;
    }
    let mut buf = Cursor::new(&hdr[..]);
    let num = buf.read_u32::<BigEndian>().unwrap();
    num >> 24
}

/// Read received buffer header len.
///
/// # Errors
/// If input vector length is smaller than needed, zero is returned.
///
/// # Example
/// ```
/// use mles_utils::read_hdr_len;
///
/// let hdr: Vec<u8> = vec![77,1,2,3,0,0,0,0];
/// let hdr_len = read_hdr_len(&hdr);
/// assert_eq!(515, hdr_len);
/// ```
#[inline]
pub fn read_hdr_len(hdr: &[u8]) -> usize { 
    if hdr.len() < HDRL {
        return 0;
    }
    let mut buf = Cursor::new(&hdr[..]);
    let num = buf.read_u32::<BigEndian>().unwrap();
    (num & 0xfff) as usize
}

/// Write a valid Mles header with specified length to network byte order.
///
/// # Example
/// ```
/// use mles_utils::{write_hdr, read_hdr_len};
///
/// let hdr = write_hdr(515);
/// let hdr_len = read_hdr_len(&hdr);
/// assert_eq!(515, hdr_len);
/// ```
#[inline]
pub fn write_hdr(len: usize) -> Vec<u8> {
    let hdr = (('M' as u32) << 24) | len as u32;
    let cid = 0 as u32;
    let mut msgv = vec![];
    let mut cidv = vec![];
    msgv.write_u32::<BigEndian>(hdr).unwrap();
    cidv.write_u32::<BigEndian>(cid).unwrap();
    msgv.extend(cidv);
    msgv
}

/// Write a valid Mles header with specified length to network byte order without cid.
///
/// # Example
/// ```
/// use mles_utils::{write_hdr_without_cid, read_hdr_len, HDRL, CIDL};
///
/// let hdr = write_hdr_without_cid(515);
/// assert_eq!(HDRL-CIDL, hdr.len());
/// ```
#[inline]
pub fn write_hdr_without_cid(len: usize) -> Vec<u8> {
    let hdr = (('M' as u32) << 24) | len as u32;
    let mut msgv = vec![];
    msgv.write_u32::<BigEndian>(hdr).unwrap();
    msgv
}

/// Return a random connection id.
///
/// # Example
/// ```
/// use mles_utils::select_cid;
///
/// let cid = select_cid();
/// assert!(cid >= 0x1 && cid <= 0x7fffffff);
/// ```
#[inline]
pub fn select_cid() -> u32 {
    let mut rnd: u32 = rand::random();
    rnd >>= 1; //skip values larger than 0x7fffffff
    if 0 == rnd { //skip zero
        rnd = 1;
    }
    rnd
}

/// Write a random connection id in network byte order.
///
/// # Example
/// ```
/// use mles_utils::{write_cid, select_cid, CIDL};
///
/// let cidv = write_cid(select_cid());
/// assert_eq!(CIDL, cidv.len());
/// ```
#[inline]
pub fn write_cid(cid: u32) -> Vec<u8> {
    let mut cidv = vec![];
    assert!(cid >= 0x1 && cid <= 0x7fffffff);
    cidv.write_u32::<BigEndian>(cid).unwrap();
    cidv
}

/// Write a random connection id in network byte order to the header.
///
/// # Example
/// ```
/// use mles_utils::{write_hdr, write_cid_to_hdr};
///
/// let mut hdr = write_hdr(515);
/// let hdr = write_cid_to_hdr(hdr);
/// ```
#[inline]
pub fn write_cid_to_hdr(mut hdrv: Vec<u8>) -> Vec<u8> {
    if hdrv.len() < HDRL {
        return vec![];
    }
    let tail = hdrv.split_off(HDRL);
    hdrv.truncate(HDRL - CIDL); //drop existing cid
    hdrv.extend(write_cid(select_cid())); //add new cid
    hdrv.extend(tail);
    hdrv
}


/// Write a valid key to network byte order.
///
/// # Example
/// ```
/// use mles_utils::{write_key, do_hash};
///
/// let hashstr = "A string".to_string();
/// let hashable = vec![hashstr];
/// let key = do_hash(&hashable); 
/// let keyhdr: Vec<u8> = write_key(key);
/// ```
#[inline]
pub fn write_key(val: u64) -> Vec<u8> {
    let key = val;
    let mut msgv = vec![];
    msgv.write_u64::<BigEndian>(key).unwrap();
    msgv
}

/// Write a valid Mles header with specified length and key to network byte order.
///
/// # Example
/// ```
/// use mles_utils::{write_hdr_with_key, read_hdr_len, read_key_from_hdr, do_hash};
///
/// let hashstr = "Yet another string".to_string();
/// let hashable = vec![hashstr];
/// let key = do_hash(&hashable); 
/// let hdr = write_hdr_with_key(515, key);
/// let hdr_len = read_hdr_len(&hdr);
/// assert_eq!(515, hdr_len);
/// let keyx = read_key_from_hdr(&hdr);
/// assert_eq!(key, keyx);
/// ```
#[inline]
pub fn write_hdr_with_key(len: usize, key: u64) -> Vec<u8> {
    let mut hdrv = write_hdr(len);
    hdrv.extend(write_key(key));
    hdrv
}

/// Read a key from buffer.
///
/// # Errors
/// If input vector length is smaller than needed, zero is returned.
///
/// # Example
/// ```
/// use mles_utils::{write_key, read_key, do_hash};
///
/// let hashstr = "Another string".to_string();
/// let hashable = vec![hashstr];
/// let key = do_hash(&hashable); 
/// let keyhdr: Vec<u8> = write_key(key);
/// let read_key = read_key(&keyhdr);
/// assert_eq!(key, read_key);
/// ```
#[inline]
pub fn read_key(keyv: &[u8]) -> u64 {
    if keyv.len() < KEYL {
        return 0;
    }
    let mut buf = Cursor::new(&keyv[..]);
    buf.read_u64::<BigEndian>().unwrap()
}

/// Read a key from header.
///
/// # Errors
/// If input vector length is smaller than needed, zero is returned.
///
/// # Example
/// ```
/// use mles_utils::{write_hdr, write_key, read_key_from_hdr, do_hash};
///
/// let hashstr = "Another string".to_string();
/// let hashable = vec![hashstr];
/// let key = do_hash(&hashable); 
/// let mut hdr: Vec<u8> = write_hdr(12);
/// let keyhdr: Vec<u8> = write_key(key);
/// hdr.extend(keyhdr);
/// let read_key = read_key_from_hdr(&hdr);
/// assert_eq!(key, read_key);
/// ```
#[inline]
pub fn read_key_from_hdr(keyv: &[u8]) -> u64 {
    if keyv.len() < HDRKEYL {
        return 0;
    }
    let mut buf = Cursor::new(&keyv[HDRL..]);
    buf.read_u64::<BigEndian>().unwrap()
}

/// Read a connection id from header.
///
/// # Errors
/// If input vector length is smaller than needed, zero is returned.
///
/// # Example
/// ```
/// use mles_utils::{write_hdr_with_key, write_cid_to_hdr, read_cid_from_hdr};
///
/// let mut hdr: Vec<u8> = write_hdr_with_key(12, 0x3f3f3); //cid set to zero
/// let read_cid = read_cid_from_hdr(&hdr);
/// assert_eq!(0, read_cid);
///
/// hdr = write_cid_to_hdr(hdr);
/// let read_cid = read_cid_from_hdr(&hdr);
/// assert!(read_cid >= 0x1 && read_cid <= 0x7fffffff);
///
/// ```
#[inline]
pub fn read_cid_from_hdr(hdrv: &[u8]) -> u32 {
    if hdrv.len() < HDRL {
        return 0;
    }
    let mut buf = Cursor::new(&hdrv[(HDRL-CIDL)..]);
    buf.read_u32::<BigEndian>().unwrap()
}


/// Do a valid hash for Mles over provided UTF-8 String list.
///
/// # Example
/// ```
/// use mles_utils::do_hash;
///
/// let hashstr1 = "A string".to_string();
/// let hashstr2 = "Another string".to_string();
/// let hashable = vec![hashstr1, hashstr2];
/// let key: u64 = do_hash(&hashable); 
/// ```
#[inline]
pub fn do_hash(t: &[String]) -> u64 {
    let mut s = SipHasher::new();
    for item in t {
        item.hash(&mut s);
    }
    s.finish()
}

/// Do a valid UTF-8 string from a `SocketAddr`.
///
/// For IPv4 the format is "x.x.x.x:y", where x is u8 and y is u16
/// For IPv6 the format is "[z:z:z:z:z:z:z:z]:y", where z is u16 in hexadecimal format and y is u16
///
/// # Example
/// ```
///
/// use std::net::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};
/// use mles_utils::addr2str;
///
/// let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
/// let addrstr = addr2str(&addr);
///
/// assert_eq!("127.0.0.1:8080", addrstr);
///
/// let addr = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0xff03, 0, 0, 0, 0, 0, 0, 1)), 8077);
/// let addrstr = addr2str(&addr);
///
/// assert_eq!("[ff03:0:0:0:0:0:0:1]:8077", addrstr);
/// ```
#[inline]
pub fn addr2str(addr: &SocketAddr) -> String {
    let ipaddr = addr.ip();
    match ipaddr {
        IpAddr::V4(v4) => {
            let v4oct = v4.octets();
            let v4str = format!("{}.{}.{}.{}:{}", 
                                v4oct[0], v4oct[1], v4oct[2], v4oct[3], 
                                addr.port());
            v4str
        }
        IpAddr::V6(v6) => {
            let v6seg = v6.segments();
            let v6str = format!("[{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}]:{}", 
                                v6seg[0], v6seg[1], v6seg[2], v6seg[3], 
                                v6seg[4], v6seg[5], v6seg[6], v6seg[7], 
                                addr.port());
            v6str
        }
    }
}

/// Check if an peer is defined
///
/// # Example
/// ```
/// use mles_utils::has_peer;
///
/// let sockaddr = None;
/// assert_eq!(false, has_peer(&sockaddr));
/// ```
#[inline]
pub fn has_peer(peer: &Option<SocketAddr>) -> bool {
    peer::has_peer(peer)
}

fn read_n<R>(reader: R, bytes_to_read: usize) -> (Result<usize, Error>, Vec<u8>)
where R: Read,
{
    let mut buf = vec![];
    let mut chunk = reader.take(bytes_to_read as u64);
    let status = chunk.read_to_end(&mut buf);
    (status, buf)
}

/// Run an Mles server
///
/// # Example
/// ```
/// use std::thread;
/// use std::net::{IpAddr, Ipv4Addr};
/// use std::net::{SocketAddr, ToSocketAddrs};
/// use mles_utils::server_run;
///
/// let uid = "User".to_string();
/// let channel = "Channel".to_string();
/// let message = "Hello World!".to_string();
/// let address = "127.0.0.1:8077".to_string();
/// let address = address.parse().unwrap();
/// let child = thread::spawn(move || server_run(address, None, "".to_string(), "".to_string(), 100, 0));
/// drop(child);
/// ```
#[inline]
pub fn server_run(address: SocketAddr, peer: Option<SocketAddr>, keyval: String, keyaddr: String,  hist_limit: usize, debug_flags: u64) {
    server::run(address, peer, keyval, keyaddr, hist_limit, debug_flags);
}

#[cfg(test)]
mod tests {
    use std::net::SocketAddr;
    use std::thread;
    use std::time::Duration;
    use super::*;

    #[test]
    fn test_encode_decode_msg() {
        let uid = "User".to_string();
        let channel = "Channel".to_string();
        let msg =  "a test msg".to_string().into_bytes();
        let orig_msg = Msg::new(uid, channel, msg);
        let encoded_msg = message_encode(&orig_msg);
        let decoded_msg = message_decode(&encoded_msg);
        assert_eq!(decoded_msg.uid, orig_msg.uid);
        assert_eq!(decoded_msg.channel, orig_msg.channel);
        assert_eq!(decoded_msg.message, orig_msg.message);
    }

    #[test]
    fn test_set_get_msg() {
        let uid =  "User".to_string();
        let channel =  "Channel".to_string();
        let msg =  "a test msg".to_string().into_bytes();
        let orig_msg = Msg::new("".to_string(), channel.to_string(), Vec::new());
        let orig_msg = orig_msg.set_uid(uid.clone());
        let orig_msg = orig_msg.set_channel(channel.clone());
        let orig_msg = orig_msg.set_message(msg.clone());
        assert_eq!(&uid, orig_msg.get_uid());
        assert_eq!(&channel, orig_msg.get_channel());
        assert_eq!(&msg, orig_msg.get_message());
    }

    #[test]
    fn test_hash() {
        let addr = "127.0.0.1:8077";
        let addr = addr.parse::<SocketAddr>().unwrap();
        let orig_key = do_hash(&vec![addr2str(&addr)]);
        let keyv = write_key(orig_key);
        let key = read_key(&keyv);
        assert_eq!(orig_key, key);
    }

    #[test]
    fn test_cid() {
        let orig_key = 0xffeffe;
        let mut hdrv = write_hdr_with_key(64, orig_key);
        let orig_len = hdrv.len();
        let key = read_key_from_hdr(&hdrv);
        assert_eq!(orig_key, key);
        let read_cid = read_cid_from_hdr(&hdrv);
        assert_eq!(0, read_cid);
        hdrv = write_cid_to_hdr(hdrv);
        let read_cid = read_cid_from_hdr(&hdrv);
        assert_ne!(0, read_cid);
        let key = read_key_from_hdr(&hdrv);
        assert_eq!(orig_key, key);
        let len = hdrv.len();
        assert_eq!(orig_len, len);
    }

    #[test]
    fn test_msgconn_send_read() {
        let sec = Duration::new(1,0);
        let addr = "127.0.0.1:8077";
        let addr = addr.parse::<SocketAddr>().unwrap();
        let raddr = addr.clone();
        let uid = "User".to_string();
        let channel = "Channel".to_string();
        let message = "Hello World!".to_string();
         
        //create server
        let child = thread::spawn(move || server_run(addr, None, "".to_string(), "".to_string(), 100, 0));
        thread::sleep(sec);

        //send hello world
        let mut conn = MsgConn::new(uid.clone(), channel.clone());
        conn = conn.connect_with_message(raddr, message.into_bytes());
        conn.close();

        //read hello world
        let mut conn = MsgConn::new(uid.clone(), channel.clone());
        conn = conn.connect(raddr);
        let (conn, msg) = conn.read_message();
        let msg = String::from_utf8_lossy(msg.as_slice());
        assert_eq!("Hello World!", msg);

        //close connection
        conn.close();

        //drop server
        drop(child);
    }

    #[test]
    fn test_msgconn_read_send() {
        let sec = Duration::new(1,0);
        let addr = "127.0.0.1:8076";
        let addr = addr.parse::<SocketAddr>().unwrap();
        let raddr = addr.clone();
        let uid = "User".to_string();
        let channel = "Channel".to_string();
        let message = "Hello World!".to_string();
         
        //create server
        let child = thread::spawn(move || server_run(addr, None, "".to_string(), "".to_string(), 100, 0));
        thread::sleep(sec);

        //read connect
        let mut conn = MsgConn::new(uid.clone(), channel.clone());
        conn = conn.connect(raddr);

        //send hello world
        let mut sconn = MsgConn::new(uid.clone(), channel.clone());
        sconn = sconn.connect_with_message(raddr, message.into_bytes());
        sconn.close();

        //read hello world
        let (conn, msg) = conn.read_message();
        let msg = String::from_utf8_lossy(msg.as_slice());
        assert_eq!("Hello World!", msg);

        //close connection
        conn.close();

        //drop server
        drop(child);
    }


}