Check fist check

This commit is contained in:
Rémi BERTHO 2021-10-04 22:51:09 +02:00
parent 186ffb822f
commit 7659338106
Signed by: dalan
GPG key ID: EE3B917931C07B64
2 changed files with 100 additions and 91 deletions

4
TODO.md Normal file
View file

@ -0,0 +1,4 @@
# TODO
* [ ] Examples de fichiers de config
* [ ] Test à partir de ladresse IP récupéré par DNS (https://crates.io/crates/trust-dns-resolver)
* [ ] Test de lIPv6 (https://crates.io/crates/query_external_ip)

View file

@ -24,122 +24,127 @@ use std::path::Path;
use std::{thread, time::Duration}; use std::{thread, time::Duration};
fn main() -> Result<()> { fn main() -> Result<()> {
// Init log // Init log
let logfile = OpenOptions::new() let logfile = OpenOptions::new()
.append(true) .append(true)
.create(true) .create(true)
.open("log.txt") .open("log.txt")
.unwrap(); .unwrap();
WriteLogger::init( WriteLogger::init(
LevelFilter::Info, LevelFilter::Info,
ConfigBuilder::new() ConfigBuilder::new()
.set_time_format_str("%d/%m/%Y %H:%M:%S") .set_time_format_str("%d/%m/%Y %H:%M:%S")
.set_time_to_local(true) .set_time_to_local(true)
.build(), .build(),
logfile, logfile,
) )
.unwrap(); .unwrap();
// Init scheduler // Init scheduler
let mut scheduler = Scheduler::new(); let mut scheduler = Scheduler::new();
info!("Init"); info!("Init");
scheduler.every(1.day()).at("06:00").run(|| { scheduler.every(1.day()).at("06:00").run(|| {
if let Err(e) = check() { if let Err(e) = check() {
error!("Error {}", e); error!("Error {}", e);
} }
}); });
check()?;
// Run // Initial check
loop { if let Err(e) = check() {
scheduler.run_pending(); error!("Error {}", e);
thread::sleep(Duration::from_secs(60)); bail!("Cannot get initial IP");
} }
// Run
loop {
scheduler.run_pending();
thread::sleep(Duration::from_secs(60));
}
} }
fn check() -> Result<()> { fn check() -> Result<()> {
info!("Check"); info!("Check");
match get() { match get() {
Ok((old_ip, new_ip)) => { Ok((old_ip, new_ip)) => {
if old_ip != new_ip { if old_ip != new_ip {
let msg = format!("IP changed from {} to {}", old_ip, new_ip); let msg = format!("IP changed from {} to {}", old_ip, new_ip);
info!("{}", msg); info!("{}", msg);
send_mail("New IP".to_owned(), msg)?; send_mail("New IP".to_owned(), msg)?;
} }
} }
Err(err) => { Err(err) => {
let msg = format!("Cannot get IP ({})", err); let msg = format!("Cannot get IP ({})", err);
error!("{}", msg); error!("{}", msg);
send_mail("Error on getting IP".to_owned(), msg)?; send_mail("Error on getting IP".to_owned(), msg)?;
} }
} }
Ok(()) Ok(())
} }
fn get() -> Result<(IpAddr, IpAddr)> { fn get() -> Result<(IpAddr, IpAddr)> {
// Get new IP // Get new IP
let new_ip = match my_internet_ip::get() { let new_ip = match my_internet_ip::get() {
Ok(ip) => ip, Ok(ip) => ip,
Err(e) => bail!("Could not get IP: {:?}", e), Err(e) => bail!("Could not get IP: {:?}", e),
}; };
info!("Current IP is {}", new_ip); info!("Current IP is {}", new_ip);
// Get old IP // Get old IP
let path = Path::new("./old_ip.txt"); let path = Path::new("./old_ip.txt");
let old_ip = if path.exists() { let old_ip = if path.exists() {
fs::read_to_string(path)?.parse()? fs::read_to_string(path)?.parse()?
} else { } else {
new_ip.clone() new_ip.clone()
}; };
info!("Old IP is {}", old_ip); info!("Old IP is {}", old_ip);
// Write new IP // Write new IP
fs::write(path, format!("{}", new_ip))?; fs::write(path, format!("{}", new_ip))?;
Ok((old_ip, new_ip)) Ok((old_ip, new_ip))
} }
fn send_mail(subject: String, body: String) -> Result<()> { fn send_mail(subject: String, body: String) -> Result<()> {
info!("Send mail {}", subject); info!("Send mail {}", subject);
let config: Config = toml::from_str(&fs::read_to_string("config.toml")?)?; let config: Config = toml::from_str(&fs::read_to_string("config.toml")?)?;
let email = EmailBuilder::new() let email = EmailBuilder::new()
.to(config.mail.from) .to(config.mail.from)
.from(config.mail.to) .from(config.mail.to)
.subject(subject) .subject(subject)
.text(body) .text(body)
.build()?; .build()?;
// Create transport // Create transport
let creds = Credentials::new(config.mail.username, config.mail.password); let creds = Credentials::new(config.mail.username, config.mail.password);
let mut tls_builder = TlsConnector::builder(); let mut tls_builder = TlsConnector::builder();
tls_builder.min_protocol_version(Some(Protocol::Sslv3)); tls_builder.min_protocol_version(Some(Protocol::Sslv3));
let tls_parameters = let tls_parameters =
ClientTlsParameters::new(config.mail.server.clone(), tls_builder.build().unwrap()); ClientTlsParameters::new(config.mail.server.clone(), tls_builder.build().unwrap());
let mut mailer = SmtpClient::new( let mut mailer = SmtpClient::new(
(config.mail.server, config.mail.port), (config.mail.server, config.mail.port),
ClientSecurity::Required(tls_parameters), ClientSecurity::Required(tls_parameters),
)? )?
.credentials(creds) .credentials(creds)
.transport(); .transport();
mailer.send(email.into())?; mailer.send(email.into())?;
Ok(()) Ok(())
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Config { struct Config {
mail: MailConfig, mail: MailConfig,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct MailConfig { struct MailConfig {
server: String, server: String,
port: u16, port: u16,
username: String, username: String,
password: String, password: String,
from: (String, String), from: (String, String),
to: String, to: String,
} }