#[cfg(feature = "standalone")]
use crate::error::IoContext;
use crate::error::{Error, Result};
#[cfg(feature = "standalone")]
use crate::fs::{Privacy, atomic_write_private_with};
pub use crate::record::{DEFAULT_TTL, MIN_TTL};
use serde::{Deserialize, Serialize};
use std::fmt;
#[cfg(feature = "standalone")]
use std::path::Path;
use std::str::FromStr;
#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
pub const CONFIG_FILE_NAME: &str = "config.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Provider {
#[default]
Dnsimple,
Digitalocean,
}
impl Provider {
pub const ALL: [Provider; 2] = [Provider::Dnsimple, Provider::Digitalocean];
pub fn as_str(self) -> &'static str {
match self {
Provider::Dnsimple => "dnsimple",
Provider::Digitalocean => "digitalocean",
}
}
}
impl fmt::Display for Provider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Provider {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"dnsimple" => Ok(Provider::Dnsimple),
"digitalocean" => Ok(Provider::Digitalocean),
other => Err(Error::Config(format!(
"unsupported provider {other:?}; choose dnsimple or digitalocean"
))),
}
}
}
#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Schedule {
#[serde(default)]
pub calendar: Option<String>,
#[serde(default)]
pub interval_secs: Option<u64>,
}
#[cfg(feature = "standalone")]
impl Default for Schedule {
fn default() -> Self {
Self {
calendar: None,
interval_secs: Some(300),
}
}
}
#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum RecordType {
#[default]
A,
Cname,
}
#[cfg(feature = "standalone")]
impl RecordType {
pub fn as_str(self) -> &'static str {
match self {
RecordType::A => "a",
RecordType::Cname => "cname",
}
}
}
#[cfg(feature = "standalone")]
impl fmt::Display for RecordType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(feature = "standalone")]
impl FromStr for RecordType {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"a" => Ok(RecordType::A),
"cname" => Ok(RecordType::Cname),
other => Err(Error::Config(format!(
"unsupported record type {other:?}; choose a or cname"
))),
}
}
}
#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CnameConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub weirdnet_link: Option<String>,
}
#[cfg(feature = "standalone")]
impl CnameConfig {
pub fn source(&self) -> Result<crate::cname::CnameSource> {
match (&self.target, &self.weirdnet_link) {
(Some(t), None) => Ok(crate::cname::CnameSource::Target(t.clone())),
(None, Some(l)) => Ok(crate::cname::CnameSource::WeirdnetLink(l.clone())),
(None, None) => Err(Error::Config(
"[cname] needs one of target or weirdnet_link".into(),
)),
(Some(_), Some(_)) => Err(Error::Config(
"[cname] takes either target or weirdnet_link, not both".into(),
)),
}
}
}
#[cfg(feature = "standalone")]
#[cfg_attr(docsrs, doc(cfg(feature = "standalone")))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppConfig {
#[serde(default)]
pub provider: Provider,
#[serde(default)]
pub account_id: Option<u64>,
pub zone: String,
pub name: String,
#[serde(default, skip_serializing_if = "is_default_record")]
pub record: RecordType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cname: Option<CnameConfig>,
#[serde(default = "default_ttl")]
pub ttl: u32,
#[serde(default)]
pub sandbox: bool,
#[serde(default)]
pub api_base_url: Option<String>,
#[serde(default)]
pub schedule: Schedule,
}
#[cfg(feature = "standalone")]
fn is_default_record(r: &RecordType) -> bool {
*r == RecordType::A
}
#[cfg(feature = "standalone")]
fn default_ttl() -> u32 {
DEFAULT_TTL
}
#[cfg(feature = "standalone")]
impl Default for AppConfig {
fn default() -> Self {
Self {
provider: Provider::default(),
account_id: None,
zone: "example.com".to_string(),
name: "@".to_string(),
record: RecordType::A,
cname: None,
ttl: DEFAULT_TTL,
sandbox: false,
api_base_url: None,
schedule: Schedule::default(),
}
}
}
#[cfg(feature = "standalone")]
impl AppConfig {
pub fn validate(&self) -> Result<()> {
if self.ttl < MIN_TTL {
return Err(Error::Config(format!("ttl must be >= {MIN_TTL}")));
}
if self.zone.trim().is_empty() {
return Err(Error::Config("zone must be set".into()));
}
if self.name.trim().is_empty() {
return Err(Error::Config("name must be set".into()));
}
if self.schedule.calendar.is_none() && self.schedule.interval_secs.is_none() {
return Err(Error::Config(
"schedule must set either calendar or interval_secs".into(),
));
}
if !crate::record::is_valid_name(&self.zone, &self.name) {
return Err(Error::Config(format!(
"{:?} is not a valid record name",
self.name
)));
}
match (self.record, &self.cname) {
(RecordType::A, Some(_)) => {
return Err(Error::Config(
"[cname] is only used with record = \"cname\"".into(),
));
}
(RecordType::A, None) => {}
(RecordType::Cname, None) => {
return Err(Error::Config(
"record = \"cname\" needs a [cname] table with target or weirdnet_link".into(),
));
}
(RecordType::Cname, Some(c)) => {
if self
.record_fqdn()
.eq_ignore_ascii_case(self.zone.trim_end_matches('.'))
{
return Err(Error::Config(
"a CNAME cannot be at the zone apex; set a name such as www".into(),
));
}
c.source()?
.target()
.map_err(|e| Error::Config(e.to_string()))?;
}
}
Ok(())
}
pub fn record_fqdn(&self) -> String {
normalize_fqdn(&self.zone, &self.name)
}
pub fn from_toml_str(text: &str) -> Result<Self> {
let cfg: AppConfig = toml::from_str(text).map_err(|e| Error::Config(e.to_string()))?;
cfg.validate()?;
Ok(cfg)
}
pub fn to_toml_string(&self) -> Result<String> {
toml::to_string_pretty(self).map_err(|e| Error::Config(e.to_string()))
}
pub fn load(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path).ctx(|| format!("reading {}", path.display()))?;
Self::from_toml_str(&text)
.map_err(|e| Error::Config(format!("parsing {}: {e}", path.display())))
}
pub fn save(&self, path: &Path) -> Result<()> {
self.save_with(path, Privacy::CurrentUser)
}
pub fn save_with(&self, path: &Path, privacy: Privacy) -> Result<()> {
let text = self.to_toml_string()?;
atomic_write_private_with(path, text.as_bytes(), privacy)
}
}
pub fn normalize_fqdn(zone: &str, name: &str) -> String {
let z = zone.trim_end_matches('.').to_string();
let n = name.trim().trim_end_matches('.');
if n == "@" || n.is_empty() || n.eq_ignore_ascii_case(&z) {
z
} else if ends_with_zone(n, &z) {
n.to_string()
} else {
format!("{}.", n) + &z
}
}
pub fn relative_name(zone: &str, name: &str) -> String {
let zone = zone.trim_end_matches('.').to_string();
let name = name.trim().trim_end_matches('.');
if name == "@" || name.is_empty() || name.eq_ignore_ascii_case(&zone) {
String::new()
} else if ends_with_zone(name, &zone) {
name[..name.len() - zone.len() - 1].to_string()
} else {
name.to_string()
}
}
fn ends_with_zone(name: &str, zone: &str) -> bool {
name.len() > zone.len() + 1
&& name.is_char_boundary(name.len() - zone.len())
&& name.as_bytes()[name.len() - zone.len() - 1] == b'.'
&& name[name.len() - zone.len()..].eq_ignore_ascii_case(zone)
}
pub mod validate {
use regex::Regex;
use std::sync::LazyLock;
static FQDN: LazyLock<Regex> = LazyLock::new(|| {
let label = r"(?i)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])";
Regex::new(&format!("^({label}\\.)+[a-z{{2,}}A-Z{{2,}}]+$")).expect("static regex")
});
static LABEL: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])$").expect("static regex")
});
pub fn is_valid_fqdn(s: &str) -> bool {
FQDN.is_match(s.trim_end_matches('.'))
}
pub fn is_valid_label(label: &str) -> bool {
LABEL.is_match(label)
}
pub fn is_valid_record_name(zone: &str, name: &str) -> bool {
let n = name.trim();
if n == "@" {
return true;
}
if n.split('.')
.all(|lbl| !lbl.is_empty() && is_valid_label(lbl))
{
return true;
}
is_valid_fqdn(n) && n.ends_with(zone.trim_end_matches('.'))
}
}