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
use std::str::from_utf8;
use std::slice::Iter as SliceIter;
use std::ascii::AsciiExt;
use std::borrow::Cow;
use httparse::{self, EMPTY_HEADER, Request, Header};
use tk_bufstream::Buf;
use server::error::{Error, ErrorEnum};
use super::{RequestTarget, Dispatcher};
use super::codec::BodyKind;
use super::encoder::ResponseConfig;
use super::websocket::{self, WebsocketHandshake};
use super::request_target;
use headers;
use {Version};
const MIN_HEADERS: usize = 16;
const MAX_HEADERS: usize = 1024;
struct RequestConfig<'a> {
body: BodyKind,
expect_continue: bool,
connection_close: bool,
connection: Option<Cow<'a, str>>,
host: Option<&'a str>,
target: RequestTarget<'a>,
conflicting_host: bool,
}
#[derive(Debug)]
pub struct Head<'a> {
method: &'a str,
raw_target: &'a str,
target: RequestTarget<'a>,
host: Option<&'a str>,
conflicting_host: bool,
version: Version,
headers: &'a [Header<'a>],
body_kind: BodyKind,
connection_close: bool,
connection_header: Option<Cow<'a, str>>,
}
pub struct HeaderIter<'a> {
head: &'a Head<'a>,
iter: SliceIter<'a, Header<'a>>,
}
impl<'a> Head<'a> {
pub fn method(&self) -> &str {
self.method
}
pub fn request_target(&self) -> &RequestTarget<'a> {
&self.target
}
pub fn raw_request_target(&self) -> &str {
self.raw_target
}
pub fn path(&self) -> Option<&str> {
use super::RequestTarget::*;
match self.target {
Origin(x) => Some(x),
Absolute { path, .. } => Some(path),
Authority(..) => None,
Asterisk => None,
}
}
pub fn host(&self) -> Option<&str> {
self.host
}
pub fn has_conflicting_host(&self) -> bool {
self.conflicting_host
}
pub fn version(&self) -> Version {
self.version
}
pub fn headers(&self) -> HeaderIter {
HeaderIter {
head: self,
iter: self.headers.iter(),
}
}
pub fn all_headers(&self) -> &'a [Header<'a>] {
self.headers
}
pub fn connection_close(&self) -> bool {
self.connection_close
}
pub fn connection_header(&'a self) -> Option<&'a str> {
self.connection_header.as_ref().map(|x| &x[..])
}
pub fn has_body(&self) -> bool {
self.body_kind != BodyKind::Fixed(0)
}
pub fn body_length(&self) -> Option<u64> {
match self.body_kind {
BodyKind::Fixed(x) => Some(x),
_ => None,
}
}
pub fn get_websocket_upgrade(&self)
-> Result<Option<WebsocketHandshake>, ()>
{
websocket::get_handshake(self)
}
}
fn scan_headers<'x>(raw_request: &'x Request)
-> Result<RequestConfig<'x>, ErrorEnum>
{
use super::codec::BodyKind::*;
use server::error::ErrorEnum::*;
let mut has_content_length = false;
let mut close = raw_request.version.unwrap() == 0;
let mut expect_continue = false;
let mut body = Fixed(0);
let mut connection = None::<Cow<_>>;
let mut host_header = false;
let target = request_target::parse(raw_request.path.unwrap())
.ok_or(BadRequestTarget)?;
let mut conflicting_host = false;
let mut host = match target {
RequestTarget::Authority(x) => Some(x),
RequestTarget::Absolute { authority, .. } => Some(authority),
_ => None,
};
for header in raw_request.headers.iter() {
if header.name.eq_ignore_ascii_case("Transfer-Encoding") {
if let Some(enc) = header.value.split(|&x| x == b',').last() {
if headers::is_chunked(enc) {
if has_content_length {
close = true;
}
body = Chunked;
}
}
} else if header.name.eq_ignore_ascii_case("Content-Length") {
if has_content_length {
return Err(DuplicateContentLength);
}
has_content_length = true;
if body != Chunked {
let s = from_utf8(header.value)
.map_err(|_| ContentLengthInvalid)?;
let len = s.parse().map_err(|_| ContentLengthInvalid)?;
body = Fixed(len);
} else {
close = true;
}
} else if header.name.eq_ignore_ascii_case("Connection") {
let strconn = from_utf8(header.value)
.map_err(|_| ConnectionInvalid)?.trim();
connection = match connection {
Some(x) => Some(x + ", " + strconn),
None => Some(strconn.into()),
};
if header.value.split(|&x| x == b',').any(headers::is_close) {
close = true;
}
} else if header.name.eq_ignore_ascii_case("Host") {
if host_header {
return Err(DuplicateHost);
}
host_header = true;
let strhost = from_utf8(header.value)
.map_err(|_| HostInvalid)?.trim();
if host.is_none() {
host = Some(strhost);
} else if host != Some(strhost) {
conflicting_host = true;
}
} else if header.name.eq_ignore_ascii_case("Expect") {
if headers::is_continue(header.value) {
expect_continue = true;
}
}
}
if raw_request.method.unwrap() == "CONNECT" {
body = Unsupported;
}
Ok(RequestConfig {
body: body,
expect_continue: expect_continue,
connection: connection,
host: host,
target: target,
connection_close: close,
conflicting_host: conflicting_host,
})
}
pub fn parse_headers<S, D>(buffer: &mut Buf, disp: &mut D)
-> Result<Option<(BodyKind, D::Codec, ResponseConfig)>, Error>
where D: Dispatcher<S>,
{
let (body_kind, codec, cfg, bytes) = {
let mut vec;
let mut headers = [EMPTY_HEADER; MIN_HEADERS];
let mut raw = Request::new(&mut headers);
let mut result = raw.parse(&buffer[..]);
if matches!(result, Err(httparse::Error::TooManyHeaders)) {
vec = vec![EMPTY_HEADER; MAX_HEADERS];
raw = Request::new(&mut vec);
result = raw.parse(&buffer[..]);
}
match result.map_err(ErrorEnum::ParseError)? {
httparse::Status::Complete(bytes) => {
let cfg = scan_headers(&raw)?;
let ver = raw.version.unwrap();
let head = Head {
method: raw.method.unwrap(),
raw_target: raw.path.unwrap(),
target: cfg.target,
version: if ver == 1
{ Version::Http11 } else { Version::Http10 },
host: cfg.host,
conflicting_host: cfg.conflicting_host,
headers: raw.headers,
body_kind: cfg.body,
connection_close: cfg.connection_close || ver == 0,
connection_header: cfg.connection,
};
let codec = disp.headers_received(&head)?;
let response_config = ResponseConfig::from(&head);
(cfg.body, codec, response_config, bytes)
}
_ => return Ok(None),
}
};
buffer.consume(bytes);
Ok(Some((body_kind, codec, cfg)))
}
impl<'a> Iterator for HeaderIter<'a> {
type Item = (&'a str, &'a [u8]);
fn next(&mut self) -> Option<(&'a str, &'a [u8])> {
while let Some(header) = self.iter.next() {
if header.name.eq_ignore_ascii_case("Connection") ||
header.name.eq_ignore_ascii_case("Transfer-Encoding") ||
header.name.eq_ignore_ascii_case("Content-Length") ||
header.name.eq_ignore_ascii_case("Upgrade") ||
header.name.eq_ignore_ascii_case("Host")
{
continue;
}
if let Some(ref conn) = self.head.connection_header {
let mut conn_headers = conn.split(',').map(|x| x.trim());
if conn_headers.any(|x| x.eq_ignore_ascii_case(header.name)) {
continue;
}
}
return Some((header.name, header.value));
}
return None;
}
}