Skip to main content

sark_http/h1/
framing.rs

1//! HTTP/1 message framing and final admission plans.
2
3use crate::{
4    field::text::Ascii,
5    h1::{
6        field::{self, expect},
7        head::line::Version,
8        switch, target,
9    },
10    payload::response::Method,
11    request::{self, span},
12};
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum Error {
16    ContentLengthWithTransferEncoding,
17    UnframedRequestTransferEncoding,
18    Http10TransferEncoding,
19    ForbiddenResponseFraming,
20    SuccessfulConnectIsTransition,
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum Response {
25    Framing(Error),
26    Transition(switch::Error),
27}
28
29#[derive(Clone, Copy, PartialEq, Eq, Debug)]
30pub enum RequestError {
31    Authority(target::Error),
32    Framing(Error),
33    Expectation(expect::Error),
34}
35
36#[derive(Clone, Copy, PartialEq, Eq)]
37#[repr(u8)]
38pub enum Transfer {
39    None,
40    Chunked,
41    Other,
42}
43
44#[derive(Clone, Copy, PartialEq, Eq)]
45pub struct Message {
46    content_length: Option<usize>,
47    transfer: Transfer,
48}
49
50impl Message {
51    pub const fn new(length: Option<usize>, transfer: Transfer) -> Self {
52        Self {
53            content_length: length,
54            transfer,
55        }
56    }
57}
58
59/// Borrow-free state for fields that determine message framing.
60#[derive(Clone, Copy, Default, PartialEq, Eq)]
61pub struct Fields {
62    content_length: Option<usize>,
63    transfer: field::Transfer,
64}
65
66impl Fields {
67    pub fn try_length(mut self, value: &[u8]) -> Result<Self, field::Error> {
68        if self.content_length.is_some() {
69            return Err(field::Error::DuplicateContentLength);
70        }
71        if self.transfer.has_encoding() {
72            return Err(field::Error::ContentLengthWithTransferEncoding);
73        }
74        let length = Ascii::new(crate::field::Error::trim_ows(value))
75            .parse_usize()
76            .map_err(field::Error::InvalidContentLength)?;
77        self.content_length = Some(length);
78        Ok(self)
79    }
80
81    /// Commits a Content-Length already parsed by a scanner's specialized
82    /// integer fast path.
83    pub fn try_set(mut self, length: usize) -> Result<Self, field::Error> {
84        if self.content_length.is_some() {
85            return Err(field::Error::DuplicateContentLength);
86        }
87        if self.transfer.has_encoding() {
88            return Err(field::Error::ContentLengthWithTransferEncoding);
89        }
90        self.content_length = Some(length);
91        Ok(self)
92    }
93
94    pub fn try_coding(mut self, value: &[u8]) -> Result<Self, field::Error> {
95        if self.content_length.is_some() {
96            return Err(field::Error::ContentLengthWithTransferEncoding);
97        }
98        let transfer = self
99            .transfer
100            .parse(value)
101            .map_err(field::Error::InvalidTransferEncoding)?;
102        self.transfer = transfer;
103        Ok(self)
104    }
105
106    /// Commits one field value already validated by a scanner's specialized
107    /// Transfer-Encoding path.
108    pub fn try_append(self, value: field::Transfer) -> Result<Self, field::Error> {
109        if self.content_length.is_some() {
110            return Err(field::Error::ContentLengthWithTransferEncoding);
111        }
112        let transfer = self
113            .transfer
114            .try_join(value)
115            .map_err(field::Error::InvalidTransferEncoding)?;
116        Ok(Self {
117            content_length: self.content_length,
118            transfer,
119        })
120    }
121
122    pub const fn length(self) -> Option<usize> {
123        self.content_length
124    }
125
126    pub const fn has_coding(self) -> bool {
127        self.transfer.has_encoding()
128    }
129
130    pub const fn is_chunked(self) -> bool {
131        self.transfer.is_chunked()
132    }
133
134    pub(in crate::h1) const fn has_other(self) -> bool {
135        self.transfer.has_other()
136    }
137
138    pub const fn finish(self) -> Message {
139        Message::new(self.content_length, self.transfer.framing())
140    }
141}
142
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub enum RequestBody {
145    Empty,
146    Fixed(usize),
147    Chunked,
148}
149
150/// The protocol-semantic result required before routing may commit an HTTP/1
151/// response. It owns only compact metadata; all byte views remain derived from
152/// the retained request owner through [`target::Target`] spans.
153#[derive(Clone, Copy, PartialEq, Eq)]
154pub struct Admission {
155    target: target::Target,
156    authority: target::Source,
157    body: RequestBody,
158    expectation: expect::Decision,
159}
160
161impl Admission {
162    pub const fn target(self) -> target::Target {
163        self.target
164    }
165
166    pub const fn authority(self) -> target::Source {
167        self.authority
168    }
169
170    pub const fn body(self) -> RequestBody {
171        self.body
172    }
173
174    pub const fn expectation(self) -> expect::Decision {
175        self.expectation
176    }
177
178    pub(in crate::h1) fn authority_span(
179        self,
180        host: Option<span::Span>,
181    ) -> Result<span::Span, target::Error> {
182        match self.authority {
183            target::Source::Host => host.ok_or(target::Error::InvalidHost),
184            target::Source::Target => self.target.authority().ok_or(target::Error::InvalidTarget),
185            target::Source::Empty => Err(target::Error::EmptyAuthority),
186        }
187    }
188
189    #[inline(always)]
190    pub fn layout(
191        self,
192        target: span::Span,
193        host: Option<span::Span>,
194    ) -> Result<request::Layout, target::Error> {
195        let span = self.authority_span(host)?;
196        self.target.layout(target, span)
197    }
198
199    pub fn admit(
200        fields: Fields,
201        auth: target::Request,
202        expect: expect::State,
203        target: target::Target,
204        version: Version,
205        policy: target::Policy,
206    ) -> Result<Self, RequestError> {
207        let authority = auth
208            .finish(target, version, policy)
209            .map_err(RequestError::Authority)?;
210        let body = fields
211            .finish()
212            .try_version(version)
213            .and_then(Message::request)
214            .map_err(RequestError::Framing)?;
215        let decision = if version == Version::Ten {
216            expect::Decision::None
217        } else {
218            expect.finish(body).map_err(RequestError::Expectation)?
219        };
220        Ok(Self {
221            target,
222            authority,
223            body,
224            expectation: decision,
225        })
226    }
227}
228
229#[derive(Clone, Copy, PartialEq, Eq)]
230pub enum ResponseBody {
231    None,
232    Fixed(usize),
233    Chunked,
234    UntilEof,
235    Empty(Empty),
236}
237
238/// Borrow-free transport decision produced at the same boundary as response
239/// framing. Consumers never need to traverse materialized headers again.
240#[derive(Clone, Copy, PartialEq, Eq)]
241#[repr(C)]
242pub struct Control {
243    keep_alive_timeout_secs: u64,
244    connection: field::Connection,
245    reuse: Reuse,
246}
247
248#[derive(Clone, Copy, PartialEq, Eq)]
249#[repr(u8)]
250enum Reuse {
251    Close = 1,
252    Reusable = 2,
253    Timed = 3,
254}
255
256impl Control {
257    pub const fn new(
258        version: Version,
259        status: u16,
260        body: ResponseBody,
261        conn: field::Connection,
262        peer: field::KeepAlive,
263    ) -> Self {
264        let (secs, reuse) = if status == 101
265            || !conn.is_persistent(version)
266            || conn.is_upgrade()
267            || matches!(
268                body,
269                ResponseBody::UntilEof | ResponseBody::Empty(Empty::UntilEof)
270            ) {
271            (0, Reuse::Close)
272        } else {
273            match peer.timeout_secs() {
274                Some(timeout) => (timeout, Reuse::Timed),
275                None => (0, Reuse::Reusable),
276            }
277        };
278        Self {
279            keep_alive_timeout_secs: secs,
280            connection: conn,
281            reuse,
282        }
283    }
284
285    pub const fn connection(self) -> field::Connection {
286        self.connection
287    }
288
289    pub const fn is_reusable(self) -> bool {
290        matches!(self.reuse, Reuse::Reusable | Reuse::Timed)
291    }
292
293    pub const fn timeout(self) -> Option<u64> {
294        match self.reuse {
295            Reuse::Timed => Some(self.keep_alive_timeout_secs),
296            Reuse::Close | Reuse::Reusable => None,
297        }
298    }
299}
300
301/// Complete semantic result of admitting one HTTP/1 response head.
302/// A protocol switch is not an HTTP message body and therefore cannot be
303/// accidentally consumed by a normal body decoder.
304#[derive(Clone, Copy, PartialEq, Eq)]
305pub enum Outcome {
306    Informational,
307    Message(ResponseBody),
308    Switch(switch::Kind),
309}
310
311/// Wire framing that still has to be consumed for a response whose status
312/// semantics require the decoded content to remain empty (currently 205).
313#[derive(Clone, Copy, PartialEq, Eq)]
314pub enum Empty {
315    Fixed,
316    Chunked,
317    UntilEof,
318}
319
320impl Message {
321    pub(in crate::h1) fn try_version(self, version: Version) -> Result<Self, Error> {
322        if version == Version::Ten && !matches!(self.transfer, Transfer::None) {
323            return Err(Error::Http10TransferEncoding);
324        }
325        Ok(self)
326    }
327
328    const fn is_unframed(self) -> bool {
329        self.content_length.is_none() && matches!(self.transfer, Transfer::None)
330    }
331
332    pub const fn request(self) -> Result<RequestBody, Error> {
333        if !matches!(self.transfer, Transfer::None) {
334            if self.content_length.is_some() {
335                return Err(Error::ContentLengthWithTransferEncoding);
336            }
337            return match self.transfer {
338                Transfer::Chunked => Ok(RequestBody::Chunked),
339                Transfer::Other => Err(Error::UnframedRequestTransferEncoding),
340                Transfer::None => Ok(RequestBody::Empty),
341            };
342        }
343        match self.content_length {
344            None | Some(0) => Ok(RequestBody::Empty),
345            Some(length) => Ok(RequestBody::Fixed(length)),
346        }
347    }
348
349    #[inline]
350    pub const fn response(self, request: Method, status: u16) -> Result<ResponseBody, Error> {
351        self.for_content(crate::payload::response::Content::new(request, status))
352    }
353
354    pub(in crate::h1) const fn for_content(
355        self,
356        content: crate::payload::response::Content,
357    ) -> Result<ResponseBody, Error> {
358        if self.content_length.is_some() && !matches!(self.transfer, Transfer::None) {
359            return Err(Error::ContentLengthWithTransferEncoding);
360        }
361        use crate::payload::response::Content;
362        match content {
363            Content::Forbidden => {
364                if !self.is_unframed() {
365                    return Err(Error::ForbiddenResponseFraming);
366                }
367                return Ok(ResponseBody::None);
368            }
369            Content::Suppressed => return Ok(ResponseBody::None),
370            Content::Tunnel => return Err(Error::SuccessfulConnectIsTransition),
371            Content::Empty => {
372                if !matches!(self.content_length, None | Some(0)) {
373                    return Err(Error::ForbiddenResponseFraming);
374                }
375                let empty = match self.transfer {
376                    Transfer::None if matches!(self.content_length, Some(0)) => Empty::Fixed,
377                    Transfer::None => Empty::UntilEof,
378                    Transfer::Chunked => Empty::Chunked,
379                    Transfer::Other => Empty::UntilEof,
380                };
381                return Ok(ResponseBody::Empty(empty));
382            }
383            Content::Allowed => {}
384        }
385        Ok(match (self.transfer, self.content_length) {
386            (Transfer::Chunked, _) => ResponseBody::Chunked,
387            (Transfer::Other, _) | (Transfer::None, None) => ResponseBody::UntilEof,
388            (Transfer::None, Some(length)) => ResponseBody::Fixed(length),
389        })
390    }
391}
392
393/// Single parser-neutral response commit point for body framing and protocol
394/// transitions. Callers must carry the returned plan through their transport
395/// submission barrier before entering raw duplex mode.
396impl Outcome {
397    pub const fn admit(
398        request: Method,
399        intent: switch::Intent,
400        status: u16,
401        framing: Message,
402        conn: field::Connection,
403        upgrade: Option<switch::Selection>,
404    ) -> Result<Self, Response> {
405        if status == 101 {
406            return match intent {
407                switch::Intent::Upgrade => {
408                    if !conn.is_upgrade() {
409                        Err(Response::Transition(
410                            switch::Error::MissingConnectionUpgrade,
411                        ))
412                    } else if upgrade.is_none() {
413                        Err(Response::Transition(switch::Error::MissingSelection))
414                    } else if !framing.is_unframed() {
415                        Err(Response::Framing(Error::ForbiddenResponseFraming))
416                    } else {
417                        Ok(Self::Switch(switch::Kind::Upgrade))
418                    }
419                }
420                switch::Intent::None | switch::Intent::Connect => {
421                    Err(Response::Transition(switch::Error::UnexpectedSwitch))
422                }
423            };
424        }
425
426        if status < 200 {
427            if !framing.is_unframed() {
428                return Err(Response::Framing(Error::ForbiddenResponseFraming));
429            }
430            return Ok(Self::Informational);
431        }
432
433        if matches!(intent, switch::Intent::Connect) && status < 300 {
434            return Ok(Self::Switch(switch::Kind::Connect));
435        }
436
437        match framing.response(request, status) {
438            Ok(body) => Ok(Self::Message(body)),
439            Err(error) => Err(Response::Framing(error)),
440        }
441    }
442}
443
444const _: () = assert!(core::mem::size_of::<Fields>() <= 3 * core::mem::size_of::<usize>());
445const _: () = assert!(core::mem::size_of::<Admission>() <= 7 * core::mem::size_of::<usize>());
446const _: () = assert!(core::mem::size_of::<Control>() == 16);
447const _: () = assert!(core::mem::size_of::<Option<Control>>() == 16);