diff --git a/src/main.rs b/src/main.rs index 9cae7e1..fcead42 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,381 +1,313 @@ -use cloudflare::{Instance, CloudflareDnsType}; +/*use cloudflare_old::{Instance, CloudflareDnsType};*/ use reqwest::blocking::get; use serde_derive::{Deserialize, Serialize}; -use std::{fs, thread::{sleep}}; +use std::{thread::{sleep}}; +use std::error::Error; +use std::net::{Ipv4Addr, Ipv6Addr}; +use std::str::FromStr; use chrono::{Utc, Duration}; +use dotenv::dotenv; use log::{info, warn, error, LevelFilter}; -use systemd_journal_logger::JournalLog; +use reqwest::StatusCode; +use systemd_journal_logger::{connected_to_journal, JournalLog}; +use crate::cloudflare::{CloudflareZone, DnsRecordType}; + mod config; mod cloudflare; -fn default_key() -> String { - return "".to_string(); +struct Addresses { + ipv4_uri: String, + ipv6_uri: String, + ipv4: Ipv4Addr, + ipv6: Ipv6Addr, } -#[derive(Clone)] -struct ChangeTracker { - created: u16, - updated: u16, - unchanged: u16, - error: u16 -} - -impl ChangeTracker { - fn new() -> ChangeTracker { - ChangeTracker { - created: 0, - updated: 0, - unchanged: 0, - error: 0 - } - } - - fn print(&self, f: &str) { - match f { - "" => { - self.print("simple"); - } - "simple" => { - println!("{} created", self.created); - println!("{} updated", self.updated); - println!("{} unchanged", self.unchanged); - println!("{} errors", self.error); - } - &_ => { - println!("unknown format pattern '{}', defaulting to 'simple'", f); - self.print("simple"); - } - } - } -} - -#[derive(Serialize, Deserialize)] -struct DnsEntry { - name: String, - type4: bool, - type6: bool, - interface: Option, -} - -impl DnsEntry { - /// Updates a single DNS Entry - /// - /// * `change4` : IPv4 DNS change tracker, used to print details about the results of the update run after it concludes - /// * `change6` : Same as `change4` but for IPv6 - /// * `ips` : Enum of current IPv4 and IPv6 base, used to check against and update the DNS record - /// * `agent` : Cloudflare Auth Agent, provides the needed Authentication headers for the API Calls - /// * `zone_id` : Cloudfalre ID of the Zone this DNS entry resides in, needed for the API Calls - /// - /// * `return` : Returns true if the DNS Update failed due to an Error, otherwise returns false - fn update( - &self, - change4: &mut ChangeTracker, - change6: &mut ChangeTracker, - ips: &Ips, - agent: &Instance, - zone_id: &String - ) -> bool { - let mut found4 = false; - let mut found6 = false; - - // Loops over every Entry in the List fetched from the Cloudflare API - // If the entry is in this List we need to update it, if not it needs to be created - for cloudflare_entry in &agent.dns_entries { - if cloudflare_entry.is_equal(&self.name) { - // Update IPv4 Entry - if cloudflare_entry.r#type == CloudflareDnsType::A && self.type4 { - found4 = true; - - if cloudflare_entry.is_ip_new(&ips.ipv4) { - match agent.update_entry(cloudflare_entry, &ips.ipv4) { - Ok(success) => { - if success { - change4.updated += 1; - } - else { - change4.error += 1; - } - }, - Err(_e) => { return true } // if an error is detected any subsequent calls are likely to fail as well - }; - } - else { - change4.unchanged += 1; - } - } - // Update IPv6 Entry - else if cloudflare_entry.r#type == CloudflareDnsType::AAAA && self.type6 { - found6 = true; - let ipv6 = ips.ipv6base.clone() + self.interface.as_ref().unwrap(); - - if cloudflare_entry.is_ip_new(&ipv6) { - match agent.update_entry(cloudflare_entry, &ipv6) { - Ok(success) => { - if success { - change6.updated += 1 - } - else { - change6.error += 1 - } - }, - Err(_e) => { return true } // if an error is detected any subsequent calls are likely to fail as well - }; - } - else { - change6.unchanged += 1; - } - } - // ignore otherwise - else {} - } - } - - if !found4 && self.type4 { - match agent.create_entry(zone_id, "A", &self.name, &ips.ipv4) { - Ok(success) => { - if success { - change4.created += 1; - } - else { - change4.error += 1; - }; - }, - Err(_e) => { return true } // early return since if an error is detected any subsequent calls are likely to fail as well - } - } - - if !found6 && self.type6 { - let ipv6 = ips.ipv6base.clone() + self.interface.as_ref().unwrap(); - match agent.create_entry(zone_id, "AAAA", &self.name, &ipv6) { - Ok(success) => { - if success { - change6.created += 1; - } - else { - change6.error += 1; - }; - }, - Err(_e) => { return true } // if an error is detected any subsequent calls are likely to fail as well - }; - } - - return false; // If this point is reached no error has been caught therefore returning false - } -} - -#[derive(Serialize, Deserialize)] -struct DnsZone { - email: String, - name: String, - id: String, - dns_entries: Vec, -} - -impl DnsZone { - /// Attempts to Update the DNS Entries of the Zone with a new IP - /// - /// * `change4` : IPv4 DNS change tracker, used to print details about the results of the update run after it concludes - /// * `change6` : Same as `change4` but for IPv6 - /// * `ips` : Enum of current IPv4 and IPv6 base, used to check against and update the DNS record - /// * `key` : API Key needed to create the Auth Agent for the API - /// - /// * `return` : Returns true if the DNS Updates failed due to an Error, false otherwise - fn update( - &self, - change4: &mut ChangeTracker, - change6: &mut ChangeTracker, - ips: &Ips, - key: &String - ) -> bool { - let mut agent = Instance::new(key); - - match agent.load_entries(&self.email, &self.id) { - Ok(_) => { - let mut results = Vec::::new(); - - for entry in &self.dns_entries { - let result = entry.update(change4, change6, &ips, &agent, &self.id); - results.append(&mut vec!(result)); - if result { - break; // if one update fails all others are likely to fail as well - } - } - - let result = results.contains(&true); - - return result; - }, - Err(_e) => { return true }, // Early return since an Error likely means subsequent calls will also fail - } - } -} - -#[derive(Serialize, Deserialize)] -struct DnsConfig { - ipv6_interface: String, - #[serde(default = "default_key")] - api_key: String, - zones: Vec, -} - -impl DnsConfig { - fn new() -> DnsConfig { - DnsConfig { - ipv6_interface: "".to_string(), - api_key: "".to_string(), - zones: Vec::new(), - } - } - - fn load(&mut self) { - let file_contents = match fs::read_to_string("config.json") { - Ok(data) => data, - Err(e) => panic!("{:#?}", e), - }; - let config_parse: DnsConfig = match serde_json::from_str(&file_contents) { - Ok(data) => data, - Err(e) => panic!("{:#?}", e), +impl Addresses { + fn new() -> Result> { + let mut ret = Self { + ipv4_uri: "https://am.i.mullvad.net/ip".to_string(), + ipv6_uri: "https://ipv6.am.i.mullvad.net/ip".to_string(), + ipv4: Ipv4Addr::new(0, 0, 0, 0), + ipv6: Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0) }; - let key_file_contents = match fs::read_to_string("api-key.json") { - Ok(data) => data, - Err(e) => panic!("{:#?}", e), - }; - let api_key_parse: serde_json::Value = match serde_json::from_str(&key_file_contents) { - Ok(data) => data, - Err(e) => panic!("{:#?}", e), - }; - - *self = config_parse; - self.api_key = api_key_parse["api_key"].as_str().unwrap().to_owned(); - } -} - -struct Ips { - ipv4: String, - ipv6base: String, -} - -impl Ips { - fn new() -> Ips { - Ips { - ipv4: "0.0.0.0".to_string(), - ipv6base: ":".to_string(), - } - } - - /// Get the current IPv4 address and IPv6 prefix from Mullvad API - /// - /// Returns true if the get succeeded and false if it failed. - /// The IPv6 Prefix is generated by removing the IPv6 Interface from the fetched IPv6 address - fn get(&mut self, ipv6_interface: &str) -> bool { - let ipv4uri = "https://am.i.mullvad.net/ip"; - let ipv6uri = "https://ipv6.am.i.mullvad.net/ip"; - let mut ret; - - match get(ipv4uri) { - Ok(data) => { - if data.status() == 200 { - self.ipv4 = data.text().expect("0.0.0.0").trim_end().to_owned(); - ret = true; + match ret.get_v4() { + Ok(ip) => ret.ipv4 = ip, + Err(_) => { + let err_msg = format!("Unable to fetch IPv4 from '{}' during init. Aborting!", ret.ipv4_uri); + match connected_to_journal() { + true => error!("[ERROR] {err_msg}"), + false => eprintln!("[ERROR] {err_msg}"), } - else { - ret = false; + panic!("{}", err_msg); + } + } + + match ret.get_v6() { + Ok(ip) => ret.ipv6 = ip, + Err(_) => { + let err_msg = format!("Unable to fetch IPv6 from '{}' during init. Aborting!", ret.ipv6_uri); + match connected_to_journal() { + true => error!("[ERROR] {err_msg}"), + false => eprintln!("[ERROR] {err_msg}"), + } + panic!("{}", err_msg); + } + } + + Ok(ret) + } + + fn check_new(&mut self, update: bool) -> bool { + let mut new = false; + + match self.get_v4() { + Ok(ip) => { + if ip != self.ipv4 { + let info_msg = format!("IPv4 changed from '{}' to '{}'", self.ipv4, ip); + match connected_to_journal() { + true => info!("[INFO] {info_msg}"), + false => println!("[INFO] {info_msg}"), + } + new = true; + if update { self.ipv4 = ip } + } + } + Err(e) => { + let warn_msg = format!("Unable to fetch IPv4 from '{}'. Error: {}", self.ipv4_uri, e); + match connected_to_journal() { + true => warn!("[WARN] {warn_msg}"), + false => println!("[WARN] {warn_msg}"), + } + } + } + + match self.get_v6() { + Ok(ip) => { + if ip != self.ipv6 { + let info_msg = format!("IPv6 changed from '{}' to '{}'", self.ipv6, ip); + match connected_to_journal() { + true => info!("[INFO] {info_msg}"), + false => println!("[INFO] {info_msg}"), + } + new = true; + if update { self.ipv6 = ip } + } + } + Err(e) => { + let warn_msg = format!("Unable to fetch IPv6 from '{}'. Error: {}", self.ipv6_uri, e); + match connected_to_journal() { + true => warn!("[WARN] {warn_msg}"), + false => println!("[WARN] {warn_msg}"), + } + } + } + + new + } + + fn get_v4(&self) -> Result { + match get(&self.ipv4_uri) { + Ok(res) => { + match res.status() { + StatusCode::OK => { + let ip_string = res.text().expect("Returned data should always contain text").trim_end().to_owned(); + Ok(Ipv4Addr::from_str(ip_string.as_str()).expect("Returned IP should always be parseable")) + }, + _ => { + let warn_msg = format!("Unexpected HTTP status {}", res.status()); + match connected_to_journal() { + true => warn!("[WARN] {warn_msg}"), + false => println!("[WARN] {warn_msg}"), + } + Ok(Ipv4Addr::new(0, 0, 0, 0)) + } + } + } + Err(e) => Err(e), + } + + } + + fn get_v6(&self) -> Result { + match get(&self.ipv6_uri) { + Ok(res) => { + match res.status() { + StatusCode::OK => { + let ip_string = res.text().expect("Returned data should always contain text").trim_end().to_owned(); + Ok(Ipv6Addr::from_str(ip_string.as_str()).expect("Returned IP should always be parseable")) + }, + _ => { + let warn_msg = format!("Unexpected HTTP status {}", res.status()); + match connected_to_journal() { + true => warn!("[WARN] {warn_msg}"), + false => println!("[WARN] {warn_msg}"), + } + Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)) + } } }, - Err(_e) => { - println!("Could not fetch IPv4"); - ret = false; - - return ret; // Early return since a fail on IPv4 means a likely fail on IPv6 - } + Err(e) => Err(e), } - - match get(ipv6uri) { - Ok(data) => { - if data.status() == 200 { - let ipv6 = match data.text() { - Ok(ip) => {ip}, - Err(_) => {panic!("Expected IP, found none")}, - }; - let stripped = match ipv6.trim_end().strip_suffix(ipv6_interface) { - Some(string) => string.to_string(), - None => ":".to_string(), - }; - self.ipv6base = stripped; - ret = true && ret; // Only set ret to true if previous ret is also true - } - else { - ret = false; - } - } - Err(_e) => { - println!("Could not fetch IPv6"); - ret = false; - } - } - - return ret; - } -} - -/// Loops over all DNS Entries in the config and calls an update on them -fn update_dns() { - let mut config = DnsConfig::new(); - config.load(); - - let mut ips = Ips::new(); - if ips.get(&config.ipv6_interface) { - println!("Current IPv4: {}", ips.ipv4); - println!("Current IPv6: {}{}", ips.ipv6base, &config.ipv6_interface); - - let mut change4 = ChangeTracker::new(); - - let mut change6 = ChangeTracker::new(); - - let mut update_results = Vec::::new(); - - // Iterator does not work here - for zone in &config.zones { - let error = zone.update(&mut change4, &mut change6, &ips, &config.api_key); - update_results.append(&mut vec!(error)); - if error { - break; // if one update fails all others are likely to fail as well - } - } - - if update_results.contains(&true) { - println!("DNS Update failed due to Network Error") - } - else { - println!("++++A Records+++"); - change4.print("simple"); - println!("++AAAA Records++"); - change6.print("simple") - } - } } fn main() { + dotenv().ok(); JournalLog::new().expect("Systemd-Logger crate error").install().expect("Systemd-Logger crate error"); log::set_max_level(LevelFilter::Info); + let mut ifaces = config::InterfaceConfig::load().unwrap(); + let mut zone_cfgs= config::ZoneConfig::load().unwrap(); + let mut now = Utc::now() - Duration::seconds(59); - let mut current = now; + let mut start = now; - let ifaces = config::InterfaceConfig::load().unwrap(); - let zone_cfgs= config::ZoneConfig::load().unwrap(); + let mut ips = match Addresses::new() { + Ok(ips) => ips, + Err(e) => panic!("{}", e) + }; + + loop { now = Utc::now(); - if now >= current + Duration::seconds(60) { - current = now; + if now >= start + Duration::seconds(60) { + start = now; - print!("\x1B[2J\x1B[1;1H"); - println!("Starting DNS Update at {} {}", now.format("%H:%M:%S"), now.timezone()); - update_dns(); + match config::InterfaceConfig::load() { + Ok(new) => ifaces = new, + Err(e) => { + let err_msg = format!("Unable to load ínterfaces.toml with error: {}", e); + match connected_to_journal() { + true => error!("[ERROR] {err_msg}"), + false => eprintln!("[ERROR] {err_msg}"), + } + } + } + + match config::ZoneConfig::load() { + Ok(new) => zone_cfgs = new, + Err(e) => { + let err_msg = format!("Unable to load from zones.d with error: {}", e); + match connected_to_journal() { + true => error!("[ERROR] {err_msg}"), + false => eprintln!("[ERROR] {err_msg}"), + } + } + } + + // Check if IPs changed + //if ips.check_new() { + if true { + let mut error = false; + for zone in &zone_cfgs { + let cf_zone = match CloudflareZone::new(&zone) { + Ok(data) => data, + Err(e) => { + let err_msg = format!("Cloudflare Token likely not set. Error: {}", e); + match connected_to_journal() { + true => error!("[ERROR] {err_msg}"), + false => eprintln!("[ERROR] {err_msg}"), + } + error = true; + continue + } + }; + + let cf_entries = match cf_zone.get_entries() { + Ok(entries) => entries, + Err(_) => { + error = true; + continue + } + }; + + for entry in &zone.entries { + let ipv6; + let ipv4; + match entry.r#type[..] { + [DnsRecordType::AAAA, DnsRecordType::A] => { + ipv6 = match ifaces.full_v6(&entry.interface, ips.ipv6) { + Ok(ip) => Some(ip), + Err(_) => { + error = true; + continue + } + }; + ipv4 = Some(ips.ipv4); + }, + [DnsRecordType::A, DnsRecordType::AAAA] => { + ipv6 = match ifaces.full_v6(&entry.interface, ips.ipv6) { + Ok(ip) => Some(ip), + Err(_) => { + error = true; + continue + } + }; + ipv4 = Some(ips.ipv4); + }, + [DnsRecordType::AAAA] => { + ipv6 = match ifaces.full_v6(&entry.interface, ips.ipv6) { + Ok(ip) => Some(ip), + Err(_) => { + error = true; + continue + } + }; + ipv4 = None; + }, + [DnsRecordType::A] => { + ipv6 = None; + ipv4 = Some(ips.ipv4); + }, + _ => { + let warn_msg = "Config contains unsupported type identifier"; + match connected_to_journal() { + true => warn!("[WARN] {warn_msg}"), + false => println!("[WARN] {warn_msg}"), + } + continue + } + } + + for r#type in &entry.r#type { + let cf_entry = cf_entries.iter().find(|cf_entry| { + cf_entry.name == entry.name && &cf_entry.r#type == r#type + }); + + if let Some(cf_entry) = cf_entry { + match cf_zone.update(entry, r#type, &cf_entry.id, ipv6, ipv4) { + Ok(_) => { + let info_msg = format!("Updated DNS Record(s) for entry '{}' in zone '{}'", entry.name, zone.name); + match connected_to_journal() { + true => warn!("[INFO] {info_msg}"), + false => println!("[INFO] {info_msg}"), + } + }, + Err(_) => error = true, + }; + } + else { + match cf_zone.create(entry, r#type, ipv6, ipv4) { + Ok(_) => { + let info_msg = format!("Created DNS Record(s) for entry '{}' in zone '{}'", entry.name, zone.name); + match connected_to_journal() { + true => info!("[INFO] {info_msg}"), + false => println!("[INFO] {info_msg}"), + } + }, + Err(_) => error = true, + }; + } + } + + // handle return values + } + } + if !error { ips.check_new(true); } + } } else { - sleep(std::time::Duration::from_millis(500)); + sleep(std::time::Duration::from_millis(200)); } } }