From 387f9d6b8cb5bef769784d08811ac74fe45e8312 Mon Sep 17 00:00:00 2001 From: Infendro Date: Sat, 21 Nov 2026 10:44:38 +0100 Subject: [PATCH] orthogonal design --- src/client/dns_client.rs | 97 ++++++++++++++++++++++++++++++++++++++ src/client/ip_client.rs | 48 +++++++++++++++++++ src/client/mod.rs | 2 + src/config.rs | 32 ++++++++----- src/dns.rs | 93 ------------------------------------ src/ip.rs | 18 ------- src/main.rs | 49 +++++-------------- src/model/dns_record.rs | 21 +++++++++ src/model/ip_address.rs | 13 +++++ src/model/mod.rs | 2 + src/service/dns_service.rs | 51 ++++++++++++++++++++ src/service/mod.rs | 1 + 12 files changed, 266 insertions(+), 161 deletions(-) create mode 100644 src/client/dns_client.rs create mode 100644 src/client/ip_client.rs create mode 100644 src/client/mod.rs delete mode 100644 src/dns.rs delete mode 100644 src/ip.rs create mode 100644 src/model/dns_record.rs create mode 100644 src/model/ip_address.rs create mode 100644 src/model/mod.rs create mode 100644 src/service/dns_service.rs create mode 100644 src/service/mod.rs diff --git a/src/client/dns_client.rs b/src/client/dns_client.rs new file mode 100644 index 0000000..b348208 --- /dev/null +++ b/src/client/dns_client.rs @@ -0,0 +1,97 @@ +use std::error::Error; + +use reqwest::Client; +use serde::{Deserialize, Serialize}; + +use crate::{config::AuthConfig, model::dns_record::DnsRecord}; + +const API: &str = "https://api.porkbun.com/api/json/v3"; + +#[derive(Clone)] +pub struct DnsClient { + auth_config: AuthConfig, + client: Client, +} + +impl DnsClient { + pub fn new(auth_config: AuthConfig, client: Client) -> Self { + Self { auth_config, client } + } + + pub async fn get_records(&self, domain: &str) -> Result, Box> { + let body = GetRecordsRequest { + apikey: self.auth_config.key.clone(), + secretapikey: self.auth_config.secret_key.clone(), + }; + let response = self.client.post(format!("{API}/dns/retrieve/{domain}")) + .json(&body) + .send().await? + .error_for_status()?; + let response_body = response.json::().await?; + let records = response_body.records.iter() + .map(|it| { + let subdomain = it.name + .strip_suffix(domain).unwrap() + .strip_suffix(".").unwrap_or(""); + + DnsRecord::new( + it.id.clone(), + it.type_.clone(), + domain.to_string(), + subdomain.to_string(), + it.content.clone(), + it.ttl.parse().unwrap(), + ) + }) + .collect(); + Ok(records) + } + + pub async fn update_record(&self, record: &DnsRecord, value: &str) -> Result<(), Box> { + let body = UpdateRecordRequest { + apikey: self.auth_config.key.clone(), + secretapikey: self.auth_config.secret_key.clone(), + type_: record.type_.clone(), + name: record.subdomain.clone(), + content: value.to_string(), + ttl: record.ttl, + }; + self.client.post(format!("{API}/dns/edit/{domain}/{id}", domain = record.domain, id = record.id)) + .json(&body) + .send().await? + .error_for_status()?; + Ok(()) + } +} + +#[derive(Serialize)] +struct GetRecordsRequest { + pub apikey: String, + pub secretapikey: String, +} + +#[derive(Deserialize)] +struct GetRecordsResponse { + pub records: Vec, +} + +#[derive(Deserialize)] +struct GetRecordsResponseRecord { + pub id: String, + #[serde(rename = "type")] + pub type_: String, + pub name: String, + pub content: String, + pub ttl: String, +} + +#[derive(Serialize)] +struct UpdateRecordRequest { + pub apikey: String, + pub secretapikey: String, + #[serde(rename = "type")] + pub type_: String, + pub name: String, + pub content: String, + pub ttl: i32, +} diff --git a/src/client/ip_client.rs b/src/client/ip_client.rs new file mode 100644 index 0000000..9758de2 --- /dev/null +++ b/src/client/ip_client.rs @@ -0,0 +1,48 @@ +use std::error::Error; + +use reqwest::Client; + +use crate::model::ip_address::IpAddress; + +const API4: &str = "https://api4.ipify.org"; +const API6: &str = "https://api6.ipify.org"; + +#[derive(Clone)] +pub struct IpClient { + client: Client, +} + +impl IpClient { + pub fn new(client: Client) -> Self { + Self { client: client.clone() } + } + + pub async fn get_ip(&self) -> Result> { + let ipv4 = self.get_ipv4().await?; + let ipv6 = self.get_ipv6().await?; + let ip = IpAddress::new(ipv4, ipv6); + Ok(ip) + } + + async fn get_ipv4(&self) -> Result, Box> { + let response = self.client.get(API4) + .send().await; + let response = match response { + Ok(x) => x, + Err(_) => return Ok(None), + }; + let ipv4 = response.text().await?; + Ok(Some(ipv4)) + } + + async fn get_ipv6(&self) -> Result, Box> { + let response = self.client.get(API6) + .send().await; + let response = match response { + Ok(x) => x, + Err(_) => return Ok(None), + }; + let ipv6 = response.text().await?; + Ok(Some(ipv6)) + } +} diff --git a/src/client/mod.rs b/src/client/mod.rs new file mode 100644 index 0000000..b8ce53f --- /dev/null +++ b/src/client/mod.rs @@ -0,0 +1,2 @@ +pub mod dns_client; +pub mod ip_client; diff --git a/src/config.rs b/src/config.rs index 548cd5b..ba5fede 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,27 +1,35 @@ -use serde::Deserialize; use std::{error::Error, fs}; -#[derive(Deserialize)] +use serde::Deserialize; + +#[derive(Clone, Deserialize)] pub struct Config { - pub auth: Auth, - #[serde(rename = "entry")] - pub entries: Vec, + pub auth: AuthConfig, + pub dns: DnsConfig, + } -#[derive(Deserialize)] -pub struct Auth { +#[derive(Clone, Deserialize)] +pub struct AuthConfig { pub key: String, pub secret_key: String, } -#[derive(Deserialize)] +#[derive(Clone, Deserialize)] +pub struct DnsConfig { + pub entries: Vec, +} + +#[derive(Clone, Deserialize)] pub struct Entry { pub domain: String, pub subdomains: Vec, } -pub fn load(path: &str) -> Result> { - let raw = fs::read_to_string(&path)?; - let config = toml::from_str(&raw)?; - Ok(config) +impl Config { + pub fn load(path: &str) -> Result> { + let raw = fs::read_to_string(&path)?; + let config = toml::from_str(&raw)?; + Ok(config) + } } diff --git a/src/dns.rs b/src/dns.rs deleted file mode 100644 index be5f7f5..0000000 --- a/src/dns.rs +++ /dev/null @@ -1,93 +0,0 @@ -use std::error::Error; - -use reqwest::Client; -use serde::Deserialize; -use serde_json::json; - -use crate::config::Auth; - -pub struct Record { - pub id: String, - pub record_type: String, - pub domain: String, - pub subdomain: String, - pub value: String, - pub ttl: String, -} - -const API: &str = "https://api.porkbun.com/api/json/v3"; - -#[derive(Deserialize)] -struct RecordsResponse { - records: Vec, -} - -#[derive(Deserialize)] -struct RecordResponse { - id: String, - #[serde(rename = "type")] - record_type: String, - name: String, - content: String, - ttl: String, -} - -impl RecordResponse { - fn into_model(self, domain: &str) -> Record { - let subdomain = self.name - .strip_suffix(domain).unwrap() - .strip_suffix(".").unwrap_or(""); - - Record { - id: self.id, - record_type: self.record_type, - domain: domain.to_string(), - subdomain: subdomain.to_string(), - value: self.content, - ttl: self.ttl, - } - } -} - -pub async fn get_records( - client: &Client, - auth: &Auth, - domain: &str, -) -> Result, Box> { - let body = json!({ - "apikey": auth.key, - "secretapikey": auth.secret_key, - }); - let request = client.post(format!("{API}/dns/retrieve/{domain}")) - .json(&body) - .send().await?; - let response = request.json::().await?; - - let records = response.records - .into_iter() - .map(|it| it.into_model(domain)) - .collect(); - - Ok(records) -} - -pub async fn update_record( - client: &Client, - auth: &Auth, - record: &Record, - value: &str, -) -> Result<(), Box> { - let body = json!({ - "apikey": auth.key, - "secretapikey": auth.secret_key, - "type": record.record_type, - "name": record.subdomain, - "content": value, - "ttl": record.ttl, - }); - client.post(format!("{API}/dns/edit/{domain}/{id}", domain = record.domain, id = record.id)) - .json(&body) - .send().await?; - - Ok(()) -} diff --git a/src/ip.rs b/src/ip.rs deleted file mode 100644 index d0ab587..0000000 --- a/src/ip.rs +++ /dev/null @@ -1,18 +0,0 @@ -use reqwest::Client; -use std::error::Error; - -pub async fn get_ipv4(client: &Client) -> Result> { - get_ip(client, "https://api4.ipify.org").await -} - -pub async fn get_ipv6(client: &Client) -> Result> { - get_ip(client, "https://api6.ipify.org").await -} - -async fn get_ip(client: &Client, url: &str) -> Result> { - let request = client.get(url) - .send().await? - .error_for_status()?; - let ip = request.text().await?; - Ok(ip) -} diff --git a/src/main.rs b/src/main.rs index cae3898..5b52b91 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,52 +1,25 @@ +pub mod client; +pub mod config; +pub mod model; +pub mod service; + use std::error::Error; use reqwest::Client; -use crate::dns::Record; - -mod config; -mod dns; -mod ip; +use crate::{client::{dns_client::DnsClient, ip_client::IpClient}, config::Config, service::dns_service::DnsService}; const CONFIG: &str = "/etc/ddns.conf"; #[tokio::main] async fn main() -> Result<(), Box> { + let config = Config::load(CONFIG)?; let client = Client::new(); + let ip_client = IpClient::new(client.clone()); + let dns_client = DnsClient::new(config.auth.clone(), client.clone()); + let dns_service = DnsService::new(config.dns.clone(), ip_client, dns_client); - let config = config::load(CONFIG)?; - - let ipv4 = ip::get_ipv4(&client).await.ok(); - let ipv6 = ip::get_ipv6(&client).await.ok(); - - for entry in &config.entries { - let records = dns::get_records(&client, &config.auth, &entry.domain).await?; - - if let Some(ip) = &ipv4 { - let a_records = find_records(&records, "A", &entry.subdomains, ip); - for record in a_records { - dns::update_record(&client, &config.auth, &record, ip).await?; - } - } - - if let Some(ip) = &ipv6 { - let aaaa_records = find_records(&records, "AAAA", &entry.subdomains, ip); - for record in aaaa_records { - dns::update_record(&client, &config.auth, &record, ip).await?; - } - } - } + dns_service.update_records().await?; Ok(()) } - -fn find_records<'a>( - records: &'a [Record], - record_type: &str, - subdomains: &[String], - value: &str -) -> Vec<&'a Record> { - records.iter() - .filter(|it| it.record_type == record_type && subdomains.contains(&it.subdomain) && it.value != value) - .collect() -} diff --git a/src/model/dns_record.rs b/src/model/dns_record.rs new file mode 100644 index 0000000..754c3fc --- /dev/null +++ b/src/model/dns_record.rs @@ -0,0 +1,21 @@ +pub struct DnsRecord { + pub id: String, + pub type_: String, + pub domain: String, + pub subdomain: String, + pub value: String, + pub ttl: i32, +} + +impl DnsRecord { + pub fn new( + id: String, + type_: String, + domain: String, + subdomain: String, + value: String, + ttl: i32, + ) -> Self { + Self { id, type_, domain, subdomain, value, ttl } + } +} diff --git a/src/model/ip_address.rs b/src/model/ip_address.rs new file mode 100644 index 0000000..1a8df9d --- /dev/null +++ b/src/model/ip_address.rs @@ -0,0 +1,13 @@ +pub struct IpAddress { + pub ipv4: Option, + pub ipv6: Option, +} + +impl IpAddress { + pub fn new( + ipv4: Option, + ipv6: Option + ) -> Self { + Self { ipv4, ipv6 } + } +} diff --git a/src/model/mod.rs b/src/model/mod.rs new file mode 100644 index 0000000..f4f7571 --- /dev/null +++ b/src/model/mod.rs @@ -0,0 +1,2 @@ +pub mod dns_record; +pub mod ip_address; diff --git a/src/service/dns_service.rs b/src/service/dns_service.rs new file mode 100644 index 0000000..a190fab --- /dev/null +++ b/src/service/dns_service.rs @@ -0,0 +1,51 @@ +use std::error::Error; + +use crate::{client::{dns_client::DnsClient, ip_client::IpClient}, config::{DnsConfig}, model::{dns_record::DnsRecord, ip_address::IpAddress}}; + +#[derive(Clone)] +pub struct DnsService { + dns_config: DnsConfig, + ip_client: IpClient, + dns_client: DnsClient, +} + +impl DnsService { + pub fn new(dns_config: DnsConfig, ip_client: IpClient, dns_client: DnsClient) -> Self { + Self { dns_config, ip_client, dns_client } + } + + pub async fn update_records(&self) -> Result<(), Box> { + let ip = self.ip_client.get_ip().await?; + for entry in &self.dns_config.entries { + self.update_ip_records(&entry.domain, &entry.subdomains, &ip).await?; + } + + Ok(()) + } + + async fn update_ip_records(&self, domain: &str, subdomains: &[String], ip: &IpAddress) -> Result<(), Box> { + let records = self.dns_client.get_records(domain).await?; + + if let Some(ipv4) = &ip.ipv4 { + let ipv4_records: Vec<&DnsRecord> = records.iter() + .filter(|it| it.type_ == "A" && subdomains.contains(&it.subdomain) && it.value != *ipv4) + .collect(); + + for ipv4_record in ipv4_records { + self.dns_client.update_record(&ipv4_record, ipv4).await?; + } + } + + if let Some(ipv6) = &ip.ipv6 { + let ipv6_records: Vec<&DnsRecord> = records.iter() + .filter(|it| it.type_ == "AAAA" && subdomains.contains(&it.subdomain) && it.value != *ipv6) + .collect(); + + for ipv6_record in ipv6_records { + self.dns_client.update_record(&ipv6_record, ipv6).await?; + } + } + + Ok(()) + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs new file mode 100644 index 0000000..ce98d2e --- /dev/null +++ b/src/service/mod.rs @@ -0,0 +1 @@ +pub mod dns_service;