// SPDX-License-Identifier: MIT //! Shared `application/x-www-form-urlencoded` / query decoding for the HTTP edge. //! //! One implementation, used by the web server, the miner service and the //! dashboard, so a fix or a bug cannot diverge between copies. /// Percent-decode a form or query token (`%XX` escapes and `+` as space). pub fn percent_decode(text: &str) -> String { let bytes = text.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; while i < bytes.len() { match bytes[i] { b'%' if i + 2 < bytes.len() => { let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or(""); match u8::from_str_radix(hex, 16) { Ok(byte) => { out.push(byte); i += 3; } Err(_) => { out.push(bytes[i]); i += 1; } } } b'+' => { out.push(b' '); i += 1; } byte => { out.push(byte); i += 1; } } } String::from_utf8_lossy(&out).into_owned() } /// Read one field from a urlencoded body by key (first match), percent-decoded. pub fn field(body: &str, key: &str) -> Option { body.split('&').find_map(|pair| { let (k, v) = pair.split_once('=')?; (percent_decode(k) == key).then(|| percent_decode(v)) }) } #[cfg(test)] mod tests { use super::*; #[test] fn decodes_escapes_and_plus() { assert_eq!(percent_decode("a+b%2Fc"), "a b/c"); assert_eq!(percent_decode("%0d%0a"), "\r\n"); // A truncated trailing escape is passed through, not dropped. assert_eq!(percent_decode("x%2"), "x%2"); } #[test] fn field_reads_first_match() { assert_eq!(field("a=1&b=two&a=3", "b").as_deref(), Some("two")); assert_eq!(field("a=1", "missing"), None); assert_eq!(field("csrf=tok&user=admin", "csrf").as_deref(), Some("tok")); } }