Obtaining IP from DNS now works.
[gandi_dns_update.git] / src / main.rs
1 /*
2 * API Reference: https://api.gandi.net/docs/livedns/
3 * Some similar implementations:
4 * - https://github.com/rmarchant/gandi-ddns/blob/master/gandi_ddns.py
5 * - https://github.com/brianhp2/gandi-automatic-dns
6 *
7 * TODO:
8 * - Log to stdout with (at least) timestamps.
9 * - Renew function.
10 */
11
12 #![cfg_attr(debug_assertions, allow(unused_variables, unused_imports, dead_code))]
13
14 use std::{ fmt::format, fs::File, net::{ IpAddr, Ipv4Addr }, thread, time };
15 use ron::{ de::from_reader, ser::to_writer };
16 use serde::{ Deserialize, Serialize };
17 use serde_json::Value;
18
19 // A generic result of type 'T'.
20 type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
21
22 #[derive(Debug)]
23 struct Error {
24 message: String
25 }
26
27 impl std::fmt::Display for Error {
28 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29 write!(f, "Error: {}", &self.message)
30 }
31 }
32
33 impl std::error::Error for Error { }
34
35 #[derive(Debug, Deserialize, Serialize)]
36 struct Config {
37 delay_between_check: time::Duration,
38 api_key: String,
39 domains: Vec<String>,
40 }
41
42 impl Config {
43 fn default() -> Self {
44 Config { delay_between_check: time::Duration::from_secs(60), api_key: String::from(""), domains: Vec::new() }
45 }
46
47 fn read(file_path: &str) -> Result<Config> {
48 match File::open(file_path) {
49 Ok(file) => from_reader(file).map_err(|e| e.into()),
50 // The file doesn't exit -> create it with default values.
51 Err(_) => {
52 let file = File::create(file_path)?;
53 let default_config = Config::default();
54 to_writer(file, &default_config)?;
55 Ok(default_config)
56 }
57 }
58 }
59 }
60
61 const FILE_CONF: &str = "config.ron";
62
63 fn main() -> Result<()> {
64 println!("GANDI DynDNS");
65
66 let config = Config::read(FILE_CONF)?;
67
68 println!("Configuration: {:?}", config);
69
70 loop {
71 let time_beginning_loop = time::Instant::now();
72
73 if let Err(err) = check_and_update_dns(&config.api_key, &config.domains) {
74 println!("!! Error: {}", err);
75 }
76
77 let elapsed = time::Instant::now() - time_beginning_loop;
78
79 if elapsed < config.delay_between_check {
80 let to_wait = config.delay_between_check - elapsed;
81 thread::sleep(to_wait);
82 }
83 }
84 }
85
86 fn check_and_update_dns(api_key: &str, domains: &Vec<String>) -> Result<()> {
87 let real_ip = get_real_ip()?;
88 dbg!(&real_ip);
89
90 for domain in domains {
91 let current_ip = get_current_record_ip(api_key, domain)?;
92 dbg!(domain, current_ip);
93
94 if real_ip != current_ip {
95 println!("IP addresses don't match for domain {}: real = {}, dns = {}. Renewing DNS...", domain, real_ip, current_ip);
96 update_record_ip()?;
97 println!("Renewing of {} successfully", domain);
98 }
99 }
100
101 Ok(())
102 }
103
104 fn get_real_ip() -> Result<Ipv4Addr> {
105
106 let url = "https://api.ipify.org";
107 let client = reqwest::blocking::Client::new();
108
109 match client.get(url).send() {
110 Ok(resp) =>
111 if resp.status().is_success() {
112 let content = resp.text().unwrap();
113 match content.parse::<IpAddr>() {
114 Ok(IpAddr::V4(ip_v4)) => Ok(ip_v4),
115 _ => Err(Box::new(Error { message: String::from("Can't parse IPv4 from ipify") }))
116 }
117 } else {
118 Err(Box::new(Error { message: format!("Request unsuccessful: {:#?}", resp) }))
119 },
120
121 Err(error) => {
122 Err(Box::new(Error { message: format!("Error during request: {:?}", error) }))
123 }
124 }
125 }
126
127 fn request_livedns_gandi(api_key: &str, url_fragment: &str) -> Result<Value> {
128 let url = format!("https://api.gandi.net/v5/livedns/{}", url_fragment);
129 let client = reqwest::blocking::Client::new();
130
131 match client.get(url).header("Authorization", format!("Apikey {}", api_key)).send() {
132 Ok(resp) =>
133 if resp.status().is_success() {
134 let content = resp.text().unwrap();
135 Ok(serde_json::from_str(&content).unwrap())
136 } else {
137 Err(Box::new(Error { message: format!("Request unsuccessful: {:#?}", resp) }))
138 },
139 Err(error) =>
140 Err(Box::new(Error { message: format!("Error during request: {:?}", error) }))
141 }
142 }
143
144 fn get_current_record_ip(api_key: &str, name: &str) -> Result<Ipv4Addr> {
145 let json_value = request_livedns_gandi(api_key, &format!("domains/euphorik.ch/records/{}/A", name))?;
146
147 match &json_value["rrset_values"][0] {
148 Value::String(ip_str) =>
149 Ok(ip_str.parse()?),
150 _ =>
151 Result::Err(Box::new(Error { message: format!("Unable to extract the IP from the JSON answer: {}", json_value) }))
152 }
153 }
154
155 fn update_record_ip() -> Result<()> {
156 // TODO.
157 Ok(())
158 }