hopr_transport/
config.rs

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
use proc_macro_regex::regex;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use std::fmt::{Display, Formatter};
use std::net::ToSocketAddrs;
use std::num::ParseIntError;
use std::str::FromStr;
use std::time::Duration;
use validator::{Validate, ValidationError};

use hopr_transport_identity::Multiaddr;
pub use hopr_transport_network::{config::NetworkConfig, heartbeat::HeartbeatConfig};
pub use hopr_transport_protocol::config::ProtocolConfig;

use crate::errors::HoprTransportError;

pub struct HoprTransportConfig {
    pub transport: TransportConfig,
    pub network: hopr_transport_network::config::NetworkConfig,
    pub protocol: hopr_transport_protocol::config::ProtocolConfig,
    pub heartbeat: hopr_transport_network::heartbeat::HeartbeatConfig,
    pub session: SessionGlobalConfig,
}

regex!(is_dns_address_regex "^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)*[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$");

/// Check whether the string looks like a valid domain.
#[inline]
pub fn looks_like_domain(s: &str) -> bool {
    is_dns_address_regex(s)
}

/// Check whether the string is an actual reachable domain.
pub fn is_reachable_domain(host: &str) -> bool {
    host.to_socket_addrs().is_ok_and(|i| i.into_iter().next().is_some())
}

/// Enumeration of possible host types.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum HostType {
    /// IPv4 based host
    IPv4(String),
    /// DNS based host
    Domain(String),
}

impl Default for HostType {
    fn default() -> Self {
        HostType::IPv4("127.0.0.1".to_owned())
    }
}

/// Configuration of the listening host.
///
/// This is used for the P2P and REST API listeners.
///
/// Intentionally has no default because it depends on the use case.
#[derive(Debug, Serialize, Deserialize, Validate, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct HostConfig {
    /// Host on which to listen
    #[serde(default)] // must be defaulted to be mergeable from CLI args
    pub address: HostType,
    /// Listening TCP or UDP port (mandatory).
    #[validate(range(min = 1u16))]
    #[serde(default)] // must be defaulted to be mergeable from CLI args
    pub port: u16,
}

impl FromStr for HostConfig {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (ip_or_dns, str_port) = match s.split_once(':') {
            None => return Err("Invalid host, is not in the '<host>:<port>' format".into()),
            Some(split) => split,
        };

        let port = str_port.parse().map_err(|e: ParseIntError| e.to_string())?;

        if validator::ValidateIp::validate_ipv4(&ip_or_dns) {
            Ok(Self {
                address: HostType::IPv4(ip_or_dns.to_owned()),
                port,
            })
        } else if looks_like_domain(ip_or_dns) {
            Ok(Self {
                address: HostType::Domain(ip_or_dns.to_owned()),
                port,
            })
        } else {
            Err("Not a valid IPv4 or domain host".into())
        }
    }
}

impl Display for HostConfig {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}:{}", self.address, self.port)
    }
}

#[cfg(not(feature = "transport-quic"))]
fn default_multiaddr_transport(port: u16) -> String {
    format!("tcp/{port}")
}

#[cfg(feature = "transport-quic")]
fn default_multiaddr_transport(port: u16) -> String {
    format!("udp/{port}/quic-v1")
}

impl TryFrom<&HostConfig> for Multiaddr {
    type Error = HoprTransportError;

    fn try_from(value: &HostConfig) -> Result<Self, Self::Error> {
        match &value.address {
            HostType::IPv4(ip) => Multiaddr::from_str(
                format!("/ip4/{}/{}", ip.as_str(), default_multiaddr_transport(value.port)).as_str(),
            )
            .map_err(|e| HoprTransportError::Api(e.to_string())),
            HostType::Domain(domain) => Multiaddr::from_str(
                format!("/dns4/{}/{}", domain.as_str(), default_multiaddr_transport(value.port)).as_str(),
            )
            .map_err(|e| HoprTransportError::Api(e.to_string())),
        }
    }
}

fn validate_ipv4_address(s: &str) -> Result<(), ValidationError> {
    if validator::ValidateIp::validate_ipv4(&s) {
        let ipv4 = std::net::Ipv4Addr::from_str(s)
            .map_err(|_| ValidationError::new("Failed to deserialize the string into an ipv4 address"))?;

        if ipv4.is_private() || ipv4.is_multicast() || ipv4.is_unspecified() {
            return Err(ValidationError::new(
                "IPv4 cannot be private, multicast or unspecified (0.0.0.0)",
            ))?;
        }
        Ok(())
    } else {
        Err(ValidationError::new("Invalid IPv4 address provided"))
    }
}

fn validate_dns_address(s: &str) -> Result<(), ValidationError> {
    if looks_like_domain(s) || is_reachable_domain(s) {
        Ok(())
    } else {
        Err(ValidationError::new("Invalid DNS address provided"))
    }
}

/// Validates the HostConfig to be used as an external host
pub fn validate_external_host(host: &HostConfig) -> Result<(), ValidationError> {
    match &host.address {
        HostType::IPv4(ip4) => validate_ipv4_address(ip4),
        HostType::Domain(domain) => validate_dns_address(domain),
    }
}

/// Configuration of the physical transport mechanism.
#[derive(Debug, Default, Serialize, Deserialize, Validate, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct TransportConfig {
    /// When true, assume that the node is running in an isolated network and does
    /// not need any connection to nodes outside the subnet
    #[serde(default)]
    pub announce_local_addresses: bool,
    /// When true, assume a testnet with multiple nodes running on the same machine
    /// or in the same private IPv4 network
    #[serde(default)]
    pub prefer_local_addresses: bool,
}

const DEFAULT_SESSION_IDLE_TIMEOUT: Duration = Duration::from_secs(180);

const SESSION_IDLE_MIN_TIMEOUT: Duration = Duration::from_secs(60);

const DEFAULT_SESSION_ESTABLISH_RETRY_DELAY: Duration = Duration::from_secs(2);

const DEFAULT_SESSION_ESTABLISH_MAX_RETRIES: u32 = 3;

fn default_session_establish_max_retries() -> u32 {
    DEFAULT_SESSION_ESTABLISH_MAX_RETRIES
}

fn default_session_idle_timeout() -> std::time::Duration {
    DEFAULT_SESSION_IDLE_TIMEOUT
}

fn default_session_establish_retry_delay() -> std::time::Duration {
    DEFAULT_SESSION_ESTABLISH_RETRY_DELAY
}

fn validate_session_idle_timeout(value: &std::time::Duration) -> Result<(), ValidationError> {
    if SESSION_IDLE_MIN_TIMEOUT <= *value {
        Ok(())
    } else {
        Err(ValidationError::new("session idle timeout is too low"))
    }
}

/// Global configuration of Sessions.
#[serde_as]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Validate, smart_default::SmartDefault)]
#[serde(deny_unknown_fields)]
pub struct SessionGlobalConfig {
    /// Maximum time before an idle Session is closed.
    ///
    /// Defaults to 3 minutes.
    #[validate(custom(function = "validate_session_idle_timeout"))]
    #[default(DEFAULT_SESSION_IDLE_TIMEOUT)]
    #[serde(default = "default_session_idle_timeout")]
    #[serde_as(as = "serde_with::DurationSeconds<u64>")]
    pub idle_timeout: std::time::Duration,

    /// Maximum retries to attempt to establish the Session
    /// Set 0 for no retries.
    ///
    /// Defaults to 3, maximum is 20.
    #[validate(range(min = 0, max = 20))]
    #[default(DEFAULT_SESSION_ESTABLISH_MAX_RETRIES)]
    #[serde(default = "default_session_establish_max_retries")]
    pub establish_max_retries: u32,

    /// Delay between Session establishment retries.
    ///
    /// Default is 2 seconds.
    #[default(DEFAULT_SESSION_ESTABLISH_RETRY_DELAY)]
    #[serde(default = "default_session_establish_retry_delay")]
    #[serde_as(as = "serde_with::DurationSeconds<u64>")]
    pub establish_retry_timeout: std::time::Duration,
}

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

    #[test]
    fn test_valid_domains_for_looks_like_a_domain() {
        assert!(looks_like_domain("localhost"));
        assert!(looks_like_domain("hoprnet.org"));
        assert!(looks_like_domain("hub.hoprnet.org"));
    }

    #[test]
    fn test_valid_domains_for_does_not_look_like_a_domain() {
        assert!(!looks_like_domain(".org"));
        assert!(!looks_like_domain("-hoprnet-.org"));
    }

    #[test]
    fn test_valid_domains_should_be_reachable() {
        assert!(!is_reachable_domain("google.com"));
    }

    #[test]
    fn test_verify_valid_ip4_addresses() {
        assert!(validate_ipv4_address("1.1.1.1").is_ok());
        assert!(validate_ipv4_address("1.255.1.1").is_ok());
        assert!(validate_ipv4_address("187.1.1.255").is_ok());
        assert!(validate_ipv4_address("127.0.0.1").is_ok());
    }

    #[test]
    fn test_verify_invalid_ip4_addresses() {
        assert!(validate_ipv4_address("1.256.1.1").is_err());
        assert!(validate_ipv4_address("-1.1.1.255").is_err());
        assert!(validate_ipv4_address("127.0.0.256").is_err());
        assert!(validate_ipv4_address("1").is_err());
        assert!(validate_ipv4_address("1.1").is_err());
        assert!(validate_ipv4_address("1.1.1").is_err());
        assert!(validate_ipv4_address("1.1.1.1.1").is_err());
    }

    #[test]
    fn test_verify_valid_dns_addresses() {
        assert!(validate_dns_address("localhost").is_ok());
        assert!(validate_dns_address("google.com").is_ok());
        assert!(validate_dns_address("hub.hoprnet.org").is_ok());
    }

    #[test]
    fn test_verify_invalid_dns_addresses() {
        assert!(validate_dns_address("-hoprnet-.org").is_err());
    }
}