Merge pull request '1.0.0 Rework' (#25) from v2 into main
All checks were successful
Run Tests on Code / run-tests (push) Successful in 11s

Reviewed-on: #25
This commit is contained in:
Neshura 2023-12-27 20:26:16 +00:00
commit f0f32472eb
11 changed files with 1369 additions and 1027 deletions

View file

@ -5,17 +5,32 @@ on:
push:
tags:
- '[0-9]+.[0-9]+.[0-9]+'
- '[0-9]+.[0-9]+.[0-9]+rc[0-9]+'
- '[0-9]+.[0-9]+.[0-9]+-rc.[0-9]+'
jobs:
test:
runs-on: docker
container: forgejo.neshweb.net/ci-docker-images/rust-node:latest
steps:
-
name: Add Clippy
run: rustup component add clippy
-
name: Checking Out Repository Code
uses: https://code.forgejo.org/actions/checkout@v3
-
name: Placeholder
run: echo Placeholder Job
name: Set Up Cargo Cache
uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
-
name: Run Clippy
run: cargo clippy
-
name: Check if Version in Cargo.toml matches Tag
run: |
@ -31,11 +46,8 @@ jobs:
needs: test
if: success()
runs-on: docker
container: rust:latest
container: forgejo.neshweb.net/ci-docker-images/rust-node:latest
steps:
-
name: Installing Node
run: apt update && apt install -y nodejs
-
name: Checking Out Repository Code
uses: https://code.forgejo.org/actions/checkout@v3

View file

@ -10,7 +10,25 @@ on:
jobs:
run-tests:
runs-on: docker
container: forgejo.neshweb.net/ci-docker-images/rust-node:latest
steps:
-
name: Placeholder
run: echo Placeholder Job
name: Add Clippy
run: rustup component add clippy
-
name: Checking Out Repository Code
uses: https://code.forgejo.org/actions/checkout@v3
-
name: Set Up Cargo Cache
uses: actions/cache@v3
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
-
name: Run Clippy
run: cargo clippy

5
.gitignore vendored
View file

@ -3,4 +3,7 @@ target/
venv/
.idea/
.vscode/
api-key.json
/.env
/interfaces.toml
/zones.d

845
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,14 +1,20 @@
[package]
name = "cloudflare-dns-updater"
version = "0.2.8"
version = "1.0.0-rc.3"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
chrono = "0.4.23"
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"
chrono = "^0.4.23"
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"
log = "^0.4.20"
systemd-journal-logger = "^2.1.1"
confy = "^0.5.1"
dotenv = "^0.15.0"
ipnet = "^2.9.0"
url = "2.5.0"

View file

@ -1,72 +1,44 @@
# Cloudflare DNS Updater
## Create and activating a venv
Make sure Python 3.10 or higher is installed.
Use `cd` to change to the location of this repository.
Now, run
```
py -3.10 -m venv venv
```
Replace the `-3.10` with other Python versions if necessary (ex.: `-3.11`)
## Using the application
Activate the venv using the command
```
venv/scripts/activate
The application necessarily requires a valid Cloudflare API Token.
Further the application must be located in the same network as the configured zones.
| Environment Variable | Required | Usage |
|:--------------------:|:--------:|:----------------------------------:|
| CF_API_TOKEN | x | Cloudflare API Token |
| STATUS_POST_URL | | Post Endpoint for a Uptime Monitor |
*Note: Variables can be stored in a .env file*
The actual configuration happens in two or more files:
`interfaces.toml` contains all IPv6 interfaces available/used by the zone config files.
`.toml` files in `zone.d` contain settings for individual zones.
Example:
*interfaces.toml*
```toml
host_address = "::edcb:a098:7654:3210"
[[interface]]
name = "example-interface-1" # this is what a user inputs in the zone.toml
address = "::0123:4567:890a:bcde" # static part of the IP, the rest will be dynamically generated using the host
```
## Installing the required packages
*zone.d/example.org.toml*
```toml
email = "owner@example.org" # Email of User owning the Zone
zone = "example.org" # Zone Name
id = "01234567890abcdefghijklmnopqrstu" # Zone ID
Make sure the venv is activated.
Run the following command
```
pip install -r requirements.txt
[[entry]]
name = "example.org" # "@" Symbol is not currently supported
type = ["AAAA", "A"] # Options are: "A" (IPv4/A Record) and/or "AAAA" (IPv6/AAAA Record)
interface = "example-interface-1" # Only required on type values 6 and 10
```
Alternatively, the packages can be installed manually by using `pip install`.
The full list of packages needed:
- cloudflare (Version 2.0.0 or greater)
- Buildins:
- json
- configparser
- ipaddress
- sys
## Using the script
Before running the script, make sure there exists a `config.ini` file next to the `cloudflare_script.py`.
The config has to have the following structure:
```ini
[cloudflare]
TOKEN=<cloudflare api token>
[server]
HOSTNAME=hostname-of-website.com
```
Run the script using the following arguments:
```
python cloudflare_script.py <ipversion> <path/to/ip/list>
```
IP-Version can be 4 or 6.
The IP-List has to conform to the following structure and be a json file:
```json
{
"AAAA": [
"ipv6 site prefix"
],
"A": [
"ipv4 site prefix"
]
}
```
To only get the currently registered DNS records for a given API key, run
```
python cloudflare_script.py
```
THis will print all DNS records for the API key with name, ip, cloudflare id and ip-version
## Debian Repository
TODO!

View file

@ -1,3 +0,0 @@
{
"api_key": ""
}

358
src/cloudflare.rs Normal file
View file

@ -0,0 +1,358 @@
use std::collections::HashMap;
use std::env;
use std::env::VarError;
use std::error::Error;
use std::net::{Ipv4Addr, Ipv6Addr};
use log::{error, warn};
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::{Url};
use reqwest::blocking::{Response, Client};
use serde_derive::{Deserialize, Serialize};
use strum_macros::{Display, IntoStaticStr};
use systemd_journal_logger::connected_to_journal;
use url::ParseError;
use crate::config::{ZoneConfig, ZoneEntry};
const API_BASE: &str = "https://api.cloudflare.com/client/v4";
#[derive(Serialize, Deserialize, Debug)]
struct CloudflareApiResults {
result: Vec<CloudflareDnsRecord>,
success: bool,
}
#[derive(Serialize, Deserialize, Debug)]
struct CloudflareApiResult {
success: bool,
}
pub(crate) struct CloudflareZone {
email: String,
key: String,
id: String,
}
impl CloudflareZone {
pub(crate) fn new(zone: &ZoneConfig) -> Result<Self, VarError> {
let key = env::var("CF_API_TOKEN")?;
Ok(Self {
email: zone.email.clone(),
key,
id: zone.id.clone(),
})
}
fn generate_auth_headers(&self) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(
"X-Auth-Email",
HeaderValue::from_str(self.email.as_str()).expect("After CloudflareZone gets created the required Values should exist"),
);
headers.insert(
"X-Auth-Key",
HeaderValue::from_str(self.key.as_str()).expect("After CloudflareZone gets created the required Values should exist"),
);
headers
}
pub(crate) fn get_entries(&self) -> Result<Vec<CloudflareDnsRecord>, ()> {
let endpoint = format!("{}/zones/{}/dns_records", API_BASE, self.id);
match self.get(&endpoint) {
Ok(response) => {
if response.status().is_success() {
let entries = match response.json::<CloudflareApiResults>() {
Ok(data) => data,
Err(e) => {
let err_msg = format!("Unable to parse API response. Error: {e}");
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
return Err(())
}
};
Ok(entries.result)
} else {
let err_msg = format!("Unable to fetch Cloudflare Zone Entries. Error: {}", response.status());
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
}
Err(e) => {
let err_msg = format!("Unable to access Cloudflare API. Error: {e}");
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
},
}
}
pub(crate) fn update(&self, entry: &ZoneEntry, r#type: &DnsRecordType, id: &String, ipv6: Option<Ipv6Addr>, ipv4: Option<Ipv4Addr>) -> Result<(), ()> {
let endpoint = format!("{}/zones/{}/dns_records/{}", API_BASE, self.id, id);
return match r#type {
DnsRecordType::A => {
if let Some(ip) = ipv4 {
let json_body = self.create_body("A", &entry.name, ip.to_string().as_str());
match self.put(&endpoint, &json_body) {
Ok(response) => {
self.validate_response(response)
},
Err(e) => {
let err_msg = format!("Unable to access Cloudflare API. Error: {e}");
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
}
} else {
let err_msg = "Missing IPv4 for Update.";
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
},
DnsRecordType::AAAA => {
if let Some(ip) = ipv6 {
let json_body = self.create_body("AAAA", &entry.name, ip.to_string().as_str());
match self.put(&endpoint, &json_body) {
Ok(response) => {
self.validate_response(response)
},
Err(e) => {
let err_msg = format!("Unable to access Cloudflare API. Error: {e}");
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
}
} else {
let err_msg = "Missing IPv6 for Update.";
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
},
_ => {
let warn_msg = "Config contains unsupported type identifier";
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => println!("[WARN] {warn_msg}"),
}
Err(())
}
}
}
pub(crate) fn create(&self, entry: &ZoneEntry, r#type: &DnsRecordType, ipv6: Option<Ipv6Addr>, ipv4: Option<Ipv4Addr>) -> Result<(), ()> {
let endpoint = format!("{}/zones/{}/dns_records", API_BASE, self.id);
return match r#type {
DnsRecordType::A => {
if let Some(ip) = ipv4 {
let json_body = self.create_body("A", &entry.name, ip.to_string().as_str());
match self.post(&endpoint, &json_body) {
Ok(response) => {
self.validate_response(response)
},
Err(e) => {
let err_msg = format!("Unable to access Cloudflare API. Error: {e}");
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
}
} else {
let err_msg = "Missing IPv4 for Update.";
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
},
DnsRecordType::AAAA => {
if let Some(ip) = ipv6 {
let json_body = self.create_body("AAAA", &entry.name, ip.to_string().as_str());
match self.post(&endpoint, &json_body) {
Ok(response) => {
self.validate_response(response)
},
Err(e) => {
let err_msg = format!("Unable to access Cloudflare API. Error: {e}");
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
}
} else {
let err_msg = "Missing IPv6 for Update.";
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
},
_ => {
let warn_msg = "Config contains unsupported type identifier";
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => println!("[WARN] {warn_msg}"),
}
Err(())
}
}
}
fn get(&self, url: &str) -> Result<Response, Box<dyn Error>> {
let url_parsed = self.parse_url(url)?;
match Client::new()
.get(url_parsed)
.headers(self.generate_auth_headers())
.send() {
Ok(result) => Ok(result),
Err(e) => Err(Box::new(e)),
}
}
fn post(&self, url: &str, data: &HashMap<String, String>) -> Result<Response, Box<dyn Error>> {
let url_parsed = self.parse_url(url)?;
match Client::new()
.post(url_parsed)
.headers(self.generate_auth_headers())
.json(data)
.send() {
Ok(result) => Ok(result),
Err(e) => Err(Box::new(e)),
}
}
fn put(&self, url: &str, data: &HashMap<String, String>) -> Result<Response, Box<dyn Error>> {
let url_parsed = self.parse_url(url)?;
match Client::new()
.put(url_parsed)
.headers(self.generate_auth_headers())
.json(data)
.send() {
Ok(result) => Ok(result),
Err(e) => Err(Box::new(e)),
}
}
fn parse_url(&self, input: &str) -> Result<Url, ParseError> {
match Url::parse(input) {
Ok(url) => Ok(url),
Err(e) => {
let err_msg = format!("Unable to parse URL. Error: {}", e);
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(e)
}
}
}
fn create_body(&self, r#type: &str, name: &str, ip: &str) -> HashMap<String, String> {
let mut body = HashMap::new();
body.insert("type".to_owned(), r#type.to_owned());
body.insert("name".to_owned(), name.to_owned());
body.insert("content".to_owned(), ip.to_owned());
body
}
fn validate_response(&self, response: Response) -> Result<(), ()> {
if response.status().is_success() {
let data = match response.json::<CloudflareApiResult>() {
Ok(data) => data,
Err(e) => {
let err_msg = format!("Unable to parse API response. Error: {e}");
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
return Err(())
}
};
match data.success {
true => Ok(()),
false => {
let err_msg = format!("Unexpected error while updating DNS record. Info: {:?}", data);
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
}
} else {
let err_msg = format!("Unable to post/put Cloudflare DNS entry. Error: {}", response.status());
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
Err(())
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy, Display, IntoStaticStr)]
#[allow(clippy::upper_case_acronyms)]
pub(crate) enum DnsRecordType {
A,
AAAA,
CAA,
CERT,
CNAME,
DNSKEY,
DS,
HTTPS,
LOC,
MX,
NAPTR,
NS,
PTR,
SMIMEA,
SRV,
SSHFP,
SVCB,
TLSA,
TXT,
URI
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub(crate) struct CloudflareDnsRecord {
pub(crate) id: String,
pub(crate) name: String,
pub(crate) r#type: DnsRecordType,
pub(crate) content: String
}

View file

@ -1,269 +0,0 @@
use reqwest::{
blocking::{Client, Response},
Url,
};
use reqwest::{
header::{HeaderMap, HeaderValue},
Error,
};
use serde_derive::{Deserialize, Serialize};
use std::{collections::HashMap, string::String};
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, Display, IntoStaticStr)]
pub enum CloudflareDnsType {
#[strum(serialize = "A")]
A = 4,
#[strum(serialize = "AAAA")]
AAAA = 6,
CAA,
CERT,
CNAME,
DNSKEY,
DS,
HTTPS,
LOC,
MX,
NAPTR,
NS,
PTR,
SMIMEA,
SRV,
SSHFP,
SVCB,
TLSA,
TXT,
URI
}
#[derive(Serialize, Deserialize)]
pub struct CloudflareDnsEntry {
id: String,
pub 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
/// * `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);
match self.get(&endpoint) {
Ok(response) => {
if response.status().is_success() {
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]);
}
return Ok(());
}
else {
println!("Server returned Status Code: {}", response.status());
return Err(response.error_for_status().err().unwrap());
}
}
Err(e) => return Err(e),
}
}
/// Shorthand for Cloudflare API Requests
///
/// Automatically appends Auth Headers and parses the URL
///
/// * `url` : URL for the request, will be parsed to [`Url`]
fn get(&self, url: &str) -> Result<Response, Error> {
let url_parsed = match Url::parse(url) {
Ok(url) => url,
Err(e) => panic!("{:#?}", e), // If this call fails the API changed
}; // Continuing without a code update is not possible
let result = Client::new()
.get(url_parsed)
.headers(self.generate_headers())
.send();
return result;
}
/// 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), // If this call fails the API changed
}; // Continuing without a code update is not possible
let result = match Client::new()
.put(url_parsed)
.headers(self.generate_headers())
.json(data)
.send()
{
Ok(res) => Ok(res),
Err(e) => Err(e),
};
return result;
}
/// 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), // If this call fails the API changed
}; // Continuing without a code update is not possible
let result = match Client::new()
.post(url_parsed)
.headers(self.generate_headers())
.json(data)
.send()
{
Ok(res) => Ok(res),
Err(e) => Err(e),
};
return result;
}
/// 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();
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");
match self.put(&endpoint, &json_body) {
Ok(response) => {
let data = response
.json::<serde_json::Value>()
.expect("Response should always be valid JSON");
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,
) -> Result<bool, Error> {
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");
match self.post(&endpoint, &json_body) {
Ok(response) => {
let data = response
.json::<serde_json::Value>()
.expect("Response should always be valid JSON");
let success = data["success"]
.as_bool()
.expect("JSON should always include success bool");
return Ok(success);
}
Err(e) => return Err(e),
}
}
/// 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
}
}

140
src/config.rs Normal file
View file

@ -0,0 +1,140 @@
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::net::Ipv6Addr;
use ipnet::{IpBitOr, IpSub};
use std::str::FromStr;
use log::{error, warn};
use serde_derive::{Deserialize, Serialize};
use systemd_journal_logger::connected_to_journal;
use crate::cloudflare::DnsRecordType;
use crate::cloudflare::DnsRecordType::{A, AAAA};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct InterfaceConfig {
pub(crate) host_address: Ipv6Addr,
pub(crate) interfaces: HashMap<String, Ipv6Addr>,
}
impl InterfaceConfig {
pub(crate) fn load() -> Result<Self, Box<dyn Error>> {
let cfg: Self = match confy::load(env!("CARGO_PKG_NAME"),"interfaces") {
Ok(data) => data,
Err(e) => {
match connected_to_journal() {
true => error!("[ERROR] {e}"),
false => eprintln!("[ERROR] {e}")
}
return Err(Box::new(e));
}
};
Ok(cfg)
}
pub(crate) fn full_v6(&self, interface_name: &String, host_v6: Ipv6Addr) -> Result<Ipv6Addr, ()> {
let host_range = Ipv6Addr::from(host_v6.saturating_sub(self.host_address));
let interface_address = match self.interfaces.get(interface_name) {
Some(address) => *address,
None => {
let err_msg = "Malformed IP in interfaces.toml";
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
return Err(());
}
};
let interface_ip = host_range.bitor(interface_address);
Ok(interface_ip)
}
}
impl Default for InterfaceConfig {
fn default() -> Self {
InterfaceConfig {
host_address: Ipv6Addr::from_str("::").expect("Malformed literal in code"),
interfaces: HashMap::from([(" ".to_owned(), Ipv6Addr::from(0))]),
}
}
}
///////////////
#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct ZoneEntry {
pub(crate) name: String,
pub(crate) r#type: Vec<DnsRecordType>,
pub(crate) interface: String,
}
impl Default for ZoneEntry {
fn default() -> Self {
ZoneEntry {
name: " ".to_owned(),
r#type: vec![A, AAAA],
interface: " ".to_owned(),
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub(crate) struct ZoneConfig {
pub(crate) email: String,
pub(crate) name: String,
pub(crate) id: String,
#[serde(alias="entry")]
pub(crate) entries: Vec<ZoneEntry>
}
impl ZoneConfig {
pub(crate) fn load() -> Result<Vec<Self>, Box<dyn Error>> {
let path = confy::get_configuration_file_path(env!("CARGO_PKG_NAME"), "interfaces").expect("Something went wrong with confy");
let zones_dir = path.parent().expect("Something went wrong with confy").join("zones.d/");
let zones = fs::read_dir(zones_dir).unwrap();
let mut zone_configs: Vec<Self> = vec![];
for entry in zones {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let warn_msg = "Subdirectory in zones.d detected, this should not be the case";
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => eprintln!("[WARN] {warn_msg}"),
}
}
else {
let zone_config_path = format!("zones.d/{}", path.file_stem()
.expect("stem could not be extracted from filename").to_str()
.expect("&OsStr could not be converted to &str"));
match confy::load(env!("CARGO_PKG_NAME"), zone_config_path.as_str()) {
Ok(data) => zone_configs.push(data),
Err(e) => {
match connected_to_journal() {
true => error!("[ERROR] {e}"),
false => eprintln!("[ERROR] {e}"),
}
return Err(Box::new(e));
}
};
}
}
Ok(zone_configs)
}
}
impl Default for ZoneConfig {
fn default() -> Self {
ZoneConfig {
email: " ".to_owned(),
name: " ".to_owned(),
id: " ".to_owned(),
entries: vec![ZoneEntry::default()],
}
}
}

View file

@ -1,375 +1,303 @@
use cloudflare::{Instance, CloudflareDnsType};
/*use cloudflare_old::{Instance, CloudflareDnsType};*/
use reqwest::blocking::get;
use serde_derive::{Deserialize, Serialize};
use std::{fs, thread::{sleep}};
use std::{thread::{sleep}};
use std::error::Error;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use chrono::{Utc, Duration};
use dotenv::dotenv;
use log::{info, warn, error, LevelFilter};
use reqwest::StatusCode;
use systemd_journal_logger::{connected_to_journal, JournalLog};
use crate::cloudflare::{CloudflareZone, DnsRecordType};
mod config;
mod cloudflare;
fn default_key() -> String {
return "".to_string();
struct Addresses {
ipv4_uri: String,
ipv6_uri: String,
ipv4: Ipv4Addr,
ipv6: Ipv6Addr,
}
#[derive(Clone)]
struct ChangeTracker {
created: u16,
updated: u16,
unchanged: u16,
error: u16
}
impl Addresses {
fn new() -> Result<Self, Box<dyn Error>> {
let mut ret = Self {
ipv4_uri: "https://am.i.mullvad.net/ip".to_owned(),
ipv6_uri: "https://ipv6.am.i.mullvad.net/ip".to_owned(),
ipv4: Ipv4Addr::new(0, 0, 0, 0),
ipv6: Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)
};
impl ChangeTracker {
fn new() -> ChangeTracker {
ChangeTracker {
created: 0,
updated: 0,
unchanged: 0,
error: 0
match ret.get_v4() {
Ok(ip) => ret.ipv4 = ip,
Err(_) => {
let err_msg = format!("Unable to fetch IPv4 from '{}' during init. Aborting!", ret.ipv4_uri);
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
panic!("{}", err_msg);
}
}
fn print(&self, f: &str) {
match f {
"" => {
self.print("simple");
match ret.get_v6() {
Ok(ip) => ret.ipv6 = ip,
Err(_) => {
let err_msg = format!("Unable to fetch IPv6 from '{}' during init. Aborting!", ret.ipv6_uri);
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
"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");
panic!("{}", err_msg);
}
}
}
}
#[derive(Serialize, Deserialize)]
struct DnsEntry {
name: String,
type4: bool,
type6: bool,
interface: Option<String>,
}
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,
ips: &Ips,
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 {
if cloudflare_entry.is_equal(&self.name) {
// Update IPv4 Entry
if cloudflare_entry.r#type == CloudflareDnsType::A && self.type4 {
found4 = true;
if cloudflare_entry.is_ip_new(&ips.ipv4) {
match agent.update_entry(cloudflare_entry, &ips.ipv4) {
Ok(success) => {
if success {
change4.updated += 1;
Ok(ret)
}
fn update(&mut self) {
match self.get_v4() {
Ok(ip) => {
if ip != self.ipv4 {
let info_msg = format!("IPv4 changed from '{}' to '{}'", self.ipv4, ip);
match connected_to_journal() {
true => info!("[INFO] {info_msg}"),
false => println!("[INFO] {info_msg}"),
}
self.ipv4 = ip;
}
}
Err(e) => {
let warn_msg = format!("Unable to fetch IPv4 from '{}'. Error: {}", self.ipv4_uri, e);
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => println!("[WARN] {warn_msg}"),
}
}
}
match self.get_v6() {
Ok(ip) => {
if ip != self.ipv6 {
let info_msg = format!("IPv6 changed from '{}' to '{}'", self.ipv6, ip);
match connected_to_journal() {
true => info!("[INFO] {info_msg}"),
false => println!("[INFO] {info_msg}"),
}
self.ipv6 = ip;
}
}
Err(e) => {
let warn_msg = format!("Unable to fetch IPv6 from '{}'. Error: {}", self.ipv6_uri, e);
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => println!("[WARN] {warn_msg}"),
}
}
}
}
fn get_v4(&self) -> Result<Ipv4Addr, reqwest::Error> {
match get(&self.ipv4_uri) {
Ok(res) => {
match res.status() {
StatusCode::OK => {
let ip_string = res.text().expect("Returned data should always contain text").trim_end().to_owned();
Ok(Ipv4Addr::from_str(ip_string.as_str()).expect("Returned IP should always be parseable"))
},
_ => {
let warn_msg = format!("Unexpected HTTP status {}", res.status());
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => println!("[WARN] {warn_msg}"),
}
Ok(Ipv4Addr::new(0, 0, 0, 0))
}
}
}
Err(e) => Err(e),
}
}
fn get_v6(&self) -> Result<Ipv6Addr, reqwest::Error> {
match get(&self.ipv6_uri) {
Ok(res) => {
match res.status() {
StatusCode::OK => {
let ip_string = res.text().expect("Returned data should always contain text").trim_end().to_owned();
Ok(Ipv6Addr::from_str(ip_string.as_str()).expect("Returned IP should always be parseable"))
},
_ => {
let warn_msg = format!("Unexpected HTTP status {}", res.status());
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => println!("[WARN] {warn_msg}"),
}
Ok(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0))
}
else {
change4.error += 1;
}
},
Err(_e) => { return true } // if an error is detected any subsequent calls are likely to fail as well
};
Err(e) => Err(e),
}
else {
change4.unchanged += 1;
}
}
// 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) {
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;
}
}
// ignore otherwise
else {}
}
}
if !found4 && self.type4 {
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
}
}
if !found6 && self.type6 {
let ipv6 = ips.ipv6base.clone() + self.interface.as_ref().unwrap();
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
}
}
#[derive(Serialize, Deserialize)]
struct DnsZone {
email: String,
name: String,
id: String,
dns_entries: Vec<DnsEntry>,
}
impl DnsZone {
/// 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);
match agent.load_entries(&self.email, &self.id) {
Ok(_) => {
let mut results = Vec::<bool>::new();
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
}
}
}
#[derive(Serialize, Deserialize)]
struct DnsConfig {
ipv6_interface: String,
#[serde(default = "default_key")]
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),
};
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),
};
*self = config_parse;
self.api_key = api_key_parse["api_key"].as_str().unwrap().to_owned();
}
}
struct Ips {
ipv4: String,
ipv6base: String,
}
impl Ips {
fn new() -> Ips {
Ips {
ipv4: "0.0.0.0".to_string(),
ipv6base: ":".to_string(),
}
}
/// 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;
match get(ipv4uri) {
Ok(data) => {
if data.status() == 200 {
self.ipv4 = data.text().expect("0.0.0.0").trim_end().to_owned();
ret = true;
}
else {
ret = false;
}
},
Err(_e) => {
println!("Could not fetch IPv4");
ret = false;
return ret; // Early return since a fail on IPv4 means a likely fail on IPv6
}
}
match get(ipv6uri) {
Ok(data) => {
if data.status() == 200 {
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(),
};
self.ipv6base = stripped;
ret = true && ret; // Only set ret to true if previous ret is also true
}
else {
ret = false;
}
}
Err(_e) => {
println!("Could not fetch IPv6");
ret = false;
}
}
return ret;
}
}
/// 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 {
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")
}
}
}
fn main() {
dotenv().ok();
JournalLog::new().expect("Systemd-Logger crate error").install().expect("Systemd-Logger crate error");
log::set_max_level(LevelFilter::Info);
let mut ifaces = config::InterfaceConfig::load().unwrap();
let mut zone_cfgs= config::ZoneConfig::load().unwrap();
let mut now = Utc::now() - Duration::seconds(59);
let mut current = now;
let mut start = now;
let mut ips = match Addresses::new() {
Ok(ips) => ips,
Err(e) => panic!("{}", e)
};
loop {
now = Utc::now();
if now >= current + Duration::seconds(60) {
current = now;
if now >= start + Duration::seconds(60) {
start = now;
print!("\x1B[2J\x1B[1;1H");
println!("Starting DNS Update at {} {}", now.format("%H:%M:%S"), now.timezone());
update_dns();
match config::InterfaceConfig::load() {
Ok(new) => ifaces = new,
Err(e) => {
let err_msg = format!("Unable to load ínterfaces.toml with error: {}", e);
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
}
}
match config::ZoneConfig::load() {
Ok(new) => zone_cfgs = new,
Err(e) => {
let err_msg = format!("Unable to load from zones.d with error: {}", e);
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
}
}
ips.update();
for zone in &zone_cfgs {
let cf_zone = match CloudflareZone::new(zone) {
Ok(data) => data,
Err(e) => {
let err_msg = format!("Cloudflare Token likely not set. Error: {}", e);
match connected_to_journal() {
true => error!("[ERROR] {err_msg}"),
false => eprintln!("[ERROR] {err_msg}"),
}
continue
}
};
let cf_entries = match cf_zone.get_entries() {
Ok(entries) => entries,
Err(_) => {
continue
}
};
for entry in &zone.entries {
let ipv6;
let ipv4;
match entry.r#type[..] {
[DnsRecordType::AAAA, DnsRecordType::A] => {
ipv6 = match ifaces.full_v6(&entry.interface, ips.ipv6) {
Ok(ip) => Some(ip),
Err(_) => {
continue
}
};
ipv4 = Some(ips.ipv4);
},
[DnsRecordType::A, DnsRecordType::AAAA] => {
ipv6 = match ifaces.full_v6(&entry.interface, ips.ipv6) {
Ok(ip) => Some(ip),
Err(_) => {
continue
}
};
ipv4 = Some(ips.ipv4);
},
[DnsRecordType::AAAA] => {
ipv6 = match ifaces.full_v6(&entry.interface, ips.ipv6) {
Ok(ip) => Some(ip),
Err(_) => {
continue
}
};
ipv4 = None;
},
[DnsRecordType::A] => {
ipv6 = None;
ipv4 = Some(ips.ipv4);
},
_ => {
let warn_msg = "Config contains unsupported type identifier";
match connected_to_journal() {
true => warn!("[WARN] {warn_msg}"),
false => println!("[WARN] {warn_msg}"),
}
continue
}
}
for r#type in &entry.r#type {
let cf_entry = cf_entries.iter().find(|cf_entry| {
cf_entry.name == entry.name && &cf_entry.r#type == r#type
});
match cf_entry.unwrap().r#type {
DnsRecordType::A => {
let cf_ip = Ipv4Addr::from_str(cf_entry.unwrap().content.as_str()).expect("Cloudflare return should always be valid IP");
if Some(cf_ip) == ipv4 {
continue
}
},
DnsRecordType::AAAA => {
let cf_ip = Ipv6Addr::from_str(cf_entry.unwrap().content.as_str()).expect("Cloudflare return should always be valid IP");
if Some(cf_ip) == ipv6 {
continue
}
},
_ => {},
}
if let Some(cf_entry) = cf_entry {
if cf_zone.update(entry, r#type, &cf_entry.id, ipv6, ipv4).is_ok() {
let info_msg = format!("Updated {} DNS Record for entry '{}' in zone '{}'", r#type, entry.name, zone.name);
match connected_to_journal() {
true => warn!("[INFO] {info_msg}"),
false => println!("[INFO] {info_msg}"),
}
}
}
else if cf_zone.create(entry, r#type, ipv6, ipv4).is_ok() {
let info_msg = format!("Created {} DNS Record for entry '{}' in zone '{}'", r#type, entry.name, zone.name);
match connected_to_journal() {
true => info!("[INFO] {info_msg}"),
false => println!("[INFO] {info_msg}"),
};
}
}
// handle return values
}
}
}
else {
sleep(std::time::Duration::from_millis(500));
sleep(std::time::Duration::from_millis(200));
}
}
}