use std::net::{TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use rustls::{ClientConnection, StreamOwned};
use serde_json::Value;
use super::{Channel, Endpoint, Reach, frame, hello};
pub(crate) const GONE: Duration = Duration::from_mins(2);
const CONNECT: Duration = Duration::from_secs(5);
pub(crate) type Tls = StreamOwned<ClientConnection, TcpStream>;
impl Channel {
pub(super) fn dial(&self, request: &Value) -> Result<Tls, Reach> {
let worked = crate::state::worked(&self.key, |worked| worked.clone());
let mut order: Vec<&Endpoint> = self.endpoints.iter().collect();
order.sort_by_key(|at| Some(&at.address) != worked.as_ref());
let mut refusals = Vec::new();
for at in order {
match self.send(at, request) {
Ok(mut tls) => {
crate::state::worked(&self.key, |worked| *worked = Some(at.address.clone()));
let spelled = hello::confirm(&mut tls)?;
self.spelled.store(spelled, Ordering::Relaxed);
return Ok(tls);
}
Err(refusal) => refusals.push(refusal),
}
}
Err(Reach::Unsent(refusals.join("; ")))
}
fn send(&self, at: &Endpoint, request: &Value) -> Result<Tls, String> {
let refused = |e| format!("connect {}: {e}", at.address);
let tcp = connect(&at.address).map_err(refused)?;
tcp.set_read_timeout(Some(GONE)).map_err(refused)?;
let conn = ClientConnection::new(Arc::clone(&self.config), at.name.clone())
.map_err(|e| format!("tls {}: {e}", at.address))?;
let mut tls = StreamOwned::new(conn, tcp);
hello::state(&mut tls)
.and_then(|()| frame::write_value(&mut tls, request))
.map_err(|e| self.wrote(&at.address, &e))?;
Ok(tls)
}
pub(super) fn wrote(&self, address: &str, e: &std::io::Error) -> String {
let Some(rustls::Error::InvalidCertificate(fault)) = e
.get_ref()
.and_then(|inner| inner.downcast_ref::<rustls::Error>())
else {
return format!("send {address}: {e}");
};
format!(
"the handshake with {address} did not verify ({fault:?}): {} must hold the anchors of THAT server's CA, and {} must be a leaf that CA issued. `lernie register` files both from an offer; otherwise both are carried here by hand",
self.anchors.display(),
self.chain.display()
)
}
}
pub(crate) fn connect(endpoint: &str) -> std::io::Result<TcpStream> {
let mut refusal = std::io::Error::other("resolved to no address");
for addr in endpoint.to_socket_addrs()? {
match TcpStream::connect_timeout(&addr, CONNECT) {
Ok(tcp) => return Ok(tcp),
Err(e) => refusal = e,
}
}
Err(refusal)
}