use std::{collections::BTreeSet, fmt, future::Future, net::IpAddr, pin::Pin, time::Duration};
pub(crate) const MAX_EXCHANGES: usize = 32;
const MAX_ADDRESSES_PER_EXCHANGE: usize = 16;
#[cfg(feature = "posture")]
const MAX_TEXT_RECORDS: usize = 32;
#[cfg(feature = "posture")]
const MAX_TEXT_RECORD_BYTES: usize = 4 * 1024;
#[cfg(feature = "posture")]
const MAX_TEXT_RESPONSE_BYTES: usize = 16 * 1024;
pub type Resolve<'a> = Pin<Box<dyn Future<Output = Result<Resolution, ResolveError>> + Send + 'a>>;
#[cfg(feature = "posture")]
pub type ResolveText<'a> =
Pin<Box<dyn Future<Output = Result<TextRecords, ResolveError>> + Send + 'a>>;
pub trait Resolver: Send + Sync {
fn resolve(&self, domain: &str) -> Resolve<'_>;
#[cfg(feature = "posture")]
fn resolve_text(&self, _domain: &str) -> ResolveText<'_> {
Box::pin(async {
Err(ResolveError::new(
ResolveErrorKind::Unavailable,
"TXT lookup capability is unavailable",
))
})
}
}
#[cfg(feature = "posture")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TextRecords {
values: Vec<String>,
valid_for: Option<Duration>,
}
#[cfg(feature = "posture")]
impl TextRecords {
pub fn new(mut values: Vec<String>, valid_for: Option<Duration>) -> Result<Self, ResolveError> {
let total_bytes = values.iter().try_fold(0_usize, |total, value| {
total.checked_add(value.len()).ok_or(())
});
let exceeds_total = match total_bytes {
Ok(total) => total > MAX_TEXT_RESPONSE_BYTES,
Err(()) => true,
};
if values.len() > MAX_TEXT_RECORDS
|| values
.iter()
.any(|value| value.len() > MAX_TEXT_RECORD_BYTES)
|| exceeds_total
{
return Err(ResolveError::new(
ResolveErrorKind::Protocol,
"TXT response exceeded its resource limit",
));
}
values.sort();
Ok(Self { values, valid_for })
}
#[must_use]
pub fn values(&self) -> &[String] {
&self.values
}
#[must_use]
pub const fn valid_for(&self) -> Option<Duration> {
self.valid_for
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct MailExchange {
preference: u16,
host: String,
addresses: Vec<IpAddr>,
}
impl MailExchange {
pub fn new(
preference: u16,
host: impl AsRef<str>,
mut addresses: Vec<IpAddr>,
) -> Result<Self, ResolveError> {
let host = host.as_ref();
let host = host.strip_suffix('.').unwrap_or(host);
let host = idna::domain_to_ascii_strict(host)
.map_err(|_| {
ResolveError::new(ResolveErrorKind::InvalidName, "invalid mail exchanger name")
})?
.to_ascii_lowercase();
if host.is_empty()
|| host.len() > 253
|| host
.split('.')
.any(|label| label.is_empty() || label.len() > 63)
{
return Err(ResolveError::new(
ResolveErrorKind::InvalidName,
"invalid mail exchanger name",
));
}
addresses.sort_unstable();
addresses.dedup();
addresses.truncate(MAX_ADDRESSES_PER_EXCHANGE);
Ok(Self {
preference,
host,
addresses,
})
}
#[must_use]
pub const fn preference(&self) -> u16 {
self.preference
}
#[must_use]
pub fn host(&self) -> &str {
&self.host
}
#[must_use]
pub fn addresses(&self) -> &[IpAddr] {
&self.addresses
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ResolutionKind {
Mx,
ImplicitMx,
NullMx,
NxDomain,
NoMailRoute,
}
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Resolution {
kind: ResolutionKind,
exchanges: Vec<MailExchange>,
valid_for: Option<Duration>,
}
impl Resolution {
#[must_use]
pub fn new(
mut kind: ResolutionKind,
exchanges: Vec<MailExchange>,
valid_for: Option<Duration>,
) -> Self {
let exchanges = if matches!(
kind,
ResolutionKind::NullMx | ResolutionKind::NxDomain | ResolutionKind::NoMailRoute
) {
Vec::new()
} else {
let mut routes = BTreeSet::new();
for exchange in exchanges {
if exchange.addresses().is_empty() {
continue;
}
routes.insert(exchange);
if routes.len() > MAX_EXCHANGES {
let _ = routes.pop_last();
}
}
if routes.is_empty() {
kind = ResolutionKind::NoMailRoute;
}
routes.into_iter().collect()
};
Self {
kind,
exchanges,
valid_for,
}
}
#[must_use]
pub const fn kind(&self) -> ResolutionKind {
self.kind
}
#[must_use]
pub fn exchanges(&self) -> &[MailExchange] {
&self.exchanges
}
#[must_use]
pub const fn valid_for(&self) -> Option<Duration> {
self.valid_for
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ResolveError {
kind: ResolveErrorKind,
message: String,
}
impl ResolveError {
#[must_use]
pub fn new(kind: ResolveErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
}
}
#[must_use]
pub const fn kind(&self) -> ResolveErrorKind {
self.kind
}
}
impl fmt::Display for ResolveError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for ResolveError {}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ResolveErrorKind {
Timeout,
Unavailable,
Protocol,
InvalidName,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exchanges_are_normalized_and_deterministic() {
let exchange = MailExchange::new(
10,
"MX.EXAMPLE.COM.",
vec!["192.0.2.2".parse().unwrap(), "192.0.2.1".parse().unwrap()],
)
.unwrap();
assert_eq!(exchange.host(), "mx.example.com");
assert_eq!(exchange.addresses()[0].to_string(), "192.0.2.1");
}
#[test]
fn exchange_names_accept_only_one_dns_root_label() {
assert!(MailExchange::new(10, "mx.example.com.", Vec::new()).is_ok());
assert!(MailExchange::new(10, "mx.example.com..", Vec::new()).is_err());
}
#[test]
fn resolver_results_are_bounded_before_use() {
let addresses = (1..=32).map(|last| IpAddr::from([1, 1, 1, last])).collect();
let exchange = MailExchange::new(10, "mx.example.com", addresses).unwrap();
assert_eq!(exchange.addresses().len(), MAX_ADDRESSES_PER_EXCHANGE);
let exchanges = (0..64)
.map(|index| {
MailExchange::new(
index,
format!("mx-{index}.example.com"),
vec![IpAddr::from([1, 1, 1, 1])],
)
})
.collect::<Result<Vec<_>, _>>()
.unwrap();
let resolution = Resolution::new(ResolutionKind::Mx, exchanges, None);
assert_eq!(resolution.exchanges().len(), MAX_EXCHANGES);
}
#[test]
fn negative_conclusions_cannot_carry_smtp_routes() {
let exchange = MailExchange::new(10, "mx.example.com", Vec::new()).unwrap();
let resolution = Resolution::new(ResolutionKind::NullMx, vec![exchange], None);
assert!(resolution.exchanges().is_empty());
}
#[test]
fn empty_positive_routes_become_no_mail_route() {
let exchange = MailExchange::new(10, "mx.example.com", Vec::new()).unwrap();
let resolution = Resolution::new(ResolutionKind::Mx, vec![exchange], None);
assert_eq!(resolution.kind(), ResolutionKind::NoMailRoute);
assert!(resolution.exchanges().is_empty());
}
#[test]
fn usable_routes_are_selected_before_the_exchange_limit() {
let mut exchanges = (0..MAX_EXCHANGES)
.map(|index| {
MailExchange::new(index as u16, format!("mx-{index}.example.com"), Vec::new())
})
.collect::<Result<Vec<_>, _>>()
.unwrap();
exchanges.push(
MailExchange::new(
100,
"mx-usable.example.com",
vec![IpAddr::from([1, 1, 1, 1])],
)
.unwrap(),
);
let resolution = Resolution::new(ResolutionKind::Mx, exchanges, None);
assert_eq!(resolution.kind(), ResolutionKind::Mx);
assert_eq!(resolution.exchanges().len(), 1);
assert_eq!(resolution.exchanges()[0].host(), "mx-usable.example.com");
}
#[cfg(feature = "posture")]
#[test]
fn text_records_reject_oversized_responses() {
let error =
TextRecords::new(vec!["x".repeat(MAX_TEXT_RECORD_BYTES + 1)], None).unwrap_err();
assert_eq!(error.kind(), ResolveErrorKind::Protocol);
}
}