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
use std::{collections::HashMap, fmt};
pub trait Header {
fn fmt(_: &Self) -> String;
}
impl<T: Header> Header for &T {
fn fmt(this: &Self) -> String {
T::fmt(this)
}
}
impl<T: fmt::Display> Header for [T; 2] {
fn fmt([key, value]: &Self) -> String {
format!("{key}: {value}\r\n")
}
}
impl<K: fmt::Display, V: fmt::Display> Header for (K, V) {
fn fmt((key, value): &Self) -> String {
format!("{key}: {value}\r\n")
}
}
#[derive(Default, Clone)]
pub struct Http<'a> {
pub schema: &'a [u8],
pub headers: HashMap<String, &'a [u8]>,
}
impl<'a> Http<'a> {
pub fn get(&self, key: impl AsRef<str>) -> Option<&[u8]> {
self.headers.get(key.as_ref()).copied()
}
fn is_ws_upgrade(&self) -> Option<bool> {
let upgrade = self.get("upgrade")?.eq_ignore_ascii_case(b"websocket");
let connection = self.get("connection")?.eq_ignore_ascii_case(b"upgrade");
Some(upgrade && connection)
}
pub fn get_sec_ws_key(&self) -> Option<&[u8]> {
let suppoted_version = self
.get("sec-websocket-version")?
.windows(2)
.any(|version| version == b"13");
(self.is_ws_upgrade()? && suppoted_version).then_some(self.get("sec-websocket-key")?)
}
pub fn get_sec_ws_accept(&self) -> Option<&[u8]> {
self.is_ws_upgrade()?
.then_some(self.get("sec-websocket-accept")?)
}
pub fn parse(bytes: &mut &'a [u8]) -> std::result::Result<Self, &'static str> {
const HTTP_EOF_ERR: &str = "http parse error: unexpected end";
let schema = trim_ascii_end(split_once(bytes, b'\n').ok_or(HTTP_EOF_ERR)?);
let mut header = HashMap::new();
loop {
match split_once(bytes, b'\n').ok_or(HTTP_EOF_ERR)? {
b"" | b"\r" => {
return Ok(Self {
schema,
headers: header,
})
}
line => {
let mut value = line;
let key = split_once(&mut value, b':')
.ok_or("http parse error: invalid header field")?
.to_ascii_lowercase();
header.insert(
String::from_utf8(key).map_err(|_| "invalid utf-8 bytes")?,
trim_ascii_start(trim_ascii_end(value)),
);
}
}
}
}
}
impl<'a> fmt::Debug for Http<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut header = vec![];
for (key, value) in &self.headers {
if let Ok(value) = std::str::from_utf8(value) {
header.push((key, value))
}
}
f.debug_struct("Http")
.field("schema", &std::str::from_utf8(self.schema))
.field("header", &header)
.finish()
}
}
fn split_once<'a>(reader: &mut &'a [u8], ascii: u8) -> Option<&'a [u8]> {
let index = reader.iter().position(|&byte| ascii == byte)?;
let val = &reader[..index];
*reader = &reader[index + 1..];
Some(val)
}
const fn trim_ascii_start(mut bytes: &[u8]) -> &[u8] {
while let [first, rest @ ..] = bytes {
if first.is_ascii_whitespace() {
bytes = rest;
} else {
break;
}
}
bytes
}
const fn trim_ascii_end(mut bytes: &[u8]) -> &[u8] {
while let [rest @ .., last] = bytes {
if last.is_ascii_whitespace() {
bytes = rest;
} else {
break;
}
}
bytes
}