//! Query strings, repository paths and URL encoding. use std::borrow::Cow; use std::collections::HashMap; use std::ffi::OsString; use std::fmt::Write as _; use std::os::unix::ffi::OsStringExt; use gitv_core::percent_decode; // --------------------------------------------------------------------------------------------- // Query strings and paths // // File paths are bytes, not text: git allows any bytes but `/` and NUL in a name, so a path // is decoded from the URL, checked and handed to git without ever passing through UTF-8. /// Query parameters with their values percent-decoded to raw bytes. The first of a repeated /// key wins. pub(crate) type Q = HashMap>; pub(crate) fn parse_query(raw: Option<&str>) -> Q { let mut query = Q::new(); for pair in raw.unwrap_or("").split('&').filter(|p| !p.is_empty()) { let (key, value) = pair.split_once('=').unwrap_or((pair, "")); // In a query string `+` is a space; an encoded plus (`%2B`) stays a plus. let (key, value) = (key.replace('+', " "), value.replace('+', " ")); if let Ok(key) = String::from_utf8(percent_decode(&key)) { query.entry(key).or_insert_with(|| percent_decode(&value)); } } query } /// A text parameter; one that isn't valid UTF-8 counts as absent. pub(crate) fn param(q: &Q, key: &str) -> Option { q.get(key).and_then(|v| String::from_utf8(v.clone()).ok()) } pub(crate) fn encode(value: &[u8]) -> String { let mut out = String::with_capacity(value.len()); for &b in value { match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => out.push(b as char), _ => { let _ = write!(out, "%{b:02X}"); } } } out } /// A repository-relative path with no `.`, `..`, empty or absolute parts and no NUL. pub(crate) fn clean_path(value: &[u8]) -> Option> { let parts: Vec<&[u8]> = value.split(|b| *b == b'/').filter(|p| !p.is_empty()).collect(); if parts.iter().any(|p| *p == b"." || *p == b".." || p.contains(&0)) { return None; } Some(parts.join(&b'/')) } pub(crate) fn parent_of(path: &[u8]) -> &[u8] { path.iter().rposition(|b| *b == b'/').map_or(&[], |i| &path[..i]) } pub(crate) fn file_name(path: &[u8]) -> &[u8] { path.iter().rposition(|b| *b == b'/').map_or(path, |i| &path[i + 1..]) } pub(crate) fn join(dir: &[u8], name: &[u8]) -> Vec { if dir.is_empty() { name.to_vec() } else { [dir, b"/", name].concat() } } /// Bytes for display. Names that aren't UTF-8 show replacement characters, but links keep /// the real bytes. pub(crate) fn lossy(bytes: &[u8]) -> Cow<'_, str> { String::from_utf8_lossy(bytes) } /// `:` for git, path bytes intact. pub(crate) fn spec(commit: &str, path: &[u8]) -> OsString { let mut spec = format!("{commit}:").into_bytes(); spec.extend_from_slice(path); OsString::from_vec(spec) } #[cfg(test)] mod tests { use super::*; #[test] fn percent_decoding_keeps_raw_bytes() { assert_eq!(percent_decode("a%2Fb+c"), b"a/b+c", "a plus is literal outside query strings"); assert_eq!(parse_query(Some("p=a+b%2Bc"))["p"], b"a b+c"); assert_eq!(percent_decode("caf%C3%A9"), "café".as_bytes()); assert_eq!(percent_decode("%FF%00"), [0xff, 0]); assert_eq!(percent_decode("100%"), b"100%"); assert_eq!(percent_decode("%zz%4"), b"%zz%4"); } #[test] fn query_first_value_wins() { let q = parse_query(Some("path=a&path=b&ref=main&flag")); assert_eq!(q["path"], b"a"); assert_eq!(param(&q, "ref").as_deref(), Some("main")); assert_eq!(q["flag"], b""); } #[test] fn paths_are_cleaned_as_bytes() { assert_eq!(clean_path(b"/a//b/"), Some(b"a/b".to_vec())); assert_eq!(clean_path(b"a/../b"), None); assert_eq!(clean_path(b"./a"), None); assert_eq!(clean_path(b"a\0b"), None); assert_eq!(clean_path(&[0xff, b'/', b'x']), Some(vec![0xff, b'/', b'x'])); assert_eq!(encode(&[b'a', b' ', 0xff, b'/']), "a%20%FF/"); } }