Skip to main content

libarchive_oxide_core/
metadata.rs

1// SPDX-FileCopyrightText: 2026 libarchive_oxide contributors
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5//! Extensible archive and entry metadata.
6
7use alloc::string::{String, ToString};
8use alloc::vec::Vec;
9
10use crate::meta::{EntryKind, Timestamp};
11
12/// Encoding of an archive-native path.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum PathEncoding {
16    /// An uninterpreted byte sequence, as used by tar and Unix cpio.
17    Bytes,
18    /// Valid UTF-8.
19    Utf8,
20    /// UTF-16 little-endian code units stored as bytes.
21    Utf16Le,
22}
23
24/// An archive path preserving its native representation.
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub struct ArchivePath {
27    raw: Vec<u8>,
28    encoding: PathEncoding,
29}
30
31impl ArchivePath {
32    /// Constructs an uninterpreted byte path.
33    #[must_use]
34    pub fn from_bytes(raw: impl Into<Vec<u8>>) -> Self {
35        Self {
36            raw: raw.into(),
37            encoding: PathEncoding::Bytes,
38        }
39    }
40
41    /// Constructs a UTF-8 path.
42    #[must_use]
43    pub fn from_utf8(path: impl Into<String>) -> Self {
44        Self {
45            raw: path.into().into_bytes(),
46            encoding: PathEncoding::Utf8,
47        }
48    }
49
50    /// Constructs a path from archive-native bytes and an encoding tag.
51    #[must_use]
52    pub fn from_encoded(raw: impl Into<Vec<u8>>, encoding: PathEncoding) -> Self {
53        Self {
54            raw: raw.into(),
55            encoding,
56        }
57    }
58
59    /// Archive-native bytes.
60    #[must_use]
61    pub fn as_bytes(&self) -> &[u8] {
62        &self.raw
63    }
64
65    /// Archive-native encoding.
66    #[must_use]
67    pub const fn encoding(&self) -> PathEncoding {
68        self.encoding
69    }
70
71    /// A lossy string intended only for diagnostics and display.
72    #[must_use]
73    pub fn display_lossy(&self) -> String {
74        match self.encoding {
75            PathEncoding::Utf16Le => {
76                let units = self
77                    .raw
78                    .chunks_exact(2)
79                    .map(|c| u16::from_le_bytes([c[0], c[1]]));
80                char::decode_utf16(units)
81                    .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
82                    .collect()
83            },
84            PathEncoding::Bytes | PathEncoding::Utf8 => {
85                String::from_utf8_lossy(&self.raw).to_string()
86            },
87        }
88    }
89}
90
91/// Owner identity.
92#[derive(Debug, Clone, Default, PartialEq, Eq)]
93pub struct Owner {
94    /// Numeric user id.
95    pub uid: Option<u64>,
96    /// Numeric group id.
97    pub gid: Option<u64>,
98    /// User name in archive encoding.
99    pub user: Option<Vec<u8>>,
100    /// Group name in archive encoding.
101    pub group: Option<Vec<u8>>,
102}
103
104/// File timestamps.
105#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
106pub struct EntryTimes {
107    /// Modification time.
108    pub modified: Option<Timestamp>,
109    /// Access time.
110    pub accessed: Option<Timestamp>,
111    /// Metadata-change time.
112    pub changed: Option<Timestamp>,
113    /// Creation/birth time.
114    pub created: Option<Timestamp>,
115}
116
117/// Device numbers.
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
119pub struct Device {
120    /// Major device number.
121    pub major: u64,
122    /// Minor device number.
123    pub minor: u64,
124}
125
126/// One sparse-file data extent.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub struct SparseExtent {
129    /// Logical byte offset.
130    pub offset: u64,
131    /// Number of stored bytes.
132    pub length: u64,
133}
134
135/// A namespaced raw extension retained for round-tripping.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Extension {
138    namespace: String,
139    key: Vec<u8>,
140    value: Vec<u8>,
141}
142
143impl Extension {
144    /// Creates an extension.
145    #[must_use]
146    pub fn new(
147        namespace: impl Into<String>,
148        key: impl Into<Vec<u8>>,
149        value: impl Into<Vec<u8>>,
150    ) -> Self {
151        Self {
152            namespace: namespace.into(),
153            key: key.into(),
154            value: value.into(),
155        }
156    }
157
158    /// Namespace such as `pax`, `zip-extra`, or `rock-ridge`.
159    #[must_use]
160    pub fn namespace(&self) -> &str {
161        &self.namespace
162    }
163
164    /// Extension key/id bytes.
165    #[must_use]
166    pub fn key(&self) -> &[u8] {
167        &self.key
168    }
169
170    /// Raw extension value.
171    #[must_use]
172    pub fn value(&self) -> &[u8] {
173        &self.value
174    }
175}
176
177/// Metadata for one archive entry.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct EntryMetadata {
180    kind: EntryKind,
181    path: ArchivePath,
182    size: Option<u64>,
183    link_target: Option<ArchivePath>,
184    mode: Option<u32>,
185    owner: Owner,
186    times: EntryTimes,
187    inode: Option<u64>,
188    links: Option<u64>,
189    device: Option<Device>,
190    referenced_device: Option<Device>,
191    sparse: Vec<SparseExtent>,
192    xattrs: Vec<(Vec<u8>, Vec<u8>)>,
193    acl: Vec<Vec<u8>>,
194    file_flags: u64,
195    checksum: Option<Vec<u8>>,
196    encrypted: bool,
197    comment: Option<Vec<u8>>,
198    extensions: Vec<Extension>,
199}
200
201impl EntryMetadata {
202    /// Starts a builder with the required kind and path.
203    #[must_use]
204    pub fn builder(kind: EntryKind, path: ArchivePath) -> EntryMetadataBuilder {
205        EntryMetadataBuilder {
206            inner: Self {
207                kind,
208                path,
209                size: None,
210                link_target: None,
211                mode: None,
212                owner: Owner::default(),
213                times: EntryTimes::default(),
214                inode: None,
215                links: None,
216                device: None,
217                referenced_device: None,
218                sparse: Vec::new(),
219                xattrs: Vec::new(),
220                acl: Vec::new(),
221                file_flags: 0,
222                checksum: None,
223                encrypted: false,
224                comment: None,
225                extensions: Vec::new(),
226            },
227        }
228    }
229
230    /// Entry kind.
231    #[must_use]
232    pub const fn kind(&self) -> EntryKind {
233        self.kind
234    }
235
236    /// Entry path.
237    #[must_use]
238    pub const fn path(&self) -> &ArchivePath {
239        &self.path
240    }
241
242    /// Declared size, or `None` when not known before streaming.
243    #[must_use]
244    pub const fn size(&self) -> Option<u64> {
245        self.size
246    }
247
248    /// Link target.
249    #[must_use]
250    pub const fn link_target(&self) -> Option<&ArchivePath> {
251        self.link_target.as_ref()
252    }
253
254    /// Unix permission/mode bits when known.
255    #[must_use]
256    pub const fn mode(&self) -> Option<u32> {
257        self.mode
258    }
259
260    /// Owner identity.
261    #[must_use]
262    pub const fn owner(&self) -> &Owner {
263        &self.owner
264    }
265
266    /// Timestamps.
267    #[must_use]
268    pub const fn times(&self) -> EntryTimes {
269        self.times
270    }
271
272    /// Archive inode number.
273    #[must_use]
274    pub const fn inode(&self) -> Option<u64> {
275        self.inode
276    }
277
278    /// Link count.
279    #[must_use]
280    pub const fn links(&self) -> Option<u64> {
281        self.links
282    }
283
284    /// Filesystem device containing the entry.
285    #[must_use]
286    pub const fn device(&self) -> Option<Device> {
287        self.device
288    }
289
290    /// Referenced device for character/block entries.
291    #[must_use]
292    pub const fn referenced_device(&self) -> Option<Device> {
293        self.referenced_device
294    }
295
296    /// Sparse extents.
297    #[must_use]
298    pub fn sparse_extents(&self) -> &[SparseExtent] {
299        &self.sparse
300    }
301
302    /// Extended attributes.
303    #[must_use]
304    pub fn xattrs(&self) -> &[(Vec<u8>, Vec<u8>)] {
305        &self.xattrs
306    }
307
308    /// Raw ACL records.
309    #[must_use]
310    pub fn acl(&self) -> &[Vec<u8>] {
311        &self.acl
312    }
313
314    /// Filesystem flags.
315    #[must_use]
316    pub const fn file_flags(&self) -> u64 {
317        self.file_flags
318    }
319
320    /// Archive checksum bytes, if present.
321    #[must_use]
322    pub fn checksum(&self) -> Option<&[u8]> {
323        self.checksum.as_deref()
324    }
325
326    /// Whether the payload is encrypted.
327    #[must_use]
328    pub const fn is_encrypted(&self) -> bool {
329        self.encrypted
330    }
331
332    /// File comment.
333    #[must_use]
334    pub fn comment(&self) -> Option<&[u8]> {
335        self.comment.as_deref()
336    }
337
338    /// Preserved format extensions.
339    #[must_use]
340    pub fn extensions(&self) -> &[Extension] {
341        &self.extensions
342    }
343
344    /// Converts this value back into a builder without losing typed or raw
345    /// metadata.
346    ///
347    /// Format readers use this after a bounded second pass discovers metadata
348    /// that is stored in an entry payload, such as a ZIP symbolic-link target.
349    #[must_use]
350    pub fn into_builder(self) -> EntryMetadataBuilder {
351        EntryMetadataBuilder { inner: self }
352    }
353}
354
355/// Builder for [`EntryMetadata`].
356#[derive(Debug)]
357pub struct EntryMetadataBuilder {
358    inner: EntryMetadata,
359}
360
361impl EntryMetadataBuilder {
362    /// Replaces the entry kind while preserving every other field.
363    #[must_use]
364    pub const fn kind(mut self, kind: EntryKind) -> Self {
365        self.inner.kind = kind;
366        self
367    }
368
369    /// Replaces the archive path while preserving every other field.
370    #[must_use]
371    pub fn path(mut self, path: ArchivePath) -> Self {
372        self.inner.path = path;
373        self
374    }
375
376    /// Sets declared size.
377    #[must_use]
378    pub const fn size(mut self, size: Option<u64>) -> Self {
379        self.inner.size = size;
380        self
381    }
382
383    /// Sets mode bits.
384    #[must_use]
385    pub const fn mode(mut self, mode: Option<u32>) -> Self {
386        self.inner.mode = mode;
387        self
388    }
389
390    /// Sets owner identity.
391    #[must_use]
392    pub fn owner(mut self, owner: Owner) -> Self {
393        self.inner.owner = owner;
394        self
395    }
396
397    /// Sets timestamps.
398    #[must_use]
399    pub const fn times(mut self, times: EntryTimes) -> Self {
400        self.inner.times = times;
401        self
402    }
403
404    /// Sets link target.
405    #[must_use]
406    pub fn link_target(mut self, target: Option<ArchivePath>) -> Self {
407        self.inner.link_target = target;
408        self
409    }
410
411    /// Sets archive inode and link count.
412    #[must_use]
413    pub const fn inode_and_links(mut self, inode: Option<u64>, links: Option<u64>) -> Self {
414        self.inner.inode = inode;
415        self.inner.links = links;
416        self
417    }
418
419    /// Sets filesystem and referenced device numbers.
420    #[must_use]
421    pub const fn devices(
422        mut self,
423        device: Option<Device>,
424        referenced_device: Option<Device>,
425    ) -> Self {
426        self.inner.device = device;
427        self.inner.referenced_device = referenced_device;
428        self
429    }
430
431    /// Adds one sparse data extent.
432    #[must_use]
433    pub fn sparse_extent(mut self, extent: SparseExtent) -> Self {
434        self.inner.sparse.push(extent);
435        self
436    }
437
438    /// Adds one extended attribute.
439    #[must_use]
440    pub fn xattr(mut self, name: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) -> Self {
441        self.inner.xattrs.push((name.into(), value.into()));
442        self
443    }
444
445    /// Adds one raw ACL record.
446    #[must_use]
447    pub fn acl(mut self, value: impl Into<Vec<u8>>) -> Self {
448        self.inner.acl.push(value.into());
449        self
450    }
451
452    /// Sets filesystem flags.
453    #[must_use]
454    pub const fn file_flags(mut self, flags: u64) -> Self {
455        self.inner.file_flags = flags;
456        self
457    }
458
459    /// Sets checksum bytes.
460    #[must_use]
461    pub fn checksum(mut self, checksum: Option<Vec<u8>>) -> Self {
462        self.inner.checksum = checksum;
463        self
464    }
465
466    /// Sets encryption state.
467    #[must_use]
468    pub const fn encrypted(mut self, encrypted: bool) -> Self {
469        self.inner.encrypted = encrypted;
470        self
471    }
472
473    /// Sets a file comment.
474    #[must_use]
475    pub fn comment(mut self, comment: Option<Vec<u8>>) -> Self {
476        self.inner.comment = comment;
477        self
478    }
479
480    /// Adds a preserved format extension.
481    #[must_use]
482    pub fn extension(mut self, extension: Extension) -> Self {
483        self.inner.extensions.push(extension);
484        self
485    }
486
487    /// Completes the metadata.
488    #[must_use]
489    pub fn build(self) -> EntryMetadata {
490        self.inner
491    }
492}
493
494/// Archive-level metadata.
495#[derive(Debug, Clone, Default, PartialEq, Eq)]
496pub struct ArchiveMetadata {
497    volume_name: Option<ArchivePath>,
498    comment: Option<Vec<u8>>,
499    extensions: Vec<Extension>,
500}
501
502impl ArchiveMetadata {
503    /// Empty archive metadata.
504    #[must_use]
505    pub const fn new() -> Self {
506        Self {
507            volume_name: None,
508            comment: None,
509            extensions: Vec::new(),
510        }
511    }
512
513    /// Volume name.
514    #[must_use]
515    pub const fn volume_name(&self) -> Option<&ArchivePath> {
516        self.volume_name.as_ref()
517    }
518
519    /// Archive comment.
520    #[must_use]
521    pub fn comment(&self) -> Option<&[u8]> {
522        self.comment.as_deref()
523    }
524
525    /// Preserved archive-level extensions.
526    #[must_use]
527    pub fn extensions(&self) -> &[Extension] {
528        &self.extensions
529    }
530
531    /// Sets the volume name.
532    #[must_use]
533    pub fn with_volume_name(mut self, volume_name: ArchivePath) -> Self {
534        self.volume_name = Some(volume_name);
535        self
536    }
537
538    /// Sets the archive comment.
539    #[must_use]
540    pub fn with_comment(mut self, comment: impl Into<Vec<u8>>) -> Self {
541        self.comment = Some(comment.into());
542        self
543    }
544
545    /// Adds a preserved archive property.
546    #[must_use]
547    pub fn with_extension(mut self, extension: Extension) -> Self {
548        self.extensions.push(extension);
549        self
550    }
551}