cpio_reader-0.1.2/.cargo_vcs_info.json0000644000000001360000000000100133100ustar { "git": { "sha1": "98d23605c5c45e9d049c12d690e2f429a38015f3" }, "path_in_vcs": "" }cpio_reader-0.1.2/.github/FUNDING.yml000064400000000000000000000000221046102023000152470ustar 00000000000000github: toku-sa-n cpio_reader-0.1.2/.github/dependabot.yml000064400000000000000000000002211046102023000162630ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "20:00" open-pull-requests-limit: 10 cpio_reader-0.1.2/.github/workflows/rust.yml000064400000000000000000000020141046102023000172120ustar 00000000000000name: Rust on: [push, pull_request] env: CARGO_TERM_COLOR: always RUSTFLAGS: -D warnings -D absolute_paths_not_starting_with_crate -D elided_lifetimes_in_paths -D explicit_outlives_requirements -D macro_use_extern_crate -D meta_variable_misuse -D missing_abi -D missing_copy_implementations -D missing_debug_implementations -D non_ascii_idents -D semicolon_in_expressions_from_macros -D trivial_casts -D trivial_numeric_casts -D unreachable_pub -D unused_extern_crates -D unused_import_braces -D unused_lifetimes -D unused_qualifications -D rustdoc::all -D missing_docs jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run rustfmt with check mode run: | cargo fmt -- --check - uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} args: -- -D clippy::pedantic -D clippy::all - name: Build run: cargo build - name: Build documentations run: cargo doc - name: Run tests run: cargo test cpio_reader-0.1.2/.gitignore000064400000000000000000000000301046102023000140610ustar 00000000000000/target Cargo.lock tags cpio_reader-0.1.2/CHANGELOG.md000064400000000000000000000013411046102023000137100ustar 00000000000000# Changelog ## [Unreleased] ## [0.1.2] - 2025-05-17 ### Fixed - Fixed an issue where user and world permissions bits were reversed. ([#15]) ## [0.1.1] - 2022-07-21 ### Fixed - References returned by `Entry::(file|name)` are now alive as long as the underlying data ([#8]). ## [0.1.0] - 2021-08-23 ### Added - Initial version. [#15]: https://github.com/toku-sa-n/cpio_reader/pull/15 [#8]: https://github.com/toku-sa-n/cpio_reader/pull/8 [Unreleased]: https://github.com/toku-sa-n/cpio_reader/compare/v0.1.2...HEAD [0.1.2]: https://github.com/toku-sa-n/cpio_reader/compare/v0.1.1...v0.1.2 [0.1.1]: https://github.com/toku-sa-n/cpio_reader/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/toku-sa-n/cpio_reader/releases/tag/v0.1.0 cpio_reader-0.1.2/Cargo.lock0000644000000005730000000000100112700ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "bitflags" version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "cpio_reader" version = "0.1.2" dependencies = [ "bitflags", ] cpio_reader-0.1.2/Cargo.toml0000644000000020630000000000100113070ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "cpio_reader" version = "0.1.2" authors = ["Hiroki Tokunaga "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A library to read the contents of cpio files" readme = "README.md" keywords = [ "no_std", "cpio", ] categories = ["no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/toku-sa-n/cpio_reader" [lib] name = "cpio_reader" path = "src/lib.rs" [[test]] name = "read_cpios" path = "tests/read_cpios.rs" [dependencies.bitflags] version = "2.0.0" cpio_reader-0.1.2/Cargo.toml.orig000064400000000000000000000005701046102023000147710ustar 00000000000000[package] name = "cpio_reader" version = "0.1.2" authors = ["Hiroki Tokunaga "] edition = "2018" license = "MIT OR Apache-2.0" description = "A library to read the contents of cpio files" repository = "https://github.com/toku-sa-n/cpio_reader" readme = "README.md" categories = ["no-std"] keywords = ["no_std", "cpio"] [dependencies] bitflags = "2.0.0" cpio_reader-0.1.2/LICENSE-APACHE000064400000000000000000000261361046102023000140340ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. cpio_reader-0.1.2/LICENSE-MIT000064400000000000000000000020611046102023000135330ustar 00000000000000MIT License Copyright (c) 2021 Hiroki Tokunaga 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. cpio_reader-0.1.2/README.md000064400000000000000000000025461046102023000133660ustar 00000000000000# `cpio_reader` [![GitHub Actions](https://github.com/toku-sa-n/cpio_reader/workflows/Rust/badge.svg)](https://github.com/toku-sa-n/cpio_reader/actions) [![Crates.io](https://img.shields.io/crates/v/cpio_reader)](https://crates.io/crates/cpio_reader) ![Crates.io](https://img.shields.io/crates/l/cpio_reader) [![docs.rs](https://docs.rs/cpio_reader/badge.svg)](https://docs.rs/cpio_reader) A library to read the contents of the cpio file. (.cpio) This library is based on the design written `man 5 cpio` and supports these four formats. - Old Binary Format - Portable ASCII Format - New ASCII Format - New CRC Format This library is `#![no_std]` compatible. ## Examples ```rust use std::fs; let cpio = fs::read("tests/newc.cpio").unwrap(); for entry in cpio_reader::iter_files(&cpio) { println!("Entry name: {}, content: {:?}", entry.name(), entry.file()); } ``` ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) at your option. ## Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. cpio_reader-0.1.2/src/lib.rs000064400000000000000000000355071046102023000140150ustar 00000000000000#![doc = include_str!("../README.md")] #![no_std] #![deny(unsafe_code)] use { bitflags::bitflags, core::{convert::TryInto, str}, }; /// Returns an iterator that iterates over each content of the given cpio file. /// /// The iterator checks if the header of an entry is correct. If it is corrupt (e.g., wrong magic /// value), the iterator stops iterating. pub fn iter_files(cpio_binary: &[u8]) -> impl Iterator> { Iter::new(cpio_binary) } /// An entry of a cpio file. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Entry<'a> { dev: Option, devmajor: Option, devminor: Option, ino: u32, mode: Mode, uid: u32, gid: u32, nlink: u32, rdev: Option, rdevmajor: Option, rdevminor: Option, mtime: u64, name: &'a str, file: &'a [u8], } impl<'a> Entry<'a> { /// Returns the device number of the device which contained the file. /// /// This method returns [`None`] if the cpio file format is either New ASCII Format or New CRC /// Format. For these formats, use [`Entry::devmajor`] and [`Entry::devminor`]. #[must_use] pub fn dev(&self) -> Option { self.dev } /// Returns the major number of the device which contained the file. /// /// This method returns [`None`] if the entry format is either Old Binary Format or Portable /// ASCII Format. For these formats, use [`Entry::dev`]. #[must_use] pub fn devmajor(&self) -> Option { self.devmajor } /// Returns the minor number of the device which contained the file. /// /// This method returns [`None`] if the entry format is either Old Binary Format or Portable /// ASCII Format. For these formats, use [`Entry::dev`]. #[must_use] pub fn devminor(&self) -> Option { self.devminor } /// Returns the inode number of the file. #[must_use] pub fn ino(&self) -> u32 { self.ino } /// Returns the [`Mode`] value of the file, which contains the file's permission information /// and file type. #[must_use] pub fn mode(&self) -> Mode { self.mode } /// Returns the user id of the owner of the file. #[must_use] pub fn uid(&self) -> u32 { self.uid } /// Returns the group id of the owner of the file. #[must_use] pub fn gid(&self) -> u32 { self.gid } /// Returns the number of links to this file. #[must_use] pub fn nlink(&self) -> u32 { self.nlink } /// Returns the associated device number if the entry is block special device or character /// special device. For the other types of entries, the caller should not use this method. /// /// This method returns [`None`] if the entry format is either New ASCII Format or New CRC /// Format. For these formats, use [`Entry::rdevmajor`] and [`Entry::rdevminor`]. #[must_use] pub fn rdev(&self) -> Option { self.rdev } /// Returns the associated device major number if the entry is block special device or /// character special device. For the other types of entries, the caller should not use this /// method. /// /// This method returns [`None`] if the entry format is either Old Binary Format or Portable /// ASCII Format. For these formats, use [`Entry::rdev`]. #[must_use] pub fn rdevmajor(&self) -> Option { self.rdevmajor } /// Returns the associated device minor number if the entry is block special device or /// character special device. For the other types of entries, the caller should not use this /// method. /// /// This method returns [`None`] if the entry format is either Old Binary Format or Portable /// ASCII Format. For these formats, use [`Entry::rdev`]. #[must_use] pub fn rdevminor(&self) -> Option { self.rdevminor } /// Returns the modification time of this file. #[must_use] pub fn mtime(&self) -> u64 { self.mtime } /// Returns the filename. #[must_use] pub fn name(&self) -> &'a str { self.name } /// Returns the content of this file. /// /// This method returns the path to the original file if the file is a symbolic link. For the /// New ASCII Format and New CRC Format, this method returns an empty slice if the file is a /// hard link and is not the last entry of the multiple duplicate files. #[must_use] pub fn file(&self) -> &'a [u8] { self.file } fn interpret_as_old_binary(binary: &'a [u8]) -> Option<(Self, &'a [u8])> { const MAGIC: u16 = 0o070_707; let mut byte_array = ByteArray::new(binary); let magic = [byte_array.proceed_byte()?, byte_array.proceed_byte()?]; let endianness = if u16::from_be_bytes(magic) == MAGIC { Endianness::Big } else if u16::from_le_bytes(magic) == MAGIC { Endianness::Little } else { return None; }; let dev = byte_array.proceed_u16(endianness)?; let ino = byte_array.proceed_u16(endianness)?; let mode = byte_array.proceed_u16(endianness)?; let u_id = byte_array.proceed_u16(endianness)?; let g_id = byte_array.proceed_u16(endianness)?; let nlink = byte_array.proceed_u16(endianness)?; let r_dev = byte_array.proceed_u16(endianness)?; let mtime_most: u64 = byte_array.proceed_u16(endianness)?.into(); let mtime_least: u64 = byte_array.proceed_u16(endianness)?.into(); let namesize = byte_array.proceed_u16(endianness)?; let filesize_most_byte: u32 = byte_array.proceed_u16(endianness)?.into(); let filesize_least_byte: u32 = byte_array.proceed_u16(endianness)?.into(); let filesize = (filesize_most_byte << 16) | filesize_least_byte; if namesize == 0 { return None; } let name = byte_array.proceed_str((namesize - 1).into())?; byte_array.skip_bytes((namesize % 2 + 1).into()); // +1 for the terminating null character. let file = byte_array.proceed_bytes(filesize.try_into().unwrap())?; let mode = Mode::from_bits(mode.into())?; let old_binary = Self { dev: Some(dev.into()), devmajor: None, devminor: None, ino: ino.into(), mode, uid: u_id.into(), gid: g_id.into(), nlink: nlink.into(), rdev: Some(r_dev.into()), rdevmajor: None, rdevminor: None, mtime: (mtime_most << 16) | mtime_least, name, file, }; byte_array.skip_bytes((filesize % 2).try_into().unwrap()); Some((old_binary, byte_array.into_inner())) } fn interpret_as_portable_ascii(binary: &'a [u8]) -> Option<(Self, &'a [u8])> { const MAGIC: &str = "070707"; let mut byte_array = ByteArray::new(binary); let magic = byte_array.proceed_str(6)?; if magic != MAGIC { return None; } let dev = byte_array.proceed_str_into_octal_u32(6)?; let ino = byte_array.proceed_str_into_octal_u32(6)?; let mode = byte_array.proceed_str_into_octal_u32(6)?; let u_id = byte_array.proceed_str_into_octal_u32(6)?; let g_id = byte_array.proceed_str_into_octal_u32(6)?; let nlink = byte_array.proceed_str_into_octal_u32(6)?; let r_dev = byte_array.proceed_str_into_octal_u32(6)?; let mtime = byte_array.proceed_str_into_octal_u64(11)?; let namesize = byte_array.proceed_str_into_octal_u32(6)?; let filesize = byte_array.proceed_str_into_octal_u64(11)?; if namesize == 0 { return None; } let name = byte_array.proceed_str((namesize - 1).try_into().unwrap())?; byte_array.skip_bytes(1); // For the terminating '\0'. let file = byte_array.proceed_bytes(filesize.try_into().unwrap())?; let mode = Mode::from_bits(mode)?; let portable_ascii = Self { dev: Some(dev), devmajor: None, devminor: None, ino, mode, uid: u_id, gid: g_id, nlink, rdev: Some(r_dev), rdevmajor: None, rdevminor: None, mtime, name, file, }; Some((portable_ascii, byte_array.into_inner())) } fn interpret_as_new_ascii_or_crc(binary: &'a [u8]) -> Option<(Self, &'a [u8])> { const MAGIC_NEW_ASCII: &str = "070701"; const MAGIC_CRC: &str = "070702"; let mut byte_array = ByteArray::new(binary); let is_crc = match byte_array.proceed_str(6)? { MAGIC_CRC => true, MAGIC_NEW_ASCII => false, _ => return None, }; let ino = byte_array.proceed_str_into_hex()?; let mode = byte_array.proceed_str_into_hex()?; let u_id = byte_array.proceed_str_into_hex()?; let g_id = byte_array.proceed_str_into_hex()?; let nlink = byte_array.proceed_str_into_hex()?; let mtime: u64 = byte_array.proceed_str_into_hex()?.into(); let filesize = byte_array.proceed_str_into_hex()?; let devmajor = byte_array.proceed_str_into_hex()?; let devminor = byte_array.proceed_str_into_hex()?; let r_devmajor = byte_array.proceed_str_into_hex()?; let r_devminor = byte_array.proceed_str_into_hex()?; let namesize = byte_array.proceed_str_into_hex()?; let check = byte_array.proceed_str_into_hex()?; if namesize == 0 { return None; } let name = byte_array.proceed_str((namesize - 1).try_into().unwrap())?; // For the terminating `\0`. byte_array.skip_bytes(1); byte_array.skip_to_next_multiple_of_four(); let file = byte_array.proceed_bytes(filesize.try_into().unwrap())?; let mode = Mode::from_bits(mode)?; let checksum = file .iter() .fold(0_u32, |acc, &x| acc.wrapping_add(x.into())); // Refer to line 1277, copyin.c, GNU cpio 2.13. It does not check the checksum of the // symbolic files. if is_crc && !mode.contains(Mode::SYMBOLIK_LINK) && (checksum != check) { return None; } let new_ascii = Self { ino, mode, uid: u_id, gid: g_id, nlink, mtime, dev: None, devmajor: Some(devmajor), devminor: Some(devminor), rdev: None, rdevmajor: Some(r_devmajor), rdevminor: Some(r_devminor), name, file, }; byte_array.skip_to_next_multiple_of_four(); Some((new_ascii, byte_array.into_inner())) } fn new(binary: &'a [u8]) -> Option<(Self, &'a [u8])> { Self::interpret_as_old_binary(binary) .or_else(|| Self::interpret_as_portable_ascii(binary)) .or_else(|| Self::interpret_as_new_ascii_or_crc(binary)) .filter(|(entry, _)| entry.name() != "TRAILER!!!") } } bitflags! { /// File information. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Mode: u32 { /// User executable bit. const USER_EXECUTABLE = 0o000_100; /// User writable bit. const USER_WRITABLE = 0o000_200; /// User readable bit. const USER_READABLE = 0o000_400; /// Group executable bit. const GROUP_EXECUTABLE = 0o000_010; /// Group writable bit. const GROUP_WRITABLE = 0o000_020; /// Group readable bit. const GROUP_READABLE = 0o000_040; /// Executable bit for the other groups. const WORLD_EXECUTABLE = 0o000_001; /// Writable bit for the other groups. const WORLD_WRITABLE = 0o000_002; /// Readable bit for the other groups. const WORLD_READABLE = 0o000_004; /// Sticky bit. const STICKY = 0o001_000; /// SGID bit. const SGID = 0o002_000; /// SUID bit. const SUID = 0o004_000; /// Named pipe or FIFO. const NAMED_PIPE_FIFO = 0o010_000; /// Character special device. const CHARACTER_SPECIAL_DEVICE = 0o020_000; /// Directory. const DIRECTORY = 0o040_000; /// Block special device. const BLOCK_SPECIAL_DEVICE = 0o060_000; /// Regular file. const REGULAR_FILE = 0o100_000; /// Symbolik link. const SYMBOLIK_LINK = 0o120_000; /// Socket. const SOCKET = 0o140_000; } } struct Iter<'a>(&'a [u8]); impl<'a> Iter<'a> { fn new(binary: &'a [u8]) -> Self { Self(binary) } } impl<'a> Iterator for Iter<'a> { type Item = Entry<'a>; fn next(&mut self) -> Option { if self.0.is_empty() { None } else { let (entry, remaining) = Entry::new(self.0)?; self.0 = remaining; Some(entry) } } } struct ByteArray<'a> { binary: &'a [u8], current: usize, } impl<'a> ByteArray<'a> { fn new(binary: &'a [u8]) -> Self { Self { binary, current: 0 } } fn into_inner(self) -> &'a [u8] { self.binary } fn proceed_byte(&mut self) -> Option { let byte = self.binary.first().copied()?; self.skip_bytes(1); Some(byte) } fn proceed_bytes(&mut self, n: usize) -> Option<&'a [u8]> { let bytes = self.binary.get(..n)?; self.skip_bytes(n); Some(bytes) } fn proceed_str_into_octal_u32(&mut self, n: usize) -> Option { self.proceed_str(n) .and_then(|s| u32::from_str_radix(s, 8).ok()) } fn proceed_str_into_octal_u64(&mut self, n: usize) -> Option { self.proceed_str(n) .and_then(|s| u64::from_str_radix(s, 8).ok()) } fn proceed_str_into_hex(&mut self) -> Option { self.proceed_str(8) .and_then(|s| u32::from_str_radix(s, 16).ok()) } fn proceed_str(&mut self, n: usize) -> Option<&'a str> { self.proceed_bytes(n) .and_then(|bytes| str::from_utf8(bytes).ok()) } fn proceed_u16(&mut self, endianness: Endianness) -> Option { Some(endianness.u8_array_to_u16([self.proceed_byte()?, self.proceed_byte()?])) } fn skip_to_next_multiple_of_four(&mut self) { self.skip_bytes((4 - self.current % 4) % 4); } fn skip_bytes(&mut self, n: usize) { self.binary = self.binary.get(n..).unwrap_or_default(); self.current += n; } } #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] enum Endianness { Big, Little, } impl Endianness { fn u8_array_to_u16(self, bytes: [u8; 2]) -> u16 { match self { Self::Big => u16::from_be_bytes(bytes), Self::Little => u16::from_le_bytes(bytes), } } } cpio_reader-0.1.2/tests/bin.cpio000064400000000000000000000010001046102023000146550ustar 00000000000000q!a derichskills/derichqA!aNskillsq!askills/derichKing qA!amagicsq!amagics/derichKing q!a magics/rosemaryMother green q TRAILER!!!cpio_reader-0.1.2/tests/crc.cpio000064400000000000000000000020001046102023000146550ustar 00000000000000070702000001840000A1FF000003E8000003E8000000016827DA3C0000000D000000000000001A00000000000000000000000700000000derichskills/derich07070200000182000041ED000003E8000003E8000000026827DA3C00000000000000000000001A00000000000000000000000700000000skills07070200000180000041ED000003E8000003E8000000026827DA3C00000000000000000000001A00000000000000000000000700000000magics07070200000183000081A4000003E8000003E8000000026827DA3C00000000000000000000001A00000000000000000000000E00000000skills/derich07070200000183000081A4000003E8000003E8000000026827DA3C00000005000000000000001A00000000000000000000000E00000193magics/derichKing 07070200000181000081E9000003E8000003E8000000016827DA3C0000000D000000000000001A000000000000000000000010000004AAmagics/rosemaryMother green 07070200000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!cpio_reader-0.1.2/tests/newc.cpio000064400000000000000000000020001046102023000150420ustar 000000000000000707010000017C0000A1FF000003E8000003E8000000016827DA360000000D000000000000001A00000000000000000000000700000000derichskills/derich0707010000017A000041ED000003E8000003E8000000026827DA3600000000000000000000001A00000000000000000000000700000000skills07070100000178000041ED000003E8000003E8000000026827DA3600000000000000000000001A00000000000000000000000700000000magics0707010000017B000081A4000003E8000003E8000000026827DA3600000000000000000000001A00000000000000000000000E00000000skills/derich0707010000017B000081A4000003E8000003E8000000026827DA3600000005000000000000001A00000000000000000000000E00000000magics/derichKing 07070100000179000081E9000003E8000003E8000000016827DA360000000D000000000000001A00000000000000000000001000000000magics/rosemaryMother green 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!cpio_reader-0.1.2/tests/odc.cpio000064400000000000000000000020001046102023000146530ustar 000000000000000707070040021372641207770017500017500000010000001411037271000000700000000015derichskills/derich0707070040021372620407550017500017500000020000001411037311600000700000000000skills0707070040021372711006440017500017500000020000001411037264000001600000000005skills/derichKing 0707070040021372670407550017500017500000020000001411037270200000700000000000magics0707070040021372711006440017500017500000020000001411037264000001600000000005magics/derichKing 0707070040021372741006440017500017500000010000001411037270100002000000000015magics/rosemaryMother green 0707070000000000000000000000000000000000010000000000000000000001300000000000TRAILER!!!cpio_reader-0.1.2/tests/read_cpios.rs000064400000000000000000000247371046102023000157350ustar 00000000000000#![allow(missing_docs)] use std::{fs, vec::Vec}; use cpio_reader::Mode; #[derive(PartialEq, Eq, Hash, Debug, Clone)] struct ExpectedEntryInfo { name: String, file: Vec, mode: Mode, uid: u32, gid: u32, ino: u32, mtime: u64, nlink: u32, dev: Option, devmajor: Option, devminor: Option, rdev: Option, rdevmajor: Option, rdevminor: Option, } #[test] fn read_bin() { general_test("tests/bin.cpio", test_files_for_bin_and_odc()); } #[test] fn read_odc() { general_test("tests/odc.cpio", test_files_for_bin_and_odc()); } #[test] fn read_newc() { general_test("tests/newc.cpio", test_files_for_newc()); } #[test] fn read_crc() { general_test("tests/crc.cpio", test_files_for_crc()); } // https://github.com/toku-sa-n/cpio_reader/pull/8 #[test] fn file_and_entry_live_as_long_as_underlying_data() { let bin = fs::read("tests/crc.cpio").unwrap(); let file_finder = |name_to_find: &str| { for entry in cpio_reader::iter_files(&bin) { if entry.name() == name_to_find { return Some((entry.name().to_string(), entry.file().to_vec())); } } None }; assert_eq!( file_finder("magics/derich"), Some(("magics/derich".to_string(), "King\n".as_bytes().to_vec())) ); } fn general_test(cpio_filename: &'static str, expected_entries_vec: Vec) { let bin_cpio = fs::read(cpio_filename).unwrap(); let collected_entries_vec = cpio_reader::iter_files(&bin_cpio) .map(|entry| ExpectedEntryInfo { name: entry.name().to_string(), file: entry.file().to_vec(), mode: entry.mode(), uid: entry.uid(), gid: entry.gid(), ino: entry.ino(), mtime: entry.mtime(), nlink: entry.nlink(), dev: entry.dev(), devmajor: entry.devmajor(), devminor: entry.devminor(), rdev: entry.rdev(), rdevmajor: entry.rdevmajor(), rdevminor: entry.rdevminor(), }) .collect::>(); assert_eq!( collected_entries_vec.len(), expected_entries_vec.len(), "Number of entries mismatch for {}", cpio_filename ); for (idx, (collected, expected)) in collected_entries_vec .iter() .zip(expected_entries_vec.iter()) .enumerate() { assert_eq!( collected, expected, "Mismatch at entry index {} for file {}", idx, cpio_filename ); } } fn test_files_for_bin_and_odc() -> Vec { let mut v = Vec::new(); v.push(ExpectedEntryInfo { name: "derich".to_string(), file: "skills/derich".as_bytes().to_vec(), mode: Mode::SYMBOLIK_LINK | Mode::from_bits_truncate(0o777), uid: 1000, gid: 1000, ino: 48820, mtime: 1629615560, nlink: 1, dev: Some(2050), devmajor: None, devminor: None, rdev: Some(0), rdevmajor: None, rdevminor: None, }); v.push(ExpectedEntryInfo { name: "skills".to_string(), file: vec![], mode: Mode::DIRECTORY | Mode::from_bits_truncate(0o755), uid: 1000, gid: 1000, ino: 48818, mtime: 1629615694, nlink: 2, dev: Some(2050), devmajor: None, devminor: None, rdev: Some(0), rdevmajor: None, rdevminor: None, }); v.push(ExpectedEntryInfo { name: "skills/derich".to_string(), file: "King\n".as_bytes().to_vec(), mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o644), uid: 1000, gid: 1000, ino: 48825, mtime: 1629615520, nlink: 2, dev: Some(2050), devmajor: None, devminor: None, rdev: Some(0), rdevmajor: None, rdevminor: None, }); v.push(ExpectedEntryInfo { name: "magics".to_string(), file: vec![], mode: Mode::DIRECTORY | Mode::from_bits_truncate(0o755), uid: 1000, gid: 1000, ino: 48823, mtime: 1629615554, nlink: 2, dev: Some(2050), devmajor: None, devminor: None, rdev: Some(0), rdevmajor: None, rdevminor: None, }); v.push(ExpectedEntryInfo { name: "magics/derich".to_string(), file: "King\n".as_bytes().to_vec(), mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o644), uid: 1000, gid: 1000, ino: 48825, mtime: 1629615520, nlink: 2, dev: Some(2050), devmajor: None, devminor: None, rdev: Some(0), rdevmajor: None, rdevminor: None, }); v.push(ExpectedEntryInfo { name: "magics/rosemary".to_string(), file: "Mother green\n".as_bytes().to_vec(), mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o644), uid: 1000, gid: 1000, ino: 48828, mtime: 1629615553, nlink: 1, dev: Some(2050), devmajor: None, devminor: None, rdev: Some(0), rdevmajor: None, rdevminor: None, }); v } fn test_files_for_newc() -> Vec { let mut v = Vec::new(); v.push(ExpectedEntryInfo { name: "derich".to_string(), file: "skills/derich".as_bytes().to_vec(), mode: Mode::SYMBOLIK_LINK | Mode::from_bits_truncate(0o777), uid: 1000, gid: 1000, nlink: 1, ino: 380, mtime: 1747442230, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "skills".to_string(), file: vec![], mode: Mode::DIRECTORY | Mode::from_bits_truncate(0o755), uid: 1000, gid: 1000, nlink: 2, ino: 378, mtime: 1747442230, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "magics".to_string(), file: vec![], mode: Mode::DIRECTORY | Mode::from_bits_truncate(0o755), uid: 1000, gid: 1000, nlink: 2, ino: 376, mtime: 1747442230, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "skills/derich".to_string(), file: vec![], mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o644), uid: 1000, gid: 1000, nlink: 2, ino: 379, mtime: 1747442230, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "magics/derich".to_string(), file: "King\n".as_bytes().to_vec(), mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o644), uid: 1000, gid: 1000, nlink: 2, ino: 379, mtime: 1747442230, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "magics/rosemary".to_string(), file: "Mother green\n".as_bytes().to_vec(), mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o751), uid: 1000, gid: 1000, nlink: 1, ino: 377, mtime: 1747442230, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v } fn test_files_for_crc() -> Vec { let mut v = Vec::new(); v.push(ExpectedEntryInfo { name: "derich".to_string(), file: "skills/derich".as_bytes().to_vec(), mode: Mode::SYMBOLIK_LINK | Mode::from_bits_truncate(0o777), uid: 1000, gid: 1000, nlink: 1, ino: 388, mtime: 1747442236, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "skills".to_string(), file: vec![], mode: Mode::DIRECTORY | Mode::from_bits_truncate(0o755), uid: 1000, gid: 1000, nlink: 2, ino: 386, mtime: 1747442236, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "magics".to_string(), file: vec![], mode: Mode::DIRECTORY | Mode::from_bits_truncate(0o755), uid: 1000, gid: 1000, nlink: 2, ino: 384, mtime: 1747442236, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "skills/derich".to_string(), file: vec![], mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o644), uid: 1000, gid: 1000, nlink: 2, ino: 387, mtime: 1747442236, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "magics/derich".to_string(), file: "King\n".as_bytes().to_vec(), mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o644), uid: 1000, gid: 1000, nlink: 2, ino: 387, mtime: 1747442236, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v.push(ExpectedEntryInfo { name: "magics/rosemary".to_string(), file: "Mother green\n".as_bytes().to_vec(), mode: Mode::REGULAR_FILE | Mode::from_bits_truncate(0o751), uid: 1000, gid: 1000, nlink: 1, ino: 385, mtime: 1747442236, devmajor: Some(0), devminor: Some(26), dev: None, rdev: None, rdevmajor: Some(0), rdevminor: Some(0), }); v }