//! Minimal blocking HTTP/1.1 client for the local sync server. Each request uses its own //! connection (`Connection: close`). use anyhow::{Context, Result, anyhow, bail}; use std::io::{Read, Write}; use std::net::TcpStream; use std::time::Duration; pub struct Response { pub status: u16, pub body: Vec, } pub fn request( port: u16, method: &str, path: &str, headers: &[(String, String)], body: &[u8], timeout: Duration, ) -> Result { let mut stream = TcpStream::connect(("127.0.0.1", port)) .with_context(|| format!("failed to connect to the sync server on port {port}"))?; stream.set_read_timeout(Some(timeout))?; stream.set_write_timeout(Some(timeout))?; let mut head = format!( "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Length: {}\r\nConnection: close\r\n", body.len() ); for (name, value) in headers { if name.eq_ignore_ascii_case("content-length") || name.eq_ignore_ascii_case("connection") { continue; } head.push_str(&format!("{name}: {value}\r\n")); } head.push_str("\r\n"); stream.write_all(head.as_bytes())?; stream.write_all(body)?; let mut raw = Vec::new(); stream .read_to_end(&mut raw) .with_context(|| format!("failed to read the response to {method} {path}"))?; parse_response(&raw).with_context(|| format!("bad response to {method} {path}")) } fn parse_response(raw: &[u8]) -> Result { let end = raw .windows(4) .position(|w| w == b"\r\n\r\n") .ok_or_else(|| anyhow!("response has no header end"))?; let head = String::from_utf8_lossy(&raw[..end]); let rest = &raw[end + 4..]; let mut lines = head.split("\r\n"); let status = lines .next() .and_then(|line| line.split_whitespace().nth(1)) .and_then(|code| code.parse().ok()) .ok_or_else(|| anyhow!("bad status line: {head}"))?; let chunked = lines.any(|line| { let line = line.to_ascii_lowercase(); line.starts_with("transfer-encoding:") && line.contains("chunked") }); let body = if chunked { decode_chunked(rest)? } else { rest.to_vec() }; Ok(Response { status, body }) } fn decode_chunked(mut data: &[u8]) -> Result> { let mut out = Vec::new(); loop { let line_end = data .windows(2) .position(|w| w == b"\r\n") .ok_or_else(|| anyhow!("chunk has no size line"))?; let size_text = String::from_utf8_lossy(&data[..line_end]); let size_text = size_text.split(';').next().unwrap_or_default().trim(); let size = usize::from_str_radix(size_text, 16) .with_context(|| format!("bad chunk size `{size_text}`"))?; data = &data[line_end + 2..]; if size == 0 { return Ok(out); } if data.len() < size + 2 { bail!("chunk is shorter than its size"); } out.extend_from_slice(&data[..size]); data = &data[size + 2..]; } } #[cfg(test)] mod tests { #[test] fn parses_plain_and_chunked_responses() { let plain = super::parse_response(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nhi").unwrap(); assert_eq!((plain.status, plain.body.as_slice()), (200, &b"hi"[..])); let chunked = super::parse_response( b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nab\r\n1\r\nc\r\n0\r\n\r\n", ) .unwrap(); assert_eq!( (chunked.status, chunked.body.as_slice()), (404, &b"abc"[..]) ); } }