isothrum_machine/
place.rs1use std::time::{Duration, Instant};
9
10use isothrum_runner::tls::{Fingerprint, Refusal, Tls, Trust};
11use tokio::net::TcpStream;
12
13pub mod esxi;
14pub mod proxmox;
15pub mod ssh;
16
17pub const REACH_TIMEOUT: Duration = Duration::from_secs(6);
19
20#[must_use]
22pub fn host_for_url(host: &str) -> String {
23 if host.contains(':') { format!("[{host}]") } else { host.to_owned() }
24}
25
26#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
28#[non_exhaustive]
29pub enum Unreachable {
30 #[error("can't reach {host}:{port}: {why}")]
32 Failed {
33 host: String,
35 port: u16,
37 why: String,
39 },
40 #[error("timed out reaching {host}:{port}")]
42 TimedOut {
43 host: String,
45 port: u16,
47 },
48}
49
50pub async fn connect(host: &str, port: u16, limit: Duration) -> Result<(TcpStream, Duration), Unreachable> {
56 let started = Instant::now();
57 match tokio::time::timeout(limit, TcpStream::connect((host, port))).await {
58 Ok(Ok(stream)) => Ok((stream, started.elapsed())),
59 Ok(Err(e)) => Err(Unreachable::Failed {
60 host: host.to_owned(),
61 port,
62 why: e.to_string(),
63 }),
64 Err(_) => Err(Unreachable::TimedOut { host: host.to_owned(), port }),
65 }
66}
67
68pub async fn reach(host: &str, port: u16, limit: Duration) -> Result<Duration, Unreachable> {
74 connect(host, port, limit).await.map(|(_, latency)| latency)
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
79#[non_exhaustive]
80pub enum NoCertificate {
81 #[error("couldn't read the certificate of {host}:{port}: {why}")]
83 Unread {
84 host: String,
86 port: u16,
88 why: String,
90 },
91}
92
93pub async fn certificate(host: &str, port: u16, limit: Duration) -> Result<Fingerprint, NoCertificate> {
101 let unread = |why: String| NoCertificate::Unread {
102 host: host.to_owned(),
103 port,
104 why,
105 };
106 let tls = Tls::new(Trust::Pinned(None)).map_err(|e| unread(e.to_string()))?;
107 let http = reqwest::Client::builder()
108 .tls_backend_preconfigured(tls.config().clone())
109 .connect_timeout(limit)
110 .timeout(limit)
111 .build()
112 .map_err(|e| unread(proxmox::chain(&e)))?;
113 let answer = http.get(format!("https://{}:{port}/", host_for_url(host))).send().await;
114 match (tls.refused(), answer) {
115 (Some(Refusal::Unconfirmed { presented } | Refusal::Changed { presented, .. }), _) => Ok(presented),
116 (None, Err(e)) => Err(unread(proxmox::chain(&e))),
117 (None, Ok(_)) => Err(unread("no certificate was offered".to_owned())),
118 }
119}
120
121#[cfg(test)]
122mod tests;