feels like done
This commit is contained in:
		@@ -5,14 +5,13 @@ use serde::{self, Deserialize, Serialize};
 | 
			
		||||
use std::{
 | 
			
		||||
    collections::HashMap,
 | 
			
		||||
    net::{IpAddr, Ipv4Addr},
 | 
			
		||||
    sync::Arc,
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
use crate::get_current_public_ipv4;
 | 
			
		||||
 | 
			
		||||
pub struct CloudflareClient {
 | 
			
		||||
    client: Client,
 | 
			
		||||
    domains: Vec<Arc<str>>,
 | 
			
		||||
    domains: Vec<Box<str>>,
 | 
			
		||||
    current_ip: Ipv4Addr,
 | 
			
		||||
    api_key: Box<str>,
 | 
			
		||||
    zone_id: Box<str>,
 | 
			
		||||
@@ -36,7 +35,7 @@ struct DnsRecord {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
impl CloudflareClient {
 | 
			
		||||
    pub async fn new(api_key: Box<str>, zone_id: Box<str>, domains: Vec<Arc<str>>) -> Result<Self> {
 | 
			
		||||
    pub async fn new(api_key: Box<str>, zone_id: Box<str>, domains: Vec<Box<str>>) -> Result<Self> {
 | 
			
		||||
        let force_ipv4 = IpAddr::from([0, 0, 0, 0]);
 | 
			
		||||
        let client = reqwest::ClientBuilder::new()
 | 
			
		||||
            .local_address(force_ipv4)
 | 
			
		||||
@@ -44,13 +43,15 @@ impl CloudflareClient {
 | 
			
		||||
 | 
			
		||||
        let current_ip = get_current_public_ipv4(&client).await?;
 | 
			
		||||
 | 
			
		||||
        Ok(Self {
 | 
			
		||||
        let this = Self {
 | 
			
		||||
            client,
 | 
			
		||||
            domains,
 | 
			
		||||
            current_ip,
 | 
			
		||||
            api_key,
 | 
			
		||||
            zone_id,
 | 
			
		||||
        })
 | 
			
		||||
        };
 | 
			
		||||
        this.update_dns_records(current_ip).await?;
 | 
			
		||||
        Ok(this)
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
    pub async fn check(&mut self) -> Result<()> {
 | 
			
		||||
@@ -58,6 +59,10 @@ impl CloudflareClient {
 | 
			
		||||
        if new_ip == self.current_ip {
 | 
			
		||||
            return Ok(());
 | 
			
		||||
        }
 | 
			
		||||
        info!(
 | 
			
		||||
            "Ip has changed from '{}' -> '{}'",
 | 
			
		||||
            &self.current_ip, &new_ip
 | 
			
		||||
        );
 | 
			
		||||
        self.update_dns_records(new_ip).await?;
 | 
			
		||||
        self.current_ip = new_ip;
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
@@ -1,7 +1,7 @@
 | 
			
		||||
use anyhow;
 | 
			
		||||
use dirs;
 | 
			
		||||
use log::warn;
 | 
			
		||||
use serde::{Deserialize, Serialize};
 | 
			
		||||
use serde::{self, Deserialize, Serialize};
 | 
			
		||||
use std::{env, path::PathBuf};
 | 
			
		||||
use tokio::{fs, io::AsyncReadExt};
 | 
			
		||||
 | 
			
		||||
@@ -12,6 +12,7 @@ pub struct Config {
 | 
			
		||||
    pub zone_id: Box<str>,
 | 
			
		||||
    pub api_key: Box<str>,
 | 
			
		||||
    pub domains: Vec<Box<str>>,
 | 
			
		||||
    pub max_errors_in_row: Option<usize>,
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub async fn get_config_path() -> Result<PathBuf, Vec<PathBuf>> {
 | 
			
		||||
 
 | 
			
		||||
@@ -1,7 +1,11 @@
 | 
			
		||||
mod cloudflare;
 | 
			
		||||
mod config;
 | 
			
		||||
mod public_ip;
 | 
			
		||||
pub mod utils;
 | 
			
		||||
 | 
			
		||||
pub use cloudflare::CloudflareClient;
 | 
			
		||||
pub use config::{get_config_path, read_config, Config};
 | 
			
		||||
pub use public_ip::get_current_public_ipv4;
 | 
			
		||||
 | 
			
		||||
pub const PROGRAM_NAME: &'static str = "dynip-cloudflare";
 | 
			
		||||
pub const MAX_ERORS_IN_ROW_DEFAULT: usize = 10;
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										66
									
								
								src/main.rs
									
									
									
									
									
								
							
							
						
						
									
										66
									
								
								src/main.rs
									
									
									
									
									
								
							@@ -1,4 +1,3 @@
 | 
			
		||||
use env_logger;
 | 
			
		||||
use futures::stream::StreamExt;
 | 
			
		||||
use log::{debug, error, info, log_enabled, Level};
 | 
			
		||||
use netlink_packet_core::NetlinkPayload;
 | 
			
		||||
@@ -6,7 +5,7 @@ use netlink_packet_route::RouteNetlinkMessage as RtnlMessage;
 | 
			
		||||
use netlink_sys::{AsyncSocket, SocketAddr};
 | 
			
		||||
use rtnetlink::new_connection;
 | 
			
		||||
 | 
			
		||||
use dynip_cloudflare::{get_config_path, read_config, Config};
 | 
			
		||||
use dynip_cloudflare::{utils, CloudflareClient, MAX_ERORS_IN_ROW_DEFAULT};
 | 
			
		||||
 | 
			
		||||
const RTNLGRP_LINK: u32 = 1;
 | 
			
		||||
const RTNLGRP_IPV4_IFADDR: u32 = 5;
 | 
			
		||||
@@ -24,32 +23,22 @@ const fn nl_mgrp(group: u32) -> u32 {
 | 
			
		||||
 | 
			
		||||
#[tokio::main]
 | 
			
		||||
async fn main() {
 | 
			
		||||
    env_logger::init();
 | 
			
		||||
    let config_path = match get_config_path().await {
 | 
			
		||||
        Ok(cp) => cp,
 | 
			
		||||
        Err(tried_paths) => {
 | 
			
		||||
            let extra: String = if !tried_paths.is_empty() {
 | 
			
		||||
                let joined = tried_paths
 | 
			
		||||
                    .iter()
 | 
			
		||||
                    .filter_map(|path| path.to_str())
 | 
			
		||||
                    .collect::<Vec<_>>()
 | 
			
		||||
                    .join(", ");
 | 
			
		||||
                format!(", tried the paths: '{}'", &joined)
 | 
			
		||||
            } else {
 | 
			
		||||
                String::with_capacity(0)
 | 
			
		||||
            };
 | 
			
		||||
            error!("Failed to find any config file{}", &extra);
 | 
			
		||||
            return;
 | 
			
		||||
        }
 | 
			
		||||
    };
 | 
			
		||||
    let config = match read_config(&config_path).await {
 | 
			
		||||
        Ok(config) => config,
 | 
			
		||||
        Err(e) => {
 | 
			
		||||
            error!("Failed to read and parse config file {:?}", &e);
 | 
			
		||||
            return;
 | 
			
		||||
        }
 | 
			
		||||
    utils::init_logger();
 | 
			
		||||
    let config = if let Some(aux) = utils::get_config().await {
 | 
			
		||||
        aux
 | 
			
		||||
    } else {
 | 
			
		||||
        return;
 | 
			
		||||
    };
 | 
			
		||||
 | 
			
		||||
    let mut cloudflare =
 | 
			
		||||
        match CloudflareClient::new(config.api_key, config.zone_id, config.domains).await {
 | 
			
		||||
            Ok(cloudflare) => cloudflare,
 | 
			
		||||
            Err(e) => {
 | 
			
		||||
                error!("Failed to initialize cloudflare client: {:?}", &e);
 | 
			
		||||
                return;
 | 
			
		||||
            }
 | 
			
		||||
        };
 | 
			
		||||
 | 
			
		||||
    let (mut conn, mut _handle, mut messages) = new_connection().unwrap();
 | 
			
		||||
    let groups = nl_mgrp(RTNLGRP_LINK) | nl_mgrp(RTNLGRP_IPV4_IFADDR);
 | 
			
		||||
 | 
			
		||||
@@ -63,6 +52,9 @@ async fn main() {
 | 
			
		||||
    tokio::spawn(conn);
 | 
			
		||||
    info!("Listening for IPv4 address changes and interface connect/disconnect events...");
 | 
			
		||||
 | 
			
		||||
    let mut errs_counter: usize = 0;
 | 
			
		||||
    let errs_max = config.max_errors_in_row.unwrap_or(MAX_ERORS_IN_ROW_DEFAULT);
 | 
			
		||||
 | 
			
		||||
    while let Some((message, _)) = messages.next().await {
 | 
			
		||||
        match message.payload {
 | 
			
		||||
            NetlinkPayload::InnerMessage(RtnlMessage::NewAddress(msg)) => {
 | 
			
		||||
@@ -70,6 +62,17 @@ async fn main() {
 | 
			
		||||
                    debug!("New IPv4 address message: {:?}", msg);
 | 
			
		||||
                } else {
 | 
			
		||||
                    info!("New IPv4 address");
 | 
			
		||||
 | 
			
		||||
                    if let Err(e) = cloudflare.check().await {
 | 
			
		||||
                        errs_counter += 1;
 | 
			
		||||
                        error!(
 | 
			
		||||
                            "Failed to check cloudflare ({}/{}): {:?}",
 | 
			
		||||
                            errs_counter, errs_max, &e
 | 
			
		||||
                        );
 | 
			
		||||
                        if errs_counter >= errs_max {
 | 
			
		||||
                            return;
 | 
			
		||||
                        }
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            NetlinkPayload::InnerMessage(RtnlMessage::DelAddress(msg)) => {
 | 
			
		||||
@@ -84,6 +87,17 @@ async fn main() {
 | 
			
		||||
                    debug!("New link message (interface connected): {:?}", link);
 | 
			
		||||
                } else {
 | 
			
		||||
                    info!("New link (interface connected)");
 | 
			
		||||
 | 
			
		||||
                    if let Err(e) = cloudflare.check().await {
 | 
			
		||||
                        errs_counter += 1;
 | 
			
		||||
                        error!(
 | 
			
		||||
                            "Failed to check cloudflare ({}/{}): {:?}",
 | 
			
		||||
                            errs_counter, errs_max, &e
 | 
			
		||||
                        );
 | 
			
		||||
                        if errs_counter >= errs_max {
 | 
			
		||||
                            return;
 | 
			
		||||
                        }
 | 
			
		||||
                    }
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            NetlinkPayload::InnerMessage(RtnlMessage::DelLink(link)) => {
 | 
			
		||||
 
 | 
			
		||||
@@ -1,44 +1,50 @@
 | 
			
		||||
    use anyhow::{anyhow, Context, Result};
 | 
			
		||||
    use log::error;
 | 
			
		||||
    use reqwest::Client;
 | 
			
		||||
    use std::{collections::HashMap, net::Ipv4Addr};
 | 
			
		||||
use anyhow::{anyhow, Context, Result};
 | 
			
		||||
use log::error;
 | 
			
		||||
use reqwest::Client;
 | 
			
		||||
use std::{collections::HashMap, net::Ipv4Addr};
 | 
			
		||||
 | 
			
		||||
    async fn ipify_org(client: &Client) -> Result<Ipv4Addr> {
 | 
			
		||||
        let response = client
 | 
			
		||||
            .get("https://api.ipify.org?format=json")
 | 
			
		||||
            .send()
 | 
			
		||||
            .await?
 | 
			
		||||
            .error_for_status()?
 | 
			
		||||
            .json::<HashMap<String, String>>()
 | 
			
		||||
            .await?;
 | 
			
		||||
async fn ipify_org(client: &Client) -> Result<Ipv4Addr> {
 | 
			
		||||
    let response = client
 | 
			
		||||
        .get("https://api.ipify.org?format=json")
 | 
			
		||||
        .send()
 | 
			
		||||
        .await?
 | 
			
		||||
        .error_for_status()?
 | 
			
		||||
        .json::<HashMap<String, String>>()
 | 
			
		||||
        .await?;
 | 
			
		||||
 | 
			
		||||
        Ok(response
 | 
			
		||||
            .get("ip")
 | 
			
		||||
            .context("Field 'ip' wasn't found")?
 | 
			
		||||
            .parse()?)
 | 
			
		||||
    }
 | 
			
		||||
    async fn ifconfig_me(client: &Client) -> Result<Ipv4Addr> {
 | 
			
		||||
        Ok(client
 | 
			
		||||
            .get("https://ifconfig.me")
 | 
			
		||||
            .header("user-agent", "curl/8.8.0")
 | 
			
		||||
            .send()
 | 
			
		||||
            .await?
 | 
			
		||||
            .error_for_status()?
 | 
			
		||||
            .text()
 | 
			
		||||
            .await?
 | 
			
		||||
            .parse()?)
 | 
			
		||||
    }
 | 
			
		||||
    pub async fn get_current_public_ipv4(client: &Client) -> Result<Ipv4Addr> {
 | 
			
		||||
        let e_ipify = match ipify_org(client).await {
 | 
			
		||||
            Ok(ipv4) => return Ok(ipv4),
 | 
			
		||||
            Err(e) => {
 | 
			
		||||
                error!("Failed to get ip from ipify.org: {:?}", &e);
 | 
			
		||||
                e
 | 
			
		||||
            }
 | 
			
		||||
        };
 | 
			
		||||
    Ok(response
 | 
			
		||||
        .get("ip")
 | 
			
		||||
        .context("Field 'ip' wasn't found")?
 | 
			
		||||
        .parse()?)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
        ifconfig_me(client).await.map_err(|e_ifconfig| {
 | 
			
		||||
            error!("Failed to get ip from ifconfig.me: {:?}", &e_ifconfig);
 | 
			
		||||
            anyhow!("Failed to get ip from ipify.org with error '{:?}', and ifconfig.me with error {:?}", &e_ipify, &e_ifconfig)
 | 
			
		||||
        })
 | 
			
		||||
    }
 | 
			
		||||
async fn ifconfig_me(client: &Client) -> Result<Ipv4Addr> {
 | 
			
		||||
    Ok(client
 | 
			
		||||
        .get("https://ifconfig.me")
 | 
			
		||||
        .header("user-agent", "curl/8.8.0")
 | 
			
		||||
        .send()
 | 
			
		||||
        .await?
 | 
			
		||||
        .error_for_status()?
 | 
			
		||||
        .text()
 | 
			
		||||
        .await?
 | 
			
		||||
        .parse()?)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub async fn get_current_public_ipv4(client: &Client) -> Result<Ipv4Addr> {
 | 
			
		||||
    let e_ipify = match ipify_org(client).await {
 | 
			
		||||
        Ok(ipv4) => return Ok(ipv4),
 | 
			
		||||
        Err(e) => {
 | 
			
		||||
            error!("Failed to get ip from ipify.org: {:?}", &e);
 | 
			
		||||
            e
 | 
			
		||||
        }
 | 
			
		||||
    };
 | 
			
		||||
 | 
			
		||||
    ifconfig_me(client).await.map_err(|e_ifconfig| {
 | 
			
		||||
        error!("Failed to get ip from ifconfig.me: {:?}", &e_ifconfig);
 | 
			
		||||
        anyhow!(
 | 
			
		||||
            "Failed to get ip from ipify.org with error '{:?}', and ifconfig.me with error {:?}",
 | 
			
		||||
            &e_ipify,
 | 
			
		||||
            &e_ifconfig
 | 
			
		||||
        )
 | 
			
		||||
    })
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										46
									
								
								src/utils.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										46
									
								
								src/utils.rs
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,46 @@
 | 
			
		||||
use env_logger::{Builder, Env};
 | 
			
		||||
use log::{error, LevelFilter};
 | 
			
		||||
use std::io::Write;
 | 
			
		||||
 | 
			
		||||
use crate::{get_config_path, read_config, Config};
 | 
			
		||||
 | 
			
		||||
pub fn init_logger() {
 | 
			
		||||
    Builder::from_env(Env::default().default_filter_or("info"))
 | 
			
		||||
        .format(|buf, record| {
 | 
			
		||||
            writeln!(
 | 
			
		||||
                buf,
 | 
			
		||||
                "{} [{}] - {}",
 | 
			
		||||
                chrono::Local::now().format("%Y:%m:%d %H:%M:%S"),
 | 
			
		||||
                record.level(),
 | 
			
		||||
                record.args()
 | 
			
		||||
            )
 | 
			
		||||
        })
 | 
			
		||||
        .filter(None, LevelFilter::Info)
 | 
			
		||||
        .init();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub async fn get_config() -> Option<Config> {
 | 
			
		||||
    let config_path = match get_config_path().await {
 | 
			
		||||
        Ok(path) => path,
 | 
			
		||||
        Err(tried_paths) => {
 | 
			
		||||
            let extra: String = if !tried_paths.is_empty() {
 | 
			
		||||
                let joined = tried_paths
 | 
			
		||||
                    .iter()
 | 
			
		||||
                    .filter_map(|path| path.to_str())
 | 
			
		||||
                    .collect::<Vec<_>>()
 | 
			
		||||
                    .join(", ");
 | 
			
		||||
                format!(", tried the paths: {}", &joined)
 | 
			
		||||
            } else {
 | 
			
		||||
                String::with_capacity(0)
 | 
			
		||||
            };
 | 
			
		||||
            error!("Failed to find any config file{}", &extra);
 | 
			
		||||
            return None;
 | 
			
		||||
        }
 | 
			
		||||
    };
 | 
			
		||||
 | 
			
		||||
    let read_result = read_config(&config_path).await;
 | 
			
		||||
    if let Err(e) = &read_result {
 | 
			
		||||
        error!("Error occurred while getting config path: {:?}", e);
 | 
			
		||||
    }
 | 
			
		||||
    read_result.ok()
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user