1#![cfg_attr(not(windows), forbid(unsafe_code))]
13
14use std::path::{Path, PathBuf};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum CloudKind {
19 GoogleDriveFs,
21 OneDriveCfApi,
23 Dropbox,
25 Syncthing,
27 Nextcloud,
29}
30
31impl CloudKind {
32 pub fn as_str(self) -> &'static str {
33 match self {
34 Self::GoogleDriveFs => "google-drive-fs",
35 Self::OneDriveCfApi => "onedrive-cfapi",
36 Self::Dropbox => "dropbox",
37 Self::Syncthing => "syncthing",
38 Self::Nextcloud => "nextcloud",
39 }
40 }
41
42 pub fn catalog_id(self) -> &'static str {
43 match self {
44 Self::GoogleDriveFs | Self::Dropbox | Self::Syncthing | Self::Nextcloud => "FS-007",
45 Self::OneDriveCfApi => "WIN-003",
46 }
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct CloudDetection {
53 pub kind: CloudKind,
54 pub root: PathBuf,
55 pub detail: String,
56 pub claimed: bool,
58}
59
60impl CloudDetection {
61 pub fn advisory_note(&self) -> String {
62 format!(
63 "note: {} — detected {} at {} ({}); advisory only — do not Claim multi-device cloud-sync safety; prefer local disk for .git writers",
64 self.kind.catalog_id(),
65 self.kind.as_str(),
66 self.root.display(),
67 self.detail
68 )
69 }
70}
71
72pub fn detect_cloud_sync(path: &Path) -> Option<CloudDetection> {
74 let abs = canonicalize_lossy(path);
75 if let Some(d) = detect_drivefs(&abs) {
76 return Some(d);
77 }
78 if let Some(d) = detect_onedrive_root(&abs) {
79 return Some(d);
80 }
81 if let Some(d) = detect_marker_root(&abs, ".dropbox", CloudKind::Dropbox) {
82 return Some(d);
83 }
84 if let Some(d) = detect_marker_root(&abs, ".stfolder", CloudKind::Syncthing) {
85 return Some(d);
86 }
87 if let Some(d) = detect_marker_root(&abs, ".syncthing", CloudKind::Syncthing) {
88 return Some(d);
89 }
90 if let Some(d) = detect_marker_root(&abs, ".csync_journal.db", CloudKind::Nextcloud) {
92 return Some(d);
93 }
94 if let Some(d) = detect_marker_root(&abs, ".owncloudsync.log", CloudKind::Nextcloud) {
95 return Some(d);
96 }
97 None
98}
99
100pub fn is_onedrive_placeholder(path: &Path) -> Result<bool, HostFsError> {
105 #[cfg(windows)]
106 {
107 windows_impl::is_recall_on_data_access(path)
108 }
109 #[cfg(not(windows))]
110 {
111 let _ = path;
112 Ok(false)
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum LsmKind {
119 SelinuxEnforcing,
120 SelinuxPermissive,
121 ApparmorEnabled,
122}
123
124impl LsmKind {
125 pub fn as_str(self) -> &'static str {
126 match self {
127 Self::SelinuxEnforcing => "selinux-enforcing",
128 Self::SelinuxPermissive => "selinux-permissive",
129 Self::ApparmorEnabled => "apparmor-enabled",
130 }
131 }
132
133 pub fn catalog_id(self) -> &'static str {
134 "FS-014"
135 }
136}
137
138pub fn detect_lsm() -> Vec<LsmKind> {
140 let mut out = Vec::new();
141 if let Ok(v) = std::fs::read_to_string("/sys/fs/selinux/enforce") {
142 match v.trim() {
143 "1" => out.push(LsmKind::SelinuxEnforcing),
144 "0" => out.push(LsmKind::SelinuxPermissive),
145 _ => {}
146 }
147 }
148 if let Ok(v) = std::fs::read_to_string("/sys/module/apparmor/parameters/enabled") {
149 if v.trim().eq_ignore_ascii_case("Y") {
150 out.push(LsmKind::ApparmorEnabled);
151 }
152 }
153 out
154}
155
156pub fn refuse_sync_env_requested() -> bool {
161 matches!(
162 std::env::var("ARKS_HOST_ENV_REFUSE_SYNC").as_deref(),
163 Ok("1") | Ok("true") | Ok("TRUE") | Ok("yes") | Ok("YES")
164 )
165}
166
167pub fn git_under_sync_root(path: &Path) -> Option<CloudDetection> {
169 if let Some(d) = detect_cloud_sync(path) {
170 return Some(d);
171 }
172 let git = path.join(".git");
173 if git.exists() {
174 return detect_cloud_sync(&git);
175 }
176 None
177}
178
179pub fn probe_repo_path(path: &Path) -> ProbeReport {
181 let cloud = detect_cloud_sync(path).or_else(|| git_under_sync_root(path));
182 let placeholder = is_onedrive_placeholder(path).unwrap_or(false);
183 let lsm = detect_lsm();
184 ProbeReport {
185 path: path.to_path_buf(),
186 cloud,
187 onedrive_placeholder: placeholder,
188 lsm,
189 }
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct ProbeReport {
194 pub path: PathBuf,
195 pub cloud: Option<CloudDetection>,
196 pub onedrive_placeholder: bool,
197 pub lsm: Vec<LsmKind>,
198}
199
200impl ProbeReport {
201 pub fn notes(&self) -> Vec<String> {
202 let mut out = Vec::new();
203 if let Some(c) = &self.cloud {
204 out.push(c.advisory_note());
205 }
206 if self.onedrive_placeholder {
207 out.push(format!(
208 "note: WIN-003 — OneDrive/CfAPI placeholder at {} (RECALL_ON_DATA_ACCESS); hydrate before relying on lstat/checkout; detect-only (not Claimed hydration); DriveFS G: ≠ WIN-003",
209 self.path.display()
210 ));
211 out.push(
212 "note: WIN-003 — on hydrate fail expect clear PermissionDenied/ERROR_CLOUD_FILE_* honesty; arks does not implement Files On-Demand hydration"
213 .into(),
214 );
215 }
216 for l in &self.lsm {
217 out.push(format!(
218 "note: {} — detected {} on host; .lock rename EACCES/EPERM → clear PermissionDenied with LSM name; cannot bypass host policy inside arks",
219 l.catalog_id(),
220 l.as_str()
221 ));
222 }
223 out
224 }
225
226 pub fn is_advisory_hazard(&self) -> bool {
227 self.cloud.is_some() || self.onedrive_placeholder
228 }
229
230 pub fn should_refuse_sync(&self, refuse_requested: bool) -> bool {
232 refuse_requested && self.cloud.is_some()
233 }
234
235 pub fn errno_honesty_hint(&self) -> Option<String> {
236 if self.onedrive_placeholder {
237 return Some(
238 "WIN-003: placeholder I/O may surface PermissionDenied / cloud-file errno — hydrate externally; not Claimed"
239 .into(),
240 );
241 }
242 if !self.lsm.is_empty() {
243 let names: Vec<&str> = self.lsm.iter().map(|l| l.as_str()).collect();
244 return Some(format!(
245 "FS-014: PermissionDenied on .lock rename may be host LSM ({})",
246 names.join(",")
247 ));
248 }
249 None
250 }
251}
252
253#[derive(Debug, thiserror::Error, PartialEq, Eq)]
254pub enum HostFsError {
255 #[error("I/O: {0}")]
256 Io(String),
257}
258
259fn canonicalize_lossy(path: &Path) -> PathBuf {
260 path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
261}
262
263fn detect_drivefs(abs: &Path) -> Option<CloudDetection> {
264 #[cfg(windows)]
265 {
266 windows_impl::detect_google_drive_fs(abs)
267 }
268 #[cfg(not(windows))]
269 {
270 let _ = abs;
271 None
272 }
273}
274
275fn detect_onedrive_root(abs: &Path) -> Option<CloudDetection> {
276 for comp in abs.components() {
278 let s = comp.as_os_str().to_string_lossy();
279 if s.eq_ignore_ascii_case("OneDrive") || s.to_ascii_lowercase().starts_with("onedrive -") {
280 return Some(CloudDetection {
281 kind: CloudKind::OneDriveCfApi,
282 root: abs.to_path_buf(),
283 detail: "path component matches OneDrive".into(),
284 claimed: false,
285 });
286 }
287 }
288 None
289}
290
291fn detect_marker_root(abs: &Path, marker: &str, kind: CloudKind) -> Option<CloudDetection> {
292 let mut cur = Some(abs);
293 while let Some(dir) = cur {
294 if dir.join(marker).exists() {
295 return Some(CloudDetection {
296 kind,
297 root: dir.to_path_buf(),
298 detail: format!("found marker `{marker}`"),
299 claimed: false,
300 });
301 }
302 cur = dir.parent();
303 }
304 None
305}
306
307#[cfg(windows)]
308mod windows_impl {
309 use super::*;
310 use std::os::windows::ffi::OsStrExt;
311 use windows::Win32::Storage::FileSystem::{
312 FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, GetFileAttributesW,
313 };
314 use windows::core::PCWSTR;
315
316 pub(crate) fn is_recall_on_data_access(path: &Path) -> Result<bool, HostFsError> {
317 let wide: Vec<u16> = path
318 .as_os_str()
319 .encode_wide()
320 .chain(std::iter::once(0))
321 .collect();
322 let attrs = unsafe { GetFileAttributesW(PCWSTR(wide.as_ptr())) };
324 if attrs == u32::MAX {
325 return Err(HostFsError::Io(format!(
326 "GetFileAttributesW failed for {}",
327 path.display()
328 )));
329 }
330 Ok((attrs & FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS.0) != 0)
331 }
332
333 pub(crate) fn detect_google_drive_fs(abs: &Path) -> Option<CloudDetection> {
334 if !is_under_drive_letter(abs) {
337 return None;
338 }
339 let root = volume_root(abs);
340 let vol_name = volume_label(&root).unwrap_or_default();
341 if !vol_name.eq_ignore_ascii_case("Google Drive") {
342 return None;
343 }
344 let drivefs_alive = google_drive_fs_install_present();
345 Some(CloudDetection {
346 kind: CloudKind::GoogleDriveFs,
347 root,
348 detail: format!(
349 "volume_label={vol_name:?}; DriveFS_install={drivefs_alive}; advisory streaming/mirror substrate (≠ Claimed FS-007)"
350 ),
351 claimed: false,
352 })
353 }
354
355 fn is_under_drive_letter(abs: &Path) -> bool {
356 abs.components()
357 .next()
358 .map(|c| {
359 let s = c.as_os_str().to_string_lossy();
360 s.as_bytes().get(1) == Some(&b':')
361 })
362 .unwrap_or(false)
363 }
364
365 fn volume_root(abs: &Path) -> PathBuf {
366 abs.components()
367 .next()
368 .map(|c| {
369 PathBuf::from(format!(
370 "{}\\",
371 c.as_os_str().to_string_lossy().trim_end_matches('\\')
372 ))
373 })
374 .unwrap_or_else(|| PathBuf::from("\\"))
375 }
376
377 fn volume_label(root: &Path) -> Option<String> {
378 use windows::Win32::Storage::FileSystem::GetVolumeInformationW;
379 let wide: Vec<u16> = root
380 .as_os_str()
381 .encode_wide()
382 .chain(std::iter::once(0))
383 .collect();
384 let mut name = [0u16; 64];
385 let ok = unsafe {
386 GetVolumeInformationW(
387 PCWSTR(wide.as_ptr()),
388 Some(&mut name),
389 None,
390 None,
391 None,
392 None,
393 )
394 };
395 if ok.is_err() {
396 return None;
397 }
398 let nul = name.iter().position(|&c| c == 0).unwrap_or(name.len());
399 Some(String::from_utf16_lossy(&name[..nul]))
400 }
401
402 fn google_drive_fs_install_present() -> bool {
403 Path::new(r"C:\Program Files\Google\Drive File Stream").is_dir()
404 || std::env::var_os("LOCALAPPDATA")
405 .map(|p| PathBuf::from(p).join("Google").join("DriveFS").is_dir())
406 .unwrap_or(false)
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 #[test]
415 fn dropbox_marker_detection() {
416 let dir = tempfile_dir();
417 std::fs::create_dir_all(dir.join(".dropbox")).unwrap();
418 let child = dir.join("proj").join("file.txt");
419 std::fs::create_dir_all(child.parent().unwrap()).unwrap();
420 std::fs::write(&child, b"x").unwrap();
421 let d = detect_cloud_sync(&child).expect("dropbox");
422 assert_eq!(d.kind, CloudKind::Dropbox);
423 assert!(!d.claimed);
424 assert!(d.advisory_note().contains("FS-007"));
425 }
426
427 #[test]
428 fn syncthing_marker_detection() {
429 let dir = tempfile_dir();
430 std::fs::create_dir_all(dir.join(".stfolder")).unwrap();
431 let d = detect_cloud_sync(&dir.join("a")).expect("syncthing");
432 assert_eq!(d.kind, CloudKind::Syncthing);
433 }
434
435 #[test]
436 fn nextcloud_journal_marker_detection() {
437 let dir = tempfile_dir();
438 std::fs::write(dir.join(".csync_journal.db"), b"x").unwrap();
439 let d = detect_cloud_sync(&dir.join("proj")).expect("nextcloud");
440 assert_eq!(d.kind, CloudKind::Nextcloud);
441 assert!(!d.claimed);
442 assert!(d.advisory_note().contains("FS-007"));
443 }
444
445 #[test]
446 fn onedrive_path_component() {
447 let dir = tempfile_dir();
448 let od = dir.join("OneDrive").join("Documents");
449 std::fs::create_dir_all(&od).unwrap();
450 let d = detect_cloud_sync(&od).expect("onedrive path");
451 assert_eq!(d.kind, CloudKind::OneDriveCfApi);
452 assert!(d.advisory_note().contains("WIN-003"));
453 }
454
455 #[test]
456 fn placeholder_false_on_normal_temp() {
457 let dir = tempfile_dir();
458 let f = dir.join("normal.txt");
459 std::fs::write(&f, b"ok").unwrap();
460 assert!(!is_onedrive_placeholder(&f).unwrap());
461 }
462
463 #[test]
464 fn probe_report_notes_empty_on_local() {
465 let dir = tempfile_dir();
466 let r = probe_repo_path(&dir);
467 assert!(!r.is_advisory_hazard());
468 assert!(r.cloud.is_none());
470 assert!(!r.onedrive_placeholder);
471 }
472
473 #[test]
474 fn refuse_sync_only_when_requested_and_cloud() {
475 let dir = tempfile_dir();
476 std::fs::create_dir_all(dir.join(".dropbox")).unwrap();
477 let r = probe_repo_path(&dir);
478 assert!(r.is_advisory_hazard());
479 assert!(!r.should_refuse_sync(false));
480 assert!(r.should_refuse_sync(true));
481 }
482
483 #[test]
484 fn lsm_detect_does_not_panic() {
485 let _ = detect_lsm();
486 }
487
488 fn tempfile_dir() -> PathBuf {
489 let mut d = std::env::temp_dir();
490 d.push(format!("arks-hostfs-{}", std::process::id()));
491 d.push(format!("{}", uniq()));
492 std::fs::create_dir_all(&d).unwrap();
493 d
494 }
495
496 fn uniq() -> u64 {
497 use std::sync::atomic::{AtomicU64, Ordering};
498 static N: AtomicU64 = AtomicU64::new(1);
499 N.fetch_add(1, Ordering::Relaxed)
500 }
501}