lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! TAR archive support with real LZ4 compression
//!
//! Provides full TAR archive creation, reading, and extraction with
//! optional LZ4 compression for .tar.lz4 archives.

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use super::types::{ArchiveEntry, ArchiveError, CompressionMethod, ExtractResult};

// ═══════════════════════════════════════════════════════════════════════════════
// TAR CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════

/// TAR header/block size (512 bytes)
const TAR_BLOCK_SIZE: usize = 512;

/// USTAR magic string
const USTAR_MAGIC: &[u8; 6] = b"ustar ";

/// GNU tar magic string
const GNU_MAGIC: &[u8; 6] = b"ustar\0";

// ═══════════════════════════════════════════════════════════════════════════════
// TAR HEADER STRUCTURE
// ═══════════════════════════════════════════════════════════════════════════════

/// TAR file type flags
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TarType {
    /// Regular file
    RegularFile,
    /// Hard link
    HardLink,
    /// Symbolic link
    SymLink,
    /// Character device
    CharDevice,
    /// Block device
    BlockDevice,
    /// Directory
    Directory,
    /// FIFO
    Fifo,
    /// Reserved/unknown
    Unknown(u8),
}

impl TarType {
    /// Convert from tar typeflag byte
    fn from_byte(b: u8) -> Self {
        match b {
            b'0' | 0 => TarType::RegularFile,
            b'1' => TarType::HardLink,
            b'2' => TarType::SymLink,
            b'3' => TarType::CharDevice,
            b'4' => TarType::BlockDevice,
            b'5' => TarType::Directory,
            b'6' => TarType::Fifo,
            _ => TarType::Unknown(b),
        }
    }

    /// Convert to tar typeflag byte
    fn as_byte(self) -> u8 {
        match self {
            TarType::RegularFile => b'0',
            TarType::HardLink => b'1',
            TarType::SymLink => b'2',
            TarType::CharDevice => b'3',
            TarType::BlockDevice => b'4',
            TarType::Directory => b'5',
            TarType::Fifo => b'6',
            TarType::Unknown(b) => b,
        }
    }
}

/// Parsed TAR header
#[derive(Debug, Clone)]
pub struct TarHeader {
    /// File name (up to 100 chars, or extended with prefix)
    pub name: String,
    /// File mode (permissions)
    pub mode: u32,
    /// Owner user ID
    pub uid: u32,
    /// Owner group ID
    pub gid: u32,
    /// File size in bytes
    pub size: u64,
    /// Modification time (Unix timestamp)
    pub mtime: u64,
    /// File type
    pub typeflag: TarType,
    /// Link target (for symlinks)
    pub linkname: String,
    /// Owner user name
    pub uname: String,
    /// Owner group name
    pub gname: String,
    /// Device major number
    pub devmajor: u32,
    /// Device minor number
    pub devminor: u32,
    /// USTAR prefix (for long names)
    pub prefix: String,
}

impl TarHeader {
    /// Parse a TAR header from 512-byte block
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() < TAR_BLOCK_SIZE {
            return None;
        }

        // Check for end marker (all zeros)
        if data[..TAR_BLOCK_SIZE].iter().all(|&b| b == 0) {
            return None;
        }

        // Verify checksum
        let stored_checksum = parse_octal(&data[148..156]);
        let computed_checksum = compute_checksum(data);
        if stored_checksum != computed_checksum {
            // Try with spaces in checksum field (some implementations)
            let alt_checksum = compute_checksum_with_spaces(data);
            if stored_checksum != alt_checksum {
                return None;
            }
        }

        let name = parse_string(&data[0..100]);
        let mode = parse_octal(&data[100..108]) as u32;
        let uid = parse_octal(&data[108..116]) as u32;
        let gid = parse_octal(&data[116..124]) as u32;
        let size = parse_octal(&data[124..136]) as u64;
        let mtime = parse_octal(&data[136..148]) as u64;
        let typeflag = TarType::from_byte(data[156]);
        let linkname = parse_string(&data[157..257]);

        // Check for USTAR format
        let (uname, gname, devmajor, devminor, prefix) =
            if &data[257..263] == USTAR_MAGIC || &data[257..263] == GNU_MAGIC {
                (
                    parse_string(&data[265..297]),
                    parse_string(&data[297..329]),
                    parse_octal(&data[329..337]) as u32,
                    parse_octal(&data[337..345]) as u32,
                    parse_string(&data[345..500]),
                )
            } else {
                (String::new(), String::new(), 0, 0, String::new())
            };

        // Combine prefix and name for full path
        let full_name = if !prefix.is_empty() {
            alloc::format!("{}/{}", prefix, name)
        } else {
            name
        };

        Some(Self {
            name: full_name,
            mode,
            uid,
            gid,
            size,
            mtime,
            typeflag,
            linkname,
            uname,
            gname,
            devmajor,
            devminor,
            prefix: String::new(), // Already combined into name
        })
    }

    /// Serialize header to 512-byte block
    pub fn to_bytes(&self) -> [u8; TAR_BLOCK_SIZE] {
        let mut header = [0u8; TAR_BLOCK_SIZE];

        // Split name if too long
        let (name_part, prefix_part) = if self.name.len() > 100 {
            let split_pos = self.name.len().saturating_sub(100);
            (&self.name[split_pos..], &self.name[..split_pos])
        } else {
            (self.name.as_str(), "")
        };

        // Name (100 bytes)
        write_string(&mut header[0..100], name_part);

        // Mode (8 bytes, octal)
        write_octal(&mut header[100..108], self.mode as usize);

        // UID (8 bytes, octal)
        write_octal(&mut header[108..116], self.uid as usize);

        // GID (8 bytes, octal)
        write_octal(&mut header[116..124], self.gid as usize);

        // Size (12 bytes, octal)
        write_octal(&mut header[124..136], self.size as usize);

        // Mtime (12 bytes, octal)
        write_octal(&mut header[136..148], self.mtime as usize);

        // Checksum placeholder (8 spaces)
        header[148..156].copy_from_slice(b"        ");

        // Type flag
        header[156] = self.typeflag.as_byte();

        // Link name (100 bytes)
        write_string(&mut header[157..257], &self.linkname);

        // USTAR magic
        header[257..263].copy_from_slice(USTAR_MAGIC);

        // Version
        header[263..265].copy_from_slice(b"00");

        // User name (32 bytes)
        write_string(&mut header[265..297], &self.uname);

        // Group name (32 bytes)
        write_string(&mut header[297..329], &self.gname);

        // Device major (8 bytes, octal)
        write_octal(&mut header[329..337], self.devmajor as usize);

        // Device minor (8 bytes, octal)
        write_octal(&mut header[337..345], self.devminor as usize);

        // Prefix (155 bytes)
        write_string(&mut header[345..500], prefix_part);

        // Calculate and write checksum
        let checksum = compute_checksum(&header);
        write_octal(&mut header[148..155], checksum);
        header[155] = 0;

        header
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// HELPER FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse null-terminated string from TAR field
fn parse_string(field: &[u8]) -> String {
    let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
    String::from_utf8_lossy(&field[..end]).trim().to_string()
}

/// Parse octal number from TAR field
fn parse_octal(field: &[u8]) -> usize {
    let s = parse_string(field);
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return 0;
    }
    usize::from_str_radix(trimmed, 8).unwrap_or(0)
}

/// Write string to TAR field
fn write_string(field: &mut [u8], value: &str) {
    let bytes = value.as_bytes();
    let len = bytes.len().min(field.len());
    field[..len].copy_from_slice(&bytes[..len]);
}

/// Write octal number to TAR field
fn write_octal(field: &mut [u8], value: usize) {
    let s = alloc::format!("{:0>width$o}", value, width = field.len() - 1);
    let bytes = s.as_bytes();
    let start = field.len().saturating_sub(bytes.len() + 1);
    let len = bytes.len().min(field.len() - start);
    field[start..start + len].copy_from_slice(&bytes[..len]);
}

/// Compute TAR header checksum
fn compute_checksum(header: &[u8]) -> usize {
    let mut sum = 0usize;
    for (i, &b) in header[..TAR_BLOCK_SIZE].iter().enumerate() {
        if (148..156).contains(&i) {
            sum += b' ' as usize; // Treat checksum field as spaces
        } else {
            sum += b as usize;
        }
    }
    sum
}

/// Compute TAR header checksum (alternative with preserved spaces)
fn compute_checksum_with_spaces(header: &[u8]) -> usize {
    header[..TAR_BLOCK_SIZE].iter().map(|&b| b as usize).sum()
}

// ═══════════════════════════════════════════════════════════════════════════════
// LZ4 COMPRESSION
// ═══════════════════════════════════════════════════════════════════════════════

/// Compress data using LZ4
fn compress_lz4(data: &[u8]) -> Vec<u8> {
    lz4_flex::compress_prepend_size(data)
}

/// Decompress LZ4 data
fn decompress_lz4(data: &[u8]) -> Result<Vec<u8>, ArchiveError> {
    lz4_flex::decompress_size_prepended(data).map_err(|_| ArchiveError::DecompressError)
}

// ═══════════════════════════════════════════════════════════════════════════════
// TAR ARCHIVE OPERATIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a TAR archive from files (uncompressed)
pub fn create_tar(files: &[(&str, &[u8])]) -> Result<Vec<u8>, ArchiveError> {
    let mut archive = Vec::new();

    for (name, data) in files {
        let header = TarHeader {
            name: (*name).to_string(),
            mode: 0o644,
            uid: 0,
            gid: 0,
            size: data.len() as u64,
            mtime: 0,
            typeflag: TarType::RegularFile,
            linkname: String::new(),
            uname: "root".to_string(),
            gname: "root".to_string(),
            devmajor: 0,
            devminor: 0,
            prefix: String::new(),
        };

        // Write header
        archive.extend_from_slice(&header.to_bytes());

        // Write data
        archive.extend_from_slice(data);

        // Pad to 512-byte boundary
        let padding = (TAR_BLOCK_SIZE - (data.len() % TAR_BLOCK_SIZE)) % TAR_BLOCK_SIZE;
        archive.extend(core::iter::repeat_n(0u8, padding));
    }

    // Two zero blocks to mark end
    archive.extend(core::iter::repeat_n(0u8, TAR_BLOCK_SIZE * 2));

    Ok(archive)
}

/// Create a compressed TAR.LZ4 archive
pub fn create_tar_lz4(files: &[(&str, &[u8])]) -> Result<Vec<u8>, ArchiveError> {
    let tar_data = create_tar(files)?;
    Ok(compress_lz4(&tar_data))
}

/// Parse TAR archive and return entries map
pub fn parse_tar(data: &[u8]) -> Result<BTreeMap<String, ArchiveEntry>, ArchiveError> {
    let mut entries = BTreeMap::new();
    let mut offset = 0;

    while offset + TAR_BLOCK_SIZE <= data.len() {
        let header_data = &data[offset..offset + TAR_BLOCK_SIZE];

        let header = match TarHeader::from_bytes(header_data) {
            Some(h) => h,
            None => break, // End of archive
        };

        let entry = ArchiveEntry {
            name: header.name.clone(),
            is_dir: header.typeflag == TarType::Directory,
            size: header.size,
            compressed_size: header.size, // TAR doesn't compress individual files
            mtime: header.mtime,
            mode: header.mode,
            offset: (offset + TAR_BLOCK_SIZE) as u64, // Data starts after header
            compression: CompressionMethod::Store,
            crc32: 0,
        };

        entries.insert(header.name, entry);

        // Move to next header
        offset += TAR_BLOCK_SIZE;
        if header.size > 0 {
            let data_blocks = (header.size as usize).div_ceil(TAR_BLOCK_SIZE);
            offset += data_blocks * TAR_BLOCK_SIZE;
        }
    }

    Ok(entries)
}

/// Parse compressed TAR.LZ4 archive
pub fn parse_tar_lz4(data: &[u8]) -> Result<BTreeMap<String, ArchiveEntry>, ArchiveError> {
    let decompressed = decompress_lz4(data)?;
    parse_tar(&decompressed)
}

/// Parse TAR directory (wrapper for compatibility)
pub fn parse_tar_directory(path: &str) -> Result<BTreeMap<String, ArchiveEntry>, ArchiveError> {
    let _ = path;
    Ok(BTreeMap::new())
}

/// Extract a single file from TAR archive
pub fn extract_file(archive_data: &[u8], entry: &ArchiveEntry) -> Result<Vec<u8>, ArchiveError> {
    let offset = entry.offset as usize;
    let size = entry.size as usize;

    if offset + size > archive_data.len() {
        return Err(ArchiveError::InvalidFormat);
    }

    Ok(archive_data[offset..offset + size].to_vec())
}

/// Extract all files from TAR archive
pub fn extract_all(archive_data: &[u8]) -> Result<Vec<(String, Vec<u8>)>, ArchiveError> {
    let entries = parse_tar(archive_data)?;
    let mut files = Vec::new();

    for (name, entry) in entries {
        if !entry.is_dir {
            let data = extract_file(archive_data, &entry)?;
            files.push((name, data));
        }
    }

    Ok(files)
}

/// Extract all files from compressed TAR.LZ4 archive
pub fn extract_all_lz4(archive_data: &[u8]) -> Result<Vec<(String, Vec<u8>)>, ArchiveError> {
    let decompressed = decompress_lz4(archive_data)?;
    extract_all(&decompressed)
}

/// Get compression statistics for TAR.LZ4
pub fn compression_stats(original_size: usize, compressed_size: usize) -> (f32, usize) {
    let ratio = if compressed_size > 0 {
        original_size as f32 / compressed_size as f32
    } else {
        1.0
    };
    let saved = original_size.saturating_sub(compressed_size);
    (ratio, saved)
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_parse_string() {
        let field = b"hello\0\0\0\0\0";
        assert_eq!(parse_string(field), "hello");
    }

    #[test]
    fn test_parse_octal() {
        let field = b"000644\0 ";
        assert_eq!(parse_octal(field), 0o644);
    }

    #[test]
    fn test_create_and_parse_tar() {
        let files = [
            ("hello.txt", b"Hello, World!".as_slice()),
            ("data.bin", &[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
        ];

        let archive = create_tar(&files).unwrap();
        let entries = parse_tar(&archive).unwrap();

        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key("hello.txt"));
        assert!(entries.contains_key("data.bin"));

        let hello_entry = entries.get("hello.txt").unwrap();
        assert_eq!(hello_entry.size, 13);
    }

    #[test]
    fn test_extract_file() {
        let original_data = b"This is test content for extraction!";
        let files = [("test.txt", original_data.as_slice())];

        let archive = create_tar(&files).unwrap();
        let entries = parse_tar(&archive).unwrap();
        let entry = entries.get("test.txt").unwrap();

        let extracted = extract_file(&archive, entry).unwrap();
        assert_eq!(extracted, original_data);
    }

    #[test]
    fn test_tar_lz4_roundtrip() {
        // Create compressible data
        let mut data = Vec::new();
        for _ in 0..100 {
            data.extend_from_slice(b"AAAAAAAAAA");
        }

        let files = [("compressible.txt", data.as_slice())];

        // Create compressed archive
        let compressed = create_tar_lz4(&files).unwrap();

        // Uncompressed TAR for comparison
        let uncompressed = create_tar(&files).unwrap();

        // Compressed should be smaller
        assert!(compressed.len() < uncompressed.len());

        // Extract and verify
        let extracted = extract_all_lz4(&compressed).unwrap();
        assert_eq!(extracted.len(), 1);
        assert_eq!(extracted[0].0, "compressible.txt");
        assert_eq!(extracted[0].1, data);
    }

    #[test]
    fn test_header_roundtrip() {
        let header = TarHeader {
            name: "test/file.txt".to_string(),
            mode: 0o755,
            uid: 1000,
            gid: 1000,
            size: 12345,
            mtime: 1234567890,
            typeflag: TarType::RegularFile,
            linkname: String::new(),
            uname: "user".to_string(),
            gname: "group".to_string(),
            devmajor: 0,
            devminor: 0,
            prefix: String::new(),
        };

        let bytes = header.to_bytes();
        let parsed = TarHeader::from_bytes(&bytes).unwrap();

        assert_eq!(parsed.name, header.name);
        assert_eq!(parsed.mode, header.mode);
        assert_eq!(parsed.size, header.size);
        assert_eq!(parsed.mtime, header.mtime);
    }

    #[test]
    fn test_compression_stats() {
        let (ratio, saved) = compression_stats(1000, 200);
        assert!((ratio - 5.0).abs() < 0.01);
        assert_eq!(saved, 800);
    }
}