use serde::{Deserialize, Serialize};
use crate::{Client, Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct RecordType(pub i32);
impl RecordType {
pub const A: RecordType = RecordType(0);
pub const AAAA: RecordType = RecordType(1);
pub const CNAME: RecordType = RecordType(2);
pub const MX: RecordType = RecordType(3);
pub const TXT: RecordType = RecordType(4);
pub const SRV: RecordType = RecordType(5);
pub const NS: RecordType = RecordType(6);
pub const PTR: RecordType = RecordType(7);
pub const SOA: RecordType = RecordType(8);
pub const CAA: RecordType = RecordType(9);
pub const TLSA: RecordType = RecordType(10);
pub const COMMON: [RecordType; 7] = [
RecordType::A,
RecordType::AAAA,
RecordType::CNAME,
RecordType::MX,
RecordType::TXT,
RecordType::SRV,
RecordType::CAA,
];
pub fn name(self) -> String {
match self {
RecordType::A => "A".into(),
RecordType::AAAA => "AAAA".into(),
RecordType::CNAME => "CNAME".into(),
RecordType::MX => "MX".into(),
RecordType::TXT => "TXT".into(),
RecordType::SRV => "SRV".into(),
RecordType::NS => "NS".into(),
RecordType::PTR => "PTR".into(),
RecordType::SOA => "SOA".into(),
RecordType::CAA => "CAA".into(),
RecordType::TLSA => "TLSA".into(),
RecordType(other) => format!("TYPE{other}"),
}
}
pub fn uses_priority(self) -> bool {
matches!(self, RecordType::MX | RecordType::SRV)
}
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DnsStatus {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub running: bool,
#[serde(default)]
pub tld: String,
#[serde(default)]
pub record_count: u64,
#[serde(default)]
pub local_forwarders: bool,
#[serde(default)]
pub forwarders: Vec<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct DnsRecord {
#[serde(default)]
pub name: String,
#[serde(default)]
pub record_type: i32,
#[serde(default)]
pub value: String,
#[serde(default)]
pub ttl: u32,
#[serde(default)]
pub priority: u32,
#[serde(default)]
pub network: String,
#[serde(default)]
pub tld: String,
}
impl DnsRecord {
pub fn kind(&self) -> RecordType {
RecordType(self.record_type)
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct DnsService {
#[serde(default)]
pub repo: String,
#[serde(default)]
pub name: String,
#[serde(default)]
pub version: String,
#[serde(default)]
pub fqdn: String,
#[serde(default)]
pub domains: Vec<String>,
#[serde(default)]
pub published: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BlocklistProvider {
pub zone: String,
pub enabled: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub refusal_codes: Vec<String>,
#[serde(default, skip_serializing_if = "is_zero")]
pub refusal_cooldown_secs: u64,
}
fn is_zero(v: &u64) -> bool {
*v == 0
}
pub const REFUSAL_CODES_NONE: &str = "none";
pub fn validate_blocklist_zone(zone: &str) -> Result<String> {
let zone = zone.trim().trim_end_matches('.').to_ascii_lowercase();
if zone.is_empty() {
return Err(Error::BaseUrl("a provider needs a zone".into()));
}
if zone.len() > 253 {
return Err(Error::BaseUrl(format!(
"a zone is at most 253 characters, and this is {}",
zone.len()
)));
}
let labels: Vec<&str> = zone.split('.').collect();
if labels.len() < 2 {
return Err(Error::BaseUrl(
"a zone must be fully qualified, as zen.spamhaus.org".into(),
));
}
for label in labels {
if label.is_empty() || label.len() > 63 {
return Err(Error::BaseUrl(format!("{label:?} is not a usable label")));
}
if label.starts_with('-') || label.ends_with('-') {
return Err(Error::BaseUrl(format!(
"{label:?} may not start or end with a hyphen"
)));
}
if !label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
return Err(Error::BaseUrl(format!(
"{label:?} must be alphanumeric with optional internal hyphens"
)));
}
}
Ok(zone)
}
pub fn parse_refusal_codes(input: &str) -> Result<Vec<String>> {
let entries: Vec<&str> = input
.split([',', ' ', '\t', '\n'])
.map(str::trim)
.filter(|e| !e.is_empty())
.collect();
if entries.is_empty() {
return Ok(Vec::new());
}
if entries.iter().any(|e| e.eq_ignore_ascii_case(REFUSAL_CODES_NONE)) {
if entries.len() == 1 {
return Ok(vec![REFUSAL_CODES_NONE.into()]);
}
return Err(Error::BaseUrl(format!(
"{REFUSAL_CODES_NONE:?} switches refusal detection off and must be the only entry"
)));
}
let mut out: Vec<String> = Vec::with_capacity(entries.len());
for entry in entries {
let code = normalize_refusal_code(entry)?;
if out.contains(&code) {
return Err(Error::BaseUrl(format!("{code} appears twice")));
}
out.push(code);
}
Ok(out)
}
fn normalize_refusal_code(code: &str) -> Result<String> {
let bad = |what: &str| Error::BaseUrl(format!("refusal code {code:?} is invalid: {what}"));
let (addr, bits) = match code.split_once('/') {
Some((addr, prefix)) => {
let bits: u32 = prefix
.trim()
.parse()
.map_err(|_| bad("the prefix must be a number"))?;
if bits > 32 {
return Err(bad("the prefix must be between 0 and 32"));
}
(addr.trim(), bits)
}
None => (code.trim(), 32),
};
let octets: Vec<u8> = addr
.split('.')
.map(|o| o.parse::<u8>().ok())
.collect::<Option<_>>()
.ok_or_else(|| bad("expected an IPv4 address"))?;
if octets.len() != 4 {
return Err(bad("expected an IPv4 address"));
}
let value = u32::from_be_bytes([octets[0], octets[1], octets[2], octets[3]]);
let mask = if bits == 0 { 0 } else { u32::MAX << (32 - bits) };
let masked = value & mask;
let [a, b, c, d] = masked.to_be_bytes();
Ok(if bits == 32 {
format!("{a}.{b}.{c}.{d}")
} else {
format!("{a}.{b}.{c}.{d}/{bits}")
})
}
#[derive(Debug, Clone, Deserialize)]
pub struct RotatedOut {
#[serde(default)]
pub zone: String,
#[serde(default)]
pub code: String,
#[serde(default)]
pub seconds_remaining: u64,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct BlocklistConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub providers: Vec<BlocklistProvider>,
#[serde(default)]
pub refusal_cooldown_secs: u64,
#[serde(default)]
pub rotated_out: Vec<RotatedOut>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct BlocklistEntry {
#[serde(default)]
pub name: String,
#[serde(default)]
pub reason: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Blocklist {
Rbl,
Dnsbl,
}
impl Blocklist {
fn path(self) -> &'static str {
match self {
Blocklist::Rbl => "/dns/rbl",
Blocklist::Dnsbl => "/dns/dnsbl",
}
}
pub fn label(self) -> &'static str {
match self {
Blocklist::Rbl => "Address blocklist (RBL)",
Blocklist::Dnsbl => "Domain blocklist (DNSBL)",
}
}
}
impl Client {
pub async fn dns_status(&self) -> Result<DnsStatus> {
self.get_json("/dns/status").await
}
pub async fn dns_records(&self, tld: Option<&str>) -> Result<Vec<DnsRecord>> {
let path = match tld.filter(|t| !t.is_empty()) {
Some(tld) => format!("/dns/records?tld={}", urlencode(tld)),
None => "/dns/records".into(),
};
self.get_json(&path).await
}
pub async fn add_dns_record(
&self,
name: &str,
record_type: RecordType,
value: &str,
ttl: u32,
) -> Result<()> {
self.post_empty(
"/dns/records/add",
&serde_json::json!({
"name": name,
"record_type": record_type.0,
"value": value,
"ttl": ttl,
}),
)
.await
}
pub async fn remove_dns_record(&self, name: &str, record_type: RecordType) -> Result<()> {
self.post_empty(
"/dns/records/remove",
&serde_json::json!({ "name": name, "record_type": record_type.0 }),
)
.await
}
pub async fn dns_tld(&self) -> Result<String> {
#[derive(Deserialize)]
struct Tld {
#[serde(default)]
tld: String,
}
let out: Tld = self.get_json("/dns/tld").await?;
Ok(out.tld)
}
pub async fn set_dns_tld(&self, tld: &str) -> Result<()> {
self.post_empty("/dns/tld", &serde_json::json!({ "tld": tld })).await
}
pub async fn setup_dns(&self) -> Result<()> {
self.post_empty("/dns/setup", &serde_json::json!({})).await
}
pub async fn dns_services(&self) -> Result<Vec<DnsService>> {
self.get_json("/dns/services").await
}
pub async fn set_dns_service(&self, repo: &str, name: &str, published: bool) -> Result<()> {
self.post_empty(
"/dns/services/set",
&serde_json::json!({ "repo": repo, "name": name, "published": published }),
)
.await
}
pub async fn blocklist_config(&self, which: Blocklist) -> Result<BlocklistConfig> {
self.get_json(which.path()).await
}
pub async fn set_blocklist_config(
&self,
which: Blocklist,
enabled: bool,
providers: &[BlocklistProvider],
refusal_cooldown_secs: u64,
) -> Result<()> {
self.post_empty(
which.path(),
&serde_json::json!({
"enabled": enabled,
"providers": providers,
"refusal_cooldown_secs": refusal_cooldown_secs,
}),
)
.await
}
pub async fn local_rbl(&self) -> Result<Vec<BlocklistEntry>> {
self.get_json("/dns/rbl/local").await
}
pub async fn add_local_rbl(&self, name: &str, reason: &str) -> Result<()> {
self.post_empty(
"/dns/rbl/local/add",
&serde_json::json!({ "name": name, "reason": reason }),
)
.await
}
pub async fn remove_local_rbl(&self, name: &str) -> Result<()> {
self.post_empty("/dns/rbl/local/remove", &serde_json::json!({ "name": name }))
.await
}
pub async fn dnsbl_allowlist(&self) -> Result<Vec<BlocklistEntry>> {
self.get_json("/dns/dnsbl/allowlist").await
}
pub async fn add_dnsbl_allowlist(&self, name: &str, reason: &str) -> Result<()> {
self.post_empty(
"/dns/dnsbl/allowlist/add",
&serde_json::json!({ "name": name, "reason": reason }),
)
.await
}
pub async fn remove_dnsbl_allowlist(&self, name: &str) -> Result<()> {
self.post_empty(
"/dns/dnsbl/allowlist/remove",
&serde_json::json!({ "name": name }),
)
.await
}
}
fn urlencode(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(byte as char)
}
other => out.push_str(&format!("%{other:02X}")),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_record_types_stay_legible() {
assert_eq!(RecordType::A.name(), "A");
assert_eq!(RecordType(42).name(), "TYPE42");
}
#[test]
fn only_mx_and_srv_carry_priority() {
assert!(RecordType::MX.uses_priority());
assert!(RecordType::SRV.uses_priority());
assert!(!RecordType::A.uses_priority());
assert!(!RecordType::TXT.uses_priority());
}
#[test]
fn query_values_are_escaped() {
assert_eq!(urlencode("home.town"), "home.town");
assert_eq!(urlencode("a b&c=d"), "a%20b%26c%3Dd");
}
#[test]
fn provider_zones_are_normalised_not_just_accepted() {
assert_eq!(validate_blocklist_zone(" ZEN.Spamhaus.ORG. ").unwrap(), "zen.spamhaus.org");
assert_eq!(validate_blocklist_zone("dbl.spamhaus.org").unwrap(), "dbl.spamhaus.org");
}
#[test]
fn a_single_label_is_never_a_dnsxl() {
let err = validate_blocklist_zone("spamhaus").unwrap_err().detail();
assert!(err.contains("fully qualified"), "{err}");
assert!(validate_blocklist_zone("").is_err());
assert!(validate_blocklist_zone("a..b").is_err());
assert!(validate_blocklist_zone("-bad.example.org").is_err());
assert!(validate_blocklist_zone("bad_label.example.org").is_err());
}
#[test]
fn an_empty_refusal_list_means_the_built_in_set() {
assert!(parse_refusal_codes("").unwrap().is_empty());
assert!(parse_refusal_codes(" , ").unwrap().is_empty());
}
#[test]
fn none_switches_detection_off_and_stands_alone() {
assert_eq!(parse_refusal_codes("none").unwrap(), vec!["none".to_string()]);
assert_eq!(parse_refusal_codes(" NONE ").unwrap(), vec!["none".to_string()]);
let err = parse_refusal_codes("none, 127.0.0.2").unwrap_err().detail();
assert!(err.contains("only entry"), "{err}");
}
#[test]
fn codes_are_separated_by_commas_or_spaces() {
let expected = vec!["127.255.255.254".to_string(), "127.255.255.255".to_string()];
assert_eq!(
parse_refusal_codes("127.255.255.254, 127.255.255.255").unwrap(),
expected
);
assert_eq!(
parse_refusal_codes("127.255.255.254 127.255.255.255").unwrap(),
expected
);
}
#[test]
fn a_prefix_is_masked_to_its_network_and_a_32_renders_bare() {
assert_eq!(
parse_refusal_codes("127.255.255.9/24").unwrap(),
vec!["127.255.255.0/24".to_string()]
);
assert_eq!(
parse_refusal_codes("127.0.0.2/32").unwrap(),
vec!["127.0.0.2".to_string()]
);
assert_eq!(parse_refusal_codes("10.1.2.3/0").unwrap(), vec!["0.0.0.0/0".to_string()]);
}
#[test]
fn duplicate_and_malformed_codes_are_refused() {
let err = parse_refusal_codes("127.255.255.0/24, 127.255.255.9/24")
.unwrap_err()
.detail();
assert!(err.contains("twice"), "{err}");
assert!(parse_refusal_codes("127.0.0.2/33").is_err());
assert!(parse_refusal_codes("127.0.0.2/nine").is_err());
assert!(parse_refusal_codes("not-an-address").is_err());
assert!(parse_refusal_codes("127.0.0").is_err());
assert!(parse_refusal_codes("127.0.0.256").is_err());
assert!(parse_refusal_codes("::1").is_err());
}
#[test]
fn providers_omit_empty_optional_fields() {
let p = BlocklistProvider {
zone: "zen.example".into(),
enabled: true,
..Default::default()
};
let json = serde_json::to_string(&p).unwrap();
assert_eq!(json, r#"{"zone":"zen.example","enabled":true}"#);
}
}