GITv
master
urls.rs114 lines, 4.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//! 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<String, Vec<u8>>;

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<String> {
    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<Vec<u8>> {
    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<u8> {
    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)
}

/// `<commit>:<path>` 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/");
    }
}