//! 单次连接与响应共属调用 future;独立参考保留 Hyper 原生字段。 use super::*; use hyper::body::Body; pub(super) async fn send( address: SocketAddr, request: Request>, ) -> io::Result> { let uri = request.uri(); if request.method() == hyper::Method::CONNECT || uri.scheme().is_some() || uri.authority().is_some() || !(uri.path().starts_with('/') || (request.method() == hyper::Method::OPTIONS && uri.path() == "*")) { return Err(io::Error::other("invalid target")); } let mut hosts = request.headers().get_all("host").iter(); let host: hyper::http::uri::Authority = hosts .next() .ok_or_else(|| io::Error::other("missing Host"))? .to_str() .map_err(io::Error::other)? .parse() .map_err(io::Error::other)?; if hosts.next().is_some() || host.host().is_empty() || host.as_str().contains('@') { return Err(io::Error::other("invalid Host")); } if ["content-length", "transfer-encoding", "upgrade"] .iter() .any(|name| request.headers().contains_key(*name)) { return Err(io::Error::other("framing headers belong to Hyper")); } if request.body().size_hint().exact().unwrap() > 1048576 { return Err(io::Error::other("request body exceeds limit")); } check_headers( request.headers(), 80 + request.method().as_str().len() + uri.path_and_query().unwrap().as_str().len(), )?; tokio::time::timeout(TIMEOUT, async { let socket = TcpStream::connect(address).await?; socket.set_nodelay(true)?; let (mut sender, connection) = hyper::client::conn::http1::Builder::new() .max_buf_size(8192) .handshake(TokioIo::new(socket)) .await .map_err(io::Error::other)?; let receiving = async { let (parts, body) = sender .send_request(request) .await .map_err(io::Error::other)? .into_parts(); check_head(&parts)?; let body = Limited::new(body, 1048576) .collect() .await .map_err(io::Error::other)?; if let Some(trailers) = body.trailers() { check_headers(trailers, 0)?; } let body = body.to_bytes(); if matches!(parts.status.as_u16(), 204 | 205 | 304) && !body.is_empty() { return Err(io::Error::other("body forbidden for status")); } Ok(Response::from_parts(parts, body)) }; tokio::pin!(connection, receiving); tokio::select! { biased; result = &mut receiving => result, result = &mut connection => match (receiving.await, result) { (Ok(response), _) => Ok(response), (Err(_), Err(error)) => Err(io::Error::other(error)), (Err(error), Ok(())) => Err(error), }, } }) .await .map_err(|error| io::Error::new(io::ErrorKind::TimedOut, error))? }