use std::io::{Read, Write};
use std::sync::Arc;
use std::time::Duration;
use rustls::pki_types::ServerName;
use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned};
use super::url::Offer;
const QUIET: Duration = Duration::from_secs(15);
const MOST: usize = 64 * 1024;
#[derive(Debug, PartialEq, Eq)]
pub struct Answer {
pub status: u16,
pub body: Vec<u8>,
}
pub fn web_roots() -> RootCertStore {
RootCertStore {
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
}
}
pub fn post(offer: &Offer, body: &str, roots: RootCertStore) -> Result<Answer, String> {
let at = offer.authority();
let config =
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.map_err(|e| format!("tls versions: {e}"))?
.with_root_certificates(roots)
.with_no_client_auth();
let name = ServerName::try_from(offer.host.clone())
.map_err(|e| format!("{at}: not a server name: {e}"))?;
let tcp = crate::channel::connect(&format!("{}:{}", offer.host(), offer.port))
.and_then(|tcp| tcp.set_read_timeout(Some(QUIET)).map(|()| tcp))
.map_err(|e| format!("connect {at}: {e}"))?;
let conn =
ClientConnection::new(Arc::new(config), name).map_err(|e| format!("tls {at}: {e}"))?;
let mut tls = StreamOwned::new(conn, tcp);
let request = format!(
"POST {} HTTP/1.1\r\nHost: {at}\r\nContent-Type: application/json\r\n\
Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
offer.path(),
body.len()
);
tls.write_all(request.as_bytes())
.map_err(|e| format!("{at} could not be spoken to over HTTPS: {e}"))?;
let mut said = Vec::new();
let mut chunk = [0u8; 4096];
while read(&said).is_none() {
match tls.read(&mut chunk) {
Ok(n) if n > 0 => said.extend_from_slice(chunk.get(..n).unwrap_or_default()),
_ => break,
}
if said.len() > MOST {
return Err(format!(
"{at} answered more than {MOST} bytes; refused unread"
));
}
}
read(&said)
.or_else(|| ended(&said))
.ok_or_else(|| format!("{at} did not answer as HTTP"))
}
fn read(said: &[u8]) -> Option<Answer> {
let (status, head, body) = split(said)?;
let length: usize = head
.lines()
.filter_map(|line| line.split_once(':'))
.find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
.and_then(|(_, value)| value.trim().parse().ok())?;
Some(Answer {
status,
body: body.get(..length)?.to_vec(),
})
}
fn ended(said: &[u8]) -> Option<Answer> {
let (status, _, body) = split(said)?;
Some(Answer {
status,
body: body.to_vec(),
})
}
fn split(said: &[u8]) -> Option<(u16, &str, &[u8])> {
let end = said.windows(4).position(|four| four == b"\r\n\r\n")?;
let head = std::str::from_utf8(said.get(..end)?).ok()?;
let status = head
.strip_prefix("HTTP/1.")?
.split_whitespace()
.nth(1)?
.parse()
.ok()?;
Some((status, head, said.get(end + 4..)?))
}
#[cfg(test)]
mod tests;