@ship.zone/runner 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1784 @@
1
+ #[cfg(not(unix))]
2
+ compile_error!("runnerworkspace requires a Unix platform");
3
+
4
+ use serde::Serialize;
5
+ use std::ffi::CString;
6
+ use std::ffi::OsString;
7
+ use std::fmt;
8
+ use std::fs::{self, Metadata, OpenOptions};
9
+ use std::io::{self, Read, Write};
10
+ use std::os::unix::ffi::{OsStrExt, OsStringExt};
11
+ use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
12
+ use std::path::{Path, PathBuf};
13
+ use std::sync::atomic::{AtomicBool, Ordering};
14
+ use std::time::Duration;
15
+
16
+ const COPY_BUFFER_SIZE: usize = 64 * 1024;
17
+ const MAXIMUM_TRAVERSAL_DEPTH: usize = 256;
18
+ const HOLD_PARK_INTERVAL: Duration = Duration::from_millis(100);
19
+ const RESERVE_FILE_NAME: &str = ".runnerworkspace-reserve";
20
+ const DESTINATION_CLEANUP_FAILURE: &str = "unable to clean destination after failure";
21
+ const RESERVE_CLEANUP_FAILURE: &str = "unable to clean volume after reserve failure";
22
+
23
+ static HOLD_TERMINATION_REQUESTED: AtomicBool = AtomicBool::new(false);
24
+
25
+ type Result<T> = std::result::Result<T, Error>;
26
+
27
+ #[derive(Debug, Clone, Copy, Eq, PartialEq)]
28
+ pub struct Error {
29
+ message: &'static str,
30
+ }
31
+
32
+ impl Error {
33
+ const fn new(message: &'static str) -> Self {
34
+ Self { message }
35
+ }
36
+ }
37
+
38
+ impl fmt::Display for Error {
39
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
40
+ formatter.write_str(self.message)
41
+ }
42
+ }
43
+
44
+ impl std::error::Error for Error {}
45
+
46
+ #[derive(Serialize)]
47
+ struct ProbeResult {
48
+ version: &'static str,
49
+ os: &'static str,
50
+ architecture: &'static str,
51
+ }
52
+
53
+ #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
54
+ #[serde(rename_all = "camelCase")]
55
+ struct FilesystemResult {
56
+ block_size: u64,
57
+ available_blocks: u64,
58
+ available_inodes: u64,
59
+ }
60
+
61
+ #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
62
+ struct Counts {
63
+ bytes: u64,
64
+ entries: u64,
65
+ }
66
+
67
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
68
+ struct Ownership {
69
+ uid: u32,
70
+ gid: u32,
71
+ }
72
+
73
+ #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
74
+ #[serde(rename_all = "camelCase")]
75
+ struct ReserveResult {
76
+ bytes: u64,
77
+ entries: u64,
78
+ workspace_bytes: u64,
79
+ workspace_entries: u64,
80
+ reserve_bytes: u64,
81
+ }
82
+
83
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
84
+ struct Snapshot {
85
+ device: u64,
86
+ inode: u64,
87
+ mode: u32,
88
+ links: u64,
89
+ length: u64,
90
+ modified_seconds: i64,
91
+ modified_nanoseconds: i64,
92
+ changed_seconds: i64,
93
+ changed_nanoseconds: i64,
94
+ }
95
+
96
+ impl Snapshot {
97
+ fn from_metadata(metadata: &Metadata) -> Self {
98
+ Self {
99
+ device: metadata.dev(),
100
+ inode: metadata.ino(),
101
+ mode: metadata.mode(),
102
+ links: metadata.nlink(),
103
+ length: metadata.len(),
104
+ modified_seconds: metadata.mtime(),
105
+ modified_nanoseconds: metadata.mtime_nsec(),
106
+ changed_seconds: metadata.ctime(),
107
+ changed_nanoseconds: metadata.ctime_nsec(),
108
+ }
109
+ }
110
+ }
111
+
112
+ #[derive(Debug)]
113
+ struct Budget {
114
+ maximum_bytes: u64,
115
+ maximum_entries: u64,
116
+ counts: Counts,
117
+ }
118
+
119
+ impl Budget {
120
+ fn new(maximum_bytes: u64, maximum_entries: u64) -> Self {
121
+ Self {
122
+ maximum_bytes,
123
+ maximum_entries,
124
+ counts: Counts::default(),
125
+ }
126
+ }
127
+
128
+ fn account_entry(&mut self) -> Result<()> {
129
+ let entries = self
130
+ .counts
131
+ .entries
132
+ .checked_add(1)
133
+ .ok_or_else(|| Error::new("entry count overflow"))?;
134
+ if entries > self.maximum_entries {
135
+ return Err(Error::new("maximum entry count exceeded"));
136
+ }
137
+ self.counts.entries = entries;
138
+ Ok(())
139
+ }
140
+
141
+ fn account_file(&mut self, length: u64) -> Result<()> {
142
+ let entries = self
143
+ .counts
144
+ .entries
145
+ .checked_add(1)
146
+ .ok_or_else(|| Error::new("entry count overflow"))?;
147
+ let bytes = self
148
+ .counts
149
+ .bytes
150
+ .checked_add(length)
151
+ .ok_or_else(|| Error::new("byte count overflow"))?;
152
+ if entries > self.maximum_entries {
153
+ return Err(Error::new("maximum entry count exceeded"));
154
+ }
155
+ if bytes > self.maximum_bytes {
156
+ return Err(Error::new("maximum byte count exceeded"));
157
+ }
158
+ self.counts.entries = entries;
159
+ self.counts.bytes = bytes;
160
+ Ok(())
161
+ }
162
+
163
+ fn remaining_entries(&self) -> u64 {
164
+ self.maximum_entries - self.counts.entries
165
+ }
166
+ }
167
+
168
+ struct Traversal {
169
+ source_root: PathBuf,
170
+ destination_root: Option<PathBuf>,
171
+ source_device: u64,
172
+ budget: Budget,
173
+ }
174
+
175
+ impl Traversal {
176
+ fn new(
177
+ source_root: PathBuf,
178
+ destination_root: Option<PathBuf>,
179
+ maximum_bytes: u64,
180
+ maximum_entries: u64,
181
+ ) -> Result<Self> {
182
+ let metadata = metadata_no_follow(&source_root, "unable to inspect source root")?;
183
+ if !metadata.file_type().is_dir() {
184
+ return Err(Error::new("source root must be a directory"));
185
+ }
186
+ Ok(Self {
187
+ source_root,
188
+ destination_root,
189
+ source_device: metadata.dev(),
190
+ budget: Budget::new(maximum_bytes, maximum_entries),
191
+ })
192
+ }
193
+
194
+ fn walk_root(&mut self) -> Result<()> {
195
+ self.walk_directory(Path::new(""), Path::new(""), 0)
196
+ }
197
+
198
+ fn walk_directory(
199
+ &mut self,
200
+ relative: &Path,
201
+ symlink_scope: &Path,
202
+ depth: usize,
203
+ ) -> Result<()> {
204
+ require_traversal_depth(depth)?;
205
+ let source = self.source_root.join(relative);
206
+ let metadata = metadata_no_follow(&source, "unable to inspect source directory")?;
207
+ if !metadata.file_type().is_dir() {
208
+ return Err(Error::new("source directory changed type"));
209
+ }
210
+ self.require_source_device(&metadata)?;
211
+ ensure_directory_beneath(&source, &self.source_root)?;
212
+ let snapshot = Snapshot::from_metadata(&metadata);
213
+
214
+ for name in sorted_child_names(&source, self.budget.remaining_entries())? {
215
+ let child_depth = depth
216
+ .checked_add(1)
217
+ .ok_or_else(|| Error::new("maximum traversal depth exceeded"))?;
218
+ require_traversal_depth(child_depth)?;
219
+ let child_relative = relative.join(name);
220
+ self.process_node(&child_relative, symlink_scope, child_depth)?;
221
+ }
222
+
223
+ require_unchanged(
224
+ &source,
225
+ snapshot,
226
+ "source directory changed during traversal",
227
+ )
228
+ }
229
+
230
+ fn process_node(&mut self, relative: &Path, symlink_scope: &Path, depth: usize) -> Result<()> {
231
+ require_traversal_depth(depth)?;
232
+ let source = self.source_root.join(relative);
233
+ if !source.starts_with(&self.source_root) {
234
+ return Err(Error::new("source path escaped its root"));
235
+ }
236
+ let metadata = metadata_no_follow(&source, "unable to inspect source entry")?;
237
+ self.require_source_device(&metadata)?;
238
+ let file_type = metadata.file_type();
239
+
240
+ if file_type.is_dir() {
241
+ self.budget.account_entry()?;
242
+ self.create_destination_directory(relative)?;
243
+ return self.walk_directory(relative, symlink_scope, depth);
244
+ }
245
+
246
+ if file_type.is_file() {
247
+ if metadata.nlink() > 1 {
248
+ return Err(Error::new("hardlinked regular files are not allowed"));
249
+ }
250
+ self.budget.account_file(metadata.len())?;
251
+ if self.destination_root.is_some() {
252
+ self.copy_regular_file(relative, &metadata)?;
253
+ } else {
254
+ require_unchanged(
255
+ &source,
256
+ Snapshot::from_metadata(&metadata),
257
+ "source file changed during traversal",
258
+ )?;
259
+ }
260
+ return Ok(());
261
+ }
262
+
263
+ if file_type.is_symlink() {
264
+ let snapshot = Snapshot::from_metadata(&metadata);
265
+ let target =
266
+ fs::read_link(&source).map_err(|_| Error::new("unable to read source symlink"))?;
267
+ validate_symlink(relative, &target, symlink_scope)?;
268
+ require_unchanged(&source, snapshot, "source symlink changed during traversal")?;
269
+ self.budget.account_entry()?;
270
+ self.create_destination_symlink(relative, &target)?;
271
+ return Ok(());
272
+ }
273
+
274
+ Err(Error::new("special filesystem entries are not allowed"))
275
+ }
276
+
277
+ fn process_export_branch(
278
+ &mut self,
279
+ relative: &Path,
280
+ node: &SelectionNode,
281
+ depth: usize,
282
+ ) -> Result<()> {
283
+ require_traversal_depth(depth)?;
284
+ if node.selected {
285
+ let source = self.source_root.join(relative);
286
+ let metadata = metadata_no_follow(&source, "unable to inspect selection path")?;
287
+ let symlink_scope = if metadata.file_type().is_dir() {
288
+ relative
289
+ } else {
290
+ relative.parent().unwrap_or_else(|| Path::new(""))
291
+ };
292
+ return self.process_node(relative, symlink_scope, depth);
293
+ }
294
+
295
+ let source = self.source_root.join(relative);
296
+ let metadata = metadata_no_follow(&source, "unable to inspect selection path")?;
297
+ self.require_source_device(&metadata)?;
298
+ if !metadata.file_type().is_dir() {
299
+ return Err(Error::new("selection parent must be a directory"));
300
+ }
301
+ let snapshot = Snapshot::from_metadata(&metadata);
302
+ ensure_directory_beneath(&source, &self.source_root)?;
303
+ self.budget.account_entry()?;
304
+ self.create_destination_directory(relative)?;
305
+
306
+ for (name, child) in &node.children {
307
+ let child_depth = depth
308
+ .checked_add(1)
309
+ .ok_or_else(|| Error::new("maximum traversal depth exceeded"))?;
310
+ require_traversal_depth(child_depth)?;
311
+ self.process_export_branch(&relative.join(name), child, child_depth)?;
312
+ }
313
+
314
+ require_unchanged(
315
+ &source,
316
+ snapshot,
317
+ "selection parent changed during traversal",
318
+ )
319
+ }
320
+
321
+ fn require_source_device(&self, metadata: &Metadata) -> Result<()> {
322
+ if metadata.dev() != self.source_device {
323
+ return Err(Error::new("filesystem boundary crossing is not allowed"));
324
+ }
325
+ Ok(())
326
+ }
327
+
328
+ fn destination_path(&self, relative: &Path) -> Result<PathBuf> {
329
+ let root = self
330
+ .destination_root
331
+ .as_ref()
332
+ .ok_or_else(|| Error::new("destination is unavailable"))?;
333
+ let destination = root.join(relative);
334
+ if !destination.starts_with(root) {
335
+ return Err(Error::new("destination path escaped its root"));
336
+ }
337
+ Ok(destination)
338
+ }
339
+
340
+ fn create_destination_directory(&self, relative: &Path) -> Result<()> {
341
+ let Some(root) = self.destination_root.as_ref() else {
342
+ return Ok(());
343
+ };
344
+ let destination = self.destination_path(relative)?;
345
+ ensure_destination_parent(&destination, root)?;
346
+ fs::create_dir(&destination)
347
+ .map_err(|_| Error::new("unable to create destination directory"))?;
348
+ fs::set_permissions(&destination, fs::Permissions::from_mode(0o755))
349
+ .map_err(|_| Error::new("unable to set destination directory permissions"))?;
350
+ ensure_directory_beneath(&destination, root)
351
+ }
352
+
353
+ fn create_destination_symlink(&self, relative: &Path, target: &Path) -> Result<()> {
354
+ let Some(root) = self.destination_root.as_ref() else {
355
+ return Ok(());
356
+ };
357
+ let destination = self.destination_path(relative)?;
358
+ ensure_destination_parent(&destination, root)?;
359
+ std::os::unix::fs::symlink(target, destination)
360
+ .map_err(|_| Error::new("unable to create destination symlink"))
361
+ }
362
+
363
+ fn copy_regular_file(&self, relative: &Path, initial_metadata: &Metadata) -> Result<()> {
364
+ let source = self.source_root.join(relative);
365
+ let initial_snapshot = Snapshot::from_metadata(initial_metadata);
366
+ let mut source_file = OpenOptions::new()
367
+ .read(true)
368
+ .custom_flags(nix::libc::O_CLOEXEC | nix::libc::O_NOFOLLOW)
369
+ .open(&source)
370
+ .map_err(|_| Error::new("unable to open source file without following links"))?;
371
+ let opened_metadata = source_file
372
+ .metadata()
373
+ .map_err(|_| Error::new("unable to inspect opened source file"))?;
374
+ if !opened_metadata.file_type().is_file()
375
+ || Snapshot::from_metadata(&opened_metadata) != initial_snapshot
376
+ {
377
+ return Err(Error::new("source file changed before copy"));
378
+ }
379
+
380
+ let root = self
381
+ .destination_root
382
+ .as_ref()
383
+ .ok_or_else(|| Error::new("destination is unavailable"))?;
384
+ let destination = self.destination_path(relative)?;
385
+ ensure_destination_parent(&destination, root)?;
386
+ let destination_mode = if initial_metadata.mode() & 0o111 == 0 {
387
+ 0o644
388
+ } else {
389
+ 0o755
390
+ };
391
+ let mut destination_file = OpenOptions::new()
392
+ .write(true)
393
+ .create_new(true)
394
+ .mode(destination_mode)
395
+ .open(destination)
396
+ .map_err(|_| Error::new("unable to create destination file"))?;
397
+
398
+ let mut remaining = initial_metadata.len();
399
+ let mut buffer = [0_u8; COPY_BUFFER_SIZE];
400
+ while remaining > 0 {
401
+ let read_limit = remaining.min(buffer.len() as u64) as usize;
402
+ let bytes_read = source_file
403
+ .read(&mut buffer[..read_limit])
404
+ .map_err(|_| Error::new("unable to read source file"))?;
405
+ if bytes_read == 0 {
406
+ return Err(Error::new("source file became shorter during copy"));
407
+ }
408
+ destination_file
409
+ .write_all(&buffer[..bytes_read])
410
+ .map_err(|_| Error::new("unable to write destination file"))?;
411
+ remaining -= bytes_read as u64;
412
+ }
413
+
414
+ if source_file
415
+ .read(&mut buffer[..1])
416
+ .map_err(|_| Error::new("unable to finish reading source file"))?
417
+ != 0
418
+ {
419
+ return Err(Error::new("source file became longer during copy"));
420
+ }
421
+ destination_file
422
+ .flush()
423
+ .map_err(|_| Error::new("unable to flush destination file"))?;
424
+ destination_file
425
+ .set_permissions(fs::Permissions::from_mode(destination_mode))
426
+ .map_err(|_| Error::new("unable to set destination file permissions"))?;
427
+
428
+ let final_opened_metadata = source_file
429
+ .metadata()
430
+ .map_err(|_| Error::new("unable to re-inspect opened source file"))?;
431
+ if Snapshot::from_metadata(&final_opened_metadata) != initial_snapshot {
432
+ return Err(Error::new("source file changed during copy"));
433
+ }
434
+ require_unchanged(&source, initial_snapshot, "source file changed during copy")
435
+ }
436
+ }
437
+
438
+ #[derive(Debug, Default)]
439
+ struct SelectionNode {
440
+ selected: bool,
441
+ children: Vec<(OsString, SelectionNode)>,
442
+ }
443
+
444
+ impl SelectionNode {
445
+ fn insert(&mut self, components: &[OsString]) -> Result<()> {
446
+ require_traversal_depth(components.len())?;
447
+ if components.is_empty() {
448
+ self.selected = true;
449
+ return Ok(());
450
+ }
451
+ let name = &components[0];
452
+ let index = self
453
+ .children
454
+ .iter()
455
+ .position(|(existing, _)| existing == name)
456
+ .unwrap_or_else(|| {
457
+ self.children.push((name.clone(), SelectionNode::default()));
458
+ self.children.len() - 1
459
+ });
460
+ self.children[index].1.insert(&components[1..])?;
461
+ self.children
462
+ .sort_by(|left, right| left.0.as_bytes().cmp(right.0.as_bytes()));
463
+ Ok(())
464
+ }
465
+ }
466
+
467
+ #[derive(Debug)]
468
+ struct ValidatedSelection {
469
+ path: PathBuf,
470
+ components: Vec<OsString>,
471
+ }
472
+
473
+ struct Options {
474
+ values: Vec<(String, OsString)>,
475
+ }
476
+
477
+ impl Options {
478
+ fn parse<I>(arguments: I) -> Result<Self>
479
+ where
480
+ I: IntoIterator<Item = OsString>,
481
+ {
482
+ let mut iterator = arguments.into_iter();
483
+ let mut values = Vec::new();
484
+ while let Some(option) = iterator.next() {
485
+ let option = option
486
+ .to_str()
487
+ .ok_or_else(|| Error::new("option names must be valid UTF-8"))?;
488
+ if !option.starts_with("--") || option.len() == 2 {
489
+ return Err(Error::new("invalid command option"));
490
+ }
491
+ let value = iterator
492
+ .next()
493
+ .ok_or_else(|| Error::new("command option is missing a value"))?;
494
+ values.push((option.to_owned(), value));
495
+ }
496
+ Ok(Self { values })
497
+ }
498
+
499
+ fn take_one(&mut self, name: &str) -> Result<OsString> {
500
+ let Some(index) = self.values.iter().position(|(key, _)| key == name) else {
501
+ return Err(Error::new("required command option is missing"));
502
+ };
503
+ if self.values.iter().filter(|(key, _)| key == name).count() != 1 {
504
+ return Err(Error::new("command option may not be repeated"));
505
+ }
506
+ Ok(self.values.remove(index).1)
507
+ }
508
+
509
+ fn take_many(&mut self, name: &str) -> Vec<OsString> {
510
+ let mut matches = Vec::new();
511
+ let mut remaining = Vec::new();
512
+ for (key, value) in self.values.drain(..) {
513
+ if key == name {
514
+ matches.push(value);
515
+ } else {
516
+ remaining.push((key, value));
517
+ }
518
+ }
519
+ self.values = remaining;
520
+ matches
521
+ }
522
+
523
+ fn finish(self) -> Result<()> {
524
+ if self.values.is_empty() {
525
+ Ok(())
526
+ } else {
527
+ Err(Error::new("unknown command option"))
528
+ }
529
+ }
530
+ }
531
+
532
+ pub fn run<I>(arguments: I) -> Result<()>
533
+ where
534
+ I: IntoIterator<Item = OsString>,
535
+ {
536
+ let mut iterator = arguments.into_iter();
537
+ let command = iterator
538
+ .next()
539
+ .ok_or_else(|| Error::new("command is required"))?;
540
+ let command = command
541
+ .to_str()
542
+ .ok_or_else(|| Error::new("command must be valid UTF-8"))?;
543
+
544
+ match command {
545
+ "probe" => {
546
+ if iterator.next().is_some() {
547
+ return Err(Error::new("probe does not accept options"));
548
+ }
549
+ emit_json(&ProbeResult {
550
+ version: env!("CARGO_PKG_VERSION"),
551
+ os: std::env::consts::OS,
552
+ architecture: std::env::consts::ARCH,
553
+ })
554
+ }
555
+ "hold" => {
556
+ if iterator.next().is_some() {
557
+ return Err(Error::new("hold does not accept options"));
558
+ }
559
+ hold()
560
+ }
561
+ "filesystem" => {
562
+ let mut options = Options::parse(iterator)?;
563
+ let path = PathBuf::from(options.take_one("--path")?);
564
+ options.finish()?;
565
+ emit_json(&filesystem(&path)?)
566
+ }
567
+ "import" => {
568
+ let mut options = Options::parse(iterator)?;
569
+ let source = PathBuf::from(options.take_one("--source")?);
570
+ let workspace = PathBuf::from(options.take_one("--workspace")?);
571
+ let maximum_bytes = parse_u64(options.take_one("--maximum-bytes")?)?;
572
+ let maximum_entries = parse_u64(options.take_one("--maximum-entries")?)?;
573
+ let ownership = Ownership {
574
+ uid: parse_u32(options.take_one("--destination-uid")?)?,
575
+ gid: parse_u32(options.take_one("--destination-gid")?)?,
576
+ };
577
+ options.finish()?;
578
+ emit_json(&import_tree_owned(
579
+ &source,
580
+ &workspace,
581
+ maximum_bytes,
582
+ maximum_entries,
583
+ ownership,
584
+ )?)
585
+ }
586
+ "export" => {
587
+ let mut options = Options::parse(iterator)?;
588
+ let workspace = PathBuf::from(options.take_one("--workspace")?);
589
+ let destination = PathBuf::from(options.take_one("--destination")?);
590
+ let selections = options
591
+ .take_many("--selection")
592
+ .into_iter()
593
+ .map(PathBuf::from)
594
+ .collect::<Vec<_>>();
595
+ let maximum_bytes = parse_u64(options.take_one("--maximum-bytes")?)?;
596
+ let maximum_entries = parse_u64(options.take_one("--maximum-entries")?)?;
597
+ options.finish()?;
598
+ emit_json(&export_tree_to_existing_owner(
599
+ &workspace,
600
+ &destination,
601
+ &selections,
602
+ maximum_bytes,
603
+ maximum_entries,
604
+ )?)
605
+ }
606
+ "measure" => {
607
+ let mut options = Options::parse(iterator)?;
608
+ let workspace = PathBuf::from(options.take_one("--workspace")?);
609
+ let maximum_bytes = parse_u64(options.take_one("--maximum-bytes")?)?;
610
+ let maximum_entries = parse_u64(options.take_one("--maximum-entries")?)?;
611
+ options.finish()?;
612
+ emit_json(&measure_tree(&workspace, maximum_bytes, maximum_entries)?)
613
+ }
614
+ "reserve" => {
615
+ let mut options = Options::parse(iterator)?;
616
+ let volume = PathBuf::from(options.take_one("--volume")?);
617
+ let workspace_bytes = parse_u64(options.take_one("--workspace-bytes")?)?;
618
+ let workspace_entries = parse_u64(options.take_one("--workspace-entries")?)?;
619
+ let reserve_bytes = parse_u64(options.take_one("--reserve-bytes")?)?;
620
+ let ownership = Ownership {
621
+ uid: parse_u32(options.take_one("--workspace-uid")?)?,
622
+ gid: parse_u32(options.take_one("--workspace-gid")?)?,
623
+ };
624
+ options.finish()?;
625
+ emit_json(&reserve_volume_owned(
626
+ &volume,
627
+ workspace_bytes,
628
+ workspace_entries,
629
+ reserve_bytes,
630
+ ownership,
631
+ )?)
632
+ }
633
+ _ => Err(Error::new("unknown command")),
634
+ }
635
+ }
636
+
637
+ fn emit_json<T: Serialize>(value: &T) -> Result<()> {
638
+ let stdout = io::stdout();
639
+ let mut output = stdout.lock();
640
+ serde_json::to_writer(&mut output, value)
641
+ .map_err(|_| Error::new("unable to serialize command result"))?;
642
+ output
643
+ .write_all(b"\n")
644
+ .map_err(|_| Error::new("unable to write command result"))?;
645
+ output
646
+ .flush()
647
+ .map_err(|_| Error::new("unable to flush command result"))
648
+ }
649
+
650
+ fn parse_u64(value: OsString) -> Result<u64> {
651
+ value
652
+ .to_str()
653
+ .ok_or_else(|| Error::new("numeric option must be valid UTF-8"))?
654
+ .parse::<u64>()
655
+ .map_err(|_| Error::new("numeric option must be an unsigned 64-bit integer"))
656
+ }
657
+
658
+ fn parse_u32(value: OsString) -> Result<u32> {
659
+ let value = value
660
+ .to_str()
661
+ .ok_or_else(|| Error::new("numeric option must be valid UTF-8"))?
662
+ .parse::<u32>()
663
+ .map_err(|_| Error::new("numeric option must be an unsigned 32-bit integer"))?;
664
+ if value == u32::MAX {
665
+ Err(Error::new(
666
+ "numeric owner must not use the unchanged-owner sentinel",
667
+ ))
668
+ } else {
669
+ Ok(value)
670
+ }
671
+ }
672
+
673
+ extern "C" fn hold_signal_handler(_signal: nix::libc::c_int) {
674
+ request_termination(&HOLD_TERMINATION_REQUESTED);
675
+ }
676
+
677
+ fn request_termination(termination_requested: &AtomicBool) {
678
+ termination_requested.store(true, Ordering::Relaxed);
679
+ }
680
+
681
+ fn hold() -> Result<()> {
682
+ use nix::sys::signal::{self, SaFlags, SigAction, SigHandler, SigSet, Signal};
683
+
684
+ HOLD_TERMINATION_REQUESTED.store(false, Ordering::Relaxed);
685
+ let action = SigAction::new(
686
+ SigHandler::Handler(hold_signal_handler),
687
+ SaFlags::empty(),
688
+ SigSet::empty(),
689
+ );
690
+ // The handler only performs a lock-free atomic store. This process runs one hold command and
691
+ // exits immediately afterward, so process-global handler ownership cannot overlap another use.
692
+ unsafe {
693
+ signal::sigaction(Signal::SIGTERM, &action)
694
+ .map_err(|_| Error::new("unable to install SIGTERM handler"))?;
695
+ signal::sigaction(Signal::SIGINT, &action)
696
+ .map_err(|_| Error::new("unable to install SIGINT handler"))?;
697
+ }
698
+ wait_for_termination(&HOLD_TERMINATION_REQUESTED);
699
+ Ok(())
700
+ }
701
+
702
+ fn wait_for_termination(termination_requested: &AtomicBool) {
703
+ while !termination_requested.load(Ordering::Relaxed) {
704
+ std::thread::park_timeout(HOLD_PARK_INTERVAL);
705
+ }
706
+ }
707
+
708
+ #[cfg(test)]
709
+ fn import_tree(
710
+ source: &Path,
711
+ workspace: &Path,
712
+ maximum_bytes: u64,
713
+ maximum_entries: u64,
714
+ ) -> Result<Counts> {
715
+ import_tree_inner(source, workspace, maximum_bytes, maximum_entries, None)
716
+ }
717
+
718
+ fn import_tree_owned(
719
+ source: &Path,
720
+ workspace: &Path,
721
+ maximum_bytes: u64,
722
+ maximum_entries: u64,
723
+ ownership: Ownership,
724
+ ) -> Result<Counts> {
725
+ import_tree_inner(
726
+ source,
727
+ workspace,
728
+ maximum_bytes,
729
+ maximum_entries,
730
+ Some(ownership),
731
+ )
732
+ }
733
+
734
+ fn import_tree_inner(
735
+ source: &Path,
736
+ workspace: &Path,
737
+ maximum_bytes: u64,
738
+ maximum_entries: u64,
739
+ ownership: Option<Ownership>,
740
+ ) -> Result<Counts> {
741
+ let source = canonical_existing_directory(source, "source root")?;
742
+ let workspace = prepare_empty_directory(workspace)?;
743
+ let result = (|| {
744
+ reject_overlapping_roots(&source, &workspace)?;
745
+ let mut traversal = Traversal::new(
746
+ source,
747
+ Some(workspace.clone()),
748
+ maximum_bytes,
749
+ maximum_entries,
750
+ )?;
751
+ traversal.walk_root()?;
752
+ if let Some(ownership) = ownership {
753
+ set_tree_owner(&workspace, ownership)?;
754
+ }
755
+ Ok(traversal.budget.counts)
756
+ })();
757
+ finish_destination_operation(&workspace, result)
758
+ }
759
+
760
+ fn measure_tree(workspace: &Path, maximum_bytes: u64, maximum_entries: u64) -> Result<Counts> {
761
+ let workspace = canonical_existing_directory(workspace, "workspace root")?;
762
+ let mut traversal = Traversal::new(workspace, None, maximum_bytes, maximum_entries)?;
763
+ traversal.walk_root()?;
764
+ Ok(traversal.budget.counts)
765
+ }
766
+
767
+ #[cfg(test)]
768
+ fn export_tree(
769
+ workspace: &Path,
770
+ destination: &Path,
771
+ selections: &[PathBuf],
772
+ maximum_bytes: u64,
773
+ maximum_entries: u64,
774
+ ) -> Result<Counts> {
775
+ export_tree_inner(
776
+ workspace,
777
+ destination,
778
+ selections,
779
+ maximum_bytes,
780
+ maximum_entries,
781
+ None,
782
+ )
783
+ }
784
+
785
+ fn export_tree_inner(
786
+ workspace: &Path,
787
+ destination: &Path,
788
+ selections: &[PathBuf],
789
+ maximum_bytes: u64,
790
+ maximum_entries: u64,
791
+ ownership: Option<Ownership>,
792
+ ) -> Result<Counts> {
793
+ let validated = validate_selections(selections)?;
794
+ let workspace = canonical_existing_directory(workspace, "workspace root")?;
795
+ let destination = prepare_empty_directory(destination)?;
796
+ let result = (|| {
797
+ reject_overlapping_roots(&workspace, &destination)?;
798
+
799
+ let mut root = SelectionNode::default();
800
+ for selection in validated {
801
+ root.insert(&selection.components)?;
802
+ }
803
+
804
+ let root_metadata = metadata_no_follow(&workspace, "unable to inspect workspace root")?;
805
+ let root_snapshot = Snapshot::from_metadata(&root_metadata);
806
+ let mut traversal = Traversal::new(
807
+ workspace.clone(),
808
+ Some(destination.clone()),
809
+ maximum_bytes,
810
+ maximum_entries,
811
+ )?;
812
+ for (name, child) in &root.children {
813
+ traversal.process_export_branch(Path::new(name), child, 1)?;
814
+ }
815
+ require_unchanged(
816
+ &workspace,
817
+ root_snapshot,
818
+ "workspace root changed during export",
819
+ )?;
820
+ if let Some(ownership) = ownership {
821
+ set_tree_owner(&destination, ownership)?;
822
+ }
823
+ Ok(traversal.budget.counts)
824
+ })();
825
+ finish_destination_operation(&destination, result)
826
+ }
827
+
828
+ fn export_tree_to_existing_owner(
829
+ workspace: &Path,
830
+ destination: &Path,
831
+ selections: &[PathBuf],
832
+ maximum_bytes: u64,
833
+ maximum_entries: u64,
834
+ ) -> Result<Counts> {
835
+ let destination_metadata = metadata_no_follow(destination, "unable to inspect export root")?;
836
+ if !destination_metadata.file_type().is_dir() {
837
+ return Err(Error::new("export root must be a directory"));
838
+ }
839
+ let ownership = Ownership {
840
+ uid: destination_metadata.uid(),
841
+ gid: destination_metadata.gid(),
842
+ };
843
+ export_tree_inner(
844
+ workspace,
845
+ destination,
846
+ selections,
847
+ maximum_bytes,
848
+ maximum_entries,
849
+ Some(ownership),
850
+ )
851
+ }
852
+
853
+ fn validate_selections(selections: &[PathBuf]) -> Result<Vec<ValidatedSelection>> {
854
+ if selections.is_empty() {
855
+ return Err(Error::new("at least one selection is required"));
856
+ }
857
+ let mut validated = Vec::with_capacity(selections.len());
858
+ for selection in selections {
859
+ let bytes = selection.as_os_str().as_bytes();
860
+ if bytes.is_empty() || bytes[0] == b'/' || bytes.contains(&0) || bytes.contains(&b'\\') {
861
+ return Err(Error::new("selection is not a safe relative path"));
862
+ }
863
+ let mut components = Vec::new();
864
+ for component in bytes.split(|byte| *byte == b'/') {
865
+ if component.is_empty() || component == b"." || component == b".." {
866
+ return Err(Error::new("selection contains an unsafe path segment"));
867
+ }
868
+ components.push(OsString::from_vec(component.to_vec()));
869
+ }
870
+ require_traversal_depth(components.len())?;
871
+ validated.push(ValidatedSelection {
872
+ path: selection.clone(),
873
+ components,
874
+ });
875
+ }
876
+
877
+ validated.sort_by(|left, right| {
878
+ left.path
879
+ .as_os_str()
880
+ .as_bytes()
881
+ .cmp(right.path.as_os_str().as_bytes())
882
+ });
883
+ for left_index in 0..validated.len() {
884
+ for right_index in (left_index + 1)..validated.len() {
885
+ let left = &validated[left_index].components;
886
+ let right = &validated[right_index].components;
887
+ if component_prefix(left, right) || component_prefix(right, left) {
888
+ return Err(Error::new("selections must be unique and non-overlapping"));
889
+ }
890
+ }
891
+ }
892
+ Ok(validated)
893
+ }
894
+
895
+ fn component_prefix(left: &[OsString], right: &[OsString]) -> bool {
896
+ left.len() <= right.len()
897
+ && left
898
+ .iter()
899
+ .zip(right.iter())
900
+ .all(|(left_component, right_component)| left_component == right_component)
901
+ }
902
+
903
+ fn validate_symlink(relative: &Path, target: &Path, scope: &Path) -> Result<()> {
904
+ let target_bytes = target.as_os_str().as_bytes();
905
+ if target_bytes.is_empty() || target_bytes[0] == b'/' || target_bytes.contains(&0) {
906
+ return Err(Error::new("symlink target must be a safe relative path"));
907
+ }
908
+
909
+ let mut resolved = path_components(relative.parent().unwrap_or_else(|| Path::new("")));
910
+ let minimum_depth = if scope.as_os_str().is_empty() {
911
+ 0
912
+ } else {
913
+ path_components(scope).len()
914
+ };
915
+ if !component_bytes_prefix(&path_components(scope), &resolved) {
916
+ return Err(Error::new("symlink is outside its allowed root"));
917
+ }
918
+
919
+ for component in target_bytes.split(|byte| *byte == b'/') {
920
+ if component.is_empty() || component == b"." {
921
+ continue;
922
+ }
923
+ if component == b".." {
924
+ if resolved.len() == minimum_depth {
925
+ return Err(Error::new("symlink target escapes its allowed root"));
926
+ }
927
+ resolved.pop();
928
+ } else {
929
+ resolved.push(component.to_vec());
930
+ require_traversal_depth(resolved.len())?;
931
+ }
932
+ }
933
+ Ok(())
934
+ }
935
+
936
+ fn path_components(path: &Path) -> Vec<Vec<u8>> {
937
+ path.as_os_str()
938
+ .as_bytes()
939
+ .split(|byte| *byte == b'/')
940
+ .filter(|component| !component.is_empty())
941
+ .map(<[u8]>::to_vec)
942
+ .collect()
943
+ }
944
+
945
+ fn component_bytes_prefix(left: &[Vec<u8>], right: &[Vec<u8>]) -> bool {
946
+ left.len() <= right.len()
947
+ && left
948
+ .iter()
949
+ .zip(right.iter())
950
+ .all(|(left_component, right_component)| left_component == right_component)
951
+ }
952
+
953
+ fn require_traversal_depth(depth: usize) -> Result<()> {
954
+ if depth > MAXIMUM_TRAVERSAL_DEPTH {
955
+ Err(Error::new("maximum traversal depth exceeded"))
956
+ } else {
957
+ Ok(())
958
+ }
959
+ }
960
+
961
+ fn canonical_existing_directory(path: &Path, name: &'static str) -> Result<PathBuf> {
962
+ require_absolute(path)?;
963
+ let metadata = metadata_no_follow(path, "unable to inspect root directory")?;
964
+ if !metadata.file_type().is_dir() {
965
+ return Err(Error::new(name));
966
+ }
967
+ let canonical =
968
+ fs::canonicalize(path).map_err(|_| Error::new("unable to canonicalize root directory"))?;
969
+ if !canonical.is_absolute() {
970
+ return Err(Error::new("canonical root is not absolute"));
971
+ }
972
+ Ok(canonical)
973
+ }
974
+
975
+ fn prepare_empty_directory(path: &Path) -> Result<PathBuf> {
976
+ require_absolute(path)?;
977
+ match fs::symlink_metadata(path) {
978
+ Ok(metadata) => {
979
+ if !metadata.file_type().is_dir() {
980
+ return Err(Error::new("destination root must be a directory"));
981
+ }
982
+ }
983
+ Err(error) if error.kind() == io::ErrorKind::NotFound => {
984
+ fs::create_dir(path).map_err(|_| Error::new("unable to create destination root"))?;
985
+ fs::set_permissions(path, fs::Permissions::from_mode(0o755))
986
+ .map_err(|_| Error::new("unable to set destination root permissions"))?;
987
+ }
988
+ Err(_) => return Err(Error::new("unable to inspect destination root")),
989
+ }
990
+ if fs::read_dir(path)
991
+ .map_err(|_| Error::new("unable to read destination root"))?
992
+ .next()
993
+ .is_some()
994
+ {
995
+ return Err(Error::new("destination root must be empty"));
996
+ }
997
+ canonical_existing_directory(path, "destination root must be a directory")
998
+ }
999
+
1000
+ fn reject_overlapping_roots(left: &Path, right: &Path) -> Result<()> {
1001
+ if left.starts_with(right) || right.starts_with(left) {
1002
+ return Err(Error::new("source and destination roots must not overlap"));
1003
+ }
1004
+ Ok(())
1005
+ }
1006
+
1007
+ fn require_absolute(path: &Path) -> Result<()> {
1008
+ if path.is_absolute() {
1009
+ Ok(())
1010
+ } else {
1011
+ Err(Error::new("root paths must be absolute"))
1012
+ }
1013
+ }
1014
+
1015
+ fn metadata_no_follow(path: &Path, message: &'static str) -> Result<Metadata> {
1016
+ fs::symlink_metadata(path).map_err(|_| Error::new(message))
1017
+ }
1018
+
1019
+ fn require_unchanged(path: &Path, snapshot: Snapshot, message: &'static str) -> Result<()> {
1020
+ let metadata = metadata_no_follow(path, message)?;
1021
+ if Snapshot::from_metadata(&metadata) == snapshot {
1022
+ Ok(())
1023
+ } else {
1024
+ Err(Error::new(message))
1025
+ }
1026
+ }
1027
+
1028
+ fn ensure_directory_beneath(path: &Path, root: &Path) -> Result<()> {
1029
+ let metadata = metadata_no_follow(path, "unable to inspect traversed directory")?;
1030
+ if !metadata.file_type().is_dir() {
1031
+ return Err(Error::new("traversed directory changed type"));
1032
+ }
1033
+ let canonical = fs::canonicalize(path)
1034
+ .map_err(|_| Error::new("unable to canonicalize traversed directory"))?;
1035
+ if canonical.starts_with(root) {
1036
+ Ok(())
1037
+ } else {
1038
+ Err(Error::new("traversal escaped its root"))
1039
+ }
1040
+ }
1041
+
1042
+ fn ensure_destination_parent(destination: &Path, root: &Path) -> Result<()> {
1043
+ let parent = destination
1044
+ .parent()
1045
+ .ok_or_else(|| Error::new("destination has no parent directory"))?;
1046
+ let metadata = metadata_no_follow(parent, "unable to inspect destination parent")?;
1047
+ if !metadata.file_type().is_dir() {
1048
+ return Err(Error::new("destination parent is not a directory"));
1049
+ }
1050
+ let canonical = fs::canonicalize(parent)
1051
+ .map_err(|_| Error::new("unable to canonicalize destination parent"))?;
1052
+ if canonical.starts_with(root) {
1053
+ Ok(())
1054
+ } else {
1055
+ Err(Error::new("destination parent escaped its root"))
1056
+ }
1057
+ }
1058
+
1059
+ fn sorted_child_names(directory: &Path, maximum_names: u64) -> Result<Vec<OsString>> {
1060
+ let mut names = Vec::new();
1061
+ let mut collected_names = 0_u64;
1062
+ for entry in
1063
+ fs::read_dir(directory).map_err(|_| Error::new("unable to read source directory"))?
1064
+ {
1065
+ let entry = entry.map_err(|_| Error::new("unable to read source directory entry"))?;
1066
+ collected_names = collected_names
1067
+ .checked_add(1)
1068
+ .ok_or_else(|| Error::new("entry count overflow"))?;
1069
+ if collected_names > maximum_names {
1070
+ return Err(Error::new("maximum entry count exceeded"));
1071
+ }
1072
+ names.push(entry.file_name());
1073
+ }
1074
+ names.sort_by(|left, right| left.as_bytes().cmp(right.as_bytes()));
1075
+ Ok(names)
1076
+ }
1077
+
1078
+ fn finish_destination_operation<T>(destination: &Path, result: Result<T>) -> Result<T> {
1079
+ match result {
1080
+ Ok(value) => Ok(value),
1081
+ Err(primary_error) => match remove_directory_children_no_follow(destination) {
1082
+ Ok(()) => Err(primary_error),
1083
+ Err(_) => Err(Error::new(DESTINATION_CLEANUP_FAILURE)),
1084
+ },
1085
+ }
1086
+ }
1087
+
1088
+ fn remove_directory_children_no_follow(directory: &Path) -> Result<()> {
1089
+ let metadata = metadata_no_follow(directory, "unable to inspect cleanup root")?;
1090
+ if !metadata.file_type().is_dir() {
1091
+ return Err(Error::new("cleanup root must be a directory"));
1092
+ }
1093
+
1094
+ let entries = fs::read_dir(directory).map_err(|_| Error::new("unable to read cleanup root"))?;
1095
+ let mut cleanup_failed = false;
1096
+ for entry in entries {
1097
+ match entry {
1098
+ Ok(entry) => {
1099
+ if remove_path_no_follow(&entry.path(), 1).is_err() {
1100
+ cleanup_failed = true;
1101
+ }
1102
+ }
1103
+ Err(_) => cleanup_failed = true,
1104
+ }
1105
+ }
1106
+ if cleanup_failed {
1107
+ Err(Error::new("unable to remove cleanup entries"))
1108
+ } else {
1109
+ Ok(())
1110
+ }
1111
+ }
1112
+
1113
+ fn remove_path_no_follow(path: &Path, depth: usize) -> Result<()> {
1114
+ require_traversal_depth(depth)?;
1115
+ let metadata = match fs::symlink_metadata(path) {
1116
+ Ok(metadata) => metadata,
1117
+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
1118
+ Err(_) => return Err(Error::new("unable to inspect cleanup entry")),
1119
+ };
1120
+ if !metadata.file_type().is_dir() {
1121
+ return fs::remove_file(path).map_err(|_| Error::new("unable to remove cleanup entry"));
1122
+ }
1123
+
1124
+ let entries = fs::read_dir(path).map_err(|_| Error::new("unable to read cleanup directory"))?;
1125
+ let mut cleanup_failed = false;
1126
+ for entry in entries {
1127
+ match entry {
1128
+ Ok(entry) => {
1129
+ let child_depth = depth
1130
+ .checked_add(1)
1131
+ .ok_or_else(|| Error::new("maximum traversal depth exceeded"))?;
1132
+ if remove_path_no_follow(&entry.path(), child_depth).is_err() {
1133
+ cleanup_failed = true;
1134
+ }
1135
+ }
1136
+ Err(_) => cleanup_failed = true,
1137
+ }
1138
+ }
1139
+ if cleanup_failed {
1140
+ return Err(Error::new("unable to remove cleanup directory contents"));
1141
+ }
1142
+ fs::remove_dir(path).map_err(|_| Error::new("unable to remove cleanup directory"))
1143
+ }
1144
+
1145
+ fn set_tree_owner(root: &Path, ownership: Ownership) -> Result<()> {
1146
+ let metadata = metadata_no_follow(root, "unable to inspect ownership root")?;
1147
+ if !metadata.file_type().is_dir() {
1148
+ return Err(Error::new("ownership root must be a directory"));
1149
+ }
1150
+ set_directory_tree_owner(root, ownership, 0)?;
1151
+ set_path_owner(root, ownership)
1152
+ }
1153
+
1154
+ fn set_directory_tree_owner(directory: &Path, ownership: Ownership, depth: usize) -> Result<()> {
1155
+ require_traversal_depth(depth)?;
1156
+ for entry in
1157
+ fs::read_dir(directory).map_err(|_| Error::new("unable to read ownership directory"))?
1158
+ {
1159
+ let path = entry
1160
+ .map_err(|_| Error::new("unable to read ownership entry"))?
1161
+ .path();
1162
+ let child_depth = depth
1163
+ .checked_add(1)
1164
+ .ok_or_else(|| Error::new("maximum traversal depth exceeded"))?;
1165
+ require_traversal_depth(child_depth)?;
1166
+ let metadata = metadata_no_follow(&path, "unable to inspect ownership entry")?;
1167
+ if metadata.file_type().is_dir() {
1168
+ set_directory_tree_owner(&path, ownership, child_depth)?;
1169
+ } else if !metadata.file_type().is_file() && !metadata.file_type().is_symlink() {
1170
+ return Err(Error::new("special ownership entries are not allowed"));
1171
+ }
1172
+ set_path_owner(&path, ownership)?;
1173
+ }
1174
+ Ok(())
1175
+ }
1176
+
1177
+ fn set_path_owner(path: &Path, ownership: Ownership) -> Result<()> {
1178
+ let path = CString::new(path.as_os_str().as_bytes())
1179
+ .map_err(|_| Error::new("ownership path contains a null byte"))?;
1180
+ // lchown is required so a copied symlink can never redirect ownership outside the tree.
1181
+ let result = unsafe { nix::libc::lchown(path.as_ptr(), ownership.uid, ownership.gid) };
1182
+ if result == 0 {
1183
+ Ok(())
1184
+ } else {
1185
+ Err(Error::new("unable to set destination ownership"))
1186
+ }
1187
+ }
1188
+
1189
+ fn filesystem(path: &Path) -> Result<FilesystemResult> {
1190
+ require_absolute(path)?;
1191
+ let canonical =
1192
+ fs::canonicalize(path).map_err(|_| Error::new("unable to canonicalize filesystem path"))?;
1193
+ let statistics = nix::sys::statvfs::statvfs(&canonical)
1194
+ .map_err(|_| Error::new("unable to read filesystem statistics"))?;
1195
+ let fragment_size = count_to_u64(statistics.fragment_size())?;
1196
+ let block_size = if fragment_size == 0 {
1197
+ count_to_u64(statistics.block_size())?
1198
+ } else {
1199
+ fragment_size
1200
+ };
1201
+ Ok(FilesystemResult {
1202
+ block_size,
1203
+ available_blocks: count_to_u64(statistics.blocks_available())?,
1204
+ available_inodes: count_to_u64(statistics.files_available())?,
1205
+ })
1206
+ }
1207
+
1208
+ fn count_to_u64<T>(value: T) -> Result<u64>
1209
+ where
1210
+ T: TryInto<u64>,
1211
+ {
1212
+ value
1213
+ .try_into()
1214
+ .map_err(|_| Error::new("filesystem statistic exceeds unsigned 64-bit range"))
1215
+ }
1216
+
1217
+ fn reserve_volume_owned(
1218
+ volume: &Path,
1219
+ workspace_bytes: u64,
1220
+ workspace_entries: u64,
1221
+ reserve_bytes: u64,
1222
+ ownership: Ownership,
1223
+ ) -> Result<ReserveResult> {
1224
+ reserve_volume_inner(
1225
+ volume,
1226
+ workspace_bytes,
1227
+ workspace_entries,
1228
+ reserve_bytes,
1229
+ Some(ownership),
1230
+ )
1231
+ }
1232
+
1233
+ fn reserve_volume_inner(
1234
+ volume: &Path,
1235
+ workspace_bytes: u64,
1236
+ workspace_entries: u64,
1237
+ reserve_bytes: u64,
1238
+ ownership: Option<Ownership>,
1239
+ ) -> Result<ReserveResult> {
1240
+ reserve_volume_inner_with_writer(
1241
+ volume,
1242
+ workspace_bytes,
1243
+ workspace_entries,
1244
+ reserve_bytes,
1245
+ ownership,
1246
+ write_reserve_file,
1247
+ )
1248
+ }
1249
+
1250
+ fn reserve_volume_inner_with_writer<F>(
1251
+ volume: &Path,
1252
+ workspace_bytes: u64,
1253
+ workspace_entries: u64,
1254
+ reserve_bytes: u64,
1255
+ ownership: Option<Ownership>,
1256
+ reserve_writer: F,
1257
+ ) -> Result<ReserveResult>
1258
+ where
1259
+ F: FnOnce(&Path, u64) -> Result<()>,
1260
+ {
1261
+ let volume = canonical_existing_directory(volume, "volume root must be a directory")?;
1262
+ if fs::read_dir(&volume)
1263
+ .map_err(|_| Error::new("unable to read volume root"))?
1264
+ .next()
1265
+ .is_some()
1266
+ {
1267
+ return Err(Error::new("volume root must be empty"));
1268
+ }
1269
+
1270
+ let statistics = filesystem(&volume)?;
1271
+ let required_bytes = workspace_bytes
1272
+ .checked_add(reserve_bytes)
1273
+ .ok_or_else(|| Error::new("reserved byte requirement overflow"))?;
1274
+ let available_bytes = statistics
1275
+ .block_size
1276
+ .checked_mul(statistics.available_blocks)
1277
+ .ok_or_else(|| Error::new("available filesystem byte count overflow"))?;
1278
+ if available_bytes < required_bytes {
1279
+ return Err(Error::new("volume has insufficient available bytes"));
1280
+ }
1281
+ let required_inodes = workspace_entries
1282
+ .checked_add(2)
1283
+ .ok_or_else(|| Error::new("workspace inode requirement overflow"))?;
1284
+ if statistics.available_inodes < required_inodes {
1285
+ return Err(Error::new("volume has insufficient available inodes"));
1286
+ }
1287
+
1288
+ let workspace = volume.join("workspace");
1289
+ let reserve_path = volume.join(RESERVE_FILE_NAME);
1290
+ let reserve_result = (|| {
1291
+ fs::create_dir(&workspace)
1292
+ .map_err(|_| Error::new("unable to create workspace directory"))?;
1293
+ fs::set_permissions(&workspace, fs::Permissions::from_mode(0o755))
1294
+ .map_err(|_| Error::new("unable to set workspace directory permissions"))?;
1295
+ if let Some(ownership) = ownership {
1296
+ set_path_owner(&workspace, ownership)?;
1297
+ }
1298
+ reserve_writer(&reserve_path, reserve_bytes)
1299
+ })();
1300
+ if let Err(primary_error) = reserve_result {
1301
+ let reserve_cleanup = remove_path_no_follow(&reserve_path, 1);
1302
+ let workspace_cleanup = remove_path_no_follow(&workspace, 1);
1303
+ if reserve_cleanup.is_err() || workspace_cleanup.is_err() {
1304
+ return Err(Error::new(RESERVE_CLEANUP_FAILURE));
1305
+ }
1306
+ return Err(primary_error);
1307
+ }
1308
+
1309
+ Ok(ReserveResult {
1310
+ bytes: 0,
1311
+ entries: 0,
1312
+ workspace_bytes,
1313
+ workspace_entries,
1314
+ reserve_bytes,
1315
+ })
1316
+ }
1317
+
1318
+ fn write_reserve_file(path: &Path, reserve_bytes: u64) -> Result<()> {
1319
+ let mut file = OpenOptions::new()
1320
+ .write(true)
1321
+ .create_new(true)
1322
+ .mode(0o600)
1323
+ .open(path)
1324
+ .map_err(|_| Error::new("unable to create reserve file"))?;
1325
+ let buffer = [0_u8; COPY_BUFFER_SIZE];
1326
+ let mut remaining = reserve_bytes;
1327
+ while remaining > 0 {
1328
+ let write_size = remaining.min(buffer.len() as u64) as usize;
1329
+ file.write_all(&buffer[..write_size])
1330
+ .map_err(|_| Error::new("unable to allocate reserve file"))?;
1331
+ remaining -= write_size as u64;
1332
+ }
1333
+ file.sync_all()
1334
+ .map_err(|_| Error::new("unable to synchronize reserve file"))?;
1335
+ let metadata = file
1336
+ .metadata()
1337
+ .map_err(|_| Error::new("unable to inspect reserve file"))?;
1338
+ if metadata.len() != reserve_bytes {
1339
+ return Err(Error::new("reserve file has an unexpected length"));
1340
+ }
1341
+ let allocated_bytes = metadata
1342
+ .blocks()
1343
+ .checked_mul(512)
1344
+ .ok_or_else(|| Error::new("reserve allocation size overflow"))?;
1345
+ if allocated_bytes < reserve_bytes {
1346
+ return Err(Error::new("reserve file allocation is sparse"));
1347
+ }
1348
+ file.set_permissions(fs::Permissions::from_mode(0o000))
1349
+ .map_err(|_| Error::new("unable to make reserve file inaccessible"))
1350
+ }
1351
+
1352
+ #[cfg(test)]
1353
+ mod tests {
1354
+ use super::*;
1355
+ use std::os::unix::net::UnixListener;
1356
+ use std::sync::atomic::{AtomicU64, Ordering};
1357
+
1358
+ static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
1359
+
1360
+ struct TestDirectory {
1361
+ path: PathBuf,
1362
+ }
1363
+
1364
+ impl TestDirectory {
1365
+ fn new() -> Self {
1366
+ let counter = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
1367
+ let path = std::env::temp_dir().join(format!(
1368
+ "runnerworkspace-test-{}-{counter}",
1369
+ std::process::id()
1370
+ ));
1371
+ fs::create_dir(&path).expect("create test directory");
1372
+ Self { path }
1373
+ }
1374
+
1375
+ fn child(&self, name: &str) -> PathBuf {
1376
+ self.path.join(name)
1377
+ }
1378
+ }
1379
+
1380
+ impl Drop for TestDirectory {
1381
+ fn drop(&mut self) {
1382
+ let _ = fs::remove_dir_all(&self.path);
1383
+ }
1384
+ }
1385
+
1386
+ fn write_file(path: &Path, contents: &[u8]) {
1387
+ fs::write(path, contents).expect("write test file");
1388
+ }
1389
+
1390
+ #[test]
1391
+ fn imports_deterministically_and_preserves_only_executable_state() {
1392
+ let temporary = TestDirectory::new();
1393
+ let source = temporary.child("source");
1394
+ let destination = temporary.child("destination");
1395
+ fs::create_dir(&source).expect("create source");
1396
+ write_file(&source.join("zeta"), b"z");
1397
+ write_file(&source.join("alpha"), b"a");
1398
+ fs::set_permissions(source.join("zeta"), fs::Permissions::from_mode(0o4711))
1399
+ .expect("set executable permissions");
1400
+
1401
+ let names = sorted_child_names(&source, 2).expect("sort source children");
1402
+ assert_eq!(names, [OsString::from("alpha"), OsString::from("zeta")]);
1403
+
1404
+ let counts = import_tree(&source, &destination, 2, 2).expect("import source");
1405
+ assert_eq!(
1406
+ counts,
1407
+ Counts {
1408
+ bytes: 2,
1409
+ entries: 2
1410
+ }
1411
+ );
1412
+ assert_eq!(fs::read(destination.join("alpha")).unwrap(), b"a");
1413
+ assert_eq!(
1414
+ fs::metadata(destination.join("alpha")).unwrap().mode() & 0o777,
1415
+ 0o644
1416
+ );
1417
+ assert_eq!(
1418
+ fs::metadata(destination.join("zeta")).unwrap().mode() & 0o777,
1419
+ 0o755
1420
+ );
1421
+ }
1422
+
1423
+ #[test]
1424
+ fn rejects_escaping_symlinks() {
1425
+ let temporary = TestDirectory::new();
1426
+ let source = temporary.child("source");
1427
+ let destination = temporary.child("destination");
1428
+ fs::create_dir(&source).unwrap();
1429
+ std::os::unix::fs::symlink("../outside", source.join("escape")).unwrap();
1430
+
1431
+ let error = import_tree(&source, &destination, 10, 10).unwrap_err();
1432
+ assert_eq!(error.to_string(), "symlink target escapes its allowed root");
1433
+ }
1434
+
1435
+ #[test]
1436
+ fn rejects_hardlinked_regular_files() {
1437
+ let temporary = TestDirectory::new();
1438
+ let source = temporary.child("source");
1439
+ let destination = temporary.child("destination");
1440
+ fs::create_dir(&source).unwrap();
1441
+ write_file(&source.join("a-copied-first"), b"data");
1442
+ write_file(&source.join("z-hardlink"), b"data");
1443
+ fs::hard_link(source.join("z-hardlink"), source.join("z-hardlink-copy")).unwrap();
1444
+
1445
+ let error = import_tree(&source, &destination, 100, 3).unwrap_err();
1446
+ assert_eq!(
1447
+ error.to_string(),
1448
+ "hardlinked regular files are not allowed"
1449
+ );
1450
+ assert!(fs::read_dir(&destination).unwrap().next().is_none());
1451
+
1452
+ fs::remove_file(source.join("z-hardlink-copy")).unwrap();
1453
+ import_tree(&source, &destination, 100, 2).expect("retry import into cleaned destination");
1454
+ assert_eq!(
1455
+ fs::read(destination.join("a-copied-first")).unwrap(),
1456
+ b"data"
1457
+ );
1458
+ }
1459
+
1460
+ #[test]
1461
+ fn rejects_special_files() {
1462
+ let temporary = TestDirectory::new();
1463
+ let source = temporary.child("source");
1464
+ fs::create_dir(&source).unwrap();
1465
+ let _listener = UnixListener::bind(source.join("socket")).unwrap();
1466
+
1467
+ let error = measure_tree(&source, 100, 10).unwrap_err();
1468
+ assert_eq!(
1469
+ error.to_string(),
1470
+ "special filesystem entries are not allowed"
1471
+ );
1472
+ }
1473
+
1474
+ #[test]
1475
+ fn enforces_byte_and_entry_ceilings_before_copying() {
1476
+ let temporary = TestDirectory::new();
1477
+ let source = temporary.child("source");
1478
+ fs::create_dir(&source).unwrap();
1479
+ write_file(&source.join("file"), b"four");
1480
+
1481
+ let byte_destination = temporary.child("byte-destination");
1482
+ let byte_error = import_tree(&source, &byte_destination, 3, 1).unwrap_err();
1483
+ assert_eq!(byte_error.to_string(), "maximum byte count exceeded");
1484
+ assert!(
1485
+ sorted_child_names(&byte_destination, u64::MAX)
1486
+ .unwrap()
1487
+ .is_empty()
1488
+ );
1489
+
1490
+ let entry_destination = temporary.child("entry-destination");
1491
+ let entry_error = import_tree(&source, &entry_destination, 4, 0).unwrap_err();
1492
+ assert_eq!(entry_error.to_string(), "maximum entry count exceeded");
1493
+ assert!(
1494
+ sorted_child_names(&entry_destination, u64::MAX)
1495
+ .unwrap()
1496
+ .is_empty()
1497
+ );
1498
+
1499
+ assert_eq!(
1500
+ measure_tree(&source, 3, 1).unwrap_err().to_string(),
1501
+ "maximum byte count exceeded"
1502
+ );
1503
+ }
1504
+
1505
+ #[test]
1506
+ fn rejects_duplicate_and_overlapping_selections() {
1507
+ let duplicate = [PathBuf::from("one"), PathBuf::from("one")];
1508
+ assert_eq!(
1509
+ validate_selections(&duplicate).unwrap_err().to_string(),
1510
+ "selections must be unique and non-overlapping"
1511
+ );
1512
+
1513
+ let overlap = [PathBuf::from("one"), PathBuf::from("one/two")];
1514
+ assert_eq!(
1515
+ validate_selections(&overlap).unwrap_err().to_string(),
1516
+ "selections must be unique and non-overlapping"
1517
+ );
1518
+
1519
+ for unsafe_selection in ["", "/absolute", "one//two", "one/../two", "one\\two"] {
1520
+ assert!(validate_selections(&[PathBuf::from(unsafe_selection)]).is_err());
1521
+ }
1522
+ }
1523
+
1524
+ #[test]
1525
+ fn bounds_directory_collection_by_remaining_entry_budget() {
1526
+ let temporary = TestDirectory::new();
1527
+ let source = temporary.child("source");
1528
+ fs::create_dir(&source).unwrap();
1529
+ write_file(&source.join("one"), b"1");
1530
+ write_file(&source.join("two"), b"2");
1531
+
1532
+ assert_eq!(
1533
+ sorted_child_names(&source, 1).unwrap_err().to_string(),
1534
+ "maximum entry count exceeded"
1535
+ );
1536
+ }
1537
+
1538
+ #[test]
1539
+ fn rejects_source_trees_beyond_maximum_depth_and_rolls_back() {
1540
+ let temporary = TestDirectory::new();
1541
+ let source = temporary.child("source");
1542
+ let destination = temporary.child("destination");
1543
+ fs::create_dir(&source).unwrap();
1544
+ let mut current = source.clone();
1545
+ for _ in 0..=MAXIMUM_TRAVERSAL_DEPTH {
1546
+ current.push("d");
1547
+ fs::create_dir(&current).unwrap();
1548
+ }
1549
+
1550
+ let error = import_tree(
1551
+ &source,
1552
+ &destination,
1553
+ 0,
1554
+ (MAXIMUM_TRAVERSAL_DEPTH + 1) as u64,
1555
+ )
1556
+ .unwrap_err();
1557
+ assert_eq!(error.to_string(), "maximum traversal depth exceeded");
1558
+ assert!(fs::read_dir(destination).unwrap().next().is_none());
1559
+ }
1560
+
1561
+ #[test]
1562
+ fn rejects_selection_paths_beyond_maximum_depth() {
1563
+ let selection = PathBuf::from(vec!["d"; MAXIMUM_TRAVERSAL_DEPTH + 1].join("/"));
1564
+ assert_eq!(
1565
+ validate_selections(&[selection]).unwrap_err().to_string(),
1566
+ "maximum traversal depth exceeded"
1567
+ );
1568
+ }
1569
+
1570
+ #[test]
1571
+ fn exports_only_selected_paths_and_counts_structural_parents() {
1572
+ let temporary = TestDirectory::new();
1573
+ let workspace = temporary.child("workspace");
1574
+ let destination = temporary.child("destination");
1575
+ fs::create_dir(&workspace).unwrap();
1576
+ fs::create_dir(workspace.join("group")).unwrap();
1577
+ write_file(&workspace.join("group/keep"), b"keep");
1578
+ write_file(&workspace.join("group/skip"), b"skip");
1579
+
1580
+ let counts = export_tree(
1581
+ &workspace,
1582
+ &destination,
1583
+ &[PathBuf::from("group/keep")],
1584
+ 4,
1585
+ 2,
1586
+ )
1587
+ .expect("export selection");
1588
+ assert_eq!(
1589
+ counts,
1590
+ Counts {
1591
+ bytes: 4,
1592
+ entries: 2
1593
+ }
1594
+ );
1595
+ assert_eq!(fs::read(destination.join("group/keep")).unwrap(), b"keep");
1596
+ assert!(!destination.join("group/skip").exists());
1597
+ }
1598
+
1599
+ #[test]
1600
+ fn rejects_symlinks_that_escape_an_exported_selection() {
1601
+ let temporary = TestDirectory::new();
1602
+ let workspace = temporary.child("workspace");
1603
+ let destination = temporary.child("destination");
1604
+ fs::create_dir(&workspace).unwrap();
1605
+ fs::create_dir(workspace.join("selected")).unwrap();
1606
+ write_file(&workspace.join("undeclared"), b"secret");
1607
+ std::os::unix::fs::symlink("../../undeclared", workspace.join("selected/link")).unwrap();
1608
+
1609
+ let error = export_tree(
1610
+ &workspace,
1611
+ &destination,
1612
+ &[PathBuf::from("selected")],
1613
+ 100,
1614
+ 10,
1615
+ )
1616
+ .unwrap_err();
1617
+ assert_eq!(error.to_string(), "symlink target escapes its allowed root");
1618
+ }
1619
+
1620
+ #[test]
1621
+ fn exports_a_safe_selected_symlink_without_following_it() {
1622
+ let temporary = TestDirectory::new();
1623
+ let workspace = temporary.child("workspace");
1624
+ let destination = temporary.child("destination");
1625
+ fs::create_dir(&workspace).unwrap();
1626
+ write_file(&workspace.join("target"), b"not selected");
1627
+ std::os::unix::fs::symlink("target", workspace.join("link")).unwrap();
1628
+
1629
+ let counts = export_tree(&workspace, &destination, &[PathBuf::from("link")], 0, 1)
1630
+ .expect("export selected symlink");
1631
+ assert_eq!(
1632
+ counts,
1633
+ Counts {
1634
+ bytes: 0,
1635
+ entries: 1
1636
+ }
1637
+ );
1638
+ assert_eq!(
1639
+ fs::read_link(destination.join("link")).unwrap(),
1640
+ Path::new("target")
1641
+ );
1642
+ assert!(!destination.join("target").exists());
1643
+ }
1644
+
1645
+ #[test]
1646
+ fn rolls_back_partial_export_and_allows_retry() {
1647
+ let temporary = TestDirectory::new();
1648
+ let workspace = temporary.child("workspace");
1649
+ let destination = temporary.child("destination");
1650
+ fs::create_dir(&workspace).unwrap();
1651
+ fs::create_dir(workspace.join("selected")).unwrap();
1652
+ write_file(&workspace.join("selected/a-copied-first"), b"data");
1653
+ let _listener = UnixListener::bind(workspace.join("selected/z-socket")).unwrap();
1654
+
1655
+ let error = export_tree(
1656
+ &workspace,
1657
+ &destination,
1658
+ &[PathBuf::from("selected")],
1659
+ 100,
1660
+ 3,
1661
+ )
1662
+ .unwrap_err();
1663
+ assert_eq!(
1664
+ error.to_string(),
1665
+ "special filesystem entries are not allowed"
1666
+ );
1667
+ assert!(fs::read_dir(&destination).unwrap().next().is_none());
1668
+
1669
+ export_tree(
1670
+ &workspace,
1671
+ &destination,
1672
+ &[PathBuf::from("selected/a-copied-first")],
1673
+ 4,
1674
+ 2,
1675
+ )
1676
+ .expect("retry export into cleaned destination");
1677
+ assert_eq!(
1678
+ fs::read(destination.join("selected/a-copied-first")).unwrap(),
1679
+ b"data"
1680
+ );
1681
+ }
1682
+
1683
+ #[test]
1684
+ fn creates_a_physical_inaccessible_reserve() {
1685
+ let temporary = TestDirectory::new();
1686
+ let volume = temporary.child("volume");
1687
+ fs::create_dir(&volume).unwrap();
1688
+ let volume_metadata = fs::metadata(&volume).unwrap();
1689
+ let result = reserve_volume_owned(
1690
+ &volume,
1691
+ 4096,
1692
+ 2,
1693
+ 8192,
1694
+ Ownership {
1695
+ uid: volume_metadata.uid(),
1696
+ gid: volume_metadata.gid(),
1697
+ },
1698
+ )
1699
+ .expect("reserve volume");
1700
+ assert_eq!(result.bytes, 0);
1701
+ assert_eq!(result.entries, 0);
1702
+ assert!(volume.join("workspace").is_dir());
1703
+
1704
+ let reserve = fs::metadata(volume.join(RESERVE_FILE_NAME)).unwrap();
1705
+ assert_eq!(reserve.len(), 8192);
1706
+ assert!(reserve.blocks() * 512 >= reserve.len());
1707
+ assert_eq!(reserve.mode() & 0o777, 0);
1708
+ }
1709
+
1710
+ #[test]
1711
+ fn reserve_failure_removes_partial_file_and_workspace() {
1712
+ let temporary = TestDirectory::new();
1713
+ let volume = temporary.child("volume");
1714
+ fs::create_dir(&volume).unwrap();
1715
+
1716
+ let error = reserve_volume_inner_with_writer(&volume, 0, 0, 0, None, |reserve_path, _| {
1717
+ write_file(reserve_path, b"partial");
1718
+ Err(Error::new("injected reserve failure"))
1719
+ })
1720
+ .unwrap_err();
1721
+ assert_eq!(error.to_string(), "injected reserve failure");
1722
+ assert!(fs::read_dir(volume).unwrap().next().is_none());
1723
+ }
1724
+
1725
+ #[test]
1726
+ fn termination_state_stops_hold_waiting() {
1727
+ let termination_requested = AtomicBool::new(false);
1728
+ request_termination(&termination_requested);
1729
+ wait_for_termination(&termination_requested);
1730
+ assert!(termination_requested.load(Ordering::Relaxed));
1731
+ }
1732
+
1733
+ #[test]
1734
+ fn reports_statvfs_values() {
1735
+ let temporary = TestDirectory::new();
1736
+ let result = filesystem(&temporary.path).expect("read statvfs");
1737
+ assert!(result.block_size > 0);
1738
+ assert!(result.available_blocks > 0);
1739
+ assert!(result.available_inodes > 0);
1740
+ }
1741
+
1742
+ #[test]
1743
+ fn rejects_unchanged_owner_sentinel() {
1744
+ assert_eq!(
1745
+ parse_u32(OsString::from(u32::MAX.to_string()))
1746
+ .unwrap_err()
1747
+ .to_string(),
1748
+ "numeric owner must not use the unchanged-owner sentinel"
1749
+ );
1750
+ }
1751
+
1752
+ #[test]
1753
+ fn owned_import_and_export_retain_namespace_visible_ownership() {
1754
+ let temporary = TestDirectory::new();
1755
+ let source = temporary.child("source");
1756
+ let workspace = temporary.child("workspace");
1757
+ let destination = temporary.child("destination");
1758
+ fs::create_dir(&source).unwrap();
1759
+ fs::create_dir(&destination).unwrap();
1760
+ write_file(&source.join("file"), b"data");
1761
+ let owner = fs::metadata(&source).unwrap();
1762
+ let ownership = Ownership {
1763
+ uid: owner.uid(),
1764
+ gid: owner.gid(),
1765
+ };
1766
+
1767
+ import_tree_owned(&source, &workspace, 4, 1, ownership).unwrap();
1768
+ assert_eq!(
1769
+ fs::symlink_metadata(&workspace).unwrap().uid(),
1770
+ ownership.uid
1771
+ );
1772
+ assert_eq!(
1773
+ fs::symlink_metadata(workspace.join("file")).unwrap().gid(),
1774
+ ownership.gid
1775
+ );
1776
+
1777
+ export_tree_to_existing_owner(&workspace, &destination, &[PathBuf::from("file")], 4, 1)
1778
+ .unwrap();
1779
+ let destination_owner = fs::symlink_metadata(&destination).unwrap();
1780
+ let exported = fs::symlink_metadata(destination.join("file")).unwrap();
1781
+ assert_eq!(exported.uid(), destination_owner.uid());
1782
+ assert_eq!(exported.gid(), destination_owner.gid());
1783
+ }
1784
+ }