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
use crate::name::Name;
use async_trait::async_trait;
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

/// A result type specialised for lookup errors.
pub type LookupResult<T> = Result<T, LookupError>;

/// Errors that may occur when doing lookups.
#[derive(Debug)]
pub enum LookupError {
    /// The lookup timed out.
    Timeout,
    /// No records were found (NXDOMAIN).
    NoRecords,
    /// Any other error (I/O, encoding, protocol etc.) that causes a DNS lookup
    /// to fail, with source attached. The error cause is made available in the
    /// trace.
    Dns(Option<Box<dyn Error + Send + Sync>>),
}

impl Error for LookupError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Timeout | Self::NoRecords => None,
            Self::Dns(e) => e.as_ref().map(|e| e.as_ref() as _),
        }
    }
}

impl Display for LookupError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Timeout => write!(f, "lookup timed out"),
            Self::NoRecords => write!(f, "no records found"),
            Self::Dns(source) => match source {
                None => write!(f, "lookup returned error"),
                Some(error) => write!(f, "lookup returned error with cause: {}", error),
            },
        }
    }
}

/// A trait for entities that perform DNS resolution.
///
/// This trait uses the [`Name`] type in arguments and return values. See the
/// documentation of this type for a discussion of its design and use.
///
/// [`Name`]: struct.Name.html
#[async_trait]
pub trait Lookup {
    /// Looks up the IPv4 addresses for the given name.
    ///
    /// # Errors
    ///
    /// If the lookup encounters an error, a `LookupError` variant is returned.
    async fn lookup_a(&self, name: &Name) -> LookupResult<Vec<Ipv4Addr>>;

    /// Looks up the IPv6 addresses for the given name.
    ///
    /// # Errors
    ///
    /// If the lookup encounters an error, a `LookupError` variant is returned.
    async fn lookup_aaaa(&self, name: &Name) -> LookupResult<Vec<Ipv6Addr>>;

    /// Looks up the mail exchanger names for the given name.
    ///
    /// Implementers may want to order the returned vector by MX preference.
    ///
    /// # Errors
    ///
    /// If the lookup encounters an error, a `LookupError` variant is returned.
    async fn lookup_mx(&self, name: &Name) -> LookupResult<Vec<Name>>;

    /// Looks up the text records for the given name.
    ///
    /// Implementers should make sure that invalid UTF-8 does not cause the
    /// lookup to fail (eg, using a lossy transformation). A record consisting
    /// of multiple elements should be returned as one string, with elements
    /// joined without a separator.
    ///
    /// # Errors
    ///
    /// If the lookup encounters an error, a `LookupError` variant is returned.
    async fn lookup_txt(&self, name: &Name) -> LookupResult<Vec<String>>;

    /// Looks up the names for the given address (reverse lookup).
    ///
    /// # Errors
    ///
    /// If the lookup encounters an error, a `LookupError` variant is returned.
    async fn lookup_ptr(&self, ip: IpAddr) -> LookupResult<Vec<Name>>;
}

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

    struct MockLookup;

    #[async_trait]
    impl Lookup for MockLookup {
        async fn lookup_a(&self, _name: &Name) -> LookupResult<Vec<Ipv4Addr>> {
            unimplemented!();
        }

        async fn lookup_aaaa(&self, _name: &Name) -> LookupResult<Vec<Ipv6Addr>> {
            unimplemented!();
        }

        async fn lookup_mx(&self, _name: &Name) -> LookupResult<Vec<Name>> {
            unimplemented!();
        }

        async fn lookup_txt(&self, name: &Name) -> LookupResult<Vec<String>> {
            Ok(vec![name.to_string()])
        }

        async fn lookup_ptr(&self, _ip: IpAddr) -> LookupResult<Vec<Name>> {
            unimplemented!();
        }
    }

    #[tokio::test]
    async fn lookup_call_ok() {
        let resolver = MockLookup;

        let v = resolver
            .lookup_txt(&Name::new("gluet.ch").unwrap())
            .await
            .unwrap();
        assert_eq!(v, vec![String::from("gluet.ch")]);
    }
}