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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use std::fmt::{Display, Error, Formatter};
use std::str::Utf8Error;
pub mod headers;
pub mod sock_ctrl_msg;
pub mod ascii {
pub const CR: u8 = b'\r';
pub const COLON: u8 = b':';
pub const LF: u8 = b'\n';
pub const SP: u8 = b' ';
pub const CRLF_LEN: usize = 2;
}
#[derive(Debug, Eq, PartialEq)]
pub enum HttpHeaderError {
InvalidFormat(String),
InvalidUtf8String(Utf8Error),
InvalidValue(String, String),
SizeLimitExceeded(String),
UnsupportedFeature(String, String),
UnsupportedName(String),
UnsupportedValue(String, String),
}
impl Display for HttpHeaderError {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::InvalidFormat(header_key) => {
write!(f, "Header is incorrectly formatted. Key: {}", header_key)
}
Self::InvalidUtf8String(header_key) => {
write!(f, "Header contains invalid characters. Key: {}", header_key)
}
Self::InvalidValue(header_name, value) => {
write!(f, "Invalid value. Key:{}; Value:{}", header_name, value)
}
Self::SizeLimitExceeded(inner) => {
write!(f, "Invalid content length. Header: {}", inner)
}
Self::UnsupportedFeature(header_key, header_value) => write!(
f,
"Unsupported feature. Key: {}; Value: {}",
header_key, header_value
),
Self::UnsupportedName(inner) => write!(f, "Unsupported header name. Key: {}", inner),
Self::UnsupportedValue(header_key, header_value) => write!(
f,
"Unsupported value. Key:{}; Value:{}",
header_key, header_value
),
}
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum RequestError {
BodyWithoutPendingRequest,
HeaderError(HttpHeaderError),
HeadersWithoutPendingRequest,
InvalidHttpMethod(&'static str),
InvalidHttpVersion(&'static str),
InvalidRequest,
InvalidUri(&'static str),
Overflow,
Underflow,
SizeLimitExceeded(usize, usize),
}
impl Display for RequestError {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::BodyWithoutPendingRequest => write!(
f,
"No request was pending while the request body was being parsed."
),
Self::HeaderError(inner) => write!(f, "Invalid header. Reason: {}", inner),
Self::HeadersWithoutPendingRequest => write!(
f,
"No request was pending while the request headers were being parsed."
),
Self::InvalidHttpMethod(inner) => write!(f, "Invalid HTTP Method: {}", inner),
Self::InvalidHttpVersion(inner) => write!(f, "Invalid HTTP Version: {}", inner),
Self::InvalidRequest => write!(f, "Invalid request."),
Self::InvalidUri(inner) => write!(f, "Invalid URI: {}", inner),
Self::Overflow => write!(f, "Overflow occurred when parsing a request."),
Self::Underflow => write!(f, "Underflow occurred when parsing a request."),
Self::SizeLimitExceeded(limit, size) => write!(
f,
"Request payload with size {} is larger than the limit of {} \
allowed by server.",
size, limit
),
}
}
}
#[derive(Debug)]
pub enum ConnectionError {
ConnectionClosed,
InvalidWrite,
ParseError(RequestError),
StreamReadError(SysError),
StreamWriteError(std::io::Error),
}
impl Display for ConnectionError {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::ConnectionClosed => write!(f, "Connection closed."),
Self::InvalidWrite => write!(f, "Invalid write attempt."),
Self::ParseError(inner) => write!(f, "Parsing error: {}", inner),
Self::StreamReadError(inner) => write!(f, "Reading stream error: {}", inner),
Self::StreamWriteError(inner) => write!(f, "Writing stream error: {}", inner),
}
}
}
#[derive(Debug)]
#[allow(dead_code)]
pub enum RouteError {
HandlerExist(String),
}
impl Display for RouteError {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
RouteError::HandlerExist(p) => write!(f, "handler for {} already exists", p),
}
}
}
#[derive(Debug)]
pub enum ServerError {
ConnectionError(ConnectionError),
IOError(std::io::Error),
Overflow,
ServerFull,
Underflow,
}
impl Display for ServerError {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::ConnectionError(inner) => write!(f, "Connection error: {}", inner),
Self::IOError(inner) => write!(f, "IO error: {}", inner),
Self::Overflow => write!(f, "Overflow occured while processing messages."),
Self::ServerFull => write!(f, "Server is full."),
Self::Underflow => write!(f, "Underflow occured while processing messages."),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Body {
pub body: Vec<u8>,
}
impl Body {
pub fn new<T: Into<Vec<u8>>>(body: T) -> Self {
Self { body: body.into() }
}
pub fn raw(&self) -> &[u8] {
self.body.as_slice()
}
pub fn len(&self) -> usize {
self.body.len()
}
pub fn is_empty(&self) -> bool {
self.body.len() == 0
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum Method {
Get,
Head,
Post,
Put,
Patch,
Delete,
}
impl Method {
pub fn try_from(bytes: &[u8]) -> Result<Self, RequestError> {
match bytes {
b"GET" => Ok(Self::Get),
b"HEAD" => Ok(Self::Head),
b"POST" => Ok(Self::Post),
b"PUT" => Ok(Self::Put),
b"PATCH" => Ok(Self::Patch),
b"DELETE" => Ok(Self::Delete),
_ => Err(RequestError::InvalidHttpMethod("Unsupported HTTP method.")),
}
}
pub fn raw(self) -> &'static [u8] {
match self {
Self::Get => b"GET",
Self::Head => b"HEAD",
Self::Post => b"POST",
Self::Put => b"PUT",
Self::Patch => b"PATCH",
Self::Delete => b"DELETE",
}
}
pub fn to_str(self) -> &'static str {
match self {
Method::Get => "GET",
Method::Head => "HEAD",
Method::Post => "POST",
Method::Put => "PUT",
Method::Patch => "PATCH",
Method::Delete => "DELETE",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Version {
Http10,
Http11,
}
impl Default for Version {
fn default() -> Self {
Self::Http11
}
}
impl Version {
pub fn raw(self) -> &'static [u8] {
match self {
Self::Http10 => b"HTTP/1.0",
Self::Http11 => b"HTTP/1.1",
}
}
pub fn try_from(bytes: &[u8]) -> Result<Self, RequestError> {
match bytes {
b"HTTP/1.0" => Ok(Self::Http10),
b"HTTP/1.1" => Ok(Self::Http11),
_ => Err(RequestError::InvalidHttpVersion(
"Unsupported HTTP version.",
)),
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SysError(i32);
impl SysError {
pub fn new(errno: i32) -> SysError {
SysError(errno)
}
pub fn last() -> SysError {
SysError(std::io::Error::last_os_error().raw_os_error().unwrap())
}
pub fn errno(self) -> i32 {
self.0
}
}
impl Display for SysError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
std::io::Error::from_raw_os_error(self.0).fmt(f)
}
}
impl std::error::Error for SysError {}
impl From<std::io::Error> for SysError {
fn from(e: std::io::Error) -> Self {
SysError::new(e.raw_os_error().unwrap_or_default())
}
}
impl From<SysError> for std::io::Error {
fn from(err: SysError) -> std::io::Error {
std::io::Error::from_raw_os_error(err.0)
}
}
pub type SysResult<T> = std::result::Result<T, SysError>;
#[cfg(test)]
mod tests {
use super::*;
impl PartialEq for ConnectionError {
fn eq(&self, other: &Self) -> bool {
use self::ConnectionError::*;
match (self, other) {
(ParseError(ref e), ParseError(ref other_e)) => e.eq(other_e),
(ConnectionClosed, ConnectionClosed) => true,
(StreamReadError(ref e), StreamReadError(ref other_e)) => {
format!("{}", e).eq(&format!("{}", other_e))
}
(StreamWriteError(ref e), StreamWriteError(ref other_e)) => {
format!("{}", e).eq(&format!("{}", other_e))
}
(InvalidWrite, InvalidWrite) => true,
_ => false,
}
}
}
#[test]
fn test_version() {
assert_eq!(Version::Http10.raw(), b"HTTP/1.0");
assert_eq!(Version::Http11.raw(), b"HTTP/1.1");
assert_eq!(Version::try_from(b"HTTP/1.0").unwrap(), Version::Http10);
assert_eq!(Version::try_from(b"HTTP/1.1").unwrap(), Version::Http11);
assert_eq!(
Version::try_from(b"HTTP/2.0").unwrap_err(),
RequestError::InvalidHttpVersion("Unsupported HTTP version.")
);
assert_eq!(Version::default(), Version::Http11);
}
#[test]
fn test_method() {
assert_eq!(Method::Get.raw(), b"GET");
assert_eq!(Method::Head.raw(), b"HEAD");
assert_eq!(Method::Post.raw(), b"POST");
assert_eq!(Method::Put.raw(), b"PUT");
assert_eq!(Method::Patch.raw(), b"PATCH");
assert_eq!(Method::Post.raw(), b"POST");
assert_eq!(Method::Delete.raw(), b"DELETE");
assert_eq!(Method::try_from(b"GET").unwrap(), Method::Get);
assert_eq!(Method::try_from(b"HEAD").unwrap(), Method::Head);
assert_eq!(Method::try_from(b"POST").unwrap(), Method::Post);
assert_eq!(Method::try_from(b"PUT").unwrap(), Method::Put);
assert_eq!(Method::try_from(b"PATCH").unwrap(), Method::Patch);
assert_eq!(Method::try_from(b"DELETE").unwrap(), Method::Delete);
assert_eq!(
Method::try_from(b"CONNECT").unwrap_err(),
RequestError::InvalidHttpMethod("Unsupported HTTP method.")
);
assert_eq!(Method::try_from(b"POST").unwrap(), Method::Post);
assert_eq!(Method::try_from(b"DELETE").unwrap(), Method::Delete);
}
#[test]
fn test_body() {
let body = Body::new("".to_string());
assert!(body.is_empty());
let body = Body::new("This is a body.".to_string());
assert_eq!(body.len(), 15);
assert_eq!(body.raw(), b"This is a body.");
}
#[test]
fn test_display_request_error() {
assert_eq!(
format!("{}", RequestError::BodyWithoutPendingRequest),
"No request was pending while the request body was being parsed."
);
assert_eq!(
format!("{}", RequestError::HeadersWithoutPendingRequest),
"No request was pending while the request headers were being parsed."
);
assert_eq!(
format!("{}", RequestError::InvalidHttpMethod("test")),
"Invalid HTTP Method: test"
);
assert_eq!(
format!("{}", RequestError::InvalidHttpVersion("test")),
"Invalid HTTP Version: test"
);
assert_eq!(
format!("{}", RequestError::InvalidRequest),
"Invalid request."
);
assert_eq!(
format!("{}", RequestError::InvalidUri("test")),
"Invalid URI: test"
);
assert_eq!(
format!("{}", RequestError::Overflow),
"Overflow occurred when parsing a request."
);
assert_eq!(
format!("{}", RequestError::Underflow),
"Underflow occurred when parsing a request."
);
assert_eq!(
format!("{}", RequestError::SizeLimitExceeded(4, 10)),
"Request payload with size 10 is larger than the limit of 4 allowed by server."
);
}
#[test]
fn test_display_header_error() {
assert_eq!(
format!(
"{}",
RequestError::HeaderError(HttpHeaderError::InvalidFormat("test".to_string()))
),
"Invalid header. Reason: Header is incorrectly formatted. Key: test"
);
let value = String::from_utf8(vec![0, 159]);
assert_eq!(
format!(
"{}",
RequestError::HeaderError(HttpHeaderError::InvalidUtf8String(
value.unwrap_err().utf8_error()
))
),
"Invalid header. Reason: Header contains invalid characters. Key: invalid utf-8 sequence of 1 bytes from index 1"
);
assert_eq!(
format!(
"{}",
RequestError::HeaderError(HttpHeaderError::SizeLimitExceeded("test".to_string()))
),
"Invalid header. Reason: Invalid content length. Header: test"
);
assert_eq!(
format!(
"{}",
RequestError::HeaderError(HttpHeaderError::UnsupportedFeature(
"test".to_string(),
"test".to_string()
))
),
"Invalid header. Reason: Unsupported feature. Key: test; Value: test"
);
assert_eq!(
format!(
"{}",
RequestError::HeaderError(HttpHeaderError::UnsupportedName("test".to_string()))
),
"Invalid header. Reason: Unsupported header name. Key: test"
);
assert_eq!(
format!(
"{}",
RequestError::HeaderError(HttpHeaderError::UnsupportedValue(
"test".to_string(),
"test".to_string()
))
),
"Invalid header. Reason: Unsupported value. Key:test; Value:test"
);
}
#[test]
fn test_display_connection_error() {
assert_eq!(
format!("{}", ConnectionError::ConnectionClosed),
"Connection closed."
);
assert_eq!(
format!(
"{}",
ConnectionError::ParseError(RequestError::InvalidRequest)
),
"Parsing error: Invalid request."
);
assert_eq!(
format!("{}", ConnectionError::InvalidWrite),
"Invalid write attempt."
);
#[cfg(target_os = "linux")]
assert_eq!(
format!(
"{}",
ConnectionError::StreamWriteError(std::io::Error::from_raw_os_error(11))
),
"Writing stream error: Resource temporarily unavailable (os error 11)"
);
#[cfg(target_os = "macos")]
assert_eq!(
format!(
"{}",
ConnectionError::StreamWriteError(std::io::Error::from_raw_os_error(11))
),
"Writing stream error: Resource deadlock avoided (os error 11)"
);
}
#[test]
fn test_display_server_error() {
assert_eq!(
format!(
"{}",
ServerError::ConnectionError(ConnectionError::ConnectionClosed)
),
"Connection error: Connection closed."
);
#[cfg(target_os = "linux")]
assert_eq!(
format!(
"{}",
ServerError::IOError(std::io::Error::from_raw_os_error(11))
),
"IO error: Resource temporarily unavailable (os error 11)"
);
#[cfg(target_os = "macos")]
assert_eq!(
format!(
"{}",
ServerError::IOError(std::io::Error::from_raw_os_error(11))
),
"IO error: Resource deadlock avoided (os error 11)"
);
assert_eq!(
format!("{}", ServerError::Overflow),
"Overflow occured while processing messages."
);
assert_eq!(format!("{}", ServerError::ServerFull), "Server is full.");
assert_eq!(
format!("{}", ServerError::Underflow),
"Underflow occured while processing messages."
);
}
#[test]
fn test_display_route_error() {
assert_eq!(
format!("{}", RouteError::HandlerExist("test".to_string())),
"handler for test already exists"
);
}
#[test]
fn test_method_to_str() {
let val = Method::Get;
assert_eq!(val.to_str(), "GET");
let val = Method::Head;
assert_eq!(val.to_str(), "HEAD");
let val = Method::Post;
assert_eq!(val.to_str(), "POST");
let val = Method::Put;
assert_eq!(val.to_str(), "PUT");
let val = Method::Patch;
assert_eq!(val.to_str(), "PATCH");
let val = Method::Delete;
assert_eq!(val.to_str(), "DELETE");
}
}