1use std::io::{Read, Write};
14use std::net::{TcpListener, TcpStream};
15use std::path::{Component, Path, PathBuf};
16
17pub const DEFAULT_PORT: u16 = 8000;
18
19pub fn serve(root: &Path, port: u16) -> Result<(), String> {
22 let listener = TcpListener::bind(("127.0.0.1", port))
23 .map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}"))?;
24 let port = listener.local_addr().map_err(|e| e.to_string())?.port();
25 println!(
26 "litz: serving {} at http://127.0.0.1:{port}/",
27 root.display()
28 );
29 println!("litz: press Ctrl-C to stop");
30 for stream in listener.incoming() {
31 match stream {
32 Ok(stream) => {
33 let root = root.to_path_buf();
34 std::thread::spawn(move || {
35 let _ = answer(stream, &root);
38 });
39 }
40 Err(e) => eprintln!("litz: {e}"),
41 }
42 }
43 Ok(())
44}
45
46fn answer(mut stream: TcpStream, root: &Path) -> std::io::Result<()> {
47 let mut buf = [0u8; 4096];
48 let n = stream.read(&mut buf)?;
49 let request = String::from_utf8_lossy(&buf[..n]);
50 let Some(line) = request.lines().next() else {
51 return respond(&mut stream, 400, "text/plain", b"bad request");
52 };
53 let mut parts = line.split(' ');
54 let (Some("GET"), Some(target)) = (parts.next(), parts.next()) else {
55 return respond(&mut stream, 405, "text/plain", b"only GET is served");
56 };
57
58 let Some(path) = resolve(root, target) else {
59 return respond(
60 &mut stream,
61 403,
62 "text/plain",
63 b"outside the served directory",
64 );
65 };
66 match std::fs::read(&path) {
67 Ok(body) => respond(&mut stream, 200, mime(&path), &body),
68 Err(_) => respond(&mut stream, 404, "text/plain", b"not found"),
69 }
70}
71
72fn resolve(root: &Path, target: &str) -> Option<PathBuf> {
77 let target = target.split(['?', '#']).next().unwrap_or("");
78 let mut relative = PathBuf::new();
79 for piece in target.split('/') {
80 if piece.is_empty() || piece == "." {
81 continue;
82 }
83 if piece == ".." || piece.contains('\\') || piece.contains('\0') {
84 return None;
85 }
86 relative.push(piece);
87 }
88 if relative.as_os_str().is_empty() || relative.extension().is_none() {
89 relative.push("index.html");
90 }
91 if !relative
93 .components()
94 .all(|c| matches!(c, Component::Normal(_)))
95 {
96 return None;
97 }
98 Some(root.join(relative))
99}
100
101fn mime(path: &Path) -> &'static str {
102 match path.extension().and_then(|e| e.to_str()) {
103 Some("html") => "text/html; charset=utf-8",
104 Some("js") => "text/javascript; charset=utf-8",
105 Some("css") => "text/css; charset=utf-8",
106 Some("json") => "application/json",
107 Some("wasm") => "application/wasm",
108 Some("svg") => "image/svg+xml",
109 Some("png") => "image/png",
110 Some("ico") => "image/x-icon",
111 Some("txt") | Some("md") => "text/plain; charset=utf-8",
112 _ => "application/octet-stream",
113 }
114}
115
116fn respond(stream: &mut TcpStream, status: u16, mime: &str, body: &[u8]) -> std::io::Result<()> {
117 let reason = match status {
118 200 => "OK",
119 400 => "Bad Request",
120 403 => "Forbidden",
121 404 => "Not Found",
122 405 => "Method Not Allowed",
123 _ => "Unknown",
124 };
125 write!(
126 stream,
127 "HTTP/1.1 {status} {reason}\r\nContent-Type: {mime}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
128 body.len()
129 )?;
130 stream.write_all(body)
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 #[test]
138 fn a_bare_path_serves_the_index() {
139 assert_eq!(
140 resolve(Path::new("site"), "/"),
141 Some(PathBuf::from("site/index.html"))
142 );
143 assert_eq!(
144 resolve(Path::new("site"), "/demo"),
145 Some(PathBuf::from("site/demo/index.html"))
146 );
147 }
148
149 #[test]
150 fn a_file_path_is_kept_whole() {
151 assert_eq!(
152 resolve(Path::new("site"), "/litz_wasm.wasm?v=2"),
153 Some(PathBuf::from("site/litz_wasm.wasm"))
154 );
155 }
156
157 #[test]
158 fn climbing_out_of_the_root_is_refused() {
159 assert_eq!(resolve(Path::new("site"), "/../Cargo.toml"), None);
160 assert_eq!(resolve(Path::new("site"), "/demo/../../Cargo.toml"), None);
161 }
162
163 #[test]
164 fn content_types_are_the_ones_a_browser_needs() {
165 assert_eq!(mime(Path::new("a.wasm")), "application/wasm");
166 assert_eq!(mime(Path::new("a.js")), "text/javascript; charset=utf-8");
167 assert_eq!(mime(Path::new("a.bin")), "application/octet-stream");
168 }
169}