ttpkit 0.1.0

Generic types for implementing protocols like HTTP, RTSP, SIP, etc.
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! Response types.

use std::{
    borrow::Borrow,
    fmt::{self, Debug, Formatter},
    marker::PhantomData,
    ops::Deref,
    str::Utf8Error,
};

use bytes::{Bytes, BytesMut};

#[cfg(feature = "tokio-codec")]
use tokio_util::codec::{Decoder, Encoder};

use crate::{
    error::Error,
    header::{
        FieldIter, HeaderField, HeaderFieldDecoder, HeaderFieldEncoder, HeaderFieldValue,
        HeaderFields, Iter,
    },
    line::{LineDecoder, LineDecoderOptions},
    utils::{
        ascii::AsciiExt,
        num::{self, DecEncoder},
    },
};

#[cfg(feature = "tokio-codec")]
use crate::error::CodecError;

/// Response status.
#[derive(Debug, Clone)]
pub struct Status {
    code: u16,
    msg: StatusMessage,
}

impl Status {
    /// Create a new status with a given code and a message.
    pub fn new<T>(code: u16, msg: T) -> Self
    where
        T: Into<StatusMessage>,
    {
        Self {
            code,
            msg: msg.into(),
        }
    }

    /// Create a new status with a given code and a message.
    #[inline]
    pub const fn from_static_str(code: u16, msg: &'static str) -> Self {
        Self {
            code,
            msg: StatusMessage::from_static_str(msg),
        }
    }

    /// Create a new status with a given code and a message.
    #[inline]
    pub const fn from_static_bytes(code: u16, msg: &'static [u8]) -> Self {
        Self {
            code,
            msg: StatusMessage::from_static_bytes(msg),
        }
    }

    /// Get the status code.
    #[inline]
    pub fn code(&self) -> u16 {
        self.code
    }

    /// Get the status message.
    #[inline]
    pub fn message(&self) -> &StatusMessage {
        &self.msg
    }
}

/// Status message.
#[derive(Clone)]
pub struct StatusMessage {
    inner: Bytes,
}

impl StatusMessage {
    /// Create a new status message.
    #[inline]
    pub const fn from_static_str(s: &'static str) -> Self {
        Self::from_static_bytes(s.as_bytes())
    }

    /// Create a new status message.
    #[inline]
    pub const fn from_static_bytes(s: &'static [u8]) -> Self {
        Self {
            inner: Bytes::from_static(s),
        }
    }

    /// Get the message as an UTF-8 string.
    #[inline]
    pub fn to_str(&self) -> Result<&str, Utf8Error> {
        std::str::from_utf8(&self.inner)
    }
}

impl AsRef<[u8]> for StatusMessage {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.inner
    }
}

impl Borrow<[u8]> for StatusMessage {
    #[inline]
    fn borrow(&self) -> &[u8] {
        &self.inner
    }
}

impl Deref for StatusMessage {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl Debug for StatusMessage {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(&self.inner, f)
    }
}

impl From<&'static [u8]> for StatusMessage {
    #[inline]
    fn from(s: &'static [u8]) -> Self {
        Self::from(Bytes::from(s))
    }
}

impl From<&'static str> for StatusMessage {
    #[inline]
    fn from(s: &'static str) -> Self {
        Self::from(Bytes::from(s))
    }
}

impl From<Bytes> for StatusMessage {
    #[inline]
    fn from(bytes: Bytes) -> Self {
        Self { inner: bytes }
    }
}

impl From<BytesMut> for StatusMessage {
    #[inline]
    fn from(bytes: BytesMut) -> Self {
        Self::from(Bytes::from(bytes))
    }
}

impl From<Box<[u8]>> for StatusMessage {
    #[inline]
    fn from(bytes: Box<[u8]>) -> Self {
        Self::from(Bytes::from(bytes))
    }
}

impl From<Vec<u8>> for StatusMessage {
    #[inline]
    fn from(bytes: Vec<u8>) -> Self {
        Self::from(Bytes::from(bytes))
    }
}

impl From<String> for StatusMessage {
    #[inline]
    fn from(s: String) -> Self {
        Self::from(Bytes::from(s))
    }
}

/// Response header builder.
#[derive(Clone)]
pub struct ResponseHeaderBuilder<P = Bytes, V = Bytes> {
    header: ResponseHeader<P, V>,
}

impl<P, V> ResponseHeaderBuilder<P, V> {
    /// Set the protocol version.
    #[inline]
    pub fn set_version(mut self, version: V) -> Self {
        self.header.version = version;
        self
    }

    /// Set the status.
    #[inline]
    pub fn set_status(mut self, status: Status) -> Self {
        self.header.status = status;
        self
    }

    /// Set the status code.
    #[inline]
    pub fn set_status_code(mut self, status_code: u16) -> Self {
        self.header.status.code = status_code;
        self
    }

    /// Set the status line.
    pub fn set_status_message<T>(mut self, status_msg: T) -> Self
    where
        T: Into<StatusMessage>,
    {
        self.header.status.msg = status_msg.into();
        self
    }

    /// Replace the current header fields having the same name (if any).
    pub fn set_header_field<T>(mut self, field: T) -> Self
    where
        T: Into<HeaderField>,
    {
        self.header.header_fields.set(field);
        self
    }

    /// Add a given header field.
    pub fn add_header_field<T>(mut self, field: T) -> Self
    where
        T: Into<HeaderField>,
    {
        self.header.header_fields.add(field);
        self
    }

    /// Remove all header fields with a given name.
    pub fn remove_header_fields<N>(mut self, name: &N) -> Self
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header.header_fields.remove(name);
        self
    }

    /// Build the response header.
    #[inline]
    pub fn build(self) -> ResponseHeader<P, V> {
        self.header
    }
}

impl<P, V> From<ResponseHeader<P, V>> for ResponseHeaderBuilder<P, V> {
    #[inline]
    fn from(header: ResponseHeader<P, V>) -> Self {
        Self { header }
    }
}

/// Internal error type for invalid response lines.
struct InvalidResponseLine;

impl From<InvalidResponseLine> for Error {
    fn from(_: InvalidResponseLine) -> Self {
        Error::from_static_msg("invalid response line")
    }
}

/// Response header.
///
/// It can be used for construction of custom headers that have the same
/// structure as HTTP headers.
#[derive(Debug, Clone)]
pub struct ResponseHeader<P = Bytes, V = Bytes> {
    protocol: P,
    version: V,
    status: Status,
    header_fields: HeaderFields,
}

impl ResponseHeader {
    /// Parse a given response line.
    fn parse_response_line(line: Bytes) -> Result<Self, InvalidResponseLine> {
        let (protocol, rest) = line.split_once(|b| b == b'/').ok_or(InvalidResponseLine)?;

        let (version, rest) = rest
            .trim_ascii_start()
            .split_once(|b| b.is_ascii_whitespace())
            .ok_or(InvalidResponseLine)?;

        let (status_code, status_msg) = rest
            .trim_ascii_start()
            .split_once(|b| b.is_ascii_whitespace())
            .ok_or(InvalidResponseLine)?;

        let status_code = num::decode_dec(&status_code).map_err(|_| InvalidResponseLine)?;

        let status = Status {
            code: status_code,
            msg: StatusMessage::from(status_msg.trim_ascii()),
        };

        let res = Self {
            protocol: protocol.trim_ascii(),
            version,
            status,
            header_fields: HeaderFields::new(),
        };

        Ok(res)
    }

    /// Parse the response parts from the current header.
    fn parse_response_parts<P, V>(self) -> Result<ResponseHeader<P, V>, Error>
    where
        P: TryFrom<Bytes>,
        V: TryFrom<Bytes>,
        Error: From<P::Error>,
        Error: From<V::Error>,
    {
        let protocol = P::try_from(self.protocol)?;
        let version = V::try_from(self.version)?;

        let res = ResponseHeader {
            protocol,
            version,
            status: self.status,
            header_fields: self.header_fields,
        };

        Ok(res)
    }
}

impl<P, V> ResponseHeader<P, V> {
    /// Create a new response header.
    #[inline]
    pub const fn new(protocol: P, version: V, status: Status) -> Self {
        Self {
            protocol,
            version,
            status,
            header_fields: HeaderFields::new(),
        }
    }

    /// Get a response header builder.
    #[inline]
    pub const fn builder(protocol: P, version: V, status: Status) -> ResponseHeaderBuilder<P, V> {
        ResponseHeaderBuilder {
            header: Self::new(protocol, version, status),
        }
    }

    /// Get type of the protocol.
    #[inline]
    pub fn protocol(&self) -> &P {
        &self.protocol
    }

    /// Get the protocol version.
    #[inline]
    pub fn version(&self) -> &V {
        &self.version
    }

    /// Get the response status.
    #[inline]
    pub fn status(&self) -> &Status {
        &self.status
    }

    /// Get the status code.
    #[inline]
    pub fn status_code(&self) -> u16 {
        self.status.code()
    }

    /// Get the status message.
    #[inline]
    pub fn status_message(&self) -> &StatusMessage {
        self.status.message()
    }

    /// Get all header fields.
    #[inline]
    pub fn get_all_header_fields(&self) -> Iter<'_> {
        self.header_fields.all()
    }

    /// Get header fields corresponding to a given name.
    pub fn get_header_fields<'a, N>(&'a self, name: &'a N) -> FieldIter<'a>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header_fields.get(name)
    }

    /// Get last header field of a given name.
    pub fn get_header_field<'a, N>(&'a self, name: &'a N) -> Option<&'a HeaderField>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header_fields.last(name)
    }

    /// Get value of the last header field with a given name.
    pub fn get_header_field_value<'a, N>(&'a self, name: &'a N) -> Option<&'a HeaderFieldValue>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header_fields.last_value(name)
    }
}

/// Encoder for response headers.
pub struct ResponseHeaderEncoder(());

impl ResponseHeaderEncoder {
    /// Create a new response header encoder.
    #[inline]
    pub const fn new() -> Self {
        Self(())
    }

    /// Encode a given response header.
    pub fn encode<P, V>(&mut self, header: &ResponseHeader<P, V>, dst: &mut BytesMut)
    where
        P: AsRef<[u8]>,
        V: AsRef<[u8]>,
    {
        // helper function to avoid expensive monomorphizations
        fn inner(
            protocol: &[u8],
            version: &[u8],
            status_code: u16,
            status_msg: &[u8],
            fields: &HeaderFields,
            dst: &mut BytesMut,
        ) {
            let mut buf = DecEncoder::new();

            let status_code = buf.encode(status_code);

            let mut hfe = HeaderFieldEncoder::new();

            let len = 7
                + protocol.len()
                + version.len()
                + status_code.len()
                + status_msg.len()
                + fields
                    .all()
                    .map(|f| 2 + hfe.get_encoded_length(f))
                    .sum::<usize>();

            dst.reserve(len);

            dst.extend_from_slice(protocol);
            dst.extend_from_slice(b"/");
            dst.extend_from_slice(version);
            dst.extend_from_slice(b" ");

            dst.extend_from_slice(status_code);
            dst.extend_from_slice(b" ");
            dst.extend_from_slice(status_msg);
            dst.extend_from_slice(b"\r\n");

            for field in fields.all() {
                hfe.encode(field, dst);
                dst.extend_from_slice(b"\r\n");
            }

            dst.extend_from_slice(b"\r\n");
        }

        let protocol = header.protocol.as_ref();
        let version = header.version.as_ref();
        let status_msg = header.status.msg.as_ref();

        inner(
            protocol,
            version,
            header.status.code,
            status_msg,
            &header.header_fields,
            dst,
        )
    }
}

impl Default for ResponseHeaderEncoder {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "tokio-codec")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio-codec")))]
impl<P, V> Encoder<&ResponseHeader<P, V>> for ResponseHeaderEncoder
where
    P: AsRef<[u8]>,
    V: AsRef<[u8]>,
{
    type Error = CodecError;

    #[inline]
    fn encode(
        &mut self,
        header: &ResponseHeader<P, V>,
        dst: &mut BytesMut,
    ) -> Result<(), Self::Error> {
        ResponseHeaderEncoder::encode(self, header, dst);

        Ok(())
    }
}

/// Response header decoder options.
#[derive(Copy, Clone)]
pub struct ResponseHeaderDecoderOptions {
    line_decoder_options: LineDecoderOptions,
    max_header_field_length: Option<usize>,
    max_header_fields: Option<usize>,
}

impl ResponseHeaderDecoderOptions {
    /// Create new response header decoder options.
    ///
    /// By default, only CRLF line endings are accepted, the maximum line
    /// length is 4096 bytes, the maximum header field length is 4096 bytes,
    /// and the maximum number of header fields is 64.
    #[inline]
    pub const fn new() -> Self {
        let line_decoder_options = LineDecoderOptions::new()
            .cr(false)
            .lf(false)
            .crlf(true)
            .max_line_length(Some(4096))
            .require_terminator(false);

        Self {
            line_decoder_options,
            max_header_field_length: Some(4096),
            max_header_fields: Some(64),
        }
    }

    /// Enable or disable acceptance of all line endings (CR, LF, CRLF).
    #[inline]
    pub const fn accept_all_line_endings(mut self, enabled: bool) -> Self {
        self.line_decoder_options = self.line_decoder_options.cr(enabled).lf(enabled).crlf(true);

        self
    }

    /// Set maximum line length.
    #[inline]
    pub const fn max_line_length(mut self, max_length: Option<usize>) -> Self {
        self.line_decoder_options = self.line_decoder_options.max_line_length(max_length);
        self
    }

    /// Set maximum header field length.
    #[inline]
    pub const fn max_header_field_length(mut self, max_length: Option<usize>) -> Self {
        self.max_header_field_length = max_length;
        self
    }

    /// Set maximum number of header fields.
    #[inline]
    pub const fn max_header_fields(mut self, max_fields: Option<usize>) -> Self {
        self.max_header_fields = max_fields;
        self
    }
}

impl Default for ResponseHeaderDecoderOptions {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Decoder for response headers.
pub struct ResponseHeaderDecoder<P, V> {
    inner: InternalResponseHeaderDecoder,
    _pd: PhantomData<(P, V)>,
}

impl<P, V> ResponseHeaderDecoder<P, V> {
    /// Create a new response header decoder.
    pub fn new(options: ResponseHeaderDecoderOptions) -> Self {
        Self {
            inner: InternalResponseHeaderDecoder::new(options),
            _pd: PhantomData,
        }
    }

    /// Reset the decoder and make it ready for parsing a new response header.
    pub fn reset(&mut self) {
        self.inner.reset();
    }
}

impl<P, V> ResponseHeaderDecoder<P, V>
where
    P: TryFrom<Bytes>,
    V: TryFrom<Bytes>,
    Error: From<P::Error>,
    Error: From<V::Error>,
{
    /// Decode a given response header chunk.
    pub fn decode(&mut self, data: &mut BytesMut) -> Result<Option<ResponseHeader<P, V>>, Error> {
        let res = self
            .inner
            .decode(data)?
            .map(ResponseHeader::parse_response_parts)
            .transpose()?;

        Ok(res)
    }

    /// Decode a given response header chunk at the end of the stream.
    pub fn decode_eof(
        &mut self,
        data: &mut BytesMut,
    ) -> Result<Option<ResponseHeader<P, V>>, Error> {
        let res = self
            .inner
            .decode_eof(data)?
            .map(ResponseHeader::parse_response_parts)
            .transpose()?;

        Ok(res)
    }
}

#[cfg(feature = "tokio-codec")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio-codec")))]
impl<P, V> Decoder for ResponseHeaderDecoder<P, V>
where
    P: TryFrom<Bytes>,
    V: TryFrom<Bytes>,
    Error: From<P::Error>,
    Error: From<V::Error>,
{
    type Item = ResponseHeader<P, V>;
    type Error = CodecError;

    #[inline]
    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        ResponseHeaderDecoder::<P, V>::decode(self, buf).map_err(CodecError::Other)
    }

    #[inline]
    fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        ResponseHeaderDecoder::<P, V>::decode_eof(self, buf).map_err(CodecError::Other)
    }
}

/// Response header decoder.
struct InternalResponseHeaderDecoder {
    line_decoder: LineDecoder,
    header: Option<ResponseHeader>,
    field_decoder: HeaderFieldDecoder,
    max_header_fields: Option<usize>,
}

impl InternalResponseHeaderDecoder {
    /// Create a new response header decoder.
    fn new(options: ResponseHeaderDecoderOptions) -> Self {
        Self {
            line_decoder: LineDecoder::new(options.line_decoder_options),
            header: None,
            field_decoder: HeaderFieldDecoder::new(options.max_header_field_length),
            max_header_fields: options.max_header_fields,
        }
    }

    /// Decode a given response header chunk.
    fn decode(&mut self, data: &mut BytesMut) -> Result<Option<ResponseHeader>, Error> {
        while let Some(line) = self.line_decoder.decode(data)? {
            if let Some(header) = self.decode_line(line)? {
                return Ok(Some(header));
            }
        }

        Ok(None)
    }

    /// Decode a given response header chunk at the end of the stream.
    fn decode_eof(&mut self, data: &mut BytesMut) -> Result<Option<ResponseHeader>, Error> {
        while let Some(line) = self.line_decoder.decode_eof(data)? {
            if let Some(header) = self.decode_line(line)? {
                return Ok(Some(header));
            }
        }

        if data.is_empty() && self.line_decoder.is_empty() && self.header.is_none() {
            Ok(None)
        } else {
            Err(Error::from_static_msg("incomplete response header"))
        }
    }

    /// Decode a given response line.
    fn decode_line(&mut self, line: Bytes) -> Result<Option<ResponseHeader>, Error> {
        if let Some(header) = self.header.as_mut() {
            let is_empty_line = line.is_empty();

            if let Some(field) = self.field_decoder.decode(line)? {
                if let Some(max_fields) = self.max_header_fields {
                    if header.header_fields.len() >= max_fields {
                        return Err(Error::from_static_msg(
                            "maximum number of header fields exceeded",
                        ));
                    }
                }

                header.header_fields.add(field);
            }

            // an empty line means the end of the header
            if is_empty_line {
                return Ok(self.take());
            }
        } else {
            self.header = Some(ResponseHeader::parse_response_line(line)?);
        }

        Ok(None)
    }

    /// Reset the decoder and make it ready for parsing a new response header.
    fn reset(&mut self) {
        self.take();
    }

    /// Take the current header and reset the decoder.
    fn take(&mut self) -> Option<ResponseHeader> {
        self.line_decoder.reset();
        self.field_decoder.reset();

        self.header.take()
    }
}