c_ares/
mx.rs

1use std::fmt;
2use std::marker::PhantomData;
3use std::os::raw::{c_int, c_uchar, c_void};
4use std::ptr;
5use std::slice;
6
7use itertools::Itertools;
8
9use crate::error::{Error, Result};
10use crate::panic;
11use crate::utils::hostname_as_str;
12
13/// The result of a successful MX lookup.
14#[derive(Debug)]
15pub struct MXResults {
16    mx_reply: *mut c_ares_sys::ares_mx_reply,
17    phantom: PhantomData<c_ares_sys::ares_mx_reply>,
18}
19
20/// The contents of a single MX record.
21#[derive(Clone, Copy)]
22pub struct MXResult<'a> {
23    mx_reply: &'a c_ares_sys::ares_mx_reply,
24}
25
26impl MXResults {
27    /// Obtain an `MXResults` from the response to an MX lookup.
28    pub fn parse_from(data: &[u8]) -> Result<MXResults> {
29        let mut mx_reply: *mut c_ares_sys::ares_mx_reply = ptr::null_mut();
30        let parse_status = unsafe {
31            c_ares_sys::ares_parse_mx_reply(data.as_ptr(), data.len() as c_int, &mut mx_reply)
32        };
33        if parse_status == c_ares_sys::ares_status_t::ARES_SUCCESS as i32 {
34            let result = MXResults::new(mx_reply);
35            Ok(result)
36        } else {
37            Err(Error::from(parse_status))
38        }
39    }
40
41    fn new(mx_reply: *mut c_ares_sys::ares_mx_reply) -> Self {
42        MXResults {
43            mx_reply,
44            phantom: PhantomData,
45        }
46    }
47
48    /// Returns an iterator over the `MXResult` values in this `MXResults`.
49    pub fn iter(&self) -> MXResultsIter {
50        MXResultsIter {
51            next: unsafe { self.mx_reply.as_ref() },
52        }
53    }
54}
55
56impl fmt::Display for MXResults {
57    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
58        let results = self.iter().format("}, {");
59        write!(fmt, "[{{{results}}}]")
60    }
61}
62
63/// Iterator of `MXResult`s.
64#[derive(Clone, Copy)]
65pub struct MXResultsIter<'a> {
66    next: Option<&'a c_ares_sys::ares_mx_reply>,
67}
68
69impl<'a> Iterator for MXResultsIter<'a> {
70    type Item = MXResult<'a>;
71    fn next(&mut self) -> Option<Self::Item> {
72        let opt_reply = self.next;
73        self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
74        opt_reply.map(|reply| MXResult { mx_reply: reply })
75    }
76}
77
78impl<'a> IntoIterator for &'a MXResults {
79    type Item = MXResult<'a>;
80    type IntoIter = MXResultsIter<'a>;
81
82    fn into_iter(self) -> Self::IntoIter {
83        self.iter()
84    }
85}
86
87impl Drop for MXResults {
88    fn drop(&mut self) {
89        unsafe { c_ares_sys::ares_free_data(self.mx_reply.cast()) }
90    }
91}
92
93unsafe impl Send for MXResults {}
94unsafe impl Sync for MXResults {}
95unsafe impl Send for MXResult<'_> {}
96unsafe impl Sync for MXResult<'_> {}
97unsafe impl Send for MXResultsIter<'_> {}
98unsafe impl Sync for MXResultsIter<'_> {}
99
100impl<'a> MXResult<'a> {
101    /// Returns the hostname in this `MXResult`.
102    pub fn host(self) -> &'a str {
103        unsafe { hostname_as_str(self.mx_reply.host) }
104    }
105
106    /// Returns the priority from this `MXResult`.
107    pub fn priority(self) -> u16 {
108        self.mx_reply.priority
109    }
110}
111
112impl fmt::Display for MXResult<'_> {
113    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
114        write!(fmt, "Hostname: {}, ", self.host())?;
115        write!(fmt, "Priority: {}", self.priority())
116    }
117}
118
119pub(crate) unsafe extern "C" fn query_mx_callback<F>(
120    arg: *mut c_void,
121    status: c_int,
122    _timeouts: c_int,
123    abuf: *mut c_uchar,
124    alen: c_int,
125) where
126    F: FnOnce(Result<MXResults>) + Send + 'static,
127{
128    ares_callback!(arg.cast::<F>(), status, abuf, alen, MXResults::parse_from);
129}