-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsers.rs
176 lines (165 loc) · 5.54 KB
/
parsers.rs
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
use std::collections::HashMap;
use std::fs;
use std::io::prelude::*;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn parse_method(line: &str) -> HashMap<String, String> {
["method", "endpoint", "http"]
.iter()
.map(|c| String::from(*c))
.zip(line.split(" ").map(|c| String::from(c)))
.collect()
}
/// Handle incoming TCP/IP requests by parsing the stream and consuming the
/// header data.
pub fn handle_client(stream: &mut TcpStream) {
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap();
let contents = String::from_utf8_lossy(&buffer[..]);
println!("Request: {}", contents);
let request = parse_request(&contents);
let (status, headers, body) = if is_valid(&request) {
if is_get(&request) || is_post(&request) {
if is_sleep(&request) {
thread::sleep(Duration::from_millis(5000));
(
"HTTP/1.1 200 OK",
fs::read_to_string("html/headers.txt").unwrap(),
fs::read_to_string("html/sleep.html").unwrap(),
)
} else {
(
"HTTP/1.1 200 OK",
fs::read_to_string("html/headers.txt").unwrap(),
fs::read_to_string("html/hello.html").unwrap(),
)
}
} else {
(
"HTTP/1.1 405 Method Not Allowed",
fs::read_to_string("html/headers.txt").unwrap(),
fs::read_to_string("html/405.html").unwrap(),
)
}
} else {
(
"HTTP/1.1 404 Not Found",
fs::read_to_string("html/headers.txt").unwrap(),
fs::read_to_string("html/404.html").unwrap(),
)
};
let info = list_info(&request);
let body = body.replace("{{}}", &info);
let response = format!(
"{}\r\n{}\r\n\r\n{}",
status,
headers,
body
);
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
println!("Response: {}", status);
println!("Headers: {}", headers);
println!("Body: {}", body);
}
fn list_info(req: &HashMap<String, String>) -> String {
let v: Vec<String> = req
.iter()
.map(|tpl| format!("<li><strong>{}</strong>: {}</li>", tpl.0, tpl.1))
.collect();
v.join("\n")
}
fn is_get(req: &HashMap<String, String>) -> bool {
let s = String::new();
req.get("method").unwrap_or(&s).contains("GET")
}
fn is_post(req: &HashMap<String, String>) -> bool {
let s = String::new();
req.get("method").unwrap_or(&s).contains("POST")
}
fn is_valid(req: &HashMap<String, String>) -> bool {
let s = String::new();
let endpoint = req.get("endpoint").unwrap_or(&s);
endpoint == "/" || endpoint.contains("/sleep")
}
fn is_sleep(req: &HashMap<String, String>) -> bool {
let s = String::new();
let endpoint = req.get("endpoint").unwrap_or(&s);
endpoint.contains("/sleep") || endpoint.contains("/sleep/")
}
/// `parse_request` parses the string that is returned from consuming the TCP stream associated with the HTTP request
pub fn parse_request(req: &str) -> HashMap<String, String> {
let mut out = HashMap::new();
for (i, line) in req.lines().enumerate() {
if i == 0 {
for (k, v) in parse_method(line).iter() {
out.insert(String::from(k), String::from(v));
}
} else {
let mut chunks = line.split(": ");
let key = chunks.nth(0).unwrap_or("").trim().to_lowercase();
let value = chunks.nth(0).unwrap_or("").trim();
if key.len() == 0 || value.len() == 0 {
continue;
}
out.insert(key, value.into());
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn test_empty_req() {
assert_eq!(parse_request(""), HashMap::new());
}
#[test]
fn test_get_sleep_req() {
let r = "GET /sleep/ HTTP/1.1
Host: 127.0.0.1:7878
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: PGADMIN_KEY=545c5f7d-bd15-44bf-8d8c-008ca33e5a61; PGADMIN_LANGUAGE=en
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0";
let parsed = parse_request(r);
assert!(
parsed.get("endpoint").unwrap() == "/sleep/" && parsed.get("method").unwrap() == "GET"
);
}
#[test]
fn test_get_index_req() {
let r = "GET / HTTP/1.1
Host: 127.0.0.1:7878
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: PGADMIN_KEY=545c5f7d-bd15-44bf-8d8c-008ca33e5a61; PGADMIN_LANGUAGE=en
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0";
let parsed = parse_request(r);
assert!(parsed.get("endpoint").unwrap() == "/" && parsed.get("method").unwrap() == "GET");
}
#[test]
fn is_not_get_request() {
let is_it = is_get(&HashMap::new());
assert!(!is_it);
}
#[test]
fn is_get_request() {
let req: HashMap<_, _> = [("method", "GET")]
.iter()
.map(|t| (String::from(t.0), (String::from(t.1))))
.collect();
let is_it = is_get(&req);
assert!(is_it);
}
}