Added Error handling, switched to using "Result" type for many methods
This commit is contained in:
parent
f4c9e39b26
commit
ef94aacc51
2 changed files with 212 additions and 105 deletions
|
@ -1,6 +1,6 @@
|
|||
use reqwest::{blocking::{Response, Client}, Url};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use reqwest::header::{HeaderMap, HeaderValue};
|
||||
use reqwest::{Error, header::{HeaderMap, HeaderValue}};
|
||||
use std::{string::String, collections::HashMap};
|
||||
use strum_macros::{Display, IntoStaticStr};
|
||||
|
||||
|
@ -64,19 +64,29 @@ impl Instance {
|
|||
///
|
||||
/// * `email` : E-Mail Address associated with the Zone, required for [`generate_headers()`]
|
||||
/// * `zone_id` : Zone to be used for the Request
|
||||
pub fn load_entries(&mut self, email: &String, zone_id: &String) {
|
||||
/// * `return` : Returns true if a recoverable Error was encountered, true otherwise
|
||||
pub fn load_entries(&mut self, email: &String, zone_id: &String) -> Result<(), Error> {
|
||||
self.dns_email = email.clone();
|
||||
let endpoint = format!("{}zones/{}/dns_records", API_BASE, zone_id);
|
||||
|
||||
let api_response = self.get(&endpoint);
|
||||
let entries = match api_response.json::<CloudflareDnsZone>() {
|
||||
Ok(data) => {data},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
match self.get(&endpoint) {
|
||||
Ok(response) => {
|
||||
let entries = match response
|
||||
.json::<CloudflareDnsZone>() {
|
||||
Ok(data) => {data},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
for entry in entries.result {
|
||||
self.dns_entries.append(&mut vec!(entry));
|
||||
for entry in entries.result {
|
||||
self.dns_entries.append(&mut vec!(entry));
|
||||
}
|
||||
|
||||
return Ok(())
|
||||
},
|
||||
Err(e) => { return Err(e) }
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// Shorthand for Cloudflare API Requests
|
||||
|
@ -84,67 +94,77 @@ impl Instance {
|
|||
/// Automatically appends Auth Headers and parses the URL
|
||||
///
|
||||
/// * `url` : URL for the request, will be parsed to [`Url`]
|
||||
/// * `email` : E-Mail Address associated with the Zone, required for [`generate_headers()`]
|
||||
fn get(&self, url: &str) -> Response {
|
||||
fn get(&self, url: &str) -> Result<Response, Error> {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
Err(e) => panic!("{:#?}", e) // If this call fails the API changed
|
||||
}; // Continuing without a code update is not possible
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.get(url_parsed)
|
||||
let result = match Client::new()
|
||||
.get(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
.send() {
|
||||
Ok(res) => { Ok(res) },
|
||||
Err(e) => { Err(e) }
|
||||
};
|
||||
|
||||
response
|
||||
return result;
|
||||
}
|
||||
|
||||
fn put(&self, url: &str, data: &HashMap<&str, &str>) -> Response {
|
||||
/// Shorthand for Cloudflare API Requests
|
||||
///
|
||||
/// Automatically appends Auth Headers and parses the URL
|
||||
///
|
||||
/// * `url` : URL for the request, will be parsed to [`Url`]
|
||||
/// * `data` : PUT request body
|
||||
fn put(&self, url: &str, data: &HashMap<&str, &str>) -> Result<Response, Error> {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
Err(e) => panic!("{:#?}", e)// If this call fails the API changed
|
||||
}; // Continuing without a code update is not possible
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.put(url_parsed)
|
||||
let result = match Client::new()
|
||||
.put(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.json(data)
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
.send() {
|
||||
Ok(res) => { Ok(res) },
|
||||
Err(e) => { Err(e) }
|
||||
};
|
||||
|
||||
response
|
||||
return result;
|
||||
}
|
||||
|
||||
fn post(&self, url: &str, data: &HashMap<&str, &str>) -> Response {
|
||||
/// Shorthand for Cloudflare API Requests
|
||||
///
|
||||
/// Automatically appends Auth Headers and parses the URL
|
||||
///
|
||||
/// * `url` : URL for the request, will be parsed to [`Url`]
|
||||
/// * `data` : POST request body
|
||||
fn post(&self, url: &str, data: &HashMap<&str, &str>) -> Result<Response, Error> {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
Err(e) => panic!("{:#?}", e) // If this call fails the API changed
|
||||
}; // Continuing without a code update is not possible
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.post(url_parsed)
|
||||
let result = match Client::new()
|
||||
.post(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.json(data)
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
.send() {
|
||||
Ok(res) => { Ok(res) },
|
||||
Err(e) => { Err(e) }
|
||||
};
|
||||
|
||||
response
|
||||
return result;
|
||||
}
|
||||
|
||||
pub fn update_entry(&self, entry: &CloudflareDnsEntry, new_ip: &String) -> bool {
|
||||
/// Updates the given DNS entry with the given IP
|
||||
///
|
||||
/// * `entry` : DNS entry to update
|
||||
/// * `new_ip` : IP used to Update the DNS entry, can be IPv4 or IPv6
|
||||
/// * `return1` : Returns success of the API call, extracted from the HTTP Response body
|
||||
pub fn update_entry(&self, entry: &CloudflareDnsEntry, new_ip: &String) -> Result<bool, Error> {
|
||||
let endpoint = format!("{}zones/{}/dns_records/{}", API_BASE, entry.zone_id, entry.id);
|
||||
|
||||
let mut json_body = HashMap::new();
|
||||
|
@ -153,16 +173,22 @@ impl Instance {
|
|||
json_body.insert("content", new_ip);
|
||||
json_body.insert("ttl", "1");
|
||||
|
||||
let api_response = self.put(&endpoint, &json_body);
|
||||
match self.put(&endpoint, &json_body) {
|
||||
Ok(response) => {
|
||||
let data = response
|
||||
.json::<serde_json::Value>()
|
||||
.expect("Response should always be valid JSON");
|
||||
|
||||
let data = api_response.json::<serde_json::Value>().unwrap();
|
||||
|
||||
let ret = data["success"].as_bool().unwrap();
|
||||
|
||||
ret
|
||||
let success = data["success"]
|
||||
.as_bool()
|
||||
.expect("JSON should always include success bool");
|
||||
return Ok(success);
|
||||
},
|
||||
Err(e) => { return Err(e) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_entry(&self, zone_id: &String, r#type: &str, name: &str, ip: &String) -> bool {
|
||||
pub fn create_entry(&self, zone_id: &String, r#type: &str, name: &str, ip: &String) -> Result<bool, Error> {
|
||||
let endpoint = format!("{}zones/{}/dns_records", API_BASE, zone_id);
|
||||
|
||||
let mut json_body = HashMap::new();
|
||||
|
@ -171,13 +197,20 @@ impl Instance {
|
|||
json_body.insert("content", ip);
|
||||
json_body.insert("ttl", "1");
|
||||
|
||||
let api_response = self.post(&endpoint, &json_body);
|
||||
match self.post(&endpoint, &json_body) {
|
||||
Ok(response) => {
|
||||
let data = response
|
||||
.json::<serde_json::Value>()
|
||||
.expect("Response should always be valid JSON");
|
||||
|
||||
let data = api_response.json::<serde_json::Value>().unwrap();
|
||||
let success = data["success"]
|
||||
.as_bool()
|
||||
.expect("JSON should always include success bool");
|
||||
|
||||
let ret = data["success"].as_bool().unwrap();
|
||||
|
||||
ret
|
||||
return Ok(success)
|
||||
},
|
||||
Err(e) => { return Err(e) },
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate Cloudflare API v4 Auth Headers
|
||||
|
|
168
src/main.rs
168
src/main.rs
|
@ -55,31 +55,46 @@ struct DnsEntry {
|
|||
}
|
||||
|
||||
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,
|
||||
agent: &Instance,
|
||||
ips: &Ips,
|
||||
zone: &DnsZone
|
||||
) {
|
||||
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 {
|
||||
// Update IPv4 Entry
|
||||
if cloudflare_entry.is_equal(&self.name) {
|
||||
found4 = true;
|
||||
// Update IPv4 Entry
|
||||
if cloudflare_entry.r#type == CloudflareDnsType::A && self.type4 {
|
||||
let success = agent.update_entry(cloudflare_entry, &ips.ipv4);
|
||||
found4 = true;
|
||||
|
||||
if cloudflare_entry.is_ip_new(&ips.ipv4) {
|
||||
if success {
|
||||
change4.updated += 1;
|
||||
}
|
||||
else {
|
||||
change4.error += 1;
|
||||
}
|
||||
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;
|
||||
|
@ -91,13 +106,17 @@ impl DnsEntry {
|
|||
let ipv6 = ips.ipv6base.clone() + self.interface.as_ref().unwrap();
|
||||
|
||||
if cloudflare_entry.is_ip_new(&ipv6) {
|
||||
let success = agent.update_entry(cloudflare_entry, &ipv6);
|
||||
if success {
|
||||
change6.updated += 1
|
||||
}
|
||||
else {
|
||||
change6.error += 1
|
||||
}
|
||||
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;
|
||||
|
@ -109,25 +128,35 @@ impl DnsEntry {
|
|||
}
|
||||
|
||||
if !found4 && self.type4 {
|
||||
let success = agent.create_entry(&zone.id, "A", &self.name, &ips.ipv4);
|
||||
if success {
|
||||
change4.created += 1;
|
||||
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
|
||||
}
|
||||
else {
|
||||
change4.error += 1;
|
||||
};
|
||||
}
|
||||
|
||||
if !found6 && self.type6 {
|
||||
let ipv6 = ips.ipv6base.clone() + self.interface.as_ref().unwrap();
|
||||
let success = agent.create_entry(&zone.id, "AAAA", &self.name, &ipv6);
|
||||
if success {
|
||||
change6.created += 1;
|
||||
}
|
||||
else {
|
||||
change6.error += 1;
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -140,13 +169,40 @@ struct DnsZone {
|
|||
}
|
||||
|
||||
impl DnsZone {
|
||||
fn update(&self, change4: &mut ChangeTracker, change6: &mut ChangeTracker, ips: &Ips, config: &DnsConfig ) {
|
||||
let mut agent = Instance::new(&config.api_key);
|
||||
/// 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);
|
||||
|
||||
agent.load_entries(&self.email, &self.id);
|
||||
match agent.load_entries(&self.email, &self.id) {
|
||||
Ok(_) => {
|
||||
let mut results = Vec::<bool>::new();
|
||||
|
||||
for entry in &self.dns_entries {
|
||||
entry.update(change4, change6, &agent, &ips, &self);
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -205,14 +261,16 @@ impl Ips {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
|
||||
let response = get(ipv4uri);
|
||||
|
||||
match response {
|
||||
match get(ipv4uri) {
|
||||
Ok(data) => {
|
||||
self.ipv4 = data.text().expect("0.0.0.0").trim_end().to_owned();
|
||||
ret = true;
|
||||
|
@ -220,12 +278,12 @@ impl Ips {
|
|||
Err(_e) => {
|
||||
println!("Could not fetch IPv4");
|
||||
ret = false;
|
||||
|
||||
return ret; // Early return since a fail on IPv4 means a likely fail on IPv6
|
||||
}
|
||||
}
|
||||
|
||||
let response = get(ipv6uri);
|
||||
|
||||
match response {
|
||||
match get(ipv6uri) {
|
||||
Ok(data) => {
|
||||
let ipv6 = match data.text() {
|
||||
Ok(ip) => {ip},
|
||||
|
@ -248,25 +306,41 @@ impl Ips {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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::<bool>::new();
|
||||
|
||||
// Iterator does not work here
|
||||
for zone in &config.zones {
|
||||
zone.update(&mut change4, &mut change6, &ips, &config)
|
||||
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")
|
||||
}
|
||||
|
||||
println!("++++A Records+++");
|
||||
change4.print("simple");
|
||||
println!("++AAAA Records++");
|
||||
change6.print("simple")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue