diff --git a/src/config.rs b/src/config.rs index 289f2a1..5dbceb6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -183,7 +183,9 @@ pub trait Config { /// ``` fn with_ssl_config(&mut self, ssl_conf: Ssl); /// Returns the Ssl instance of the config and - /// sets the port number for TLS + /// sets the port number for TLS. TLS is served once both a + /// key and a certificate are set, with the `rustls` or + /// `openSSL` feature on. Without them only plain HTTP is served. /// /// # Example /// diff --git a/src/decode.rs b/src/decode.rs new file mode 100644 index 0000000..497f3d3 --- /dev/null +++ b/src/decode.rs @@ -0,0 +1,77 @@ +//! Percent-decoding, shared by request paths and query strings + +use std::borrow::Cow; + +/// Decode the `%XX` escapes in `string`, and `+` as a space when +/// `plus_is_space` (query strings and form bodies, not paths). A `%` that +/// isn't followed by two hex digits is kept as it is, and invalid UTF-8 +/// becomes U+FFFD. It is borrowed when there is nothing to decode. +pub(crate) fn unescape(string: &str, plus_is_space: bool) -> Cow<'_, str> { + let bytes = string.as_bytes(); + if !bytes + .iter() + .any(|&b| b == b'%' || (plus_is_space && b == b'+')) + { + return Cow::Borrowed(string); + } + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' if plus_is_space => out.push(b' '), + b'%' => match (hex(bytes.get(i + 1)), hex(bytes.get(i + 2))) { + (Some(high), Some(low)) => { + out.push(high << 4 | low); + i += 2; + } + _ => out.push(b'%'), + }, + b => out.push(b), + } + i += 1; + } + // valid UTF-8 keeps the buffer it was decoded into + Cow::Owned( + String::from_utf8(out) + .unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()), + ) +} + +fn hex(byte: Option<&u8>) -> Option { + match byte? { + b @ b'0'..=b'9' => Some(b - b'0'), + b @ b'a'..=b'f' => Some(b - b'a' + 10), + b @ b'A'..=b'F' => Some(b - b'A' + 10), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::unescape; + use std::borrow::Cow; + + #[test] + fn borrows_when_nothing_to_decode() { + assert!(matches!(unescape("plain", true), Cow::Borrowed("plain"))); + // `+` is only special in queries + assert!(matches!(unescape("a+b", false), Cow::Borrowed("a+b"))); + } + + #[test] + fn decodes_escapes() { + assert_eq!(unescape("Ada%20Lovelace", false), "Ada Lovelace"); + assert_eq!(unescape("caf%C3%A9", false), "café"); + assert_eq!(unescape("caf%c3%a9", false), "café"); + assert_eq!(unescape("a%2Fb", false), "a/b"); + assert_eq!(unescape("1+1%3D2", true), "1 1=2"); + assert_eq!(unescape("1+1%3D2", false), "1+1=2"); + } + + #[test] + fn keeps_what_it_cant_decode() { + assert_eq!(unescape("100%", false), "100%"); + assert_eq!(unescape("%zz%4", false), "%zz%4"); + assert_eq!(unescape("%FF", false), "\u{FFFD}"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 42e01ed..051fe74 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -116,6 +116,11 @@ pub(crate) mod constants; #[cfg(feature = "cookies")] /// Module for cookie parsing and handling pub mod cookie; +#[cfg(any( + feature = "std", + all(feature = "wasm", target_os = "wasi", target_env = "p3") +))] +pub(crate) mod decode; #[cfg(feature = "std")] pub(crate) mod error; #[cfg(feature = "std")] @@ -136,7 +141,8 @@ pub(crate) mod method; ))] pub(crate) mod path; #[cfg(feature = "std")] -pub(crate) mod query; +/// Decoding query strings, form bodies and url components +pub mod query; #[cfg(feature = "std")] /// Request module contains the ongoing request and methods to read from it pub mod request; diff --git a/src/path.rs b/src/path.rs index ccb56aa..a30e698 100644 --- a/src/path.rs +++ b/src/path.rs @@ -1,3 +1,4 @@ +use crate::decode::unescape; use crate::{default, deref}; use std::convert::TryFrom; use std::error; @@ -70,6 +71,33 @@ impl PathBuf { Ok(PathBuf { chunks }) } + /// Parse the path of a request. Like [`parse`](Self::parse), but every + /// segment is percent-decoded first (a `+` stays a `+`), so routes and + /// url variables see `/users/Ada%20Lovelace` as `users`, `Ada Lovelace`. + /// The path is split before decoding: an encoded `/` (`%2F`) stays + /// inside its segment. A segment that decodes to `.` or `..` counts as + /// one, so `%2e%2e` climbs a level like `..` does instead of reaching a + /// handler as a variable. + pub fn parse_request(path: &str) -> Result { + let mut chunks = Vec::new(); + for chunk in path.split('/') { + if chunk.is_empty() { + continue; + } + let chunk = unescape(chunk, false); + match &*chunk { + "." => {} + ".." => { + if chunks.pop().is_none() { + return Err(InvalidPathError); + } + } + _ => chunks.push(chunk.into_owned()), + } + } + Ok(PathBuf { chunks }) + } + pub fn check_starts_with(&self, other: &PathBuf) -> bool { for (a, b) in self.iter().zip(other.iter()) { if a != b { @@ -426,6 +454,38 @@ mod test { PathBuf::parse("/asdf/../..").unwrap(); } + #[test] + fn request_paths_are_decoded() { + let path = PathBuf::parse_request("/users/Ada%20Lovelace/caf%C3%A9").unwrap(); + assert_eq!(*path.chunks(), vec!["users", "Ada Lovelace", "café"]); + // a `+` is only a space in queries + let path = PathBuf::parse_request("/a+b").unwrap(); + assert_eq!(*path.chunks(), vec!["a+b"]); + // split first, an encoded slash is part of the segment + let path = PathBuf::parse_request("/files/a%2Fb").unwrap(); + assert_eq!(*path.chunks(), vec!["files", "a/b"]); + } + + #[test] + fn encoded_dot_segments_are_dot_segments() { + let path = PathBuf::parse_request("/static/%2e%2E/a/%2e/b").unwrap(); + assert_eq!(*path.chunks(), vec!["a", "b"]); + assert!(PathBuf::parse_request("/%2e%2e").is_err()); + // only a whole segment is a dot segment + let path = PathBuf::parse_request("/%2e%2e%2Fetc").unwrap(); + assert_eq!(*path.chunks(), vec!["../etc"]); + } + + #[test] + #[cfg(feature = "url_variables")] + fn route_paths_are_not_decoded() { + let route = PathBuf::parse("/users/:name").unwrap(); + let request = PathBuf::parse_request("/users/Ada%20Lovelace").unwrap(); + let vars = route.check_matches(&request).unwrap(); + assert_eq!(vars.get("name"), Some("Ada Lovelace")); + assert_eq!(*PathBuf::parse("/a%20b").unwrap().chunks(), vec!["a%20b"]); + } + #[test] #[cfg(feature = "url_variables")] fn success_tree() { diff --git a/src/query.rs b/src/query.rs index 849c673..bd504da 100644 --- a/src/query.rs +++ b/src/query.rs @@ -2,11 +2,11 @@ use std::borrow::Cow; #[cfg(feature = "extended_queries")] use std::collections::HashMap; -/// The query of a request, its `name=value` pairs in order, decoded the -/// way browsers encode them (`application/x-www-form-urlencoded`: `+` is a -/// space and `%XX` the byte XX, read as UTF-8). A pair without `=` has an -/// empty value. Names and values with nothing to decode are borrowed from -/// the request rather than copied. +/// The query of a request or a form body, its `name=value` pairs in order, +/// decoded the way browsers encode them (`application/x-www-form-urlencoded`: +/// `+` is a space and `%XX` the byte XX, read as UTF-8), see [`decode`]. A +/// pair without `=` has an empty value. Names and values with nothing to +/// decode are borrowed from the request rather than copied. /// /// ``` /// use octane::prelude::*; @@ -78,57 +78,31 @@ impl<'a> Query<'a> { } } -/// Decode a query component, see [`Query`]. A `%` that isn't followed by -/// two hex digits is kept as it is, and invalid UTF-8 becomes U+FFFD. It is -/// borrowed when there is nothing to decode. +/// Decode a query string or form body component, the way browsers encode +/// them: `+` is a space and `%XX` the byte XX, read as UTF-8. A `%` that +/// isn't followed by two hex digits is kept as it is, and invalid UTF-8 +/// becomes U+FFFD. It is borrowed when there is nothing to decode. +/// +/// ``` +/// use octane::query::decode; +/// +/// assert_eq!(decode("Ada+Lovelace%21"), "Ada Lovelace!"); +/// ``` pub fn decode(string: &str) -> Cow<'_, str> { - if string.bytes().any(|b| b == b'%' || b == b'+') { - Cow::Owned(unescape(string)) - } else { - Cow::Borrowed(string) - } -} - -fn unescape(string: &str) -> String { - let bytes = string.as_bytes(); - let mut ret = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'+' => ret.push(b' '), - b'%' => { - let hex = |at: usize| bytes.get(at).and_then(|&b| from_hex(b as char)); - match (hex(i + 1), hex(i + 2)) { - (Some(h1), Some(h2)) => { - ret.push(h1 * 16 + h2); - i += 2; - } - _ => ret.push(b'%'), - } - } - b => ret.push(b), - } - i += 1; - } - // valid UTF-8 keeps the buffer it was decoded into - String::from_utf8(ret).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned()) + crate::decode::unescape(string, true) } -pub fn from_hex(chr: char) -> Option { - if chr > 'f' { - return None; - } - let c = chr as u8; - if c >= b'0' && c <= b'9' { - return Some(c - b'0'); - } - if c >= b'A' && c <= b'F' { - return Some(c - b'A' + 10); - } - if c >= b'a' && c <= b'f' { - return Some(c - b'a' + 10); - } - None +/// Decode the `%XX` escapes of a url path segment. Unlike [`decode`] a +/// `+` stays a `+`, it only means a space in queries and forms. Url +/// variables are already decoded with it. +/// +/// ``` +/// use octane::query::percent_decode; +/// +/// assert_eq!(percent_decode("caf%C3%A9+cr%C3%A8me"), "café+crème"); +/// ``` +pub fn percent_decode(string: &str) -> Cow<'_, str> { + crate::decode::unescape(string, false) } #[cfg(feature = "extended_queries")] @@ -186,7 +160,7 @@ impl QueryValue { } #[cfg(feature = "extended_queries")] -pub fn parse_extended_query(query: &str) -> HashMap { +pub(crate) fn parse_extended_query(query: &str) -> HashMap { let toks = query.split('&'); let mut ret: HashMap = HashMap::new(); for tok in toks { diff --git a/src/request.rs b/src/request.rs index e9c96ff..5a66189 100644 --- a/src/request.rs +++ b/src/request.rs @@ -79,7 +79,7 @@ impl RequestLine { fn from_parts(method: &str, target: &str, version: &str, has_extra: bool) -> Option { // only the path is used for routing, the query is kept apart let (path, query) = target.split_once('?').unwrap_or((target, "")); - let path = PathBuf::parse(path).ok()?; + let path = PathBuf::parse_request(path).ok()?; // `get` avoids slicing through a multi-byte character and handles // versions shorter than the `HTTP/` prefix without panicking. let ver = version.get(5..).unwrap_or(""); @@ -483,6 +483,28 @@ impl<'a> Request<'a> { Query::parse(&self.request_line.query) } + /// Parse an `application/x-www-form-urlencoded` body, what an HTML + /// `
` sends, into its decoded `name=value` pairs. + /// See [`Query`]. A body that isn't UTF-8 has no pairs: a form encodes + /// everything outside ASCII as `%XX`. + /// + /// ``` + /// use octane::prelude::*; + /// + /// let mut app = Octane::new(); + /// + /// app.post("/sign-up", route_stop!(|req, res| { + /// let form = req.get_form(); + /// let name = form.get("name").unwrap_or("stranger"); + /// res.send(format!("Welcome, {}", name)); + /// })); + /// ``` + pub fn get_form(&self) -> Query<'_> { + str::from_utf8(self.body) + .map(Query::parse) + .unwrap_or_default() + } + /// Parse the extended query and return the key value pairs in the form /// of an HashMap. See [`QueryValue`](../enum.QueryValue.html) #[cfg(feature = "extended_queries")] diff --git a/src/responder.rs b/src/responder.rs index 4708503..0814f6b 100644 --- a/src/responder.rs +++ b/src/responder.rs @@ -167,18 +167,11 @@ impl<'a> Response<'a> { self.default_type(); self } - // `Content-Type: text/html`, unless a type was set + // `Content-Type: text/html`, unless a type was set. A charset is added + // when the head is written, see `charset` fn default_type(&mut self) { if !self.headers.contains("Content-Type") { - match &self.charset { - Some(charset) => { - let mut format = String::from("text/html"); - write!(&mut format, " ;charset={:?}", charset) - .expect("writing a charset to a String cannot fail"); - self.headers.set("Content-Type", format); - } - None => self.headers.set("Content-Type", "text/html"), - } + self.headers.set("Content-Type", "text/html"); } } /// Modify the `Content-Type` header as passed @@ -358,7 +351,8 @@ impl<'a> Response<'a> { /// Sets the http `Content-Disposition` header field /// to `attachment` with the filename and automatically /// updates the content type with the extension - /// provided in the filename + /// provided in the filename. A name outside ASCII is sent the way + /// browsers read it (`filename*`, RFC 8187), with an ASCII fallback. /// /// # Example /// @@ -369,18 +363,16 @@ impl<'a> Response<'a> { /// app.get( /// "/", /// route!(|req, res| { + /// // Content-Disposition: attachment; filename="image.png" /// res.attachment_with_filename("image.png"); /// Flow::Stop /// }), /// ); /// ``` - pub fn attachment_with_filename(&mut self, file_name: &'static str) -> &mut Self { - let extension = FileHandler::get_extension(&PathBuf::from(file_name)); - self.set( - "Content-Disposition", - &format!("attachment; filename = {:?}", file_name), - ); - self.set("Content-Type", &extension); + pub fn attachment_with_filename(&mut self, file_name: &str) -> &mut Self { + let content_type = FileHandler::get_extension(&PathBuf::from(file_name)); + self.set("Content-Disposition", &content_disposition(file_name)); + self.set("Content-Type", &content_type); self } /// Sets the Location header with a status code `302 FOUND` @@ -432,7 +424,11 @@ impl<'a> Response<'a> { self.cookies.push(cookie.into()); self } - /// Sets the content type charset + /// Sets the charset of the `Content-Type`, whichever type it is and + /// whenever it's set: `Content-Type: text/html; charset=utf-8`. A type + /// that already names a charset keeps its own. A charset that isn't a + /// valid token (letters, digits and `-`, `_`, `.` and the like) is + /// ignored. /// /// # Example /// @@ -449,7 +445,9 @@ impl<'a> Response<'a> { /// ); /// ``` pub fn charset(&mut self, charset: &str) -> &mut Self { - self.charset = Some(charset.to_owned()); + if !charset.is_empty() && charset.bytes().all(is_tchar) { + self.charset = Some(charset.to_owned()); + } self } pub(crate) fn has_body(&self) -> bool { @@ -561,6 +559,11 @@ impl<'a> Response<'a> { has_length = true; } else if name.eq_ignore_ascii_case("date") { has_date = true; + } else if name.eq_ignore_ascii_case("content-type") { + if let Some(charset) = self.charset.as_deref().filter(|_| !has_charset(value)) { + push_header(out, name, &format!("{}; charset={}", value, charset)); + continue; + } } push_header(out, name, value); } @@ -680,6 +683,53 @@ fn push_number(out: &mut Vec, mut n: usize) { // Push a `name: value` line. A name that isn't a token is skipped and control // characters in the value, CR and LF included, are replaced by spaces, so no // value can start another header line or end the head early. +// A character of a token (RFC 9110 section 5.6.2) +fn is_tchar(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte) +} + +// Whether a `Content-Type` value names its charset +fn has_charset(content_type: &str) -> bool { + content_type.split(';').skip(1).any(|param| { + let param = param.trim_start().as_bytes(); + param.len() >= 8 && param[..8].eq_ignore_ascii_case(b"charset=") + }) +} + +// `attachment; filename="..."` (RFC 6266). The quoted name keeps the +// printable ASCII of the name with `"` and `\` escaped, anything else +// becomes `_`. When that changed the name it is also sent exactly, as UTF-8 +// percent-encoded in `filename*` (RFC 8187), which browsers prefer. +fn content_disposition(file_name: &str) -> String { + let mut out = String::from("attachment; filename=\""); + let mut exact = true; + for c in file_name.chars() { + match c { + '"' | '\\' => { + out.push('\\'); + out.push(c); + } + ' '..='~' => out.push(c), + _ => { + out.push('_'); + exact = false; + } + } + } + out.push('"'); + if !exact { + out.push_str("; filename*=UTF-8''"); + for byte in file_name.bytes() { + if byte.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&byte) { + out.push(byte as char); + } else { + write!(out, "%{:02X}", byte).expect("writing to a String cannot fail"); + } + } + } + out +} + fn push_header(out: &mut Vec, name: &str, value: &str) { if !is_token(name) { return; @@ -735,6 +785,69 @@ mod test { assert_eq!(req, "HTTP/1.1 200 OK\r\n\r\n"); } + // the head as it would be sent, after `frame` + fn head(mut res: Response<'_>) -> String { + res.frame(); + res.into_parts().0 + } + + #[test] + fn charset_is_added_to_the_content_type() { + let mut res = Response::new_empty(); + res.charset("utf-8").send("Hello"); + assert!(head(res).contains("Content-Type: text/html; charset=utf-8\r\n")); + + // whatever the order, and whatever the type + let mut res = Response::new_empty(); + res.send("Hello"); + res.with_type("text/plain").charset("UTF-8"); + assert!(head(res).contains("Content-Type: text/plain; charset=UTF-8\r\n")); + } + + #[test] + fn charset_keeps_a_named_one_and_ignores_invalid_ones() { + let mut res = Response::new_empty(); + res.with_type("text/plain; Charset=latin1") + .charset("utf-8") + .send(""); + assert!(head(res).contains("Content-Type: text/plain; Charset=latin1\r\n")); + + let mut res = Response::new_empty(); + res.charset("utf-8; boundary=x").send(""); + assert!(head(res).contains("Content-Type: text/html\r\n")); + } + + #[test] + fn attachment_filenames() { + assert_eq!( + content_disposition("report.pdf"), + r#"attachment; filename="report.pdf""# + ); + assert_eq!( + content_disposition(r#"say "hi"\.txt"#), + r#"attachment; filename="say \"hi\"\\.txt""# + ); + assert_eq!( + content_disposition("résumé 1.pdf"), + r#"attachment; filename="r_sum_ 1.pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%201.pdf"# + ); + // a line break can't end the header early + assert_eq!( + content_disposition("a\r\nb"), + r#"attachment; filename="a__b"; filename*=UTF-8''a%0D%0Ab"# + ); + } + + #[test] + fn attachment_sets_the_type() { + let mut res = Response::new_empty(); + res.attachment_with_filename(&String::from("data.json")) + .send("{}"); + let head = head(res); + assert!(head.contains("Content-Disposition: attachment; filename=\"data.json\"\r\n")); + assert!(head.contains("Content-Type: application/json\r\n")); + } + #[tokio::test] async fn response_with_status_code_different() { // Reponse with different status codes should work diff --git a/src/router.rs b/src/router.rs index 939c741..f0f7fbb 100644 --- a/src/router.rs +++ b/src/router.rs @@ -136,8 +136,10 @@ impl Router { } // Fetch the handlers matching the request path and run them in - // registration order until one returns `Flow::Stop`. - pub(crate) async fn run(&self, request: &Request<'_>, res: &mut Response<'_>) { + // registration order until one returns `Flow::Stop`. Returns whether + // that answered the request: a handler stopped, or a route for the + // path and method ran (middleware alone doesn't answer). + pub(crate) async fn run(&self, request: &Request<'_>, res: &mut Response<'_>) -> bool { let line = &request.request_line; let routes = self.routes.matched(line.method, &line.path); #[cfg(feature = "url_variables")] @@ -148,15 +150,18 @@ impl Router { #[cfg(not(feature = "url_variables"))] let matched = MatchedRequest { request }; + let mut answered = false; for route in routes { + answered |= route.is_route; #[cfg(feature = "url_variables")] { matched.vars = route.vars; } if !route.data.call(&matched, res).await.should_continue() { - break; + return true; } } + answered } } diff --git a/src/routes.rs b/src/routes.rs index de54a3b..bab0c8f 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -16,6 +16,13 @@ pub(crate) type RouterResult = Result<(), InvalidPathError>; /// the execution should go to the next similar route /// or not /// +/// A request is answered once a handler returns `Flow::Stop`, or a route +/// registered for its path and method has run, whether or not a body was +/// set: `res.redirect("/")` or `res.status(StatusCode::NoContent)` alone is +/// a complete response, sent with an empty body. Only a request that no +/// route matched, that no handler stopped and that has no body gets +/// Octane's `404`, or a `405` when the path has routes for other methods. +/// /// # Example /// /// ``` @@ -221,6 +228,10 @@ pub(crate) struct Indexed { /// A handler that matched a request, with the url variables of its path pub(crate) struct Matched<'a, T> { pub(crate) data: &'a T, + // a route registered for the request's path, not middleware. The + // WASIp3 router doesn't need it, its handlers answer by sending + #[cfg_attr(not(feature = "std"), allow(dead_code))] + pub(crate) is_route: bool, // where it was registered, which is the order handlers run in index: usize, #[cfg(feature = "url_variables")] @@ -298,6 +309,7 @@ impl Routes { node.find(path, &mut |route| { matched.push(Matched { data: &route.data.data, + is_route: true, index: route.data.index, #[cfg(feature = "url_variables")] vars: route.vars, @@ -307,6 +319,7 @@ impl Routes { } matched.extend(self.middlewares.iter().map(|middleware| Matched { data: &middleware.data, + is_route: false, index: middleware.index, #[cfg(feature = "url_variables")] vars: Vars::new(), diff --git a/src/server.rs b/src/server.rs index dbd7050..66bec00 100644 --- a/src/server.rs +++ b/src/server.rs @@ -152,7 +152,9 @@ impl Octane { } /// Start listening on the port specified, the listen /// function also starts the Ssl server if the features - /// are enabled and the key/certs are provided + /// are enabled and the key/certs are provided. A key or + /// certificate that can't be loaded, or a port that can't be + /// bound, is returned as an error before anything is served. /// /// The default connection deadline uses Tokio's time driver. A custom /// runtime must call `enable_time` or `enable_all`; runtimes created by @@ -215,41 +217,34 @@ impl Octane { S: Future, { let max_connections = checked_connection_limit(self.settings.max_connections)?; + // Everything that can fail happens before anything is served: the TLS + // key and certificate are loaded and both ports bound, so `listen` + // returns the error instead of running without one of them. + #[cfg(any(feature = "openSSL", feature = "rustls"))] + let tls = Octane::bind_tls(&self.settings)?; + let listener = ServerBuilder::new(port)?; let server = Arc::new(self); let connections = Arc::new(Semaphore::new(max_connections)); - let mut _ssl = false; #[cfg(any(feature = "openSSL", feature = "rustls"))] - { + if let Some((tls_listener, acceptor)) = tls { use crate::task; - let clone = Arc::clone(&server); - let tls_connections = Arc::clone(&connections); - _ssl = true; - - async fn listen_ssl( - server: Arc, - connections: Arc, - ) -> Result<(), Box> { - let server_builder = ServerBuilder::new(server.settings.ssl.port); - server_builder? + let server = Arc::clone(&server); + let connections = Arc::clone(&connections); + task!({ + tls_listener .listen_ssl( + acceptor, |stream, server| async { Octane::serve(stream, server).await }, server, connections, ) - .await?; - Ok(()) - } - - task!({ - if let Err(x) = listen_ssl(clone, tls_connections).await { - println!("WARNING: {}", x); - } + .await }); } exec(); let shutdown = Arc::clone(&server.shutdown); - let accepting = ServerBuilder::new(port)?.listen( + let accepting = listener.listen( move |stream, server| async move { Octane::serve(stream, server).await }, server, Arc::clone(&connections), @@ -278,6 +273,40 @@ impl Octane { Ok(()) } + /// The TLS listener and the acceptor for its connections, `None` when + /// TLS isn't set up: neither a key nor a certificate was given. Giving + /// only one of them is an error, as is a key or certificate that can't + /// be loaded. + #[cfg(any(feature = "openSSL", feature = "rustls"))] + fn bind_tls( + settings: &OctaneConfig, + ) -> Result, Box> { + let ssl = &settings.ssl; + match ( + ssl.key.as_os_str().is_empty(), + ssl.cert.as_os_str().is_empty(), + ) { + (true, true) => return Ok(None), + (false, false) => {} + _ => { + return Err("TLS needs both a key and a certificate, \ + set them with `app.ssl(port).key(..).cert(..)`" + .into()) + } + } + let acceptor = crate::tls::acceptor(settings).map_err(|error| { + format!( + "can't load the TLS certificate {} and key {}: {}", + ssl.cert.display(), + ssl.key.display(), + error + ) + })?; + let listener = ServerBuilder::new(ssl.port) + .map_err(|error| format!("can't listen on the TLS port {}: {}", ssl.port, error))?; + Ok(Some((listener, acceptor))) + } + /// Register a task that stops when the server shuts down pub(crate) fn watch_shutdown(&self) -> Watch { self.shutdown.watch() @@ -482,24 +511,9 @@ impl Octane { let version = request.request_line.version; let keep_alive = settings.keep_alive.is_some() && request.keep_alive(); let mut res = Response::new_empty(); - // run closures - server.router.run(&request, &mut res).await; + server.route(request, &mut res).await; // a shutdown that started while the handler ran ends the connection let keep_alive = keep_alive && !server.shutdown.started(); - if !res.has_body() { - // nothing answered: the path doesn't exist, or not for this - // method, which gets a 405 naming the ones it has (RFC 9110 - // section 15.5.6) - let allowed = server.router.allowed(&request.request_line.path); - let method = request.request_line.method; - if allowed.is_empty() || allowed.contains(&method) { - res = Error::response(StatusCode::NotFound); - } else { - let names: Vec<&str> = allowed.iter().map(RequestMethod::as_str).collect(); - res = Error::response(StatusCode::MethodNotAllowed); - res.headers.set("Allow", names.join(", ")); - } - } if !keep_alive { res.headers.set("Connection", "close"); } else if version == HttpVersion::Http10 { @@ -530,10 +544,25 @@ impl Octane { Ok(false) } - /// Run the router for a parsed request, filling `res`. Exposed for the - /// HTTP/2 driver (a separate module) which cannot reach the private router. + /// Run the router for a parsed request, filling `res`. A request that + /// nothing answered (see [`Flow`](crate::router::Flow)) gets a 404, or + /// a 405 naming the methods its path has. Also used by the HTTP/2 + /// driver (a separate module) which cannot reach the private router. pub(crate) async fn route(&self, request: Request<'_>, res: &mut Response<'_>) { - self.router.run(&request, res).await; + if self.router.run(&request, res).await || res.has_body() { + return; + } + // the path doesn't exist, or not for this method, which gets a 405 + // naming the ones it has (RFC 9110 section 15.5.6) + let allowed = self.router.allowed(&request.request_line.path); + let method = request.request_line.method; + if allowed.is_empty() || allowed.contains(&method) { + *res = Error::response(StatusCode::NotFound); + } else { + let names: Vec<&str> = allowed.iter().map(RequestMethod::as_str).collect(); + *res = Error::response(StatusCode::MethodNotAllowed); + res.headers.set("Allow", names.join(", ")); + } } /// Write a response, without its body when `head_only` (the answer to a diff --git a/src/server_builder.rs b/src/server_builder.rs index a701232..887ccf6 100644 --- a/src/server_builder.rs +++ b/src/server_builder.rs @@ -111,15 +111,14 @@ impl ServerBuilder { #[cfg(feature = "openSSL")] pub async fn listen_ssl( self, + acceptor: crate::tls::Acceptor, exec: C, server: Arc, connections: Arc, - ) -> Result<()> - where + ) where T: Future + Send + 'static, C: FnOnce(SslStream, Arc) -> T + Send + 'static + Copy, { - let acceptor = crate::tls::openssl::acceptor(&server.settings)?; let shutdown = server.watch_shutdown(); while let Some((tcp_stream, permit)) = accept_bounded(&self.socket, &connections, &shutdown).await @@ -136,21 +135,19 @@ impl ServerBuilder { } }); } - Ok(()) } #[cfg(feature = "rustls")] pub async fn listen_ssl( self, + acceptor: crate::tls::Acceptor, exec: C, server: Arc, connections: Arc, - ) -> std::result::Result<(), Box> - where + ) where T: Future + Send + 'static, C: FnOnce(TlsStream, Arc) -> T + Send + 'static + Copy, { - let acceptor = crate::tls::rustls::acceptor(&server.settings)?; let shutdown = server.watch_shutdown(); while let Some((tcp_stream, permit)) = accept_bounded(&self.socket, &connections, &shutdown).await @@ -167,7 +164,6 @@ impl ServerBuilder { } }); } - Ok(()) } } diff --git a/src/tls/mod.rs b/src/tls/mod.rs index 4fc0542..d562cd3 100644 --- a/src/tls/mod.rs +++ b/src/tls/mod.rs @@ -3,6 +3,27 @@ use tokio::net::TcpStream; pub mod openssl; pub mod rustls; +/// What TLS connections are accepted with, from the configured key and +/// certificate +#[cfg(feature = "rustls")] +pub(crate) type Acceptor = tokio_rustls::TlsAcceptor; +#[cfg(feature = "openSSL")] +pub(crate) type Acceptor = ::openssl::ssl::SslAcceptor; + +/// Load the key and certificate of `settings` into an [`Acceptor`] +#[cfg(feature = "rustls")] +pub(crate) fn acceptor( + settings: &crate::config::OctaneConfig, +) -> Result> { + rustls::acceptor(settings) +} +#[cfg(feature = "openSSL")] +pub(crate) fn acceptor( + settings: &crate::config::OctaneConfig, +) -> Result> { + Ok(openssl::acceptor(settings)?) +} + pub trait AsMutStream { fn stream_mut(&mut self) -> &mut TcpStream; } diff --git a/src/wasip3.rs b/src/wasip3.rs index 2646aae..fab9207 100644 --- a/src/wasip3.rs +++ b/src/wasip3.rs @@ -116,9 +116,10 @@ impl Router { /// returns [`Flow::Stop`] pub async fn run(&self, request: &Request<'_>, res: &mut Responder<'_>) { let method = RequestMethod::from(request.method); - // the parser already refused `..` segments, so this can't fail by - // climbing above the root - let path = match PathBuf::parse(request.path) { + // segments are percent-decoded for routing and url variables. The + // parser already refused `..` segments, but an encoded one (`%2e%2e`) + // above the root fails here and the request gets a 404. + let path = match PathBuf::parse_request(request.path) { Ok(path) => path, Err(_) => return, }; diff --git a/tests/bodyless.rs b/tests/bodyless.rs new file mode 100644 index 0000000..47882ef --- /dev/null +++ b/tests/bodyless.rs @@ -0,0 +1,70 @@ +#![cfg(feature = "std")] +//! A route that answers without a body still answers the request. +use octane::prelude::*; +use octane::StatusCode; +mod common; + +const PORT: u16 = 8096; + +#[test] +pub fn responses_without_a_body() { + let mut app = Octane::new(); + // middleware that stops answers, one that passes doesn't + app.add(route!(|req, res| { + if req.headers.contains("x-block") { + res.status(StatusCode::Unauthorized); + Flow::Stop + } else { + res.set("X-Seen", "yes"); + Flow::Next + } + })) + .unwrap(); + app.get( + "/redirect", + route_stop!(|req, res| { + res.redirect("/"); + }), + ) + .unwrap(); + app.get( + "/next-redirect", + route_next!(|req, res| { + res.redirect("/"); + }), + ) + .unwrap(); + app.delete( + "/item", + route_stop!(|req, res| { + res.status(StatusCode::NoContent); + }), + ) + .unwrap(); + + common::run(app, PORT, || { + let res = common::request(PORT, "GET", "/redirect", &[]); + assert_eq!(302, res.status); + assert_eq!(Some("/"), res.header("location")); + assert_eq!(Some("0"), res.header("content-length")); + assert!(res.body.is_empty()); + + // a route that ran answers even when it passes the request on + let res = common::request(PORT, "GET", "/next-redirect", &[]); + assert_eq!(302, res.status); + + let res = common::request(PORT, "DELETE", "/item", &[]); + assert_eq!(204, res.status); + assert_eq!(None, res.header("content-length")); + + let res = common::request(PORT, "GET", "/missing", &["X-Block: 1"]); + assert_eq!(401, res.status); + + // only middleware ran: still nothing at this path + let res = common::request(PORT, "GET", "/missing", &[]); + assert_eq!(404, res.status); + let res = common::request(PORT, "POST", "/redirect", &[]); + assert_eq!(405, res.status); + assert_eq!(Some("GET"), res.header("allow")); + }); +} diff --git a/tests/common.rs b/tests/common.rs index 886f50b..bb7a86b 100644 --- a/tests/common.rs +++ b/tests/common.rs @@ -95,7 +95,8 @@ pub fn connect(port: u16) -> TcpStream { /// Read one response off `stream`, and nothing past it: the body is as long /// as its `Content-Length`, or runs to the end of the stream without one. -/// The answer to a `HEAD` request (`head_only`) has no body. +/// The answer to a `HEAD` request (`head_only`) has no body, nor do 1xx, +/// `204` and `304` responses. #[allow(dead_code)] pub fn read_response(stream: &mut TcpStream, head_only: bool) -> Response { // a byte at a time, so the start of the next response stays unread @@ -123,7 +124,7 @@ pub fn read_response(stream: &mut TcpStream, head_only: bool) -> Response { head, body: Vec::new(), }; - if !head_only { + if !head_only && !matches!(status, 100..=199 | 204 | 304) { match response.header("content-length") { Some(len) => { response.body = vec![0; len.parse().expect("bad Content-Length")]; diff --git a/tests/forms.rs b/tests/forms.rs new file mode 100644 index 0000000..7444ad0 --- /dev/null +++ b/tests/forms.rs @@ -0,0 +1,32 @@ +#![cfg(feature = "std")] +use octane::prelude::*; +mod common; + +const PORT: u16 = 8098; + +#[test] +pub fn form_bodies_are_decoded() { + let mut app = Octane::new(); + app.post( + "/sign", + route_stop!(|req, res| { + let form = req.get_form(); + let name = form.get("name").unwrap_or(""); + let note = form.get("note").unwrap_or(""); + res.send(format!("{}|{}", name, note)); + }), + ) + .unwrap(); + common::run(app, PORT, || { + let body = "name=Ada+Lovelace¬e=1%2B1%3D2+%F0%9F%A6%80"; + let request = format!( + "POST /sign HTTP/1.1\r\nHost: localhost\r\n\ + Content-Type: application/x-www-form-urlencoded\r\n\ + Content-Length: {}\r\n\r\n{}", + body.len(), + body + ); + let res = common::raw_request(PORT, request.as_bytes()); + assert_eq!("Ada Lovelace|1+1=2 \u{1F980}", res.text()); + }); +} diff --git a/tests/tls_config.rs b/tests/tls_config.rs new file mode 100644 index 0000000..3003a99 --- /dev/null +++ b/tests/tls_config.rs @@ -0,0 +1,58 @@ +#![cfg(any(feature = "rustls", feature = "openSSL"))] +//! TLS problems are returned by `listen`, and TLS that isn't set up +//! doesn't start. +use octane::prelude::*; +use std::time::Duration; +use tokio::runtime::Runtime; +use tokio::time::timeout; +mod common; + +// `listen` with `app`, which should fail right away +fn listen_error(app: Octane, port: u16) -> String { + let runtime = Runtime::new().unwrap(); + runtime.block_on(async { + let listening = timeout(Duration::from_secs(5), app.listen(port, || {})); + match listening.await { + Ok(Err(error)) => error.to_string(), + Ok(Ok(())) => panic!("listen returned without an error"), + Err(_) => panic!("listen started serving instead of failing"), + } + }) +} + +#[test] +pub fn missing_certificate_is_an_error() { + let mut app = Octane::new(); + app.ssl(8445) + .key("templates/does-not-exist.pem") + .cert("templates/does-not-exist.pem"); + let error = listen_error(app, 8099); + assert!( + error.contains("can't load the TLS certificate"), + "{}", + error + ); + // nothing was left listening + assert!(std::net::TcpStream::connect(("127.0.0.1", 8099)).is_err()); +} + +#[test] +pub fn half_configured_tls_is_an_error() { + let mut app = Octane::new(); + app.ssl(8446).key("templates/key.pem"); + let error = listen_error(app, 8100); + assert!(error.contains("both a key and a certificate"), "{}", error); +} + +#[test] +pub fn tls_without_a_certificate_is_off() { + let mut app = Octane::new(); + app.settings.ssl.port = 8447; + app.get("/", route_stop!(|req, res| res.send("plain"))) + .unwrap(); + // with the TLS feature on but no key or certificate, only HTTP is served + common::run(app, 8101, || { + assert_eq!("plain", common::request(8101, "GET", "/", &[]).text()); + assert!(std::net::TcpStream::connect(("127.0.0.1", 8447)).is_err()); + }); +} diff --git a/tests/url_variables.rs b/tests/url_variables.rs index 1cb0095..2c3ed77 100644 --- a/tests/url_variables.rs +++ b/tests/url_variables.rs @@ -18,3 +18,34 @@ pub fn basic_url_variables() { assert_eq!(value, res.text()); }); } + +#[test] +pub fn url_variables_are_decoded() { + const PORT: u16 = 8097; + let mut app = Octane::new(); + app.get( + "/users/:name", + route_stop!(|req, res| { + res.send(req.vars.get("name").unwrap()); + }), + ) + .unwrap(); + app.get("/café", route_stop!(|req, res| res.send("coffee"))) + .unwrap(); + common::run(app, PORT, || { + let res = common::request(PORT, "GET", "/users/Ada%20Lovelace", &[]); + assert_eq!("Ada Lovelace", res.text()); + // `+` is only a space in queries and forms + let res = common::request(PORT, "GET", "/users/a+b", &[]); + assert_eq!("a+b", res.text()); + // an encoded slash stays in the variable + let res = common::request(PORT, "GET", "/users/a%2Fb", &[]); + assert_eq!("a/b", res.text()); + // literal routes match the decoded path too + let res = common::request(PORT, "GET", "/caf%C3%A9", &[]); + assert_eq!("coffee", res.text()); + // an encoded `..` is a dot segment, not a variable + let res = common::request(PORT, "GET", "/users/x/%2e%2e/Ada", &[]); + assert_eq!("Ada", res.text()); + }); +}