1use alloc::boxed::Box;
14use alloc::format;
15use alloc::string::String;
16use alloc::sync::Arc;
17use alloc::vec::Vec;
18use core::sync::atomic::AtomicBool;
19
20use formats::json::{self, Value};
21use plat::net::{NetError, NetErrorKind, SocketAddr};
22
23use crate::Stream;
24
25pub const MAX_HEAD: usize = 16 * 1024;
26pub const MAX_HEADERS: usize = 100;
27
28#[derive(Clone, Debug, Default, PartialEq, Eq)]
30pub struct Headers(pub Vec<(String, String)>);
31
32impl Headers {
33 pub fn new() -> Headers {
34 Headers(Vec::new())
35 }
36
37 pub fn get(&self, name: &str) -> Option<&str> {
38 self.0.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
39 }
40
41 pub fn set(&mut self, name: &str, value: &str) {
43 self.remove(name);
44 self.0.push((String::from(name), String::from(value)));
45 }
46
47 pub fn add(&mut self, name: &str, value: &str) {
48 self.0.push((String::from(name), String::from(value)));
49 }
50
51 pub fn content_length(&self) -> Result<Option<u64>, ()> {
54 let mut found: Option<u64> = None;
55 for (k, v) in &self.0 {
56 if !k.eq_ignore_ascii_case("content-length") {
57 continue;
58 }
59 let v = v.trim();
60 if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) {
61 return Err(());
62 }
63 let n: u64 = v.parse().map_err(|_| ())?;
64 if found.is_some_and(|f| f != n) {
65 return Err(());
66 }
67 found = Some(n);
68 }
69 Ok(found)
70 }
71
72 pub fn remove(&mut self, name: &str) {
73 self.0.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
74 }
75
76 pub fn has_token(&self, name: &str, token: &str) -> bool {
78 self.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case(name)).any(|(_, v)| v.split(',').any(|t| t.trim().eq_ignore_ascii_case(token)))
79 }
80}
81
82#[derive(Debug, Default)]
84pub struct Request {
85 pub method: String,
86 pub target: String,
88 pub headers: Headers,
89 pub body: Vec<u8>,
90 pub peer: Option<SocketAddr>,
92 pub client_id: Option<String>,
94}
95
96impl Request {
97 pub fn new(method: &str, target: &str) -> Request {
98 Request { method: String::from(method), target: String::from(target), ..Request::default() }
99 }
100
101 pub fn path(&self) -> &str {
103 crate::url::split_target(&self.target).0
104 }
105
106 pub fn query(&self, key: &str) -> Option<String> {
108 crate::url::query_pairs(crate::url::split_target(&self.target).1).into_iter().find(|(k, _)| k == key).map(|(_, v)| v)
109 }
110
111 pub fn header(&self, name: &str) -> Option<&str> {
112 self.headers.get(name)
113 }
114
115 pub fn json(&self, limits: json::Limits) -> Option<Value> {
117 json::parse_with_limits(&self.body, limits).ok()
118 }
119
120 pub fn bearer(&self) -> Option<&str> {
122 let v = self.header("authorization")?;
123 let (scheme, token) = v.split_once(' ')?;
124 scheme.eq_ignore_ascii_case("bearer").then(|| token.trim())
125 }
126}
127
128#[non_exhaustive]
130pub enum Body {
131 Empty,
132 Bytes(Vec<u8>),
133 Stream { len: Option<u64>, next: Box<dyn FnMut(&mut Vec<u8>) -> bool + Send> },
136 Upgrade(Upgrade),
140}
141
142pub struct Upgrade(Box<dyn FnOnce(Upgraded) + Send>);
145
146impl Upgrade {
147 pub fn new(f: impl FnOnce(Upgraded) + Send + 'static) -> Upgrade {
149 Upgrade(Box::new(f))
150 }
151
152 pub fn run(self, up: Upgraded) {
154 (self.0)(up)
155 }
156}
157
158pub struct Upgraded {
160 pub stream: Box<dyn crate::Stream>,
163 pub buffered: Vec<u8>,
165 pub peer: Option<SocketAddr>,
167 pub stop: Arc<AtomicBool>,
169}
170
171impl core::fmt::Debug for Body {
172 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
173 match self {
174 Body::Empty => f.write_str("Empty"),
175 Body::Bytes(b) => write!(f, "Bytes({})", b.len()),
176 Body::Stream { len, .. } => write!(f, "Stream({:?})", len),
177 Body::Upgrade(_) => f.write_str("Upgrade"),
178 }
179 }
180}
181
182#[derive(Debug)]
183pub struct Response {
184 pub status: u16,
185 pub headers: Headers,
186 pub body: Body,
187}
188
189impl Response {
190 pub fn new(status: u16) -> Response {
191 Response { status, headers: Headers::new(), body: Body::Empty }
192 }
193
194 pub fn bytes(status: u16, content_type: &str, body: Vec<u8>) -> Response {
195 let mut r = Response::new(status);
196 r.headers.set("Content-Type", content_type);
197 r.body = Body::Bytes(body);
198 r
199 }
200
201 pub fn text(status: u16, s: &str) -> Response {
202 Response::bytes(status, "text/plain; charset=utf-8", Vec::from(s.as_bytes()))
203 }
204
205 pub fn json(status: u16, v: &Value) -> Response {
206 let lim = json::Limits { bytes: 64 << 20, depth: 32, values: 4_000_000, string_bytes: 16 << 20, members: 1_000_000 };
207 match json::stringify_with_limits(v, lim) {
208 Ok(s) => Response::bytes(status, "application/json", s.into_bytes()),
209 Err(_) => Response::text(500, "response too large"),
210 }
211 }
212
213 pub fn header(mut self, name: &str, value: &str) -> Response {
214 self.headers.set(name, value);
215 self
216 }
217
218 pub fn body_bytes(&self) -> &[u8] {
220 match &self.body {
221 Body::Bytes(b) => b,
222 _ => &[],
223 }
224 }
225
226 pub fn body_json(&self, limits: json::Limits) -> Option<Value> {
227 json::parse_with_limits(self.body_bytes(), limits).ok()
228 }
229}
230
231pub fn reason(status: u16) -> &'static str {
233 match status {
234 100 => "Continue",
235 101 => "Switching Protocols",
236 200 => "OK",
237 201 => "Created",
238 202 => "Accepted",
239 204 => "No Content",
240 206 => "Partial Content",
241 301 => "Moved Permanently",
242 302 => "Found",
243 304 => "Not Modified",
244 400 => "Bad Request",
245 401 => "Unauthorized",
246 403 => "Forbidden",
247 404 => "Not Found",
248 405 => "Method Not Allowed",
249 408 => "Request Timeout",
250 409 => "Conflict",
251 411 => "Length Required",
252 413 => "Content Too Large",
253 414 => "URI Too Long",
254 415 => "Unsupported Media Type",
255 422 => "Unprocessable Content",
256 423 => "Locked",
257 429 => "Too Many Requests",
258 431 => "Request Header Fields Too Large",
259 500 => "Internal Server Error",
260 501 => "Not Implemented",
261 502 => "Bad Gateway",
262 503 => "Service Unavailable",
263 504 => "Gateway Timeout",
264 505 => "HTTP Version Not Supported",
265 _ => "Unknown",
266 }
267}
268
269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
273#[non_exhaustive]
274pub enum ReadError {
275 Closed,
277 Net(NetError),
278 Bad,
280 HeadTooLarge,
282 BodyTooLarge,
284}
285
286impl From<NetError> for ReadError {
287 fn from(e: NetError) -> Self {
288 ReadError::Net(e)
289 }
290}
291
292pub struct Reader<'a> {
294 s: &'a dyn Stream,
295 buf: Vec<u8>,
296 pos: usize,
297 deadline_us: Option<u64>,
298 rate: Option<(u64, u64, u64)>,
300 got: u64,
301}
302
303impl<'a> Reader<'a> {
304 pub fn new(s: &'a dyn Stream) -> Reader<'a> {
305 Reader { s, buf: Vec::with_capacity(8192), pos: 0, deadline_us: None, rate: None, got: 0 }
306 }
307
308 pub fn set_min_rate(&mut self, rate: Option<(u32, u32)>) {
312 self.rate = rate.map(|(r, g)| (plat::time_us(), g as u64 * 1000, r.max(1) as u64));
313 self.got = 0;
314 }
315
316 pub fn set_deadline(&mut self, deadline_us: Option<u64>) {
319 self.deadline_us = deadline_us;
320 }
321
322 pub fn has_buffered(&self) -> bool {
324 self.pos < self.buf.len()
325 }
326
327 pub fn take_buffered(&mut self) -> Vec<u8> {
330 let rest = self.buf[self.pos..].to_vec();
331 self.pos = self.buf.len();
332 rest
333 }
334
335 fn fill(&mut self) -> Result<usize, NetError> {
336 if self.pos > 0 && self.pos == self.buf.len() {
337 self.buf.clear();
338 self.pos = 0;
339 }
340 if let Some(d) = self.deadline_us {
341 let left = d.saturating_sub(plat::time_us()) / 1000;
343 if left == 0 || !self.s.wait_readable(left.min(u32::MAX as u64) as u32) {
344 return Err(NetError::new(NetErrorKind::TimedOut, 0));
345 }
346 }
347 if let Some((t0, grace, r)) = self.rate {
348 if plat::time_us() > t0 + grace + self.got.saturating_mul(1_000_000) / r {
349 return Err(NetError::new(NetErrorKind::TimedOut, 0));
350 }
351 }
352 let old = self.buf.len();
353 self.buf.resize(old + 16 * 1024, 0);
354 let n = self.s.read(&mut self.buf[old..]);
355 let got = *n.as_ref().unwrap_or(&0);
356 self.buf.truncate(old + got);
357 self.got += got as u64;
358 n
359 }
360
361 fn line(&mut self, max: usize, first: bool) -> Result<String, ReadError> {
363 loop {
364 if let Some(i) = self.buf[self.pos..].iter().position(|&c| c == b'\n') {
365 let mut l = &self.buf[self.pos..self.pos + i];
366 self.pos += i + 1;
367 if l.last() == Some(&b'\r') {
368 l = &l[..l.len() - 1];
369 }
370 return core::str::from_utf8(l).map(String::from).map_err(|_| ReadError::Bad);
371 }
372 if self.buf.len() - self.pos > max {
373 return Err(ReadError::HeadTooLarge);
374 }
375 let n = self.fill().map_err(|e| if first && self.buf.len() == self.pos && e.kind == NetErrorKind::Reset { ReadError::Closed } else { ReadError::Net(e) })?;
376 if n == 0 {
377 return Err(if first && self.buf.len() == self.pos { ReadError::Closed } else { ReadError::Bad });
378 }
379 }
380 }
381
382 pub fn head(&mut self) -> Result<(String, Headers), ReadError> {
384 let mut budget = MAX_HEAD;
385 let mut start = self.line(budget, true)?;
386 let mut skipped = 0;
388 while start.is_empty() && skipped < 4 {
389 start = self.line(budget, false)?;
390 skipped += 1;
391 }
392 budget = budget.saturating_sub(start.len());
393 let mut h = Headers::new();
394 loop {
395 let l = self.line(budget, false)?;
396 if l.is_empty() {
397 break;
398 }
399 budget = budget.checked_sub(l.len() + 2).ok_or(ReadError::HeadTooLarge)?;
400 if h.0.len() >= MAX_HEADERS {
401 return Err(ReadError::HeadTooLarge);
402 }
403 if l.starts_with([' ', '\t']) {
404 return Err(ReadError::Bad); }
406 let (k, v) = l.split_once(':').ok_or(ReadError::Bad)?;
407 if k.is_empty() || k.bytes().any(|b| b <= b' ' || b == 0x7f) {
408 return Err(ReadError::Bad);
409 }
410 let v = v.trim();
411 if v.bytes().any(|b| (b < b' ' && b != b'\t') || b == 0x7f) {
412 return Err(ReadError::Bad);
413 }
414 h.add(k, v);
415 }
416 Ok((start, h))
417 }
418
419 fn pass(&mut self, n: u64, sink: &mut dyn FnMut(&[u8]) -> bool) -> Result<(), ReadError> {
421 let mut need = n;
422 while need > 0 {
423 if self.pos == self.buf.len() && self.fill()? == 0 {
424 return Err(ReadError::Bad);
425 }
426 let k = need.min((self.buf.len() - self.pos) as u64) as usize;
427 if !sink(&self.buf[self.pos..self.pos + k]) {
428 return Err(ReadError::Bad);
429 }
430 self.pos += k;
431 need -= k as u64;
432 }
433 Ok(())
434 }
435
436 pub fn body(&mut self, h: &Headers, max: usize, until_close: bool) -> Result<Vec<u8>, ReadError> {
439 let mut out = Vec::new();
440 if h.get("transfer-encoding").is_none() {
441 if let Ok(Some(n)) = h.content_length() {
442 out.reserve((n.min(max as u64) as usize).min(1 << 20));
443 }
444 }
445 self.body_to(h, max as u64, until_close, &mut |b| {
446 out.extend_from_slice(b);
447 true
448 })?;
449 Ok(out)
450 }
451
452 pub fn body_to(&mut self, h: &Headers, max: u64, until_close: bool, sink: &mut dyn FnMut(&[u8]) -> bool) -> Result<u64, ReadError> {
455 if h.get("transfer-encoding").is_some() {
456 let mut codings = h.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case("transfer-encoding")).flat_map(|(_, v)| v.split(',')).map(str::trim).filter(|c| !c.is_empty());
459 if !codings.next().is_some_and(|c| c.eq_ignore_ascii_case("chunked")) || codings.next().is_some() {
460 return Err(ReadError::Bad);
461 }
462 let mut total: u64 = 0;
463 loop {
464 let l = self.line(1024, false)?;
465 let size = l.split(';').next().unwrap_or("").trim();
466 if !size.bytes().all(|c| c.is_ascii_hexdigit()) {
467 return Err(ReadError::Bad);
468 }
469 let n = u64::from_str_radix(size, 16).map_err(|_| ReadError::Bad)?;
470 if n == 0 {
471 let mut budget = MAX_HEAD;
473 for _ in 0..=MAX_HEADERS {
474 let l = self.line(budget, false)?;
475 if l.is_empty() {
476 return Ok(total);
477 }
478 budget = budget.checked_sub(l.len() + 2).ok_or(ReadError::HeadTooLarge)?;
479 }
480 return Err(ReadError::HeadTooLarge);
481 }
482 if total.saturating_add(n) > max {
483 return Err(ReadError::BodyTooLarge);
484 }
485 self.pass(n, sink)?;
486 total += n;
487 if !self.line(2, false)?.is_empty() {
488 return Err(ReadError::Bad);
489 }
490 }
491 }
492 if let Some(n) = h.content_length().map_err(|_| ReadError::Bad)? {
493 if n > max {
494 return Err(ReadError::BodyTooLarge);
495 }
496 self.pass(n, sink)?;
497 return Ok(n);
498 }
499 if until_close {
500 let mut total: u64 = 0;
501 loop {
502 let piece = &self.buf[self.pos..];
503 total += piece.len() as u64;
504 if total > max {
505 return Err(ReadError::BodyTooLarge);
506 }
507 if !piece.is_empty() && !sink(piece) {
508 return Err(ReadError::Bad);
509 }
510 self.pos = self.buf.len();
511 match self.fill() {
514 Ok(0) if self.s.end_is_clean() => return Ok(total),
515 Ok(0) => return Err(ReadError::Net(NetError::new(NetErrorKind::Reset, 0))),
516 Ok(_) => {}
517 Err(e) => return Err(ReadError::Net(e)),
518 }
519 }
520 }
521 Ok(0)
522 }
523}
524
525fn head_bytes(start: &str, h: &Headers) -> Vec<u8> {
528 let mut s = String::with_capacity(256);
529 s.push_str(start);
530 s.push_str("\r\n");
531 let token = |b: u8| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b);
532 for (k, v) in &h.0 {
533 if k.is_empty() || !k.bytes().all(token) || v.bytes().any(|b| (b < b' ' && b != b'\t') || b == 0x7f) {
536 continue;
537 }
538 s.push_str(k);
539 s.push_str(": ");
540 s.push_str(v);
541 s.push_str("\r\n");
542 }
543 s.push_str("\r\n");
544 s.into_bytes()
545}
546
547pub fn write_response(s: &dyn Stream, r: &mut Response, head_only: bool, keep_alive: bool) -> bool {
549 let mut h = core::mem::take(&mut r.headers);
550 h.set("Connection", if keep_alive { "keep-alive" } else { "close" });
551 let chunked = match &r.body {
552 Body::Empty | Body::Upgrade(_) => {
553 if r.status >= 200 && r.status != 204 && r.status != 304 {
554 h.set("Content-Length", "0");
555 }
556 false
557 }
558 Body::Bytes(b) => {
559 h.set("Content-Length", &format!("{}", b.len()));
560 false
561 }
562 Body::Stream { len: Some(n), .. } => {
563 h.set("Content-Length", &format!("{}", n));
564 false
565 }
566 Body::Stream { len: None, .. } => {
567 h.set("Transfer-Encoding", "chunked");
568 true
569 }
570 };
571 let start = format!("HTTP/1.1 {} {}", r.status, reason(r.status));
572 let head = head_bytes(&start, &h);
573 r.headers = h;
574 match &mut r.body {
575 Body::Bytes(b) if !head_only && b.len() <= 64 * 1024 => {
576 let mut all = head;
578 all.extend_from_slice(b);
579 s.write_all(&all).is_ok()
580 }
581 Body::Bytes(b) => s.write_all(&head).is_ok() && (head_only || s.write_all(b).is_ok()),
582 Body::Empty | Body::Upgrade(_) => s.write_all(&head).is_ok(),
583 Body::Stream { next, .. } => {
584 if s.write_all(&head).is_err() {
585 return false;
586 }
587 if head_only {
588 return true;
589 }
590 let mut piece = Vec::with_capacity(256 * 1024);
591 loop {
592 piece.clear();
593 let more = next(&mut piece);
594 if !piece.is_empty() {
595 let ok = if chunked {
596 let mut frame = format!("{:x}\r\n", piece.len()).into_bytes();
597 frame.extend_from_slice(&piece);
598 frame.extend_from_slice(b"\r\n");
599 s.write_all(&frame).is_ok()
600 } else {
601 s.write_all(&piece).is_ok()
602 };
603 if !ok {
604 return false;
605 }
606 }
607 if !more {
608 break;
609 }
610 }
611 !chunked || s.write_all(b"0\r\n\r\n").is_ok()
612 }
613 }
614}
615
616pub fn write_switch(s: &dyn Stream, r: &Response) -> bool {
619 s.write_all(&head_bytes(&format!("HTTP/1.1 {} {}", r.status, reason(r.status)), &r.headers)).is_ok()
620}
621
622pub fn write_request(s: &dyn Stream, method: &str, target: &str, h: &Headers, body: &[u8]) -> bool {
624 let token = |b: u8| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b);
625 if method.is_empty() || !method.bytes().all(token) || target.is_empty() || target.bytes().any(|b| b <= b' ' || b == 0x7f) {
626 return false;
627 }
628 let mut h = h.clone();
629 if !body.is_empty() || matches!(method, "POST" | "PUT" | "PATCH") {
630 h.set("Content-Length", &format!("{}", body.len()));
631 }
632 let mut all = head_bytes(&format!("{} {} HTTP/1.1", method, target), &h);
633 all.extend_from_slice(body);
634 s.write_all(&all).is_ok()
635}