ntex 4.0.0-beta.17

Framework for composable network services
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use std::{cell::Cell, cell::RefCell};

use bitflags::bitflags;

use crate::client::ClientRawRequest;
use crate::codec::{Decoder, Encoder};
use crate::http::HttpServiceConfig;
use crate::http::error::{DecodeError, EncodeError, PayloadError};
use crate::http::h1::{
    Message, MessageType, PayloadDecoder, PayloadItem, PayloadType, decoder, encoder,
};
use crate::http::{
    ConnectionType, Method, RequestHead, ResponseHead, StatusCode, Version, body::BodySize,
};
use crate::service::cfg::Cfg;
use crate::util::{BytePages, Bytes, BytesMut};

bitflags! {
    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
    struct Flags: u8 {
        const HEAD              = 0b0000_0001;
        const CONNECT           = 0b0000_0010;
        const KEEPALIVE_ENABLED = 0b0000_1000;
        const STREAM            = 0b0001_0000;
    }
}

#[derive(Debug)]
/// HTTP/1 Codec
pub(crate) struct ClientCodec {
    inner: ClientCodecInner,
}

#[derive(Debug)]
/// HTTP/1 Payload Codec
pub(crate) struct ClientPayloadCodec {
    inner: ClientCodecInner,
}

#[derive(Debug)]
struct ClientCodecInner {
    decoder: decoder::MessageDecoder<ResponseHead>,
    payload: RefCell<Option<PayloadDecoder>>,
    version: Cell<Version>,
    ctype: Cell<ConnectionType>,

    // encoder part
    flags: Cell<Flags>,
    encoder: encoder::MessageEncoder<RequestHead>,
}

impl ClientCodec {
    /// Create HTTP/1 codec.
    ///
    /// `keep_alive` controls whether connections are kept alive, which affects
    /// how the `connection` header is generated.
    pub(crate) fn new(keep_alive: bool, cfg: Cfg<HttpServiceConfig>) -> Self {
        let flags = if keep_alive {
            Flags::KEEPALIVE_ENABLED
        } else {
            Flags::empty()
        };
        ClientCodec {
            inner: ClientCodecInner {
                decoder: decoder::MessageDecoder::new(cfg),
                payload: RefCell::new(None),
                version: Cell::new(Version::HTTP_11),
                ctype: Cell::new(ConnectionType::Close),
                flags: Cell::new(flags),
                encoder: encoder::MessageEncoder::default(),
            },
        }
    }

    /// Check if last response is keep-alive
    pub(crate) fn keepalive(&self) -> bool {
        self.inner.ctype.get() == ConnectionType::KeepAlive
    }

    /// Do not keep the connection alive after the current response
    pub(crate) fn set_close(&self) {
        self.inner.ctype.set(ConnectionType::Close);
    }

    /// Check last request's message type
    pub(crate) fn message_type(&self) -> MessageType {
        if self.inner.flags.get().contains(Flags::STREAM) {
            MessageType::Stream
        } else if self.inner.payload.borrow().is_none() {
            MessageType::None
        } else {
            MessageType::Payload
        }
    }

    /// Convert message codec to a payload codec
    pub(crate) fn into_payload_codec(self) -> ClientPayloadCodec {
        ClientPayloadCodec { inner: self.inner }
    }
}

impl ClientPayloadCodec {
    /// Check if last response is keep-alive
    pub(crate) fn keepalive(&self) -> bool {
        self.inner.ctype.get() == ConnectionType::KeepAlive
    }

    /// Check if the payload is delimited by connection close
    pub(crate) fn eof_delimited(&self) -> bool {
        self.inner
            .payload
            .borrow()
            .as_ref()
            .is_some_and(PayloadDecoder::is_eof)
    }
}

impl Decoder for ClientCodec {
    type Item = ResponseHead;
    type Error = DecodeError;

    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        debug_assert!(
            !self.inner.payload.borrow().is_some(),
            "Payload decoder is set"
        );

        loop {
            let Some((req, payload)) = self.inner.decoder.decode(src)? else {
                return Ok(None);
            };

            // skip interim responses, `101` is the final response for upgrades
            if req.status.is_informational() && req.status != StatusCode::SWITCHING_PROTOCOLS {
                log::trace!("Skipping interim response: {}", req.status);
                continue;
            }

            match req.ctype() {
                // do not use peer's keep-alive
                Some(ConnectionType::KeepAlive) => (),
                Some(ctype) => self.inner.ctype.set(ctype),
                // HTTP/1.0 connections are not persistent by default
                None if req.version < Version::HTTP_11 => {
                    self.inner.ctype.set(ConnectionType::Close);
                }
                None => (),
            }

            let flags = self.inner.flags.get();
            if flags.contains(Flags::CONNECT) && req.status.is_success() {
                // the connection becomes a tunnel, framing headers are ignored
                // see https://www.rfc-editor.org/rfc/rfc9112#section-6.3
                self.inner.ctype.set(ConnectionType::Close);
                *self.inner.payload.borrow_mut() = Some(PayloadDecoder::eof());
                self.inner.flags.set(flags | Flags::STREAM);
            } else if flags.contains(Flags::HEAD) {
                self.inner.payload.borrow_mut().take();
            } else {
                match payload {
                    PayloadType::None => {
                        self.inner.payload.borrow_mut().take();
                    }
                    PayloadType::Payload(pl) => *self.inner.payload.borrow_mut() = Some(pl),
                    PayloadType::Stream(pl) => {
                        *self.inner.payload.borrow_mut() = Some(pl);
                        let mut flags = self.inner.flags.get();
                        flags.insert(Flags::STREAM);
                        self.inner.flags.set(flags);
                    }
                }
            }
            return Ok(Some(req));
        }
    }
}

impl Decoder for ClientPayloadCodec {
    type Item = Option<Bytes>;
    type Error = PayloadError;

    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        debug_assert!(
            self.inner.payload.borrow().is_some(),
            "Payload decoder is not specified"
        );

        let item = self
            .inner
            .payload
            .borrow_mut()
            .as_mut()
            .unwrap()
            .decode(src)?;

        Ok(match item {
            Some(PayloadItem::Chunk(chunk)) => Some(Some(chunk)),
            // response trailers are not exposed
            Some(PayloadItem::Trailers(_)) => return self.decode(src),
            Some(PayloadItem::Eof) => {
                self.inner.payload.borrow_mut().take();
                Some(None)
            }
            None => None,
        })
    }
}

impl Encoder for ClientCodec {
    type Item = Message<ClientRawRequest>;
    type Error = EncodeError;

    fn encode(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
        match item {
            Message::Item(mut req) => {
                let inner = &self.inner;
                inner.version.set(req.head.version);
                let mut flags = inner.flags.get();
                flags.set(Flags::HEAD, req.head.method == Method::HEAD);
                flags.set(Flags::CONNECT, req.head.method == Method::CONNECT);
                inner.flags.set(flags);

                // connection status
                inner.ctype.set(match req.head.connection_type() {
                    ConnectionType::KeepAlive => {
                        if inner.flags.get().contains(Flags::KEEPALIVE_ENABLED) {
                            ConnectionType::KeepAlive
                        } else {
                            ConnectionType::Close
                        }
                    }
                    ConnectionType::Upgrade => ConnectionType::Upgrade,
                    ConnectionType::Close => ConnectionType::Close,
                });

                // a request without content declares its length if the method
                // defines meaning for content, see RFC 9110 section 8.6
                let size = if req.size == BodySize::None
                    && matches!(req.head.method, Method::POST | Method::PUT | Method::PATCH)
                {
                    BodySize::Empty
                } else {
                    req.size
                };

                let headers = req.headers.take();
                inner.encoder.encode(
                    dst,
                    &req.head,
                    false,
                    false,
                    inner.version.get(),
                    size,
                    inner.ctype.get(),
                    headers,
                )?;
            }
            Message::Chunk(Some(bytes)) => {
                self.inner.encoder.encode_chunk(bytes, dst);
            }
            Message::Chunk(None) => {
                self.inner.encoder.encode_eof(dst)?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::service::cfg::SharedCfg;

    #[test]
    fn test_skip_interim_responses() {
        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
        let codec = ClientCodec::new(true, cfg.get());

        let mut buf = BytesMut::from(
            "HTTP/1.1 100 Continue\r\n\r\n\
             HTTP/1.1 103 Early Hints\r\nlink: </style.css>\r\n\r\n\
             HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok",
        );
        let head = codec.decode(&mut buf).unwrap().unwrap();
        assert_eq!(head.status, StatusCode::OK);
        assert!(!head.headers.contains_key("link"));
        assert_eq!(codec.message_type(), MessageType::Payload);
        assert_eq!(&buf[..], b"ok");

        // final response is not available yet
        let codec = ClientCodec::new(true, cfg.get());
        let mut buf = BytesMut::from("HTTP/1.1 103 Early Hints\r\n\r\nHTTP/1.1 200");
        assert!(codec.decode(&mut buf).unwrap().is_none());
        buf.extend_from_slice(b" OK\r\ncontent-length: 0\r\n\r\n");
        let head = codec.decode(&mut buf).unwrap().unwrap();
        assert_eq!(head.status, StatusCode::OK);

        // `101` is a final response
        let codec = ClientCodec::new(true, cfg.get());
        let mut buf = BytesMut::from("HTTP/1.1 101 Switching Protocols\r\n\r\n");
        let head = codec.decode(&mut buf).unwrap().unwrap();
        assert_eq!(head.status, StatusCode::SWITCHING_PROTOCOLS);
    }

    #[test]
    fn test_http10_response_keepalive() {
        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
        for (resp, keepalive) in [
            ("HTTP/1.0 200 OK\r\ncontent-length: 0\r\n\r\n", false),
            (
                "HTTP/1.0 200 OK\r\nconnection: keep-alive\r\ncontent-length: 0\r\n\r\n",
                true,
            ),
            ("HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\n", true),
            (
                "HTTP/1.1 200 OK\r\nconnection: close\r\ncontent-length: 0\r\n\r\n",
                false,
            ),
        ] {
            let codec = ClientCodec::new(true, cfg.get());
            // request was sent with keep-alive
            codec.inner.ctype.set(ConnectionType::KeepAlive);
            let mut buf = BytesMut::from(resp);
            codec.decode(&mut buf).unwrap().unwrap();
            assert_eq!(codec.keepalive(), keepalive, "{resp:?}");
        }
    }

    #[crate::rt_test]
    async fn test_connect_response_is_tunnel() {
        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
        let connect = |codec: &ClientCodec| {
            let mut head = crate::http::Message::<RequestHead>::new();
            head.method = Method::CONNECT;
            head.uri = urly::Url::from_static("http://example.com:443");
            let req = ClientRawRequest {
                head,
                headers: None,
                size: crate::http::body::BodySize::None,
            };
            codec
                .encode(Message::Item(req), &mut BytePages::default())
                .unwrap();
        };

        // framing headers of a 2xx response are ignored
        for resp in [
            "HTTP/1.1 200 OK\r\ncontent-length: 0\r\n\r\ntunnel",
            "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\ntunnel",
            "HTTP/1.1 200 OK\r\n\r\ntunnel",
        ] {
            let codec = ClientCodec::new(true, cfg.get());
            connect(&codec);
            let mut buf = BytesMut::from(resp);
            let head = codec.decode(&mut buf).unwrap().unwrap();
            assert_eq!(head.status, StatusCode::OK);
            assert_eq!(codec.message_type(), MessageType::Stream, "{resp:?}");
            assert!(!codec.keepalive(), "{resp:?}");

            let codec = codec.into_payload_codec();
            assert!(codec.eof_delimited());
            assert_eq!(codec.decode(&mut buf).unwrap(), Some(Some("tunnel".into())));
        }

        // other responses use regular framing
        let codec = ClientCodec::new(true, cfg.get());
        connect(&codec);
        let mut buf = BytesMut::from(
            "HTTP/1.1 407 Proxy Authentication Required\r\ncontent-length: 2\r\n\r\nno",
        );
        let head = codec.decode(&mut buf).unwrap().unwrap();
        assert_eq!(head.status, StatusCode::PROXY_AUTHENTICATION_REQUIRED);
        assert_eq!(codec.message_type(), MessageType::Payload);
        assert!(codec.keepalive());
    }

    #[crate::rt_test]
    async fn test_empty_request_content_length() {
        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
        for (method, size, cl) in [
            (Method::POST, BodySize::None, Some("0")),
            (Method::PUT, BodySize::None, Some("0")),
            (Method::PATCH, BodySize::None, Some("0")),
            (Method::POST, BodySize::Sized(3), Some("3")),
            (Method::GET, BodySize::None, None),
            (Method::DELETE, BodySize::None, None),
            (Method::GET, BodySize::Empty, Some("0")),
        ] {
            let codec = ClientCodec::new(true, cfg.get());
            let mut head = crate::http::Message::<RequestHead>::new();
            head.method = method.clone();
            head.uri = urly::Url::from_static("/");
            let req = ClientRawRequest {
                head,
                headers: None,
                size,
            };
            let mut buf = BytePages::default();
            codec.encode(Message::Item(req), &mut buf).unwrap();
            let data = String::from_utf8(buf.take().unwrap().to_vec()).unwrap();
            let expected = cl.map(|cl| format!("content-length: {cl}\r\n"));
            match expected {
                Some(line) => assert!(data.contains(&line), "{method} {size:?}: {data:?}"),
                None => assert!(!data.contains("content-length"), "{method}: {data:?}"),
            }
        }
    }
}