libpna 0.38.0

PNA(Portable-Network-Archive) decoding and encoding library
Documentation
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
//! Entry header types for normal and solid mode entries.

use crate::entry::{CipherMode, Compression, DataKind, Encryption, EntryName};
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::io;
use std::sync::OnceLock;

/// Represents the entry information header expressed in the [`FHED`] chunk.
///
/// [`FHED`]: crate::ChunkType::FHED
#[derive(Clone, Debug)]
pub struct EntryHeader {
    pub(crate) major: u8,
    pub(crate) minor: u8,
    pub(crate) data_kind: DataKind,
    pub(crate) compression: Compression,
    pub(crate) encryption: Encryption,
    pub(crate) cipher_mode: CipherMode,
    sanitized_path: OnceLock<EntryName>,
    pub(crate) name: EntryName,
}

impl EntryHeader {
    pub(crate) const fn new_with_options(
        data_kind: DataKind,
        compression: Compression,
        encryption: Encryption,
        cipher_mode: CipherMode,
        path: EntryName,
    ) -> Self {
        Self {
            major: 0,
            minor: 0,
            data_kind,
            compression,
            encryption,
            cipher_mode,
            sanitized_path: OnceLock::new(),
            name: path,
        }
    }

    pub(crate) const fn new(data_kind: DataKind, path: EntryName) -> Self {
        Self::new_with_options(
            data_kind,
            Compression::NO,
            Encryption::NO,
            CipherMode::CBC,
            path,
        )
    }

    #[inline]
    pub(crate) const fn for_file(
        compression: Compression,
        encryption: Encryption,
        cipher_mode: CipherMode,
        path: EntryName,
    ) -> Self {
        Self::new_with_options(DataKind::FILE, compression, encryption, cipher_mode, path)
    }

    #[inline]
    pub(crate) const fn for_dir(path: EntryName) -> Self {
        Self::new(DataKind::DIRECTORY, path)
    }

    /// Creates a header for a symbolic link (symlink).
    #[inline]
    pub(crate) const fn for_symlink(path: EntryName) -> Self {
        Self::new(DataKind::SYMBOLIC_LINK, path)
    }

    #[inline]
    pub(crate) const fn for_hard_link(path: EntryName) -> Self {
        Self::new(DataKind::HARD_LINK, path)
    }

    /// Creates a new EntryHeader with a different name, resetting the sanitized path cache.
    #[inline]
    pub(crate) fn with_name(self, name: EntryName) -> Self {
        Self {
            sanitized_path: OnceLock::new(),
            name,
            ..self
        }
    }

    /// Returns the sanitized path of this entry, with path traversal characters removed by [`EntryName::sanitize`].
    #[inline]
    pub fn path(&self) -> &EntryName {
        self.sanitized_path.get_or_init(|| self.name.sanitize())
    }

    /// Returns the data kind of this entry.
    #[inline]
    pub const fn data_kind(&self) -> DataKind {
        self.data_kind
    }

    /// Returns the compression method of this entry.
    #[inline]
    pub const fn compression(&self) -> Compression {
        self.compression
    }

    /// Returns the encryption method of this entry.
    #[inline]
    pub const fn encryption(&self) -> Encryption {
        self.encryption
    }

    /// Returns the cipher mode of this entry's encryption method.
    #[inline]
    pub const fn cipher_mode(&self) -> CipherMode {
        self.cipher_mode
    }

    /// Must stay byte-identical to the bytes [`Self::try_from_bytes`] accepted:
    /// AEAD stream-key derivation is specified over the received `FHED` Data
    /// field and reads it back through this method.
    pub(crate) fn to_bytes(&self) -> Vec<u8> {
        let name = self.name.as_bytes();
        let mut data = Vec::with_capacity(6 + name.len());
        data.push(self.major);
        data.push(self.minor);
        data.push(self.data_kind.to_byte());
        data.push(self.compression.to_byte());
        data.push(self.encryption.to_byte());
        data.push(self.cipher_mode.to_byte());
        data.extend_from_slice(name);
        data
    }

    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        if bytes.len() < 6 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "entry header too short",
            ));
        }
        let path = EntryName::from_utf8_preserve_root(
            std::str::from_utf8(&bytes[6..])
                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?,
        );
        let sanitized = path.sanitize();
        let header = Self {
            major: bytes[0],
            minor: bytes[1],
            data_kind: DataKind::from_byte(bytes[2]),
            compression: Compression::from_byte(bytes[3]),
            encryption: Encryption::from_byte(bytes[4]),
            cipher_mode: CipherMode::from_byte(bytes[5]),
            sanitized_path: OnceLock::new(),
            name: path,
        };
        let _ = header.sanitized_path.set(sanitized);
        Ok(header)
    }
}

impl PartialEq for EntryHeader {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.major == other.major
            && self.minor == other.minor
            && self.data_kind == other.data_kind
            && self.compression == other.compression
            && self.encryption == other.encryption
            && self.cipher_mode == other.cipher_mode
            && self.name == other.name
    }
}

impl Eq for EntryHeader {}

impl PartialOrd for EntryHeader {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EntryHeader {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.major
            .cmp(&other.major)
            .then_with(|| self.minor.cmp(&other.minor))
            .then_with(|| self.data_kind.cmp(&other.data_kind))
            .then_with(|| self.compression.cmp(&other.compression))
            .then_with(|| self.encryption.cmp(&other.encryption))
            .then_with(|| self.cipher_mode.cmp(&other.cipher_mode))
            .then_with(|| self.path().cmp(other.path()))
            .then_with(|| self.name.cmp(&other.name))
    }
}

impl Hash for EntryHeader {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.major.hash(state);
        self.minor.hash(state);
        self.data_kind.hash(state);
        self.compression.hash(state);
        self.encryption.hash(state);
        self.cipher_mode.hash(state);
        self.path().hash(state);
        self.name.hash(state);
    }
}

impl TryFrom<&[u8]> for EntryHeader {
    type Error = io::Error;

    #[inline]
    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        Self::try_from_bytes(bytes)
    }
}

/// Represents the entry information header expressed in the [`SHED`] chunk.
///
/// [`SHED`]: crate::ChunkType::SHED
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct SolidHeader {
    pub(crate) major: u8,
    pub(crate) minor: u8,
    pub(crate) compression: Compression,
    pub(crate) encryption: Encryption,
    pub(crate) cipher_mode: CipherMode,
}

impl SolidHeader {
    pub(crate) const fn new(
        compression: Compression,
        encryption: Encryption,
        cipher_mode: CipherMode,
    ) -> Self {
        Self {
            major: 0,
            minor: 0,
            compression,
            encryption,
            cipher_mode,
        }
    }

    /// Returns the compression method of this solid entry.
    #[inline]
    pub const fn compression(&self) -> Compression {
        self.compression
    }

    /// Returns the encryption method of this solid entry.
    #[inline]
    pub const fn encryption(&self) -> Encryption {
        self.encryption
    }

    /// Returns the cipher mode of this solid entry's encryption method.
    #[inline]
    pub const fn cipher_mode(&self) -> CipherMode {
        self.cipher_mode
    }

    /// Converts to [`ChunkType::SHED`](crate::ChunkType::SHED) body bytes.
    ///
    /// For a header read from an archive this reproduces the `SHED` Data field
    /// byte for byte, which [`CipherMode::GCM`] relies on: stream-key
    /// derivation is specified over that field as received.
    #[inline]
    pub const fn to_bytes(&self) -> [u8; 5] {
        [
            self.major,
            self.minor,
            self.compression.to_byte(),
            self.encryption.to_byte(),
            self.cipher_mode.to_byte(),
        ]
    }

    pub(crate) fn try_from_bytes(bytes: &[u8]) -> io::Result<Self> {
        let bytes: [_; 5] = bytes
            .try_into()
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        Ok(Self {
            major: bytes[0],
            minor: bytes[1],
            compression: Compression::from_byte(bytes[2]),
            encryption: Encryption::from_byte(bytes[3]),
            cipher_mode: CipherMode::from_byte(bytes[4]),
        })
    }
}

impl TryFrom<&[u8]> for SolidHeader {
    type Error = io::Error;

    #[inline]
    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        Self::try_from_bytes(bytes)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
    use wasm_bindgen_test::wasm_bindgen_test as test;

    #[test]
    fn entry_header_to_bytes_follows_fhed_layout() {
        let header = EntryHeader::for_file(
            Compression::XZ,
            Encryption::AES,
            CipherMode::GCM,
            "file".into(),
        );
        assert_eq!(header.to_bytes(), b"\x00\x00\x00\x04\x01\x02file");
    }

    #[test]
    fn entry_header_try_from_bytes_requires_six_fixed_bytes() {
        assert_eq!(
            EntryHeader::try_from_bytes(&[]).unwrap_err().kind(),
            io::ErrorKind::InvalidData
        );
        assert_eq!(
            EntryHeader::try_from_bytes(&[0; 5]).unwrap_err().kind(),
            io::ErrorKind::InvalidData
        );
        assert_eq!(
            EntryHeader::try_from_bytes(&[0; 6]).unwrap(),
            EntryHeader::for_file(Compression::NO, Encryption::NO, CipherMode::CBC, "".into())
        );
    }

    #[test]
    fn entry_header_to_bytes_reproduces_the_parsed_bytes() {
        for bytes in [
            b"\x00\x00\x00\x00\x00\x00".as_slice(),
            b"\x00\x00\x00\x00\x00\x00file",
            b"\x00\x00\x02\x02\x01\x01dir/file",
            b"\x00\x00\x00\x00\x00\x00/abs//dir/../trailing/",
            b"\x00\x00\x7f\x3f\xc8\xff\xe6\x97\xa5",
            b"\xff\xff\xff\xff\xff\xffa",
        ] {
            assert_eq!(
                EntryHeader::try_from_bytes(bytes).unwrap().to_bytes(),
                bytes
            );
        }
    }

    #[test]
    fn solid_header_try_from_bytes() {
        assert_eq!(
            SolidHeader::try_from_bytes(&[0; 5]).unwrap(),
            SolidHeader::new(Compression::NO, Encryption::NO, CipherMode::CBC)
        );
        assert_eq!(
            SolidHeader::try_from_bytes(&[0; 4]).unwrap_err().kind(),
            io::ErrorKind::InvalidData,
        );
        assert_eq!(
            SolidHeader::try_from_bytes(&[0; 6]).unwrap_err().kind(),
            io::ErrorKind::InvalidData,
        );
    }

    #[test]
    fn solid_header_to_bytes_follows_shed_layout() {
        assert_eq!(
            SolidHeader::new(Compression::ZSTANDARD, Encryption::AES, CipherMode::CBC).to_bytes(),
            [0x00, 0x00, 0x02, 0x01, 0x00]
        );
    }

    #[test]
    fn solid_header_to_bytes_reproduces_the_parsed_bytes() {
        for bytes in [
            [0x00, 0x00, 0x00, 0x00, 0x00],
            [0x00, 0x00, 0x02, 0x01, 0x02],
            [0x00, 0x00, 0x3f, 0xc8, 0x7f],
            [0xff, 0xff, 0xff, 0xff, 0xff],
        ] {
            assert_eq!(
                SolidHeader::try_from_bytes(&bytes).unwrap().to_bytes(),
                bytes
            );
        }
    }

    #[test]
    fn with_name_invalidates_cache() {
        let header = EntryHeader::for_dir("original/path".into());
        let _ = header.path(); // Populate cache
        let renamed = header.with_name("new/path".into());
        assert_eq!(renamed.path().as_str(), "new/path");
        assert_eq!(renamed.name.as_str(), "new/path");
    }
}