sark-http 0.29.3

HTTP wire types, semantics, codecs, and ownership invariants for Sark
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
//! HTTP/1 message framing and final admission plans.

use crate::{
    field::text::Ascii,
    h1::{
        field::{self, expect},
        switch, target,
    },
    payload::response::Method,
    request::{self, span},
};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    ContentLengthWithTransferEncoding,
    UnframedRequestTransferEncoding,
    Http10TransferEncoding,
    ForbiddenResponseFraming,
    SuccessfulConnectIsTransition,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Response {
    Framing(Error),
    Transition(switch::Error),
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RequestError {
    Authority(target::Error),
    Framing(Error),
    Expectation(expect::Error),
}

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Transfer {
    None,
    Chunked,
    Other,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Message {
    content_length: Option<usize>,
    transfer: Transfer,
}

impl Message {
    pub const fn new(length: Option<usize>, transfer: Transfer) -> Self {
        Self {
            content_length: length,
            transfer,
        }
    }
}

/// Borrow-free state for fields that determine message framing.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Fields {
    content_length: Option<usize>,
    transfer: field::Transfer,
}

impl Fields {
    pub fn try_length(mut self, value: &[u8]) -> Result<Self, field::Error> {
        if self.content_length.is_some() {
            return Err(field::Error::DuplicateContentLength);
        }
        if self.transfer.has_encoding() {
            return Err(field::Error::ContentLengthWithTransferEncoding);
        }
        let length = Ascii::new(crate::field::Error::trim_ows(value))
            .parse_usize()
            .map_err(field::Error::InvalidContentLength)?;
        self.content_length = Some(length);
        Ok(self)
    }

    /// Commits a Content-Length already parsed by a scanner's specialized
    /// integer fast path.
    pub fn try_set(mut self, length: usize) -> Result<Self, field::Error> {
        if self.content_length.is_some() {
            return Err(field::Error::DuplicateContentLength);
        }
        if self.transfer.has_encoding() {
            return Err(field::Error::ContentLengthWithTransferEncoding);
        }
        self.content_length = Some(length);
        Ok(self)
    }

    pub fn try_coding(mut self, value: &[u8]) -> Result<Self, field::Error> {
        if self.content_length.is_some() {
            return Err(field::Error::ContentLengthWithTransferEncoding);
        }
        let transfer = self
            .transfer
            .parse(value)
            .map_err(field::Error::InvalidTransferEncoding)?;
        self.transfer = transfer;
        Ok(self)
    }

    /// Commits one field value already validated by a scanner's specialized
    /// Transfer-Encoding path.
    pub fn try_append(self, value: field::Transfer) -> Result<Self, field::Error> {
        if self.content_length.is_some() {
            return Err(field::Error::ContentLengthWithTransferEncoding);
        }
        let transfer = self
            .transfer
            .try_join(value)
            .map_err(field::Error::InvalidTransferEncoding)?;
        Ok(Self {
            content_length: self.content_length,
            transfer,
        })
    }

    pub const fn length(self) -> Option<usize> {
        self.content_length
    }

    pub const fn has_coding(self) -> bool {
        self.transfer.has_encoding()
    }

    pub const fn is_chunked(self) -> bool {
        self.transfer.is_chunked()
    }

    pub(in crate::h1) const fn has_other(self) -> bool {
        self.transfer.has_other()
    }

    pub const fn finish(self) -> Message {
        Message::new(self.content_length, self.transfer.framing())
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RequestBody {
    Empty,
    Fixed(usize),
    Chunked,
}

/// The protocol-semantic result required before routing may commit an HTTP/1
/// response. It owns only compact metadata; all byte views remain derived from
/// the retained request owner through [`target::Target`] spans.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Admission {
    target: target::Target,
    authority: target::Plan,
    body: RequestBody,
    expectation: expect::Decision,
}

impl Admission {
    pub const fn target(self) -> target::Target {
        self.target
    }

    pub const fn authority(self) -> target::Plan {
        self.authority
    }

    pub const fn body(self) -> RequestBody {
        self.body
    }

    pub const fn expectation(self) -> expect::Decision {
        self.expectation
    }

    pub fn layout(
        self,
        target: span::Span,
        host: Option<span::Span>,
    ) -> Result<request::Layout, target::Error> {
        let span = self.authority.span(self.target, host)?;
        self.target.layout(target, span)
    }

    pub fn admit(
        fields: Fields,
        auth: target::Request,
        expect: expect::State,
        target: target::Target,
        version: &[u8],
        policy: target::Policy,
    ) -> Result<Self, RequestError> {
        let plan = auth
            .finish_plan(target, version)
            .and_then(|plan| match policy {
                target::Policy::AllowEmpty => Ok(plan),
                target::Policy::Require => plan.require(),
            })
            .map_err(RequestError::Authority)?;
        let body = fields
            .finish()
            .try_version(version)
            .and_then(Message::request)
            .map_err(RequestError::Framing)?;
        let decision = if version == b"HTTP/1.0" {
            expect::Decision::None
        } else {
            expect.finish(body).map_err(RequestError::Expectation)?
        };
        Ok(Self {
            target,
            authority: plan,
            body,
            expectation: decision,
        })
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ResponseBody {
    None,
    Fixed(usize),
    Chunked,
    UntilEof,
    Empty(Empty),
}

/// Borrow-free transport decision produced at the same boundary as response
/// framing. Consumers never need to traverse materialized headers again.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct Control {
    keep_alive_timeout_secs: u64,
    connection: field::Connection,
    reuse: Reuse,
}

#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
enum Reuse {
    Close = 1,
    Reusable = 2,
    Timed = 3,
}

impl Control {
    pub const fn new(
        version: u8,
        status: u16,
        body: ResponseBody,
        conn: field::Connection,
        peer: field::KeepAlive,
    ) -> Self {
        let persist = version == 1 || version == 0 && conn.is_keep();
        let (secs, reuse) = if status == 101
            || !persist
            || conn.is_close()
            || conn.is_upgrade()
            || matches!(
                body,
                ResponseBody::UntilEof | ResponseBody::Empty(Empty::UntilEof)
            ) {
            (0, Reuse::Close)
        } else {
            match peer.timeout_secs() {
                Some(timeout) => (timeout, Reuse::Timed),
                None => (0, Reuse::Reusable),
            }
        };
        Self {
            keep_alive_timeout_secs: secs,
            connection: conn,
            reuse,
        }
    }

    pub const fn connection(self) -> field::Connection {
        self.connection
    }

    pub const fn is_reusable(self) -> bool {
        matches!(self.reuse, Reuse::Reusable | Reuse::Timed)
    }

    pub const fn timeout(self) -> Option<u64> {
        match self.reuse {
            Reuse::Timed => Some(self.keep_alive_timeout_secs),
            Reuse::Close | Reuse::Reusable => None,
        }
    }
}

/// Complete semantic result of admitting one HTTP/1 response head.
/// A protocol switch is not an HTTP message body and therefore cannot be
/// accidentally consumed by a normal body decoder.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    Informational,
    Message(ResponseBody),
    Switch(switch::Kind),
}

/// Wire framing that still has to be consumed for a response whose status
/// semantics require the decoded content to remain empty (currently 205).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Empty {
    Fixed,
    Chunked,
    UntilEof,
}

impl Message {
    pub(in crate::h1) fn try_version(self, version: &[u8]) -> Result<Self, Error> {
        if version == b"HTTP/1.0" && !matches!(self.transfer, Transfer::None) {
            return Err(Error::Http10TransferEncoding);
        }
        Ok(self)
    }

    const fn is_unframed(self) -> bool {
        self.content_length.is_none() && matches!(self.transfer, Transfer::None)
    }

    pub const fn request(self) -> Result<RequestBody, Error> {
        if !matches!(self.transfer, Transfer::None) {
            if self.content_length.is_some() {
                return Err(Error::ContentLengthWithTransferEncoding);
            }
            return match self.transfer {
                Transfer::Chunked => Ok(RequestBody::Chunked),
                Transfer::Other => Err(Error::UnframedRequestTransferEncoding),
                Transfer::None => Ok(RequestBody::Empty),
            };
        }
        match self.content_length {
            None | Some(0) => Ok(RequestBody::Empty),
            Some(length) => Ok(RequestBody::Fixed(length)),
        }
    }

    #[inline]
    pub const fn response(self, request: Method, status: u16) -> Result<ResponseBody, Error> {
        self.for_content(crate::payload::response::Content::new(request, status))
    }

    pub(in crate::h1) const fn for_content(
        self,
        content: crate::payload::response::Content,
    ) -> Result<ResponseBody, Error> {
        if self.content_length.is_some() && !matches!(self.transfer, Transfer::None) {
            return Err(Error::ContentLengthWithTransferEncoding);
        }
        use crate::payload::response::Content;
        match content {
            Content::Forbidden => {
                if !self.is_unframed() {
                    return Err(Error::ForbiddenResponseFraming);
                }
                return Ok(ResponseBody::None);
            }
            Content::Suppressed => return Ok(ResponseBody::None),
            Content::Tunnel => return Err(Error::SuccessfulConnectIsTransition),
            Content::Empty => {
                if !matches!(self.content_length, None | Some(0)) {
                    return Err(Error::ForbiddenResponseFraming);
                }
                let empty = match self.transfer {
                    Transfer::None if matches!(self.content_length, Some(0)) => Empty::Fixed,
                    Transfer::None => Empty::UntilEof,
                    Transfer::Chunked => Empty::Chunked,
                    Transfer::Other => Empty::UntilEof,
                };
                return Ok(ResponseBody::Empty(empty));
            }
            Content::Allowed => {}
        }
        Ok(match (self.transfer, self.content_length) {
            (Transfer::Chunked, _) => ResponseBody::Chunked,
            (Transfer::Other, _) | (Transfer::None, None) => ResponseBody::UntilEof,
            (Transfer::None, Some(length)) => ResponseBody::Fixed(length),
        })
    }
}

/// Single parser-neutral response commit point for body framing and protocol
/// transitions. Callers must carry the returned plan through their transport
/// submission barrier before entering raw duplex mode.
impl Outcome {
    pub const fn admit(
        request: Method,
        intent: switch::Intent,
        status: u16,
        framing: Message,
        conn: field::Connection,
        upgrade: Option<switch::Selection>,
    ) -> Result<Self, Response> {
        if status == 101 {
            return match intent {
                switch::Intent::Upgrade => {
                    if !conn.is_upgrade() {
                        Err(Response::Transition(
                            switch::Error::MissingConnectionUpgrade,
                        ))
                    } else if upgrade.is_none() {
                        Err(Response::Transition(switch::Error::MissingSelection))
                    } else if !framing.is_unframed() {
                        Err(Response::Framing(Error::ForbiddenResponseFraming))
                    } else {
                        Ok(Self::Switch(switch::Kind::Upgrade))
                    }
                }
                switch::Intent::None | switch::Intent::Connect => {
                    Err(Response::Transition(switch::Error::UnexpectedSwitch))
                }
            };
        }

        if status < 200 {
            if !framing.is_unframed() {
                return Err(Response::Framing(Error::ForbiddenResponseFraming));
            }
            return Ok(Self::Informational);
        }

        if matches!(intent, switch::Intent::Connect) && status < 300 {
            return Ok(Self::Switch(switch::Kind::Connect));
        }

        match framing.response(request, status) {
            Ok(body) => Ok(Self::Message(body)),
            Err(error) => Err(Response::Framing(error)),
        }
    }
}

const _: () = assert!(core::mem::size_of::<Fields>() <= 3 * core::mem::size_of::<usize>());
const _: () = assert!(core::mem::size_of::<Admission>() <= 7 * core::mem::size_of::<usize>());
const _: () = assert!(core::mem::size_of::<Control>() == 16);
const _: () = assert!(core::mem::size_of::<Option<Control>>() == 16);