c_ares/
srv.rs

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