use crate::error::{Error, Result};
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
pub const MIN_TTL: u32 = 60;
pub const DEFAULT_TTL: u32 = 300;
pub const MAX_TXT_LEN: usize = 2048;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum RecordKind {
A,
Aaaa,
Txt,
Cname,
}
impl RecordKind {
pub const ALL: [RecordKind; 4] = [
RecordKind::A,
RecordKind::Aaaa,
RecordKind::Txt,
RecordKind::Cname,
];
pub fn as_str(self) -> &'static str {
match self {
RecordKind::A => "A",
RecordKind::Aaaa => "AAAA",
RecordKind::Txt => "TXT",
RecordKind::Cname => "CNAME",
}
}
}
impl fmt::Display for RecordKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RecordValue {
A(Ipv4Addr),
Aaaa(Ipv6Addr),
Txt(String),
Cname(String),
}
impl RecordValue {
pub fn kind(&self) -> RecordKind {
match self {
RecordValue::A(_) => RecordKind::A,
RecordValue::Aaaa(_) => RecordKind::Aaaa,
RecordValue::Txt(_) => RecordKind::Txt,
RecordValue::Cname(_) => RecordKind::Cname,
}
}
pub fn content(&self) -> String {
match self {
RecordValue::A(ip) => ip.to_string(),
RecordValue::Aaaa(ip) => ip.to_string(),
RecordValue::Txt(t) => t.clone(),
RecordValue::Cname(t) => normalize_target(t),
}
}
pub fn parse(kind: RecordKind, content: &str) -> Result<Self> {
let c = content.trim();
match kind {
RecordKind::A => c.parse().map(RecordValue::A).map_err(|_| {
Error::InvalidRecord(format!("not an IPv4 address in A record: {c:?}"))
}),
RecordKind::Aaaa => c.parse().map(RecordValue::Aaaa).map_err(|_| {
Error::InvalidRecord(format!("not an IPv6 address in AAAA record: {c:?}"))
}),
RecordKind::Txt => Ok(RecordValue::Txt(normalize_txt(c))),
RecordKind::Cname => {
let t = normalize_target(c);
if is_valid_target(&t) {
Ok(RecordValue::Cname(t))
} else {
Err(Error::InvalidRecord(format!(
"not a host name in CNAME record: {c:?}"
)))
}
}
}
}
pub fn same_data(&self, other: &RecordValue) -> bool {
match (self, other) {
(RecordValue::Txt(a), RecordValue::Txt(b)) => normalize_txt(a) == normalize_txt(b),
(RecordValue::Cname(a), RecordValue::Cname(b)) => {
normalize_target(a) == normalize_target(b)
}
(a, b) => a == b,
}
}
}
impl fmt::Display for RecordValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RecordValue::Txt(t) => write!(f, "{t:?}"),
other => f.write_str(&other.content()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Record {
pub name: String,
pub value: RecordValue,
pub ttl: u32,
}
impl Record {
pub fn a(name: impl Into<String>, ip: Ipv4Addr) -> Self {
Self::new(name, RecordValue::A(ip))
}
pub fn aaaa(name: impl Into<String>, ip: Ipv6Addr) -> Self {
Self::new(name, RecordValue::Aaaa(ip))
}
pub fn txt(name: impl Into<String>, text: impl Into<String>) -> Self {
Self::new(name, RecordValue::Txt(text.into()))
}
pub fn cname(name: impl Into<String>, target: impl Into<String>) -> Self {
Self::new(name, RecordValue::Cname(target.into()))
}
pub fn new(name: impl Into<String>, value: RecordValue) -> Self {
Self {
name: name.into(),
value,
ttl: DEFAULT_TTL,
}
}
pub fn with_ttl(mut self, ttl: u32) -> Self {
self.ttl = ttl;
self
}
pub fn kind(&self) -> RecordKind {
self.value.kind()
}
pub fn txt_key(&self) -> Option<&str> {
match &self.value {
RecordValue::Txt(t) => Some(txt_key(t)),
_ => None,
}
}
pub fn validate(&self, zone: &str) -> Result<()> {
if self.ttl < MIN_TTL {
return Err(Error::InvalidRecord(format!(
"{} {}: ttl {} is below {MIN_TTL}",
self.kind(),
self.name,
self.ttl
)));
}
if !is_valid_name(zone, &self.name) {
return Err(Error::InvalidRecord(format!(
"{:?} is not a valid record name in zone {zone}",
self.name
)));
}
if let RecordValue::Txt(t) = &self.value {
if t.is_empty() || t.len() > MAX_TXT_LEN {
return Err(Error::InvalidRecord(format!(
"TXT {}: value must be 1..={MAX_TXT_LEN} bytes",
self.name
)));
}
if t.contains('"') || t.contains('\n') {
return Err(Error::InvalidRecord(format!(
"TXT {}: value must not contain quotes or newlines",
self.name
)));
}
}
if let RecordValue::Cname(t) = &self.value {
let fqdn = crate::config::normalize_fqdn(zone, &self.name).to_ascii_lowercase();
let zone_l = zone.trim().trim_end_matches('.').to_ascii_lowercase();
if fqdn == zone_l {
return Err(Error::InvalidRecord(format!(
"CNAME {fqdn}: a CNAME cannot be at the zone apex"
)));
}
let target = normalize_target(t);
if !is_valid_target(&target) {
return Err(Error::InvalidRecord(format!(
"CNAME {fqdn}: target {t:?} is not a full host name"
)));
}
if target == fqdn {
return Err(Error::InvalidRecord(format!(
"CNAME {fqdn}: a CNAME cannot point at itself"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExistingRecord {
pub id: u64,
pub name: String,
pub value: RecordValue,
pub ttl: Option<u32>,
}
pub fn normalize_txt(s: &str) -> String {
let t = s.trim();
if t.len() >= 2 && t.starts_with('"') && t.ends_with('"') {
let inner = &t[1..t.len() - 1];
if inner.contains("\" \"") {
return inner.split("\" \"").collect();
}
return inner.replace("\\\"", "\"");
}
t.to_string()
}
pub fn normalize_target(s: &str) -> String {
let t = s.trim();
t.strip_suffix('.').unwrap_or(t).to_ascii_lowercase()
}
pub(crate) fn is_valid_target(target: &str) -> bool {
!target.is_empty()
&& target.len() <= 253
&& target.contains('.')
&& target.split('.').all(|l| {
!l.is_empty()
&& l.len() <= 63
&& !l.starts_with('-')
&& !l.ends_with('-')
&& l.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
})
}
pub(crate) fn txt_key(t: &str) -> &str {
match t.find('=') {
Some(1) if t.starts_with('v') => t.split_whitespace().next().unwrap_or(t),
Some(i) => &t[..=i],
None => t,
}
}
pub fn is_valid_name(zone: &str, name: &str) -> bool {
let zone = zone.trim().trim_end_matches('.').to_ascii_lowercase();
let n = name.trim().trim_end_matches('.').to_ascii_lowercase();
if n.is_empty() || n == "@" || n == zone {
return true;
}
if n.len() > 253 {
return false;
}
let label_ok = |l: &str| {
!l.is_empty()
&& l.len() <= 63
&& !l.starts_with('-')
&& !l.ends_with('-')
&& l.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
};
n.split('.').all(label_ok)
}