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
use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{
    c_int,
    c_uchar,
    c_void,
};
use std::str;
use std::ptr;
use std::slice;

use c_ares_sys;
use itertools::Itertools;

use error::{
    Error,
    Result,
};

/// The result of a successful SRV lookup.
#[derive(Debug)]
pub struct SRVResults {
    srv_reply: *mut c_ares_sys::ares_srv_reply,
    phantom: PhantomData<c_ares_sys::ares_srv_reply>,
}

/// The contents of a single SRV record.
#[derive(Clone, Copy)]
pub struct SRVResult<'a> {
    // A single result - reference into an `SRVResults`.
    srv_reply: &'a c_ares_sys::ares_srv_reply,
}

impl SRVResults {
    /// Obtain an `SRVResults` from the response to an SRV lookup.
    pub fn parse_from(data: &[u8]) -> Result<SRVResults> {
        let mut srv_reply: *mut c_ares_sys::ares_srv_reply =
            ptr::null_mut();
        let parse_status = unsafe {
            c_ares_sys::ares_parse_srv_reply(
                data.as_ptr(),
                data.len() as c_int,
                &mut srv_reply)
        };
        if parse_status == c_ares_sys::ARES_SUCCESS {
            let srv_result = SRVResults::new(srv_reply);
            Ok(srv_result)
        } else {
            Err(Error::from(parse_status))
        }
    }

    fn new(srv_reply: *mut c_ares_sys::ares_srv_reply) -> SRVResults {
        SRVResults {
            srv_reply: srv_reply,
            phantom: PhantomData,
        }
    }

    /// Returns an iterator over the `SRVResult` values in this `SRVResults`.
    pub fn iter(&self) -> SRVResultsIter {
        SRVResultsIter {
            next: unsafe { self.srv_reply.as_ref() },
        }
    }
}

impl fmt::Display for SRVResults {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let results = self.iter().format("}, {");
        write!(fmt, "[{{{}}}]", results)?;
        Ok(())
    }
}

/// Iterator of `SRVResult`s.
#[derive(Clone, Copy)]
pub struct SRVResultsIter<'a> {
    next: Option<&'a c_ares_sys::ares_srv_reply>,
}

impl<'a> Iterator for SRVResultsIter<'a> {
    type Item = SRVResult<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        let opt_reply = self.next;
        self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
        opt_reply.map(|reply| {
            SRVResult {
                srv_reply: reply,
            }
        })
    }
}

impl<'a> IntoIterator for &'a SRVResults {
    type Item = SRVResult<'a>;
    type IntoIter = SRVResultsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl Drop for SRVResults {
    fn drop(&mut self) {
        unsafe {
            c_ares_sys::ares_free_data(self.srv_reply as *mut c_void);
        }
    }
}

unsafe impl Send for SRVResults { }
unsafe impl Sync for SRVResults { }
unsafe impl<'a> Send for SRVResult<'a> { }
unsafe impl<'a> Sync for SRVResult<'a> { }
unsafe impl<'a> Send for SRVResultsIter<'a> { }
unsafe impl<'a> Sync for SRVResultsIter<'a> { }

impl<'a> SRVResult<'a> {
    /// Returns the hostname in this `SRVResult`.
    pub fn host(&self) -> &str {
        unsafe {
            let c_str = CStr::from_ptr(self.srv_reply.host);
            str::from_utf8_unchecked(c_str.to_bytes())
        }
    }

    /// Returns the weight in this `SRVResult`.
    pub fn weight(&self) -> u16 {
        self.srv_reply.weight
    }

    /// Returns the priority in this `SRVResult`.
    pub fn priority(&self) -> u16 {
        self.srv_reply.priority
    }

    /// Returns the port in this `SRVResult`.
    pub fn port(&self) -> u16 {
        self.srv_reply.port
    }
}

impl<'a> fmt::Display for SRVResult<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Host: {}, ", self.host())?;
        write!(fmt, "Port: {}, ", self.port())?;
        write!(fmt, "Priority: {}, ", self.priority())?;
        write!(fmt, "Weight: {}", self.weight())?;
        Ok(())
    }
}

pub unsafe extern "C" fn query_srv_callback<F>(
    arg: *mut c_void,
    status: c_int,
    _timeouts: c_int,
    abuf: *mut c_uchar,
    alen: c_int)
    where F: FnOnce(Result<SRVResults>) + Send + 'static {
    let result = if status == c_ares_sys::ARES_SUCCESS {
        let data = slice::from_raw_parts(abuf, alen as usize);
        SRVResults::parse_from(data)
    } else {
        Err(Error::from(status))
    };
    let handler = Box::from_raw(arg as *mut F);
    handler(result);
}