-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcleanup.rs
More file actions
2848 lines (2748 loc) · 104 KB
/
Copy pathcleanup.rs
File metadata and controls
2848 lines (2748 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
accounting,
model::*,
safety, scanner,
store::{Store, err},
};
use rusqlite::{CachedStatement, Statement, params};
use std::{
collections::HashMap,
ffi::{CStr, CString, OsStr},
fs::File,
os::unix::{
ffi::OsStrExt,
io::{AsRawFd, FromRawFd, RawFd},
},
path::{Component, Path, PathBuf},
sync::atomic::{AtomicBool, Ordering},
time::{Duration, Instant},
};
pub type TrashCallback =
unsafe extern "C" fn(*const libc::c_char, *mut libc::c_char, usize) -> libc::c_int;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CleanupPhase {
Checking,
Preparing,
Comparing,
Removing,
Accounting,
}
const MANIFEST_INSERT: &str = "INSERT INTO cleanup_entries VALUES(?1,?2,?3)";
const MANIFEST_IDENTITY: &str =
"SELECT identity FROM cleanup_entries WHERE operation_id=?1 AND path=?2";
const PROGRESS_INTERVAL: Duration = Duration::from_millis(100);
struct Progress<'a> {
callback: &'a mut dyn FnMut(CleanupPhase, u64, u64),
phase: CleanupPhase,
completed: u64,
total: u64,
last: Instant,
reported: Option<(CleanupPhase, u64, u64)>,
}
impl<'a> Progress<'a> {
fn new(callback: &'a mut dyn FnMut(CleanupPhase, u64, u64)) -> Self {
Self {
callback,
phase: CleanupPhase::Checking,
completed: 0,
total: 0,
last: Instant::now(),
reported: None,
}
}
fn start(&mut self, phase: CleanupPhase, total: u64) {
self.phase = phase;
self.completed = 0;
self.total = total;
self.finish();
}
fn update(&mut self, completed: u64) {
self.completed = completed;
if completed == 1 || self.last.elapsed() >= PROGRESS_INTERVAL {
self.finish();
}
}
fn advance(&mut self) {
self.update(self.completed.saturating_add(1));
}
fn complete(&mut self) {
if self.total == 0 {
self.total = self.completed;
} else {
self.completed = self.total;
}
self.finish();
}
/// Phase boundaries and the final result bypass the intermediate update
/// throttle, including when an error leaves this phase incomplete.
fn finish(&mut self) {
let value = (self.phase, self.completed, self.total);
if self.reported == Some(value) {
return;
}
(self.callback)(self.phase, self.completed, self.total);
self.reported = Some(value);
self.last = Instant::now();
}
}
fn cancelled(cancel: &AtomicBool) -> Result<()> {
if cancel.load(Ordering::Relaxed) {
Err("Cancelled. Completed removals cannot be undone.".into())
} else {
Ok(())
}
}
fn cstr(name: &OsStr) -> Result<CString> {
CString::new(name.as_bytes()).map_err(err)
}
fn ioerr() -> String {
std::io::Error::last_os_error().to_string()
}
pub fn open_directory(path: &Path) -> Result<File> {
if !path.is_absolute() {
return Err("An absolute authorized path is required.".into());
}
let fd = unsafe {
libc::open(
c"/".as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(ioerr());
}
let mut current = unsafe { File::from_raw_fd(fd) };
for component in path.components() {
match component {
Component::RootDir => {}
Component::Normal(name) => {
let name = cstr(name)?;
#[cfg(target_os = "macos")]
let access = libc::O_SEARCH;
#[cfg(not(target_os = "macos"))]
let access = libc::O_RDONLY | libc::O_DIRECTORY;
let fd = unsafe {
libc::openat(
current.as_raw_fd(),
name.as_ptr(),
access | libc::O_NOFOLLOW | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(format!(
"Cannot safely open {}: {}",
path.display(),
ioerr()
));
}
current = unsafe { File::from_raw_fd(fd) };
}
_ => return Err("Relative traversal is not authorized.".into()),
}
}
Ok(current)
}
fn stat_at(parent: RawFd, name: &CStr) -> Result<libc::stat> {
let mut stat = std::mem::MaybeUninit::uninit();
if unsafe {
libc::fstatat(
parent,
name.as_ptr(),
stat.as_mut_ptr(),
libc::AT_SYMLINK_NOFOLLOW,
)
} != 0
{
return Err(ioerr());
}
Ok(unsafe { stat.assume_init() })
}
fn identity_stat(stat: &libc::stat) -> Identity {
Identity {
device: stat.st_dev as u64,
inode: stat.st_ino,
mode: stat.st_mode as u32,
size: stat.st_size.max(0) as u64,
modified_ns: stat
.st_mtime
.saturating_mul(1_000_000_000)
.saturating_add(stat.st_mtime_nsec),
changed_ns: stat
.st_ctime
.saturating_mul(1_000_000_000)
.saturating_add(stat.st_ctime_nsec),
}
}
fn same_object(a: &Identity, b: &Identity) -> bool {
a.device == b.device && a.inode == b.inode && a.mode == b.mode
}
fn each_entry(fd: RawFd, mut visit: impl FnMut(&CStr) -> Result<()>) -> Result<()> {
let duplicate = unsafe { libc::dup(fd) };
if duplicate < 0 {
return Err(ioerr());
}
let dir = unsafe { libc::fdopendir(duplicate) };
if dir.is_null() {
unsafe { libc::close(duplicate) };
return Err(ioerr());
}
struct Directory(*mut libc::DIR);
impl Drop for Directory {
fn drop(&mut self) {
unsafe { libc::closedir(self.0) };
}
}
let _guard = Directory(dir);
loop {
#[cfg(target_os = "macos")]
unsafe {
*libc::__error() = 0;
}
#[cfg(target_os = "linux")]
unsafe {
*libc::__errno_location() = 0;
}
let entry = unsafe { libc::readdir(dir) };
if entry.is_null() {
let code = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
return if code == 0 { Ok(()) } else { Err(ioerr()) };
}
let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) };
if name.to_bytes() == b"." || name.to_bytes() == b".." {
continue;
}
visit(name)?;
}
}
fn record_manifest_entry(
statement: &mut Statement<'_>,
op: &str,
artifact: &Path,
entry: &safety::Entry,
) -> Result<()> {
let relative = entry
.path
.strip_prefix(artifact)
.map_err(|_| "A measured entry is outside the reviewed artifact")?;
statement
.execute(params![
op,
relative.as_os_str().as_bytes(),
serde_json::to_string(&entry.meta.identity).map_err(err)?
])
.map_err(err)?;
Ok(())
}
#[derive(Default)]
struct Removed {
private: u64,
private_known: bool,
// Removed regular names, including aliases of the same inode.
files: u64,
}
struct LinkRemoval {
reviewed: Identity,
current: safety::EntryMeta,
}
/// Only completely verified internal groups enter this map. The manifest keeps
/// each path's original identity; current records the exact result of our last
/// unlink so later aliases cannot ignore unrelated ctime or link-count changes.
#[derive(Default)]
struct LinkRemovals {
groups: HashMap<(u64, u64), LinkRemoval>,
}
impl LinkRemovals {
fn from_closure(closure: safety::RegularLinkClosure) -> Result<Self> {
let closed = closure.into_closed()?;
let mut groups = HashMap::new();
groups
.try_reserve(closed.size_hint().0)
.map_err(|_| "Hard-link removal state is unavailable; cleanup stopped.")?;
for current in closed {
groups.insert(
(current.identity.device, current.identity.inode),
LinkRemoval {
reviewed: current.identity.clone(),
current,
},
);
}
Ok(Self { groups })
}
fn ensure_exhausted(&self) -> Result<()> {
if self.groups.values().any(|group| group.current.links != 0) {
return Err(
"A reviewed hard-link alias was not removed. Cleanup stopped without credit."
.into(),
);
}
Ok(())
}
}
/// A separate directory prevents ordinary writers retaining an artifact fd from
/// replacing the name we ultimately unlink. It is never recursively cleaned on
/// error: unexpected or cancelled captures remain available for recovery.
struct LeafRecovery {
file: File,
name: CString,
path: PathBuf,
identity: Identity,
}
impl LeafRecovery {
fn path(parent: &Path, operation: &str) -> PathBuf {
parent.join(format!(".chippytea-recovery-{operation}"))
}
fn create(parent: RawFd, parent_path: &Path, operation: &str) -> Result<Self> {
let path = Self::path(parent_path, operation);
let name = cstr(path.file_name().ok_or("Recovery directory has no name")?)?;
if unsafe { libc::mkdirat(parent, name.as_ptr(), 0o700) } != 0 {
return Err(format!("Cannot reserve recovery directory: {}", ioerr()));
}
let expected = identity_stat(&stat_at(parent, &name)?);
let fd = unsafe {
libc::openat(
parent,
name.as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(format!(
"Cannot safely open recovery directory: {}",
ioerr()
));
}
let file = unsafe { File::from_raw_fd(fd) };
let actual = stat_file(&file)?;
if !same_object(&expected, &identity_stat(&actual))
|| actual.st_uid != unsafe { libc::geteuid() }
|| actual.st_mode as u32 & 0o777 != 0o700
{
return Err("Recovery directory ownership or identity could not be verified.".into());
}
Ok(Self {
file,
name,
path,
identity: expected,
})
}
fn leaf_name(operation: &str, relative: &Path) -> CString {
// The full original path/identity was committed in cleanup_entries before
// mutation. This deterministic name maps a retained leaf back to that row
// without a durable write or an unbounded in-memory map for every file.
let mut hash = blake3::Hasher::new();
hash.update(operation.as_bytes());
hash.update(&[0]);
hash.update(relative.as_os_str().as_bytes());
CString::new(format!("leaf-{}", hash.finalize().to_hex())).expect("hex has no NUL")
}
fn remove_empty(self, parent: RawFd) -> Result<()> {
if !same_object(
&self.identity,
&identity_stat(&stat_at(parent, &self.name)?),
) {
return Err("Recovery directory changed; its contents were preserved.".into());
}
if unsafe { libc::unlinkat(parent, self.name.as_ptr(), libc::AT_REMOVEDIR) } != 0 {
return Err(format!(
"Recovery directory was not empty or could not be removed: {}",
ioerr()
));
}
// self.file closes here, before the caller samples available capacity.
Ok(())
}
}
fn stat_file(file: &File) -> Result<libc::stat> {
let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
if unsafe { libc::fstat(file.as_raw_fd(), stat.as_mut_ptr()) } != 0 {
return Err(ioerr());
}
Ok(unsafe { stat.assume_init() })
}
fn same_after_rename(expected: &Identity, current: &Identity) -> bool {
same_object(expected, current)
&& expected.size == current.size
&& expected.modified_ns == current.modified_ns
}
fn same_link_transition(
before: &safety::EntryMeta,
after: &safety::EntryMeta,
remaining: u64,
) -> bool {
let mut comparable = after.clone();
comparable.identity.changed_ns = before.identity.changed_ns;
comparable.links = before.links;
after.links == remaining && comparable == *before
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum LeafPhase {
BeforeCapture,
AfterCapture,
BeforeUnlink,
AfterUnlink,
}
#[cfg(test)]
type LeafTestHook = Box<dyn FnMut(LeafPhase, RawFd, &CStr)>;
#[cfg(test)]
thread_local! { static LEAF_TEST_HOOK:std::cell::RefCell<Option<LeafTestHook>>=const{std::cell::RefCell::new(None)}; }
fn leaf_hook(phase: LeafPhase, parent: RawFd, name: &CStr) {
#[cfg(test)]
LEAF_TEST_HOOK.with(|hook| {
if let Some(hook) = hook.borrow_mut().as_mut() {
hook(phase, parent, name);
}
});
#[cfg(not(test))]
let _ = (phase, parent, name);
}
struct RemovalContext<'a, 'p> {
identities: CachedStatement<'a>,
operation: &'a str,
recovery: &'a LeafRecovery,
removed: &'a mut Removed,
cancel: &'a AtomicBool,
progress: &'a mut Progress<'p>,
links: LinkRemovals,
}
impl RemovalContext<'_, '_> {
fn remove(&mut self, parent: RawFd, name: &CStr, relative: &Path, root: bool) -> Result<()> {
cancelled(self.cancel)?;
let expected: Identity = self
.identities
.query_row(
params![self.operation, relative.as_os_str().as_bytes()],
|row| Ok(serde_json::from_str(row.get_ref(0)?.as_str()?)),
)
.map_err(|_| "An unreviewed entry appeared. Cleanup stopped.".to_owned())?
.map_err(err)?;
let stat = stat_at(parent, name)?;
let current = safety::EntryMeta::from_stat(&stat);
let group = if current.is_file() {
self.links
.groups
.get(&(current.identity.device, current.identity.inode))
} else {
None
};
let linked = group.is_some();
let matches = if let Some(group) = group {
group.reviewed == expected && group.current == current && current.links > 0
} else if root {
same_object(&expected, ¤t.identity)
} else {
expected == current.identity
};
if !matches {
return Err("An item changed after review. Cleanup stopped.".into());
}
let kind = stat.st_mode as u32 & libc::S_IFMT as u32;
if kind == libc::S_IFDIR as u32 {
let fd = unsafe {
libc::openat(
parent,
name.as_ptr(),
libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(ioerr());
}
let file = unsafe { File::from_raw_fd(fd) };
if !same_object(&expected, &identity_stat(&stat_file(&file)?)) {
return Err("Directory identity changed.".into());
}
each_entry(fd, |child| {
self.remove(
fd,
child,
&relative.join(OsStr::from_bytes(child.to_bytes())),
false,
)
})?;
cancelled(self.cancel)?;
if !same_object(&expected, &identity_stat(&stat_at(parent, name)?)) {
return Err("Directory was replaced during cleanup.".into());
}
// AT_REMOVEDIR cannot remove a replacement regular file/link, and a
// newly populated directory causes ENOTEMPTY rather than data loss.
if unsafe { libc::unlinkat(parent, name.as_ptr(), libc::AT_REMOVEDIR) } != 0 {
return Err(ioerr());
}
self.progress.advance();
Ok(())
} else if kind == libc::S_IFREG as u32 || kind == libc::S_IFLNK as u32 {
if !linked && current.links != 1 {
return Err("A shared hard link appeared. Cleanup stopped.".into());
}
self.remove_leaf(parent, name, relative, ¤t, linked)
} else {
Err("Special files cannot be cleaned.".into())
}
}
fn remove_leaf(
&mut self,
parent: RawFd,
name: &CStr,
relative: &Path,
expected: &safety::EntryMeta,
linked: bool,
) -> Result<()> {
cancelled(self.cancel)?;
let captured = LeafRecovery::leaf_name(self.operation, relative);
leaf_hook(LeafPhase::BeforeCapture, parent, name);
cancelled(self.cancel)?;
if linked && safety::EntryMeta::from_stat(&stat_at(parent, name)?) != *expected {
return Err("A hard-linked item changed before capture. Cleanup stopped.".into());
}
rename_exclusive(parent, name, self.recovery.file.as_raw_fd(), &captured)?;
let mut unlinked = false;
let result = (|| -> Result<()> {
leaf_hook(LeafPhase::AfterCapture, parent, name);
cancelled(self.cancel)?;
let stat = stat_at(self.recovery.file.as_raw_fd(), &captured)?;
let current = safety::EntryMeta::from_stat(&stat);
// Capture may change ctime only. In particular, it cannot explain an
// added outside link, different allocation, permissions or flags.
if !same_link_transition(expected, ¤t, expected.links)
|| current.uid != unsafe { libc::geteuid() }
{
return Err(
"A replacement or changed leaf was captured; it was not deleted.".into(),
);
}
if current.is_dataless() {
return Err(
"The captured leaf became a cloud placeholder; it was not opened or deleted."
.into(),
);
}
let regular = current.is_file();
// Ordinary leaves need no descriptor after unlink. Read their
// private allocation with matching identity metadata in one call;
// both surrounding full stat checks remain authoritative. Linked
// groups still require an fd for the post-unlink transition check.
let direct_private = if regular && !linked && current.links == 1 {
accounting::private_bytes_at(self.recovery.file.as_raw_fd(), &captured, ¤t)?
} else {
None
};
let file = if regular && direct_private.is_none() {
let fd = unsafe {
libc::openat(
self.recovery.file.as_raw_fd(),
captured.as_ptr(),
libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(ioerr());
}
let file = unsafe { File::from_raw_fd(fd) };
if safety::EntryMeta::from_stat(&stat_file(&file)?) != current {
return Err("Captured file changed while opening.".into());
}
Some(file)
} else {
None
};
let last_link = regular && current.links == 1;
let private = if last_link {
direct_private.or_else(|| {
file.as_ref()
.and_then(|file| accounting::private_bytes(file.as_raw_fd()))
})
} else {
None
};
leaf_hook(LeafPhase::BeforeUnlink, parent, name);
cancelled(self.cancel)?;
let latest =
safety::EntryMeta::from_stat(&stat_at(self.recovery.file.as_raw_fd(), &captured)?);
if latest != current {
return Err("Captured leaf changed before removal; it was preserved.".into());
}
if unsafe { libc::unlinkat(self.recovery.file.as_raw_fd(), captured.as_ptr(), 0) } != 0
{
return Err(ioerr());
}
// This name is gone even if the following fstat fails. Record the
// irreversible boundary before running any post-unlink checks.
unlinked = true;
if regular {
self.removed.files += 1;
}
self.progress.advance();
leaf_hook(LeafPhase::AfterUnlink, parent, name);
if linked {
let file = file
.as_ref()
.ok_or("Hard-link capture lost its file descriptor.")?;
let after = safety::EntryMeta::from_stat(&stat_file(file)?);
if !same_link_transition(¤t, &after, current.links - 1) {
return Err("The hard-linked inode changed during removal.".into());
}
let group = self
.links
.groups
.get_mut(&(current.identity.device, current.identity.inode))
.ok_or("Hard-link removal state was lost.")?;
group.current = after;
}
if last_link {
self.removed.private = self.removed.private.saturating_add(private.unwrap_or(0));
self.removed.private_known &= private.is_some();
}
drop(file); // close the final inode fd before capacity observation
Ok(())
})();
match result {
Ok(()) => Ok(()),
Err(reason) if unlinked => {
self.removed.private_known = false;
Err(format!(
"{reason} The captured name was already removed. Cleanup stopped before removing another item."
))
}
Err(reason) => {
let returned =
rename_exclusive(self.recovery.file.as_raw_fd(), &captured, parent, name)
.is_ok();
if returned {
Err(format!(
"{reason} The captured leaf was put back without overwriting another item."
))
} else {
Err(format!(
"{reason} The captured leaf is retained at {} (original relative path: {}). No existing item was overwritten.",
self.recovery
.path
.join(OsStr::from_bytes(captured.to_bytes()))
.display(),
relative.display()
))
}
}
}
}
}
fn rename_exclusive(from: RawFd, name: &CStr, to: RawFd, destination: &CStr) -> Result<()> {
#[cfg(target_os = "macos")]
let result = unsafe {
libc::renameatx_np(
from,
name.as_ptr(),
to,
destination.as_ptr(),
libc::RENAME_EXCL,
)
};
#[cfg(target_os = "linux")]
let result = unsafe {
libc::renameat2(
from,
name.as_ptr(),
to,
destination.as_ptr(),
libc::RENAME_NOREPLACE,
)
};
if result == 0 { Ok(()) } else { Err(ioerr()) }
}
fn parents(path: &Path) -> Result<Vec<(PathBuf, Identity)>> {
let mut result = Vec::new();
let mut current = path.to_path_buf();
loop {
let i = safety::identity(¤t)?;
result.push((current.clone(), i));
if !current.pop() {
break;
}
}
Ok(result)
}
pub fn execute(
store: &mut Store,
root: &Root,
candidate: &Candidate,
operation: &str,
trash: Option<TrashCallback>,
cancel: &AtomicBool,
) -> Result<Receipt> {
execute_with_progress(
store,
root,
candidate,
operation,
trash,
cancel,
|_, _, _| {},
)
}
/// Progress counts filesystem entries, including directories and symbolic links.
/// A total of zero means the preparing traversal has not established it yet.
pub fn execute_with_progress(
store: &mut Store,
root: &Root,
candidate: &Candidate,
operation: &str,
trash: Option<TrashCallback>,
cancel: &AtomicBool,
callback: impl FnMut(CleanupPhase, u64, u64),
) -> Result<Receipt> {
execute_with_duplicate_guard(
store, root, candidate, operation, trash, cancel, None, callback,
)
}
/// Duplicate review adds a retained-file guard; it never changes the ordinary
/// single-path scanner evidence or grants permanent-deletion eligibility.
#[allow(clippy::too_many_arguments)]
pub(crate) fn execute_with_duplicate_guard(
store: &mut Store,
root: &Root,
candidate: &Candidate,
operation: &str,
trash: Option<TrashCallback>,
cancel: &AtomicBool,
duplicate_keeper: Option<&crate::duplicates::Input>,
mut callback: impl FnMut(CleanupPhase, u64, u64),
) -> Result<Receipt> {
let _local_io = safety::LocalOnlyIo::new()?;
let mut progress = Progress::new(&mut callback);
progress.start(CleanupPhase::Checking, 1);
let result = execute_inner(
store,
root,
candidate,
operation,
trash,
cancel,
duplicate_keeper,
&mut progress,
);
progress.finish();
result
}
#[allow(clippy::too_many_arguments)]
fn execute_inner(
store: &mut Store,
root: &Root,
candidate: &Candidate,
operation: &str,
trash: Option<TrashCallback>,
cancel: &AtomicBool,
duplicate_keeper: Option<&crate::duplicates::Input>,
progress: &mut Progress<'_>,
) -> Result<Receipt> {
cancelled(cancel)?;
if operation != "trash" && operation != "permanent" {
return Err("Unsupported cleanup operation.".into());
}
if duplicate_keeper.is_some() && operation != "trash" {
return Err("Duplicate review permits only Move to Trash.".into());
}
if operation == "permanent"
&& (!candidate.eligible_permanent
|| !crate::recommendations::permanent_kind(&candidate.kind))
{
return Err("Permanent cleanup is restricted to recognized developer artifacts.".into());
}
if candidate.blocked_reason.is_some() {
return Err("This item is for inspection only.".into());
}
// Full revalidation below also records the durable manifest. This preflight
// only establishes authorization and identity before creating its receipt.
safety::validate_root(root)?;
if candidate.root_id != root.id
|| candidate.path == root.path
|| !candidate.path.starts_with(&root.path)
{
return Err("The item is outside its authorized location".into());
}
safety::check_scope_policy(root, &candidate.path)?;
if !candidate.suggestion_eligible || candidate.provisional {
return Err("This item is not a completed cleanup suggestion.".into());
}
let current = safety::identity(&candidate.path)?;
if current != candidate.identity || current.device != root.identity.device {
return Err("The item changed since review; scan it again".into());
}
let parent_path = candidate
.path
.parent()
.ok_or("Cannot clean a filesystem root")?;
let parent = open_directory(parent_path)?;
progress.complete();
let name = cstr(candidate.path.file_name().ok_or("Missing filename")?)?;
let id = unique_id();
let stage_name = CString::new(format!(".chippytea-{id}")).unwrap();
let stage = parent_path.join(OsStr::from_bytes(stage_name.to_bytes()));
let recovery_path = LeafRecovery::path(parent_path, &id);
let recovery_detail = format!(
" If interrupted, inspect the staged item at {}. Captured leaves may be preserved at {}. Their original paths and identities remain in this operation's cleanup ledger.",
stage.display(),
recovery_path.display()
);
let mut receipt = Receipt {
id: id.clone(),
path: candidate.path.to_string_lossy().into(),
title: candidate.title.clone(),
operation: operation.into(),
outcome: "prepared".into(),
detail: if operation == "permanent" {
format!("Cleanup prepared; no recovery is credited yet.{recovery_detail}")
} else {
format!(
"Trash prepared. If interrupted, inspect {} and native Trash. No chips are earned.",
stage.display()
)
},
created_at: now(),
reported_bytes: candidate.allocated_bytes,
observed_bytes: 0,
credited_bytes: 0,
coins: 0,
trash_path: None,
can_restore: false,
seq: None,
};
store.prepare_operation(root, candidate, &receipt, &stage)?;
progress.start(CleanupPhase::Preparing, 0);
let preparation = (|| -> Result<u64> {
store.conn.execute_batch("CREATE TABLE IF NOT EXISTS cleanup_entries(operation_id TEXT NOT NULL,path BLOB NOT NULL,identity TEXT NOT NULL,PRIMARY KEY(operation_id,path)); CREATE TABLE IF NOT EXISTS operation_parents(operation_id TEXT PRIMARY KEY,json TEXT NOT NULL);").map_err(err)?;
let transaction = store
.conn
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
.map_err(err)?;
transaction
.execute(
"INSERT INTO operation_parents VALUES(?1,?2)",
params![
id,
serde_json::to_string(&parents(parent_path)?).map_err(err)?
],
)
.map_err(err)?;
let mut entries = 0u64;
{
let mut statement = transaction.prepare_cached(MANIFEST_INSERT).map_err(err)?;
scanner::revalidate_observing(root, candidate, cancel, |entry, _| {
record_manifest_entry(&mut statement, &id, &candidate.path, entry)?;
entries = entries.saturating_add(1);
progress.update(entries);
cancelled(cancel)
})?;
}
if identity_stat(&stat_at(parent.as_raw_fd(), &name)?) != candidate.identity {
return Err("Identity changed before staging.".into());
}
cancelled(cancel)?;
// All paths/identities and parent evidence commit before the first
// rename. Failed observation or cancellation rolls the manifest back.
transaction.commit().map_err(err)?;
Ok(entries)
})();
let entries = match preparation {
Ok(entries) => entries,
Err(reason) => {
receipt.outcome = if cancel.load(Ordering::Relaxed) {
"cancelled"
} else {
"skipped"
}
.into();
receipt.detail = format!(
"Cleanup stopped before staging: {reason}. No file was removed and no chips were earned."
);
store.finish_operation(&receipt, None)?;
return Ok(receipt);
}
};
progress.complete();
if cancel.load(Ordering::Relaxed) {
receipt.outcome = "cancelled".into();
receipt.detail =
"Cancelled before staging. No file was removed and no chips were earned.".into();
store.finish_operation(&receipt, None)?;
return Ok(receipt);
}
if let Err(reason) =
rename_exclusive(parent.as_raw_fd(), &name, parent.as_raw_fd(), &stage_name)
{
receipt.outcome = "skipped".into();
receipt.detail = format!(
"The item could not be staged without overwriting another item: {reason}. No file was removed."
);
store.finish_operation(&receipt, None)?;
return Ok(receipt);
}
progress.start(CleanupPhase::Checking, entries);
let staged_safe = (|| -> Result<(LinkRemovals, Option<crate::duplicates::RetainedFile>)> {
store
.conn
.execute("UPDATE operations SET state='mutating' WHERE id=?1", [&id])
.map_err(err)?;
let staged_identity = identity_stat(&stat_at(parent.as_raw_fd(), &stage_name)?);
let mut links = safety::RegularLinkClosure::default();
let staged = safety::measure_try_observing_with_policy(
&stage,
root.identity.device,
cancel,
measurement_policy(candidate),
|entry, measured| {
links.observe(&entry.meta)?;
progress.update(measured.entries);
Ok(())
},
)?;
if !same_object(&staged_identity, &candidate.identity)
|| staged.fingerprint != candidate.fingerprint
|| staged.unsafe_reason.is_some()
|| staged.pruned
|| staged.errors != 0
{
return Err("The staged artifact no longer matches the reviewed contents.".into());
}
let retained = if let Some(keeper) = duplicate_keeper {
progress.start(
CleanupPhase::Comparing,
candidate.logical_bytes.saturating_mul(2),
);
Some(crate::duplicates::verify_staged(
root,
candidate,
&stage,
keeper,
cancel,
|bytes| progress.update(bytes),
)?)
} else {
None
};
Ok((LinkRemovals::from_closure(links)?, retained))
})();
let (links, retained) = match staged_safe {
Ok(links) => links,
Err(reason) => {
let restored =
rename_exclusive(parent.as_raw_fd(), &stage_name, parent.as_raw_fd(), &name)
.is_ok();
receipt.outcome = if cancel.load(Ordering::Relaxed) {
"cancelled"
} else {
"skipped"
}
.into();
receipt.detail = if restored {
"Staged contents could not be verified; the original item was put back. Refresh to review again. No chips were earned.".into()
} else {
format!(
"Staged contents could not be verified. Inspect staged item at {}. No credit.",
stage.display()
)
};
receipt.detail.push_str(&format!(" {reason}"));
store.finish_operation(&receipt, None)?;
return Ok(receipt);
}
};
progress.complete();
if operation == "trash" {
progress.start(CleanupPhase::Removing, entries);
let outcome = (|| -> Result<Identity> {
let callback = trash
.ok_or("Native Trash is unavailable. Permanent deletion was not attempted.")?;
let input = cstr(stage.as_os_str())?;
let mut output = vec![0i8; 16384];
cancelled(cancel)?;
if let Some(keeper) = &retained {