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
use std::fmt;
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::convert::TryFrom;
use std::net::SocketAddr;
use std::net::ToSocketAddrs;
use std::net::Ipv4Addr;
use std::net::IpAddr;

use log::debug;
use log::error;

//
// Structures
//
#[derive(Debug, PartialEq, Clone)]
pub struct ServerAddress {
    pub host: String,
    pub port: u16,
}

impl ServerAddress {

    pub fn new<S>(host: S,port: u16) -> Self where S: Into<String>{
        Self {
            host: host.into(),
            port
        }
    }
}

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

impl TryFrom<String> for ServerAddress {
    type Error = IoError;

    fn try_from(host_port: String) -> Result<Self, Self::Error> {
        let v: Vec<&str> = host_port.split(':').collect();

        if v.len() != 2 {
            return Err(IoError::new(
                ErrorKind::InvalidInput,
                format!("invalid host:port format {}", host_port).as_str(),
            ));
        }

        Ok(ServerAddress {
            host: v[0].to_string(),
            port: v[1]
                .parse::<u16>()
                .map_err(|err| IoError::new(ErrorKind::InvalidData, format!("{}", err)))?,
        })
    }
}

impl TryFrom<ServerAddress> for SocketAddr {
    type Error = IoError;

    fn try_from(endpoint: ServerAddress) -> Result<Self, Self::Error> {
        host_port_to_socket_addr(&endpoint.host, endpoint.port)
    }
}

// converts a host/port to SocketAddress
pub fn server_to_socket_addr(server_addr: &ServerAddress) -> Result<SocketAddr, IoError> {
    host_port_to_socket_addr(&server_addr.host, server_addr.port)
}

// converts a host/port to SocketAddress
pub fn host_port_to_socket_addr(host: &str, port: u16) -> Result<SocketAddr, IoError> {
    let addr_string = format!("{}:{}", host, port);
    string_to_socket_addr(&addr_string)
}

/// convert string to socket addr
pub fn string_to_socket_addr(addr_string: &str) -> Result<SocketAddr, IoError> {
    debug!("resolving host: {}",addr_string);
    match addr_string.to_socket_addrs() {
        Err(err) => {
            error!("error resolving addr: {} {}",addr_string,err);
            Err(err)
        },
        Ok(mut addrs_iter) => {
            match addrs_iter.next() {
                Some(addr) => {
                    debug!("resolved: {}",addr);
                    Ok(addr)
                },
                None => {
                    error!("error resolving addr: {}",addr_string);
                    Err(IoError::new(
                        ErrorKind::InvalidInput,
                        format!("host/port cannot be resolved {}", addr_string).as_str(),
                    ))
                }
            }
        }
    
    }


}

#[derive(Debug, PartialEq, Clone)]
pub enum EndPointEncryption {
    PLAINTEXT,
}

impl Default for EndPointEncryption {
    fn default() -> Self {
        EndPointEncryption::PLAINTEXT
    }
}

impl fmt::Display for EndPointEncryption {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Plain")
    }
}

#[derive(Debug, PartialEq, Clone)]
pub struct EndPoint {
    pub addr: SocketAddr,
    pub encryption: EndPointEncryption,
}

impl EndPoint {
    /// Build endpoint for local server
    pub fn local_end_point(port: u16) -> Self {
        Self {
            addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port),
            encryption: EndPointEncryption::default(),
        }
    }

    /// listen on 0.0.0.0
    pub fn all_end_point(port: u16) -> Self {
        Self {
            addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port),
            encryption: EndPointEncryption::default(),
        }
    }
}

impl From<SocketAddr> for EndPoint {
    fn from(addr: SocketAddr) -> Self {
        EndPoint {
            addr,
            encryption: EndPointEncryption::default(),
        }
    }
}

impl TryFrom<&str> for EndPoint {
    type Error = IoError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        string_to_socket_addr(value).map(|addr| EndPoint {
            addr,
            encryption: EndPointEncryption::PLAINTEXT,
        })
    }
}

impl fmt::Display for EndPoint {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.addr, self.encryption)
    }
}