X-Git-Url: http://git.euphorik.ch/?a=blobdiff_plain;f=src%2Fmain.rs;h=6665155fb5afa94d17c3c00bbbaad89d6774ec3a;hb=8ba22e853dc85ebee11668c42e0cf7398a911517;hp=fa7584ecbb8f9234ed082a4ee59ed53788bbc1c5;hpb=81a586e4cbc435651174131d75f05cf33094678c;p=gandi_dns_update.git diff --git a/src/main.rs b/src/main.rs index fa7584e..6665155 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,71 +1,50 @@ /* * API Reference: https://api.gandi.net/docs/livedns/ + * * Some similar implementations: * - https://github.com/rmarchant/gandi-ddns/blob/master/gandi_ddns.py * - https://github.com/brianhp2/gandi-automatic-dns + * */ #![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; +use std::{ + net::{IpAddr, Ipv4Addr}, + thread, time, +}; -type Result = std::result::Result>; +use serde_json::{json, Value}; -#[derive(Debug)] -struct Error { - message: String -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.message) - } -} - -impl std::error::Error for Error { } +use crate::{ + config::Config, + error::{Error, Result}, +}; -#[derive(Debug, Deserialize, Serialize)] -struct Config { - delay_between_check: time::Duration, - api_key: String, - domains: Vec, -} - -impl Config { - fn default() -> Self { - Config { delay_between_check: time::Duration::from_secs(60), api_key: String::from(""), domains: Vec::new() } - } - - fn read(file_path: &str) -> Result { - match File::open(file_path) { - Ok(file) => from_reader(file).map_err(|e| e.into()), - // The file doesn't exit -> create it with default values. - Err(_) => { - let file = File::create(file_path)?; - let default_config = Config::default(); - to_writer(file, &default_config)?; - Ok(default_config) - } - } - } -} +mod config; +mod error; const FILE_CONF: &str = "config.ron"; fn main() -> Result<()> { - println!("GANDI DynDNS"); + println!("GANDI LiveDNS updater"); 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.domains, config.ttl) { + println!("!! {}", err); + } let elapsed = time::Instant::now() - time_beginning_loop; @@ -73,96 +52,121 @@ fn main() -> Result<()> { let to_wait = config.delay_between_check - elapsed; thread::sleep(to_wait); } - } } -fn check_and_update_dns(api_key: &str) { - /* - */ - //dbg!(get_real_ip()); +fn check_and_update_dns(api_key: &str, domains: &Vec<(String, String)>, ttl: i32) -> Result<()> { + let real_ip = get_real_ip()?; - get_current_record_ip(api_key); + for (hostname, domain) in domains { + let current_ip = get_current_record_ip(api_key, hostname, domain)?; + + 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, hostname, domain, real_ip, ttl)?; + println!("Renewing of {}.{} successfully", hostname, domain); + } + } + + Ok(()) } fn get_real_ip() -> Result { - let url = "https://api.ipify.org"; let client = reqwest::blocking::Client::new(); match client.get(url).send() { - Ok(resp) => + Ok(resp) => { if resp.status().is_success() { let content = resp.text().unwrap(); - match content.parse::() { + match content.parse() { Ok(IpAddr::V4(ip_v4)) => Ok(ip_v4), - /*Err(_)*/ _ => Err(Box::new(Error { message: String::from("Can't parse IPv4 from ipify") })) + _ => 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(Error { message: format!("Request unsuccessful: {:#?}", resp) })) - }, - - Err(error) => { - //println!("Error during request: {:?}", error); - Err(Box::new(Error { message: format!("Error during request: {:?}", error) })) + Err(Box::new(Error { + message: format!("Request unsuccessful to {}: {:#?}", url, resp), + })) + } } + Err(error) => Err(Box::new(Error { + message: format!("Error during request to {}: {:?}", url, error), + })), } } -fn request_livedns_gandi(api_key: &str, url_fragment: &str) -> Result { - let url = format!("https://api.gandi.net/v5/livedns/{}", url_fragment); - let client = reqwest::blocking::Client::new(); - - match client.get(&url).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 get_current_record_ip(api_key: &str) -> Result { +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 + } + ); - request_livedns_gandi(api_key, "domains/euphorik.ch/records/home/A")?; // TODO... - // .map() - //.map(|json_value| json_value["rrset_values"][0].as_str().unwrap()) + let json_value = request_livedns_gandi( + api_key, + &format!("domains/{}/records/{}/A", fqdn, name), + Method::Put(json_body.to_string()), + )?; - Result::Err(Box::new(Error { message: String::new() })) + println!("Update response: {}", json_value); + Ok(()) +} - //let url = "https://api.gandi.net/v5/livedns/domains/euphorik.ch/records"; - //let url = "https://api.gandi.net/v5/livedns/domains"; // ?sharing_id=" - //let url = "https://api.gandi.net/v5/organization/organizations"; - //let url = "https://api.gandi.net/v5/livedns/domains/euphorik.ch/records/home/A"; +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(); - match client.get(url).header("Authorization", format!("Apikey {}", api_key)).send() { - Ok(resp) => + 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(); - - let json: Value = serde_json::from_str(&content).unwrap(); - let prout = json["rrset_values"][0].as_str().unwrap(); - println!("IP: {}", prout); - - println!("Content:\n{}", serde_json::to_string_pretty(&json).unwrap()); + Ok(serde_json::from_str(&content).unwrap()) } else { - println!("Request unsuccessful:\n{:#?}", resp); - }, - Err(error) => - println!("Error during request: {:?}", error) + Err(Box::new(Error { + message: format!("Request unsuccessful to {}: {:#?}", &url, resp), + })) + } + } + Err(error) => Err(Box::new(Error { + message: format!("Error during request to {}: {:?}", &url, error), + })), } - */ -} - -fn update_record_ip() { }