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
use crate::{
error::Result,
helpers::{
self, BufReadExt, SliceU8Ext,
MatchFlag::{ Required, Trim }
}
};
use std::{
str, collections::BTreeMap, iter::FromIterator, ops::Deref,
io::{ BufRead, Write }
};
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Header {
start_line: HeaderStartLine,
fields: HeaderFields
}
impl Header {
pub const fn new(start_line: HeaderStartLine, fields: HeaderFields) -> Self {
Self { start_line, fields }
}
pub fn start_line(&self) -> &HeaderStartLine {
&self.start_line
}
pub fn start_line_mut(&mut self) -> &mut HeaderStartLine {
&mut self.start_line
}
pub fn fields(&self) -> &HeaderFields {
&self.fields
}
pub fn fields_mut(&mut self) -> &mut HeaderFields {
&mut self.fields
}
pub fn read<T>(source: &mut T) -> Result<Self> where T: BufRead {
let header = source.read_word("\r\n\r\n", [Required])?;
let mut header = helpers::memreader(header);
let start_line = HeaderStartLine::read(&mut header)?;
let fields = HeaderFields::read(&mut header)?;
Ok(Self { start_line, fields })
}
pub fn write(self, output: &mut dyn Write) -> Result {
self.start_line.write(output)?;
self.fields.write(output)?;
output.flush()?;
Ok(())
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct HeaderStartLine {
field0: Vec<u8>,
field1: Vec<u8>,
field2: Vec<u8>,
}
impl HeaderStartLine {
pub fn new_request<T, U>(method: T, target: U) -> Self where T: Into<Vec<u8>>, U: Into<Vec<u8>> {
Self {
field0: method.into(),
field1: target.into(),
field2: "HTTP/1.1".into()
}
}
pub fn new_response<T>(status: u16, reason: T) -> Self where T: Into<Vec<u8>> {
Self {
field0: "HTTP/1.1".into(),
field1: status.to_string().into(),
field2: reason.into()
}
}
pub fn request_method(&self) -> &[u8] {
&self.field0
}
pub fn request_method_mut(&mut self) -> &mut Vec<u8> {
&mut self.field0
}
pub fn request_target(&self) -> &[u8] {
&self.field1
}
pub fn request_target_mut(&mut self) -> &mut Vec<u8> {
&mut self.field1
}
pub fn response_binstatus(&self) -> &[u8] {
&self.field1
}
pub fn response_binstatus_mut(&mut self) -> &mut Vec<u8> {
&mut self.field1
}
pub fn response_reason(&self) -> &[u8] {
&self.field2
}
pub fn response_reason_mut(&mut self) -> &mut Vec<u8> {
&mut self.field2
}
pub fn read<T>(source: &mut T) -> Result<Self> where T: BufRead {
let line = source.read_word("\r\n", [Required, Trim])?;
let mut line = helpers::memreader(line);
let this = Self {
field0: line.read_word(" ", [Required, Trim])?,
field1: line.read_word(" ", [Required, Trim])?,
field2: line.read_all([Required])?
};
Ok(this)
}
pub fn write(self, output: &mut dyn Write) -> Result {
output.write_all(&self.field0)?;
output.write_all(b" ")?;
output.write_all(&self.field1)?;
output.write_all(b" ")?;
output.write_all(&self.field2)?;
output.write_all(b"\r\n")?;
Ok(())
}
}
#[derive(Debug, Default, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct HeaderFields {
fields: BTreeMap<Vec<u8>, Vec<u8>>
}
impl HeaderFields {
pub fn new() -> Self {
Self { fields: BTreeMap::new() }
}
pub fn get<T>(&self, name: T) -> Option<&[u8]> where T: AsRef<[u8]> {
let name = name.as_ascii_lowercase();
self.fields.get(name.as_ref()).map(|s| s.as_ref())
}
pub fn set<A, B>(&mut self, name: A, value: B) where A: AsRef<[u8]>, B: Into<Vec<u8>> {
let name = name.as_ascii_lowercase();
self.fields.insert(name.into(), value.into());
}
pub fn read<T>(source: &mut T) -> Result<Self> where T: BufRead {
let mut this = HeaderFields::new();
'read_lines: loop {
let mut line = match source.read_word("\r\n", [Required, Trim])? {
line if line.is_empty() => break 'read_lines,
line => helpers::memreader(line)
};
let key = line.read_word(":", [Required, Trim])?;
let value = line.read_all([Required])?;
let leading_whitespace = value.iter().take_while(|b| **b == b' ').count();
let value = &value[leading_whitespace..];
this.set(key, value);
}
Ok(this)
}
pub fn write(self, output: &mut dyn Write) -> Result {
for (key, value) in self.fields {
output.write_all(&key)?;
output.write_all(b": ")?;
output.write_all(&value)?;
output.write_all(b"\r\n")?;
}
output.write_all(b"\r\n")?;
Ok(())
}
}
impl Deref for HeaderFields {
type Target = BTreeMap<Vec<u8>, Vec<u8>>;
fn deref(&self) -> &Self::Target {
&self.fields
}
}
impl<K, V> FromIterator<(K, V)> for HeaderFields where K: Into<Vec<u8>>, V: Into<Vec<u8>> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(pairs: T) -> Self {
let fields = pairs.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.map(|(k, v)| (k.to_ascii_lowercase(), v))
.collect();
Self { fields }
}
}
impl IntoIterator for HeaderFields {
type Item = <BTreeMap<Vec<u8>, Vec<u8>> as IntoIterator>::Item;
type IntoIter = <BTreeMap<Vec<u8>, Vec<u8>> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.fields.into_iter()
}
}
pub trait HeaderFieldsExt {
fn get_contentlength(&self) -> Result<Option<u64>>;
fn set_contentlength(&mut self, length: u64);
}
impl HeaderFieldsExt for HeaderFields {
fn get_contentlength(&self) -> Result<Option<u64>> {
let value = match self.get("content-length") {
Some(value) => value,
None => return Ok(None)
};
let value_str = str::from_utf8(value)
.map_err(|_| einval!("Invalid Content-Length field"))?;
let value_int = u64::from_str_radix(value_str, 10)
.map_err(|_| einval!("Invalid Content-Length field"))?;
Ok(Some(value_int))
}
fn set_contentlength(&mut self, length: u64) {
self.set("content-length", length.to_string())
}
}