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
/*
MIT License

Copyright (c) 2023 Philipp Schuster

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
//! Module for [`TarArchiveRef`]. If the `alloc`-feature is enabled, this crate
//! also exports `TarArchive`, which owns data on the heap.

use crate::header::PosixHeader;
use crate::{TypeFlag, BLOCKSIZE, FILENAME_MAX_LEN};
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
use arrayvec::ArrayString;
use core::fmt::{Debug, Formatter};
use core::str::{FromStr, Utf8Error};
use log::warn;

/// Describes an entry in an archive.
/// Currently only supports files but no directories.
pub struct ArchiveEntry<'a> {
    filename: ArrayString<FILENAME_MAX_LEN>,
    data: &'a [u8],
    size: usize,
}

#[allow(unused)]
impl<'a> ArchiveEntry<'a> {
    const fn new(filename: ArrayString<FILENAME_MAX_LEN>, data: &'a [u8]) -> Self {
        ArchiveEntry {
            filename,
            data,
            size: data.len(),
        }
    }

    /// Filename of the entry with a maximum of 100 characters (including the
    /// terminating NULL-byte).
    pub const fn filename(&self) -> ArrayString<{ FILENAME_MAX_LEN }> {
        self.filename
    }

    /// Data of the file.
    pub const fn data(&self) -> &'a [u8] {
        self.data
    }

    /// Data of the file as string slice, if data is valid UTF-8.
    pub fn data_as_str(&self) -> Result<&'a str, Utf8Error> {
        core::str::from_utf8(self.data)
    }

    /// Filesize in bytes.
    pub const fn size(&self) -> usize {
        self.size
    }
}

impl<'a> Debug for ArchiveEntry<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ArchiveEntry")
            .field("filename", &self.filename().as_str())
            .field("size", &self.size())
            .field("data", &"<bytes>")
            .finish()
    }
}

/// Type that owns bytes on the heap, that represents a Tar archive.
/// Unlike [`TarArchiveRef`], this type is useful, if you need to own the
/// data as long as you need the archive, but not longer.
///
/// This is only available with the `alloc` feature of this crate.
#[cfg(feature = "alloc")]
#[derive(Debug)]
pub struct TarArchive {
    data: Box<[u8]>,
}

#[cfg(feature = "alloc")]
impl TarArchive {
    /// Creates a new archive type, that owns the data on the heap. The provided byte array is
    /// interpreted as bytes in Tar archive format.
    pub fn new(data: Box<[u8]>) -> Self {
        assert_eq!(
            data.len() % BLOCKSIZE,
            0,
            "data must be a multiple of BLOCKSIZE={}, len is {}",
            BLOCKSIZE,
            data.len(),
        );
        Self { data }
    }

    /// Iterates over all entries of the Tar archive.
    /// Returns items of type [`ArchiveEntry`].
    /// See also [`ArchiveIterator`].
    pub fn entries(&self) -> ArchiveIterator {
        ArchiveIterator::new(self.data.as_ref())
    }
}

#[cfg(feature = "alloc")]
impl From<Box<[u8]>> for TarArchive {
    fn from(data: Box<[u8]>) -> Self {
        Self::new(data)
    }
}

#[cfg(feature = "alloc")]
impl From<TarArchive> for Box<[u8]> {
    fn from(ar: TarArchive) -> Self {
        ar.data
    }
}

/// Wrapper type around bytes, which represents a Tar archive.
/// Unlike [`TarArchive`], this uses only a reference to the data.
#[derive(Debug)]
pub struct TarArchiveRef<'a> {
    data: &'a [u8],
}

#[allow(unused)]
impl<'a> TarArchiveRef<'a> {
    /// Creates a new archive wrapper type. The provided byte array is interpreted as
    /// bytes in Tar archive format.
    pub fn new(data: &'a [u8]) -> Self {
        assert_eq!(
            data.len() % BLOCKSIZE,
            0,
            "data must be a multiple of BLOCKSIZE={}",
            BLOCKSIZE
        );
        Self { data }
    }

    /// Iterates over all entries of the Tar archive.
    /// Returns items of type [`ArchiveEntry`].
    /// See also [`ArchiveIterator`].
    pub const fn entries(&self) -> ArchiveIterator {
        ArchiveIterator::new(self.data)
    }
}

/// Iterator over the files of the archive. Each iteration starts
/// at the next Tar header entry.
#[derive(Debug)]
pub struct ArchiveIterator<'a> {
    archive_data: &'a [u8],
    block_index: usize,
}

impl<'a> ArchiveIterator<'a> {
    pub const fn new(archive: &'a [u8]) -> Self {
        Self {
            archive_data: archive,
            block_index: 0,
        }
    }

    /// Returns a reference to the next Header.
    fn next_hdr(&self, block_index: usize) -> &'a PosixHeader {
        let hdr_ptr = &self.archive_data[block_index * BLOCKSIZE];
        unsafe { (hdr_ptr as *const u8).cast::<PosixHeader>().as_ref() }.unwrap()
    }
}

impl<'a> Iterator for ArchiveIterator<'a> {
    type Item = ArchiveEntry<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.block_index * BLOCKSIZE >= self.archive_data.len() {
            warn!("Reached end of Tar archive data without finding zero/end blocks!");
            return None;
        }

        let hdr = self.next_hdr(self.block_index);

        // check if we found end of archive
        if hdr.is_zero_block() {
            let next_hdr = self.next_hdr(self.block_index + 1);
            if next_hdr.is_zero_block() {
                // gracefully terminated Archive
                log::debug!("End of Tar archive with two zero blocks!");
            } else {
                log::warn!("Zero block found at end of Tar archive, but only one instead of two!");
            }
            // end of archive
            return None;
        }

        if hdr.typeflag != TypeFlag::AREGTYPE && hdr.typeflag != TypeFlag::REGTYPE {
            log::warn!(
                "Found entry of type={:?}, but only files are supported",
                hdr.typeflag
            );
            return None;
        }

        if hdr.name.is_empty() {
            warn!("Found empty file name",);
        }

        let hdr_size = hdr.size.val();
        if let Err(e) = hdr_size {
            warn!("Can't parse the file size from the header block. Stop iterating Tar archive. {e:#?}");
            return None;
        }
        let hdr_size = hdr_size.unwrap();

        // Fetch data of file from next block(s).
        // .unwrap() is fine as we checked that hdr.size().val() is valid
        // above
        let data_block_count = hdr.payload_block_count().unwrap();

        // +1: skip hdr block itself and start at data!
        // i_begin is the byte begin index of this file in the array of the whole archive
        let i_begin = (self.block_index + 1) * BLOCKSIZE;
        // i_end is the exclusive byte end index of the data of the current file
        let i_end = i_begin + data_block_count * BLOCKSIZE;
        let file_block_bytes = &self.archive_data[i_begin..i_end];
        // Each block is 512 bytes long, but the file size is not necessarily a
        // multiple of 512.
        let file_bytes = &file_block_bytes[0..hdr_size];

        // in next iteration: start at next Archive entry header
        // +1 for current hdr block itself + all data blocks
        self.block_index += data_block_count + 1;

        let filename = ArrayString::from_str(hdr.name.as_string().as_str());
        // .unwrap is fine as the capacity is MUST be ok.
        let filename = filename.unwrap();

        Some(ArchiveEntry::new(filename, file_bytes))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::vec::Vec;

    #[test]
    fn test_archive_list() {
        let archive = TarArchiveRef::new(include_bytes!("../tests/gnu_tar_default.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        println!("{:#?}", entries);
    }

    /// Tests to read the entries from existing archives in various Tar flavors.
    #[test]
    fn test_archive_entries() {
        let archive = TarArchiveRef::new(include_bytes!("../tests/gnu_tar_default.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);

        let archive = TarArchiveRef::new(include_bytes!("../tests/gnu_tar_gnu.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);

        let archive = TarArchiveRef::new(include_bytes!("../tests/gnu_tar_oldgnu.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);

        // UNSUPPORTED. Uses extensions.
        /*let archive = TarArchive::new(include_bytes!("../tests/gnu_tar_pax.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);*/

        // UNSUPPORTED. Uses extensions.
        /*let archive = TarArchive::new(include_bytes!("../tests/gnu_tar_posix.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);*/

        let archive = TarArchiveRef::new(include_bytes!("../tests/gnu_tar_ustar.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);

        let archive = TarArchiveRef::new(include_bytes!("../tests/gnu_tar_v7.tar"));
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);
    }

    /// Like [`test_archive_entries`] but with additional `alloc` functionality.
    #[cfg(feature = "alloc")]
    #[test]
    fn test_archive_entries_alloc() {
        let data = include_bytes!("../tests/gnu_tar_default.tar")
            .to_vec()
            .into_boxed_slice();
        let archive = TarArchive::new(data.clone());
        let entries = archive.entries().collect::<Vec<_>>();
        assert_archive_content(&entries);

        // Test that the archive can be transformed into owned heap data.
        assert_eq!(data, archive.into());
    }

    /// Tests that the parsed archive matches the expected order. The tarballs
    /// the tests directory were created once by me with files in the order
    /// specified in this test.
    fn assert_archive_content(entries: &[ArchiveEntry]) {
        assert_eq!(entries.len(), 3);

        assert_eq!(entries[0].filename().as_str(), "bye_world_513b.txt");
        assert_eq!(entries[0].size(), 513);
        assert_eq!(entries[0].data().len(), 513);
        assert_eq!(
            entries[0].data_as_str().expect("Should be valid UTF-8"),
            // .replace: Ensure that the test also works on Windows
            include_str!("../tests/bye_world_513b.txt").replace("\r\n", "\n")
        );

        // Test that an entry that needs two 512 byte data blocks is read
        // properly.
        assert_eq!(entries[1].filename().as_str(), "hello_world_513b.txt");
        assert_eq!(entries[1].size(), 513);
        assert_eq!(entries[1].data().len(), 513);
        assert_eq!(
            entries[1].data_as_str().expect("Should be valid UTF-8"),
            // .replace: Ensure that the test also works on Windows
            include_str!("../tests/hello_world_513b.txt").replace("\r\n", "\n")
        );

        assert_eq!(entries[2].filename().as_str(), "hello_world.txt");
        assert_eq!(entries[2].size(), 12);
        assert_eq!(entries[2].data().len(), 12);
        assert_eq!(
            entries[2].data_as_str().expect("Should be valid UTF-8"),
            "Hello World\n",
            "file content must match"
        );
    }
}