1use std::collections::HashMap;
27use std::hash::{DefaultHasher, Hash, Hasher};
28use std::io;
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex, MutexGuard, mpsc};
31use std::thread;
32use std::time::{Duration, Instant};
33
34use crate::error::{CoreError, ErrorCode};
35use crate::fs::Fs;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
39#[cfg_attr(feature = "specta", derive(specta::Type))]
40#[serde(rename_all = "snake_case")]
41pub enum ReadOnlyKind {
42 Acl,
44 Attribute,
47 Owner,
49 Share,
52}
53
54impl ReadOnlyKind {
55 pub const fn as_str(self) -> &'static str {
56 match self {
57 ReadOnlyKind::Acl => "acl",
58 ReadOnlyKind::Attribute => "attribute",
59 ReadOnlyKind::Owner => "owner",
60 ReadOnlyKind::Share => "share",
61 }
62 }
63
64 pub const fn describe(self) -> &'static str {
66 match self {
67 ReadOnlyKind::Acl => "its permissions deny this account writing",
68 ReadOnlyKind::Attribute => "it is marked read only",
69 ReadOnlyKind::Owner => "another user owns it and this account may not write it",
70 ReadOnlyKind::Share => "it is on a read-only share or mount",
71 }
72 }
73}
74
75impl std::fmt::Display for ReadOnlyKind {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 f.write_str(self.as_str())
78 }
79}
80
81pub fn read_only_json<S: serde::Serializer>(
83 kind: &Option<ReadOnlyKind>,
84 serializer: S,
85) -> Result<S::Ok, S::Error> {
86 #[derive(serde::Serialize)]
87 struct ReadOnly {
88 kind: ReadOnlyKind,
89 }
90 serde::Serialize::serialize(&kind.map(|kind| ReadOnly { kind }), serializer)
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
95pub enum WriteAccess {
96 Writable,
97 ReadOnly(ReadOnlyKind),
98 Unknown,
101}
102
103impl WriteAccess {
104 pub const fn read_only(self) -> Option<ReadOnlyKind> {
105 match self {
106 WriteAccess::ReadOnly(kind) => Some(kind),
107 _ => None,
108 }
109 }
110}
111
112pub type WriteProbe = Arc<dyn Fn(&Path) -> WriteAccess + Send + Sync>;
116
117pub const PROBE_BUDGET: Duration = Duration::from_secs(2);
119
120pub fn probe(path: &Path) -> WriteAccess {
123 platform::probe(&crate::fs::long(path))
124}
125
126pub fn fingerprint(bytes: Option<&[u8]>) -> Option<u64> {
129 bytes.map(|bytes| {
130 let mut hasher = DefaultHasher::new();
131 bytes.hash(&mut hasher);
132 hasher.finish()
133 })
134}
135
136#[derive(Debug)]
141pub struct ProbeCache {
142 budget: Duration,
143 entries: Arc<Mutex<HashMap<PathBuf, Cached>>>,
144}
145
146#[derive(Debug, Clone, Copy)]
147enum Cached {
148 Done(Option<u64>, WriteAccess),
149 Running(Option<u64>),
150}
151
152impl Default for ProbeCache {
153 fn default() -> Self {
154 Self::with_budget(PROBE_BUDGET)
155 }
156}
157
158impl ProbeCache {
159 pub fn new() -> Self {
160 Self::default()
161 }
162
163 pub fn with_budget(budget: Duration) -> Self {
165 Self {
166 budget,
167 entries: Arc::default(),
168 }
169 }
170
171 pub fn clear(&self) {
175 lock(&self.entries).retain(|_, cached| matches!(cached, Cached::Running(_)));
176 }
177}
178
179fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
180 mutex
181 .lock()
182 .unwrap_or_else(std::sync::PoisonError::into_inner)
183}
184
185pub fn probe_files(
191 fs: &dyn Fs,
192 files: &[(PathBuf, Option<u64>)],
193 cache: Option<&ProbeCache>,
194) -> HashMap<PathBuf, WriteAccess> {
195 let mut out: HashMap<PathBuf, WriteAccess> = HashMap::new();
196 let Some(probe) = fs.write_probe() else {
197 for (path, _) in files {
198 out.insert(path.clone(), WriteAccess::Unknown);
199 }
200 return out;
201 };
202 let local;
203 let cache = match cache {
204 Some(cache) => cache,
205 None => {
206 local = ProbeCache::new();
207 &local
208 }
209 };
210 let (tx, rx) = mpsc::channel::<(PathBuf, WriteAccess)>();
211 let mut running: Vec<(PathBuf, thread::JoinHandle<()>)> = Vec::new();
212 {
213 let mut entries = lock(&cache.entries);
214 for (path, print) in files {
215 if out.contains_key(path) || running.iter().any(|(p, _)| p == path) {
216 continue;
217 }
218 match entries.get(path) {
219 Some(Cached::Done(seen, access)) if seen == print => {
220 out.insert(path.clone(), *access);
221 continue;
222 }
223 Some(Cached::Running(seen)) if seen == print => {
224 out.insert(path.clone(), WriteAccess::Unknown);
225 continue;
226 }
227 _ => {}
228 }
229 entries.insert(path.clone(), Cached::Running(*print));
230 let (probe, tx, shared) = (probe.clone(), tx.clone(), cache.entries.clone());
231 let (owned, print) = (path.clone(), *print);
232 let spawned = thread::Builder::new()
233 .name("surjection-probe".to_owned())
234 .spawn(move || {
235 let access = probe(&owned);
236 {
237 let mut entries = lock(&shared);
238 if matches!(entries.get(&owned), Some(Cached::Running(seen)) if *seen == print)
239 {
240 entries.insert(owned.clone(), Cached::Done(print, access));
241 }
242 }
243 let _ = tx.send((owned, access));
244 });
245 match spawned {
246 Ok(handle) => running.push((path.clone(), handle)),
247 Err(_) => {
248 entries.remove(path);
249 out.insert(path.clone(), WriteAccess::Unknown);
250 }
251 }
252 }
253 }
254 drop(tx);
255 let deadline = Instant::now() + cache.budget;
256 let mut left = running.len();
257 while left > 0 {
258 let now = Instant::now();
259 if now >= deadline {
260 break;
261 }
262 match rx.recv_timeout(deadline - now) {
263 Ok((path, access)) => {
264 out.insert(path, access);
265 left -= 1;
266 }
267 Err(_) => break,
268 }
269 }
270 for (path, handle) in running {
271 if out.contains_key(&path) {
272 continue;
273 }
274 if handle.is_finished()
277 && let Err(panic) = handle.join()
278 {
279 lock(&cache.entries).remove(&path);
280 std::panic::resume_unwind(panic);
281 }
282 out.insert(path, WriteAccess::Unknown);
283 }
284 out
285}
286
287pub fn probe_path(fs: &dyn Fs, path: &Path) -> WriteAccess {
290 probe_files(fs, &[(path.to_path_buf(), None)], None)
291 .remove(path)
292 .unwrap_or(WriteAccess::Unknown)
293}
294
295pub fn denied(fs: &dyn Fs, err: &io::Error, path: &Path) -> Option<ReadOnlyKind> {
303 if cfg!(windows) && matches!(err.raw_os_error(), Some(32 | 33)) {
304 return None;
305 }
306 if err.kind() == io::ErrorKind::ReadOnlyFilesystem
307 || (cfg!(windows) && matches!(err.raw_os_error(), Some(19 | 65)))
308 {
309 return Some(ReadOnlyKind::Share);
310 }
311 if err.kind() != io::ErrorKind::PermissionDenied {
312 return None;
313 }
314 let fallback = if is_unc(path) {
315 ReadOnlyKind::Share
316 } else {
317 ReadOnlyKind::Acl
318 };
319 match fs.write_probe().map(|probe| probe(path)) {
320 Some(WriteAccess::ReadOnly(kind)) => Some(kind),
321 Some(WriteAccess::Writable) => None,
322 Some(WriteAccess::Unknown) | None => Some(fallback),
323 }
324}
325
326pub fn read_only_target(kind: ReadOnlyKind, path: &Path) -> CoreError {
328 CoreError::new(
329 ErrorCode::ReadOnlyTarget,
330 format!(
331 "this account cannot write here ({}); Surjection leaves it as it is",
332 kind.describe()
333 ),
334 )
335 .with_path(path)
336 .with_read_only(kind)
337}
338
339pub fn write_error(fs: &dyn Fs, what: &str, path: &Path, err: &io::Error) -> CoreError {
342 match denied(fs, err, path) {
343 Some(kind) => read_only_target(kind, path),
344 None => CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path),
345 }
346}
347
348fn is_unc(path: &Path) -> bool {
350 if !cfg!(windows) {
351 return false;
352 }
353 let text = path.as_os_str().to_string_lossy();
354 text.starts_with(r"\\?\UNC\")
355 || (text.starts_with(r"\\") && !text.starts_with(r"\\?\") && !text.starts_with(r"\\.\"))
356}
357
358fn existing_parent(path: &Path) -> Option<(&Path, bool)> {
361 let mut direct = true;
362 let mut at = path.parent();
363 while let Some(dir) = at {
364 if dir.is_dir() {
365 return Some((dir, direct));
366 }
367 if dir.exists() {
368 return None;
369 }
370 direct = false;
371 at = dir.parent();
372 }
373 None
374}
375
376#[cfg(windows)]
377mod platform {
378 use std::fs::OpenOptions;
379 use std::io;
380 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
381 use std::path::Path;
382
383 use super::{ReadOnlyKind, WriteAccess, existing_parent, is_unc};
384
385 const FILE_ATTRIBUTE_READONLY: u32 = 0x1;
386 const FILE_ADD_FILE: u32 = 0x2;
387 const FILE_ADD_SUBDIRECTORY: u32 = 0x4;
388 const FILE_DELETE_CHILD: u32 = 0x40;
389 const DELETE: u32 = 0x0001_0000;
390 const GENERIC_WRITE: u32 = 0x4000_0000;
391 const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
392
393 pub fn probe(path: &Path) -> WriteAccess {
394 match std::fs::metadata(path) {
395 Ok(meta) if meta.is_dir() => open_dir(
397 path,
398 FILE_ADD_FILE | FILE_ADD_SUBDIRECTORY | FILE_DELETE_CHILD,
399 ),
400 Ok(meta) => {
401 if meta.file_attributes() & FILE_ATTRIBUTE_READONLY != 0 {
402 return WriteAccess::ReadOnly(ReadOnlyKind::Attribute);
403 }
404 if let Err(err) = OpenOptions::new()
412 .access_mode(GENERIC_WRITE | DELETE)
413 .open(path)
414 {
415 return classify(&err, path);
416 }
417 match path.parent() {
419 Some(dir) => open_dir(dir, FILE_ADD_FILE),
420 None => WriteAccess::Writable,
421 }
422 }
423 Err(err) if err.kind() == io::ErrorKind::NotFound => match existing_parent(path) {
424 Some((dir, true)) => open_dir(dir, FILE_ADD_FILE),
425 Some((dir, false)) => open_dir(dir, FILE_ADD_SUBDIRECTORY),
426 None => WriteAccess::Unknown,
427 },
428 Err(_) => WriteAccess::Unknown,
429 }
430 }
431
432 fn open_dir(dir: &Path, access: u32) -> WriteAccess {
435 match OpenOptions::new()
436 .access_mode(access)
437 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
438 .open(dir)
439 {
440 Ok(_) => WriteAccess::Writable,
441 Err(err) => classify(&err, dir),
442 }
443 }
444
445 fn classify(err: &io::Error, path: &Path) -> WriteAccess {
446 match err.raw_os_error() {
447 Some(5) if is_unc(path) => WriteAccess::ReadOnly(ReadOnlyKind::Share),
449 Some(5) => WriteAccess::ReadOnly(ReadOnlyKind::Acl),
450 Some(19 | 65) => WriteAccess::ReadOnly(ReadOnlyKind::Share),
452 _ if err.kind() == io::ErrorKind::ReadOnlyFilesystem => {
453 WriteAccess::ReadOnly(ReadOnlyKind::Share)
454 }
455 _ => WriteAccess::Unknown,
457 }
458 }
459}
460
461#[cfg(unix)]
462mod platform {
463 use std::fs::Metadata;
464 use std::io;
465 use std::os::unix::fs::MetadataExt;
466 use std::path::Path;
467
468 use rustix::fs::{Access, access};
469 use rustix::io::Errno;
470
471 use super::{ReadOnlyKind, WriteAccess, existing_parent};
472
473 pub fn probe(path: &Path) -> WriteAccess {
474 match std::fs::metadata(path) {
476 Ok(meta) if meta.is_dir() => check(path, &meta, Access::WRITE_OK | Access::EXEC_OK),
477 Ok(meta) => {
478 let file = check(path, &meta, Access::WRITE_OK);
479 if file != WriteAccess::Writable {
480 return file;
481 }
482 match path.parent() {
484 Some(dir) => folder(dir),
485 None => WriteAccess::Writable,
486 }
487 }
488 Err(err) if err.kind() == io::ErrorKind::NotFound => match existing_parent(path) {
489 Some((dir, _)) => folder(dir),
490 None => WriteAccess::Unknown,
491 },
492 Err(_) => WriteAccess::Unknown,
493 }
494 }
495
496 fn folder(dir: &Path) -> WriteAccess {
497 match std::fs::metadata(dir) {
498 Ok(meta) => check(dir, &meta, Access::WRITE_OK | Access::EXEC_OK),
499 Err(_) => WriteAccess::Unknown,
500 }
501 }
502
503 fn check(path: &Path, meta: &Metadata, mode: Access) -> WriteAccess {
504 match access(path, mode) {
505 Ok(()) => WriteAccess::Writable,
506 Err(Errno::ROFS) => WriteAccess::ReadOnly(ReadOnlyKind::Share),
507 Err(Errno::ACCESS | Errno::PERM) => WriteAccess::ReadOnly(kind(meta)),
508 Err(_) => WriteAccess::Unknown,
509 }
510 }
511
512 fn kind(meta: &Metadata) -> ReadOnlyKind {
514 let mode = meta.mode();
515 if meta.uid() == rustix::process::geteuid().as_raw() {
516 if mode & 0o200 == 0 {
517 ReadOnlyKind::Attribute
518 } else {
519 ReadOnlyKind::Acl
520 }
521 } else if mode & 0o022 == 0 {
522 ReadOnlyKind::Owner
523 } else {
524 ReadOnlyKind::Acl
525 }
526 }
527}
528
529#[cfg(not(any(windows, unix)))]
530mod platform {
531 use std::path::Path;
532
533 use super::WriteAccess;
534
535 pub fn probe(_path: &Path) -> WriteAccess {
536 WriteAccess::Unknown
537 }
538}