1use std::io::Write;
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::sync::Arc;
23use std::time::{Duration, SystemTime, UNIX_EPOCH};
24
25use libtea_core::escape_control_chars;
26use libtea_core::http_cache::{
27 decode_entry, encode_entry, is_cache_key, CacheEntryMeta, EntryBuilder,
28};
29use tokio::io::AsyncWriteExt;
30
31use crate::error::ClientError;
32
33const FRAMING_SLACK: u64 = 80 * 1024;
35const ENTRY_DIR: &str = "v1";
36
37#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub struct CacheConfig {
43 pub dir: PathBuf,
45 pub max_total_bytes: u64,
47 pub max_entry_bytes: u64,
49 pub max_age: Duration,
52 pub authenticated: bool,
55}
56
57impl CacheConfig {
58 #[must_use]
61 pub fn new(dir: impl Into<PathBuf>) -> Self {
62 Self {
63 dir: dir.into(),
64 max_total_bytes: 512 * 1024 * 1024,
65 max_entry_bytes: 64 * 1024 * 1024,
66 max_age: Duration::from_secs(7 * 24 * 60 * 60),
67 authenticated: false,
68 }
69 }
70
71 #[must_use]
73 pub fn with_max_total_bytes(mut self, value: u64) -> Self {
74 self.max_total_bytes = value;
75 self
76 }
77
78 #[must_use]
80 pub fn with_max_entry_bytes(mut self, value: u64) -> Self {
81 self.max_entry_bytes = value;
82 self
83 }
84
85 #[must_use]
87 pub fn with_max_age(mut self, value: Duration) -> Self {
88 self.max_age = value;
89 self
90 }
91
92 #[must_use]
94 pub fn with_authenticated(mut self, value: bool) -> Self {
95 self.authenticated = value;
96 self
97 }
98}
99
100pub(crate) fn now_secs() -> u64 {
101 SystemTime::now()
102 .duration_since(UNIX_EPOCH)
103 .map_or(0, |elapsed| elapsed.as_secs())
104}
105
106fn io_error(what: &str, err: &std::io::Error) -> ClientError {
107 ClientError::Io(escape_control_chars(&format!("{what}: {}", err.kind())))
108}
109
110fn refuse(path: &Path, why: &str) -> ClientError {
111 ClientError::Io(escape_control_chars(&format!(
112 "cache directory {}: {why}",
113 path.display()
114 )))
115}
116
117fn private_dir(path: &Path, create: bool) -> Result<bool, ClientError> {
121 match std::fs::symlink_metadata(path) {
122 Ok(meta) if meta.file_type().is_symlink() => {
123 Err(refuse(path, "is a symbolic link; refusing to use it"))
124 }
125 Ok(meta) if !meta.is_dir() => Err(refuse(path, "is not a directory")),
126 Ok(meta) => {
127 #[cfg(unix)]
128 {
129 use std::os::unix::fs::{MetadataExt, PermissionsExt};
130 if !owner_matches(meta.uid(), current_uid(Some(path))?) {
134 return Err(refuse(
135 path,
136 "is owned by another user; use a directory you own",
137 ));
138 }
139 let mode = meta.permissions().mode() & 0o777;
140 if mode & 0o077 != 0 {
141 return Err(refuse(
142 path,
143 &format!(
144 "is accessible by other users (mode {mode:o}); run chmod 700 on it"
145 ),
146 ));
147 }
148 }
149 #[cfg(not(unix))]
150 let _ = meta;
151 Ok(true)
152 }
153 Err(err) if err.kind() == std::io::ErrorKind::NotFound && create => {
154 let mut builder = std::fs::DirBuilder::new();
155 builder.recursive(true);
156 #[cfg(unix)]
157 {
158 use std::os::unix::fs::DirBuilderExt;
159 builder.mode(0o700);
160 }
161 builder
162 .create(path)
163 .map_err(|e| io_error("creating the cache directory", &e))?;
164 private_dir(path, false)
166 }
167 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false),
168 Err(err) => Err(io_error("inspecting the cache directory", &err)),
169 }
170}
171
172#[cfg(unix)]
175pub(crate) fn owner_matches(dir_uid: u32, own_uid: u32) -> bool {
176 dir_uid == own_uid
177}
178
179#[cfg(unix)]
182pub(crate) fn current_uid(fallback: Option<&Path>) -> Result<u32, ClientError> {
183 use std::os::unix::fs::MetadataExt;
184 static COUNTER: AtomicU64 = AtomicU64::new(0);
185 let name = format!(
186 ".libtea-uid-{}-{}",
187 std::process::id(),
188 COUNTER.fetch_add(1, Ordering::Relaxed)
189 );
190 let mut last = None;
191 for dir in std::iter::once(std::env::temp_dir()).chain(fallback.map(Path::to_path_buf)) {
192 let probe = dir.join(&name);
193 match open_private(&probe) {
194 Ok(file) => {
195 let uid = file
196 .metadata()
197 .map_err(|e| io_error("checking directory ownership", &e))?
198 .uid();
199 drop(file);
200 let _ = std::fs::remove_file(&probe);
201 return Ok(uid);
202 }
203 Err(err) => last = Some(err),
204 }
205 }
206 Err(match last {
207 Some(err) => io_error("checking directory ownership", &err),
208 None => ClientError::Io("checking directory ownership".into()),
209 })
210}
211
212pub(crate) struct Cache {
213 pub(crate) config: CacheConfig,
214 entries: PathBuf,
215 pub(crate) offline: bool,
216}
217
218static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
222
223impl Cache {
224 pub(crate) fn open(config: CacheConfig, offline: bool) -> Result<Self, ClientError> {
225 private_dir(&config.dir, true)?;
226 let entries = config.dir.join(ENTRY_DIR);
227 private_dir(&entries, true)?;
228 Ok(Self {
229 config,
230 entries,
231 offline,
232 })
233 }
234
235 fn entry_path(&self, key: &str) -> PathBuf {
236 debug_assert!(is_cache_key(key));
237 self.entries.join(format!("{key}.entry"))
238 }
239
240 fn temp_path(&self, key: &str) -> PathBuf {
241 self.entries.join(format!(
242 ".{key}.{}-{}.tmp",
243 std::process::id(),
244 TEMP_COUNTER.fetch_add(1, Ordering::Relaxed)
245 ))
246 }
247
248 pub(crate) fn load_blocking(&self, key: &str) -> Option<(CacheEntryMeta, Vec<u8>)> {
250 if !is_cache_key(key) {
251 return None;
252 }
253 let path = self.entry_path(key);
254 let meta = std::fs::symlink_metadata(&path).ok()?;
255 let remove = |path: &Path| {
256 let _ = std::fs::remove_file(path);
257 };
258 if !meta.file_type().is_file() || meta.len() > self.config.max_entry_bytes + FRAMING_SLACK {
259 remove(&path);
260 return None;
261 }
262 let bytes = read_regular(&path, self.config.max_entry_bytes + FRAMING_SLACK).ok()?;
263 let max_body = usize::try_from(self.config.max_entry_bytes).unwrap_or(usize::MAX);
264 match decode_entry(&bytes, key, max_body) {
265 Ok((entry, body)) => {
266 let now = now_secs();
267 let age = now.saturating_sub(entry.validated_at);
268 if entry.validated_at > now.saturating_add(24 * 60 * 60)
269 || age > self.config.max_age.as_secs()
270 {
271 remove(&path);
272 return None;
273 }
274 Some((entry, body))
275 }
276 Err(error) => {
277 tracing::debug!(%error, "cache entry refused and removed");
278 remove(&path);
279 None
280 }
281 }
282 }
283
284 pub(crate) async fn load(self: &Arc<Self>, key: &str) -> Option<(CacheEntryMeta, Vec<u8>)> {
285 let cache = Arc::clone(self);
286 let key = key.to_owned();
287 tokio::task::spawn_blocking(move || cache.load_blocking(&key))
288 .await
289 .ok()
290 .flatten()
291 }
292
293 pub(crate) fn store_blocking(&self, key: &str, meta: CacheEntryMeta, body: &[u8]) {
295 if !is_cache_key(key) || body.len() as u64 > self.config.max_entry_bytes {
296 return;
297 }
298 let Ok(bytes) = encode_entry(meta, body) else {
299 return;
300 };
301 match write_entry_file(&self.temp_path(key), &bytes, &self.entry_path(key)) {
302 Ok(()) => self.prune_blocking(),
303 Err(error) => tracing::debug!(kind = ?error.kind(), "cache entry not written"),
304 }
305 }
306
307 pub(crate) async fn store(self: &Arc<Self>, key: &str, meta: CacheEntryMeta, body: Vec<u8>) {
308 let cache = Arc::clone(self);
309 let key = key.to_owned();
310 let _ = tokio::task::spawn_blocking(move || cache.store_blocking(&key, meta, &body)).await;
311 }
312
313 pub(crate) fn remove_blocking(&self, key: &str) {
314 if is_cache_key(key) {
315 let _ = std::fs::remove_file(self.entry_path(key));
316 }
317 }
318
319 pub(crate) async fn remove(self: &Arc<Self>, key: &str) {
320 let cache = Arc::clone(self);
321 let key = key.to_owned();
322 let _ = tokio::task::spawn_blocking(move || cache.remove_blocking(&key)).await;
323 }
324
325 pub(crate) fn prune_blocking(&self) {
328 let Ok(dir) = std::fs::read_dir(&self.entries) else {
329 return;
330 };
331 let now = SystemTime::now();
332 let mut entries: Vec<(SystemTime, u64, PathBuf)> = Vec::new();
333 let mut total = 0u64;
334 for item in dir.flatten() {
335 let path = item.path();
336 let Ok(meta) = std::fs::symlink_metadata(&path) else {
337 continue;
338 };
339 let name = item.file_name();
340 let name = name.to_string_lossy();
341 if is_cache_temp(&name) {
342 let old = meta
343 .modified()
344 .ok()
345 .and_then(|m| now.duration_since(m).ok())
346 .is_some_and(|age| age > Duration::from_secs(3600));
347 if old {
348 let _ = std::fs::remove_file(&path);
349 }
350 continue;
351 }
352 if !meta.file_type().is_file() || !name.ends_with(".entry") {
353 continue;
354 }
355 total = total.saturating_add(meta.len());
356 entries.push((meta.modified().unwrap_or(UNIX_EPOCH), meta.len(), path));
357 }
358 if total <= self.config.max_total_bytes {
359 return;
360 }
361 entries.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.cmp(&b.2)));
362 for (_, size, path) in entries {
363 if total <= self.config.max_total_bytes {
364 break;
365 }
366 if std::fs::remove_file(&path).is_ok() {
367 total = total.saturating_sub(size);
368 }
369 }
370 }
371
372 pub(crate) async fn start_tee(self: &Arc<Self>, key: &str) -> Option<CacheTee> {
375 if !is_cache_key(key) {
376 return None;
377 }
378 let tmp = self.temp_path(key);
379 let mut options = tokio::fs::OpenOptions::new();
380 options.write(true).create_new(true);
381 #[cfg(unix)]
382 options.mode(0o600);
383 let mut file = options.open(&tmp).await.ok()?;
384 if file.write_all(EntryBuilder::prefix()).await.is_err() {
385 let _ = std::fs::remove_file(&tmp);
386 return None;
387 }
388 Some(CacheTee {
389 cache: Arc::clone(self),
390 key: key.to_owned(),
391 file: Some(file),
392 tmp,
393 builder: EntryBuilder::new(),
394 })
395 }
396}
397
398#[cfg(unix)]
406fn open_regular_with(path: &Path, between: impl FnOnce()) -> std::io::Result<std::fs::File> {
407 use std::os::unix::fs::MetadataExt;
408 let invalid =
409 |what: &str| std::io::Error::new(std::io::ErrorKind::InvalidInput, what.to_owned());
410 let before = std::fs::symlink_metadata(path)?;
411 if !before.file_type().is_file() {
412 return Err(invalid("not a regular file"));
413 }
414 between();
415 let file = std::fs::File::open(path)?;
416 let opened = file.metadata()?;
417 let after = std::fs::symlink_metadata(path)?;
418 if !after.file_type().is_file()
419 || !opened.is_file()
420 || (opened.dev(), opened.ino()) != (after.dev(), after.ino())
421 || (opened.dev(), opened.ino()) != (before.dev(), before.ino())
422 {
423 return Err(invalid("the path changed while it was opened"));
424 }
425 Ok(file)
426}
427
428fn read_regular(path: &Path, limit: u64) -> std::io::Result<Vec<u8>> {
431 use std::io::Read;
432 #[cfg(unix)]
433 let file = open_regular_with(path, || {})?;
434 #[cfg(not(unix))]
435 let file = {
436 if !std::fs::symlink_metadata(path)?.file_type().is_file() {
437 return Err(std::io::Error::new(
438 std::io::ErrorKind::InvalidInput,
439 "not a regular file",
440 ));
441 }
442 std::fs::File::open(path)?
443 };
444 let mut bytes = Vec::new();
445 file.take(limit + 1).read_to_end(&mut bytes)?;
446 if bytes.len() as u64 > limit {
447 return Err(std::io::Error::new(
448 std::io::ErrorKind::InvalidData,
449 "entry is larger than the limit",
450 ));
451 }
452 Ok(bytes)
453}
454
455fn write_entry_file(tmp: &Path, bytes: &[u8], dest: &Path) -> std::io::Result<()> {
459 let mut file = open_private(tmp)?;
460 let result = file.write_all(bytes).and_then(|()| {
461 drop(file);
462 std::fs::rename(tmp, dest)
463 });
464 if result.is_err() {
465 let _ = std::fs::remove_file(tmp);
466 }
467 result
468}
469
470fn open_private(path: &Path) -> std::io::Result<std::fs::File> {
471 let mut options = std::fs::OpenOptions::new();
472 options.write(true).create_new(true);
473 #[cfg(unix)]
474 {
475 use std::os::unix::fs::OpenOptionsExt;
476 options.mode(0o600);
477 }
478 options.open(path)
479}
480
481pub(crate) struct CacheTee {
485 cache: Arc<Cache>,
486 key: String,
487 file: Option<tokio::fs::File>,
488 tmp: PathBuf,
489 builder: EntryBuilder,
490}
491
492impl CacheTee {
493 pub(crate) async fn write(&mut self, chunk: &[u8]) -> bool {
496 let Some(file) = self.file.as_mut() else {
497 return false;
498 };
499 if self.builder.len().saturating_add(chunk.len() as u64) > self.cache.config.max_entry_bytes
500 || file.write_all(chunk).await.is_err()
501 {
502 self.abandon();
503 return false;
504 }
505 self.builder.update(chunk);
506 true
507 }
508
509 fn abandon(&mut self) {
510 self.file = None;
511 let _ = std::fs::remove_file(&self.tmp);
512 }
513
514 pub(crate) async fn finish(mut self, meta: CacheEntryMeta) {
516 let Some(mut file) = self.file.take() else {
517 return;
518 };
519 let builder = std::mem::take(&mut self.builder);
520 let Ok(trailer) = builder.trailer(meta) else {
521 self.abandon();
522 return;
523 };
524 if file.write_all(&trailer).await.is_err() || file.flush().await.is_err() {
525 drop(file);
526 let _ = std::fs::remove_file(&self.tmp);
527 return;
528 }
529 drop(file);
530 let cache = Arc::clone(&self.cache);
531 let tmp = self.tmp.clone();
532 let final_path = cache.entry_path(&self.key);
533 let committed = tokio::task::spawn_blocking(move || {
534 let ok = std::fs::rename(&tmp, final_path).is_ok();
535 if ok {
536 cache.prune_blocking();
537 } else {
538 let _ = std::fs::remove_file(&tmp);
539 }
540 ok
541 })
542 .await
543 .unwrap_or(false);
544 if committed {
545 self.tmp = PathBuf::new();
547 }
548 }
549}
550
551impl Drop for CacheTee {
552 fn drop(&mut self) {
553 if !self.tmp.as_os_str().is_empty() {
554 let _ = std::fs::remove_file(&self.tmp);
555 }
556 }
557}
558
559#[derive(Debug, Clone, PartialEq, Eq)]
563#[non_exhaustive]
564pub struct CacheStats {
565 pub dir: PathBuf,
567 pub exists: bool,
569 pub entries: u64,
571 pub bytes: u64,
573 pub foreign: u64,
575 pub oldest_age_secs: Option<u64>,
577 pub newest_age_secs: Option<u64>,
579}
580
581fn entry_files(dir: &Path) -> Result<Option<(PathBuf, std::fs::ReadDir)>, ClientError> {
582 if !private_dir(dir, false)? {
583 return Ok(None);
584 }
585 let entries = dir.join(ENTRY_DIR);
586 if !private_dir(&entries, false)? {
587 return Ok(None);
588 }
589 let read =
590 std::fs::read_dir(&entries).map_err(|e| io_error("reading the cache directory", &e))?;
591 Ok(Some((entries, read)))
592}
593
594pub fn cache_stat(dir: &Path) -> Result<CacheStats, ClientError> {
601 let mut stats = CacheStats {
602 dir: dir.to_path_buf(),
603 exists: false,
604 entries: 0,
605 bytes: 0,
606 foreign: 0,
607 oldest_age_secs: None,
608 newest_age_secs: None,
609 };
610 let Some((_, read)) = entry_files(dir)? else {
611 return Ok(stats);
612 };
613 stats.exists = true;
614 let now = SystemTime::now();
615 for item in read.flatten() {
616 let name = item.file_name();
617 let name = name.to_string_lossy().into_owned();
618 let Ok(meta) = std::fs::symlink_metadata(item.path()) else {
619 continue;
620 };
621 let key = name.strip_suffix(".entry").unwrap_or("");
622 if meta.file_type().is_file() && is_cache_key(key) {
623 stats.entries += 1;
624 stats.bytes = stats.bytes.saturating_add(meta.len());
625 if let Some(age) = meta
626 .modified()
627 .ok()
628 .and_then(|m| now.duration_since(m).ok())
629 {
630 let age = age.as_secs();
631 stats.oldest_age_secs = Some(stats.oldest_age_secs.map_or(age, |o| o.max(age)));
632 stats.newest_age_secs = Some(stats.newest_age_secs.map_or(age, |n| n.min(age)));
633 }
634 } else if !name.ends_with(".tmp") {
635 stats.foreign += 1;
636 }
637 }
638 Ok(stats)
639}
640
641fn is_cache_temp(name: &str) -> bool {
644 let Some(rest) = name.strip_prefix('.') else {
645 return false;
646 };
647 let Some(rest) = rest.strip_suffix(".tmp") else {
648 return false;
649 };
650 let Some((key, tail)) = rest.split_once('.') else {
651 return false;
652 };
653 is_cache_key(key)
654 && tail.split_once('-').is_some_and(|(pid, n)| {
655 !pid.is_empty()
656 && !n.is_empty()
657 && pid.bytes().all(|b| b.is_ascii_digit())
658 && n.bytes().all(|b| b.is_ascii_digit())
659 })
660}
661
662pub fn cache_clear(dir: &Path) -> Result<u64, ClientError> {
673 let Some((entries, read)) = entry_files(dir)? else {
674 return Ok(0);
675 };
676 let mut removed = 0;
677 for item in read.flatten() {
678 let name = item.file_name();
679 let name = name.to_string_lossy().into_owned();
680 let is_entry = name.strip_suffix(".entry").is_some_and(is_cache_key);
681 let is_temp = is_cache_temp(&name);
682 if !(is_entry || is_temp) {
683 continue;
684 }
685 let path = entries.join(&name);
686 let Ok(meta) = std::fs::symlink_metadata(&path) else {
687 continue;
688 };
689 if (meta.file_type().is_file() || meta.file_type().is_symlink())
690 && std::fs::remove_file(&path).is_ok()
691 {
692 removed += 1;
693 }
694 }
695 Ok(removed)
696}
697
698#[cfg(test)]
699mod temp_file_tests {
700 use super::*;
701
702 fn scratch(tag: &str) -> PathBuf {
703 let dir =
704 std::env::temp_dir().join(format!("libtea-cache-tmp-{tag}-{}", std::process::id()));
705 let _ = std::fs::remove_dir_all(&dir);
706 std::fs::create_dir_all(&dir).unwrap();
707 dir
708 }
709
710 #[test]
711 fn two_caches_on_one_directory_never_share_a_temporary_name() {
712 let dir = scratch("names");
713 let cache_dir = dir.join("cache");
715 let first = Cache::open(CacheConfig::new(&cache_dir), false).unwrap();
716 let second = Cache::open(CacheConfig::new(&cache_dir), false).unwrap();
717 let key = "0".repeat(64);
718 let names: std::collections::BTreeSet<PathBuf> = (0..4)
719 .flat_map(|_| [first.temp_path(&key), second.temp_path(&key)])
720 .collect();
721 assert_eq!(names.len(), 8);
722 let _ = std::fs::remove_dir_all(&dir);
723 }
724
725 #[test]
726 fn a_temporary_file_someone_else_created_is_left_alone() {
727 let dir = scratch("theirs");
728 let tmp = dir.join("theirs.tmp");
729 let dest = dir.join("entry");
730 std::fs::write(&tmp, b"theirs").unwrap();
731 let error = write_entry_file(&tmp, b"mine", &dest).unwrap_err();
732 assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
733 assert_eq!(std::fs::read(&tmp).unwrap(), b"theirs");
734 assert!(!dest.exists());
735 let _ = std::fs::remove_dir_all(&dir);
736 }
737
738 #[test]
739 fn a_failed_rename_removes_only_its_own_temporary_file() {
740 let dir = scratch("mine");
741 let tmp = dir.join("mine.tmp");
742 let dest = dir.join("missing").join("entry");
744 assert!(write_entry_file(&tmp, b"mine", &dest).is_err());
745 assert!(!tmp.exists());
746 let _ = std::fs::remove_dir_all(&dir);
747 }
748}
749
750#[cfg(all(test, unix))]
751mod tests {
752 use super::*;
753
754 fn scratch(tag: &str) -> PathBuf {
755 let dir =
756 std::env::temp_dir().join(format!("libtea-cache-unit-{tag}-{}", std::process::id()));
757 let _ = std::fs::remove_dir_all(&dir);
758 std::fs::create_dir_all(&dir).unwrap();
759 dir
760 }
761
762 #[test]
763 fn ownership_is_compared_with_the_uid_of_a_file_just_created() {
764 let dir = scratch("uid");
765 let mine = current_uid(None).unwrap();
766 let probe = dir.join("probe");
767 std::fs::write(&probe, b"x").unwrap();
768 use std::os::unix::fs::MetadataExt;
769 assert_eq!(std::fs::metadata(&probe).unwrap().uid(), mine);
770 assert_eq!(std::fs::metadata(&dir).unwrap().uid(), mine);
771 assert!(owner_matches(mine, mine));
772 assert!(
773 !owner_matches(mine.wrapping_add(1), mine),
774 "another uid must not match"
775 );
776 assert!(!owner_matches(0, 501) && !owner_matches(501, 0));
777 let _ = std::fs::remove_dir_all(dir);
778 }
779
780 #[test]
781 fn a_regular_file_opens_and_a_symlink_never_does() {
782 let dir = scratch("nofollow");
783 let real = dir.join("real");
784 std::fs::write(&real, b"entry").unwrap();
785 assert_eq!(read_regular(&real, 100).unwrap(), b"entry");
786 let link = dir.join("link");
787 std::os::unix::fs::symlink(&real, &link).unwrap();
788 assert!(open_regular_with(&link, || {}).is_err());
789 assert!(read_regular(&link, 100).is_err());
790 assert!(
791 read_regular(&dir, 100).is_err(),
792 "a directory is not an entry"
793 );
794 assert!(read_regular(&real, 3).is_err(), "over the limit");
795 let _ = std::fs::remove_dir_all(dir);
796 }
797
798 #[test]
799 fn a_symlink_swapped_in_after_the_check_is_refused_not_followed() {
800 let dir = scratch("swap");
801 let entry = dir.join("entry");
802 let secret = dir.join("secret");
803 std::fs::write(&entry, b"genuine").unwrap();
804 std::fs::write(&secret, b"must not be read").unwrap();
805 let swapped = open_regular_with(&entry, || {
807 std::fs::remove_file(&entry).unwrap();
808 std::os::unix::fs::symlink(&secret, &entry).unwrap();
809 });
810 assert!(swapped.is_err(), "the swapped-in link was followed");
811 let entry2 = dir.join("entry2");
816 let kept = dir.join("entry2-kept");
817 std::fs::write(&entry2, b"first").unwrap();
818 std::fs::hard_link(&entry2, &kept).unwrap();
819 let replaced = open_regular_with(&entry2, || {
820 std::fs::remove_file(&entry2).unwrap();
821 std::fs::write(&entry2, b"second").unwrap();
822 });
823 assert!(
824 replaced.is_err(),
825 "a different file than the one inspected was accepted"
826 );
827 let _ = std::fs::remove_dir_all(dir);
828 }
829
830 #[test]
831 fn only_the_caches_own_temporary_files_are_temporary_files() {
832 let key = "a".repeat(64);
833 assert!(is_cache_temp(&format!(".{key}.123-4.tmp")));
834 for other in [
835 ".mine.tmp",
836 ".notes.libtea.tmp",
837 "build.tmp",
838 &format!(".{key}.tmp"),
839 &format!(".{key}.x-4.tmp"),
840 &format!(".{key}.12-.tmp"),
841 &format!(".{key}.12-4.tmp.bak"),
842 &format!(".{}.1-2.tmp", "g".repeat(64)),
843 &format!(".{}.1-2.tmp", "a".repeat(63)),
844 &format!("{key}.1-2.tmp"),
845 ] {
846 assert!(!is_cache_temp(other), "{other}");
847 }
848 }
849}