1use std::path::{Component, Path, PathBuf};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum VfsRoot {
8 AppData,
10 Cache,
12 Documents,
14 Temp,
16}
17
18impl VfsRoot {
19 pub fn as_str(&self) -> &'static str {
20 match self {
21 Self::AppData => "app_data",
22 Self::Cache => "cache",
23 Self::Documents => "documents",
24 Self::Temp => "temp",
25 }
26 }
27
28 pub fn parse(s: &str) -> Option<Self> {
29 s.parse().ok()
30 }
31}
32
33impl std::str::FromStr for VfsRoot {
34 type Err = ();
35
36 fn from_str(s: &str) -> Result<Self, Self::Err> {
37 match s.to_ascii_lowercase().as_str() {
38 "app_data" | "appdata" => Ok(Self::AppData),
39 "cache" => Ok(Self::Cache),
40 "documents" | "docs" => Ok(Self::Documents),
41 "temp" | "tmp" => Ok(Self::Temp),
42 _ => Err(()),
43 }
44 }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51pub struct VfsPath {
52 root: VfsRoot,
53 subpath: PathBuf,
54}
55
56impl VfsPath {
57 pub fn new(root: VfsRoot, subpath: impl AsRef<Path>) -> Self {
58 let sub_ref = subpath.as_ref();
59 let raw_str = sub_ref.to_string_lossy();
60 if crate::driver::is_windows_unc_device_namespace(&raw_str) {
61 return Self {
62 root,
63 subpath: sub_ref.to_path_buf(),
64 };
65 }
66 let clean = Self::sanitize_subpath(sub_ref);
67 Self {
68 root,
69 subpath: clean,
70 }
71 }
72
73 pub fn root(&self) -> VfsRoot {
75 self.root
76 }
77
78 pub fn subpath(&self) -> &Path {
80 &self.subpath
81 }
82
83 pub fn join(&self, path: impl AsRef<Path>) -> Self {
85 let path_ref = path.as_ref();
86 let raw_str = path_ref.to_string_lossy();
87 if crate::driver::is_windows_unc_device_namespace(&raw_str) {
88 return Self {
89 root: self.root,
90 subpath: self.subpath.join(path_ref),
91 };
92 }
93 let joined = self.subpath.join(path);
94 let clean = Self::sanitize_subpath(&joined);
95 Self {
96 root: self.root,
97 subpath: clean,
98 }
99 }
100
101 pub fn to_uri(&self) -> String {
103 let sub = self.subpath.to_string_lossy().replace('\\', "/");
104 let sub_clean = sub.trim_start_matches('/');
105 format!("vfs://{}/{}", self.root.as_str(), sub_clean)
106 }
107
108 pub fn has_traversal_escape(subpath: &str) -> bool {
110 let normalized = subpath.replace('\\', "/");
111 let mut depth: isize = 0;
112 for part in normalized.split('/') {
113 if part.is_empty() || part == "." {
114 continue;
115 } else if part == ".." {
116 depth -= 1;
117 if depth < 0 {
118 return true;
119 }
120 } else {
121 depth += 1;
122 }
123 }
124 false
125 }
126
127 pub fn try_new(root: VfsRoot, subpath: impl AsRef<Path>) -> Result<Self, FsError> {
129 let subpath_ref = subpath.as_ref();
130 let subpath_str = subpath_ref.to_string_lossy();
131 if Self::has_traversal_escape(&subpath_str) {
132 return Err(FsError::SecurityViolation(format!(
133 "Directory traversal escape detected in subpath: {}",
134 subpath_str
135 )));
136 }
137 Ok(Self::new(root, subpath_ref))
138 }
139
140 pub fn from_uri(uri: &str) -> Result<Self, FsError> {
142 let stripped = uri.strip_prefix("vfs://").ok_or_else(|| {
143 FsError::InvalidPath(format!("URI does not start with 'vfs://': {uri}"))
144 })?;
145
146 let mut parts = stripped.splitn(2, '/');
147 let root_str = parts.next().unwrap_or("");
148 let sub_str = parts.next().unwrap_or("");
149
150 let root = VfsRoot::parse(root_str)
151 .ok_or_else(|| FsError::InvalidPath(format!("Unknown VfsRoot in URI: {root_str}")))?;
152
153 if Self::has_traversal_escape(sub_str) {
154 return Err(FsError::SecurityViolation(format!(
155 "Directory traversal escape detected in URI: {uri}"
156 )));
157 }
158
159 Ok(Self::new(root, PathBuf::from(sub_str)))
160 }
161
162 fn sanitize_subpath(path: &Path) -> PathBuf {
164 let mut clean = PathBuf::new();
165 for comp in path.components() {
166 match comp {
167 Component::Normal(c) => {
168 let s = c.to_string_lossy();
169 if s.len() == 2
171 && s.ends_with(':')
172 && s.chars()
173 .next()
174 .map(|ch| ch.is_ascii_alphabetic())
175 .unwrap_or(false)
176 {
177 continue;
178 }
179 clean.push(c);
180 }
181 Component::CurDir => {}
182 Component::ParentDir => {
183 clean.pop();
185 }
186 Component::RootDir | Component::Prefix(_) => {
187 }
189 }
190 }
191 clean
192 }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct VfsMetadata {
198 pub is_file: bool,
199 pub is_dir: bool,
200 pub len: u64,
201 pub modified_timestamp_secs: u64,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum FsError {
207 NotFound(String),
208 PermissionDenied(String),
209 AlreadyExists(String),
210 InvalidPath(String),
211 IoError(String),
212 SecurityViolation(String),
213}
214
215impl std::fmt::Display for FsError {
216 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217 match self {
218 Self::NotFound(s) => write!(f, "File or directory not found: {s}"),
219 Self::PermissionDenied(s) => write!(f, "Permission denied: {s}"),
220 Self::AlreadyExists(s) => write!(f, "Already exists: {s}"),
221 Self::InvalidPath(s) => write!(f, "Invalid path: {s}"),
222 Self::IoError(s) => write!(f, "I/O error: {s}"),
223 Self::SecurityViolation(s) => write!(f, "Security violation: {s}"),
224 }
225 }
226}
227
228impl std::error::Error for FsError {}