Skip to main content

isothrum_machine/
place.rs

1//! The servers a computer places machines on, checked before anything is placed there: whether
2//! the server answers at all ([`reach`], a TCP connection and how long it took), and what it
3//! answers as: a Proxmox VE API that accepts a sign-in and has the nodes, storages and bridges a
4//! placement needs ([`proxmox`]), an ESXi host's SSH ([`esxi`]).
5//!
6//! Each finding is typed; how it is put to a user, and what they are told to fix, is the caller's.
7
8use 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
17/// How long a server may take to accept a connection, or to answer once connected.
18pub const REACH_TIMEOUT: Duration = Duration::from_secs(6);
19
20/// A host as it goes in a URL: an IPv6 address in brackets.
21#[must_use]
22pub fn host_for_url(host: &str) -> String {
23    if host.contains(':') { format!("[{host}]") } else { host.to_owned() }
24}
25
26/// Why a server couldn't be reached.
27#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
28#[non_exhaustive]
29pub enum Unreachable {
30    /// The connection was refused or failed (name not resolved, no route): why.
31    #[error("can't reach {host}:{port}: {why}")]
32    Failed {
33        /// The host asked.
34        host: String,
35        /// The port asked.
36        port: u16,
37        /// Why, as the system said it.
38        why: String,
39    },
40    /// Nothing answered within the time given.
41    #[error("timed out reaching {host}:{port}")]
42    TimedOut {
43        /// The host asked.
44        host: String,
45        /// The port asked.
46        port: u16,
47    },
48}
49
50/// A connection to `host:port`, and how long it took to accept it, within `limit`.
51///
52/// # Errors
53///
54/// It wasn't accepted ([`Unreachable::Failed`]) or not within `limit` ([`Unreachable::TimedOut`]).
55pub 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
68/// Whether `host:port` accepts a TCP connection within `limit`, and how long it took.
69///
70/// # Errors
71///
72/// As [`connect`].
73pub async fn reach(host: &str, port: u16, limit: Duration) -> Result<Duration, Unreachable> {
74    connect(host, port, limit).await.map(|(_, latency)| latency)
75}
76
77/// Why a server's certificate couldn't be read.
78#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
79#[non_exhaustive]
80pub enum NoCertificate {
81    /// No TLS handshake got as far as the certificate (no connection, not TLS, timed out): why.
82    #[error("couldn't read the certificate of {host}:{port}: {why}")]
83    Unread {
84        /// The host asked.
85        host: String,
86        /// The port asked.
87        port: u16,
88        /// Why.
89        why: String,
90    },
91}
92
93/// The SHA-256 fingerprint of the certificate `host` offers on `port`, for a user to confirm
94/// before it is pinned ([`isothrum_runner::tls::Trust::Pinned`]): read from the handshake alone,
95/// which is refused before any request, so nothing is sent to the server.
96///
97/// # Errors
98///
99/// No handshake got as far as the certificate within `limit`.
100pub 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;