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
//! Types on domain name.

use std::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    num::ParseIntError,
    str::FromStr,
};

#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

use crate::port::Port;

/// A domain name.
#[derive(Clone, Debug)]
pub struct Domain(String);

impl Domain {
    const MAX_TOTAL_BYTE_LEN: usize = 0xff;
    const MAX_LABEL_BYTE_LEN: usize = 0x3f;

    /// Constructs a new domain name from its string.
    pub fn new(s: &str) -> Result<Self, ParseDomainError> {
        if s.as_bytes().len() > Self::MAX_TOTAL_BYTE_LEN {
            return Err(ParseDomainError::TooLong {
                max: Self::MAX_TOTAL_BYTE_LEN,
                len: s.as_bytes().len(),
            });
        }
        let s = if s.ends_with('.') {
            &s[..s.len() - 1]
        } else {
            s
        };
        let mut tld = true;
        for label in s.rsplit('.') {
            if label.is_empty() {
                return Err(ParseDomainError::NullLabel);
            }
            if label.as_bytes().len() > Self::MAX_LABEL_BYTE_LEN {
                return Err(ParseDomainError::LabelTooLong {
                    max: Self::MAX_LABEL_BYTE_LEN,
                    len: label.as_bytes().len(),
                });
            }
            if label.starts_with('-') || label.ends_with('-') {
                return Err(ParseDomainError::InvalidHyphen(label.to_string()));
            }

            fn valid_char(c: char) -> bool {
                if c >= '0' && c <= '9' {
                    return true;
                }
                if c >= 'A' && c <= 'Z' {
                    return true;
                }
                if c >= 'a' && c <= 'z' {
                    return true;
                }
                if c == '-' {
                    return true;
                }
                false
            }

            for c in label.chars() {
                if !valid_char(c) {
                    return Err(ParseDomainError::InvalidChar(c));
                }
            }

            fn is_num(s: &str) -> bool {
                for c in s.chars() {
                    if c < '0' || c > '9' {
                        return false;
                    }
                }
                true
            }

            if tld {
                if is_num(label) {
                    return Err(ParseDomainError::InvalidTld(label.to_string()));
                }
                tld = false;
            }
        }
        Ok(Self(s.to_string()))
    }

    /// Constructs a new domain name from its byte string.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ParseDomainError> {
        Ok(Self::new(&String::from_utf8_lossy(bytes))?)
    }

    /// Converts a domain name to a byte slice.
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }
}

#[test]
#[should_panic]
fn test_domain_too_long() {
    let s = String::from_utf8_lossy(&[b'a'; 256]);
    let _domain = Domain::new(&s).unwrap();
}

#[test]
fn test_domain_fqdn() {
    let _domain = Domain::new("example.org.").unwrap();
}

#[test]
#[should_panic]
fn test_domain_single_dot() {
    let _domain = Domain::new(".").unwrap();
}

#[test]
#[should_panic]
fn test_domain_null_label() {
    let _domain = Domain::new("www..example.org").unwrap();
}

#[test]
#[should_panic]
fn test_domain_label_too_long() {
    let _domain =
        Domain::new("abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwxyz234567.onion")
            .unwrap();
}

#[test]
#[should_panic]
fn test_domain_starts_with_hyphen() {
    let _domain = Domain::new("-www.example.org").unwrap();
}

#[test]
#[should_panic]
fn test_domain_ends_with_hyphen() {
    let _domain = Domain::new("www-.example.org").unwrap();
}

#[test]
#[should_panic]
fn test_domain_invalid_char() {
    let _domain = Domain::new("hello=world.example.org").unwrap();
}

#[test]
#[should_panic]
fn test_domain_invalid_tld() {
    let _domain = Domain::new("example.123").unwrap();
}

impl PartialEq for Domain {
    fn eq(&self, other: &Self) -> bool {
        self.0.to_ascii_lowercase() == other.0.to_ascii_lowercase()
    }
}

impl Eq for Domain {}

#[test]
fn test_domain_eq() {
    assert_eq!(
        Domain::new("example.org").unwrap(),
        Domain::new("EXAMPLE.ORG").unwrap()
    );
}

impl PartialOrd for Domain {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Domain {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0
            .to_ascii_lowercase()
            .cmp(&other.0.to_ascii_lowercase())
    }
}

#[test]
fn test_domain_ord() {
    assert!(Domain::new("example.net").unwrap() < Domain::new("example.org").unwrap());
    assert!(Domain::new("example.net").unwrap() < Domain::new("EXAMPLE.ORG").unwrap());
}

impl Hash for Domain {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.to_ascii_lowercase().hash(state);
    }
}

#[test]
fn test_domain_hash() {
    let upper = Domain::new("EXAMPLE.ORG").unwrap();
    let lower = Domain::new("example.org").unwrap();

    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    upper.hash(&mut hasher);
    let upper_hash = hasher.finish();

    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    lower.hash(&mut hasher);
    let lower_hash = hasher.finish();

    assert_eq!(upper_hash, lower_hash);
}

impl AsRef<str> for Domain {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

impl fmt::Display for Domain {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl FromStr for Domain {
    type Err = ParseDomainError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Ok(Self::new(s)?)
    }
}

/// An error which can be returned when parsing a domain name.
///
/// This error is used as the error type for `new`
/// and `FromStr` implementations for [`DomainName`].
///
/// [`DomainName`]: struct.DomainName.html
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ParseDomainError {
    /// The input was too long to construct a domain name.
    /// The maximum length allowed and the actual length of the input
    /// are returned as payloads of this variant.
    TooLong {
        /// The maximum length allowed.
        max: usize,
        /// The actual length of the input.
        len: usize,
    },

    /// A label of the input was null.
    NullLabel,

    /// A label of the input was too long to construct a domain name.
    /// The maximum length allowed and the actual length of the label
    /// are returned as payloads of this variant.
    LabelTooLong {
        /// The maximum length allowed.
        max: usize,
        /// The actual length of the label.
        len: usize,
    },

    /// A label starts or ends with a hyphen.
    /// The actual label is returned as a payload of this variant.
    InvalidHyphen(String),

    /// An invalid character was found.
    /// The actual character found is returned as a payload of this variant.
    InvalidChar(char),

    /// TLD was invalid.
    /// The actual TLD is returned as a payload of this variant.
    InvalidTld(String),
}

impl fmt::Display for ParseDomainError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooLong { max, len } => {
                write!(f, "max length is {}, but actual length is {}", max, len)
            }
            Self::NullLabel => "null label".fmt(f),
            Self::LabelTooLong { max, len } => {
                write!(f, "max length is {}, but actual length is {}", max, len)
            }
            Self::InvalidHyphen(label) => {
                write!(f, "a label starts or ends with a hyphen: {}", label)
            }
            Self::InvalidChar(ch) => {
                let code = u32::from(*ch);
                if ch.is_control() {
                    write!(f, "invalid character ({:#08x}) found", code)
                } else {
                    write!(f, "invalid character '{}' ({:#08x}) found", ch, code)
                }
            }
            Self::InvalidTld(label) => write!(f, "invalid TLD: {}", label),
        }
    }
}

impl std::error::Error for ParseDomainError {}

/// A socket address which uses a domain name,
/// i.e. a domain name with a port number.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct SocketDomain {
    domain: Domain,
    port: Port,
}

impl SocketDomain {
    /// Constructs a new socket address from a domain name with a port number.
    pub fn new(domain: Domain, port: Port) -> Self {
        Self { domain, port }
    }

    /// Returns the domain name of this socket address.
    pub fn domain(&self) -> &Domain {
        &self.domain
    }

    /// Returns the port number of this socket address.
    pub fn port(&self) -> Port {
        self.port
    }
}

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

impl FromStr for SocketDomain {
    type Err = ParseSocketDomainError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let colon = s.rfind(':');
        if colon.is_none() {
            return Err(Self::Err::PortNotFound);
        }
        let colon = colon.unwrap();

        let mut addr_part = &s[..colon];
        if addr_part.starts_with('[') && addr_part.ends_with(']') {
            addr_part = &addr_part[1..addr_part.len() - 1];
        }
        let port_part = &s[colon + 1..];

        let port = port_part.parse()?;
        let addr = addr_part.parse()?;
        Ok(Self::new(addr, port))
    }
}

#[cfg(feature = "serde")]
impl Serialize for SocketDomain {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for SocketDomain {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(de::Error::custom)
    }
}

/// An error which can be returned
/// when parsing a socket domain name.
///
/// This error is used as the error type for the `FromStr` implementation
/// for [`SocketDomain`].
///
/// [`SocketDomain`]: enum.SocketDomain.html
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum ParseSocketDomainError {
    /// No port number was found in the input.
    PortNotFound,

    /// An error was caught when parsing a port number.
    /// The actual error caught is returned
    /// as a payload of this variant.
    ParseIntError(ParseIntError),

    /// An error was caught when parsing a domain name.
    /// The actual error caught is returned
    /// as a payload of this variant.
    ParseDomainError(ParseDomainError),
}

impl fmt::Display for ParseSocketDomainError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PortNotFound => write!(f, "port not found"),
            Self::ParseIntError(err) => err.fmt(f),
            Self::ParseDomainError(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for ParseSocketDomainError {}

impl From<ParseIntError> for ParseSocketDomainError {
    fn from(err: ParseIntError) -> Self {
        Self::ParseIntError(err)
    }
}

impl From<ParseDomainError> for ParseSocketDomainError {
    fn from(err: ParseDomainError) -> Self {
        Self::ParseDomainError(err)
    }
}

#[test]
fn test_socket_domain_parse() {
    let test = "example.org:1234".parse::<SocketDomain>().unwrap();
    let expected = SocketDomain::new(Domain::new("example.org").unwrap(), 1234.into());
    assert_eq!(test, expected);
}