280b718b1533746a9c9ac6bbe25db418705bdc40
[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::{ 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, json };
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, Clone, Deserialize, Serialize)]
36 struct Config {
37 delay_between_check: time::Duration,
38 api_key: String,
39 fqdn: String,
40 domains: Vec<String>,
41 ttl: i32
42 }
43
44 impl Config {
45 fn default() -> Self {
46 Config { delay_between_check: time::Duration::from_secs(120), api_key: String::from(""), fqdn: String::from(""), domains: Vec::new(), ttl: 300 }
47 }
48
49 fn read(file_path: &str) -> Result<Config> {
50 match File::open(file_path) {
51 Ok(file) => from_reader(file).map_err(|e| e.into()),
52 // The file doesn't exit -> create it with default values.
53 Err(_) => {
54 let file = File::create(file_path)?;
55 let default_config = Config::default();
56 to_writer(file, &default_config)?;
57 Ok(default_config)
58 }
59 }
60 }
61 }
62
63 const FILE_CONF: &str = "config.ron";
64
65 fn main() -> Result<()> {
66
67 println!("GANDI DynDNS");
68
69 let config = Config::read(FILE_CONF)?;
70
71 println!("Configuration: {:?}", Config { api_key: String::from("*****"), ..config.clone() });
72
73 loop {
74 let time_beginning_loop = time::Instant::now();
75
76 if let Err(err) = check_and_update_dns(&config.api_key, &config.fqdn, &config.domains, config.ttl) {
77 println!("!! Error: {}", err);
78 }
79
80 let elapsed = time::Instant::now() - time_beginning_loop;
81
82 if elapsed < config.delay_between_check {
83 let to_wait = config.delay_between_check - elapsed;
84 thread::sleep(to_wait);
85 }
86 }
87 }
88
89 fn check_and_update_dns(api_key: &str, fqdn: &str, domains: &Vec<String>, ttl: i32) -> Result<()> {
90 let real_ip = get_real_ip()?;
91
92 for domain in domains {
93 let current_ip = get_current_record_ip(api_key, domain, fqdn)?;
94
95 if real_ip != current_ip {
96 println!("IP addresses don't match for domain {}: real = {}, dns = {}. Renewing DNS...", domain, real_ip, current_ip);
97 update_record_ip(api_key, domain, fqdn, real_ip, ttl)?;
98 println!("Renewing of {} successfully", domain);
99 }
100 }
101
102 Ok(())
103 }
104
105 fn get_real_ip() -> Result<Ipv4Addr> {
106
107 let url = "https://api.ipify.org";
108 let client = reqwest::blocking::Client::new();
109
110 match client.get(url).send() {
111 Ok(resp) =>
112 if resp.status().is_success() {
113 let content = resp.text().unwrap();
114 match content.parse::<IpAddr>() {
115 Ok(IpAddr::V4(ip_v4)) => Ok(ip_v4),
116 _ => Err(Box::new(Error { message: String::from("Can't parse IPv4 from ipify") }))
117 }
118 } else {
119 Err(Box::new(Error { message: format!("Request unsuccessful: {:#?}", resp) }))
120 },
121
122 Err(error) => {
123 Err(Box::new(Error { message: format!("Error during request: {:?}", error) }))
124 }
125 }
126 }
127
128 enum Method {
129 Put(String),
130 Get
131 }
132
133 fn request_livedns_gandi(api_key: &str, url_fragment: &str, method: Method) -> Result<Value> {
134 let url = format!("https://api.gandi.net/v5/livedns/{}", url_fragment);
135 let client = reqwest::blocking::Client::new();
136
137 let request_builder =
138 match method {
139 Method::Put(body) => client.put(url).body(body),
140 Method::Get => client.get(url)
141 };
142
143 match request_builder.header("Authorization", format!("Apikey {}", api_key)).send() {
144 Ok(resp) =>
145 if resp.status().is_success() {
146 let content = resp.text().unwrap();
147 Ok(serde_json::from_str(&content).unwrap())
148 } else {
149 Err(Box::new(Error { message: format!("Request unsuccessful: {:#?}", resp) }))
150 },
151 Err(error) =>
152 Err(Box::new(Error { message: format!("Error during request: {:?}", error) }))
153 }
154 }
155
156 fn get_current_record_ip(api_key: &str, name: &str, fqdn: &str) -> Result<Ipv4Addr> {
157 let json_value = request_livedns_gandi(api_key, &format!("domains/{}/records/{}/A", fqdn, name), Method::Get)?;
158
159 match &json_value["rrset_values"][0] {
160 Value::String(ip_str) =>
161 Ok(ip_str.parse()?),
162 _ =>
163 Result::Err(Box::new(Error { message: format!("Unable to extract the IP from the JSON answer: {}", json_value) }))
164 }
165 }
166
167 fn update_record_ip(api_key: &str, name: &str, fqdn: &str, ip: Ipv4Addr, ttl: i32) -> Result<()> {
168 let json_body =
169 json!(
170 {
171 "rrset_values": [ format!("{}", ip) ],
172 "rrset_ttl": ttl
173 }
174 );
175
176 let json_value = request_livedns_gandi(api_key, &format!("domains/{}/records/{}/A", fqdn, name), Method::Put(json_body.to_string()))?;
177
178 Ok(())
179 }