arcthis 0.5.1

A command-line tool for reading and managing compressed files
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
//! Frontend-neutral application service for archive access operations.

use std::io::{self, Write};
use std::path::PathBuf;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

use serde::Serialize;

use crate::archive::{Archive, ArchiveOpenOptions};
use crate::error::{ArcthisError, Result};
use crate::model::{
    ArchiveEntry, ArchiveFormat, ArchiveInspection, EntryCopyResult, EntryKind, VerificationResult,
};
use crate::query::{FindResult, GrepOptions, GrepResult, HashAlgorithm, HashResult};
use crate::security::ExtractionLimits;

/// Explicit source description shared by non-CLI frontends.
#[derive(Debug, Default)]
pub struct ArchiveSourceRequest {
    pub path: PathBuf,
    pub within: Vec<String>,
    pub max_nested_entry_size: u64,
    pub open_options: ArchiveOpenOptions,
}

impl ArchiveSourceRequest {
    pub fn file(path: impl Into<PathBuf>) -> Self {
        Self {
            path: path.into(),
            within: Vec::new(),
            max_nested_entry_size: 256 * 1024 * 1024,
            open_options: ArchiveOpenOptions::default(),
        }
    }
}

/// Shared resource limits enforced by the application service.
#[derive(Debug, Clone, Copy)]
pub struct ServiceLimits {
    pub max_entries: u64,
    pub max_decoded_bytes: u64,
    pub max_results: u64,
    pub max_read_window: u64,
    pub max_result_bytes: u64,
}

impl Default for ServiceLimits {
    fn default() -> Self {
        Self {
            max_entries: 100_000,
            max_decoded_bytes: 1024 * 1024 * 1024,
            max_results: 10_000,
            max_read_window: 1024 * 1024,
            max_result_bytes: 16 * 1024 * 1024,
        }
    }
}

impl ServiceLimits {
    /// Compatibility profile used by the CLI, whose existing flags own operation limits.
    pub const fn cli_compatibility() -> Self {
        Self {
            max_entries: u64::MAX,
            max_decoded_bytes: u64::MAX,
            max_results: u64::MAX,
            max_read_window: u64::MAX,
            max_result_bytes: u64::MAX,
        }
    }
}

/// Cooperative cancellation handle checked between archive operations and streaming writes.
#[derive(Debug, Clone, Default)]
pub struct CancellationToken(Arc<AtomicBool>);

impl CancellationToken {
    pub fn cancel(&self) {
        self.0.store(true, Ordering::Release);
    }

    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Acquire)
    }

    pub(crate) fn checkpoint(&self) -> Result<()> {
        if self.is_cancelled() {
            Err(ArcthisError::UnsupportedOperation {
                message: "operation cancelled".to_owned(),
            })
        } else {
            Ok(())
        }
    }
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct ArchiveReference {
    pub path: PathBuf,
    pub format: ArchiveFormat,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct InspectResult {
    pub archive: ArchiveReference,
    pub inspection: ArchiveInspection,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct ListResult {
    pub archive: ArchiveReference,
    pub entries: Vec<ArchiveEntry>,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct TreeResult {
    pub archive: ArchiveReference,
    pub entries: Vec<ArchiveEntry>,
    pub tree: Vec<TreeNode>,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct TreeNode {
    pub name: String,
    pub path: String,
    pub kind: EntryKind,
    pub entry: Option<ArchiveEntry>,
    pub children: Vec<Self>,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct StatResult {
    pub archive: ArchiveReference,
    pub entry: ArchiveEntry,
}

#[derive(Debug, Clone)]
pub struct ReadRequest<'a> {
    pub source: &'a ArchiveSourceRequest,
    pub entry: &'a str,
    pub offset: u64,
    pub length: u64,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct ReadResult {
    pub archive: ArchiveReference,
    pub entry: ArchiveEntry,
    pub offset: u64,
    pub data: Vec<u8>,
    pub eof: bool,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct FindServiceResult {
    pub archive: ArchiveReference,
    pub find: FindResult,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct GrepServiceResult {
    pub archive: ArchiveReference,
    pub grep: GrepResult,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct HashServiceResult {
    pub archive: ArchiveReference,
    pub hash: HashResult,
}

#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "mcp", derive(rmcp::schemars::JsonSchema))]
pub struct VerifyServiceResult {
    pub archive: ArchiveReference,
    pub verification: VerificationResult,
}

/// Synchronous application boundary used by CLI, MCP, and future frontends.
#[derive(Debug, Clone)]
pub struct ApplicationService {
    limits: ServiceLimits,
    cancellation: CancellationToken,
}

impl Default for ApplicationService {
    fn default() -> Self {
        Self::new(ServiceLimits::default(), CancellationToken::default())
    }
}

impl ApplicationService {
    pub const fn new(limits: ServiceLimits, cancellation: CancellationToken) -> Self {
        Self {
            limits,
            cancellation,
        }
    }

    pub fn cancellation_token(&self) -> CancellationToken {
        self.cancellation.clone()
    }

    pub fn inspect(&self, source: &ArchiveSourceRequest) -> Result<InspectResult> {
        let archive = self.open(source)?;
        self.ensure_entries_within_limits(&archive)?;
        self.cancellation.checkpoint()?;
        let inspection = archive.inspect()?;
        self.cancellation.checkpoint()?;
        Ok(InspectResult {
            archive: reference(&archive),
            inspection,
        })
    }

    pub fn list(&self, source: &ArchiveSourceRequest) -> Result<ListResult> {
        let archive = self.open(source)?;
        let entries = self.entries(&archive)?;
        Ok(ListResult {
            archive: reference(&archive),
            entries,
        })
    }

    pub fn tree(&self, source: &ArchiveSourceRequest) -> Result<TreeResult> {
        let archive = self.open(source)?;
        let entries = self.entries(&archive)?;
        let tree = build_tree(&entries)?;
        Ok(TreeResult {
            archive: reference(&archive),
            entries,
            tree,
        })
    }

    pub fn stat(&self, source: &ArchiveSourceRequest, path: &str) -> Result<StatResult> {
        let archive = self.open(source)?;
        self.ensure_entries_within_limits(&archive)?;
        self.cancellation.checkpoint()?;
        let entry = archive.entry(path)?;
        Ok(StatResult {
            archive: reference(&archive),
            entry,
        })
    }

    pub fn read(&self, request: &ReadRequest<'_>) -> Result<ReadResult> {
        if request.length > self.limits.max_read_window {
            return Err(limit_error(
                "read window",
                request.length,
                self.limits.max_read_window,
            ));
        }
        let decoded_limit = request.offset.checked_add(request.length).ok_or_else(|| {
            ArcthisError::ResourceLimit {
                message: "read window end overflows u64".to_owned(),
            }
        })?;
        if decoded_limit > self.limits.max_decoded_bytes {
            return Err(limit_error(
                "decoded read bytes",
                decoded_limit,
                self.limits.max_decoded_bytes,
            ));
        }
        let archive = self.open(request.source)?;
        let entry = archive.entry(request.entry)?;
        let capacity =
            usize::try_from(request.length).map_err(|_| ArcthisError::ResourceLimit {
                message: "read window cannot fit in memory".to_owned(),
            })?;
        let mut writer = WindowWriter::new(
            request.offset,
            request.length,
            capacity,
            self.cancellation.clone(),
        )?;
        let copy = archive.copy_entry_to(request.entry, &mut writer);
        if let Err(error) = copy
            && !writer.window_complete()
        {
            return Err(error);
        }
        self.cancellation.checkpoint()?;
        let eof = request
            .offset
            .saturating_add(u64::try_from(writer.data.len()).unwrap_or(u64::MAX))
            >= entry.size;
        Ok(ReadResult {
            archive: reference(&archive),
            entry,
            offset: request.offset,
            data: writer.data,
            eof,
        })
    }

    pub fn read_to(
        &self,
        source: &ArchiveSourceRequest,
        entry: &str,
        writer: &mut dyn Write,
    ) -> Result<(ArchiveReference, EntryCopyResult)> {
        let archive = self.open(source)?;
        let metadata = archive.entry(entry)?;
        if metadata.size > self.limits.max_decoded_bytes {
            return Err(limit_error(
                "decoded entry bytes",
                metadata.size,
                self.limits.max_decoded_bytes,
            ));
        }
        let mut writer = CancellationWriter {
            inner: writer,
            cancellation: &self.cancellation,
        };
        let result = archive.copy_entry_to(entry, &mut writer)?;
        self.cancellation.checkpoint()?;
        Ok((reference(&archive), result))
    }

    pub fn find(&self, source: &ArchiveSourceRequest, glob: &str) -> Result<FindServiceResult> {
        let archive = self.open(source)?;
        self.ensure_entries_within_limits(&archive)?;
        self.cancellation.checkpoint()?;
        let find = crate::query::find(&archive, glob)?;
        ensure_count("find results", find.matched, self.limits.max_results)?;
        Ok(FindServiceResult {
            archive: reference(&archive),
            find,
        })
    }

    pub fn grep(
        &self,
        source: &ArchiveSourceRequest,
        pattern: &str,
        options: &GrepOptions,
    ) -> Result<GrepServiceResult> {
        ensure_count(
            "grep match limit",
            options.max_matches,
            self.limits.max_results,
        )?;
        if options.max_entry_size > self.limits.max_decoded_bytes {
            return Err(limit_error(
                "grep entry bytes",
                options.max_entry_size,
                self.limits.max_decoded_bytes,
            ));
        }
        let archive = self.open(source)?;
        self.ensure_entries_within_limits(&archive)?;
        self.cancellation.checkpoint()?;
        let mut options = options.clone();
        options.max_result_bytes = options.max_result_bytes.min(self.limits.max_result_bytes);
        options.max_total_size = options.max_total_size.min(self.limits.max_decoded_bytes);
        let grep = crate::query::grep(&archive, pattern, &options)?;
        self.cancellation.checkpoint()?;
        Ok(GrepServiceResult {
            archive: reference(&archive),
            grep,
        })
    }

    pub fn hash(
        &self,
        source: &ArchiveSourceRequest,
        entry: &str,
        algorithm: HashAlgorithm,
    ) -> Result<HashServiceResult> {
        let archive = self.open(source)?;
        let metadata = archive.entry(entry)?;
        if metadata.size > self.limits.max_decoded_bytes {
            return Err(limit_error(
                "hash decoded bytes",
                metadata.size,
                self.limits.max_decoded_bytes,
            ));
        }
        self.cancellation.checkpoint()?;
        let hash = crate::query::hash(&archive, entry, algorithm)?;
        self.cancellation.checkpoint()?;
        Ok(HashServiceResult {
            archive: reference(&archive),
            hash,
        })
    }

    pub fn verify(&self, source: &ArchiveSourceRequest) -> Result<VerifyServiceResult> {
        let archive = self.open(source)?;
        let entries = self.ensure_entries_within_limits(&archive)?;
        let decoded = entries
            .iter()
            .try_fold(0_u64, |total, entry| total.checked_add(entry.size))
            .ok_or_else(|| ArcthisError::ResourceLimit {
                message: "declared decoded byte total overflows u64".to_owned(),
            })?;
        if decoded > self.limits.max_decoded_bytes {
            return Err(limit_error(
                "verify decoded bytes",
                decoded,
                self.limits.max_decoded_bytes,
            ));
        }
        self.cancellation.checkpoint()?;
        let verification = archive.verify()?;
        self.cancellation.checkpoint()?;
        Ok(VerifyServiceResult {
            archive: reference(&archive),
            verification,
        })
    }

    fn open(&self, source: &ArchiveSourceRequest) -> Result<Archive> {
        self.cancellation.checkpoint()?;
        Archive::open_within_options(
            source.path.as_path(),
            &source.within,
            source.max_nested_entry_size,
            &source.open_options,
        )
    }

    fn entries(&self, archive: &Archive) -> Result<Vec<ArchiveEntry>> {
        let entries = self.ensure_entries_within_limits(archive)?;
        self.cancellation.checkpoint()?;
        Ok(entries)
    }

    fn ensure_entries_within_limits(&self, archive: &Archive) -> Result<Vec<ArchiveEntry>> {
        let entries = archive.entries()?;
        ensure_count(
            "archive entries",
            u64::try_from(entries.len()).unwrap_or(u64::MAX),
            self.limits.max_entries,
        )?;
        self.cancellation.checkpoint()?;
        Ok(entries)
    }
}

#[allow(clippy::too_many_lines)] // One iterative arena pass avoids recursion and duplicate tree construction.
pub(crate) fn build_tree(entries: &[ArchiveEntry]) -> Result<Vec<TreeNode>> {
    #[derive(Debug)]
    struct ArenaNode {
        name: String,
        path: String,
        kind: EntryKind,
        entry: Option<ArchiveEntry>,
        children: Vec<usize>,
    }

    let limits = ExtractionLimits::default();
    let mut arena = Vec::<ArenaNode>::new();
    let mut roots = Vec::<usize>::new();
    for entry in entries {
        if entry.path.len() > limits.max_path_bytes {
            return Err(limit_error(
                "tree entry path bytes",
                u64::try_from(entry.path.len()).unwrap_or(u64::MAX),
                u64::try_from(limits.max_path_bytes).unwrap_or(u64::MAX),
            ));
        }
        let components = entry
            .path
            .split('/')
            .filter(|component| !component.is_empty())
            .collect::<Vec<_>>();
        if components.is_empty() {
            continue;
        }
        if components.len() > limits.max_components {
            return Err(limit_error(
                "tree entry path components",
                u64::try_from(components.len()).unwrap_or(u64::MAX),
                u64::try_from(limits.max_components).unwrap_or(u64::MAX),
            ));
        }

        let mut parent: Option<usize> = None;
        let mut path = String::new();
        for (position, name) in components.iter().enumerate() {
            if !path.is_empty() {
                path.push('/');
            }
            path.push_str(name);
            let last = position + 1 == components.len();
            let siblings =
                parent.map_or(roots.as_slice(), |index| arena[index].children.as_slice());
            let existing_directory = siblings.iter().copied().find(|index| {
                arena[*index].name == *name && arena[*index].kind == EntryKind::Directory
            });

            if last {
                if entry.kind == EntryKind::Directory
                    && let Some(index) = existing_directory
                {
                    arena[index].entry = Some(entry.clone());
                    break;
                }
                let index = arena.len();
                arena.push(ArenaNode {
                    name: (*name).to_owned(),
                    path: path.clone(),
                    kind: entry.kind,
                    entry: Some(entry.clone()),
                    children: Vec::new(),
                });
                if let Some(parent) = parent {
                    arena[parent].children.push(index);
                } else {
                    roots.push(index);
                }
                break;
            }

            let index = existing_directory.unwrap_or_else(|| {
                let index = arena.len();
                arena.push(ArenaNode {
                    name: (*name).to_owned(),
                    path: path.clone(),
                    kind: EntryKind::Directory,
                    entry: None,
                    children: Vec::new(),
                });
                if let Some(parent) = parent {
                    arena[parent].children.push(index);
                } else {
                    roots.push(index);
                }
                index
            });
            parent = Some(index);
        }
    }

    roots.sort_by(|left, right| arena[*left].name.cmp(&arena[*right].name));
    for index in 0..arena.len() {
        let mut children = std::mem::take(&mut arena[index].children);
        children.sort_by(|left, right| arena[*left].name.cmp(&arena[*right].name));
        arena[index].children = children;
    }
    let mut built = std::iter::repeat_with(|| None)
        .take(arena.len())
        .collect::<Vec<Option<TreeNode>>>();
    for index in (0..arena.len()).rev() {
        let children = arena[index]
            .children
            .iter()
            .map(|child| {
                built[*child]
                    .take()
                    .ok_or_else(|| ArcthisError::InvalidArchive {
                        message: "tree construction order is invalid".to_owned(),
                    })
            })
            .collect::<Result<Vec<_>>>()?;
        built[index] = Some(TreeNode {
            name: std::mem::take(&mut arena[index].name),
            path: std::mem::take(&mut arena[index].path),
            kind: arena[index].kind,
            entry: arena[index].entry.take(),
            children,
        });
    }
    roots
        .into_iter()
        .map(|root| {
            built[root]
                .take()
                .ok_or_else(|| ArcthisError::InvalidArchive {
                    message: "tree root construction is invalid".to_owned(),
                })
        })
        .collect()
}

fn reference(archive: &Archive) -> ArchiveReference {
    ArchiveReference {
        path: archive.path().to_path_buf(),
        format: archive.format(),
    }
}

fn ensure_count(label: &str, actual: u64, limit: u64) -> Result<()> {
    if actual > limit {
        Err(limit_error(label, actual, limit))
    } else {
        Ok(())
    }
}

fn limit_error(label: &str, actual: u64, limit: u64) -> ArcthisError {
    ArcthisError::ResourceLimit {
        message: format!("{label} {actual} exceeds limit {limit}"),
    }
}

struct CancellationWriter<'a> {
    inner: &'a mut dyn Write,
    cancellation: &'a CancellationToken,
}

impl Write for CancellationWriter<'_> {
    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        if self.cancellation.is_cancelled() {
            return Err(io::Error::new(
                io::ErrorKind::Interrupted,
                "operation cancelled",
            ));
        }
        self.inner.write(buffer)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

struct WindowWriter {
    skip_remaining: u64,
    take_remaining: u64,
    data: Vec<u8>,
    cancellation: CancellationToken,
}

impl WindowWriter {
    fn new(skip: u64, take: u64, capacity: usize, cancellation: CancellationToken) -> Result<Self> {
        let mut data = Vec::new();
        data.try_reserve_exact(capacity)
            .map_err(|error| ArcthisError::ResourceLimit {
                message: format!("cannot reserve read window: {error}"),
            })?;
        Ok(Self {
            skip_remaining: skip,
            take_remaining: take,
            data,
            cancellation,
        })
    }

    const fn window_complete(&self) -> bool {
        self.take_remaining == 0
    }
}

impl Write for WindowWriter {
    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        if self.cancellation.is_cancelled() {
            return Err(io::Error::new(
                io::ErrorKind::Interrupted,
                "operation cancelled",
            ));
        }
        if self.take_remaining == 0 {
            return Err(io::Error::new(
                io::ErrorKind::BrokenPipe,
                "read window complete",
            ));
        }
        let buffer_len = u64::try_from(buffer.len()).unwrap_or(u64::MAX);
        if self.skip_remaining >= buffer_len {
            self.skip_remaining -= buffer_len;
            return Ok(buffer.len());
        }
        let start = usize::try_from(self.skip_remaining).unwrap_or(buffer.len());
        self.skip_remaining = 0;
        let available = buffer.len().saturating_sub(start);
        let take = available.min(usize::try_from(self.take_remaining).unwrap_or(usize::MAX));
        self.data.extend_from_slice(&buffer[start..start + take]);
        self.take_remaining -= u64::try_from(take).unwrap_or(u64::MAX);
        Ok(start + take)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}