1use std::collections::BTreeMap;
71use std::io::Write as _;
72use std::path::{Path, PathBuf};
73use std::process::{Command, Stdio};
74use std::time::{Duration, Instant};
75
76use lean_ctx_protocol::cloud::gate::{LockedChange, under_locked};
77use sha2::{Digest as _, Sha256};
78
79use super::GateError;
80
81pub(super) const CARGO_CONFIGS: [&str; 2] = [".cargo/config", ".cargo/config.toml"];
83
84#[cfg(test)]
87pub(super) fn exe(name: &str) -> String {
88 format!("{name}{}", std::env::consts::EXE_SUFFIX)
89}
90
91#[cfg(not(windows))]
95pub(super) fn system_dirs() -> Vec<PathBuf> {
96 ["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin", "/bin"]
97 .iter()
98 .map(PathBuf::from)
99 .collect()
100}
101
102#[cfg(windows)]
107pub(super) fn system_dirs() -> Vec<PathBuf> {
108 let mut dirs = Vec::new();
109 if let Some(windows) = win::windows_dir() {
110 let system32 = windows.join("System32");
111 dirs.extend([
112 system32.clone(),
113 windows,
114 system32.join("Wbem"),
115 system32.join("WindowsPowerShell").join("v1.0"),
116 ]);
117 }
118 if let Some(pf) = win::program_files() {
119 dirs.push(pf.join("Git").join("cmd"));
120 }
121 dirs
122}
123
124pub(super) fn system_path() -> std::ffi::OsString {
126 std::env::join_paths(system_dirs()).unwrap_or_default()
127}
128
129pub(super) fn shell() -> Result<PathBuf, GateError> {
132 #[cfg(windows)]
133 {
134 let sh = win::program_files()
135 .map(|pf| pf.join("Git").join("bin").join("sh.exe"))
136 .filter(|sh| sh.is_file())
137 .ok_or_else(|| {
138 GateError::Check(
139 "the gate runs its commands in Git for Windows' sh (Program Files\\Git\\bin\\sh.exe), which is missing".into(),
140 )
141 })?;
142 Ok(sh)
143 }
144 #[cfg(not(windows))]
145 {
146 Ok(PathBuf::from("/bin/sh"))
147 }
148}
149
150#[cfg(windows)]
153mod win {
154 use std::ffi::{OsString, c_void};
155 use std::os::windows::ffi::OsStringExt as _;
156 use std::path::PathBuf;
157
158 #[repr(C)]
159 struct Guid {
160 data1: u32,
161 data2: u16,
162 data3: u16,
163 data4: [u8; 8],
164 }
165
166 const FOLDERID_PROGRAM_FILES: Guid = Guid {
168 data1: 0x905E_63B6,
169 data2: 0xC1BF,
170 data3: 0x494E,
171 data4: [0xB2, 0x9C, 0x65, 0xB7, 0x32, 0xD3, 0xD2, 0x1A],
172 };
173
174 const FOLDERID_PROGRAM_DATA: Guid = Guid {
176 data1: 0x62AB_5D82,
177 data2: 0xFDC1,
178 data3: 0x4DC3,
179 data4: [0xA9, 0xDD, 0x07, 0x0D, 0x1D, 0x49, 0x5D, 0x97],
180 };
181
182 #[repr(C)]
183 #[derive(Default)]
184 struct BasicLimits {
185 per_process_user_time_limit: i64,
186 per_job_user_time_limit: i64,
187 limit_flags: u32,
188 minimum_working_set_size: usize,
189 maximum_working_set_size: usize,
190 active_process_limit: u32,
191 affinity: usize,
192 priority_class: u32,
193 scheduling_class: u32,
194 }
195
196 #[repr(C)]
197 #[derive(Default)]
198 struct IoCounters {
199 counts: [u64; 6],
200 }
201
202 #[repr(C)]
204 #[derive(Default)]
205 struct ExtendedLimits {
206 basic: BasicLimits,
207 io: IoCounters,
208 process_memory_limit: usize,
209 job_memory_limit: usize,
210 peak_process_memory_used: usize,
211 peak_job_memory_used: usize,
212 }
213
214 const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: u32 = 9;
215 const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x2000;
216
217 #[link(name = "kernel32")]
218 unsafe extern "system" {
219 fn GetSystemWindowsDirectoryW(buffer: *mut u16, size: u32) -> u32;
220 fn CreateJobObjectW(attributes: *mut c_void, name: *const u16) -> *mut c_void;
221 fn SetInformationJobObject(
222 job: *mut c_void,
223 class: u32,
224 info: *const c_void,
225 length: u32,
226 ) -> i32;
227 fn AssignProcessToJobObject(job: *mut c_void, process: *mut c_void) -> i32;
228 fn TerminateJobObject(job: *mut c_void, exit_code: u32) -> i32;
229 fn CloseHandle(handle: *mut c_void) -> i32;
230 }
231
232 #[link(name = "ntdll")]
233 unsafe extern "system" {
234 fn NtResumeProcess(process: *mut c_void) -> i32;
235 }
236
237 pub(super) const CREATE_SUSPENDED: u32 = 0x0000_0004;
240
241 #[link(name = "shell32")]
242 unsafe extern "system" {
243 fn SHGetKnownFolderPath(
244 id: *const Guid,
245 flags: u32,
246 token: *mut c_void,
247 path: *mut *mut u16,
248 ) -> i32;
249 }
250
251 #[link(name = "ole32")]
252 unsafe extern "system" {
253 fn CoTaskMemFree(memory: *mut c_void);
254 }
255
256 pub(super) fn windows_dir() -> Option<PathBuf> {
258 let mut buf = vec![0u16; 1024];
259 let len = u32::try_from(buf.len()).ok()?;
260 let n = unsafe { GetSystemWindowsDirectoryW(buf.as_mut_ptr(), len) };
262 let n = usize::try_from(n).ok()?;
263 (n > 0 && n < buf.len()).then(|| PathBuf::from(OsString::from_wide(&buf[..n])))
264 }
265
266 pub(super) fn program_files() -> Option<PathBuf> {
268 known_folder(&FOLDERID_PROGRAM_FILES)
269 }
270
271 pub(super) fn program_data() -> Option<PathBuf> {
275 known_folder(&FOLDERID_PROGRAM_DATA)
276 }
277
278 fn known_folder(id: &Guid) -> Option<PathBuf> {
279 let mut raw: *mut u16 = std::ptr::null_mut();
280 let hr = unsafe {
283 SHGetKnownFolderPath(
284 std::ptr::from_ref(id),
285 0,
286 std::ptr::null_mut(),
287 &raw mut raw,
288 )
289 };
290 let path = (hr == 0 && !raw.is_null()).then(|| {
291 let mut len = 0usize;
292 unsafe {
294 while *raw.add(len) != 0 {
295 len += 1;
296 }
297 PathBuf::from(OsString::from_wide(std::slice::from_raw_parts(raw, len)))
298 }
299 });
300 unsafe { CoTaskMemFree(raw.cast()) };
302 path
303 }
304
305 pub(super) struct Job(*mut c_void);
309
310 impl Job {
311 pub(super) fn new() -> Option<Self> {
312 let handle = unsafe { CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()) };
314 if handle.is_null() {
315 return None;
316 }
317 let job = Self(handle);
318 let mut limits = ExtendedLimits::default();
319 limits.basic.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
320 let size = u32::try_from(std::mem::size_of::<ExtendedLimits>()).ok()?;
321 let ok = unsafe {
323 SetInformationJobObject(
324 job.0,
325 JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
326 (&raw const limits).cast(),
327 size,
328 )
329 };
330 (ok != 0).then_some(job)
331 }
332
333 pub(super) fn assign_and_resume(&self, child: &std::process::Child) -> bool {
337 use std::os::windows::io::AsRawHandle as _;
338 let process = child.as_raw_handle().cast();
339 if unsafe { AssignProcessToJobObject(self.0, process) } == 0 {
341 return false;
342 }
343 unsafe { NtResumeProcess(process) == 0 }
346 }
347
348 pub(super) fn terminate(&self) {
350 unsafe {
352 TerminateJobObject(self.0, 1);
353 }
354 }
355 }
356
357 impl Drop for Job {
358 fn drop(&mut self) {
359 unsafe {
362 CloseHandle(self.0);
363 }
364 }
365 }
366}
367
368#[derive(Debug, Clone, PartialEq, Eq)]
372pub struct GateDirs {
373 pub work: PathBuf,
374 pub runs: PathBuf,
375}
376
377impl GateDirs {
378 #[must_use]
380 pub fn for_instance(data_dir: &Path) -> Self {
381 let work = data_dir.join("g6");
382 Self {
383 work,
384 runs: default_runs(),
385 }
386 }
387}
388
389fn default_runs() -> PathBuf {
397 #[cfg(unix)]
398 {
399 use std::os::unix::fs::MetadataExt as _;
400 let uid = unsafe { libc::getuid() };
402 let run = PathBuf::from(format!("/run/user/{uid}"));
403 if std::fs::symlink_metadata(&run).is_ok_and(|m| m.is_dir() && m.uid() == uid) {
404 return run;
405 }
406 }
407 #[cfg(windows)]
408 {
409 dirs::data_local_dir().map_or_else(std::env::temp_dir, |local| local.join("Temp"))
412 }
413 #[cfg(not(windows))]
414 {
415 std::fs::canonicalize("/tmp").unwrap_or_else(|_| PathBuf::from("/tmp"))
416 }
417}
418
419pub(super) fn resolved(path: &Path) -> std::io::Result<PathBuf> {
422 std::fs::canonicalize(path).map(lean_ctx::core::pathutil::strip_verbatim)
423}
424
425#[cfg(unix)]
426fn private_mode(dir: &Path) -> Result<(), GateError> {
427 use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
428 let meta = std::fs::symlink_metadata(dir)
429 .map_err(|e| GateError::Check(format!("{}: {e}", dir.display())))?;
430 let uid = unsafe { libc::getuid() };
432 if meta.file_type().is_symlink() || !meta.is_dir() || meta.uid() != uid {
433 return Err(GateError::Check(format!(
434 "{} is no directory of this user; the gate refuses to work in it",
435 dir.display()
436 )));
437 }
438 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
439 .map_err(|e| GateError::Check(format!("{}: {e}", dir.display())))
440}
441
442#[cfg(not(unix))]
443fn private_mode(_dir: &Path) -> Result<(), GateError> {
444 Ok(())
445}
446
447pub(super) fn make_private_dir(dir: &Path) -> Result<(), GateError> {
449 std::fs::create_dir_all(dir)
450 .map_err(|e| GateError::Check(format!("the gate's directory {}: {e}", dir.display())))?;
451 private_mode(dir)
452}
453
454pub(super) fn private_dir(work: &Path) -> Result<tempfile::TempDir, GateError> {
457 make_private_dir(work)?;
458 let work = resolved(work).map_err(|e| GateError::Check(format!("the gate's work dir: {e}")))?;
461 tempfile::Builder::new()
462 .prefix("g6-")
463 .tempdir_in(&work)
464 .map_err(|e| GateError::Check(format!("a fresh directory: {e}")))
465}
466
467pub(super) fn cargo_run_dir(runs: &Path) -> Result<tempfile::TempDir, GateError> {
472 match std::fs::symlink_metadata(runs) {
473 Ok(meta) if meta.is_dir() => {}
474 Ok(_) => {
475 return Err(GateError::Check(format!(
476 "{} is no directory; the gate refuses to run in it",
477 runs.display()
478 )));
479 }
480 Err(_) => make_private_dir(runs)?,
481 }
482 let canonical =
483 resolved(runs).map_err(|e| GateError::Check(format!("the gate's run directory: {e}")))?;
484 for dir in canonical.ancestors() {
485 for name in CARGO_CONFIGS {
486 let file = dir.join(Path::new(name).components().collect::<PathBuf>());
487 if std::fs::symlink_metadata(&file).is_ok() {
488 return Err(GateError::Check(format!(
489 "{} lies above the gate's run directory, and cargo would read it in the rerun; the gate refuses to run under it",
490 file.display()
491 )));
492 }
493 }
494 }
495 tempfile::Builder::new()
497 .prefix("lean-ctx-g6-run-")
498 .tempdir_in(&canonical)
499 .map_err(|e| GateError::Check(format!("a fresh directory: {e}")))
500}
501
502#[cfg(unix)]
504pub(super) fn user_home() -> Result<PathBuf, GateError> {
505 use std::ffi::{CStr, OsStr};
506 use std::os::unix::ffi::OsStrExt as _;
507 let mut buf = vec![0 as libc::c_char; 16 * 1024];
508 let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
510 let mut found: *mut libc::passwd = std::ptr::null_mut();
511 let rc = unsafe {
514 libc::getpwuid_r(
515 libc::getuid(),
516 &raw mut pwd,
517 buf.as_mut_ptr(),
518 buf.len(),
519 &raw mut found,
520 )
521 };
522 if rc != 0 || found.is_null() || pwd.pw_dir.is_null() {
523 return Err(GateError::Check(
524 "this user has no passwd entry, so the gate cannot tell its home".into(),
525 ));
526 }
527 let dir = unsafe { CStr::from_ptr(pwd.pw_dir) };
529 let home = PathBuf::from(OsStr::from_bytes(dir.to_bytes()));
530 if !home.is_absolute() {
531 return Err(GateError::Check(
532 "this user's passwd home is not absolute".into(),
533 ));
534 }
535 Ok(home)
536}
537
538#[cfg(not(unix))]
541pub(super) fn user_home() -> Result<PathBuf, GateError> {
542 dirs::home_dir()
543 .filter(|home| home.is_absolute())
544 .ok_or_else(|| GateError::Check("this user has no profile directory".into()))
545}
546
547pub(super) fn toolchain_dirs(
552 home: &Path,
553 cargo_home: Option<&std::ffi::OsStr>,
554 rustup_home: Option<&std::ffi::OsStr>,
555) -> Result<(PathBuf, PathBuf), GateError> {
556 let fixed = (home.join(".cargo"), home.join(".rustup"));
557 let same = |given: &Path, fixed: &Path| {
558 given == fixed
559 || std::fs::canonicalize(given)
560 .is_ok_and(|g| std::fs::canonicalize(fixed).ok().as_ref() == Some(&g))
561 };
562 for (name, given, fixed) in [
563 ("CARGO_HOME", cargo_home, &fixed.0),
564 ("RUSTUP_HOME", rustup_home, &fixed.1),
565 ] {
566 if let Some(given) = given.filter(|g| !g.is_empty())
567 && !same(Path::new(given), fixed)
568 {
569 return Err(GateError::Check(format!(
570 "{name} is {}, not {}; the gate runs only rustup's toolchain of this user's home, so it refuses the run",
571 Path::new(given).display(),
572 fixed.display()
573 )));
574 }
575 }
576 Ok(fixed)
577}
578
579#[cfg(not(test))]
582fn run_toolchain(home: &Path) -> Result<(PathBuf, PathBuf), GateError> {
583 toolchain_dirs(
584 home,
585 std::env::var_os("CARGO_HOME").as_deref(),
586 std::env::var_os("RUSTUP_HOME").as_deref(),
587 )
588}
589
590#[cfg(test)]
597fn run_toolchain(home: &Path) -> Result<(PathBuf, PathBuf), GateError> {
598 if home.join(".cargo").join("bin").join(exe("cargo")).is_file() {
599 return toolchain_dirs(
600 home,
601 std::env::var_os("CARGO_HOME").as_deref(),
602 std::env::var_os("RUSTUP_HOME").as_deref(),
603 );
604 }
605 let path = std::env::var_os("PATH").unwrap_or_default();
606 let cargo_dir = std::env::split_paths(&path)
607 .find(|dir| dir.is_absolute() && dir.join(exe("cargo")).is_file())
608 .and_then(|bin| bin.parent().map(Path::to_path_buf))
609 .ok_or_else(|| GateError::Check("no cargo for the gate's test runs".into()))?;
610 let rustup = std::env::var_os("RUSTUP_HOME")
611 .filter(|v| !v.is_empty())
612 .map_or_else(|| home.join(".rustup"), PathBuf::from);
613 Ok((cargo_dir, rustup))
614}
615
616pub(super) fn run_env(
625 scratch: &Path,
626 work: &Path,
627) -> Result<Vec<(String, std::ffi::OsString)>, GateError> {
628 let home = user_home()?;
629 let (rustup_cargo, rustup) = run_toolchain(&home)?;
630 make_private_dir(work)?;
631 let work = resolved(work).map_err(|e| GateError::Check(format!("the gate's work dir: {e}")))?;
632 let cargo_home = work.join("cargo-home");
633 make_private_dir(&cargo_home)?;
634 for name in ["config", "config.toml", "credentials", "credentials.toml"] {
635 let file = cargo_home.join(name);
636 if std::fs::symlink_metadata(&file).is_ok() {
637 return Err(GateError::Check(format!(
638 "{} is in the gate's CARGO_HOME, which the gate never writes; refused",
639 file.display()
640 )));
641 }
642 }
643 let tmp = scratch.join("tmp");
644 make_private_dir(&tmp)?;
645 let mut dirs = vec![home.join(".local").join("bin"), rustup_cargo.join("bin")];
646 dirs.extend(system_dirs());
647 let path = std::env::join_paths(&dirs)
648 .map_err(|e| GateError::Check(format!("the run's PATH: {e}")))?;
649 let mut env: Vec<(String, std::ffi::OsString)> = vec![
650 ("PATH".into(), path),
651 ("HOME".into(), home.clone().into()),
652 ("LANG".into(), "C.UTF-8".into()),
653 ("CARGO_HOME".into(), cargo_home.into()),
654 ("CARGO_TARGET_DIR".into(), scratch.join("target").into()),
655 ("CARGO_TERM_COLOR".into(), "never".into()),
656 ("TMPDIR".into(), tmp.clone().into()),
657 ];
658 #[cfg(windows)]
666 {
667 env.push(("USERPROFILE".into(), home.clone().into()));
668 env.push(("TEMP".into(), tmp.clone().into()));
669 env.push(("TMP".into(), tmp.into()));
670 if let Some(windows) = win::windows_dir() {
671 env.push(("SystemRoot".into(), windows.into()));
672 }
673 if let Some(data) = win::program_data() {
674 env.push(("ProgramData".into(), data.into()));
675 }
676 }
677 if rustup.is_dir() {
678 env.push(("RUSTUP_HOME".into(), rustup.into()));
679 }
680 Ok(env)
681}
682
683pub(super) fn run_command(
687 dir: &Path,
688 command: &str,
689 env: &[(String, std::ffi::OsString)],
690 log: &mut std::fs::File,
691 deadline: Instant,
692) -> Result<i32, GateError> {
693 let out = log
694 .try_clone()
695 .map_err(|e| GateError::Check(format!("the run log: {e}")))?;
696 let err = log
697 .try_clone()
698 .map_err(|e| GateError::Check(format!("the run log: {e}")))?;
699 let mut cmd = Command::new(shell()?);
700 #[cfg(windows)]
704 let _script = {
705 let tmp = env
706 .iter()
707 .find(|(k, _)| k == "TMPDIR")
708 .map(|(_, v)| PathBuf::from(v))
709 .ok_or_else(|| GateError::Check("the run has no temp directory".into()))?;
710 let mut file = tempfile::Builder::new()
711 .prefix("g6-command-")
712 .suffix(".sh")
713 .tempfile_in(&tmp)
714 .map_err(|e| GateError::Check(format!("the command file: {e}")))?;
715 file.write_all(command.as_bytes())
716 .map_err(|e| GateError::Check(format!("the command file: {e}")))?;
717 let path = file.into_temp_path();
718 cmd.arg(&*path);
719 path
720 };
721 #[cfg(not(windows))]
722 cmd.arg("-c").arg(command);
723 cmd.env_clear()
724 .envs(env.iter().map(|(k, v)| (k, v)))
725 .current_dir(dir)
726 .stdin(Stdio::null())
727 .stdout(out)
728 .stderr(err);
729 #[cfg(unix)]
730 {
731 use std::os::unix::process::CommandExt as _;
732 cmd.process_group(0);
733 }
734 #[cfg(windows)]
739 let job = {
740 use std::os::windows::process::CommandExt as _;
741 cmd.creation_flags(win::CREATE_SUSPENDED);
742 win::Job::new().ok_or_else(|| GateError::Check("no job object for the run".into()))?
743 };
744 let mut child = cmd
745 .spawn()
746 .map_err(|e| GateError::Check(format!("the command did not start: {e}")))?;
747 #[cfg(windows)]
748 if !job.assign_and_resume(&child) {
749 let _ = child.kill();
750 let _ = child.wait();
751 return Err(GateError::Check(
752 "the run could not be held in its job object".into(),
753 ));
754 }
755 loop {
756 match child.try_wait() {
757 Ok(Some(status)) => return Ok(status.code().unwrap_or(-1)),
758 Ok(None) if Instant::now() >= deadline => {
759 #[cfg(unix)]
760 if let Ok(group) = i32::try_from(child.id()) {
761 unsafe {
763 libc::kill(-group, libc::SIGKILL);
764 }
765 }
766 #[cfg(windows)]
767 job.terminate();
768 let _ = child.kill();
769 let _ = child.wait();
770 let _ = writeln!(log, "\n[G6: the run passed its time limit and was stopped]");
771 return Ok(-1);
772 }
773 Ok(None) => std::thread::sleep(Duration::from_millis(50)),
774 Err(e) => return Err(GateError::Check(format!("waiting for the command: {e}"))),
775 }
776 }
777}
778
779#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
784struct Stamp {
785 dev: u64,
786 ino: u64,
787 mode: u32,
788 ctime: i64,
789 ctime_ns: i64,
790}
791
792impl Stamp {
793 #[cfg(unix)]
794 fn of(meta: &std::fs::Metadata) -> Self {
795 use std::os::unix::fs::MetadataExt as _;
796 Self {
797 dev: meta.dev(),
798 ino: meta.ino(),
799 mode: meta.mode(),
800 ctime: meta.ctime(),
801 ctime_ns: meta.ctime_nsec(),
802 }
803 }
804
805 #[cfg(windows)]
810 fn of(meta: &std::fs::Metadata) -> Self {
811 use std::os::windows::fs::MetadataExt as _;
812 let written = meta.last_write_time();
813 Self {
814 mode: meta.file_attributes(),
815 ctime: i64::try_from(written / 10_000_000).unwrap_or(i64::MAX),
816 ctime_ns: i64::try_from(written % 10_000_000).unwrap_or_default() * 100,
817 ..Self::default()
818 }
819 }
820
821 #[cfg(not(any(unix, windows)))]
822 fn of(_meta: &std::fs::Metadata) -> Self {
823 Self::default()
824 }
825}
826
827#[derive(Debug, Clone, PartialEq, Eq)]
830enum Held {
831 File(String, Stamp),
832 Link(String, Stamp),
833}
834
835#[derive(Debug, Clone, Default, PartialEq, Eq)]
843pub(super) struct LockedFiles {
844 held: BTreeMap<String, Held>,
845 dirs: BTreeMap<String, Option<Stamp>>,
846 root: Option<(u64, u64)>,
847 chain: Vec<(PathBuf, Option<Stamp>)>,
848}
849
850#[cfg(unix)]
854fn movable(dir: &Path) -> bool {
855 use std::os::unix::ffi::OsStrExt as _;
856 use std::os::unix::fs::MetadataExt as _;
857 let Some(parent) = dir.parent() else {
858 return false;
859 };
860 let uid = unsafe { libc::getuid() };
862 if std::fs::metadata(parent).is_ok_and(|m| m.uid() == uid) {
863 return true;
864 }
865 let Ok(c) = std::ffi::CString::new(parent.as_os_str().as_bytes()) else {
866 return true;
867 };
868 unsafe { libc::access(c.as_ptr(), libc::W_OK) == 0 }
870}
871
872#[cfg(not(unix))]
873fn movable(_dir: &Path) -> bool {
874 true
875}
876
877fn chain(cradle: &Path) -> Vec<(PathBuf, Option<Stamp>)> {
888 cradle
889 .ancestors()
890 .enumerate()
891 .map(|(i, dir)| {
892 let stamp = std::fs::symlink_metadata(dir)
893 .ok()
894 .filter(std::fs::Metadata::is_dir)
895 .map(|m| {
896 let s = Stamp::of(&m);
897 if i == 0 || (cfg!(unix) && !MoveWatch::SEES_RENAMES && movable(dir)) {
898 s
899 } else {
900 Stamp {
901 dev: s.dev,
902 ino: s.ino,
903 ..Stamp::default()
904 }
905 }
906 });
907 (dir.to_path_buf(), stamp)
908 })
909 .collect()
910}
911
912#[cfg(target_os = "linux")]
917pub(super) struct MoveWatch(std::os::fd::OwnedFd);
918
919#[cfg(target_os = "linux")]
920impl MoveWatch {
921 pub(super) fn new(cradle: &Path) -> Result<Self, GateError> {
922 use std::os::fd::{AsRawFd as _, FromRawFd as _};
923 use std::os::unix::ffi::OsStrExt as _;
924 let raw = unsafe { libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC) };
926 if raw < 0 {
927 return Err(GateError::Check(format!(
928 "watching the run directory: {}",
929 std::io::Error::last_os_error()
930 )));
931 }
932 let fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(raw) };
934 for dir in cradle.ancestors() {
935 let c = std::ffi::CString::new(dir.as_os_str().as_bytes())
936 .map_err(|_| GateError::Check("a run path with a NUL byte".into()))?;
937 let wd = unsafe {
939 libc::inotify_add_watch(
940 fd.as_raw_fd(),
941 c.as_ptr(),
942 libc::IN_MOVE_SELF | libc::IN_DELETE_SELF | libc::IN_ONLYDIR,
943 )
944 };
945 if wd < 0 {
946 return Err(GateError::Check(format!(
947 "watching {}: {}",
948 dir.display(),
949 std::io::Error::last_os_error()
950 )));
951 }
952 }
953 Ok(Self(fd))
954 }
955
956 pub(super) fn moved(&self) -> bool {
959 use std::os::fd::AsRawFd as _;
960 let mut buf = [0u8; 4096];
961 let n = unsafe { libc::read(self.0.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
963 !(n < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::WouldBlock)
964 }
965}
966
967#[cfg(target_os = "linux")]
968impl MoveWatch {
969 const SEES_RENAMES: bool = true;
972}
973
974#[cfg(target_vendor = "apple")]
980pub(super) struct MoveWatch {
981 queue: std::os::fd::OwnedFd,
982 _dirs: Vec<std::os::fd::OwnedFd>,
983}
984
985#[cfg(target_vendor = "apple")]
986impl MoveWatch {
987 const SEES_RENAMES: bool = true;
988
989 pub(super) fn new(cradle: &Path) -> Result<Self, GateError> {
990 use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd};
991 use std::os::unix::ffi::OsStrExt as _;
992 let fail = |what: &Path| {
993 GateError::Check(format!(
994 "watching {}: {}",
995 what.display(),
996 std::io::Error::last_os_error()
997 ))
998 };
999 let raw = unsafe { libc::kqueue() };
1001 if raw < 0 {
1002 return Err(fail(cradle));
1003 }
1004 let queue = unsafe { OwnedFd::from_raw_fd(raw) };
1006 let mut dirs = Vec::new();
1007 for dir in cradle.ancestors() {
1008 let c = std::ffi::CString::new(dir.as_os_str().as_bytes())
1009 .map_err(|_| GateError::Check("a run path with a NUL byte".into()))?;
1010 let fd = unsafe {
1012 libc::open(
1013 c.as_ptr(),
1014 libc::O_EVTONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
1015 )
1016 };
1017 if fd < 0 {
1018 return Err(fail(dir));
1019 }
1020 let fd = unsafe { OwnedFd::from_raw_fd(fd) };
1022 let ident = usize::try_from(fd.as_raw_fd()).map_err(|_| fail(dir))?;
1023 let change = libc::kevent {
1024 ident,
1025 filter: libc::EVFILT_VNODE,
1026 flags: libc::EV_ADD | libc::EV_CLEAR,
1027 fflags: libc::NOTE_RENAME | libc::NOTE_DELETE | libc::NOTE_REVOKE,
1028 data: 0,
1029 udata: std::ptr::null_mut(),
1030 };
1031 let added = unsafe {
1033 libc::kevent(
1034 queue.as_raw_fd(),
1035 &raw const change,
1036 1,
1037 std::ptr::null_mut(),
1038 0,
1039 std::ptr::null(),
1040 )
1041 };
1042 if added < 0 {
1043 return Err(fail(dir));
1044 }
1045 dirs.push(fd);
1046 }
1047 Ok(Self { queue, _dirs: dirs })
1048 }
1049
1050 pub(super) fn moved(&self) -> bool {
1053 use std::os::fd::AsRawFd as _;
1054 let mut event: libc::kevent = unsafe { std::mem::zeroed() };
1056 let now = libc::timespec {
1057 tv_sec: 0,
1058 tv_nsec: 0,
1059 };
1060 let n = unsafe {
1062 libc::kevent(
1063 self.queue.as_raw_fd(),
1064 std::ptr::null(),
1065 0,
1066 &raw mut event,
1067 1,
1068 &raw const now,
1069 )
1070 };
1071 n != 0
1072 }
1073}
1074
1075#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
1077pub(super) struct MoveWatch;
1078
1079#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
1080impl MoveWatch {
1081 const SEES_RENAMES: bool = false;
1082
1083 #[allow(clippy::unnecessary_wraps)]
1084 pub(super) fn new(_cradle: &Path) -> Result<Self, GateError> {
1085 Ok(Self)
1086 }
1087
1088 pub(super) fn moved(&self) -> bool {
1089 false
1090 }
1091}
1092
1093impl LockedFiles {
1094 pub(super) fn read(tree: &Path, locked: &[String]) -> Result<Self, GateError> {
1096 let mut held = BTreeMap::new();
1097 if !locked.is_empty() {
1098 walk(tree, tree, &mut |rel, path, meta| {
1099 if !locked.iter().any(|c| under_locked(rel, c)) {
1100 return Ok(());
1101 }
1102 let fail = |e: std::io::Error| GateError::Check(format!("reading {rel}: {e}"));
1103 let stamp = Stamp::of(meta);
1104 let entry = if meta.file_type().is_symlink() {
1105 let target = std::fs::read_link(path).map_err(fail)?;
1106 Held::Link(
1107 hex::encode(Sha256::digest(target.to_string_lossy().as_bytes())),
1108 stamp,
1109 )
1110 } else {
1111 Held::File(
1112 hex::encode(Sha256::digest(std::fs::read(path).map_err(fail)?)),
1113 stamp,
1114 )
1115 };
1116 held.insert(rel.to_owned(), entry);
1117 Ok(())
1118 })?;
1119 }
1120 let mut dirs = BTreeMap::new();
1121 for rel in held.keys() {
1122 for dir in parents(rel) {
1123 dirs.entry(dir.clone()).or_insert_with(|| {
1124 std::fs::symlink_metadata(tree.join(&dir))
1125 .ok()
1126 .filter(std::fs::Metadata::is_dir)
1127 .map(|m| Stamp::of(&m))
1128 });
1129 }
1130 }
1131 let root = std::fs::symlink_metadata(tree)
1135 .ok()
1136 .filter(std::fs::Metadata::is_dir)
1137 .map(|m| {
1138 let s = Stamp::of(&m);
1139 (s.dev, s.ino)
1140 });
1141 let chain = tree.parent().map(chain).unwrap_or_default();
1142 Ok(Self {
1143 held,
1144 dirs,
1145 root,
1146 chain,
1147 })
1148 }
1149
1150 pub(super) fn changes(
1158 &self,
1159 tree: &Path,
1160 now: &Self,
1161 moved: bool,
1162 ) -> BTreeMap<String, LockedChange> {
1163 let mut changed = BTreeMap::new();
1164 for (path, was) in &self.held {
1165 match now.held.get(path) {
1166 None => {
1167 changed.insert(path.clone(), LockedChange::Deleted);
1168 }
1169 Some(is) if std::mem::discriminant(is) != std::mem::discriminant(was) => {
1170 changed.insert(path.clone(), LockedChange::TypeChanged);
1171 }
1172 Some(is) if is != was => {
1173 changed.insert(path.clone(), LockedChange::Modified);
1174 }
1175 Some(_) => {}
1176 }
1177 }
1178 for (dir, was) in &self.dirs {
1179 let is = std::fs::symlink_metadata(tree.join(dir))
1180 .ok()
1181 .filter(std::fs::Metadata::is_dir)
1182 .map(|m| Stamp::of(&m));
1183 if is != *was {
1184 for path in self
1185 .held
1186 .keys()
1187 .filter(|p| p.starts_with(&format!("{dir}/")))
1188 {
1189 changed
1190 .entry(path.clone())
1191 .or_insert(LockedChange::Modified);
1192 }
1193 }
1194 }
1195 for path in now.held.keys() {
1196 if !self.held.contains_key(path) {
1197 changed.insert(path.clone(), LockedChange::Added);
1198 }
1199 }
1200 let root_moved = self.root.is_some() && self.root != now.root;
1204 let chain_moved = moved || self.chain != now.chain;
1205 if (root_moved || chain_moved) && !self.held.is_empty() {
1206 for path in self.held.keys() {
1207 changed
1208 .entry(path.clone())
1209 .or_insert(LockedChange::Modified);
1210 }
1211 }
1212 changed
1213 }
1214
1215 #[cfg(unix)]
1219 pub(super) fn lock(&self, tree: &Path) -> Result<(), GateError> {
1220 use std::os::unix::fs::PermissionsExt as _;
1221 let set = |path: &Path, mode: u32| {
1222 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
1223 .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))
1224 };
1225 for (rel, held) in &self.held {
1226 if matches!(held, Held::File(..)) {
1227 set(&tree.join(rel), 0o444)?;
1228 }
1229 }
1230 for dir in self.dirs.keys() {
1231 set(&tree.join(dir), 0o555)?;
1232 }
1233 if let Some(cradle) = tree.parent() {
1237 set(cradle, 0o555)?;
1238 }
1239 Ok(())
1240 }
1241
1242 #[cfg(not(unix))]
1245 pub(super) fn lock(&self, tree: &Path) -> Result<(), GateError> {
1246 for (rel, held) in &self.held {
1247 if matches!(held, Held::File(..)) {
1248 let path = tree.join(rel);
1249 let mut perms = std::fs::symlink_metadata(&path)
1250 .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))?
1251 .permissions();
1252 perms.set_readonly(true);
1253 std::fs::set_permissions(&path, perms)
1254 .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))?;
1255 }
1256 }
1257 Ok(())
1258 }
1259}
1260
1261fn parents(rel: &str) -> Vec<String> {
1263 let mut out = Vec::new();
1264 let mut parent = Path::new(rel).parent();
1265 while let Some(dir) = parent.filter(|d| !d.as_os_str().is_empty()) {
1266 out.push(dir.to_string_lossy().replace('\\', "/"));
1267 parent = dir.parent();
1268 }
1269 out
1270}
1271
1272fn walk(
1275 root: &Path,
1276 dir: &Path,
1277 visit: &mut dyn FnMut(&str, &Path, &std::fs::Metadata) -> Result<(), GateError>,
1278) -> Result<(), GateError> {
1279 let entries = std::fs::read_dir(dir)
1280 .map_err(|e| GateError::Check(format!("reading {}: {e}", dir.display())))?;
1281 for entry in entries {
1282 let entry = entry.map_err(|e| GateError::Check(format!("reading the tree: {e}")))?;
1283 let path = entry.path();
1284 let meta = std::fs::symlink_metadata(&path)
1285 .map_err(|e| GateError::Check(format!("{}: {e}", path.display())))?;
1286 if meta.is_dir() {
1287 walk(root, &path, visit)?;
1288 continue;
1289 }
1290 let rel = path
1291 .strip_prefix(root)
1292 .map_err(|_| GateError::Check("a path outside the run tree".into()))?
1293 .to_string_lossy()
1294 .replace('\\', "/");
1295 visit(&rel, &path, &meta)?;
1296 }
1297 Ok(())
1298}
1299
1300pub(super) struct Unlock(pub(super) PathBuf);
1304
1305impl Drop for Unlock {
1306 fn drop(&mut self) {
1307 fn open_up(dir: &Path) {
1308 #[cfg(unix)]
1309 {
1310 use std::os::unix::fs::PermissionsExt as _;
1311 let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
1312 }
1313 if let Ok(entries) = std::fs::read_dir(dir) {
1314 for entry in entries.flatten() {
1315 let path = entry.path();
1316 match std::fs::symlink_metadata(&path) {
1317 Ok(m) if m.is_dir() => open_up(&path),
1318 #[cfg(not(unix))]
1319 Ok(m) if m.is_file() && m.permissions().readonly() => {
1320 let mut perms = m.permissions();
1321 #[expect(
1322 clippy::permissions_set_readonly_false,
1323 reason = "Windows: clears the read-only attribute, no mode bits"
1324 )]
1325 perms.set_readonly(false);
1326 let _ = std::fs::set_permissions(&path, perms);
1327 }
1328 _ => {}
1329 }
1330 }
1331 }
1332 }
1333 open_up(&self.0);
1334 }
1335}