Rewrite in Rust
This commit is contained in:
parent
331f0c092c
commit
e76c82492f
5 changed files with 1402 additions and 0 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -1,4 +1,6 @@
|
|||
# Default ignores
|
||||
target/
|
||||
venv/
|
||||
.idea/
|
||||
.vscode/
|
||||
config.json
|
||||
|
|
1021
Cargo.lock
generated
Normal file
1021
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
13
Cargo.toml
Normal file
13
Cargo.toml
Normal file
|
@ -0,0 +1,13 @@
|
|||
[package]
|
||||
name = "cloudflare-dns-updater"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
reqwest = { version = "0.11.14", features = ["blocking", "json"] }
|
||||
serde = "1.0.152"
|
||||
serde_derive = "1.0.152"
|
||||
serde_json = "1.0.93"
|
||||
strum_macros = "0.24.3"
|
191
src/cloudflare/mod.rs
Normal file
191
src/cloudflare/mod.rs
Normal file
|
@ -0,0 +1,191 @@
|
|||
use reqwest::{blocking::{Response, Client}, Url};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use reqwest::header::{HeaderMap, HeaderValue};
|
||||
use std::{string::String, collections::HashMap};
|
||||
use strum_macros::{Display, IntoStaticStr};
|
||||
|
||||
const API_BASE: &str = "https://api.cloudflare.com/client/v4/";
|
||||
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct CloudflareDnsZone {
|
||||
result: Vec<CloudflareDnsEntry>,
|
||||
success: bool
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy)]
|
||||
#[derive(Display, IntoStaticStr)]
|
||||
pub enum CloudflareDnsType {
|
||||
#[strum(serialize = "A")]
|
||||
A,
|
||||
#[strum(serialize = "AAAA")]
|
||||
AAAA,
|
||||
TXT,
|
||||
MX
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct CloudflareDnsEntry {
|
||||
id: String,
|
||||
zone_id: String,
|
||||
pub name: String,
|
||||
pub r#type: CloudflareDnsType,
|
||||
content: String,
|
||||
proxied: bool
|
||||
}
|
||||
|
||||
impl CloudflareDnsEntry {
|
||||
pub fn is_equal(&self, other_entry: &String) -> bool {
|
||||
return if &self.name == other_entry { true } else { false };
|
||||
}
|
||||
|
||||
pub fn is_ip_new(&self, other_entry: &String) -> bool {
|
||||
return if &self.content == other_entry { false } else { true };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub(crate) struct Instance {
|
||||
api_key: String,
|
||||
pub dns_entries: Vec<CloudflareDnsEntry>,
|
||||
dns_email: String
|
||||
}
|
||||
|
||||
impl Instance {
|
||||
pub fn new(key: &String) -> Instance {
|
||||
Instance {
|
||||
api_key: key.clone(),
|
||||
dns_entries: Vec::new(),
|
||||
dns_email: "".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all DNS entires in a Zone as a [`CloudflareDnsEntry`] Vector
|
||||
///
|
||||
/// * `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) {
|
||||
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)
|
||||
};
|
||||
|
||||
for entry in entries.result {
|
||||
self.dns_entries.append(&mut vec!(entry));
|
||||
}
|
||||
}
|
||||
|
||||
/// Shorthand for Cloudflare API Requests
|
||||
///
|
||||
/// 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 {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.get(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
fn put(&self, url: &str, data: &HashMap<&str, &str>) -> Response {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.put(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.json(data)
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
fn post(&self, url: &str, data: &HashMap<&str, &str>) -> Response {
|
||||
let url_parsed = match Url::parse(url) {
|
||||
Ok(url) => {url},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
let client = Client::new();
|
||||
let res = client.post(url_parsed)
|
||||
.headers(self.generate_headers())
|
||||
.json(data)
|
||||
.send();
|
||||
|
||||
let response = match res {
|
||||
Ok(res) => {res},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
pub fn update_entry(&self, entry: &CloudflareDnsEntry, new_ip: &String) -> bool {
|
||||
let endpoint = format!("{}zones/{}/dns_records/{}", API_BASE, entry.zone_id, entry.id);
|
||||
|
||||
let mut json_body = HashMap::new();
|
||||
json_body.insert("type", entry.r#type.clone().into());
|
||||
json_body.insert("name", entry.name.as_ref());
|
||||
json_body.insert("content", new_ip);
|
||||
json_body.insert("ttl", "1");
|
||||
|
||||
let api_response = self.put(&endpoint, &json_body);
|
||||
|
||||
let data = api_response.json::<serde_json::Value>().unwrap();
|
||||
|
||||
let ret = data["success"].as_bool().unwrap();
|
||||
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn create_entry(&self, zone_id: &String, r#type: &str, name: &str, ip: &String) -> bool {
|
||||
let endpoint = format!("{}zones/{}/dns_records", API_BASE, zone_id);
|
||||
|
||||
let mut json_body = HashMap::new();
|
||||
json_body.insert("type", r#type);
|
||||
json_body.insert("name", name);
|
||||
json_body.insert("content", ip);
|
||||
json_body.insert("ttl", "1");
|
||||
|
||||
let api_response = self.post(&endpoint, &json_body);
|
||||
|
||||
let data = api_response.json::<serde_json::Value>().unwrap();
|
||||
|
||||
let ret = data["success"].as_bool().unwrap();
|
||||
|
||||
ret
|
||||
}
|
||||
|
||||
/// Generate Cloudflare API v4 Auth Headers
|
||||
fn generate_headers(&self) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("X-Auth-Key", HeaderValue::from_str(self.api_key.as_ref()).unwrap());
|
||||
headers.insert("X-Auth-Email", HeaderValue::from_str(self.dns_email.as_ref()).unwrap());
|
||||
headers
|
||||
}
|
||||
|
||||
}
|
175
src/main.rs
Normal file
175
src/main.rs
Normal file
|
@ -0,0 +1,175 @@
|
|||
use serde_derive::{Deserialize, Serialize};
|
||||
use reqwest::blocking::get;
|
||||
use std::fs;
|
||||
mod cloudflare;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct DnsEntry {
|
||||
name: String,
|
||||
type4: bool,
|
||||
type6: bool,
|
||||
interface: Option<String>
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct DnsZone {
|
||||
email: String,
|
||||
name: String,
|
||||
id: String,
|
||||
dns_entries: Vec<DnsEntry>
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct DnsConfig {
|
||||
ipv6_interface: String,
|
||||
api_key: String,
|
||||
zones: Vec<DnsZone>
|
||||
}
|
||||
|
||||
impl DnsConfig {
|
||||
fn new() -> DnsConfig {
|
||||
DnsConfig {
|
||||
ipv6_interface: "".to_string(),
|
||||
api_key: "".to_string(),
|
||||
zones: Vec::new() }
|
||||
}
|
||||
|
||||
fn load(&mut self) {
|
||||
let file_contents = match fs::read_to_string("config.json") {
|
||||
Ok(data) => {data},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
let config_parse: DnsConfig = match serde_json::from_str(&file_contents) {
|
||||
Ok(data) => {data},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
};
|
||||
*self = config_parse;
|
||||
}
|
||||
}
|
||||
|
||||
struct Ips {
|
||||
ipv4: String,
|
||||
ipv6base: String
|
||||
}
|
||||
|
||||
impl Ips {
|
||||
fn new() -> Ips {
|
||||
Ips {
|
||||
ipv4: "0.0.0.0".to_string(),
|
||||
ipv6base: ":".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&mut self, ipv6_interface: &str) {
|
||||
let ipv4uri = "https://am.i.mullvad.net/ip";
|
||||
let ipv6uri = "https://ipv6.am.i.mullvad.net/ip";
|
||||
|
||||
let response = get(ipv4uri);
|
||||
|
||||
match response {
|
||||
Ok(data) => self.ipv4 = data.text().expect("0.0.0.0").trim_end().to_owned(),
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
}
|
||||
|
||||
let response = get(ipv6uri);
|
||||
|
||||
match response {
|
||||
Ok(data) => {
|
||||
let ipv6 = data.text().expect(":");
|
||||
let stripped = match ipv6.strip_suffix(ipv6_interface) {
|
||||
Some(string) => {string.to_string()},
|
||||
None => {":".to_string()}
|
||||
};
|
||||
self.ipv6base = stripped;
|
||||
},
|
||||
Err(e) => panic!("{:#?}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
|
||||
let mut config = DnsConfig::new();
|
||||
config.load();
|
||||
|
||||
let mut ips = Ips::new();
|
||||
ips.get(&config.ipv6_interface);
|
||||
|
||||
let mut created4: u16 = 0;
|
||||
let mut updated4: u16 = 0;
|
||||
let mut unchanged4: u16 = 0;
|
||||
let mut error4: u16 = 0;
|
||||
|
||||
let mut created6: u16 = 0;
|
||||
let mut updated6: u16 = 0;
|
||||
let mut unchanged6: u16 = 0;
|
||||
let mut error6: u16 = 0;
|
||||
|
||||
for zone in config.zones {
|
||||
let mut agent = cloudflare::Instance::new(&config.api_key);
|
||||
|
||||
agent.load_entries(&zone.email, &zone.id);
|
||||
|
||||
|
||||
for entry in zone.dns_entries {
|
||||
let mut found4 = false;
|
||||
let mut found6 = false;
|
||||
|
||||
for cloudflare_entry in &agent.dns_entries {
|
||||
|
||||
if cloudflare_entry.is_equal(&entry.name) {
|
||||
if cloudflare_entry.r#type == cloudflare::CloudflareDnsType::A && entry.type4 {
|
||||
found4 = true;
|
||||
if cloudflare_entry.is_ip_new(&ips.ipv4) {
|
||||
let success = agent.update_entry(cloudflare_entry, &ips.ipv4);
|
||||
if success { updated4 += 1 } else { error4 += 1 }
|
||||
}
|
||||
else {
|
||||
unchanged4 += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if cloudflare_entry.r#type == cloudflare::CloudflareDnsType::AAAA && entry.type6 {
|
||||
found6 = true;
|
||||
let ipv6 = ips.ipv6base.clone() + entry.interface.as_ref().unwrap();
|
||||
|
||||
if cloudflare_entry.is_ip_new(&ipv6) {
|
||||
let success = agent.update_entry(cloudflare_entry, &ipv6);
|
||||
if success { updated6 += 1 } else { error6 += 1 }
|
||||
}
|
||||
else {
|
||||
unchanged6 += 1;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//println!("{:#?}", entry.subdomain); // DEBUG
|
||||
}
|
||||
|
||||
if !found4 && entry.type4 {
|
||||
let success = agent.create_entry(&zone.id, "A", &entry.name, &ips.ipv4);
|
||||
if success { created4 += 1 };
|
||||
}
|
||||
|
||||
if !found6 && entry.type6 {
|
||||
let ipv6 = ips.ipv6base.clone() + entry.interface.as_ref().unwrap();
|
||||
let success = agent.create_entry(&zone.id, "AAAA", &entry.name, &ipv6);
|
||||
if success { created6 += 1 };
|
||||
}
|
||||
}
|
||||
|
||||
//println!("{:#?}", zone.domain); // DEBUG
|
||||
}
|
||||
println!("++++A Records+++");
|
||||
println!("{} created", created4);
|
||||
println!("{} updated", updated4);
|
||||
println!("{} unchanged", unchanged4);
|
||||
println!("{} errors", error4);
|
||||
println!("++AAAA Records++");
|
||||
println!("{} created", created6);
|
||||
println!("{} updated", updated6);
|
||||
println!("{} unchanged", unchanged6);
|
||||
println!("{} errors", error6);
|
||||
|
||||
}
|
Loading…
Reference in a new issue