mini_c_ares/
caa.rs

1use std::ffi::CStr;
2use std::fmt;
3use std::marker::PhantomData;
4use std::os::raw::{c_char, c_int, c_uchar, c_void};
5use std::ptr;
6use std::slice;
7
8use itertools::Itertools;
9
10use crate::error::{Error, Result};
11use crate::panic;
12
13/// The result of a successful CAA lookup.
14#[derive(Debug)]
15pub struct CAAResults {
16    caa_reply: *mut c_ares_sys::ares_caa_reply,
17    phantom: PhantomData<c_ares_sys::ares_caa_reply>,
18}
19
20/// The contents of a single CAA record.
21#[derive(Clone, Copy)]
22pub struct CAAResult<'a> {
23    // A single result - reference into a `CAAResults`.
24    caa_reply: &'a c_ares_sys::ares_caa_reply,
25}
26
27impl CAAResults {
28    /// Obtain a `CAAResults` from the response to a CAA lookup.
29    pub fn parse_from(data: &[u8]) -> Result<CAAResults> {
30        let mut caa_reply: *mut c_ares_sys::ares_caa_reply = ptr::null_mut();
31        let parse_status = unsafe {
32            c_ares_sys::ares_parse_caa_reply(data.as_ptr(), data.len() as c_int, &mut caa_reply)
33        };
34        if parse_status == c_ares_sys::ARES_SUCCESS {
35            let caa_result = CAAResults::new(caa_reply);
36            Ok(caa_result)
37        } else {
38            Err(Error::from(parse_status))
39        }
40    }
41
42    fn new(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self {
43        CAAResults {
44            caa_reply,
45            phantom: PhantomData,
46        }
47    }
48
49    /// Returns an iterator over the `CAAResult` values in this `CAAResults`.
50    pub fn iter(&self) -> CAAResultsIter {
51        CAAResultsIter {
52            next: unsafe { self.caa_reply.as_ref() },
53        }
54    }
55}
56
57impl fmt::Display for CAAResults {
58    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
59        let results = self.iter().format("}, {");
60        write!(fmt, "[{{{results}}}]")
61    }
62}
63
64/// Iterator of `CAAResult`s.
65#[derive(Clone, Copy)]
66pub struct CAAResultsIter<'a> {
67    next: Option<&'a c_ares_sys::ares_caa_reply>,
68}
69
70impl<'a> Iterator for CAAResultsIter<'a> {
71    type Item = CAAResult<'a>;
72    fn next(&mut self) -> Option<Self::Item> {
73        let opt_reply = self.next;
74        self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
75        opt_reply.map(|reply| CAAResult { caa_reply: reply })
76    }
77}
78
79impl<'a> IntoIterator for &'a CAAResults {
80    type Item = CAAResult<'a>;
81    type IntoIter = CAAResultsIter<'a>;
82
83    fn into_iter(self) -> Self::IntoIter {
84        self.iter()
85    }
86}
87
88impl Drop for CAAResults {
89    fn drop(&mut self) {
90        unsafe { c_ares_sys::ares_free_data(self.caa_reply as *mut c_void) }
91    }
92}
93
94unsafe impl Send for CAAResults {}
95unsafe impl Sync for CAAResults {}
96unsafe impl<'a> Send for CAAResult<'a> {}
97unsafe impl<'a> Sync for CAAResult<'a> {}
98unsafe impl<'a> Send for CAAResultsIter<'a> {}
99unsafe impl<'a> Sync for CAAResultsIter<'a> {}
100
101impl<'a> CAAResult<'a> {
102    /// Is the 'critical' flag set in this `CAAResult`?
103    pub fn critical(self) -> bool {
104        self.caa_reply.critical != 0
105    }
106
107    /// The property represented by this `CAAResult`.
108    ///
109    /// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
110    /// library does not guarantee this - so we leave it to users to decide whether they prefer a
111    /// fallible conversion, a lossy conversion, or something else altogether.
112    pub fn property(self) -> &'a CStr {
113        unsafe { CStr::from_ptr(self.caa_reply.property as *const c_char) }
114    }
115
116    /// The value represented by this `CAAResult`.
117    ///
118    /// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
119    /// library does not guarantee this - so we leave it to users to decide whether they prefer a
120    /// fallible conversion, a lossy conversion, or something else altogether.
121    pub fn value(self) -> &'a CStr {
122        unsafe { CStr::from_ptr(self.caa_reply.value as *const c_char) }
123    }
124}
125
126impl<'a> fmt::Display for CAAResult<'a> {
127    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
128        write!(fmt, "Critical: {}, ", self.critical())?;
129        write!(
130            fmt,
131            "Property: {}, ",
132            self.property().to_str().unwrap_or("<not utf8>")
133        )?;
134        write!(
135            fmt,
136            "Value: {}",
137            self.value().to_str().unwrap_or("<not utf8>")
138        )
139    }
140}
141
142pub(crate) unsafe extern "C" fn query_caa_callback<F>(
143    arg: *mut c_void,
144    status: c_int,
145    _timeouts: c_int,
146    abuf: *mut c_uchar,
147    alen: c_int,
148) where
149    F: FnOnce(Result<CAAResults>) + Send + 'static,
150{
151    ares_callback!(arg as *mut F, status, abuf, alen, CAAResults::parse_from);
152}