use std::time::{Duration, Instant};
use isothrum_runner::tls::{Fingerprint, Refusal, Tls, Trust};
use tokio::net::TcpStream;
pub mod esxi;
pub mod proxmox;
pub mod ssh;
pub const REACH_TIMEOUT: Duration = Duration::from_secs(6);
#[must_use]
pub fn host_for_url(host: &str) -> String {
if host.contains(':') { format!("[{host}]") } else { host.to_owned() }
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Unreachable {
#[error("can't reach {host}:{port}: {why}")]
Failed {
host: String,
port: u16,
why: String,
},
#[error("timed out reaching {host}:{port}")]
TimedOut {
host: String,
port: u16,
},
}
pub async fn connect(host: &str, port: u16, limit: Duration) -> Result<(TcpStream, Duration), Unreachable> {
let started = Instant::now();
match tokio::time::timeout(limit, TcpStream::connect((host, port))).await {
Ok(Ok(stream)) => Ok((stream, started.elapsed())),
Ok(Err(e)) => Err(Unreachable::Failed {
host: host.to_owned(),
port,
why: e.to_string(),
}),
Err(_) => Err(Unreachable::TimedOut { host: host.to_owned(), port }),
}
}
pub async fn reach(host: &str, port: u16, limit: Duration) -> Result<Duration, Unreachable> {
connect(host, port, limit).await.map(|(_, latency)| latency)
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum NoCertificate {
#[error("couldn't read the certificate of {host}:{port}: {why}")]
Unread {
host: String,
port: u16,
why: String,
},
}
pub async fn certificate(host: &str, port: u16, limit: Duration) -> Result<Fingerprint, NoCertificate> {
let unread = |why: String| NoCertificate::Unread {
host: host.to_owned(),
port,
why,
};
let tls = Tls::new(Trust::Pinned(None)).map_err(|e| unread(e.to_string()))?;
let http = reqwest::Client::builder()
.tls_backend_preconfigured(tls.config().clone())
.connect_timeout(limit)
.timeout(limit)
.build()
.map_err(|e| unread(proxmox::chain(&e)))?;
let answer = http.get(format!("https://{}:{port}/", host_for_url(host))).send().await;
match (tls.refused(), answer) {
(Some(Refusal::Unconfirmed { presented } | Refusal::Changed { presented, .. }), _) => Ok(presented),
(None, Err(e)) => Err(unread(proxmox::chain(&e))),
(None, Ok(_)) => Err(unread("no certificate was offered".to_owned())),
}
}
#[cfg(test)]
mod tests;