1use std::collections::BTreeMap;
19use std::fmt::Write as _;
20use std::io::{BufRead, BufReader, Read, Write};
21use std::net::TcpStream;
22use std::sync::mpsc::Receiver;
23
24const MAX_BODY: usize = 16 * 1024 * 1024;
28
29const MAX_LINE: usize = 64 * 1024;
31
32#[derive(Debug, Clone, Default)]
36pub struct Request {
37 pub method: String,
38 pub path: String,
40 pub query: String,
42 pub headers: BTreeMap<String, String>,
44 pub body: Vec<u8>,
45}
46
47impl Request {
48 #[must_use]
49 pub fn header(&self, name: &str) -> Option<&str> {
50 self.headers.get(name).map(String::as_str)
51 }
52
53 #[must_use]
55 pub fn text(&self) -> String {
56 String::from_utf8_lossy(&self.body).into_owned()
57 }
58
59 #[must_use]
62 pub fn segments(&self) -> Vec<&str> {
63 self.path.split('/').filter(|s| !s.is_empty()).collect()
64 }
65
66 #[must_use]
68 pub fn param(&self, name: &str) -> Option<String> {
69 self.query.split('&').find_map(|pair| {
70 let (k, v) = pair.split_once('=')?;
71 (percent_decode(k) == name).then(|| percent_decode(v))
72 })
73 }
74
75 #[must_use]
77 pub fn cookie(&self, name: &str) -> Option<String> {
78 self.header("cookie")?.split(';').find_map(|pair| {
79 let (k, v) = pair.split_once('=')?;
80 (k.trim() == name).then(|| v.trim().to_string())
81 })
82 }
83}
84
85#[derive(Debug, Clone)]
87pub struct Response {
88 pub status: u16,
89 pub content_type: String,
90 pub body: Vec<u8>,
91 pub headers: Vec<(String, String)>,
93}
94
95impl Response {
96 #[must_use]
97 pub fn new(status: u16, content_type: &str, body: impl Into<Vec<u8>>) -> Response {
98 Response {
99 status,
100 content_type: content_type.to_string(),
101 body: body.into(),
102 headers: Vec::new(),
103 }
104 }
105
106 #[must_use]
107 pub fn html(body: impl Into<Vec<u8>>) -> Response {
108 Response::new(200, "text/html; charset=utf-8", body)
109 }
110
111 #[must_use]
112 pub fn text(body: impl Into<Vec<u8>>) -> Response {
113 Response::new(200, "text/plain; charset=utf-8", body)
114 }
115
116 #[must_use]
117 pub fn json(body: impl Into<Vec<u8>>) -> Response {
118 Response::new(200, "application/json; charset=utf-8", body)
119 }
120
121 #[must_use]
123 pub fn status(status: u16, message: &str) -> Response {
124 Response::new(status, "text/plain; charset=utf-8", message.to_string())
125 }
126
127 #[must_use]
128 pub fn with_header(mut self, name: &str, value: &str) -> Response {
129 self.headers.push((name.to_string(), value.to_string()));
130 self
131 }
132}
133
134#[derive(Debug, Clone)]
136pub struct Event {
137 pub name: String,
138 pub data: String,
139}
140
141pub enum Reply {
143 Done(Response),
144 Events(Receiver<Event>),
147}
148
149pub fn read_request<R: BufRead>(r: &mut R) -> std::io::Result<Option<Request>> {
154 let Some(line) = read_line(r)? else {
155 return Ok(None);
156 };
157 if line.trim().is_empty() {
158 return Ok(None);
159 }
160 let mut parts = line.split_whitespace();
161 let (Some(method), Some(target)) = (parts.next(), parts.next()) else {
162 return Err(bad("a request line is `METHOD TARGET VERSION`"));
163 };
164 let (path, query) = target.split_once('?').unwrap_or((target, ""));
165 let mut req = Request {
166 method: method.to_ascii_uppercase(),
167 path: percent_decode(path),
168 query: query.to_string(),
169 ..Request::default()
170 };
171 while let Some(line) = read_line(r)? {
172 if line.trim().is_empty() {
173 break;
174 }
175 if let Some((name, value)) = line.split_once(':') {
176 req.headers
177 .insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
178 }
179 }
180 let length: usize = req
181 .header("content-length")
182 .and_then(|v| v.trim().parse().ok())
183 .unwrap_or(0);
184 if length > MAX_BODY {
185 return Err(bad("request body too large"));
186 }
187 req.body = vec![0; length];
188 r.read_exact(&mut req.body)?;
189 Ok(Some(req))
190}
191
192fn read_line<R: BufRead>(r: &mut R) -> std::io::Result<Option<String>> {
194 let mut buf = Vec::new();
195 let read = r.take(MAX_LINE as u64).read_until(b'\n', &mut buf)?;
196 if read == 0 {
197 return Ok(None);
198 }
199 while buf.last().is_some_and(|c| *c == b'\n' || *c == b'\r') {
200 buf.pop();
201 }
202 Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
203}
204
205fn bad(message: &str) -> std::io::Error {
206 std::io::Error::new(std::io::ErrorKind::InvalidData, message)
207}
208
209#[must_use]
212pub fn percent_decode(s: &str) -> String {
213 let bytes = s.as_bytes();
214 let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
215 let mut i = 0;
216 while i < bytes.len() {
217 match bytes[i] {
218 b'%' if i + 2 < bytes.len() => {
219 let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("");
220 if let Ok(byte) = u8::from_str_radix(hex, 16) {
221 out.push(byte);
222 i += 3;
223 } else {
224 out.push(bytes[i]);
225 i += 1;
226 }
227 }
228 b'+' => {
229 out.push(b' ');
230 i += 1;
231 }
232 byte => {
233 out.push(byte);
234 i += 1;
235 }
236 }
237 }
238 String::from_utf8_lossy(&out).into_owned()
239}
240
241pub fn serve_connection<H>(stream: TcpStream, handle: &H)
246where
247 H: Fn(&Request) -> Reply,
248{
249 let _ = stream.set_nodelay(true);
250 let Ok(write_half) = stream.try_clone() else {
251 return;
252 };
253 let mut reader = BufReader::new(stream);
254 let mut writer = write_half;
255 loop {
256 let request = match read_request(&mut reader) {
257 Ok(Some(request)) => request,
258 Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
261 let _ = write_response(&mut writer, &Response::status(400, &e.to_string()), false);
262 return;
263 }
264 Ok(None) | Err(_) => return,
265 };
266 let keep_alive = !request
269 .header("connection")
270 .is_some_and(|v| v.eq_ignore_ascii_case("close"));
271 match handle(&request) {
272 Reply::Done(response) => {
273 if write_response(&mut writer, &response, keep_alive).is_err() || !keep_alive {
274 return;
275 }
276 }
277 Reply::Events(events) => {
278 stream_events(&mut writer, &events);
279 return;
280 }
281 }
282 }
283}
284
285pub fn write_response<W: Write>(
289 w: &mut W,
290 response: &Response,
291 keep_alive: bool,
292) -> std::io::Result<()> {
293 let mut head = format!(
294 "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: {}\r\n",
295 response.status,
296 reason(response.status),
297 response.content_type,
298 response.body.len(),
299 if keep_alive { "keep-alive" } else { "close" },
300 );
301 for (name, value) in &response.headers {
302 let _ = write!(head, "{name}: {value}\r\n");
303 }
304 head.push_str("\r\n");
305 w.write_all(head.as_bytes())?;
306 w.write_all(&response.body)?;
307 w.flush()
308}
309
310fn stream_events<W: Write>(w: &mut W, events: &Receiver<Event>) {
313 let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\n\
314 Connection: keep-alive\r\n\r\n";
315 if w.write_all(head.as_bytes()).is_err() || w.flush().is_err() {
316 return;
317 }
318 while let Ok(event) = events.recv() {
319 if write_event(w, &event).is_err() {
320 return;
321 }
322 }
323}
324
325pub fn write_event<W: Write>(w: &mut W, event: &Event) -> std::io::Result<()> {
328 let mut out = String::new();
329 if !event.name.is_empty() {
330 let _ = writeln!(out, "event: {}", event.name);
331 }
332 for line in event.data.split('\n') {
333 let _ = writeln!(out, "data: {line}");
334 }
335 out.push('\n');
336 w.write_all(out.as_bytes())?;
337 w.flush()
338}
339
340fn reason(status: u16) -> &'static str {
341 match status {
342 200 => "OK",
343 204 => "No Content",
344 400 => "Bad Request",
345 403 => "Forbidden",
346 404 => "Not Found",
347 405 => "Method Not Allowed",
348 409 => "Conflict",
349 500 => "Internal Server Error",
350 _ => "Status",
351 }
352}
353
354#[cfg(test)]
357mod tests {
358 use super::*;
359
360 fn parse(raw: &str) -> Request {
361 let mut reader = BufReader::new(raw.as_bytes());
362 read_request(&mut reader)
363 .expect("the request reads")
364 .expect("there is a request")
365 }
366
367 #[test]
368 fn a_request_is_its_line_headers_and_body() {
369 let req = parse(
370 "POST /cells/3/run?engine=browser HTTP/1.1\r\nHost: localhost\r\n\
371 Content-Length: 7\r\n\r\n{\"a\":1}",
372 );
373 assert_eq!(req.method, "POST");
374 assert_eq!(req.segments(), ["cells", "3", "run"]);
375 assert_eq!(req.param("engine").as_deref(), Some("browser"));
376 assert_eq!(req.header("host"), Some("localhost"));
377 assert_eq!(req.text(), "{\"a\":1}");
378 }
379
380 #[test]
381 fn paths_and_params_are_decoded() {
382 let req = parse("GET /page/a%20b?q=x%2By&t=%E2%86%96 HTTP/1.1\r\n\r\n");
383 assert_eq!(req.path, "/page/a b");
384 assert_eq!(req.param("q").as_deref(), Some("x+y"));
385 assert_eq!(req.param("t").as_deref(), Some("↖"));
386 }
387
388 #[test]
389 fn cookies_are_read_by_name() {
390 let req = parse("GET / HTTP/1.1\r\nCookie: other=1; quilt_token=abc\r\n\r\n");
391 assert_eq!(req.cookie("quilt_token").as_deref(), Some("abc"));
392 }
393
394 #[test]
395 fn an_event_is_framed_line_by_line() {
396 let mut out = Vec::new();
397 write_event(
398 &mut out,
399 &Event {
400 name: "page".into(),
401 data: "one\ntwo".into(),
402 },
403 )
404 .expect("write");
405 assert_eq!(
406 String::from_utf8(out).unwrap(),
407 "event: page\ndata: one\ndata: two\n\n"
408 );
409 }
410}