1use std::ffi::OsString;
2use std::path::{Component, Path, PathBuf};
3
4use crate::{WorkspacePathError, WorkspacePathErrorCode};
5
6pub const MAX_WORKSPACE_PATH_BYTES: usize = 4096;
8pub const MAX_WORKSPACE_PATH_COMPONENTS: usize = 256;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub(crate) struct ValidatedRelativePath {
13 display: String,
14 components: Vec<OsString>,
15}
16
17impl ValidatedRelativePath {
18 pub(crate) fn parse(input: &str) -> Result<Self, WorkspacePathError> {
19 if input.is_empty()
20 || input.as_bytes().contains(&0)
21 || input.chars().any(char::is_control)
22 || looks_like_windows_prefix(input)
23 {
24 return Err(WorkspacePathError::new(WorkspacePathErrorCode::InvalidPath));
25 }
26 if input.len() > MAX_WORKSPACE_PATH_BYTES {
27 return Err(WorkspacePathError::new(WorkspacePathErrorCode::PathTooLong));
28 }
29
30 let path = Path::new(input);
31 if path.is_absolute() {
32 return Err(WorkspacePathError::new(
33 WorkspacePathErrorCode::AbsolutePath,
34 ));
35 }
36
37 let mut display_components = Vec::new();
38 let mut components = Vec::new();
39 for component in path.components() {
40 match component {
41 Component::CurDir => {}
42 Component::Normal(value) => {
43 if components.len() == MAX_WORKSPACE_PATH_COMPONENTS {
44 return Err(WorkspacePathError::new(
45 WorkspacePathErrorCode::TooManyComponents,
46 ));
47 }
48 let Some(display) = value.to_str() else {
49 return Err(WorkspacePathError::new(WorkspacePathErrorCode::InvalidPath));
50 };
51 if display.contains(['/', '\\']) {
52 return Err(WorkspacePathError::new(WorkspacePathErrorCode::InvalidPath));
53 }
54 display_components.push(display.to_owned());
55 components.push(value.to_owned());
56 }
57 Component::ParentDir => {
58 return Err(WorkspacePathError::new(
59 WorkspacePathErrorCode::ParentTraversal,
60 ));
61 }
62 Component::RootDir | Component::Prefix(_) => {
63 return Err(WorkspacePathError::new(
64 WorkspacePathErrorCode::AbsolutePath,
65 ));
66 }
67 }
68 }
69
70 let display = if display_components.is_empty() {
71 ".".to_owned()
72 } else {
73 display_components.join("/")
74 };
75 Ok(Self {
76 display,
77 components,
78 })
79 }
80
81 pub(crate) fn display(&self) -> &str {
82 &self.display
83 }
84
85 pub(crate) fn join_to(&self, root: &Path) -> PathBuf {
86 self.components
87 .iter()
88 .fold(root.to_path_buf(), |path, component| path.join(component))
89 }
90}
91
92fn looks_like_windows_prefix(input: &str) -> bool {
93 let bytes = input.as_bytes();
94 let drive_prefix = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
95 drive_prefix || input.starts_with("\\\\") || input.contains('\\')
96}