c-ares 13.0.0

A Rust wrapper for the c-ares library, for asynchronous DNS requests.
Documentation
use core::ffi::c_int;
use std::{fmt, ptr, slice, str};

use itertools::Itertools;

use crate::error::{Error, Result};
use crate::record::QueryRecord;
use crate::types::QueryType;
use crate::utils::dns_string_as_str;

/// The result of a successful CAA lookup.
#[derive(Debug)]
pub struct CAAResults {
    caa_reply: *mut c_ares_sys::ares_caa_reply,
}

/// The contents of a single CAA record.
#[derive(Clone, Copy)]
pub struct CAAResult<'a> {
    // A single result - reference into a `CAAResults`.
    caa_reply: &'a c_ares_sys::ares_caa_reply,
}

impl CAAResults {
    /// Obtain a `CAAResults` from the response to a CAA lookup.
    pub fn parse_from(data: &[u8]) -> Result<CAAResults> {
        let mut caa_reply: *mut c_ares_sys::ares_caa_reply = ptr::null_mut();
        let parse_status = unsafe {
            c_ares_sys::ares_parse_caa_reply(data.as_ptr(), data.len() as c_int, &raw mut caa_reply)
        };
        if parse_status == c_ares_sys::ares_status_t::ARES_SUCCESS as i32 {
            let caa_result = CAAResults::new(caa_reply);
            Ok(caa_result)
        } else {
            Err(Error::from(parse_status))
        }
    }

    fn new(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self {
        CAAResults { caa_reply }
    }

    /// Returns an iterator over the `CAAResult` values in this `CAAResults`.
    pub fn iter(&self) -> CAAResultsIter<'_> {
        CAAResultsIter {
            next: unsafe { self.caa_reply.as_ref() },
        }
    }
}

impl fmt::Display for CAAResults {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let results = self.iter().format("}, {");
        write!(fmt, "[{{{results}}}]")
    }
}

/// Iterator of `CAAResult`s.
#[derive(Clone, Debug)]
pub struct CAAResultsIter<'a> {
    next: Option<&'a c_ares_sys::ares_caa_reply>,
}

impl<'a> Iterator for CAAResultsIter<'a> {
    type Item = CAAResult<'a>;
    fn next(&mut self) -> Option<Self::Item> {
        let opt_reply = self.next;
        self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
        opt_reply.map(|reply| CAAResult { caa_reply: reply })
    }
}

impl<'a> IntoIterator for &'a CAAResults {
    type Item = CAAResult<'a>;
    type IntoIter = CAAResultsIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl std::iter::FusedIterator for CAAResultsIter<'_> {}

impl Drop for CAAResults {
    fn drop(&mut self) {
        unsafe { c_ares_sys::ares_free_data(self.caa_reply.cast()) }
    }
}

unsafe impl Send for CAAResults {}
unsafe impl Sync for CAAResults {}
unsafe impl Send for CAAResult<'_> {}
unsafe impl Sync for CAAResult<'_> {}
unsafe impl Send for CAAResultsIter<'_> {}
unsafe impl Sync for CAAResultsIter<'_> {}

impl fmt::Debug for CAAResult<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CAAResult")
            .field("critical", &self.critical())
            .field("property", &self.property())
            .field("value", &self.value())
            .finish()
    }
}

impl<'a> CAAResult<'a> {
    /// Is the 'critical' flag set in this `CAAResult`?
    pub fn critical(self) -> bool {
        self.caa_reply.critical != 0
    }

    /// The property represented by this `CAAResult`.
    pub fn property(self) -> &'a str {
        unsafe { dns_string_as_str(self.caa_reply.property.cast()) }
    }

    /// The value represented by this `CAAResult`.
    pub fn value(self) -> &'a [u8] {
        unsafe { slice::from_raw_parts(self.caa_reply.value, self.caa_reply.length) }
    }
}

impl fmt::Display for CAAResult<'_> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Critical: {}, ", self.critical())?;
        write!(fmt, "Property: {}, ", self.property())?;
        let value = str::from_utf8(self.value()).unwrap_or("<binary>");
        write!(fmt, "Value: {value}")
    }
}

impl QueryRecord for CAAResults {
    const QUERY_TYPE: QueryType = QueryType::CAA;
    fn parse(data: &[u8]) -> Result<Self> {
        Self::parse_from(data)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_invalid_data() {
        let result = CAAResults::parse_from(&[]);
        assert!(result.is_err());
    }

    #[test]
    fn is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<CAAResult>();
        assert_send::<CAAResults>();
        assert_send::<CAAResultsIter>();
    }

    #[test]
    fn is_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<CAAResult>();
        assert_sync::<CAAResults>();
        assert_sync::<CAAResultsIter>();
    }

    // DNS CAA response: example.com -> 0 issue "letsencrypt.org", TTL 300
    const ONE_CAA_RECORD: &[u8] = &[
        0x00, 0x00, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x07, 0x65, 0x78,
        0x61, 0x6d, 0x70, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0x01, 0x01, 0x00, 0x01, 0xc0,
        0x0c, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x16, 0x00, 0x05, 0x69, 0x73,
        0x73, 0x75, 0x65, 0x6c, 0x65, 0x74, 0x73, 0x65, 0x6e, 0x63, 0x72, 0x79, 0x70, 0x74, 0x2e,
        0x6f, 0x72, 0x67,
    ];

    #[test]
    fn debug_caa_result() {
        let results = CAAResults::parse_from(ONE_CAA_RECORD).unwrap();
        let result = results.iter().next().unwrap();
        let debug = format!("{result:?}");
        assert!(debug.contains("CAAResult"));
        assert!(debug.contains("issue"));
        assert!(debug.contains("critical"));
    }

    #[test]
    fn debug_caa_results_iter() {
        let results = CAAResults::parse_from(ONE_CAA_RECORD).unwrap();
        let iter = results.iter();
        let debug = format!("{iter:?}");
        assert!(debug.contains("CAAResultsIter"));
    }
}