c_ares/
uri.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::dns_string_as_str;
11
12/// The result of a successful URI lookup.
13#[derive(Debug)]
14pub struct URIResults {
15    uri_reply: *mut c_ares_sys::ares_uri_reply,
16}
17
18/// The contents of a single URI record.
19#[derive(Clone, Copy)]
20pub struct URIResult<'a> {
21    // A single result - reference into a `URIResults`.
22    uri_reply: &'a c_ares_sys::ares_uri_reply,
23}
24
25impl URIResults {
26    /// Obtain a `URIResults` from the response to a URI lookup.
27    pub fn parse_from(data: &[u8]) -> Result<URIResults> {
28        let mut uri_reply: *mut c_ares_sys::ares_uri_reply = ptr::null_mut();
29        let parse_status = unsafe {
30            c_ares_sys::ares_parse_uri_reply(data.as_ptr(), data.len() as c_int, &mut uri_reply)
31        };
32        if parse_status == c_ares_sys::ares_status_t::ARES_SUCCESS as i32 {
33            let uri_result = URIResults::new(uri_reply);
34            Ok(uri_result)
35        } else {
36            Err(Error::from(parse_status))
37        }
38    }
39
40    fn new(uri_reply: *mut c_ares_sys::ares_uri_reply) -> Self {
41        URIResults { uri_reply }
42    }
43
44    /// Returns an iterator over the `URIResult` values in this `URIResults`.
45    pub fn iter(&self) -> URIResultsIter<'_> {
46        URIResultsIter {
47            next: unsafe { self.uri_reply.as_ref() },
48        }
49    }
50}
51
52impl fmt::Display for URIResults {
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 `URIResult`s.
60#[derive(Clone, Copy)]
61pub struct URIResultsIter<'a> {
62    next: Option<&'a c_ares_sys::ares_uri_reply>,
63}
64
65impl<'a> Iterator for URIResultsIter<'a> {
66    type Item = URIResult<'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| URIResult { uri_reply: reply })
71    }
72}
73
74impl<'a> IntoIterator for &'a URIResults {
75    type Item = URIResult<'a>;
76    type IntoIter = URIResultsIter<'a>;
77
78    fn into_iter(self) -> Self::IntoIter {
79        self.iter()
80    }
81}
82
83impl Drop for URIResults {
84    fn drop(&mut self) {
85        unsafe { c_ares_sys::ares_free_data(self.uri_reply.cast()) }
86    }
87}
88
89unsafe impl Send for URIResults {}
90unsafe impl Sync for URIResults {}
91unsafe impl Send for URIResult<'_> {}
92unsafe impl Sync for URIResult<'_> {}
93unsafe impl Send for URIResultsIter<'_> {}
94unsafe impl Sync for URIResultsIter<'_> {}
95
96impl<'a> URIResult<'a> {
97    /// Returns the weight in this `URIResult`.
98    pub fn weight(self) -> u16 {
99        self.uri_reply.weight
100    }
101
102    /// Returns the priority in this `URIResult`.
103    pub fn priority(self) -> u16 {
104        self.uri_reply.priority
105    }
106
107    /// Returns the uri in this `URIResult`.
108    pub fn uri(self) -> &'a str {
109        unsafe { dns_string_as_str(self.uri_reply.uri) }
110    }
111
112    /// Returns the time-to-live in this `URIResult`.
113    pub fn ttl(self) -> i32 {
114        #[allow(clippy::unnecessary_cast)]
115        let ttl = self.uri_reply.ttl as i32;
116        ttl
117    }
118}
119
120impl fmt::Display for URIResult<'_> {
121    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
122        write!(fmt, "URI: {}, ", self.uri())?;
123        write!(fmt, "Priority: {}, ", self.priority())?;
124        write!(fmt, "Weight: {}, ", self.weight())?;
125        write!(fmt, "TTL: {}", self.ttl())
126    }
127}
128
129pub(crate) unsafe extern "C" fn query_uri_callback<F>(
130    arg: *mut c_void,
131    status: c_int,
132    _timeouts: c_int,
133    abuf: *mut c_uchar,
134    alen: c_int,
135) where
136    F: FnOnce(Result<URIResults>) + Send + 'static,
137{
138    ares_callback!(arg.cast::<F>(), status, abuf, alen, URIResults::parse_from);
139}