X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=src%2Fmain.rs;h=2a9b5e43887c7d19cea4c2a00c9bdb21d666cb79;hb=52284b0325bfc45c902884c0c3633d8147767941;hp=84306f6adb8631034e52bd6e29513b480889614a;hpb=4d545d80471a5c59f21c3b530a40274b2760c9be;p=gandi_dns_update.git diff --git a/src/main.rs b/src/main.rs index 84306f6..2a9b5e4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,34 +1,49 @@ /* * API Reference: https://api.gandi.net/docs/livedns/ - * Some inspiration: https://github.com/rmarchant/gandi-ddns/blob/master/gandi_ddns.py + * Some similar implementations: + * - https://github.com/rmarchant/gandi-ddns/blob/master/gandi_ddns.py + * - https://github.com/brianhp2/gandi-automatic-dns + * + * TODO: + * - Log to stdout with (at least) timestamps. + * - Renew function. */ -use std::{ thread, time, fs::File, net::{ IpAddr, Ipv4Addr } }; +#![cfg_attr(debug_assertions, allow(unused_variables, unused_imports, dead_code))] + +use std::{ fmt::format, fs::File, net::{ IpAddr, Ipv4Addr }, thread, time }; use ron::{ de::from_reader, ser::to_writer }; use serde::{ Deserialize, Serialize }; +use serde_json::{ Value, json }; +// A generic result of type 'T'. type Result = std::result::Result>; #[derive(Debug)] -struct GetRealIpError; +struct Error { + message: String +} -impl std::fmt::Display for GetRealIpError { +impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "SuperErrorSideKick is here!") + write!(f, "Error: {}", &self.message) } } -impl std::error::Error for GetRealIpError {} +impl std::error::Error for Error { } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Clone, Deserialize, Serialize)] struct Config { delay_between_check: time::Duration, api_key: String, + fqdn: String, + domains: Vec, + ttl: i32 } impl Config { fn default() -> Self { - Config { delay_between_check: time::Duration::from_secs(60), api_key: String::from("") } + Config { delay_between_check: time::Duration::from_secs(120), api_key: String::from(""), fqdn: String::from(""), domains: Vec::new(), ttl: 300 } } fn read(file_path: &str) -> Result { @@ -48,16 +63,19 @@ impl Config { const FILE_CONF: &str = "config.ron"; fn main() -> Result<()> { + println!("GANDI DynDNS"); let config = Config::read(FILE_CONF)?; - println!("Configuration: {:?}", config); + println!("Configuration: {:?}", Config { api_key: String::from("*****"), ..config.clone() }); loop { let time_beginning_loop = time::Instant::now(); - check_and_update_dns(&config.api_key); + if let Err(err) = check_and_update_dns(&config.api_key, &config.fqdn, &config.domains, config.ttl) { + println!("!! Error: {}", err); + } let elapsed = time::Instant::now() - time_beginning_loop; @@ -65,28 +83,25 @@ fn main() -> Result<()> { let to_wait = config.delay_between_check - elapsed; thread::sleep(to_wait); } - } } -fn check_and_update_dns(api_key: &str) { - /* - let url = "https://api.gandi.net/v5/livedns/domains"; - let client = reqwest::blocking::Client::new(); +fn check_and_update_dns(api_key: &str, fqdn: &str, domains: &Vec, ttl: i32) -> Result<()> { + let real_ip = get_real_ip()?; + dbg!(&real_ip); - match client.get(url).header("Authorization", format!("Apikey {}", api_key)).send() { - Ok(resp) => - if resp.status().is_success() { - let content = resp.text().unwrap(); - println!("Content:\n{:?}", content); - } else { - println!("Request unsuccessful:\n{:#?}", resp); - }, - Err(error) => - println!("Error during request: {:?}", error) + for domain in domains { + let current_ip = get_current_record_ip(api_key, domain, fqdn)?; + dbg!(domain, current_ip); + + if real_ip != current_ip { + println!("IP addresses don't match for domain {}: real = {}, dns = {}. Renewing DNS...", domain, real_ip, current_ip); + update_record_ip(api_key, domain, fqdn, real_ip, ttl)?; + println!("Renewing of {} successfully", domain); + } } - */ - dbg!(get_real_ip()); + + Ok(()) } fn get_real_ip() -> Result { @@ -100,25 +115,69 @@ fn get_real_ip() -> Result { let content = resp.text().unwrap(); match content.parse::() { Ok(IpAddr::V4(ip_v4)) => Ok(ip_v4), - /*Err(_)*/ _ => Err(Box::new(GetRealIpError)) + _ => Err(Box::new(Error { message: String::from("Can't parse IPv4 from ipify") })) } - //println!("Content:\n{:?}", content); } else { - println!("Request unsuccessful:\n{:#?}", resp); - Err(Box::new(GetRealIpError)) + Err(Box::new(Error { message: format!("Request unsuccessful: {:#?}", resp) })) }, Err(error) => { - println!("Error during request: {:?}", error); - Err(Box::new(GetRealIpError)) + Err(Box::new(Error { message: format!("Error during request: {:?}", error) })) } } } -fn get_current_record_ip() { +enum Method { + Put(String), + Get +} +fn request_livedns_gandi(api_key: &str, url_fragment: &str, method: Method) -> Result { + let url = format!("https://api.gandi.net/v5/livedns/{}", url_fragment); + let client = reqwest::blocking::Client::new(); + + let request_builder = + match method { + Method::Put(body) => client.put(url).body(body), + Method::Get => client.get(url) + }; + + match request_builder.header("Authorization", format!("Apikey {}", api_key)).send() { + Ok(resp) => + if resp.status().is_success() { + let content = resp.text().unwrap(); + Ok(serde_json::from_str(&content).unwrap()) + } else { + Err(Box::new(Error { message: format!("Request unsuccessful: {:#?}", resp) })) + }, + Err(error) => + Err(Box::new(Error { message: format!("Error during request: {:?}", error) })) + } +} + +fn get_current_record_ip(api_key: &str, name: &str, fqdn: &str) -> Result { + let json_value = request_livedns_gandi(api_key, &format!("domains/{}/records/{}/A", fqdn, name), Method::Get)?; + + match &json_value["rrset_values"][0] { + Value::String(ip_str) => + Ok(ip_str.parse()?), + _ => + Result::Err(Box::new(Error { message: format!("Unable to extract the IP from the JSON answer: {}", json_value) })) + } } -fn update_record_ip() { +fn update_record_ip(api_key: &str, name: &str, fqdn: &str, ip: Ipv4Addr, ttl: i32) -> Result<()> { + let json_body = + json!( + { + "rrset_values": [ format!("{}", ip) ], + "rrset_ttl": ttl + } + ); + + let json_value = request_livedns_gandi(api_key, &format!("domains/{}/records/{}/A", fqdn, name), Method::Put(json_body.to_string()))?; + + dbg!(json_value); + Ok(()) }