1use super::types::*;
2use crate::{
3 sensing::local_custody::{quota::StagingCharge, validate_root},
4 storage_driver::MmapDriver,
5};
6use std::{
7 fs::{self, File, OpenOptions},
8 io::{Read, Seek, SeekFrom, Write},
9 marker::PhantomData,
10 path::{Path, PathBuf},
11};
12use tempfile::{Builder, TempDir};
13
14pub struct RangeSession<'driver, 'root> {
19 files: Option<[File; 3]>,
21 dir: Option<TempDir>,
22 parent: PathBuf,
23 charge: Option<StagingCharge<'root>>,
24 limits: RangeLimits,
25 driver: PhantomData<&'driver MmapDriver>,
26}
27
28impl MmapDriver {
29 pub fn create_range_staging<'driver, 'root>(
33 &'driver self,
34 charge: StagingCharge<'root>,
35 limits: RangeLimits,
36 ) -> Result<RangeSession<'driver, 'root>, RangeCreateError<'root>> {
37 self.create_staging_inner(charge, limits, |_| {})
38 }
39 fn create_staging_inner<'driver, 'root>(
40 &'driver self,
41 charge: StagingCharge<'root>,
42 limits: RangeLimits,
43 before_open: impl FnOnce(&Path),
44 ) -> Result<RangeSession<'driver, 'root>, RangeCreateError<'root>> {
45 let fail = |error| RangeCreateError {
46 error,
47 cleanup_pending: None,
48 };
49 let total = limits.total().map_err(fail)?;
50 if total > charge.allowance() {
51 return Err(fail(RangeError::InvalidLimits));
52 }
53 if !cfg!(any(unix, windows)) {
54 return Err(fail(RangeError::Unsupported));
55 }
56 validate_root(&self.root).map_err(|_| fail(RangeError::InvalidRoot))?;
57 validate_root(charge.root()).map_err(|_| fail(RangeError::InvalidRoot))?;
58 let parent = checked_root(&self.root).map_err(fail)?;
59 let quota_root = checked_root(charge.root()).map_err(fail)?;
60 if parent != quota_root {
61 return Err(fail(RangeError::ScopeMismatch));
62 }
63 let dir = Builder::new()
64 .prefix("qualia-range-")
65 .tempdir_in(&parent)
66 .map_err(|e| fail(e.into()))?;
67 before_open(dir.path());
68 let opened = prepare_directory(&dir)
69 .and_then(|_| write_owner(dir.path(), charge.attempt_id()))
70 .and_then(|_| open_files(dir.path()));
71 match opened {
72 Ok(files) => Ok(RangeSession {
73 files: Some(files),
74 dir: Some(dir),
75 parent,
76 charge: Some(charge),
77 limits,
78 driver: PhantomData,
79 }),
80 Err(error) => Err(RangeCreateError {
81 error,
82 cleanup_pending: close_directory(dir, parent, charge).err(),
83 }),
84 }
85 }
86}
87pub(super) fn checked_root(path: &Path) -> Result<PathBuf, RangeError> {
88 let meta = fs::symlink_metadata(path)?;
89 if !meta.is_dir() || meta.file_type().is_symlink() || is_reparse(&meta) {
90 return Err(RangeError::InvalidRoot);
91 }
92 Ok(fs::canonicalize(path)?)
93}
94fn prepare_directory(dir: &TempDir) -> Result<(), RangeError> {
95 #[cfg(unix)]
96 {
97 use std::os::unix::fs::PermissionsExt;
98 fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o700))?;
99 }
100 let _ = dir;
101 Ok(())
102}
103fn open_files(dir: &Path) -> Result<[File; 3], RangeError> {
104 fn open(dir: &Path, which: RangeFile) -> Result<File, RangeError> {
105 let mut options = OpenOptions::new();
106 options.read(true).write(true).create_new(true);
107 #[cfg(unix)]
108 {
109 use std::os::unix::fs::OpenOptionsExt;
110 options.mode(0o600);
111 }
112 #[cfg(windows)]
113 {
114 use std::os::windows::fs::OpenOptionsExt;
115 options.share_mode(0);
116 }
117 let file = options.open(dir.join(which.name()))?;
118 file.try_lock().map_err(|_| RangeError::LockUnavailable)?;
119 Ok(file)
120 }
121 Ok([
123 open(dir, RangeFile::Payload)?,
124 open(dir, RangeFile::Proof)?,
125 open(dir, RangeFile::Checkpoint)?,
126 ])
127}
128impl RangeSession<'_, '_> {
129 pub const fn limits(&self) -> RangeLimits {
130 self.limits
131 }
132 pub fn attempt_id(&self) -> [u8; 32] {
133 self.charge
134 .as_ref()
135 .expect("live range charge")
136 .attempt_id()
137 }
138 pub fn staging_path(&self) -> &Path {
139 self.dir.as_ref().expect("live range directory").path()
140 }
141 pub const fn capabilities(&self) -> RangeCapabilities {
142 RangeCapabilities {
143 writer_exclusion: if cfg!(windows) {
144 WriterExclusion::WindowsShareDeny
145 } else {
146 WriterExclusion::CooperativeLockOnly
147 },
148 directory_power_loss_qualified: false,
149 }
150 }
151 pub fn observed_file_length(&self, which: RangeFile) -> Result<u64, RangeError> {
154 Ok(
155 self.files.as_ref().expect("live range handles")[which.index()]
156 .metadata()?
157 .len(),
158 )
159 }
160 pub fn read_exact_at(
162 &mut self,
163 which: RangeFile,
164 offset: u64,
165 out: &mut [u8],
166 ) -> Result<(), RangeError> {
167 self.limits.check(which, offset, out.len())?;
168 if out.is_empty() {
169 return Ok(());
170 }
171 let file = &mut self.files.as_mut().expect("live range handles")[which.index()];
172 file.seek(SeekFrom::Start(offset))?;
173 file.read_exact(out)?;
174 Ok(())
175 }
176 pub fn write_exact_at(
179 &mut self,
180 which: RangeFile,
181 offset: u64,
182 bytes: &[u8],
183 ) -> Result<(), RangeError> {
184 self.limits.check(which, offset, bytes.len())?;
185 if bytes.is_empty() {
186 return Ok(());
187 }
188 let file = &mut self.files.as_mut().expect("live range handles")[which.index()];
189 file.seek(SeekFrom::Start(offset))?;
190 file.write_all(bytes)?;
191 Ok(())
192 }
193 pub fn sync_file(&self, which: RangeFile) -> Result<FileBarrier, RangeError> {
195 self.files.as_ref().expect("live range handles")[which.index()].sync_all()?;
196 Ok(FileBarrier::SyncAllReturned)
197 }
198}
199impl<'root> RangeSession<'_, 'root> {
200 pub fn close(self) -> Result<CleanupObservation, CleanupPending<'root>> {
201 self.close_then(|| {})
202 }
203 fn close_then(
204 mut self,
205 after_handles: impl FnOnce(),
206 ) -> Result<CleanupObservation, CleanupPending<'root>> {
207 drop(self.files.take());
208 after_handles();
209 let dir = self.dir.take().expect("live range directory");
210 let parent = std::mem::take(&mut self.parent);
211 let charge = self.charge.take().expect("live range charge");
212 close_directory(dir, parent, charge)
213 }
214}
215impl Drop for RangeSession<'_, '_> {
216 fn drop(&mut self) {
217 drop(self.files.take());
218 if let Some(dir) = self.dir.take() {
219 if let Some(charge) = self.charge.take() {
220 let _ = close_directory(dir, std::mem::take(&mut self.parent), charge);
223 } else {
224 let _ = dir.keep();
226 }
227 }
228 }
229}
230
231fn close_directory<'root>(
232 dir: TempDir,
233 parent: PathBuf,
234 charge: StagingCharge<'root>,
235) -> Result<CleanupObservation, CleanupPending<'root>> {
236 let path = dir.path().to_path_buf();
237 if let Err(error) =
238 check_owned_child(&path, &parent).and_then(|_| check_owner(&path, charge.attempt_id()))
239 {
240 let _ = dir.keep();
242 return Err(CleanupPending {
243 path,
244 parent,
245 charge,
246 error,
247 });
248 }
249 match dir.close() {
250 Ok(()) => Ok(CleanupObservation::Removed),
251 Err(error) => {
252 let original = RangeError::from(error);
253 let error = restore_owner_after_cleanup_error(&path, &parent, charge.attempt_id())
254 .err()
255 .unwrap_or(original);
256 Err(CleanupPending {
257 path,
258 parent,
259 charge,
260 error,
261 })
262 }
263 }
264}
265impl CleanupPending<'_> {
266 pub fn retry(mut self) -> Result<CleanupObservation, Self> {
271 if let Err(error) = check_owned_child(&self.path, &self.parent)
272 .and_then(|_| check_owner(&self.path, self.charge.attempt_id()))
273 {
274 self.error = error;
275 return Err(self);
276 }
277 match fs::remove_dir_all(&self.path) {
278 Ok(()) => Ok(CleanupObservation::Removed),
279 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(CleanupObservation::Removed),
280 Err(e) => {
281 let original = RangeError::from(e);
282 self.error = restore_owner_after_cleanup_error(
283 &self.path,
284 &self.parent,
285 self.charge.attempt_id(),
286 )
287 .err()
288 .unwrap_or(original);
289 Err(self)
290 }
291 }
292 }
293}
294pub(super) fn check_owned_child(path: &Path, parent: &Path) -> Result<(), RangeError> {
295 if !path.is_absolute()
296 || path.parent() != Some(parent)
297 || !path
298 .file_name()
299 .and_then(|n| n.to_str())
300 .is_some_and(|n| n.starts_with("qualia-range-") && n.len() > 13)
301 || fs::canonicalize(parent)? != parent
302 {
303 return Err(RangeError::InvalidRoot);
304 }
305 let meta = match fs::symlink_metadata(path) {
306 Ok(meta) => meta,
307 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
308 Err(e) => return Err(e.into()),
309 };
310 if !meta.is_dir()
311 || meta.file_type().is_symlink()
312 || is_reparse(&meta)
313 || fs::canonicalize(path)? != path
314 {
315 return Err(RangeError::InvalidRoot);
316 }
317 Ok(())
318}
319pub(super) fn is_reparse(meta: &fs::Metadata) -> bool {
320 #[cfg(windows)]
321 {
322 use std::os::windows::fs::MetadataExt;
323 meta.file_attributes() & 0x400 != 0
324 }
325 #[cfg(not(windows))]
326 {
327 let _ = meta;
328 false
329 }
330}
331#[cfg(test)]
332pub(super) fn close_for_test<'root>(
333 session: RangeSession<'_, 'root>,
334 after_handles: impl FnOnce(),
335) -> Result<CleanupObservation, CleanupPending<'root>> {
336 session.close_then(after_handles)
337}
338
339#[cfg(test)]
340pub(super) fn creation_failure_for_test<'driver, 'root>(
341 driver: &'driver MmapDriver,
342 charge: StagingCharge<'root>,
343 limits: RangeLimits,
344) -> Result<RangeSession<'driver, 'root>, RangeCreateError<'root>> {
345 driver.create_staging_inner(charge, limits, |path| {
346 File::create(path.join("proof")).unwrap();
347 })
348}
349const OWNER_NAME: &str = ".owner";
350const OWNER_BYTES: usize = 64;
351const OWNER_MAGIC: &[u8; 8] = b"QBSOWN1\0";
352pub(super) fn owner_bytes(attempt: [u8; 32]) -> [u8; OWNER_BYTES] {
353 let mut bytes = [0; OWNER_BYTES];
354 bytes[..8].copy_from_slice(OWNER_MAGIC);
355 bytes[8..10].copy_from_slice(&1u16.to_be_bytes());
356 bytes[16..48].copy_from_slice(&attempt);
357 bytes
358}
359fn write_owner(dir: &Path, attempt: [u8; 32]) -> Result<(), RangeError> {
360 let mut options = OpenOptions::new();
361 options.write(true).create_new(true);
362 #[cfg(unix)]
363 {
364 use std::os::unix::fs::OpenOptionsExt;
365 options.mode(0o600);
366 }
367 #[cfg(windows)]
368 {
369 use std::os::windows::fs::OpenOptionsExt;
370 options.share_mode(0);
371 }
372 let mut file = options.open(dir.join(OWNER_NAME))?;
373 file.write_all(&owner_bytes(attempt))?;
374 Ok(())
375}
376fn check_owner(dir: &Path, attempt: [u8; 32]) -> Result<(), RangeError> {
377 if let Err(e) = fs::symlink_metadata(dir) {
379 if e.kind() == std::io::ErrorKind::NotFound {
380 return Ok(());
381 }
382 return Err(e.into());
383 }
384 let path = dir.join(OWNER_NAME);
385 let meta = fs::symlink_metadata(&path).map_err(|_| RangeError::OwnershipMarker)?;
386 if !meta.is_file()
387 || meta.file_type().is_symlink()
388 || is_reparse(&meta)
389 || meta.len() != OWNER_BYTES as u64
390 {
391 return Err(RangeError::OwnershipMarker);
392 }
393 let mut file = File::open(path).map_err(|_| RangeError::OwnershipMarker)?;
394 let opened = file.metadata().map_err(|_| RangeError::OwnershipMarker)?;
395 if !opened.is_file() || is_reparse(&opened) || opened.len() != OWNER_BYTES as u64 {
396 return Err(RangeError::OwnershipMarker);
397 }
398 let mut bytes = [0; OWNER_BYTES];
399 file.read_exact(&mut bytes)
400 .map_err(|_| RangeError::OwnershipMarker)?;
401 let mut trailing = [0; 1];
402 if bytes != owner_bytes(attempt)
403 || file
404 .read(&mut trailing)
405 .map_err(|_| RangeError::OwnershipMarker)?
406 != 0
407 {
408 return Err(RangeError::OwnershipMarker);
409 }
410 Ok(())
411}
412
413#[cfg(test)]
414pub(super) fn drop_for_test(session: RangeSession<'_, '_>, after_handles: impl FnOnce()) {
415 let mut session = session;
416 drop(session.files.take());
417 after_handles();
418 drop(session);
419}
420
421fn restore_owner_after_cleanup_error(
422 path: &Path,
423 parent: &Path,
424 attempt: [u8; 32],
425) -> Result<(), RangeError> {
426 check_owned_child(path, parent)?;
430 match fs::symlink_metadata(path) {
431 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
432 Err(e) => return Err(e.into()),
433 Ok(_) => {}
434 }
435 match fs::symlink_metadata(path.join(OWNER_NAME)) {
436 Ok(_) => return check_owner(path, attempt), Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
438 Err(e) => return Err(e.into()),
439 }
440 match write_owner(path, attempt) {
441 Ok(()) => Ok(()),
442 Err(RangeError::Io(std::io::ErrorKind::AlreadyExists)) => check_owner(path, attempt),
444 Err(e) => Err(e),
445 }
446}
447#[cfg(test)]
448pub(super) fn restore_owner_for_test(
449 path: &Path,
450 parent: &Path,
451 attempt: [u8; 32],
452) -> Result<(), RangeError> {
453 restore_owner_after_cleanup_error(path, parent, attempt)
454}