Skip to main content

sark_http/h1/
framing.rs

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