|
| 1 | +//! HTTP/1 Server Connections |
| 2 | +
|
| 3 | +use std::error::Error as StdError; |
| 4 | +use std::fmt; |
| 5 | +use std::time::Duration; |
| 6 | + |
| 7 | +use bytes::Bytes; |
| 8 | +use tokio::io::{AsyncRead, AsyncWrite}; |
| 9 | + |
| 10 | +use crate::body::{Body as IncomingBody, HttpBody as Body}; |
| 11 | +use crate::common::{task, Future, Pin, Poll, Unpin}; |
| 12 | +use crate::proto; |
| 13 | +use crate::service::HttpService; |
| 14 | + |
| 15 | +type Http1Dispatcher<T, B, S> = proto::h1::Dispatcher< |
| 16 | + proto::h1::dispatch::Server<S, IncomingBody>, |
| 17 | + B, |
| 18 | + T, |
| 19 | + proto::ServerTransaction, |
| 20 | +>; |
| 21 | + |
| 22 | +pin_project_lite::pin_project! { |
| 23 | + /// A future binding an http1 connection with a Service. |
| 24 | + /// |
| 25 | + /// Polling this future will drive HTTP forward. |
| 26 | + #[must_use = "futures do nothing unless polled"] |
| 27 | + pub struct Connection<T, S> |
| 28 | + where |
| 29 | + S: HttpService<IncomingBody>, |
| 30 | + { |
| 31 | + conn: Http1Dispatcher<T, S::ResBody, S>, |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/// A configuration builder for HTTP/1 server connections. |
| 36 | +#[derive(Clone, Debug)] |
| 37 | +pub struct Builder { |
| 38 | + h1_half_close: bool, |
| 39 | + h1_keep_alive: bool, |
| 40 | + h1_title_case_headers: bool, |
| 41 | + h1_preserve_header_case: bool, |
| 42 | + h1_header_read_timeout: Option<Duration>, |
| 43 | + h1_writev: Option<bool>, |
| 44 | + max_buf_size: Option<usize>, |
| 45 | + pipeline_flush: bool, |
| 46 | +} |
| 47 | + |
| 48 | +/// Deconstructed parts of a `Connection`. |
| 49 | +/// |
| 50 | +/// This allows taking apart a `Connection` at a later time, in order to |
| 51 | +/// reclaim the IO object, and additional related pieces. |
| 52 | +#[derive(Debug)] |
| 53 | +pub struct Parts<T, S> { |
| 54 | + /// The original IO object used in the handshake. |
| 55 | + pub io: T, |
| 56 | + /// A buffer of bytes that have been read but not processed as HTTP. |
| 57 | + /// |
| 58 | + /// If the client sent additional bytes after its last request, and |
| 59 | + /// this connection "ended" with an upgrade, the read buffer will contain |
| 60 | + /// those bytes. |
| 61 | + /// |
| 62 | + /// You will want to check for any existing bytes if you plan to continue |
| 63 | + /// communicating on the IO object. |
| 64 | + pub read_buf: Bytes, |
| 65 | + /// The `Service` used to serve this connection. |
| 66 | + pub service: S, |
| 67 | + _inner: (), |
| 68 | +} |
| 69 | + |
| 70 | +// ===== impl Connection ===== |
| 71 | + |
| 72 | +impl<I, S> fmt::Debug for Connection<I, S> |
| 73 | +where |
| 74 | + S: HttpService<IncomingBody>, |
| 75 | +{ |
| 76 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 77 | + f.debug_struct("Connection").finish() |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +impl<I, B, S> Connection<I, S> |
| 82 | +where |
| 83 | + S: HttpService<IncomingBody, ResBody = B>, |
| 84 | + S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 85 | + I: AsyncRead + AsyncWrite + Unpin, |
| 86 | + B: Body + 'static, |
| 87 | + B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 88 | +{ |
| 89 | + /// Start a graceful shutdown process for this connection. |
| 90 | + /// |
| 91 | + /// This `Connection` should continue to be polled until shutdown |
| 92 | + /// can finish. |
| 93 | + /// |
| 94 | + /// # Note |
| 95 | + /// |
| 96 | + /// This should only be called while the `Connection` future is still |
| 97 | + /// pending. If called after `Connection::poll` has resolved, this does |
| 98 | + /// nothing. |
| 99 | + pub fn graceful_shutdown(mut self: Pin<&mut Self>) { |
| 100 | + self.conn.disable_keep_alive(); |
| 101 | + } |
| 102 | + |
| 103 | + /// Return the inner IO object, and additional information. |
| 104 | + /// |
| 105 | + /// If the IO object has been "rewound" the io will not contain those bytes rewound. |
| 106 | + /// This should only be called after `poll_without_shutdown` signals |
| 107 | + /// that the connection is "done". Otherwise, it may not have finished |
| 108 | + /// flushing all necessary HTTP bytes. |
| 109 | + /// |
| 110 | + /// # Panics |
| 111 | + /// This method will panic if this connection is using an h2 protocol. |
| 112 | + pub fn into_parts(self) -> Parts<I, S> { |
| 113 | + let (io, read_buf, dispatch) = self.conn.into_inner(); |
| 114 | + Parts { |
| 115 | + io, |
| 116 | + read_buf, |
| 117 | + service: dispatch.into_service(), |
| 118 | + _inner: (), |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + /// Poll the connection for completion, but without calling `shutdown` |
| 123 | + /// on the underlying IO. |
| 124 | + /// |
| 125 | + /// This is useful to allow running a connection while doing an HTTP |
| 126 | + /// upgrade. Once the upgrade is completed, the connection would be "done", |
| 127 | + /// but it is not desired to actually shutdown the IO object. Instead you |
| 128 | + /// would take it back using `into_parts`. |
| 129 | + pub fn poll_without_shutdown(&mut self, cx: &mut task::Context<'_>) -> Poll<crate::Result<()>> |
| 130 | + where |
| 131 | + S: Unpin, |
| 132 | + S::Future: Unpin, |
| 133 | + B: Unpin, |
| 134 | + { |
| 135 | + self.conn.poll_without_shutdown(cx) |
| 136 | + } |
| 137 | + |
| 138 | + /// Prevent shutdown of the underlying IO object at the end of service the request, |
| 139 | + /// instead run `into_parts`. This is a convenience wrapper over `poll_without_shutdown`. |
| 140 | + /// |
| 141 | + /// # Error |
| 142 | + /// |
| 143 | + /// This errors if the underlying connection protocol is not HTTP/1. |
| 144 | + pub fn without_shutdown(self) -> impl Future<Output = crate::Result<Parts<I, S>>> |
| 145 | + where |
| 146 | + S: Unpin, |
| 147 | + S::Future: Unpin, |
| 148 | + B: Unpin, |
| 149 | + { |
| 150 | + let mut zelf = Some(self); |
| 151 | + futures_util::future::poll_fn(move |cx| { |
| 152 | + ready!(zelf.as_mut().unwrap().conn.poll_without_shutdown(cx))?; |
| 153 | + Poll::Ready(Ok(zelf.take().unwrap().into_parts())) |
| 154 | + }) |
| 155 | + } |
| 156 | + |
| 157 | + /// Enable this connection to support higher-level HTTP upgrades. |
| 158 | + /// |
| 159 | + /// See [the `upgrade` module](crate::upgrade) for more. |
| 160 | + pub fn with_upgrades(self) -> upgrades::UpgradeableConnection<I, S> |
| 161 | + where |
| 162 | + I: Send, |
| 163 | + { |
| 164 | + upgrades::UpgradeableConnection { inner: Some(self) } |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +impl<I, B, S> Future for Connection<I, S> |
| 169 | +where |
| 170 | + S: HttpService<IncomingBody, ResBody = B>, |
| 171 | + S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 172 | + I: AsyncRead + AsyncWrite + Unpin + 'static, |
| 173 | + B: Body + 'static, |
| 174 | + B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 175 | +{ |
| 176 | + type Output = crate::Result<()>; |
| 177 | + |
| 178 | + fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { |
| 179 | + match ready!(Pin::new(&mut self.conn).poll(cx)) { |
| 180 | + Ok(done) => { |
| 181 | + match done { |
| 182 | + proto::Dispatched::Shutdown => {} |
| 183 | + proto::Dispatched::Upgrade(pending) => { |
| 184 | + // With no `Send` bound on `I`, we can't try to do |
| 185 | + // upgrades here. In case a user was trying to use |
| 186 | + // `Body::on_upgrade` with this API, send a special |
| 187 | + // error letting them know about that. |
| 188 | + pending.manual(); |
| 189 | + } |
| 190 | + }; |
| 191 | + return Poll::Ready(Ok(())); |
| 192 | + } |
| 193 | + Err(e) => Poll::Ready(Err(e)), |
| 194 | + } |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +// ===== impl Builder ===== |
| 199 | + |
| 200 | +impl Builder { |
| 201 | + /// Create a new connection builder. |
| 202 | + pub fn new() -> Self { |
| 203 | + Self { |
| 204 | + h1_half_close: false, |
| 205 | + h1_keep_alive: true, |
| 206 | + h1_title_case_headers: false, |
| 207 | + h1_preserve_header_case: false, |
| 208 | + h1_header_read_timeout: None, |
| 209 | + h1_writev: None, |
| 210 | + max_buf_size: None, |
| 211 | + pipeline_flush: false, |
| 212 | + } |
| 213 | + } |
| 214 | + /// Set whether HTTP/1 connections should support half-closures. |
| 215 | + /// |
| 216 | + /// Clients can chose to shutdown their write-side while waiting |
| 217 | + /// for the server to respond. Setting this to `true` will |
| 218 | + /// prevent closing the connection immediately if `read` |
| 219 | + /// detects an EOF in the middle of a request. |
| 220 | + /// |
| 221 | + /// Default is `false`. |
| 222 | + pub fn half_close(&mut self, val: bool) -> &mut Self { |
| 223 | + self.h1_half_close = val; |
| 224 | + self |
| 225 | + } |
| 226 | + |
| 227 | + /// Enables or disables HTTP/1 keep-alive. |
| 228 | + /// |
| 229 | + /// Default is true. |
| 230 | + pub fn keep_alive(&mut self, val: bool) -> &mut Self { |
| 231 | + self.h1_keep_alive = val; |
| 232 | + self |
| 233 | + } |
| 234 | + |
| 235 | + /// Set whether HTTP/1 connections will write header names as title case at |
| 236 | + /// the socket level. |
| 237 | + /// |
| 238 | + /// Default is false. |
| 239 | + pub fn title_case_headers(&mut self, enabled: bool) -> &mut Self { |
| 240 | + self.h1_title_case_headers = enabled; |
| 241 | + self |
| 242 | + } |
| 243 | + |
| 244 | + /// Set whether to support preserving original header cases. |
| 245 | + /// |
| 246 | + /// Currently, this will record the original cases received, and store them |
| 247 | + /// in a private extension on the `Request`. It will also look for and use |
| 248 | + /// such an extension in any provided `Response`. |
| 249 | + /// |
| 250 | + /// Since the relevant extension is still private, there is no way to |
| 251 | + /// interact with the original cases. The only effect this can have now is |
| 252 | + /// to forward the cases in a proxy-like fashion. |
| 253 | + /// |
| 254 | + /// Default is false. |
| 255 | + pub fn preserve_header_case(&mut self, enabled: bool) -> &mut Self { |
| 256 | + self.h1_preserve_header_case = enabled; |
| 257 | + self |
| 258 | + } |
| 259 | + |
| 260 | + /// Set a timeout for reading client request headers. If a client does not |
| 261 | + /// transmit the entire header within this time, the connection is closed. |
| 262 | + /// |
| 263 | + /// Default is None. |
| 264 | + pub fn header_read_timeout(&mut self, read_timeout: Duration) -> &mut Self { |
| 265 | + self.h1_header_read_timeout = Some(read_timeout); |
| 266 | + self |
| 267 | + } |
| 268 | + |
| 269 | + /// Set whether HTTP/1 connections should try to use vectored writes, |
| 270 | + /// or always flatten into a single buffer. |
| 271 | + /// |
| 272 | + /// Note that setting this to false may mean more copies of body data, |
| 273 | + /// but may also improve performance when an IO transport doesn't |
| 274 | + /// support vectored writes well, such as most TLS implementations. |
| 275 | + /// |
| 276 | + /// Setting this to true will force hyper to use queued strategy |
| 277 | + /// which may eliminate unnecessary cloning on some TLS backends |
| 278 | + /// |
| 279 | + /// Default is `auto`. In this mode hyper will try to guess which |
| 280 | + /// mode to use |
| 281 | + pub fn writev(&mut self, val: bool) -> &mut Self { |
| 282 | + self.h1_writev = Some(val); |
| 283 | + self |
| 284 | + } |
| 285 | + |
| 286 | + /// Set the maximum buffer size for the connection. |
| 287 | + /// |
| 288 | + /// Default is ~400kb. |
| 289 | + /// |
| 290 | + /// # Panics |
| 291 | + /// |
| 292 | + /// The minimum value allowed is 8192. This method panics if the passed `max` is less than the minimum. |
| 293 | + pub fn max_buf_size(&mut self, max: usize) -> &mut Self { |
| 294 | + assert!( |
| 295 | + max >= proto::h1::MINIMUM_MAX_BUFFER_SIZE, |
| 296 | + "the max_buf_size cannot be smaller than the minimum that h1 specifies." |
| 297 | + ); |
| 298 | + self.max_buf_size = Some(max); |
| 299 | + self |
| 300 | + } |
| 301 | + |
| 302 | + /// Aggregates flushes to better support pipelined responses. |
| 303 | + /// |
| 304 | + /// Experimental, may have bugs. |
| 305 | + /// |
| 306 | + /// Default is false. |
| 307 | + pub fn pipeline_flush(&mut self, enabled: bool) -> &mut Self { |
| 308 | + self.pipeline_flush = enabled; |
| 309 | + self |
| 310 | + } |
| 311 | + |
| 312 | + // /// Set the timer used in background tasks. |
| 313 | + // pub fn timer<M>(&mut self, timer: M) -> &mut Self |
| 314 | + // where |
| 315 | + // M: Timer + Send + Sync + 'static, |
| 316 | + // { |
| 317 | + // self.timer = Time::Timer(Arc::new(timer)); |
| 318 | + // self |
| 319 | + // } |
| 320 | + |
| 321 | + /// Bind a connection together with a [`Service`](crate::service::Service). |
| 322 | + /// |
| 323 | + /// This returns a Future that must be polled in order for HTTP to be |
| 324 | + /// driven on the connection. |
| 325 | + /// |
| 326 | + /// # Example |
| 327 | + /// |
| 328 | + /// ``` |
| 329 | + /// # use hyper::{Body as Incoming, Request, Response}; |
| 330 | + /// # use hyper::service::Service; |
| 331 | + /// # use hyper::server::conn::http1::Builder; |
| 332 | + /// # use tokio::io::{AsyncRead, AsyncWrite}; |
| 333 | + /// # async fn run<I, S>(some_io: I, some_service: S) |
| 334 | + /// # where |
| 335 | + /// # I: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 336 | + /// # S: Service<hyper::Request<Incoming>, Response=hyper::Response<Incoming>> + Send + 'static, |
| 337 | + /// # S::Error: Into<Box<dyn std::error::Error + Send + Sync>>, |
| 338 | + /// # S::Future: Send, |
| 339 | + /// # { |
| 340 | + /// let http = Builder::new(); |
| 341 | + /// let conn = http.serve_connection(some_io, some_service); |
| 342 | + /// |
| 343 | + /// if let Err(e) = conn.await { |
| 344 | + /// eprintln!("server connection error: {}", e); |
| 345 | + /// } |
| 346 | + /// # } |
| 347 | + /// # fn main() {} |
| 348 | + /// ``` |
| 349 | + pub fn serve_connection<I, S>(&self, io: I, service: S) -> Connection<I, S> |
| 350 | + where |
| 351 | + S: HttpService<IncomingBody>, |
| 352 | + S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 353 | + S::ResBody: 'static, |
| 354 | + <S::ResBody as Body>::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 355 | + I: AsyncRead + AsyncWrite + Unpin, |
| 356 | + { |
| 357 | + let mut conn = proto::Conn::new(io); |
| 358 | + if !self.h1_keep_alive { |
| 359 | + conn.disable_keep_alive(); |
| 360 | + } |
| 361 | + if self.h1_half_close { |
| 362 | + conn.set_allow_half_close(); |
| 363 | + } |
| 364 | + if self.h1_title_case_headers { |
| 365 | + conn.set_title_case_headers(); |
| 366 | + } |
| 367 | + if self.h1_preserve_header_case { |
| 368 | + conn.set_preserve_header_case(); |
| 369 | + } |
| 370 | + if let Some(header_read_timeout) = self.h1_header_read_timeout { |
| 371 | + conn.set_http1_header_read_timeout(header_read_timeout); |
| 372 | + } |
| 373 | + if let Some(writev) = self.h1_writev { |
| 374 | + if writev { |
| 375 | + conn.set_write_strategy_queue(); |
| 376 | + } else { |
| 377 | + conn.set_write_strategy_flatten(); |
| 378 | + } |
| 379 | + } |
| 380 | + conn.set_flush_pipeline(self.pipeline_flush); |
| 381 | + if let Some(max) = self.max_buf_size { |
| 382 | + conn.set_max_buf_size(max); |
| 383 | + } |
| 384 | + let sd = proto::h1::dispatch::Server::new(service); |
| 385 | + let proto = proto::h1::Dispatcher::new(sd, conn); |
| 386 | + Connection { conn: proto } |
| 387 | + } |
| 388 | +} |
| 389 | + |
| 390 | +mod upgrades { |
| 391 | + use crate::upgrade::Upgraded; |
| 392 | + |
| 393 | + use super::*; |
| 394 | + |
| 395 | + // A future binding a connection with a Service with Upgrade support. |
| 396 | + // |
| 397 | + // This type is unnameable outside the crate. |
| 398 | + #[must_use = "futures do nothing unless polled"] |
| 399 | + #[allow(missing_debug_implementations)] |
| 400 | + pub struct UpgradeableConnection<T, S> |
| 401 | + where |
| 402 | + S: HttpService<IncomingBody>, |
| 403 | + { |
| 404 | + pub(super) inner: Option<Connection<T, S>>, |
| 405 | + } |
| 406 | + |
| 407 | + impl<I, B, S> UpgradeableConnection<I, S> |
| 408 | + where |
| 409 | + S: HttpService<IncomingBody, ResBody = B>, |
| 410 | + S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 411 | + I: AsyncRead + AsyncWrite + Unpin, |
| 412 | + B: Body + 'static, |
| 413 | + B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 414 | + { |
| 415 | + /// Start a graceful shutdown process for this connection. |
| 416 | + /// |
| 417 | + /// This `Connection` should continue to be polled until shutdown |
| 418 | + /// can finish. |
| 419 | + pub fn graceful_shutdown(mut self: Pin<&mut Self>) { |
| 420 | + Pin::new(self.inner.as_mut().unwrap()).graceful_shutdown() |
| 421 | + } |
| 422 | + } |
| 423 | + |
| 424 | + impl<I, B, S> Future for UpgradeableConnection<I, S> |
| 425 | + where |
| 426 | + S: HttpService<IncomingBody, ResBody = B>, |
| 427 | + S::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 428 | + I: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 429 | + B: Body + 'static, |
| 430 | + B::Error: Into<Box<dyn StdError + Send + Sync>>, |
| 431 | + { |
| 432 | + type Output = crate::Result<()>; |
| 433 | + |
| 434 | + fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { |
| 435 | + match ready!(Pin::new(&mut self.inner.as_mut().unwrap().conn).poll(cx)) { |
| 436 | + Ok(proto::Dispatched::Shutdown) => Poll::Ready(Ok(())), |
| 437 | + Ok(proto::Dispatched::Upgrade(pending)) => { |
| 438 | + let (io, buf, _) = self.inner.take().unwrap().conn.into_inner(); |
| 439 | + pending.fulfill(Upgraded::new(io, buf)); |
| 440 | + Poll::Ready(Ok(())) |
| 441 | + } |
| 442 | + Err(e) => Poll::Ready(Err(e)), |
| 443 | + } |
| 444 | + } |
| 445 | + } |
| 446 | +} |
0 commit comments