1use std::path::PathBuf;
4
5pub struct PathSanitizer;
8
9impl PathSanitizer {
10 pub fn parse_drop_payload(payload: &str) -> Vec<PathBuf> {
13 let mut paths = Vec::new();
14
15 for line in payload.lines() {
16 let trimmed = line.trim();
17 if trimmed.is_empty() {
18 continue;
19 }
20
21 let path_str = Self::strip_file_uri(trimmed);
22
23 let decoded = Self::percent_decode_bytes(path_str);
27 let cleaned = Self::unescape_shell_bytes(decoded);
28 if !cleaned.is_empty() {
29 paths.push(Self::bytes_to_pathbuf(cleaned));
30 }
31 }
32
33 paths
34 }
35
36 pub fn looks_like_drop(payload: &str) -> bool {
48 let mut saw_line = false;
49 for line in payload.lines() {
50 let t = line.trim();
51 if t.is_empty() {
52 continue;
53 }
54 saw_line = true;
55 let is_uri = t.starts_with("file://");
56 let is_path = t.starts_with('/')
57 || t.starts_with("~/")
58 || t.starts_with("./")
59 || t.starts_with("../")
60 || Self::looks_like_windows_path(t);
61 if !(is_uri || is_path) {
62 return false;
63 }
64 }
65 saw_line
66 }
67
68 fn looks_like_windows_path(s: &str) -> bool {
70 let b = s.as_bytes();
71 b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\')
72 }
73
74 fn strip_file_uri(input: &str) -> &str {
78 let Some(rest) = input.strip_prefix("file://") else {
79 return input;
80 };
81 let path = match rest.find('/') {
82 Some(0) => rest, Some(slash) => {
84 if rest[..slash].eq_ignore_ascii_case("localhost") {
85 &rest[slash..]
86 } else {
87 rest
88 }
89 }
90 None => rest,
91 };
92 #[cfg(windows)]
93 let path = path.strip_prefix('/').unwrap_or(path); path
95 }
96
97 pub fn percent_decode(input: &str) -> String {
105 String::from_utf8(Self::percent_decode_bytes(input)).unwrap_or_else(|_| input.to_string())
106 }
107
108 pub fn percent_decode_bytes(input: &str) -> Vec<u8> {
110 let bytes = input.as_bytes();
111 let mut out = Vec::with_capacity(bytes.len());
112 let mut i = 0;
113
114 while i < bytes.len() {
115 if bytes[i] == b'%'
116 && i + 2 < bytes.len()
117 && let (Some(h1), Some(h2)) = ((bytes[i + 1] as char).to_digit(16), (bytes[i + 2] as char).to_digit(16))
118 {
119 out.push(((h1 << 4) | h2) as u8);
120 i += 3;
121 continue;
122 }
123 out.push(bytes[i]);
124 i += 1;
125 }
126
127 out
128 }
129
130 pub fn unescape_shell_path(input: &str) -> String {
132 input.replace("\\ ", " ").replace("\\\\", "\\")
133 }
134
135 fn unescape_shell_bytes(input: Vec<u8>) -> Vec<u8> {
139 let mut out = Vec::with_capacity(input.len());
140 let mut i = 0;
141 while i < input.len() {
142 if input[i] == b'\\' && i + 1 < input.len() {
143 match input[i + 1] {
144 b' ' => {
145 out.push(b' ');
146 i += 2;
147 continue;
148 }
149 b'\\' => {
150 out.push(b'\\');
151 i += 2;
152 continue;
153 }
154 _ => {}
155 }
156 }
157 out.push(input[i]);
158 i += 1;
159 }
160 out
161 }
162
163 #[cfg(unix)]
164 fn bytes_to_pathbuf(bytes: Vec<u8>) -> PathBuf {
165 use std::os::unix::ffi::OsStringExt;
166 PathBuf::from(std::ffi::OsString::from_vec(bytes))
167 }
168
169 #[cfg(not(unix))]
170 fn bytes_to_pathbuf(bytes: Vec<u8>) -> PathBuf {
171 PathBuf::from(String::from_utf8_lossy(&bytes).into_owned())
172 }
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn test_file_uri_host_stripping() {
181 assert_eq!(
182 PathSanitizer::parse_drop_payload("file:///home/demon/a.txt"),
183 vec![PathBuf::from("/home/demon/a.txt")]
184 );
185 assert_eq!(
187 PathSanitizer::parse_drop_payload("file://localhost/home/demon/a.txt"),
188 vec![PathBuf::from("/home/demon/a.txt")]
189 );
190 assert_eq!(
192 PathSanitizer::parse_drop_payload("/tmp/plain path"),
193 vec![PathBuf::from("/tmp/plain path")]
194 );
195 }
196
197 #[test]
198 fn test_percent_and_shell_decode() {
199 assert_eq!(
200 PathSanitizer::parse_drop_payload("file:///home/a%20b/c%2Fd"),
201 vec![PathBuf::from("/home/a b/c/d")]
202 );
203 assert_eq!(
204 PathSanitizer::parse_drop_payload("/home/a\\ b"),
205 vec![PathBuf::from("/home/a b")]
206 );
207 }
208
209 #[test]
210 fn test_looks_like_drop_classifies_payloads() {
211 assert!(PathSanitizer::looks_like_drop("file:///home/demon/a.txt"));
213 assert!(PathSanitizer::looks_like_drop("/tmp/a.txt\n/tmp/b.txt"));
214 assert!(PathSanitizer::looks_like_drop("~/notes.md"));
215 assert!(PathSanitizer::looks_like_drop("./rel/path"));
216 assert!(PathSanitizer::looks_like_drop("C:\\Users\\me\\f.txt"));
217
218 assert!(!PathSanitizer::looks_like_drop("hello world"));
220 assert!(!PathSanitizer::looks_like_drop("fn main() { println!(\"hi\"); }"));
221 assert!(!PathSanitizer::looks_like_drop("/tmp/ok.txt\nbut this line is prose"));
222 assert!(!PathSanitizer::looks_like_drop("")); assert!(!PathSanitizer::looks_like_drop(" \n ")); }
225
226 #[cfg(unix)]
227 #[test]
228 fn test_non_utf8_path_preserved() {
229 use std::os::unix::ffi::OsStrExt;
230 let paths = PathSanitizer::parse_drop_payload("file:///tmp/%FFname");
232 assert_eq!(paths.len(), 1);
233 assert!(paths[0].as_os_str().as_bytes().contains(&0xFF));
234 }
235}