Skip to main content

aria2_protocol/
proxy.rs

1use crate::uri::percent_decode;
2
3/// A parsed proxy URL (for example, `socks5://user:pass@host:port`).
4pub struct ProxyUrl {
5    pub protocol: ProxyProtocol,
6    pub host: String,
7    pub port: u16,
8    pub username: Option<String>,
9    pub password: Option<String>,
10}
11
12impl std::fmt::Debug for ProxyUrl {
13    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        formatter
15            .debug_struct("ProxyUrl")
16            .field("protocol", &self.protocol)
17            .field("host", &self.host)
18            .field("port", &self.port)
19            .field("username", &self.username.as_ref().map(|_| "[REDACTED]"))
20            .field("password", &self.password.as_ref().map(|_| "[REDACTED]"))
21            .finish()
22    }
23}
24
25/// The protocol selected by a proxy URL scheme.
26#[derive(Debug, Clone, PartialEq)]
27pub enum ProxyProtocol {
28    Socks4,
29    Socks5,
30    Http,
31    Https,
32}
33
34impl ProxyUrl {
35    /// Parse a proxy URL and percent-decode its username and password.
36    ///
37    /// Supported forms are `socks5://[username:password@]host[:port]`,
38    /// `socks4://[username@]host[:port]`, `http://[username:password@]host[:port]`,
39    /// and `https://[username:password@]host[:port]`. Schemes are matched
40    /// case-insensitively. Any path, query, or fragment is ignored because
41    /// proxy routing uses only the authority.
42    pub fn parse(url: &str) -> Result<Self, String> {
43        let url = url.trim();
44        let (scheme, rest) = url
45            .split_once("://")
46            .ok_or_else(|| "Invalid proxy URL: expected scheme://authority".to_string())?;
47        let protocol = if scheme.eq_ignore_ascii_case("socks5") {
48            ProxyProtocol::Socks5
49        } else if scheme.eq_ignore_ascii_case("socks4") {
50            ProxyProtocol::Socks4
51        } else if scheme.eq_ignore_ascii_case("http") {
52            ProxyProtocol::Http
53        } else if scheme.eq_ignore_ascii_case("https") {
54            ProxyProtocol::Https
55        } else {
56            return Err(format!("Unsupported proxy protocol '{scheme}'"));
57        };
58
59        let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
60        let (auth_part, host_port) = match authority.rfind('@') {
61            Some(0) => return Err("Username is empty in proxy URL".to_string()),
62            Some(index) => (&authority[..index], &authority[index + 1..]),
63            None => ("", authority),
64        };
65        if auth_part.starts_with('@') {
66            return Err("Username is empty in proxy URL".to_string());
67        }
68        let (username, password) = if !auth_part.is_empty() {
69            if let Some(index) = auth_part.find(':') {
70                (
71                    Some(percent_decode(&auth_part[..index])),
72                    Some(percent_decode(&auth_part[index + 1..])),
73                )
74            } else {
75                (Some(percent_decode(auth_part)), None)
76            }
77        } else {
78            (None, None)
79        };
80
81        let default_port = match protocol {
82            ProxyProtocol::Socks4 | ProxyProtocol::Socks5 => 1080,
83            ProxyProtocol::Http => 80,
84            ProxyProtocol::Https => 443,
85        };
86        let (host, port) = if let Some(bracketed) = host_port.strip_prefix('[') {
87            let close = bracketed
88                .find(']')
89                .ok_or_else(|| "Missing closing bracket in proxy IPv6 host".to_string())?;
90            let host = &bracketed[..close];
91            host.parse::<std::net::Ipv6Addr>()
92                .map_err(|_| "Invalid IPv6 host in proxy URL".to_string())?;
93            let suffix = &bracketed[close + 1..];
94            let port = if suffix.is_empty() {
95                default_port
96            } else if let Some(port_text) = suffix.strip_prefix(':') {
97                port_text
98                    .parse()
99                    .map_err(|_| "Invalid port number in proxy URL".to_string())?
100            } else {
101                return Err("Invalid bracketed proxy host".to_string());
102            };
103            (host.to_string(), port)
104        } else if let Some(index) = host_port.rfind(':') {
105            let host = &host_port[..index];
106            let port_text = &host_port[index + 1..];
107            if host.contains(':') {
108                return Err("IPv6 proxy hosts must be enclosed in brackets".to_string());
109            }
110            let port = port_text
111                .parse()
112                .map_err(|_| "Invalid port number in proxy URL".to_string())?;
113            (host.to_string(), port)
114        } else {
115            (host_port.to_string(), default_port)
116        };
117
118        if host.is_empty() {
119            return Err("Host is empty in proxy URL".to_string());
120        }
121        if host.chars().any(|character| {
122            character.is_whitespace()
123                || character.is_control()
124                || matches!(character, '@' | '[' | ']')
125        }) {
126            return Err("Invalid host in proxy URL".to_string());
127        }
128
129        Ok(Self {
130            protocol,
131            host,
132            port,
133            username,
134            password,
135        })
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::{ProxyProtocol, ProxyUrl};
142
143    #[test]
144    fn proxy_url_debug_redacts_credentials() {
145        let proxy = ProxyUrl {
146            protocol: ProxyProtocol::Http,
147            host: "proxy.example".to_string(),
148            port: 80,
149            username: Some("private-user".to_string()),
150            password: Some("private-password".to_string()),
151        };
152
153        let debug = format!("{proxy:?}");
154        assert!(debug.contains("[REDACTED]"));
155        assert!(!debug.contains("private-user"));
156        assert!(!debug.contains("private-password"));
157    }
158
159    #[test]
160    fn proxy_url_parses_case_insensitive_scheme_and_decodes_credentials() {
161        let proxy = ProxyUrl::parse("HtTp://user%40name:p%3A%40%25@proxy.example").unwrap();
162
163        assert_eq!(proxy.protocol, ProxyProtocol::Http);
164        assert_eq!(proxy.host, "proxy.example");
165        assert_eq!(proxy.port, 80);
166        assert_eq!(proxy.username.as_deref(), Some("user@name"));
167        assert_eq!(proxy.password.as_deref(), Some("p:@%"));
168    }
169
170    #[test]
171    fn proxy_url_ignores_userinfo_delimiters_after_authority() {
172        let proxy = ProxyUrl::parse("http://proxy.example/path@marker?next=@query#@fragment")
173            .expect("path, query, and fragment are ignored");
174
175        assert_eq!(proxy.host, "proxy.example");
176        assert_eq!(proxy.port, 80);
177        assert_eq!(proxy.username, None);
178        assert_eq!(proxy.password, None);
179
180        let proxy = ProxyUrl::parse("http://user:pass@proxy.example/path@marker")
181            .expect("authority userinfo should still parse");
182        assert_eq!(proxy.username.as_deref(), Some("user"));
183        assert_eq!(proxy.password.as_deref(), Some("pass"));
184        assert_eq!(proxy.host, "proxy.example");
185    }
186
187    #[test]
188    fn proxy_url_parse_errors_do_not_include_userinfo() {
189        let error = ProxyUrl::parse("unknown://private-user:private-password@proxy.example")
190            .expect_err("unknown schemes should be rejected");
191
192        assert!(!error.contains("private-user"));
193        assert!(!error.contains("private-password"));
194    }
195
196    #[test]
197    fn proxy_url_uses_last_at_sign_for_userinfo() {
198        let proxy = ProxyUrl::parse("http://user@domain:pass@proxy.example").unwrap();
199
200        assert_eq!(proxy.username.as_deref(), Some("user@domain"));
201        assert_eq!(proxy.password.as_deref(), Some("pass"));
202        assert_eq!(proxy.host, "proxy.example");
203    }
204
205    #[test]
206    fn proxy_url_rejects_malformed_authorities() {
207        for url in [
208            "http://@proxy.example",
209            "http://@user@proxy.example",
210            "http://proxy.example@",
211            "http://2001:db8::1:8080",
212            "http://[not-ipv6]:8080",
213            "http://proxy[.example]:8080",
214        ] {
215            assert!(ProxyUrl::parse(url).is_err(), "accepted {url}");
216        }
217    }
218}