qualia_core_db/bundle/stream/http/
status.rs1use super::range::{
5 content_type_is_multipart, encoding_is_identity, eq_ignore_ascii_case, parse_u64_ascii,
6 require_exact_partial, trim_ows, write_hex_lower, InclusiveRange, RangeError,
7 LEGACY_FULL_OBJECT_FALLBACK_BYTES,
8};
9use crate::net::qdnf::types::StrongDigest;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum StatusError {
13 Unsupported,
14 Redirect,
15 ChangedValidator,
16 Encoding,
17 Multipart,
18 Unsatisfiable,
19 OverBudget,
20 Length,
21 Syntax,
22 Truncated,
23 Range(RangeError),
24}
25
26impl From<RangeError> for StatusError {
27 fn from(e: RangeError) -> Self {
28 match e {
29 RangeError::Unsatisfiable => Self::Unsatisfiable,
30 RangeError::Encoding => Self::Encoding,
31 RangeError::Multipart => Self::Multipart,
32 RangeError::Mismatch => Self::ChangedValidator,
33 other => Self::Range(other),
34 }
35 }
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum HttpStatusClass {
40 FullObject,
41 Partial,
42 Unsatisfiable,
43 Redirect { code: u16 },
44}
45
46pub fn classify_status(code: u16) -> Result<HttpStatusClass, StatusError> {
48 match code {
49 200 => Ok(HttpStatusClass::FullObject),
50 206 => Ok(HttpStatusClass::Partial),
51 416 => Ok(HttpStatusClass::Unsatisfiable),
52 300..=399 => Ok(HttpStatusClass::Redirect { code }),
53 _ => Err(StatusError::Unsupported),
54 }
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub struct Validator<'a> {
59 pub etag: Option<&'a [u8]>,
60 pub last_modified: Option<&'a [u8]>,
61}
62
63impl<'a> Validator<'a> {
64 pub const NONE: Self = Self {
65 etag: None,
66 last_modified: None,
67 };
68}
69
70pub fn strong_etag(value: &[u8]) -> Option<&[u8]> {
72 let v = trim_ows(value);
73 if starts_weak(v) {
74 return None;
75 }
76 if v.len() >= 2 && v[0] == b'"' && v[v.len() - 1] == b'"' {
77 Some(v)
78 } else {
79 None
80 }
81}
82
83fn starts_weak(v: &[u8]) -> bool {
84 v.len() >= 2 && (v[0] == b'W' || v[0] == b'w') && v[1] == b'/'
85}
86
87pub fn write_strong_etag(digest: StrongDigest, out: &mut [u8]) -> Result<usize, RangeError> {
88 if out.len() < 98 {
89 return Err(RangeError::Capacity);
90 }
91 out[0] = b'"';
92 write_hex_lower(&digest.0, &mut out[1..97])?;
93 out[97] = b'"';
94 Ok(98)
95}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub struct FallbackPolicy {
99 pub allow_full_object: bool,
100 pub max_full_object_bytes: u64,
101}
102
103impl FallbackPolicy {
104 pub const FORBIDDEN: Self = Self {
105 allow_full_object: false,
106 max_full_object_bytes: 0,
107 };
108
109 pub fn explicit(max_bytes: u64) -> Result<Self, StatusError> {
110 if max_bytes == 0 || max_bytes > LEGACY_FULL_OBJECT_FALLBACK_BYTES {
111 return Err(StatusError::OverBudget);
112 }
113 Ok(Self {
114 allow_full_object: true,
115 max_full_object_bytes: max_bytes,
116 })
117 }
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub struct HeaderView<'a> {
122 pub status: u16,
123 pub content_range: Option<&'a [u8]>,
124 pub content_encoding: Option<&'a [u8]>,
125 pub content_length: Option<&'a [u8]>,
126 pub content_type: Option<&'a [u8]>,
127 pub etag: Option<&'a [u8]>,
128 pub last_modified: Option<&'a [u8]>,
129 pub location: Option<&'a [u8]>,
130 pub transfer_encoding: Option<&'a [u8]>,
131}
132
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134pub enum AdmittedTransfer {
135 Partial { length: u64 },
136 FullObject { length: u64 },
137 Unsatisfiable { total: Option<u64> },
138 Redirect { code: u16 },
139}
140
141fn parse_length(raw: Option<&[u8]>) -> Result<u64, StatusError> {
142 let v = raw.ok_or(StatusError::Length)?;
143 parse_u64_ascii(trim_ows(v)).map_err(StatusError::from)
144}
145
146fn validators_match(expected: Validator<'_>, headers: HeaderView<'_>) -> Result<(), StatusError> {
147 if let Some(want) = expected.etag {
148 let got = headers.etag.and_then(strong_etag).ok_or(StatusError::ChangedValidator)?;
149 if got != want {
150 return Err(StatusError::ChangedValidator);
151 }
152 }
153 if let Some(want) = expected.last_modified {
154 let got = headers
155 .last_modified
156 .map(trim_ows)
157 .filter(|v| !v.is_empty())
158 .ok_or(StatusError::ChangedValidator)?;
159 if got != trim_ows(want) {
160 return Err(StatusError::ChangedValidator);
161 }
162 }
163 if let Some(tag) = headers.etag {
164 if starts_weak(trim_ows(tag)) {
165 return Err(StatusError::ChangedValidator);
166 }
167 }
168 Ok(())
169}
170
171pub fn admit_headers(
173 headers: HeaderView<'_>,
174 requested: InclusiveRange,
175 pinned_total: u64,
176 expected: Validator<'_>,
177 fallback: FallbackPolicy,
178 body_budget: u64,
179) -> Result<AdmittedTransfer, StatusError> {
180 if content_type_is_multipart(headers.content_type) {
181 return Err(StatusError::Multipart);
182 }
183 if !encoding_is_identity(headers.content_encoding) {
184 return Err(StatusError::Encoding);
185 }
186 if let Some(te) = headers.transfer_encoding {
187 if !eq_ignore_ascii_case(trim_ows(te), b"identity") {
188 return Err(StatusError::Encoding);
189 }
190 }
191
192 match classify_status(headers.status)? {
193 HttpStatusClass::Redirect { code } => {
194 if headers.location.is_none() {
195 return Err(StatusError::Syntax);
196 }
197 Ok(AdmittedTransfer::Redirect { code })
198 }
199 HttpStatusClass::Unsatisfiable => {
200 let total = match headers.content_range {
201 Some(v) => Some(super::range::parse_unsatisfiable_total(v)?),
202 None => None,
203 };
204 Ok(AdmittedTransfer::Unsatisfiable { total })
205 }
206 HttpStatusClass::Partial => {
207 let cr = headers.content_range.ok_or(StatusError::Syntax)?;
208 require_exact_partial(cr, requested, pinned_total)?;
209 validators_match(expected, headers)?;
210 let length = parse_length(headers.content_length)?;
211 if length != requested.length() || length > body_budget {
212 return Err(StatusError::Length);
213 }
214 Ok(AdmittedTransfer::Partial { length })
215 }
216 HttpStatusClass::FullObject => {
217 if !fallback.allow_full_object {
218 return Err(StatusError::OverBudget);
219 }
220 validators_match(expected, headers)?;
221 let length = parse_length(headers.content_length)?;
222 let cap = fallback
223 .max_full_object_bytes
224 .min(LEGACY_FULL_OBJECT_FALLBACK_BYTES)
225 .min(body_budget);
226 if length == 0 || length > cap {
227 return Err(StatusError::OverBudget);
228 }
229 Ok(AdmittedTransfer::FullObject { length })
230 }
231 }
232}