//! Conversion between file paths and `file:` URIs. //! //! LSP addresses documents by URI (RFC 3986). Paths become //! `file:///C:/dir/a%20b.php` on Windows and `file:///dir/a%20b.php` on Unix: //! every byte outside the unreserved set, `/` and a drive letter's `:` is //! percent-encoded as UTF-8. URIs from the server are untrusted and are //! decoded leniently (any case of escapes, an encoded drive colon, a //! `localhost` authority) but strictly enough that a bad escape or a //! non-`file` scheme yields `None` rather than a wrong path. use std::path::{Path, PathBuf}; use crate::LspError; /// Converts an absolute path to a `file:` URI. /// /// On Windows the verbatim prefix (`\\?\`) is removed, `\` becomes `/`, and a /// UNC path `\\server\share\x` becomes `file://server/share/x`. /// /// # Errors /// [`LspError::InvalidPath`] when the path is relative or not valid UTF-8. pub fn path_to_uri(path: &Path) -> Result { let invalid = || LspError::InvalidPath { path: path.display().to_string(), }; if !path.is_absolute() { return Err(invalid()); } let text = path.to_str().ok_or_else(invalid)?; if cfg!(windows) { let text = text .strip_prefix(r"\\?\UNC\") .map(|rest| format!(r"\\{rest}")) .unwrap_or_else(|| text.strip_prefix(r"\\?\").unwrap_or(text).to_string()); let slashed = text.replace('\\', "/"); if let Some(unc) = slashed.strip_prefix("//") { let (host, rest) = unc.split_once('/').unwrap_or((unc, "")); return Ok(format!( "file://{}/{}", encode(host, false), encode(rest, false) )); } return Ok(format!("file:///{}", encode(&slashed, true))); } Ok(format!("file://{}", encode(text, false))) } /// Converts a `file:` URI to a path. /// /// A query or fragment is ignored. On Windows a drive letter is returned in /// upper case, so `file:///c%3A/x` and `file:///C:/x` give the same path. /// /// # Returns /// `None` for another scheme, a bad percent escape, a decoded path that is /// not UTF-8 or contains a NUL, or (on Unix) a host other than `localhost`. pub fn uri_to_path(uri: &str) -> Option { let scheme = uri.get(..7)?; if !scheme.eq_ignore_ascii_case("file://") { return None; } let rest = uri.get(7..)?; let rest = rest.split(['?', '#']).next().unwrap_or_default(); let (host, path) = match rest.find('/') { Some(at) => (rest.get(..at)?, rest.get(at..)?), None => (rest, ""), }; let host = decode(host)?; let path = decode(path)?; if path.contains('\0') || host.contains(['\0', '/', '\\']) { return None; } let host = if host.eq_ignore_ascii_case("localhost") { String::new() } else { host }; if cfg!(windows) { if !host.is_empty() { return Some(PathBuf::from(format!( r"\\{host}{}", path.replace('/', "\\") ))); } let trimmed = path.strip_prefix('/').unwrap_or(&path); let mut chars = trimmed.chars(); if let (Some(letter), Some(':')) = (chars.next(), chars.next()) && letter.is_ascii_alphabetic() { let tail = chars.as_str().replace('/', "\\"); let tail = if tail.is_empty() { "\\".to_string() } else { tail }; return Some(PathBuf::from(format!( "{}:{tail}", letter.to_ascii_uppercase() ))); } return None; } if !host.is_empty() || !path.starts_with('/') { return None; } Some(PathBuf::from(path)) } /// Percent-encodes `text`, keeping unreserved characters and `/`; with /// `drive` set, a `:` right after a leading drive letter is kept too. fn encode(text: &str, drive: bool) -> String { let keep_colon_at = if drive && text.len() >= 2 && text.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) && text.as_bytes().get(1) == Some(&b':') { Some(1) } else { None }; let mut out = String::with_capacity(text.len()); for (index, byte) in text.bytes().enumerate() { let keep = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/') || keep_colon_at == Some(index); if keep { out.push(char::from(byte)); } else { out.push_str(&format!("%{byte:02X}")); } } out } /// Decodes percent escapes; `None` for a malformed escape or bytes that are /// not UTF-8. fn decode(text: &str) -> Option { let bytes = text.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut index = 0; while let Some(&byte) = bytes.get(index) { if byte == b'%' { let high = hex(*bytes.get(index + 1)?)?; let low = hex(*bytes.get(index + 2)?)?; out.push(high * 16 + low); index += 3; } else { out.push(byte); index += 1; } } String::from_utf8(out).ok() } /// The value of one hex digit. fn hex(digit: u8) -> Option { char::from(digit) .to_digit(16) .and_then(|d| u8::try_from(d).ok()) } #[cfg(test)] mod tests { use super::*; use proptest::prelude::*; fn root() -> PathBuf { if cfg!(windows) { PathBuf::from(r"C:\") } else { PathBuf::from("/") } } #[test] fn encodes_spaces_and_unicode() { let path = root().join("my dir").join("รค#.php"); let uri = path_to_uri(&path).unwrap(); if cfg!(windows) { assert_eq!(uri, "file:///C:/my%20dir/%C3%A4%23.php"); } else { assert_eq!(uri, "file:///my%20dir/%C3%A4%23.php"); } assert_eq!(uri_to_path(&uri), Some(path)); } #[test] fn rejects_relative_and_foreign() { assert!(path_to_uri(Path::new("a/b")).is_err()); assert_eq!(uri_to_path("http://x/y"), None); assert_eq!(uri_to_path("file:///a%zz"), None); assert_eq!(uri_to_path("file:///a%"), None); assert_eq!(uri_to_path("file:///a%00"), None); assert_eq!(uri_to_path("fi"), None); } #[cfg(windows)] #[test] fn windows_forms() { assert_eq!( uri_to_path("file:///c%3A/x/y.php"), Some(PathBuf::from(r"C:\x\y.php")) ); assert_eq!( uri_to_path("FILE://localhost/C:/x"), Some(PathBuf::from(r"C:\x")) ); assert_eq!( uri_to_path("file://server/share/a"), Some(PathBuf::from(r"\\server\share\a")) ); assert_eq!(path_to_uri(Path::new(r"\\?\C:\x")).unwrap(), "file:///C:/x"); assert_eq!( path_to_uri(Path::new(r"\\server\share\a b")).unwrap(), "file://server/share/a%20b" ); } proptest! { #[test] fn round_trips(segments in proptest::collection::vec("[^/\\\\:*?\"<>|\u{0}]{1,8}", 1..5)) { let mut path = root(); for segment in &segments { let segment = segment.trim_end_matches(['.', ' ']); if segment.is_empty() || segment == ".." || segment == "." { continue; } path.push(segment); } let uri = path_to_uri(&path).unwrap(); prop_assert_eq!(uri_to_path(&uri), Some(path)); } #[test] fn never_panics(input in ".{0,40}") { let _ = uri_to_path(&input); let _ = uri_to_path(&format!("file://{input}")); } } }