cloudflare-dns-updater/src/main.rs

293 lines
7.8 KiB
Rust
Raw Normal View History

use cloudflare::{Instance, CloudflareDnsType};
2023-02-26 00:10:39 +00:00
use reqwest::blocking::get;
use serde_derive::{Deserialize, Serialize};
use std::{fs, thread::{sleep}};
use chrono::{Utc, Duration};
2023-02-26 00:10:39 +00:00
mod cloudflare;
fn default_key() -> String {
return "".to_string();
}
#[derive(Clone)]
struct ChangeTracker {
created: u16,
updated: u16,
unchanged: u16,
error: u16
}
impl ChangeTracker {
fn new() -> ChangeTracker {
ChangeTracker {
created: 0,
updated: 0,
unchanged: 0,
error: 0
}
}
fn print(&self, f: &str) {
match f {
"" => {
self.print("simple");
}
"simple" => {
println!("{} created", self.created);
println!("{} updated", self.updated);
println!("{} unchanged", self.unchanged);
println!("{} errors", self.error);
}
&_ => {
println!("unknown format pattern '{}', defaulting to 'simple'", f);
self.print("simple");
}
}
}
}
2023-02-26 00:10:39 +00:00
#[derive(Serialize, Deserialize)]
struct DnsEntry {
name: String,
type4: bool,
type6: bool,
interface: Option<String>,
2023-02-26 00:10:39 +00:00
}
impl DnsEntry {
2023-02-27 15:15:00 +00:00
fn update(
&self,
change4: &mut ChangeTracker,
change6: &mut ChangeTracker,
agent: &Instance,
ips: &Ips,
zone: &DnsZone
) {
let mut found4 = false;
let mut found6 = false;
for cloudflare_entry in &agent.dns_entries {
// Update IPv4 Entry
if cloudflare_entry.is_equal(&self.name) {
found4 = true;
if cloudflare_entry.r#type == CloudflareDnsType::A && self.type4 {
let success = agent.update_entry(cloudflare_entry, &ips.ipv4);
2023-02-27 15:15:00 +00:00
if cloudflare_entry.is_ip_new(&ips.ipv4) {
if success {
change4.updated += 1;
}
else {
change4.error += 1;
}
}
else {
2023-02-27 15:15:00 +00:00
change4.unchanged += 1;
}
}
2023-02-27 15:15:00 +00:00
// Update IPv6 Entry
else if cloudflare_entry.r#type == CloudflareDnsType::AAAA && self.type6 {
found6 = true;
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
}
}
else {
2023-02-27 15:15:00 +00:00
change6.unchanged += 1;
}
}
2023-02-27 15:15:00 +00:00
// ignore otherwise
else {}
}
2023-02-27 15:15:00 +00:00
}
2023-02-27 15:15:00 +00:00
if !found4 && self.type4 {
let success = agent.create_entry(&zone.id, "A", &self.name, &ips.ipv4);
if success {
change4.created += 1;
}
2023-02-27 15:15:00 +00:00
else {
change4.error += 1;
};
}
2023-02-27 15:15:00 +00:00
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;
}
2023-02-27 15:15:00 +00:00
else {
change6.error += 1;
};
}
}
}
2023-02-26 00:10:39 +00:00
#[derive(Serialize, Deserialize)]
struct DnsZone {
email: String,
name: String,
id: String,
dns_entries: Vec<DnsEntry>,
2023-02-26 00:10:39 +00:00
}
impl DnsZone {
fn update(&self, change4: &mut ChangeTracker, change6: &mut ChangeTracker, ips: &Ips, config: &DnsConfig ) {
let mut agent = Instance::new(&config.api_key);
agent.load_entries(&self.email, &self.id);
for entry in &self.dns_entries {
2023-02-27 15:15:00 +00:00
entry.update(change4, change6, &agent, &ips, &self);
}
}
}
2023-02-26 00:10:39 +00:00
#[derive(Serialize, Deserialize)]
struct DnsConfig {
ipv6_interface: String,
#[serde(default = "default_key")]
2023-02-26 00:10:39 +00:00
api_key: String,
zones: Vec<DnsZone>,
2023-02-26 00:10:39 +00:00
}
impl DnsConfig {
fn new() -> DnsConfig {
DnsConfig {
ipv6_interface: "".to_string(),
2023-02-26 00:10:39 +00:00
api_key: "".to_string(),
zones: Vec::new(),
}
2023-02-26 00:10:39 +00:00
}
fn load(&mut self) {
let file_contents = match fs::read_to_string("config.json") {
Ok(data) => data,
Err(e) => panic!("{:#?}", e),
2023-02-26 00:10:39 +00:00
};
let config_parse: DnsConfig = match serde_json::from_str(&file_contents) {
Ok(data) => data,
Err(e) => panic!("{:#?}", e),
2023-02-26 00:10:39 +00:00
};
let key_file_contents = match fs::read_to_string("api-key.json") {
Ok(data) => data,
Err(e) => panic!("{:#?}", e),
};
let api_key_parse: serde_json::Value = match serde_json::from_str(&key_file_contents) {
Ok(data) => data,
Err(e) => panic!("{:#?}", e),
};
2023-02-26 00:10:39 +00:00
*self = config_parse;
self.api_key = api_key_parse["api_key"].as_str().unwrap().to_owned();
2023-02-26 00:10:39 +00:00
}
}
struct Ips {
ipv4: String,
ipv6base: String,
2023-02-26 00:10:39 +00:00
}
impl Ips {
fn new() -> Ips {
Ips {
ipv4: "0.0.0.0".to_string(),
ipv6base: ":".to_string(),
2023-02-26 00:10:39 +00:00
}
}
fn get(&mut self, ipv6_interface: &str) -> bool {
2023-02-26 00:10:39 +00:00
let ipv4uri = "https://am.i.mullvad.net/ip";
let ipv6uri = "https://ipv6.am.i.mullvad.net/ip";
let mut ret;
2023-02-26 00:10:39 +00:00
let response = get(ipv4uri);
2023-02-26 00:10:39 +00:00
match response {
Ok(data) => {
self.ipv4 = data.text().expect("0.0.0.0").trim_end().to_owned();
ret = true;
},
Err(_e) => {
println!("Could not fetch IPv4");
ret = false;
}
2023-02-26 00:10:39 +00:00
}
let response = get(ipv6uri);
match response {
Ok(data) => {
2023-02-27 02:20:45 +00:00
let ipv6 = match data.text() {
Ok(ip) => {ip},
Err(_) => {panic!("Expected IP, found none")},
};
let stripped = match ipv6.trim_end().strip_suffix(ipv6_interface) {
Some(string) => string.to_string(),
None => ":".to_string(),
2023-02-26 00:10:39 +00:00
};
self.ipv6base = stripped;
ret = true && ret; // Only set ret to true if previous ret is also true
}
Err(_e) => {
println!("Could not fetch IPv6");
ret = false;
}
2023-02-26 00:10:39 +00:00
}
return ret;
2023-02-26 00:10:39 +00:00
}
}
fn update_dns() {
2023-02-26 00:10:39 +00:00
let mut config = DnsConfig::new();
config.load();
let mut ips = Ips::new();
if ips.get(&config.ipv6_interface) {
let mut change4 = ChangeTracker::new();
2023-02-26 00:10:39 +00:00
let mut change6 = ChangeTracker::new();
2023-02-26 00:10:39 +00:00
// Iterator does not work here
for zone in &config.zones {
zone.update(&mut change4, &mut change6, &ips, &config)
2023-02-26 00:10:39 +00:00
}
println!("++++A Records+++");
change4.print("simple");
println!("++AAAA Records++");
change6.print("simple")
2023-02-26 00:10:39 +00:00
}
}
fn main() {
let mut now = Utc::now() - Duration::seconds(59);
let mut current = now;
println!("Initial Time is {} {}", now.format("%H:%M:%S"), now.timezone());
loop {
now = Utc::now();
if now >= current + Duration::seconds(60) {
current = now;
println!("Starting DNS Update at {} {}", now.format("%H:%M:%S"), now.timezone());
update_dns();
}
else {
sleep(std::time::Duration::from_millis(500));
}
}
2023-02-26 00:10:39 +00:00
}