1 //! One HTTP/1.1 request over a Unix socket or a TCP address.2 //!3 //! A Unix socket peer authenticates by uid; a TCP peer carries the bearer4 //! token (spec section 9.1). The reply may have a `Content-Length` body or a5 //! chunked body. A streamed route is chunked by nature, so the client reads6 //! both and hands the caller one body.7 8 use std::fmt;9 use std::io::{Read, Write};10 use std::net::TcpStream;11 use std::os::unix::net::UnixStream;12 use std::path::PathBuf;13 14 /// The end of the reply head.15 const HEAD_END: &[u8] = b"\r\n\r\n";16 17 /// The header that names the body size.18 const CONTENT_LENGTH: &str = "content-length";19 20 /// The header that would make the body a stream.21 const TRANSFER_ENCODING: &str = "transfer-encoding";22 23 /// The one transfer coding that this client reads.24 const CHUNKED: &str = "chunked";25 26 /// The end of one chunk.27 const LINE_END: &[u8] = b"\r\n";28 29 /// The character that starts a chunk extension.30 const EXTENSION: char = ';';31 32 /// The exit code of a failed check.33 const EXIT_CHECK: u8 = 1;34 35 /// The exit code of a usage fault.36 const EXIT_USAGE: u8 = 2;37 38 /// The exit code of a refused socket.39 const EXIT_REFUSED: u8 = 3;40 41 /// The request that reads one route. The path and the optional authorization42 /// header are the only variable parts.43 const GET_REQUEST: &str = "GET {path} HTTP/1.1\r\nHost: inf3r\r\nConnection: close\r\n{auth}\r\n";44 45 /// The head of a request that submits a JSON body. The bench uses it to reach46 /// the same route that a client reaches.47 const POST_REQUEST: &str = "POST {path} HTTP/1.1\r\nHost: inf3r\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {len}\r\n{auth}\r\n";48 49 /// A DELETE with an optional JSON body.50 const DELETE_REQUEST: &str = "DELETE {path} HTTP/1.1\r\nHost: inf3r\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {len}\r\n{auth}\r\n";51 52 /// The authorization line for a token, or the empty string.53 fn auth_line(token: Option<&str>) -> String {54 token55 .map(|token| format!("Authorization: Bearer {token}\r\n"))56 .unwrap_or_default()57 }58 59 /// Where one client connects.60 #[derive(Clone, PartialEq, Eq, Debug)]61 enum Endpoint {62 /// A Unix domain socket. The peer uid is the credential.63 Unix(PathBuf),64 /// A TCP address. The bearer token is the credential.65 Tcp(String),66 }67 68 /// A client for the web's operator routes.69 #[derive(Clone, PartialEq, Eq, Debug)]70 pub struct Client {71 endpoint: Endpoint,72 token: Option<String>,73 }74 75 impl Client {76 /// Makes a client for one Unix socket. The socket is the credential.77 pub fn new(socket: impl Into<PathBuf>) -> Client {78 Client {79 endpoint: Endpoint::Unix(socket.into()),80 token: None,81 }82 }83 84 /// Makes a client for one TCP address, as `host:port`. An `http://` prefix85 /// is accepted because an operator copies a URL. This client has no TLS.86 pub fn tcp(address: impl Into<String>) -> Client {87 let address = address.into();88 let address = address89 .strip_prefix("http://")90 .unwrap_or(&address)91 .to_string();92 Client {93 endpoint: Endpoint::Tcp(address),94 token: None,95 }96 }97 98 /// Adds the bearer token that a TCP listener requires.99 pub fn with_token(mut self, token: Option<String>) -> Client {100 self.token = token;101 self102 }103 104 /// Reads one operator route.105 ///106 /// The status is returned as data: a refusal is a reply that the command107 /// decides how to report, not a transport failure.108 pub fn get(&self, path: &str) -> Result<Reply, CliError> {109 let request = GET_REQUEST110 .replace("{path}", path)111 .replace("{auth}", &auth_line(self.token.as_deref()));112 self.send(&request)113 }114 115 /// Submits a JSON body to one route.116 ///117 /// The whole reply is read before it is returned, so a caller that times118 /// this call times the job and not its first byte.119 pub fn post(&self, path: &str, body: &str) -> Result<Reply, CliError> {120 let length = body.len().to_string();121 let head = POST_REQUEST122 .replace("{path}", path)123 .replace("{len}", &length)124 .replace("{auth}", &auth_line(self.token.as_deref()));125 self.send(&(head + body))126 }127 128 /// Sends a DELETE with a JSON body.129 pub fn delete(&self, path: &str, body: &str) -> Result<Reply, CliError> {130 let length = body.len().to_string();131 let head = DELETE_REQUEST132 .replace("{path}", path)133 .replace("{len}", &length)134 .replace("{auth}", &auth_line(self.token.as_deref()));135 self.send(&(head + body))136 }137 138 fn send(&self, request: &str) -> Result<Reply, CliError> {139 let mut stream = self.connect()?;140 stream141 .write_all(request.as_bytes())142 .map_err(|why| CliError::Io(why.to_string()))?;143 stream144 .flush()145 .map_err(|why| CliError::Io(why.to_string()))?;146 let mut raw = Vec::new();147 stream148 .read_to_end(&mut raw)149 .map_err(|why| CliError::Io(why.to_string()))?;150 parse_reply(&raw)151 }152 153 fn connect(&self) -> Result<Box<dyn ReadWrite>, CliError> {154 match &self.endpoint {155 Endpoint::Unix(path) => {156 let stream = UnixStream::connect(path).map_err(|why| CliError::Connect {157 path: path.clone(),158 reason: why.to_string(),159 })?;160 Ok(Box::new(stream))161 }162 Endpoint::Tcp(address) => {163 let stream = TcpStream::connect(address).map_err(|why| CliError::Connect {164 path: PathBuf::from(address),165 reason: why.to_string(),166 })?;167 Ok(Box::new(stream))168 }169 }170 }171 }172 173 /// A stream that reads and writes, so the two transports share one send path.174 trait ReadWrite: Read + Write {}175 impl<T: Read + Write> ReadWrite for T {}176 177 /// The status and the body of one reply.178 #[derive(Clone, PartialEq, Eq, Debug)]179 pub struct Reply {180 /// The HTTP status.181 pub status: u16,182 /// The body as UTF-8. The operator routes answer JSON or text.183 pub body: String,184 }185 186 /// The reason a request or a reply failed.187 #[derive(Clone, PartialEq, Eq, Debug)]188 pub enum CliError {189 /// The socket refused the connection, or no socket is there.190 Connect {191 /// The socket that the client tried.192 path: PathBuf,193 /// The system message.194 reason: String,195 },196 /// A socket or a file failed while the command was in flight.197 Io(String),198 /// The reply is not a head and a body.199 Malformed(String),200 /// The body does not have the length that `Content-Length` gave.201 Short {202 /// The length that the head declared.203 want: usize,204 /// The bytes that arrived.205 got: usize,206 },207 /// The route answered with a status other than 200.208 Status {209 /// The route that was read.210 path: String,211 /// The status that it answered.212 status: u16,213 },214 /// The line on the command line cannot be run.215 Usage(String),216 /// The bundle directory that `new` was asked for is already there.217 Exists(PathBuf),218 /// The bench work failed, or the bench asked for no runs.219 Bench(String),220 /// The body is not JSON that this tree reads.221 Json(String),222 }223 224 impl fmt::Display for CliError {225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {226 match self {227 CliError::Connect { path, reason } => {228 write!(f, "cannot connect to {}: {reason}", path.display())229 }230 CliError::Io(why) => write!(f, "{why}"),231 CliError::Malformed(why) => write!(f, "the reply is not HTTP: {why}"),232 CliError::Short { want, got } => {233 write!(f, "the body is {got} bytes, Content-Length says {want}")234 }235 CliError::Status { path, status } => write!(f, "{path} answered {status}"),236 CliError::Usage(why) => write!(f, "{why}"),237 CliError::Exists(path) => write!(f, "{} already exists", path.display()),238 CliError::Bench(why) => write!(f, "the bench failed: {why}"),239 CliError::Json(why) => write!(f, "the body is not JSON: {why}"),240 }241 }242 }243 244 impl std::error::Error for CliError {}245 246 impl CliError {247 /// The exit code that this fault asks for (spec section 22).248 pub fn exit_code(&self) -> u8 {249 match self {250 CliError::Connect { .. } => EXIT_REFUSED,251 CliError::Usage(_) => EXIT_USAGE,252 _ => EXIT_CHECK,253 }254 }255 }256 257 fn parse_reply(raw: &[u8]) -> Result<Reply, CliError> {258 let at = raw259 .windows(HEAD_END.len())260 .position(|window| window == HEAD_END)261 .ok_or_else(|| CliError::Malformed("the head has no end".to_string()))?;262 let head =263 std::str::from_utf8(&raw[..at]).map_err(|why| CliError::Malformed(why.to_string()))?;264 let body = &raw[at + HEAD_END.len()..];265 266 let mut lines = head.split("\r\n");267 let status_line = lines268 .next()269 .ok_or_else(|| CliError::Malformed("there is no status line".to_string()))?;270 if !status_line.starts_with("HTTP/") {271 return Err(CliError::Malformed(status_line.to_string()));272 }273 let status = status_line274 .split_whitespace()275 .nth(1)276 .ok_or_else(|| CliError::Malformed("there is no status".to_string()))?277 .parse::<u16>()278 .map_err(|why| CliError::Malformed(why.to_string()))?;279 280 let mut length = None;281 let mut chunked = false;282 for line in lines {283 if line.is_empty() {284 continue;285 }286 let (name, value) = line287 .split_once(':')288 .ok_or_else(|| CliError::Malformed(line.to_string()))?;289 if name.eq_ignore_ascii_case(CONTENT_LENGTH) {290 let want = value291 .trim()292 .parse::<usize>()293 .map_err(|why| CliError::Malformed(why.to_string()))?;294 length = Some(want);295 } else if name.eq_ignore_ascii_case(TRANSFER_ENCODING)296 && value297 .split(',')298 .any(|coding| coding.trim().eq_ignore_ascii_case(CHUNKED))299 {300 chunked = true;301 }302 }303 let body = if chunked {304 decode_chunked(body).map_err(CliError::Malformed)?305 } else {306 // A reply without a body length carries no body. A body after a zero307 // length is the same fault as a short body: the head and the bytes308 // disagree.309 let want = length.unwrap_or(0);310 if body.len() != want {311 return Err(CliError::Short {312 want,313 got: body.len(),314 });315 }316 body.to_vec()317 };318 Ok(Reply {319 status,320 body: String::from_utf8_lossy(&body).into_owned(),321 })322 }323 324 /// Decodes a chunked body. A chunk is a hex size, an optional extension, and325 /// the bytes, and a zero chunk ends the body after any trailer headers.326 fn decode_chunked(mut body: &[u8]) -> Result<Vec<u8>, String> {327 let mut out = Vec::new();328 loop {329 let (line, rest) = line_of(body)?;330 let size = line.split(EXTENSION).next().unwrap_or_default().trim();331 let size = usize::from_str_radix(size, 16)332 .map_err(|_| format!("the chunk size is not hex: {size}"))?;333 body = rest;334 if size == 0 {335 // A zero chunk is followed by zero or more trailer lines and one336 // empty line. No byte may follow the end of the body.337 loop {338 let (line, rest) = line_of(body)?;339 body = rest;340 if line.is_empty() {341 break;342 }343 }344 if !body.is_empty() {345 return Err("the body continues after the last chunk".to_string());346 }347 return Ok(out);348 }349 if body.len() < size.saturating_add(LINE_END.len()) {350 return Err("a chunk is shorter than its size".to_string());351 }352 out.extend_from_slice(&body[..size]);353 if &body[size..size + LINE_END.len()] != LINE_END {354 return Err("a chunk does not end with a line break".to_string());355 }356 body = &body[size + LINE_END.len()..];357 }358 }359 360 /// Splits one CRLF-terminated line from the front of `body`.361 fn line_of(body: &[u8]) -> Result<(&str, &[u8]), String> {362 let at = body363 .windows(LINE_END.len())364 .position(|window| window == LINE_END)365 .ok_or_else(|| "a chunk line has no end".to_string())?;366 let line = std::str::from_utf8(&body[..at])367 .map_err(|why| format!("a chunk line is not text: {why}"))?;368 Ok((line, &body[at + LINE_END.len()..]))369 }