-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_server.rs
More file actions
279 lines (240 loc) · 7.84 KB
/
Copy pathweb_server.rs
File metadata and controls
279 lines (240 loc) · 7.84 KB
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
use std::{
env,
fs::File,
io::{self, Read, Write},
net::{Shutdown, TcpListener, TcpStream},
path::{Component, Path, PathBuf},
thread,
};
const DEFAULT_LISTEN_ADDR: &str = "0.0.0.0:80";
const MAX_REQUEST_BYTES: usize = 8192;
fn main() -> io::Result<()> {
let root = env::current_dir()?.canonicalize()?;
let listen_addr = listen_addr();
let listener = TcpListener::bind(&listen_addr)?;
println!("Serving {} on http://{}", root.display(), listen_addr);
for stream in listener.incoming() {
match stream {
Ok(stream) => {
let root = root.clone();
thread::spawn(move || {
let _ = handle_connection(stream, &root);
});
}
Err(error) => eprintln!("accept failed: {error}"),
}
}
Ok(())
}
fn listen_addr() -> String {
let mut args = env::args().skip(1);
match args.next() {
Some(arg) if arg == "--port" => {
let port = args.next().unwrap_or_else(|| "80".to_string());
format!("0.0.0.0:{port}")
}
Some(arg) if arg.starts_with("--port=") => {
format!("0.0.0.0:{}", arg.trim_start_matches("--port="))
}
Some(arg) if arg.contains(':') => arg,
Some(arg) => format!("0.0.0.0:{arg}"),
None => DEFAULT_LISTEN_ADDR.to_string(),
}
}
fn handle_connection(mut stream: TcpStream, root: &Path) -> io::Result<()> {
let request = read_request_head(&mut stream)?;
let Some((method, target)) = parse_request_line(&request) else {
return write_error(&mut stream, 400, "Bad Request");
};
if method != "GET" && method != "HEAD" {
return write_error(&mut stream, 405, "Method Not Allowed");
}
if target == "/favicon.ico" {
return write_response(&mut stream, method == "HEAD", "image/x-icon", None, &[]);
}
let Some(path) = safe_request_path(root, target) else {
return write_error(&mut stream, 404, "Not Found");
};
let Some(mime_type) = mime_type_for(&path) else {
return write_error(&mut stream, 404, "Not Found");
};
let br_path = with_br_extension(&path);
if let Some(body) = read_safe_file(root, &br_path) {
return write_response(&mut stream, method == "HEAD", mime_type, Some("br"), &body);
}
if let Some(body) = read_safe_file(root, &path) {
return write_response(&mut stream, method == "HEAD", mime_type, None, &body);
}
write_error(&mut stream, 404, "Not Found")
}
fn read_request_head(stream: &mut TcpStream) -> io::Result<Vec<u8>> {
let mut request = Vec::with_capacity(1024);
let mut byte = [0u8; 1];
while request.len() < MAX_REQUEST_BYTES {
let len = stream.read(&mut byte)?;
if len == 0 {
break;
}
request.push(byte[0]);
if request.ends_with(b"\r\n\r\n") || request.ends_with(b"\n\n") {
break;
}
}
Ok(request)
}
fn parse_request_line(request: &[u8]) -> Option<(&str, &str)> {
let request = std::str::from_utf8(request).ok()?;
let line = request.lines().next()?;
let mut parts = line.split_whitespace();
let method = parts.next()?;
let target = parts.next()?;
let version = parts.next()?;
if !version.starts_with("HTTP/") || parts.next().is_some() {
return None;
}
Some((method, target))
}
fn safe_request_path(root: &Path, target: &str) -> Option<PathBuf> {
let target = target.split_once('?').map_or(target, |(path, _)| path);
let target = target.split_once('#').map_or(target, |(path, _)| path);
if !target.starts_with('/') {
return None;
}
let mut decoded = percent_decode(target)?;
if decoded == "/" || decoded.ends_with('/') {
decoded.push_str("index.html");
}
if decoded.as_bytes().contains(&0) || decoded.contains('\\') {
return None;
}
let relative = decoded.trim_start_matches('/');
let relative_path = Path::new(relative);
if relative_path.is_absolute() {
return None;
}
let mut clean = PathBuf::new();
for component in relative_path.components() {
match component {
Component::Normal(part) => clean.push(part),
_ => return None,
}
}
let joined = root.join(clean);
ensure_under_root(root, &joined).then_some(joined)
}
fn percent_decode(input: &str) -> Option<String> {
let bytes = input.as_bytes();
let mut output = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
if bytes[index] == b'%' {
if index + 2 >= bytes.len() {
return None;
}
let high = hex_value(bytes[index + 1])?;
let low = hex_value(bytes[index + 2])?;
output.push((high << 4) | low);
index += 3;
} else {
output.push(bytes[index]);
index += 1;
}
}
String::from_utf8(output).ok()
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn read_safe_file(root: &Path, path: &Path) -> Option<Vec<u8>> {
if !ensure_under_root(root, path) {
return None;
}
let canonical = path.canonicalize().ok()?;
if !canonical.starts_with(root) || !canonical.is_file() {
return None;
}
let mut file = File::open(canonical).ok()?;
let mut body = Vec::new();
file.read_to_end(&mut body).ok()?;
Some(body)
}
fn with_br_extension(path: &Path) -> PathBuf {
let mut name = path.file_name().and_then(|name| name.to_str()).unwrap_or("").to_string();
name.push_str(".br");
path.with_file_name(name)
}
fn ensure_under_root(root: &Path, path: &Path) -> bool {
if path.is_absolute() {
path.starts_with(root)
} else {
false
}
}
fn write_response(
stream: &mut TcpStream,
head_only: bool,
mime_type: &str,
encoding: Option<&str>,
body: &[u8],
) -> io::Result<()> {
let mut header = format!(
"HTTP/1.1 200 OK\r\n\
Content-Type: {mime_type}\r\n\
Cross-Origin-Embedder-Policy: require-corp\r\n\
Cross-Origin-Opener-Policy: same-origin\r\n\
Cache-Control: max-age=0\r\n\
Content-Length: {}\r\n\
Connection: close\r\n",
body.len()
);
if let Some(encoding) = encoding {
header.push_str(&format!("Content-Encoding: {encoding}\r\n"));
}
header.push_str("\r\n");
stream.write_all(header.as_bytes())?;
if !head_only {
stream.write_all(body)?;
}
let _ = stream.flush();
let _ = stream.shutdown(Shutdown::Both);
Ok(())
}
fn write_error(stream: &mut TcpStream, status: u16, reason: &str) -> io::Result<()> {
let body = format!("{status} {reason}\n");
let header = format!(
"HTTP/1.1 {status} {reason}\r\n\
Content-Type: text/plain\r\n\
Content-Length: {}\r\n\
Connection: close\r\n\r\n",
body.len()
);
stream.write_all(header.as_bytes())?;
stream.write_all(body.as_bytes())?;
let _ = stream.flush();
let _ = stream.shutdown(Shutdown::Both);
Ok(())
}
fn mime_type_for(path: &Path) -> Option<&'static str> {
match path.extension()?.to_str()? {
"html" => Some("text/html"),
"wasm" => Some("application/wasm"),
"css" => Some("text/css"),
"js" => Some("text/javascript"),
"ttf" => Some("application/ttf"),
"otf" => Some("font/otf"),
"png" => Some("image/png"),
"jpg" => Some("image/jpg"),
"jpeg" => Some("image/jpeg"),
"svg" => Some("image/svg+xml"),
"md" => Some("text/markdown"),
"bin" => Some("application/octet-stream"),
"woff" => Some("font/woff"),
"woff2" => Some("font/woff2"),
_ => None,
}
}