Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand Down
77 changes: 77 additions & 0 deletions src/decode.rs
Original file line number Diff line number Diff line change
@@ -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<u8> {
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}");
}
}
8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -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;
Expand Down
60 changes: 60 additions & 0 deletions src/path.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::decode::unescape;
use crate::{default, deref};
use std::convert::TryFrom;
use std::error;
Expand Down Expand Up @@ -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<Self, InvalidPathError> {
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 {
Expand Down Expand Up @@ -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() {
Expand Down
82 changes: 28 additions & 54 deletions src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -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<u8> {
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")]
Expand Down Expand Up @@ -186,7 +160,7 @@ impl QueryValue {
}

#[cfg(feature = "extended_queries")]
pub fn parse_extended_query(query: &str) -> HashMap<String, QueryValue> {
pub(crate) fn parse_extended_query(query: &str) -> HashMap<String, QueryValue> {
let toks = query.split('&');
let mut ret: HashMap<String, QueryValue> = HashMap::new();
for tok in toks {
Expand Down
24 changes: 23 additions & 1 deletion src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ impl RequestLine {
fn from_parts(method: &str, target: &str, version: &str, has_extra: bool) -> Option<Self> {
// 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("");
Expand Down Expand Up @@ -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
/// `<form method="post">` 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")]
Expand Down
Loading
Loading