armybox 0.3.0

A memory-safe #[no_std] BusyBox/Toybox clone in Rust - 299 Unix utilities in ~500KB
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
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
//! tar - tape archiver
//!
//! Create, extract, and list tar archives.

use alloc::vec::Vec;
use crate::io;
use super::{get_arg, open_read, open_write_create, create_parent_dirs, mode_string};

/// USTAR tar header structure (512 bytes)
#[repr(C)]
pub struct TarHeader {
    pub name: [u8; 100],
    pub mode: [u8; 8],
    pub uid: [u8; 8],
    pub gid: [u8; 8],
    pub size: [u8; 12],
    pub mtime: [u8; 12],
    pub checksum: [u8; 8],
    pub typeflag: u8,
    pub linkname: [u8; 100],
    pub magic: [u8; 6],
    pub version: [u8; 2],
    pub uname: [u8; 32],
    pub gname: [u8; 32],
    pub devmajor: [u8; 8],
    pub devminor: [u8; 8],
    pub prefix: [u8; 155],
    pub _pad: [u8; 12],
}

impl TarHeader {
    pub fn new() -> Self {
        Self {
            name: [0; 100],
            mode: [0; 8],
            uid: [0; 8],
            gid: [0; 8],
            size: [0; 12],
            mtime: [0; 12],
            checksum: [0; 8],
            typeflag: 0,
            linkname: [0; 100],
            magic: [0; 6],
            version: [0; 2],
            uname: [0; 32],
            gname: [0; 32],
            devmajor: [0; 8],
            devminor: [0; 8],
            prefix: [0; 155],
            _pad: [0; 12],
        }
    }

    pub fn is_empty(&self) -> bool {
        self.name[0] == 0
    }

    pub fn get_name(&self) -> &[u8] {
        let len = self.name.iter().position(|&c| c == 0).unwrap_or(100);
        &self.name[..len]
    }

    pub fn get_size(&self) -> u64 {
        parse_octal(&self.size)
    }

    pub fn get_mode(&self) -> u32 {
        parse_octal(&self.mode) as u32
    }

    pub fn compute_checksum(&self) -> u32 {
        let bytes = unsafe {
            core::slice::from_raw_parts(self as *const _ as *const u8, 512)
        };
        let mut sum = 0u32;
        for (i, &b) in bytes.iter().enumerate() {
            // Treat checksum field (bytes 148-155) as spaces
            if i >= 148 && i < 156 {
                sum += b' ' as u32;
            } else {
                sum += b as u32;
            }
        }
        sum
    }

    pub fn set_checksum(&mut self) {
        // Fill with spaces first
        self.checksum = *b"        ";
        let sum = self.compute_checksum();
        // Write checksum as octal with null terminator and space
        write_octal(&mut self.checksum[..6], sum as u64);
        self.checksum[6] = 0;
        self.checksum[7] = b' ';
    }
}

fn parse_octal(bytes: &[u8]) -> u64 {
    let mut result = 0u64;
    for &b in bytes {
        if b == 0 || b == b' ' { break; }
        if b >= b'0' && b <= b'7' {
            result = result * 8 + (b - b'0') as u64;
        }
    }
    result
}

fn write_octal(buf: &mut [u8], mut val: u64) {
    let len = buf.len();
    for i in (0..len).rev() {
        buf[i] = b'0' + (val & 7) as u8;
        val >>= 3;
    }
}

/// tar - tape archiver
///
/// # Synopsis
/// ```text
/// tar [-cxtv] -f ARCHIVE [FILES...]
/// ```
///
/// # Description
/// Create, extract, or list tar archives.
///
/// # Options
/// - `-c`: Create archive
/// - `-x`: Extract archive
/// - `-t`: List archive contents
/// - `-v`: Verbose output
/// - `-f FILE`: Archive file
///
/// # Exit Status
/// - 0: Success
/// - 1: Error
pub fn tar(argc: i32, argv: *const *const u8) -> i32 {
    let mut create = false;
    let mut extract = false;
    let mut list = false;
    let mut verbose = false;
    let mut archive_file: Option<&[u8]> = None;
    let mut files: Vec<&[u8]> = Vec::new();

    let mut i = 1;
    while i < argc {
        if let Some(arg) = unsafe { get_arg(argv, i) } {
            if arg.starts_with(b"-") || (i == 1 && !arg.starts_with(b"/")) {
                // Options (possibly without leading dash for first arg)
                let opts = if arg.starts_with(b"-") { &arg[1..] } else { arg };
                for &c in opts {
                    match c {
                        b'c' => create = true,
                        b'x' => extract = true,
                        b't' => list = true,
                        b'v' => verbose = true,
                        b'f' => {
                            // Next arg is the archive file
                            i += 1;
                            if let Some(f) = unsafe { get_arg(argv, i) } {
                                archive_file = Some(f);
                            }
                        }
                        b'z' | b'j' | b'J' => {
                            // Compression flags - we'll handle uncompressed only for now
                        }
                        _ => {}
                    }
                }
            } else {
                files.push(arg);
            }
        }
        i += 1;
    }

    let archive = match archive_file {
        Some(f) => f,
        None => {
            io::write_str(2, b"tar: -f archive required\n");
            return 1;
        }
    };

    if create {
        tar_create(archive, &files, verbose)
    } else if extract {
        tar_extract(archive, &files, verbose)
    } else if list {
        tar_list(archive, verbose)
    } else {
        io::write_str(2, b"tar: specify -c, -x, or -t\n");
        1
    }
}

fn tar_create(archive: &[u8], files: &[&[u8]], verbose: bool) -> i32 {
    let fd = open_write_create(archive, 0o644);
    if fd < 0 {
        io::write_str(2, b"tar: cannot create archive\n");
        return 1;
    }

    for &file in files {
        if tar_add_file(fd, file, verbose) != 0 {
            io::close(fd);
            return 1;
        }
    }

    // Write two empty blocks as end marker
    let empty = [0u8; 512];
    io::write_all(fd, &empty);
    io::write_all(fd, &empty);

    io::close(fd);
    0
}

fn tar_add_file(fd: i32, path: &[u8], verbose: bool) -> i32 {
    // Get file info
    let mut stat_buf: libc::stat = unsafe { core::mem::zeroed() };
    let mut path_z = [0u8; 256];
    let len = path.len().min(255);
    path_z[..len].copy_from_slice(&path[..len]);

    if unsafe { libc::stat(path_z.as_ptr() as *const i8, &mut stat_buf) } != 0 {
        io::write_str(2, b"tar: cannot stat ");
        io::write_all(2, path);
        io::write_str(2, b"\n");
        return 1;
    }

    let mode = stat_buf.st_mode;
    let is_dir = (mode & libc::S_IFMT) == libc::S_IFDIR;
    let is_link = (mode & libc::S_IFMT) == libc::S_IFLNK;

    if is_dir {
        // Add directory and recurse
        tar_add_dir_entry(fd, path, &stat_buf, verbose);
        // Recursively add directory contents
        let dir = unsafe { libc::opendir(path_z.as_ptr() as *const i8) };
        if !dir.is_null() {
            loop {
                let entry = unsafe { libc::readdir(dir) };
                if entry.is_null() { break; }
                let name = unsafe { io::cstr_to_slice((*entry).d_name.as_ptr() as *const u8) };
                if name == b"." || name == b".." { continue; }

                // Build full path
                let mut full_path = Vec::new();
                full_path.extend_from_slice(path);
                if !path.ends_with(b"/") {
                    full_path.push(b'/');
                }
                full_path.extend_from_slice(name);

                tar_add_file(fd, &full_path, verbose);
            }
            unsafe { libc::closedir(dir) };
        }
    } else if is_link {
        tar_add_link_entry(fd, path, &stat_buf, verbose);
    } else {
        tar_add_file_entry(fd, path, &stat_buf, verbose);
    }

    0
}

fn tar_add_dir_entry(fd: i32, path: &[u8], stat: &libc::stat, verbose: bool) {
    let mut header = TarHeader::new();

    // Name (with trailing slash for directories)
    let len = path.len().min(99);
    header.name[..len].copy_from_slice(&path[..len]);
    if len < 99 && !path.ends_with(b"/") {
        header.name[len] = b'/';
    }

    // Mode
    write_octal(&mut header.mode[..7], (stat.st_mode & 0o7777) as u64);

    // UID/GID
    write_octal(&mut header.uid[..7], stat.st_uid as u64);
    write_octal(&mut header.gid[..7], stat.st_gid as u64);

    // Size (0 for directories)
    write_octal(&mut header.size[..11], 0);

    // Mtime
    write_octal(&mut header.mtime[..11], stat.st_mtime as u64);

    // Type flag - directory
    header.typeflag = b'5';

    // USTAR magic
    header.magic = *b"ustar ";
    header.version = *b" \0";

    header.set_checksum();

    let header_bytes = unsafe {
        core::slice::from_raw_parts(&header as *const _ as *const u8, 512)
    };
    io::write_all(fd, header_bytes);

    if verbose {
        io::write_all(1, path);
        io::write_str(1, b"/\n");
    }
}

fn tar_add_link_entry(fd: i32, path: &[u8], stat: &libc::stat, verbose: bool) {
    let mut header = TarHeader::new();

    // Name
    let len = path.len().min(100);
    header.name[..len].copy_from_slice(&path[..len]);

    // Mode
    write_octal(&mut header.mode[..7], (stat.st_mode & 0o7777) as u64);

    // UID/GID
    write_octal(&mut header.uid[..7], stat.st_uid as u64);
    write_octal(&mut header.gid[..7], stat.st_gid as u64);

    // Size (0 for symlinks)
    write_octal(&mut header.size[..11], 0);

    // Mtime
    write_octal(&mut header.mtime[..11], stat.st_mtime as u64);

    // Read link target
    let mut path_z = [0u8; 256];
    let plen = path.len().min(255);
    path_z[..plen].copy_from_slice(&path[..plen]);

    let mut linkbuf = [0u8; 100];
    let link_len = unsafe {
        libc::readlink(path_z.as_ptr() as *const i8, linkbuf.as_mut_ptr() as *mut i8, 100)
    };
    if link_len > 0 {
        header.linkname[..link_len as usize].copy_from_slice(&linkbuf[..link_len as usize]);
    }

    // Type flag - symlink
    header.typeflag = b'2';

    // USTAR magic
    header.magic = *b"ustar ";
    header.version = *b" \0";

    header.set_checksum();

    let header_bytes = unsafe {
        core::slice::from_raw_parts(&header as *const _ as *const u8, 512)
    };
    io::write_all(fd, header_bytes);

    if verbose {
        io::write_all(1, path);
        io::write_str(1, b"\n");
    }
}

fn tar_add_file_entry(fd: i32, path: &[u8], stat: &libc::stat, verbose: bool) {
    let mut header = TarHeader::new();

    // Name
    let len = path.len().min(100);
    header.name[..len].copy_from_slice(&path[..len]);

    // Mode
    write_octal(&mut header.mode[..7], (stat.st_mode & 0o7777) as u64);

    // UID/GID
    write_octal(&mut header.uid[..7], stat.st_uid as u64);
    write_octal(&mut header.gid[..7], stat.st_gid as u64);

    // Size
    let size = stat.st_size as u64;
    write_octal(&mut header.size[..11], size);

    // Mtime
    write_octal(&mut header.mtime[..11], stat.st_mtime as u64);

    // Type flag - regular file
    header.typeflag = b'0';

    // USTAR magic
    header.magic = *b"ustar ";
    header.version = *b" \0";

    header.set_checksum();

    let header_bytes = unsafe {
        core::slice::from_raw_parts(&header as *const _ as *const u8, 512)
    };
    io::write_all(fd, header_bytes);

    // Write file content
    let mut path_z = [0u8; 256];
    let plen = path.len().min(255);
    path_z[..plen].copy_from_slice(&path[..plen]);

    let file_fd = open_read(&path_z);
    if file_fd >= 0 {
        let mut buf = [0u8; 512];
        let mut remaining = size;
        while remaining > 0 {
            let to_read = remaining.min(512) as usize;
            let n = io::read(file_fd, &mut buf[..to_read]);
            if n <= 0 { break; }
            // Pad last block to 512 bytes
            if (n as usize) < 512 {
                for i in (n as usize)..512 {
                    buf[i] = 0;
                }
            }
            io::write_all(fd, &buf);
            remaining -= n as u64;
        }
        io::close(file_fd);
    }

    if verbose {
        io::write_all(1, path);
        io::write_str(1, b"\n");
    }
}

fn tar_extract(archive: &[u8], files: &[&[u8]], verbose: bool) -> i32 {
    let fd = open_read(archive);
    if fd < 0 {
        io::write_str(2, b"tar: cannot open archive\n");
        return 1;
    }

    let mut header_buf = [0u8; 512];

    loop {
        if io::read(fd, &mut header_buf) != 512 {
            break;
        }

        let header = unsafe { &*(header_buf.as_ptr() as *const TarHeader) };

        if header.is_empty() {
            break;
        }

        let name = header.get_name();
        let size = header.get_size();
        let mode = header.get_mode();

        // Check if this file matches the filter (if any)
        let should_extract = files.is_empty() || files.iter().any(|&f| {
            name.starts_with(f) || f == name
        });

        if should_extract {
            match header.typeflag {
                b'5' | b'\0' if name.ends_with(b"/") => {
                    // Directory
                    let mut path_z = [0u8; 256];
                    let len = name.len().min(255);
                    path_z[..len].copy_from_slice(&name[..len]);
                    unsafe { libc::mkdir(path_z.as_ptr() as *const i8, mode) };
                    if verbose {
                        io::write_all(1, name);
                        io::write_str(1, b"\n");
                    }
                }
                b'2' => {
                    // Symlink
                    let target = {
                        let len = header.linkname.iter().position(|&c| c == 0).unwrap_or(100);
                        &header.linkname[..len]
                    };
                    let mut name_z = [0u8; 256];
                    let mut target_z = [0u8; 256];
                    let nlen = name.len().min(255);
                    let tlen = target.len().min(255);
                    name_z[..nlen].copy_from_slice(&name[..nlen]);
                    target_z[..tlen].copy_from_slice(&target[..tlen]);
                    unsafe { libc::symlink(target_z.as_ptr() as *const i8, name_z.as_ptr() as *const i8) };
                    if verbose {
                        io::write_all(1, name);
                        io::write_str(1, b"\n");
                    }
                }
                b'0' | b'\0' => {
                    // Regular file
                    extract_file(name, fd, size, mode, verbose);
                }
                _ => {
                    // Skip unknown types
                }
            }
        }

        // Skip file content blocks
        if size > 0 && (header.typeflag == b'0' || header.typeflag == 0) {
            let blocks = (size + 511) / 512;
            if !should_extract {
                for _ in 0..blocks {
                    io::read(fd, &mut header_buf);
                }
            }
        }
    }

    io::close(fd);
    0
}

fn extract_file(name: &[u8], archive_fd: i32, size: u64, mode: u32, verbose: bool) {
    // Create parent directories if needed
    create_parent_dirs(name);

    let mut path_z = [0u8; 256];
    let len = name.len().min(255);
    path_z[..len].copy_from_slice(&name[..len]);

    let fd = open_write_create(&path_z, mode as i32);
    if fd < 0 {
        io::write_str(2, b"tar: cannot create ");
        io::write_all(2, name);
        io::write_str(2, b"\n");
        // Still need to skip the blocks
        let blocks = (size + 511) / 512;
        let mut skip_buf = [0u8; 512];
        for _ in 0..blocks {
            io::read(archive_fd, &mut skip_buf);
        }
        return;
    }

    let mut remaining = size;
    let mut buf = [0u8; 512];
    while remaining > 0 {
        if io::read(archive_fd, &mut buf) != 512 {
            break;
        }
        let to_write = remaining.min(512) as usize;
        io::write_all(fd, &buf[..to_write]);
        remaining -= to_write as u64;
    }

    io::close(fd);

    if verbose {
        io::write_all(1, name);
        io::write_str(1, b"\n");
    }
}

fn tar_list(archive: &[u8], verbose: bool) -> i32 {
    let fd = open_read(archive);
    if fd < 0 {
        io::write_str(2, b"tar: cannot open archive\n");
        return 1;
    }

    let mut header_buf = [0u8; 512];

    loop {
        if io::read(fd, &mut header_buf) != 512 {
            break;
        }

        let header = unsafe { &*(header_buf.as_ptr() as *const TarHeader) };

        if header.is_empty() {
            break;
        }

        let name = header.get_name();
        let size = header.get_size();

        if verbose {
            // Show mode, size, name
            let mode = header.get_mode();
            let type_char = match header.typeflag {
                b'5' => b'd',
                b'2' => b'l',
                _ => b'-',
            };
            io::write_all(1, &[type_char]);
            io::write_all(1, &mode_string(mode));
            io::write_str(1, b" ");
            io::write_num(1, size);
            io::write_str(1, b" ");
        }
        io::write_all(1, name);
        io::write_str(1, b"\n");

        // Skip file content blocks
        if size > 0 && (header.typeflag == b'0' || header.typeflag == 0) {
            let blocks = (size + 511) / 512;
            for _ in 0..blocks {
                io::read(fd, &mut header_buf);
            }
        }
    }

    io::close(fd);
    0
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::process::Command;
    use std::path::PathBuf;

    fn get_armybox_path() -> PathBuf {
        if let Ok(path) = std::env::var("ARMYBOX_PATH") {
            return PathBuf::from(path);
        }
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| std::env::current_dir().unwrap());
        let release = manifest_dir.join("target/release/armybox");
        if release.exists() { return release; }
        manifest_dir.join("target/debug/armybox")
    }

    #[test]
    fn test_tar_no_archive() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["tar", "-c"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("-f archive required"));
    }

    #[test]
    fn test_tar_no_mode() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let output = Command::new(&armybox)
            .args(["tar", "-f", "test.tar"])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(1));
        let stderr = std::string::String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("specify -c, -x, or -t"));
    }

    #[test]
    fn test_tar_create_and_list() {
        let armybox = get_armybox_path();
        if !armybox.exists() { return; }

        let dir = std::env::temp_dir().join("armybox_tar_test");
        let _ = std::fs::create_dir_all(&dir);
        std::fs::write(dir.join("testfile.txt"), "hello world").unwrap();

        let tar_path = dir.join("test.tar");

        // Create
        let output = Command::new(&armybox)
            .args(["tar", "-cf", tar_path.to_str().unwrap(),
                   dir.join("testfile.txt").to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));

        // List
        let output = Command::new(&armybox)
            .args(["tar", "-tf", tar_path.to_str().unwrap()])
            .output()
            .unwrap();

        assert_eq!(output.status.code(), Some(0));
        let stdout = std::string::String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("testfile.txt"));

        let _ = std::fs::remove_dir_all(&dir);
    }
}