Skip to main content

ntex/http/
message.rs

1use std::{cell::Ref, cell::RefCell, cell::RefMut, fmt, net, rc::Rc};
2
3use bitflags::bitflags;
4use ntex_h2::StreamRef;
5use urly::Url;
6
7use crate::http::header::HeaderMap;
8use crate::http::{HeaderItem, Method, StatusCode, Version, h1::Codec};
9use crate::io::{IoBoxed, IoRef, types};
10use crate::util::{ByteString, Extensions};
11
12/// The connection behavior selected for an HTTP message.
13#[derive(Copy, Clone, PartialEq, Eq, Debug)]
14pub enum ConnectionType {
15    /// Close connection after response
16    Close,
17    /// Keep connection alive after response
18    KeepAlive,
19    /// Connection is upgraded to different type
20    Upgrade,
21}
22
23bitflags! {
24    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
25    pub(crate) struct Flags: u8 {
26        const CLOSE       = 0b0000_0001;
27        const KEEP_ALIVE  = 0b0000_0010;
28        const UPGRADE     = 0b0000_0100;
29        const EXPECT      = 0b0000_1000;
30        const NO_CHUNKING = 0b0001_0000;
31    }
32}
33
34pub(crate) trait Head: Default + 'static + fmt::Debug {
35    fn clear(&mut self);
36
37    /// Calls `f` with the thread's pool, returns `None` if the pool is already destroyed.
38    fn with_pool<F, R>(f: F) -> Option<R>
39    where
40        F: FnOnce(&MessagePool<Self>) -> R;
41}
42
43#[derive(Clone, Debug)]
44pub(crate) enum CurrentIo {
45    Ref(IoRef),
46    Io(Rc<dyn IoAccess>),
47    None,
48}
49
50pub(crate) trait IoAccess: fmt::Debug {
51    fn get(&self) -> Option<&IoRef>;
52
53    fn take(&self) -> Option<(IoBoxed, Codec)>;
54}
55
56impl CurrentIo {
57    pub(crate) fn new(io: Rc<dyn IoAccess>) -> Self {
58        CurrentIo::Io(io)
59    }
60
61    pub(crate) fn as_ref(&self) -> Option<&IoRef> {
62        match self {
63            CurrentIo::Ref(io) => Some(io),
64            CurrentIo::Io(io) => io.get(),
65            CurrentIo::None => None,
66        }
67    }
68
69    pub(crate) fn take(&self) -> Option<(IoBoxed, Codec)> {
70        match self {
71            CurrentIo::Io(io) => io.take(),
72            _ => None,
73        }
74    }
75}
76
77/// The parsed metadata for an HTTP request.
78#[derive(Debug)]
79pub struct RequestHead {
80    /// Identifier of the connection that received the request.
81    pub id: usize,
82    /// Request URI.
83    ///
84    /// A request received over HTTP/2 holds only its `:path` pseudo-header
85    /// here, or its `:authority` for `CONNECT`, see [`scheme`](Self::scheme)
86    /// and [`authority`](Self::authority).
87    pub uri: Url,
88    /// Request method.
89    pub method: Method,
90    /// HTTP protocol version.
91    pub version: Version,
92    /// Parsed request headers.
93    pub headers: HeaderMap,
94    /// Headers in their original order and with their original names.
95    ///
96    /// This collection is populated only when
97    /// [`HttpServiceConfig::set_headers_vec`](crate::http::HttpServiceConfig::set_headers_vec)
98    /// is enabled.
99    pub headers_vec: Vec<HeaderItem>,
100    /// Request-local type map.
101    pub extensions: RefCell<Extensions>,
102    /// Stream this request is made on (if over http/2).
103    pub(crate) stream: Option<StreamRef>,
104    /// `:scheme` pseudo-header of an HTTP/2 request.
105    pub(crate) scheme: Option<ByteString>,
106    /// `:authority` pseudo-header of an HTTP/2 request.
107    pub(crate) authority: Option<ByteString>,
108    pub(crate) io: CurrentIo,
109    pub(crate) flags: Flags,
110}
111
112impl Default for RequestHead {
113    fn default() -> RequestHead {
114        RequestHead {
115            id: 0,
116            stream: None,
117            scheme: None,
118            authority: None,
119            io: CurrentIo::None,
120            uri: Url::new(),
121            method: Method::default(),
122            version: Version::HTTP_11,
123            headers: HeaderMap::with_capacity(16),
124            headers_vec: Vec::default(),
125            flags: Flags::empty(),
126            extensions: RefCell::new(Extensions::new()),
127        }
128    }
129}
130
131impl Head for RequestHead {
132    fn clear(&mut self) {
133        self.io = CurrentIo::None;
134        // the uri, pseudo-headers and headers may share the connection read
135        // buffer, a pooled head must not keep it alive
136        self.uri = Url::new();
137        self.scheme = None;
138        self.authority = None;
139        self.flags = Flags::empty();
140        self.version = Version::HTTP_11;
141        self.headers.clear();
142        self.headers_vec.clear();
143        self.extensions.get_mut().clear();
144        self.stream = None;
145    }
146
147    fn with_pool<F, R>(f: F) -> Option<R>
148    where
149        F: FnOnce(&MessagePool<Self>) -> R,
150    {
151        REQUEST_POOL.try_with(|p| f(p)).ok()
152    }
153}
154
155impl RequestHead {
156    /// Returns the request scheme.
157    ///
158    /// The scheme of an absolute-form target, or the `:scheme` pseudo-header of
159    /// an HTTP/2 request, whose [`uri`](Self::uri) is in origin-form. Origin-form
160    /// HTTP/1 requests carry no scheme. It is not derived from the connection,
161    /// so it does not tell whether the request arrived over TLS.
162    pub fn scheme(&self) -> Option<&str> {
163        self.uri.scheme_str().or(self.scheme.as_deref())
164    }
165
166    /// Returns the request authority.
167    ///
168    /// The authority of an absolute-form or authority-form target, or the
169    /// `:authority` pseudo-header of an HTTP/2 request, whose [`uri`](Self::uri)
170    /// is in origin-form. It is not taken from the `Host` header. It is
171    /// validated only if the server validates request targets.
172    pub fn authority(&self) -> Option<&str> {
173        self.uri
174            .authority()
175            .map(urly::Authority::as_str)
176            .or(self.authority.as_deref())
177    }
178
179    /// Returns the request extensions.
180    #[inline]
181    pub fn extensions(&self) -> Ref<'_, Extensions> {
182        self.extensions.borrow()
183    }
184
185    /// Returns mutable access to the request extensions.
186    #[inline]
187    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
188        self.extensions.borrow_mut()
189    }
190
191    /// Returns the request headers.
192    pub fn headers(&self) -> &HeaderMap {
193        &self.headers
194    }
195
196    /// Returns mutable access to the request headers.
197    pub fn headers_mut(&mut self) -> &mut HeaderMap {
198        &mut self.headers
199    }
200
201    /// Returns headers preserved in their original order and casing.
202    pub fn headers_vec(&self) -> &[HeaderItem] {
203        &self.headers_vec
204    }
205
206    #[inline]
207    /// Sets the request connection behavior.
208    ///
209    /// Connection types are flags, and calling this method again does not clear
210    /// a previously set type. When several are set, `Close` takes precedence
211    /// over `KeepAlive`, which takes precedence over `Upgrade`.
212    pub fn set_connection_type(&mut self, ctype: ConnectionType) {
213        match ctype {
214            ConnectionType::Close => self.flags.insert(Flags::CLOSE),
215            ConnectionType::KeepAlive => self.flags.insert(Flags::KEEP_ALIVE),
216            ConnectionType::Upgrade => self.flags.insert(Flags::UPGRADE),
217        }
218    }
219
220    #[inline]
221    /// Returns the request connection behavior.
222    pub fn connection_type(&self) -> ConnectionType {
223        if self.flags.contains(Flags::CLOSE) {
224            ConnectionType::Close
225        } else if self.flags.contains(Flags::KEEP_ALIVE) {
226            ConnectionType::KeepAlive
227        } else if self.flags.contains(Flags::UPGRADE) {
228            ConnectionType::Upgrade
229        } else if self.version < Version::HTTP_11 {
230            ConnectionType::Close
231        } else {
232            ConnectionType::KeepAlive
233        }
234    }
235
236    #[inline]
237    /// Returns whether the request upgrades the connection.
238    pub fn upgrade(&self) -> bool {
239        self.flags.contains(Flags::UPGRADE)
240    }
241
242    #[inline]
243    /// Returns whether the request contains `Expect: 100-continue`.
244    pub fn expect(&self) -> bool {
245        self.flags.contains(Flags::EXPECT)
246    }
247
248    #[inline]
249    /// Returns whether chunked transfer encoding is allowed.
250    pub fn chunked(&self) -> bool {
251        !self.flags.contains(Flags::NO_CHUNKING)
252    }
253
254    #[inline]
255    /// Enables or disables chunked transfer encoding.
256    ///
257    /// A streaming request body without chunked coding requires a `Content-Length` header.
258    pub fn no_chunking(&mut self, val: bool) {
259        if val {
260            self.flags.insert(Flags::NO_CHUNKING);
261        } else {
262            self.flags.remove(Flags::NO_CHUNKING);
263        }
264    }
265
266    #[inline]
267    pub(crate) fn set_expect(&mut self) {
268        self.flags.insert(Flags::EXPECT);
269    }
270
271    #[inline]
272    pub(crate) fn set_upgrade(&mut self) {
273        self.flags.insert(Flags::UPGRADE);
274    }
275
276    pub(crate) fn set_stream(&mut self, stream: StreamRef) {
277        self.stream = Some(stream);
278    }
279
280    pub fn stream(&self) -> Option<&StreamRef> {
281        self.stream.as_ref()
282    }
283
284    /// Returns the peer socket address.
285    ///
286    /// Peer address is actual socket address, if proxy is used in front of
287    /// ntex http server, then peer address would be address of this proxy.
288    #[inline]
289    pub fn peer_addr(&self) -> Option<net::SocketAddr> {
290        self.io.as_ref().and_then(|io| {
291            io.query::<types::PeerAddr>()
292                .get()
293                .map(types::PeerAddr::into_inner)
294        })
295    }
296
297    /// Takes ownership of the I/O stream and HTTP/1 codec for an upgrade.
298    ///
299    /// The handle is installed only after an upgrade is acknowledged through
300    /// the HTTP/1 control service. This is a one-shot operation: subsequent
301    /// calls return [`None`]. Calls made from filter callbacks of the
302    /// connection return [`None`] and leave the handle in place.
303    pub fn take_io(&self) -> Option<(IoBoxed, Codec)> {
304        self.io.take()
305    }
306
307    #[doc(hidden)]
308    pub fn remove_io(&mut self) {
309        self.io = CurrentIo::None;
310    }
311}
312
313/// The metadata for an HTTP response.
314#[derive(Debug)]
315pub struct ResponseHead {
316    /// HTTP protocol version.
317    pub version: Version,
318    /// Response status code.
319    pub status: StatusCode,
320    /// Response headers.
321    pub headers: HeaderMap,
322    /// Headers in their original order and with their original names.
323    ///
324    /// This collection is populated when decoding a response with
325    /// [`HttpServiceConfig::set_headers_vec`](crate::http::HttpServiceConfig::set_headers_vec)
326    /// enabled.
327    pub headers_vec: Vec<HeaderItem>,
328    /// Custom reason phrase, or `None` to use the status code's standard phrase.
329    pub reason: Option<&'static str>,
330    pub(crate) io: CurrentIo,
331    pub(crate) extensions: RefCell<Extensions>,
332    pub(crate) flags: Flags,
333}
334
335impl ResponseHead {
336    /// Creates response metadata with the supplied status and HTTP version.
337    #[inline]
338    pub fn new(status: StatusCode, version: Version) -> ResponseHead {
339        ResponseHead {
340            status,
341            version,
342            headers: HeaderMap::with_capacity(12),
343            headers_vec: Vec::default(),
344            reason: None,
345            flags: Flags::empty(),
346            io: CurrentIo::None,
347            extensions: RefCell::new(Extensions::new()),
348        }
349    }
350
351    /// Returns the response extensions.
352    #[inline]
353    pub fn extensions(&self) -> Ref<'_, Extensions> {
354        self.extensions.borrow()
355    }
356
357    /// Returns mutable access to the response extensions.
358    #[inline]
359    pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
360        self.extensions.borrow_mut()
361    }
362
363    #[inline]
364    /// Returns the response headers.
365    pub fn headers(&self) -> &HeaderMap {
366        &self.headers
367    }
368
369    #[inline]
370    /// Returns mutable access to the response headers.
371    pub fn headers_mut(&mut self) -> &mut HeaderMap {
372        &mut self.headers
373    }
374
375    /// Returns headers preserved in their original order and casing.
376    pub fn headers_vec(&self) -> &[HeaderItem] {
377        &self.headers_vec
378    }
379
380    #[inline]
381    /// Sets the response connection behavior.
382    ///
383    /// Connection types are flags, and calling this method again does not clear
384    /// a previously set type. When several are set, `Close` takes precedence
385    /// over `KeepAlive`, which takes precedence over `Upgrade`.
386    pub fn set_connection_type(&mut self, ctype: ConnectionType) {
387        match ctype {
388            ConnectionType::Close => self.flags.insert(Flags::CLOSE),
389            ConnectionType::KeepAlive => self.flags.insert(Flags::KEEP_ALIVE),
390            ConnectionType::Upgrade => self.flags.insert(Flags::UPGRADE),
391        }
392    }
393
394    #[inline]
395    /// Returns the response's connection behavior.
396    pub fn connection_type(&self) -> ConnectionType {
397        if self.flags.contains(Flags::CLOSE) {
398            ConnectionType::Close
399        } else if self.flags.contains(Flags::KEEP_ALIVE) {
400            ConnectionType::KeepAlive
401        } else if self.flags.contains(Flags::UPGRADE) {
402            ConnectionType::Upgrade
403        } else if self.version < Version::HTTP_11 {
404            ConnectionType::Close
405        } else {
406            ConnectionType::KeepAlive
407        }
408    }
409
410    #[inline]
411    /// Returns whether the response keeps the connection open.
412    pub fn keep_alive(&self) -> bool {
413        self.connection_type() == ConnectionType::KeepAlive
414    }
415
416    #[inline]
417    /// Returns whether the response upgrades the connection.
418    pub fn upgrade(&self) -> bool {
419        self.connection_type() == ConnectionType::Upgrade
420    }
421
422    /// Returns the custom or canonical reason phrase.
423    ///
424    /// The reason phrase is empty for a status code without a canonical reason.
425    #[inline]
426    pub fn reason(&self) -> &str {
427        if let Some(reason) = self.reason {
428            reason
429        } else {
430            self.status.canonical_reason().unwrap_or("")
431        }
432    }
433
434    #[inline]
435    pub(crate) fn ctype(&self) -> Option<ConnectionType> {
436        if self.flags.contains(Flags::CLOSE) {
437            Some(ConnectionType::Close)
438        } else if self.flags.contains(Flags::KEEP_ALIVE) {
439            Some(ConnectionType::KeepAlive)
440        } else if self.flags.contains(Flags::UPGRADE) {
441            Some(ConnectionType::Upgrade)
442        } else {
443            None
444        }
445    }
446
447    #[inline]
448    /// Returns whether HTTP/1 chunked transfer encoding is allowed.
449    pub fn chunked(&self) -> bool {
450        !self.flags.contains(Flags::NO_CHUNKING)
451    }
452
453    #[inline]
454    /// Enables or disables HTTP/1 chunked transfer encoding.
455    pub fn no_chunking(&mut self, val: bool) {
456        if val {
457            self.flags.insert(Flags::NO_CHUNKING);
458        } else {
459            self.flags.remove(Flags::NO_CHUNKING);
460        }
461    }
462}
463
464impl Default for ResponseHead {
465    fn default() -> Self {
466        Self::new(StatusCode::default(), Version::default())
467    }
468}
469
470impl Head for ResponseHead {
471    fn clear(&mut self) {
472        self.reason = None;
473        self.headers.clear();
474        self.headers_vec.clear();
475        self.io = CurrentIo::None;
476        self.flags = Flags::empty();
477        self.extensions.get_mut().clear();
478    }
479
480    fn with_pool<F, R>(f: F) -> Option<R>
481    where
482        F: FnOnce(&MessagePool<Self>) -> R,
483    {
484        RESPONSE_POOL.try_with(|p| f(p)).ok()
485    }
486}
487
488#[derive(Debug)]
489pub(crate) struct Message<T: Head> {
490    head: Rc<T>,
491}
492
493impl<T: Head> Message<T> {
494    /// Get new message from the pool of objects
495    pub(crate) fn new() -> Self {
496        let head = T::with_pool(MessagePool::get_head)
497            .flatten()
498            .unwrap_or_else(|| Rc::new(T::default()));
499        Message { head }
500    }
501
502    /// Clears the head, so a cached message does not hold request data.
503    pub(crate) fn clear(&mut self) {
504        if let Some(head) = Rc::get_mut(&mut self.head) {
505            head.clear();
506        }
507    }
508}
509
510impl Message<ResponseHead> {
511    /// Get new message from the pool of objects
512    pub(crate) fn with_status(status: StatusCode) -> Self {
513        let mut msg = Self::new();
514        msg.status = status;
515        msg
516    }
517
518    /// Copies the response head into a new message, extensions are not copied.
519    pub(crate) fn copy(&self) -> Self {
520        let mut msg = Self::with_status(self.status);
521        msg.version = self.version;
522        msg.headers = self.headers.clone();
523        msg.headers_vec.clone_from(&self.headers_vec);
524        msg.reason = self.reason;
525        msg.io = self.io.clone();
526        msg.flags = self.flags;
527        msg
528    }
529}
530
531impl<T: Head> Clone for Message<T> {
532    fn clone(&self) -> Self {
533        Self {
534            head: self.head.clone(),
535        }
536    }
537}
538
539impl<T: Head> std::ops::Deref for Message<T> {
540    type Target = T;
541
542    fn deref(&self) -> &Self::Target {
543        self.head.as_ref()
544    }
545}
546
547impl<T: Head> std::ops::DerefMut for Message<T> {
548    fn deref_mut(&mut self) -> &mut Self::Target {
549        Rc::get_mut(&mut self.head).expect("Multiple copies exist")
550    }
551}
552
553impl<T: Head> Drop for Message<T> {
554    fn drop(&mut self) {
555        let Some(head) = Rc::get_mut(&mut self.head) else {
556            return;
557        };
558        // a head the pool would reject is freed as is, clearing it first
559        // would be wasted work
560        if !T::with_pool(MessagePool::has_room).unwrap_or(false) {
561            return;
562        }
563        // clearing may drop other messages (e.g. stored in extensions),
564        // so the pool must not be borrowed at this point
565        head.clear();
566        T::with_pool(|pool| {
567            if let Ok(mut v) = pool.0.try_borrow_mut()
568                && v.len() < POOL_CAP
569            {
570                v.push(self.head.clone());
571            }
572        });
573    }
574}
575
576/// Maximum number of cleared heads kept by each thread-local pool
577const POOL_CAP: usize = 128;
578
579/// Request's objects pool
580pub(crate) struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
581
582thread_local!(static REQUEST_POOL: MessagePool<RequestHead> = MessagePool::<RequestHead>::new());
583thread_local!(static RESPONSE_POOL: MessagePool<ResponseHead> = MessagePool::<ResponseHead>::new());
584
585impl<T: Head> MessagePool<T> {
586    fn new() -> MessagePool<T> {
587        MessagePool(RefCell::new(Vec::with_capacity(256)))
588    }
589
590    /// Get cleared head from the pool
591    #[inline]
592    fn get_head(&self) -> Option<Rc<T>> {
593        self.0.try_borrow_mut().ok()?.pop()
594    }
595
596    fn has_room(&self) -> bool {
597        self.0.try_borrow().is_ok_and(|v| v.len() < POOL_CAP)
598    }
599}
600
601#[cfg(test)]
602mod tests {
603    use super::*;
604
605    /// STATEMENT: Dropping messages nested in extensions permits reentrant pool cleanup.
606    ///
607    /// HOW:
608    /// - Nest request and response messages in extensions, drop the outer owner, and allocate from both pools again.
609    #[test]
610    fn nested_message_drop() {
611        let inner = Message::<RequestHead>::new();
612        let outer = Message::<RequestHead>::new();
613        outer.extensions_mut().insert(inner);
614        let mut res = Message::<ResponseHead>::with_status(StatusCode::OK);
615        res.extensions
616            .get_mut()
617            .insert(Message::<ResponseHead>::new());
618        outer.extensions_mut().insert(res);
619        drop(outer);
620
621        let _ = Message::<RequestHead>::new();
622        let _ = Message::<ResponseHead>::new();
623    }
624
625    /// STATEMENT: Messages can be dropped or allocated after their thread-local pools have been destroyed.
626    ///
627    /// HOW:
628    /// - Arrange a thread-local holder to outlive both pools and manipulate messages in its destructor.
629    /// - Join the thread and verify teardown completes without panic.
630    #[test]
631    fn message_drop_after_pool_destroyed() {
632        struct Holder(Option<Message<RequestHead>>, Option<Message<ResponseHead>>);
633
634        impl Drop for Holder {
635            fn drop(&mut self) {
636                drop(self.0.take());
637                drop(self.1.take());
638                drop(Message::<RequestHead>::new());
639            }
640        }
641
642        thread_local!(static HOLDER: RefCell<Option<Holder>> = const { RefCell::new(None) });
643
644        std::thread::spawn(|| {
645            // register holder before the pools, so it is destroyed after them
646            HOLDER.with(|_| ());
647            let req = Message::<RequestHead>::new();
648            let res = Message::<ResponseHead>::new();
649            HOLDER.with(|h| *h.borrow_mut() = Some(Holder(Some(req), Some(res))));
650        })
651        .join()
652        .unwrap();
653    }
654
655    /// STATEMENT: Response connection defaults depend on HTTP version and can be overridden explicitly.
656    ///
657    /// HOW:
658    /// - Inspect an HTTP/1.1 response, switch to HTTP/1.0, then force keepalive and compare each result.
659    #[test]
660    fn response_connection_type() {
661        let mut res = Message::<ResponseHead>::with_status(StatusCode::OK);
662        assert_eq!(res.connection_type(), ConnectionType::KeepAlive);
663        res.version = Version::HTTP_10;
664        assert_eq!(res.connection_type(), ConnectionType::Close);
665        res.set_connection_type(ConnectionType::KeepAlive);
666        assert_eq!(res.connection_type(), ConnectionType::KeepAlive);
667    }
668
669    /// STATEMENT: Message clones expose the original request metadata, and absent I/O can be taken safely.
670    ///
671    /// HOW:
672    /// - Clone a POST request message and inspect its method, then verify taking absent current I/O returns none.
673    #[test]
674    fn message_clone() {
675        let mut msg = Message::<RequestHead>::new();
676        msg.method = Method::POST;
677        let msg2 = msg.clone();
678        assert_eq!(msg2.method, Method::POST);
679        assert!(CurrentIo::None.take().is_none());
680    }
681}