Skip to main content

rust_web_server/url/
mod.rs

1//! URL helpers: percent encoding (`URL::percent_encode` / `percent_decode`),
2//! query strings (`URL::build_query` / `parse_query`) and whole URLs
3//! (`URL::build` / `parse`, a panic-free RFC 3986 parser).
4//! `URL::parse_request_target` gives a request's path and query without
5//! inventing a scheme and host. Percent encoding is what lets a query value
6//! carry a space (`%20`), `=` (`%3D`) or `&` (`%26`). Examples:
7//! `src/url/example/`.
8
9#[cfg(test)]
10mod tests;
11#[cfg(test)]
12mod example;
13pub mod path;
14
15use std::collections::HashMap;
16use url_build_parse::{build_url, UrlAuthority, UrlComponents, UrlUserInfo};
17use url_search_params::{build_url_search_params, encode_uri_component, parse_url_search_params};
18use url_search_params::decode_uri_component;
19
20/// URL parsing, building, and percent-encoding utilities.
21pub struct URL;
22
23impl URL {
24    pub fn percent_encode(component: &str) -> String {
25        encode_uri_component(component)
26    }
27
28    pub fn percent_decode(component: &str) -> String {
29        decode_uri_component(component)
30    }
31
32    pub fn build_query(params: HashMap<String, String>) -> String {
33        build_url_search_params(params)
34    }
35
36    pub fn parse_query(component: &str) -> HashMap<String, String> {
37        parse_url_search_params(component)
38    }
39
40    pub fn build(components: UrlComponents) -> Result<String, String> {
41        build_url(components)
42    }
43
44    pub fn parse(url: &str) -> Result<UrlComponents, String> {
45        parse_url(url)
46    }
47
48    /// Parse an origin-form request target (`/path?query`) — what
49    /// `Request::request_uri` holds. Anything not starting with `/` is an
50    /// error rather than being glued onto a placeholder authority, where a
51    /// target like `:x` would become the port of `http://localhost:x`.
52    pub fn parse_request_target(target: &str) -> Result<UrlComponents, String> {
53        if !target.starts_with('/') {
54            return Err(format!("not an origin-form request target: {:?}", target));
55        }
56        parse_url(&format!("http://localhost{}", target))
57    }
58
59    /// The path of an origin-form request target — everything before the
60    /// first `?` or `#` — borrowed, without parsing or allocating. Same value
61    /// as [`URL::parse_request_target`]`(target)?.path`; `None` for a target
62    /// that isn't origin-form. For per-request matching on hot paths.
63    pub(crate) fn request_target_path(target: &str) -> Option<&str> {
64        if !target.starts_with('/') {
65            return None;
66        }
67        Some(&target[..target.find(['?', '#']).unwrap_or(target.len())])
68    }
69}
70
71/// RFC 3986 parse of `scheme:[//authority]path[?query][#fragment]` into
72/// url-build-parse's `UrlComponents`, without panicking on malformed input.
73/// (url-build-parse's own `parse_url` unwraps on input-derived values — e.g.
74/// a non-numeric port — so a hostile URL could panic the caller.)
75fn parse_url(url: &str) -> Result<UrlComponents, String> {
76    let (scheme, rest) = url.split_once(':').ok_or("unable to identify scheme")?;
77    if rest.is_empty() {
78        return Err("error: remaining url is empty".to_string());
79    }
80    let mut components = UrlComponents::new();
81    components.scheme = scheme.to_string();
82
83    // Authority: after "//", up to the first '/', '?' or '#'.
84    let mut remaining = rest;
85    if let Some(after) = rest.strip_prefix("//") {
86        let end = after.find(['/', '?', '#']).unwrap_or(after.len());
87        components.authority = Some(parse_authority(&after[..end])?);
88        remaining = &after[end..];
89    }
90
91    // Path: up to the first '?' or '#'.
92    let path_end = remaining.find(['?', '#']).unwrap_or(remaining.len());
93    components.path = remaining[..path_end].to_string();
94    remaining = &remaining[path_end..];
95
96    if let Some(after) = remaining.strip_prefix('?') {
97        let query_end = after.find('#').unwrap_or(after.len());
98        components.query = Some(parse_url_search_params(&after[..query_end]));
99        remaining = &after[query_end..];
100    }
101    if let Some(fragment) = remaining.strip_prefix('#') {
102        components.fragment = Some(fragment.to_string());
103    }
104    Ok(components)
105}
106
107/// `[userinfo@]host[:port]`, with `[...]` IPv6 hosts.
108fn parse_authority(authority: &str) -> Result<UrlAuthority, String> {
109    let (user_info, host_port) = match authority.split_once('@') {
110        Some((user_info, host_port)) => {
111            let user_info = match user_info.split_once(':') {
112                Some((username, password)) => UrlUserInfo {
113                    username: username.to_string(),
114                    password: Some(password.to_string()),
115                },
116                None => UrlUserInfo { username: user_info.to_string(), password: None },
117            };
118            (Some(user_info), host_port)
119        }
120        None => (None, authority),
121    };
122
123    let (host, port_str) = if host_port.starts_with('[') {
124        let close = host_port.find(']').ok_or("unterminated IPv6 host")?;
125        let after = &host_port[close + 1..];
126        let port = match after.strip_prefix(':') {
127            Some(port) => Some(port),
128            None if after.is_empty() => None,
129            None => return Err(format!("unexpected characters after IPv6 host: {:?}", after)),
130        };
131        (&host_port[..=close], port)
132    } else {
133        match host_port.split_once(':') {
134            Some((host, port)) => (host, Some(port)),
135            None => (host_port, None),
136        }
137    };
138
139    let port = match port_str {
140        Some(port) => Some(port.parse::<usize>().map_err(|_| format!("invalid port: {:?}", port))?),
141        None => None,
142    };
143    Ok(UrlAuthority { user_info, host: host.to_string(), port })
144}
145