c_ares/
naptr.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::{dns_string_as_str, hostname_as_str};
12
13/// The result of a successful NAPTR lookup.
14#[derive(Debug)]
15pub struct NAPTRResults {
16    naptr_reply: *mut c_ares_sys::ares_naptr_reply,
17    phantom: PhantomData<c_ares_sys::ares_naptr_reply>,
18}
19
20/// The contents of a single NAPTR record.
21#[derive(Clone, Copy)]
22pub struct NAPTRResult<'a> {
23    naptr_reply: &'a c_ares_sys::ares_naptr_reply,
24}
25
26impl NAPTRResults {
27    /// Obtain a `NAPTRResults` from the response to a NAPTR lookup.
28    pub fn parse_from(data: &[u8]) -> Result<NAPTRResults> {
29        let mut naptr_reply: *mut c_ares_sys::ares_naptr_reply = ptr::null_mut();
30        let parse_status = unsafe {
31            c_ares_sys::ares_parse_naptr_reply(data.as_ptr(), data.len() as c_int, &mut naptr_reply)
32        };
33        if parse_status == c_ares_sys::ares_status_t::ARES_SUCCESS as i32 {
34            let naptr_result = NAPTRResults::new(naptr_reply);
35            Ok(naptr_result)
36        } else {
37            Err(Error::from(parse_status))
38        }
39    }
40
41    fn new(reply: *mut c_ares_sys::ares_naptr_reply) -> Self {
42        NAPTRResults {
43            naptr_reply: reply,
44            phantom: PhantomData,
45        }
46    }
47
48    /// Returns an iterator over the `NAPTRResult` values in this `NAPTRResults`.
49    pub fn iter(&self) -> NAPTRResultsIter {
50        NAPTRResultsIter {
51            next: unsafe { self.naptr_reply.as_ref() },
52        }
53    }
54}
55
56impl fmt::Display for NAPTRResults {
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 `NAPTRResult`s.
64#[derive(Clone, Copy)]
65pub struct NAPTRResultsIter<'a> {
66    next: Option<&'a c_ares_sys::ares_naptr_reply>,
67}
68
69impl<'a> Iterator for NAPTRResultsIter<'a> {
70    type Item = NAPTRResult<'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| NAPTRResult { naptr_reply: reply })
75    }
76}
77
78impl<'a> IntoIterator for &'a NAPTRResults {
79    type Item = NAPTRResult<'a>;
80    type IntoIter = NAPTRResultsIter<'a>;
81
82    fn into_iter(self) -> Self::IntoIter {
83        self.iter()
84    }
85}
86
87impl Drop for NAPTRResults {
88    fn drop(&mut self) {
89        unsafe { c_ares_sys::ares_free_data(self.naptr_reply.cast()) }
90    }
91}
92
93unsafe impl Send for NAPTRResults {}
94unsafe impl Sync for NAPTRResults {}
95unsafe impl Send for NAPTRResult<'_> {}
96unsafe impl Sync for NAPTRResult<'_> {}
97unsafe impl Send for NAPTRResultsIter<'_> {}
98unsafe impl Sync for NAPTRResultsIter<'_> {}
99
100impl<'a> NAPTRResult<'a> {
101    /// Returns the flags in this `NAPTRResult`.
102    pub fn flags(self) -> &'a str {
103        unsafe { dns_string_as_str(self.naptr_reply.flags.cast()) }
104    }
105
106    /// Returns the service name in this `NAPTRResult`.
107    pub fn service_name(self) -> &'a str {
108        unsafe { dns_string_as_str(self.naptr_reply.service.cast()) }
109    }
110
111    /// Returns the regular expression in this `NAPTRResult`.
112    pub fn reg_exp(self) -> &'a str {
113        unsafe { dns_string_as_str(self.naptr_reply.regexp.cast()) }
114    }
115
116    /// Returns the replacement pattern in this `NAPTRResult`.
117    pub fn replacement_pattern(self) -> &'a str {
118        unsafe { hostname_as_str(self.naptr_reply.replacement) }
119    }
120
121    /// Returns the order value in this `NAPTRResult`.
122    pub fn order(self) -> u16 {
123        self.naptr_reply.order
124    }
125
126    /// Returns the preference value in this `NAPTRResult`.
127    pub fn preference(self) -> u16 {
128        self.naptr_reply.preference
129    }
130}
131
132impl fmt::Display for NAPTRResult<'_> {
133    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
134        write!(fmt, "Flags: {}, ", self.flags())?;
135        write!(fmt, "Service name: {}, ", self.service_name())?;
136        write!(fmt, "Regular expression: {}, ", self.reg_exp())?;
137        write!(fmt, "Replacement pattern: {}, ", self.replacement_pattern())?;
138        write!(fmt, "Order: {}, ", self.order())?;
139        write!(fmt, "Preference: {}", self.preference())
140    }
141}
142
143pub(crate) unsafe extern "C" fn query_naptr_callback<F>(
144    arg: *mut c_void,
145    status: c_int,
146    _timeouts: c_int,
147    abuf: *mut c_uchar,
148    alen: c_int,
149) where
150    F: FnOnce(Result<NAPTRResults>) + Send + 'static,
151{
152    ares_callback!(
153        arg.cast::<F>(),
154        status,
155        abuf,
156        alen,
157        NAPTRResults::parse_from
158    );
159}