Skip to main content

ntex/web/types/
mod.rs

1//! Extractor types
2
3pub(in crate::web) mod form;
4pub(in crate::web) mod json;
5mod path;
6pub(in crate::web) mod payload;
7mod query;
8
9pub use self::form::{Form, FormConfig};
10pub use self::json::{Json, JsonConfig};
11pub use self::path::Path;
12pub use self::payload::{Payload, PayloadConfig};
13pub use self::query::Query;
14
15use std::{future::Future, pin::Pin, task::Context, task::Poll};
16
17#[cfg(feature = "compress")]
18use crate::http::encoding::Decoder;
19use crate::http::{Payload as HttpPayload, error::PayloadError, helpers::take_trimmed};
20use crate::util::{Bytes, BytesMut, Stream};
21use crate::web::HttpRequest;
22
23/// Request body stream, decoded according to `Content-Encoding`.
24enum BodyStream {
25    Plain(HttpPayload),
26    #[cfg(feature = "compress")]
27    Decoded(Box<Decoder<HttpPayload>>),
28}
29
30impl BodyStream {
31    /// Takes the request payload, a body without `Content-Encoding` is not
32    /// passed through a decoder.
33    fn new(req: &HttpRequest, payload: &mut HttpPayload) -> Self {
34        #[cfg(feature = "compress")]
35        if req
36            .headers()
37            .contains_key(&crate::http::header::CONTENT_ENCODING)
38        {
39            return BodyStream::Decoded(Box::new(Decoder::from_headers(
40                payload.take(),
41                req.headers(),
42            )));
43        }
44        #[cfg(not(feature = "compress"))]
45        let _ = req;
46        BodyStream::Plain(payload.take())
47    }
48}
49
50impl Stream for BodyStream {
51    type Item = Result<Bytes, PayloadError>;
52
53    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
54        match self.get_mut() {
55            BodyStream::Plain(pl) => Pin::new(pl).poll_next(cx),
56            #[cfg(feature = "compress")]
57            BodyStream::Decoded(pl) => Pin::new(pl.as_mut()).poll_next(cx),
58        }
59    }
60}
61
62/// Failure to read the complete body.
63enum ReadBodyError {
64    /// The body size exceeds the limit
65    Overflow(usize),
66    Payload(PayloadError),
67}
68
69/// Future that reads the complete body, failing with
70/// `ReadBodyError::Overflow(size)` once `size > limit`.
71///
72/// A single-chunk body is copied only if it is a part of a larger buffer,
73/// which it would otherwise keep alive.
74struct ReadBody<S> {
75    stream: S,
76    limit: usize,
77    length: Option<usize>,
78    first: Option<Bytes>,
79    body: Option<BytesMut>,
80}
81
82impl<S> ReadBody<S> {
83    fn new(stream: S, limit: usize, length: Option<usize>) -> Self {
84        ReadBody {
85            stream,
86            limit,
87            length,
88            first: None,
89            body: None,
90        }
91    }
92}
93
94impl ReadBody<BodyStream> {
95    fn from_request(req: &HttpRequest, payload: &mut HttpPayload, limit: usize) -> Self {
96        Self::new(BodyStream::new(req, payload), limit, None)
97    }
98
99    fn length(mut self, length: Option<usize>) -> Self {
100        self.length = length;
101        self
102    }
103}
104
105impl<S> Future for ReadBody<S>
106where
107    S: Stream<Item = Result<Bytes, PayloadError>> + Unpin,
108{
109    type Output = Result<Bytes, ReadBodyError>;
110
111    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
112        let this = self.get_mut();
113        loop {
114            let chunk = match Pin::new(&mut this.stream).poll_next(cx) {
115                Poll::Ready(Some(Ok(chunk))) => chunk,
116                Poll::Ready(Some(Err(err))) => {
117                    return Poll::Ready(Err(ReadBodyError::Payload(err)));
118                }
119                Poll::Ready(None) => {
120                    let body = if let Some(mut body) = this.body.take() {
121                        take_trimmed(&mut body)
122                    } else if let Some(mut first) = this.first.take() {
123                        first.trimdown();
124                        first
125                    } else {
126                        Bytes::new()
127                    };
128                    return Poll::Ready(Ok(body));
129                }
130                Poll::Pending => return Poll::Pending,
131            };
132
133            if let Some(body) = this.body.as_mut() {
134                let size = body.len() + chunk.len();
135                if size > this.limit {
136                    return Poll::Ready(Err(ReadBodyError::Overflow(size)));
137                }
138                body.extend_from_slice(&chunk);
139            } else if let Some(first) = this.first.take() {
140                let size = first.len() + chunk.len();
141                if size > this.limit {
142                    return Poll::Ready(Err(ReadBodyError::Overflow(size)));
143                }
144                let mut body =
145                    BytesMut::with_capacity(this.length.unwrap_or(0).clamp(size, this.limit));
146                body.extend_from_slice(&first);
147                body.extend_from_slice(&chunk);
148                this.body = Some(body);
149            } else {
150                if chunk.len() > this.limit {
151                    return Poll::Ready(Err(ReadBodyError::Overflow(chunk.len())));
152                }
153                this.first = Some(chunk);
154            }
155        }
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use std::{collections::VecDeque, pin::Pin, task::Context, task::Poll};
162
163    use super::*;
164
165    struct Chunks(VecDeque<Result<Bytes, PayloadError>>);
166
167    impl Stream for Chunks {
168        type Item = Result<Bytes, PayloadError>;
169
170        fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
171            Poll::Ready(self.0.pop_front())
172        }
173    }
174
175    fn chunks(items: &[&'static [u8]]) -> Chunks {
176        Chunks(items.iter().map(|b| Ok(Bytes::from_static(b))).collect())
177    }
178
179    /// STATEMENT: Body collection preserves contents, avoids unnecessary retention, and enforces limits.
180    ///
181    /// HOW:
182    /// - Check a static single chunk is reused, an empty stream is empty, and multiple chunks concatenate.
183    /// - Assert oversized backing storage is copied away and an accumulated body has no unused capacity.
184    /// - Exceed a six-byte limit with different chunk layouts and assert overflow reports seven bytes.
185    #[crate::rt_test]
186    async fn test_read_body() {
187        let data: &'static [u8] = b"single chunk";
188        let body = ReadBody::new(chunks(&[data]), 64, None).await.ok().unwrap();
189        assert_eq!(
190            body.as_ptr(),
191            data.as_ptr(),
192            "single chunk must not be copied"
193        );
194
195        let body = ReadBody::new(chunks(&[]), 64, None).await.ok().unwrap();
196        assert!(body.is_empty());
197
198        let body = ReadBody::new(chunks(&[b"ab", b"cd", b"ef"]), 6, Some(6))
199            .await
200            .ok()
201            .unwrap();
202        assert_eq!(body, Bytes::from_static(b"abcdef"));
203
204        // the body does not keep the larger buffer it is a part of
205        let page = Bytes::from(vec![b'x'; 32 * 1024]);
206        let stream = Chunks([Ok(page.slice(..1024))].into());
207        let body = ReadBody::new(stream, 64 * 1024, None).await.ok().unwrap();
208        assert_eq!(body, page.slice(..1024));
209        assert_ne!(body.as_ptr(), page.as_ptr());
210
211        // nor the unused part of the buffer it is read into
212        let chunk = Bytes::from(vec![b'x'; 1000]);
213        let stream = Chunks(std::iter::repeat_n(Ok(chunk), 33).collect());
214        let body = ReadBody::new(stream, 64 * 1024, None).await.ok().unwrap();
215        assert_eq!(body.len(), 33 * 1000);
216        let mut copy = body.clone();
217        copy.trimdown();
218        assert_eq!(copy.as_ptr(), body.as_ptr(), "the body has no unused space");
219
220        for items in [
221            &[&b"abcdefg"[..]][..],
222            &[b"abcd", b"efg"],
223            &[b"ab", b"cd", b"efg"],
224        ] {
225            let res = ReadBody::new(chunks(items), 6, None).await;
226            assert!(matches!(res, Err(ReadBodyError::Overflow(7))));
227        }
228    }
229}