1pub mod headers;
2pub(super) mod known;
3
4use core::{mem, num::NonZero};
5use headers::Bounds;
6
7use crate::{
8 field::text::IntError,
9 h1::{
10 field::{self, TokenError, value},
11 head::request::{Coding, Message},
12 switch, target,
13 },
14};
15
16#[derive(Clone, Copy, PartialEq, Eq, Debug)]
17pub enum Error {
18 Value,
19 Connection(TokenError),
20 ContentLength(IntError),
21 TransferEncoding(value::Error),
22 Host(target::HostError),
23 Message(field::Error),
24 Routing(target::Invalid),
25 Upgrade(switch::UpgradeError),
26}
27
28const _: () = {
29 assert!(mem::size_of::<Error>() == 3 * mem::size_of::<usize>());
30 assert!(mem::size_of::<Option<Error>>() == mem::size_of::<Error>());
31 assert!(!mem::needs_drop::<Error>());
32};
33
34#[derive(Clone, Copy, Default, PartialEq, Eq)]
35pub struct Flags(u16);
36
37impl Flags {
38 const GZIP_SEEN: u16 = 1 << 3;
39 const IDENTITY_SEEN: u16 = 1 << 4;
40 const GZIP_EXCLUDED: u16 = 1 << 5;
41 const WILDCARD_ALLOWED: u16 = 1 << 6;
42 const WILDCARD_EXCLUDED: u16 = 1 << 7;
43 const IDENTITY_EXCLUDED: u16 = 1 << 8;
44
45 fn is_set(self, bit: u16) -> bool {
46 (self.0 & bit) != 0
47 }
48
49 fn set(&mut self, bit: u16) {
50 self.0 |= bit;
51 }
52
53 fn try_apply(&mut self, message: &mut Message, raw: &[u8]) -> Result<(), Error> {
56 let (next, []) = Qualities::scan::<0>(raw)?;
57 message.set_coding(self.append(next));
58 Ok(())
59 }
60
61 fn append(&mut self, next: Self) -> Coding {
62 self.0 |= next.0;
63 let gzip = if self.is_set(Self::GZIP_SEEN) {
64 !self.is_set(Self::GZIP_EXCLUDED)
65 } else {
66 self.is_set(Self::WILDCARD_ALLOWED) && !self.is_set(Self::WILDCARD_EXCLUDED)
67 };
68 let identity = if self.is_set(Self::IDENTITY_SEEN) {
69 !self.is_set(Self::IDENTITY_EXCLUDED)
70 } else {
71 !self.is_set(Self::WILDCARD_EXCLUDED)
72 };
73 Coding::from_flags(identity, gzip)
74 }
75}
76
77#[repr(u8)]
78#[derive(Clone, Copy, PartialEq, Eq, Debug)]
79pub enum Name {
80 Invalid,
81 Method,
82 Scheme,
83 Path,
84 Status,
85 Authority,
86 Protocol,
87 Host,
88 Connection,
89 ContentLength,
90 TransferEncoding,
91 Expect,
92 AcceptEncoding,
93 Te,
94 KeepAlive,
95 ProxyConnection,
96 Upgrade,
97 Regular,
98}
99
100impl Name {
101 pub const H1: [Self; 7] = [
102 Self::Host,
103 Self::Connection,
104 Self::ContentLength,
105 Self::TransferEncoding,
106 Self::Expect,
107 Self::AcceptEncoding,
108 Self::Upgrade,
109 ];
110
111 pub const fn wire(&self) -> &[u8] {
112 match self {
113 Self::Method => b":method",
114 Self::Scheme => b":scheme",
115 Self::Path => b":path",
116 Self::Status => b":status",
117 Self::Authority => b":authority",
118 Self::Protocol => b":protocol",
119 Self::Host => known::HOST.as_bytes(),
120 Self::Connection => known::CONNECTION.as_bytes(),
121 Self::ContentLength => known::CONTENT_LENGTH.as_bytes(),
122 Self::TransferEncoding => known::TRANSFER_ENCODING.as_bytes(),
123 Self::Expect => known::EXPECT.as_bytes(),
124 Self::AcceptEncoding => known::ACCEPT_ENCODING.as_bytes(),
125 Self::Te => known::TE.as_bytes(),
126 Self::KeepAlive => known::KEEP_ALIVE.as_bytes(),
127 Self::ProxyConnection => known::PROXY_CONNECTION.as_bytes(),
128 Self::Upgrade => known::UPGRADE.as_bytes(),
129 Self::Invalid | Self::Regular => b"",
130 }
131 }
132
133 pub const fn is_required(self) -> bool {
134 matches!(
135 self,
136 Self::Host
137 | Self::Connection
138 | Self::ContentLength
139 | Self::TransferEncoding
140 | Self::Expect
141 | Self::Upgrade
142 )
143 }
144
145 pub fn from_h1(name: &[u8]) -> Option<Self> {
146 let known = match name.len() {
147 4 => Self::Host,
148 6 => Self::Expect,
149 7 => Self::Upgrade,
150 10 if name.first()?.eq_ignore_ascii_case(&b'k') => Self::KeepAlive,
151 10 => Self::Connection,
152 14 => Self::ContentLength,
153 15 => Self::AcceptEncoding,
154 17 => Self::TransferEncoding,
155 _ => return None,
156 };
157 name.eq_ignore_ascii_case(known.wire()).then_some(known)
158 }
159}
160
161pub const MAX_HEADER_LINE_BYTES: usize = 8 * 1024;
162
163const GZIP: usize = 0;
164const BR: usize = 1;
165const IDENTITY: usize = 2;
166const WILDCARD: usize = 3;
167
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170pub struct Qualities([NonZero<u16>; 4]);
171
172impl Default for Qualities {
173 fn default() -> Self {
174 Self([NonZero::<u16>::MAX; 4])
175 }
176}
177
178impl Qualities {
179 pub fn try_parse(raw: &[u8]) -> Result<Self, Error> {
180 let (_, values) = Self::scan::<4>(raw)?;
181 Ok(Self(values))
182 }
183
184 pub(crate) fn try_apply(
185 message: &mut Message,
186 flags: &mut Flags,
187 raw: &[u8],
188 ) -> Result<Self, Error> {
189 let (next, values) = Self::scan::<4>(raw)?;
190 message.set_coding(flags.append(next));
191 Ok(Self(values))
192 }
193
194 pub(crate) fn scan_line(
195 message: &mut Message,
196 flags: &mut Flags,
197 raw: &[u8],
198 ) -> Result<Option<(Bounds, Self)>, Error> {
199 let Some(bounds) = Bounds::trim(raw)? else {
200 return Ok(None);
201 };
202 let encoding = Self::try_apply(message, flags, bounds.value(raw))?;
203 Ok(Some((bounds, encoding)))
204 }
205
206 pub fn append(&mut self, other: Self) {
207 for (target, value) in self.0.iter_mut().zip(other.0) {
208 *target = (*target).min(value);
209 }
210 }
211
212 pub fn gzip(self) -> u16 {
213 Self::resolve(self.0[GZIP], self.0[WILDCARD])
214 }
215
216 pub fn br(self) -> u16 {
217 Self::resolve(self.0[BR], self.0[WILDCARD])
218 }
219
220 fn resolve(value: NonZero<u16>, wildcard: NonZero<u16>) -> u16 {
221 match value {
222 value if value != NonZero::<u16>::MAX => value.get() - 1,
223 _ if wildcard != NonZero::<u16>::MAX => wildcard.get() - 1,
224 _ => 0,
225 }
226 }
227
228 pub fn identity(self) -> u16 {
229 match self.0[IDENTITY] {
230 q if q != NonZero::<u16>::MAX => q.get() - 1,
231 _ if self.0[WILDCARD] == NonZero::<u16>::MIN => 0,
232 _ => 1000,
233 }
234 }
235
236 fn scan<const N: usize>(raw: &[u8]) -> Result<(Flags, [NonZero<u16>; N]), Error> {
237 let mut next = Flags::default();
238 let mut values = [NonZero::<u16>::MAX; N];
239 for member in raw.split(|&byte| byte == b',') {
240 let member = crate::field::Error::trim_ows(member);
241 if member.is_empty() {
242 continue;
243 }
244 let end = member
245 .iter()
246 .position(|&byte| !crate::field::Error::is_name_byte(byte))
247 .unwrap_or(member.len());
248 if end == 0 {
249 return Err(Error::Value);
250 }
251 let token = &member[..end];
252 let quality = Self::quality::<N>(&member[end..])?;
253 let slot = if token.eq_ignore_ascii_case(b"gzip") {
254 next.set(Flags::GZIP_SEEN);
255 if quality == 0 {
256 next.set(Flags::GZIP_EXCLUDED);
257 }
258 GZIP
259 } else if token == b"*" {
260 next.set(if quality != 0 {
261 Flags::WILDCARD_ALLOWED
262 } else {
263 Flags::WILDCARD_EXCLUDED
264 });
265 WILDCARD
266 } else if N != 0 && token.eq_ignore_ascii_case(b"br") {
267 BR
268 } else if token.eq_ignore_ascii_case(b"identity") {
269 next.set(Flags::IDENTITY_SEEN);
270 if quality == 0 {
271 next.set(Flags::IDENTITY_EXCLUDED);
272 }
273 IDENTITY
274 } else {
275 continue;
276 };
277 if let Some(target) = values.get_mut(slot)
278 && let Some(value) = NonZero::new(quality + 1)
279 {
280 *target = (*target).min(value);
281 }
282 }
283 Ok((next, values))
284 }
285
286 fn quality<const N: usize>(raw: &[u8]) -> Result<u16, Error> {
289 let raw = crate::field::Error::trim_ows(raw);
290 if raw.is_empty() {
291 return Ok(if N != 0 { 1000 } else { 1 });
292 }
293 let Some(raw) = raw.strip_prefix(b";") else {
294 return Err(Error::Value);
295 };
296 let raw = crate::field::Error::trim_ows(raw);
297 let Some((&name, raw)) = raw.split_first() else {
298 return Err(Error::Value);
299 };
300 if !name.eq_ignore_ascii_case(&b'q') {
301 return Err(Error::Value);
302 }
303 let Some(raw) = raw.strip_prefix(b"=") else {
304 return Err(Error::Value);
305 };
306 let Some((&whole, rest)) = raw.split_first() else {
307 return Err(Error::Value);
308 };
309 if !matches!(whole, b'0' | b'1') {
310 return Err(Error::Value);
311 }
312 let fraction = if rest.is_empty() {
313 rest
314 } else {
315 rest.strip_prefix(b".").ok_or(Error::Value)?
316 };
317 if fraction.len() > 3 {
318 return Err(Error::Value);
319 }
320 let mut quality = u16::from(whole == b'1');
321 if N != 0 {
322 quality *= 1000;
323 }
324 let mut scale = 100;
325 for &byte in fraction {
326 if !byte.is_ascii_digit() || (whole == b'1' && byte != b'0') {
327 return Err(Error::Value);
328 }
329 if N != 0 {
330 quality += u16::from(byte - b'0') * scale;
331 scale /= 10;
332 } else {
333 quality |= u16::from(byte != b'0');
334 }
335 }
336 Ok(quality)
337 }
338}