From c42aec785394b40645a283384838b856beace011 Mon Sep 17 00:00:00 2001 From: Ivan Goncharov Date: Thu, 24 Oct 2024 23:59:58 +0300 Subject: [PATCH] Add Http::http1_max_headers --- src/server/conn.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/server/conn.rs b/src/server/conn.rs index 951c9ee5cd..caaa6d2059 100644 --- a/src/server/conn.rs +++ b/src/server/conn.rs @@ -113,6 +113,7 @@ pub struct Http { h1_keep_alive: bool, h1_title_case_headers: bool, h1_preserve_header_case: bool, + h1_max_headers: Option, #[cfg(all(feature = "http1", feature = "runtime"))] h1_header_read_timeout: Option, h1_writev: Option, @@ -260,6 +261,7 @@ impl Http { h1_title_case_headers: false, h1_preserve_header_case: false, #[cfg(all(feature = "http1", feature = "runtime"))] + h1_max_headers: None, h1_header_read_timeout: None, h1_writev: None, #[cfg(feature = "http2")] @@ -349,6 +351,26 @@ impl Http { self } + /// Set the maximum number of headers. + /// + /// When a request is received, the parser will reserve a buffer to store headers for optimal + /// performance. + /// + /// If server receives more headers than the buffer size, it responds to the client with + /// "431 Request Header Fields Too Large". + /// + /// Note that headers is allocated on the stack by default, which has higher performance. After + /// setting this value, headers will be allocated in heap memory, that is, heap memory + /// allocation will occur for each request, and there will be a performance drop of about 5%. + /// + /// Default is 100. + #[cfg(feature = "http1")] + #[cfg_attr(docsrs, doc(cfg(feature = "http1")))] + pub fn http1_max_headers(&mut self, val: usize) -> &mut Self { + self.h1_max_headers = Some(val); + self + } + /// Set a timeout for reading client request headers. If a client does not /// transmit the entire header within this time, the connection is closed. /// @@ -623,6 +645,7 @@ impl Http { h1_keep_alive: self.h1_keep_alive, h1_title_case_headers: self.h1_title_case_headers, h1_preserve_header_case: self.h1_preserve_header_case, + h1_max_headers: self.h1_max_headers, #[cfg(all(feature = "http1", feature = "runtime"))] h1_header_read_timeout: self.h1_header_read_timeout, h1_writev: self.h1_writev, @@ -687,6 +710,9 @@ impl Http { if self.h1_preserve_header_case { conn.set_preserve_header_case(); } + if let Some(max_headers) = self.h1_max_headers { + conn.set_http1_max_headers(max_headers); + } #[cfg(all(feature = "http1", feature = "runtime"))] if let Some(header_read_timeout) = self.h1_header_read_timeout { conn.set_http1_header_read_timeout(header_read_timeout);