From 8818dd8b7d27ba0c9a079e9639ed17d5d4199e56 Mon Sep 17 00:00:00 2001 From: ModSync CI Date: Mon, 23 Nov 2026 22:49:47 +0000 Subject: [PATCH] fix(unrar): use stdcall ("system") ABI for UnRAR FFI UnRAR's dll.hpp declares the API PASCAL and callbacks CALLBACK, both __stdcall on Windows. unrar_sys declared them extern "C", so the i686-pc-windows-msvc link looked for undecorated _RAR* symbols and failed. - vendor/unrar_sys: FFI block and ChangeVolProc/ProcessDataProc/Callback types are now extern "system" (stdcall on 32-bit x86 Windows, identical to "C" everywhere else). - vendor/unrar: vendor unrar 0.5.8 (production sources only) with its RARSetCallback callback changed to extern "system" so it matches the corrected type; wired through [patch.crates-io]. Cargo.lock only drops the registry source/checksum for the patched unrar. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QDKiomK3BZE8fScCAGRfuq --- Cargo.lock | 2 - Cargo.toml | 1 + vendor/unrar/Cargo.toml | 45 +++ vendor/unrar/LICENSE-APACHE | 176 ++++++++ vendor/unrar/LICENSE-MIT | 23 ++ vendor/unrar/README.md | 52 +++ vendor/unrar/src/archive.rs | 441 ++++++++++++++++++++ vendor/unrar/src/error.rs | 146 +++++++ vendor/unrar/src/lib.rs | 14 + vendor/unrar/src/open_archive.rs | 667 +++++++++++++++++++++++++++++++ vendor/unrar/src/pathed/all.rs | 32 ++ vendor/unrar/src/pathed/linux.rs | 32 ++ vendor/unrar/src/pathed/mod.rs | 5 + vendor/unrar_sys/README.md | 10 +- vendor/unrar_sys/src/lib.rs | 8 +- 15 files changed, 1647 insertions(+), 7 deletions(-) create mode 100644 vendor/unrar/Cargo.toml create mode 100644 vendor/unrar/LICENSE-APACHE create mode 100644 vendor/unrar/LICENSE-MIT create mode 100644 vendor/unrar/README.md create mode 100644 vendor/unrar/src/archive.rs create mode 100644 vendor/unrar/src/error.rs create mode 100644 vendor/unrar/src/lib.rs create mode 100644 vendor/unrar/src/open_archive.rs create mode 100644 vendor/unrar/src/pathed/all.rs create mode 100644 vendor/unrar/src/pathed/linux.rs create mode 100644 vendor/unrar/src/pathed/mod.rs diff --git a/Cargo.lock b/Cargo.lock index f60cc723..9783d6a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6127,8 +6127,6 @@ dependencies = [ [[package]] name = "unrar" version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ec61343a630d2b50d13216dea5125e157d3fc180a7d3f447d22fe146b648fc" dependencies = [ "bitflags 2.13.2", "regex", diff --git a/Cargo.toml b/Cargo.toml index 6c335989..47a12089 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -84,4 +84,5 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = [" # unrar_sys 0.5.8 build-host/target correction; see vendor/unrar_sys/README.md. [patch.crates-io] serde_json = { path = "vendor/serde_json" } +unrar = { path = "vendor/unrar" } unrar_sys = { path = "vendor/unrar_sys" } diff --git a/vendor/unrar/Cargo.toml b/vendor/unrar/Cargo.toml new file mode 100644 index 00000000..55733126 --- /dev/null +++ b/vendor/unrar/Cargo.toml @@ -0,0 +1,45 @@ +# 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 = "2021" +name = "unrar" +version = "0.5.8" +authors = [ + "Danyel Bayraktar ", + "vjoki ", +] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "list and extract RAR archives" +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/muja/unrar.rs" + +[lib] +name = "unrar" +path = "src/lib.rs" + +[dependencies.bitflags] +version = "2" + +[dependencies.regex] +version = "1" + +[dependencies.unrar_sys] +version = "0.5" + +[dependencies.widestring] +version = "1" diff --git a/vendor/unrar/LICENSE-APACHE b/vendor/unrar/LICENSE-APACHE new file mode 100644 index 00000000..1b5ec8b7 --- /dev/null +++ b/vendor/unrar/LICENSE-APACHE @@ -0,0 +1,176 @@ + 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 diff --git a/vendor/unrar/LICENSE-MIT b/vendor/unrar/LICENSE-MIT new file mode 100644 index 00000000..31aa7938 --- /dev/null +++ b/vendor/unrar/LICENSE-MIT @@ -0,0 +1,23 @@ +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. diff --git a/vendor/unrar/README.md b/vendor/unrar/README.md new file mode 100644 index 00000000..a1debc04 --- /dev/null +++ b/vendor/unrar/README.md @@ -0,0 +1,52 @@ +# Local unrar production build correction + +## Source provenance + +- Crate: `unrar` 0.5.8 from the existing crates.io registry cache. +- Original crates.io package SHA-256 (Cargo.lock checksum): + `92ec61343a630d2b50d13216dea5125e157d3fc180a7d3f447d22fe146b648fc`. +- Packaged VCS revision: `8fe139781b92d0678afecc568496f5805401a6c4`, repository + `https://github.com/muja/unrar.rs`, repository root. +- It depends on `unrar_sys` 0.5, which root Cargo.toml redirects to + `vendor/unrar_sys`. + +## Exact production patch + +1. `src/open_archive.rs`: `Internal::::callback`, the only Rust function + handed to native code (through `native::RARSetCallback` in `read_header` + and `process_file_raw`), is declared `extern "system" fn` instead of + `extern "C" fn`. This matches the vendored `unrar_sys::Callback` type, + which follows UnRAR's `dll.hpp` `CALLBACK` (`__stdcall` on Windows). + `"system"` is stdcall on 32-bit x86 Windows and identical to `"C"` on every + other target. Leaving the callback `"C"` would fail to type-check against + the corrected `unrar_sys`, and forcing it through would corrupt the stack + on `i686-pc-windows-msvc`. +2. The Cargo manifest retains upstream package/dependency/features + definitions (automatic tests, examples and benches are already disabled + upstream). The explicit `[[example]]` and `[[test]]` targets and the + `tempfile` dev-dependency were removed, since those files are not copied. + Root Cargo.toml selects this directory through `[patch.crates-io]`. + +## Production-only inventory + +The copy contains `src/` (lib, archive, error, open_archive, pathed) and the +license files. It excludes examples, integration tests, test archives under +`data/`, the upstream CI workflow, changelog, `Cargo.toml.orig`, the package +`Cargo.lock`, and registry bookkeeping. This README replaces the upstream one. + +The trailing `#[cfg(test)]` modules of `src/archive.rs` and +`src/open_archive.rs` were excluded; the production prefix of each file is +unchanged apart from patch item 1. No test code was created or run as part +of this patch. + +## Licenses + +The crate declares `MIT OR Apache-2.0`; both license texts are copied +verbatim from the package. + +## Evidence boundary + +This correction was established by source inspection of the +`i686-pc-windows-msvc` linker failure (unresolved stdcall-decorated +`_RAR*` symbols). Host builds confirm it compiles; the i686 MSVC link is a +separate acceptance gate this patch does not claim succeeded. diff --git a/vendor/unrar/src/archive.rs b/vendor/unrar/src/archive.rs new file mode 100644 index 00000000..03d3958f --- /dev/null +++ b/vendor/unrar/src/archive.rs @@ -0,0 +1,441 @@ +use crate::error::*; +use crate::open_archive::{CursorBeforeHeader, List, ListSplit, OpenArchive, OpenMode, Process}; +use regex::Regex; +use std::borrow::Cow; +use std::iter::repeat; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +fn multipart_extension() -> &'static Regex { + static INSTANCE: OnceLock = OnceLock::new(); + INSTANCE.get_or_init(|| Regex::new(r"(\.part|\.r?)(\d+)((?:\.rar)?)$").unwrap()) +} + +fn extension() -> &'static Regex { + static INSTANCE: OnceLock = OnceLock::new(); + INSTANCE.get_or_init(|| Regex::new(r"(\.part|\.r?)(\d+)((?:\.rar)?)$|\.rar$").unwrap()) +} + +/// A RAR archive on the file system. +/// +/// This struct provides two major classes of methods: +/// 1. methods that do not touch the FS. These are opinionated utility methods +/// that are based on RAR path conventions out in the wild. Most commonly, multipart +/// files usually have extensions such as `.part08.rar` or `.r08.rar`. Since extracting +/// must start at the first part, it may be helpful to figure that out using, for instance, +/// [`archive.as_first_part()`](Archive::as_first_part) +/// 2. methods that open the underlying path in the specified mode +/// (possible modes are [`List`], [`ListSplit`] and [`Process`]). +/// These methods have the word `open` in them, are fallible operations, +/// return [`OpenArchive`](struct.OpenArchive.html) inside a `Result` and are as follows: +/// - [`open_for_listing`](Archive::open_for_listing) and +/// [`open_for_listing_split`](Archive::open_for_listing_split): list the archive +/// entries (skipping over content/payload) +/// - [`open_for_processing`](Archive::open_for_processing): process archive entries +/// as well as content/payload +/// - [`break_open`](Archive::break_open): read archive even if an error is returned, +/// if possible. The [`OpenMode`](open_archive/struct.OpenMode.html) must be provided +/// explicitly. +pub struct Archive<'a> { + filename: Cow<'a, Path>, + password: Option<&'a [u8]>, + comments: Option<&'a mut Vec>, +} + +pub type Glob = PathBuf; + +impl<'a> Archive<'a> { + /// Creates an `Archive` object to operate on a plain non-encrypted RAR archive. + pub fn new(file: &'a T) -> Self + where + T: AsRef + ?Sized, + { + Archive { + filename: Cow::Borrowed(file.as_ref()), + password: None, + comments: None, + } + } + + /// Creates an `Archive` object to operate on a password encrypted RAR archive. + pub fn with_password(file: &'a F, password: &'a Pw) -> Self + where + F: AsRef + ?Sized, + Pw: AsRef<[u8]> + ?Sized, + { + Archive { + filename: Cow::Borrowed(file.as_ref()), + password: Some(password.as_ref()), + comments: None, + } + } + + /// returns the archive's path + pub fn filename(&self) -> &Path { + &self.filename + } + + /// Set the comment buffer of the underlying archive. + /// Note: Comments are not supported yet so this method will have no effect. + pub fn set_comments(&mut self, comments: &'a mut Vec) { + self.comments = Some(comments); + } + + /// Returns `true` if the filename matches a RAR archive. + /// + /// This method does not make any FS operations and operates purely on strings. + pub fn is_archive(&self) -> bool { + is_archive(&self.filename) + } + + /// Returns `true` if the filename matches a part of a multipart collection, `false` otherwise + /// + /// This method does not make any FS operations and operates purely on strings. + pub fn is_multipart(&self) -> bool { + is_multipart(&self.filename) + } + + /// Returns a glob string covering all parts of the multipart collection or `None` if the + /// underlying archive does not appear to be a multipart archive (based solely on filename). + /// + /// This method does not make any FS operations and operates purely on strings. + /// + /// # Example + /// + /// Basic usage (multipart archive): + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let glob = Archive::new("path/my.archive.part01.rar").all_parts_option(); + /// + /// assert_eq!(glob, Some(PathBuf::from("path/my.archive.part??.rar"))); + /// ``` + /// + /// Single part archive: + /// ``` + /// # use unrar::Archive; + /// let glob = Archive::new("path/my.archive.rar").all_parts_option(); + /// + /// assert_eq!(glob, None); + /// ``` + pub fn all_parts_option(&self) -> Option { + get_rar_extension(&self.filename) + .and_then(|full_ext| { + multipart_extension().captures(&full_ext).map(|captures| { + let mut replacement = String::from(captures.get(1).unwrap().as_str()); + replacement.push_str( + &repeat("?") + .take(captures.get(2).unwrap().as_str().len()) + .collect::(), + ); + replacement.push_str(captures.get(3).unwrap().as_str()); + full_ext.replace(captures.get(0).unwrap().as_str(), &replacement) + }) + }) + .and_then(|new_ext| { + self.filename.file_stem().map(|x| { + self.filename + .with_file_name(Path::new(x).with_extension(&new_ext[1..])) + }) + }) + } + + /// Returns a glob string covering all parts of the multipart collection or `self.filename` if + /// the underlying archive does not appear to be a multipart archive (based solely on filename). + /// + /// This method does not make any FS operations and operates purely on strings. + /// + /// # Examples + /// + /// Basic usage (multipart archive): + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let glob = Archive::new("path/my.archive.part01.rar").all_parts(); + /// + /// assert_eq!(glob, PathBuf::from("path/my.archive.part??.rar")); + /// ``` + /// + /// Single part archive: + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let glob = Archive::new("path/my.archive.rar").all_parts(); + /// + /// assert_eq!(glob, PathBuf::from("path/my.archive.rar")); + /// ``` + pub fn all_parts(&self) -> Glob { + match self.all_parts_option() { + Some(x) => x, + None => self.filename.to_path_buf(), + } + } + + /// Returns the nth part of this multi-part collection or `None` if + /// the underlying archive does not appear to be a multipart archive (based solely on filename). + /// + /// This method does not make any FS operations and operates purely on strings. + /// + /// # Examples + /// + /// Simple usage: + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let part42 = Archive::new("path/my.archive.part01.rar").nth_part(42).unwrap(); + /// + /// assert_eq!(part42, PathBuf::from("path/my.archive.part42.rar")); + /// ``` + /// + /// Returns None for single-part archives: + /// + /// ``` + /// # use unrar::Archive; + /// let part42 = Archive::new("path/my.archive.rar").nth_part(42); + /// + /// assert_eq!(part42, None); + /// ``` + pub fn nth_part(&self, n: i32) -> Option { + get_rar_extension(&self.filename) + .and_then(|full_ext| { + multipart_extension().captures(&full_ext).map(|captures| { + let mut replacement = String::from(captures.get(1).unwrap().as_str()); + // `n` padded with zeroes to the length of archive's number's length + replacement.push_str(&format!( + "{:01$}", + n, + captures.get(2).unwrap().as_str().len() + )); + replacement.push_str(captures.get(3).unwrap().as_str()); + full_ext.replace(captures.get(0).unwrap().as_str(), &replacement) + }) + }) + .and_then(|new_ext| { + self.filename.file_stem().map(|x| { + self.filename + .with_file_name(Path::new(x).with_extension(&new_ext[1..])) + }) + }) + } + + /// Return the first part of the multipart collection or `None` if + /// the underlying archive does not appear to be a multipart archive (based solely on filename). + /// + /// This method does not make any FS operations and operates purely on strings. + /// + /// Equivalent to [`nth_part(1)`](Archive::nth_part). + /// + /// # Examples + /// + /// Simple usage: + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let part1 = Archive::new("path/my.archive.part42.rar").first_part_option().unwrap(); + /// + /// assert_eq!(part1, PathBuf::from("path/my.archive.part01.rar")); + /// ``` + /// + /// Returns None for single-part archives: + /// + /// ``` + /// # use unrar::Archive; + /// let part1 = Archive::new("path/my.archive.rar").first_part_option(); + /// + /// assert_eq!(part1, None); + /// ``` + pub fn first_part_option(&self) -> Option { + self.nth_part(1) + } + + /// Returns the first part of the multipart collection or `self.filename` if + /// the underlying archive does not appear to be a multipart archive (based solely on filename). + /// + /// This method does not make any FS operations and operates purely on strings. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let part1 = Archive::new("path/archive.part33.rar").first_part(); + /// + /// assert_eq!(part1, PathBuf::from("path/archive.part01.rar")); + /// ``` + /// + /// Single part archive: + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let part1 = Archive::new("path/archive.rar").first_part(); + /// + /// assert_eq!(part1, PathBuf::from("path/archive.rar")); + /// ``` + /// + /// Note that this will always return the underlying path + /// if a first part could not be found: + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let part1 = Archive::new("https://gibberish").first_part(); + /// + /// assert_eq!(part1, PathBuf::from("https://gibberish")); + /// ``` + pub fn first_part(&self) -> PathBuf { + match self.nth_part(1) { + Some(x) => x, + None => self.filename.to_path_buf(), + } + } + + /// Changes the filename to point to the first part of the multipart collection. Does nothing if + /// the underlying archive does not appear to be a multipart archive (based solely on filename). + /// + /// This method does not make any FS operations and operates purely on strings. + /// + /// # Example + /// + /// Basic usage: + /// + /// ``` + /// # use unrar::Archive; + /// # use std::path::PathBuf; + /// let mut archive = Archive::new("path/some.004.rar").as_first_part(); + /// assert_eq!(archive.filename(), PathBuf::from("path/some.001.rar")); + /// ``` + pub fn as_first_part(mut self) -> Self { + self.first_part_option() + .map(|fp| self.filename = Cow::Owned(fp)); + self + } + + /// Opens the underlying archive for processing, that is, the payloads of each archive entry can be + /// actively read. What actually happens with individual entries (e.g. read, extract, skip, test), + /// can be specified during processing. + /// + /// See also: [`Process`] + /// + /// # Panics + /// + /// Panics if `self.filename` contains nul values. + pub fn open_for_processing(self) -> UnrarResult> { + self.open(None) + } + + /// Opens the underlying archive for listing its entries, i.e. the payloads are skipped automatically. + /// + /// See also: [`List`] + /// + /// # Panics + /// + /// Panics if `self.filename` contains nul values. + pub fn open_for_listing(self) -> UnrarResult> { + self.open(None) + } + + /// Opens the underlying archive for listing its entries without omitting or pooling split entries. + /// For a multipart archive, this means a file spanning the border of 2 parts will appear twice, + /// or even more often than that if it spans multiple parts, whereas in the normal list, it will + /// appear once. + /// + /// See also: [`ListSplit`] + /// + /// # Panics + /// + /// Panics if `self.filename` contains nul values. + + pub fn open_for_listing_split(self) -> UnrarResult> { + self.open(None) + } + + /// Opens the underlying archive with the provided parameters. + /// + /// # Panics + /// + /// Panics if `path` contains nul values. + fn open( + self, + recover: Option<&mut Option>>, + ) -> UnrarResult> { + OpenArchive::new(&self.filename, self.password, recover) + } + + /// Opens the underlying archive with the provided OpenMode, + /// even if archive is broken (e.g. malformed header). + /// + /// Provide an optional mutable reference for book-keeping, to check whether an error + /// did occur. Note that this error will never be set if an Err is returned, i.e. if we + /// were not able to read the archive. + /// + /// # Example: I don't care if there was a recoverable error + /// + /// ```no_run + /// # use unrar::{Archive, List, UnrarResult}; + /// # fn x() -> UnrarResult<()> { + /// let mut open_archive = Archive::new("file").break_open::(None)?; + /// // use open_archive + /// # Ok(()) + /// # } + /// ``` + /// + /// # Example: I want to know if there was a recoverable error + /// + /// ```no_run + /// # use unrar::{Archive, List, UnrarResult}; + /// # fn x() -> UnrarResult<()> { + /// let mut possible_error = None; + /// let mut open_archive = Archive::new("file").break_open::(Some(&mut possible_error))?; + /// // check the error, e.g.: + /// possible_error.map(|error| eprintln!("recoverable error occurred: {error}")); + /// // use open_archive + /// # Ok(()) + /// # } + /// ``` + /// + /// # Panics + /// + /// Panics if `path` contains nul values. + pub fn break_open( + self, + error: Option<&mut Option>, + ) -> UnrarResult> { + let mut recovered = None; + self.open(Some(&mut recovered)) + .or_else(|x| match recovered { + Some(archive) => { + error.map(|error| *error = Some(x)); + Ok(archive) + } + None => Err(x), + }) + } +} + +fn get_rar_extension>(path: T) -> Option { + path.as_ref().extension().and_then(|ext| { + let pre_ext = path + .as_ref() + .file_stem() + .and_then(|x| Path::new(x).extension()); + Some(match pre_ext { + Some(pre_ext) => format!(".{}.{}", pre_ext.to_str()?, ext.to_str()?), + None => format!(".{}", ext.to_str()?), + }) + }) +} + +pub fn is_archive(s: &Path) -> bool { + get_rar_extension(s).is_some_and(|e| extension().is_match(&e)) +} + +pub fn is_multipart(s: &Path) -> bool { + get_rar_extension(s).is_some_and(|e| multipart_extension().is_match(&e)) +} diff --git a/vendor/unrar/src/error.rs b/vendor/unrar/src/error.rs new file mode 100644 index 00000000..55daf033 --- /dev/null +++ b/vendor/unrar/src/error.rs @@ -0,0 +1,146 @@ +#![allow(missing_docs)] + +use super::*; +use std::error; +use std::ffi; +use std::fmt; +use std::result::Result; + + +#[derive(PartialEq, Eq, Debug, Clone, Copy)] +#[repr(i32)] +pub enum Code { + Success = native::ERAR_SUCCESS, + EndArchive = native::ERAR_END_ARCHIVE, + NoMemory = native::ERAR_NO_MEMORY, + BadData = native::ERAR_BAD_DATA, + BadArchive = native::ERAR_BAD_ARCHIVE, + UnknownFormat = native::ERAR_UNKNOWN_FORMAT, + EOpen = native::ERAR_EOPEN, + ECreate = native::ERAR_ECREATE, + EClose = native::ERAR_ECLOSE, + ERead = native::ERAR_EREAD, + EWrite = native::ERAR_EWRITE, + SmallBuf = native::ERAR_SMALL_BUF, + Unknown = native::ERAR_UNKNOWN, + MissingPassword = native::ERAR_MISSING_PASSWORD, + // From the UnRARDLL docs: + // When attempting to unpack a reference record (see RAR -oi switch), + // source file for this reference was not found. + // Entire archive needs to be unpacked to properly create file references. + // This error is returned when attempting to unpack the reference + // record without its source file. + EReference = native::ERAR_EREFERENCE, + BadPassword = native::ERAR_BAD_PASSWORD, +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum When { + Open, + Read, + Process, +} + +impl Code { + pub fn from(code: i32) -> Option { + use Code::*; + match code { + native::ERAR_SUCCESS => Some(Success), + native::ERAR_END_ARCHIVE => Some(EndArchive), + native::ERAR_NO_MEMORY => Some(NoMemory), + native::ERAR_BAD_DATA => Some(BadData), + native::ERAR_BAD_ARCHIVE => Some(BadArchive), + native::ERAR_UNKNOWN_FORMAT => Some(UnknownFormat), + native::ERAR_EOPEN => Some(EOpen), + native::ERAR_ECREATE => Some(ECreate), + native::ERAR_ECLOSE => Some(EClose), + native::ERAR_EREAD => Some(ERead), + native::ERAR_EWRITE => Some(EWrite), + native::ERAR_SMALL_BUF => Some(SmallBuf), + native::ERAR_UNKNOWN => Some(Unknown), + native::ERAR_MISSING_PASSWORD => Some(MissingPassword), + native::ERAR_EREFERENCE => Some(EReference), + native::ERAR_BAD_PASSWORD => Some(BadPassword), + _ => None, + } + } +} + +#[derive(PartialEq)] +pub struct UnrarError { + pub code: Code, + pub when: When, +} + +impl std::error::Error for UnrarError {} + +impl fmt::Debug for UnrarError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}@{:?}", self.code, self.when)?; + write!(f, " ({})", self) + } +} + +impl fmt::Display for UnrarError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Code::*; + use self::When::*; + match (self.code, self.when) { + (BadData, Open) => write!(f, "Archive header damaged"), + (BadData, Read) => write!(f, "File header damaged"), + (BadData, Process) => write!(f, "File CRC error"), + (UnknownFormat, Open) => write!(f, "Unknown encryption"), + (EOpen, Process) => write!(f, "Could not open next volume"), + (UnknownFormat, _) => write!(f, "Unknown archive format"), + (EOpen, _) => write!(f, "Could not open archive"), + (NoMemory, _) => write!(f, "Not enough memory"), + (BadArchive, _) => write!(f, "Not a RAR archive"), + (ECreate, _) => write!(f, "Could not create file"), + (EClose, _) => write!(f, "Could not close file"), + (ERead, _) => write!(f, "Read error"), + (EWrite, _) => write!(f, "Write error"), + (SmallBuf, _) => write!(f, "Archive comment was truncated to fit to buffer"), + (MissingPassword, _) => write!(f, "Password for encrypted archive not specified"), + (EReference, _) => write!(f, "Cannot open file source for reference record"), + (BadPassword, _) => write!(f, "Wrong password was specified"), + (Unknown, _) => write!(f, "Unknown error"), + (EndArchive, _) => write!(f, "Archive end"), + (Success, _) => write!(f, "Success"), + } + } +} + +impl UnrarError { + pub fn from(code: Code, when: When) -> Self { + UnrarError { code, when } + } +} + +pub type UnrarResult = Result; + +#[derive(Debug)] +pub struct NulError(usize); + +impl fmt::Display for NulError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "nul value found at position: {}", self.0) + } +} + +impl error::Error for NulError { + fn description(&self) -> &str { + "nul value found" + } +} + +impl From> for NulError { + fn from(e: widestring::error::ContainsNul) -> NulError { + NulError(e.nul_position()) + } +} + +impl From for NulError { + fn from(e: ffi::NulError) -> NulError { + NulError(e.nul_position()) + } +} diff --git a/vendor/unrar/src/lib.rs b/vendor/unrar/src/lib.rs new file mode 100644 index 00000000..ef542af7 --- /dev/null +++ b/vendor/unrar/src/lib.rs @@ -0,0 +1,14 @@ +#![doc = include_str!("../README.md")] +#![warn(missing_docs)] + +pub use archive::Archive; +use unrar_sys as native; +mod archive; +pub mod error; +mod pathed; +mod open_archive; +pub use error::UnrarResult; +pub use open_archive::{ + CursorBeforeFile, CursorBeforeHeader, FileHeader, List, ListSplit, OpenArchive, Process, + VolumeInfo, +}; diff --git a/vendor/unrar/src/open_archive.rs b/vendor/unrar/src/open_archive.rs new file mode 100644 index 00000000..4ee5856a --- /dev/null +++ b/vendor/unrar/src/open_archive.rs @@ -0,0 +1,667 @@ +use super::error::*; +use super::*; +use std::fmt; +use std::os::raw::{c_int, c_uint}; +use std::path::{Path, PathBuf}; +use std::ptr::NonNull; + +bitflags::bitflags! { + #[derive(Debug, Default)] + struct ArchiveFlags: u32 { + const VOLUME = native::ROADF_VOLUME; + const COMMENT = native::ROADF_COMMENT; + const LOCK = native::ROADF_LOCK; + const SOLID = native::ROADF_SOLID; + const NEW_NUMBERING = native::ROADF_NEWNUMBERING; + const SIGNED = native::ROADF_SIGNED; + const RECOVERY = native::ROADF_RECOVERY; + const ENC_HEADERS = native::ROADF_ENCHEADERS; + const FIRST_VOLUME = native::ROADF_FIRSTVOLUME; + } +} + +/// Volume information on the file that was *initially* opened. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VolumeInfo { + /// the *initially* opened file is a single-part archive + None, + /// the *initially* opened file is the first volume in a multipart archive + First, + /// the *initially* opened file is any volume but the first in a multipart archive + Subsequent, +} + +#[derive(Debug)] +struct Handle(NonNull); + +impl Drop for Handle { + fn drop(&mut self) { + unsafe { native::RARCloseArchive(self.0.as_ptr() as *const _) }; + } +} + +/// An open RAR archive that can be read or processed. +/// +/// See the [OpenArchive chapter](index.html#openarchive) for more information. +#[derive(Debug)] +pub struct OpenArchive { + handle: Handle, + flags: ArchiveFlags, + damaged: bool, + extra: C, + marker: std::marker::PhantomData, +} +type Userdata = (T, Option); + +mod private { + use super::native; + pub trait Sealed {} + impl Sealed for super::CursorBeforeHeader {} + impl Sealed for super::CursorBeforeFile {} + impl Sealed for super::List {} + impl Sealed for super::ListSplit {} + impl Sealed for super::Process {} + + #[repr(i32)] + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub(crate) enum Operation { + Skip = native::RAR_SKIP, + Test = native::RAR_TEST, + Extract = native::RAR_EXTRACT, + } + + #[repr(u32)] + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum OpenModeValue { + Extract = native::RAR_OM_EXTRACT, + List = native::RAR_OM_LIST, + ListIncSplit = native::RAR_OM_LIST_INCSPLIT, + } +} + +/// Type parameter for OpenArchive denoting a `read_header` operation must follow next. +/// +/// See the chapter [OpenArchive: Cursors](index.html#openarchive-cursors) for more information. +#[derive(Debug)] +pub struct CursorBeforeHeader; +/// Type parameter for OpenArchive denoting a `process_file` operation must follow next. +/// +/// See the chapter [OpenArchive: Cursors](index.html#openarchive-cursors) for more information. +#[derive(Debug)] +pub struct CursorBeforeFile { + header: FileHeader, +} + +/// The Cursor trait enables archives to keep track of their state. +/// +/// See the chapter [OpenArchive: Cursors](index.html#openarchive-cursors) for more information. +pub trait Cursor: private::Sealed {} +impl Cursor for CursorBeforeHeader {} +impl Cursor for CursorBeforeFile {} + +/// An OpenMode for processing RAR archive entries. +/// +/// Process allows more sophisticated operations in the `ProcessFile` step. +#[derive(Debug)] +pub struct Process; +#[derive(Debug)] +/// An OpenMode for listing RAR archive entries. +/// +/// List mode will list all entries. The payload itself cannot be processed and instead can only +/// be skipped over. This will yield one header per individual file, regardless of how many parts +/// the file is split across. +pub struct List; +/// An OpenMode for listing RAR archive entries. +/// +/// ListSplit mode will list all entries. The payload itself cannot be processed and instead can +/// only be skipped over. This will yield one header per individual file per part if the file is +/// split across multiple parts. The [`FileHeader::is_split`] method will return true in that case. +#[derive(Debug)] +pub struct ListSplit; + +/// Mode with which the archive should be opened. +/// +/// Possible modes are: +/// +/// - [`List`](struct.List.html) +/// - [`ListSplit`](struct.ListSplit.html) +/// - [`Process`](struct.Process.html) +pub trait OpenMode: private::Sealed { + const VALUE: private::OpenModeValue; +} +impl OpenMode for Process { + const VALUE: private::OpenModeValue = private::OpenModeValue::Extract; +} +impl OpenMode for List { + const VALUE: private::OpenModeValue = private::OpenModeValue::List; +} +impl OpenMode for ListSplit { + const VALUE: private::OpenModeValue = private::OpenModeValue::ListIncSplit; +} + +impl OpenArchive { + /// is the archive locked + pub fn is_locked(&self) -> bool { + self.flags.contains(ArchiveFlags::LOCK) + } + + /// are the archive headers encrypted + pub fn has_encrypted_headers(&self) -> bool { + self.flags.contains(ArchiveFlags::ENC_HEADERS) + } + + /// does the archive have a recovery record + pub fn has_recovery_record(&self) -> bool { + self.flags.contains(ArchiveFlags::RECOVERY) + } + + /// does the archive have comments + pub fn has_comment(&self) -> bool { + self.flags.contains(ArchiveFlags::COMMENT) + } + + /// is the archive solid (all files in a single compressed block). + pub fn is_solid(&self) -> bool { + self.flags.contains(ArchiveFlags::SOLID) + } + + /// Volume information on the file that was *initially* opened. + /// + /// returns + /// - `VolumeInfo::None` if the opened file is a single-part archive + /// - `VolumeInfo::First` if the opened file is the first volume in a multipart archive + /// - `VolumeInfo::Subsequent` if the opened file is any other volume in a multipart archive + /// + /// Note that this value *never* changes from `First` to `Subsequent` by advancing to a + /// different volume. + pub fn volume_info(&self) -> VolumeInfo { + if self.flags.contains(ArchiveFlags::FIRST_VOLUME) { + VolumeInfo::First + } else if self.flags.contains(ArchiveFlags::VOLUME) { + VolumeInfo::Subsequent + } else { + VolumeInfo::None + } + } + + /// unsets the `damaged` flag so that `Iterator` will not refuse to yield elements. + /// + /// Normally, when an error is returned during iteration, the archive remembers this + /// so that subsequent calls to `next` return `None` immediately. This is to prevent + /// the same error from recurring over and over again, leading to endless loops in programs + /// that might not have considered this. However, maybe there are errors that can be recovered + /// from? That's where this method might come in handy if you really know what you're doing. + /// However, should that be the case, I urge you to submit an issue / PR with an archive where + /// the recoverable error can be reproduced so I can exclude that case from "irrecoverable + /// errors" (currently all errors). + /// + /// Use at your own risk. Might be removed in future releases if somehow it can be verified + /// which errors are recoverable and which are not. + /// + /// # Example how you *might* use this + /// + /// ```no_run + /// use unrar::{Archive, error::{When, Code}}; + /// + /// let mut archive = Archive::new("corrupt.rar").open_for_listing().expect("archive error"); + /// loop { + /// let mut error = None; + /// for result in &mut archive { + /// match result { + /// Ok(entry) => println!("{entry}"), + /// Err(e) => error = Some(e), + /// } + /// } + /// match error { + /// // your special recoverable error, please submit a PR with reproducible archive + /// Some(e) if (e.when, e.code) == (When::Process, Code::BadData) => archive.force_heal(), + /// Some(e) => panic!("irrecoverable error: {e}"), + /// None => break, + /// } + /// } + /// ``` + pub fn force_heal(&mut self) { + self.damaged = false; + } +} + +impl OpenArchive { + pub(crate) fn new( + filename: &Path, + password: Option<&[u8]>, + recover: Option<&mut Option>, + ) -> UnrarResult { + let filename = pathed::construct(filename); + + let mut data = + native::OpenArchiveDataEx::new(filename.as_ptr() as *const _, Mode::VALUE as u32); + let handle = + NonNull::new(unsafe { native::RAROpenArchiveEx(&mut data as *mut _) } as *mut _); + + let arc = handle.and_then(|handle| { + if let Some(pw) = password { + let cpw = std::ffi::CString::new(pw).unwrap(); + unsafe { native::RARSetPassword(handle.as_ptr(), cpw.as_ptr() as *const _) } + } + Some(OpenArchive { + handle: Handle(handle), + damaged: false, + flags: ArchiveFlags::from_bits(data.flags).unwrap(), + extra: CursorBeforeHeader, + marker: std::marker::PhantomData, + }) + }); + let result = Code::from(data.open_result as i32).unwrap(); + + match (arc, result) { + (Some(arc), Code::Success) => Ok(arc), + (arc, _) => { + recover.and_then(|recover| arc.and_then(|arc| recover.replace(arc))); + Err(UnrarError::from(result, When::Open)) + } + } + } + + /// reads the next header of the underlying archive. The resulting OpenArchive will + /// be in "ProcessFile" mode, i.e. the file corresponding to the header (that has just + /// been read via this method call) will have to be read. Also contains header data + /// via [`archive.entry()`](OpenArchive::entry). + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// let archive = unrar::Archive::new("data/version.rar").open_for_listing().unwrap().read_header(); + /// assert!(archive.as_ref().is_ok_and(Option::is_some)); + /// let archive = archive.unwrap().unwrap(); + /// assert_eq!(archive.entry().filename.as_os_str(), "VERSION"); + /// ``` + pub fn read_header(self) -> UnrarResult>> { + Ok(read_header(&self.handle)?.map(|entry| OpenArchive { + extra: CursorBeforeFile { header: entry }, + damaged: self.damaged, + handle: self.handle, + flags: self.flags, + marker: std::marker::PhantomData, + })) + } +} + +impl Iterator for OpenArchive { + type Item = Result; + + fn next(&mut self) -> Option { + if self.damaged { + return None; + } + match read_header(&self.handle) { + Ok(Some(header)) => { + match Internal::::process_file_raw(&self.handle, None, None) { + Ok(_) => Some(Ok(header)), + Err(s) => { + self.damaged = true; + Some(Err(s)) + } + } + } + Ok(None) => None, + Err(s) => { + self.damaged = true; + Some(Err(s)) + } + } + } +} + +impl Iterator for OpenArchive { + type Item = Result; + + fn next(&mut self) -> Option { + if self.damaged { + return None; + } + match read_header(&self.handle) { + Ok(Some(header)) => { + match Internal::::process_file_raw(&self.handle, None, None) { + Ok(_) => Some(Ok(header)), + Err(s) => { + self.damaged = true; + Some(Err(s)) + } + } + } + Ok(None) => None, + Err(s) => { + self.damaged = true; + Some(Err(s)) + } + } + } +} + +impl OpenArchive { + /// returns the file header for the file that follows which is to be processed next. + pub fn entry(&self) -> &FileHeader { + &self.extra.header + } + + /// skips over the next file, not doing anything with it. + pub fn skip(self) -> UnrarResult> { + self.process_file::(None, None) + } + + fn process_file( + self, + path: Option<&pathed::RarStr>, + file: Option<&pathed::RarStr>, + ) -> UnrarResult> { + Ok(self.process_file_x::(path, file)?.1) + } + + fn process_file_x( + self, + path: Option<&pathed::RarStr>, + file: Option<&pathed::RarStr>, + ) -> UnrarResult<(PM::Output, OpenArchive)> { + let result = Ok(( + Internal::::process_file_raw(&self.handle, path, file)?, + OpenArchive { + extra: CursorBeforeHeader, + damaged: self.damaged, + handle: self.handle, + flags: self.flags, + marker: std::marker::PhantomData, + }, + )); + result + } +} + +impl OpenArchive { + /// Reads the underlying file into a `Vec` + /// Returns the data as well as the owned Archive that can be processed further. + pub fn read(self) -> UnrarResult<(Vec, OpenArchive)> { + Ok(self.process_file_x::(None, None)?) + } + + /// Test the file without extracting it + pub fn test(self) -> UnrarResult> { + Ok(self.process_file::(None, None)?) + } + + /// Extracts the file into the current working directory + /// Returns the OpenArchive for further processing + pub fn extract(self) -> UnrarResult> { + self.dir_extract(None) + } + + /// Extracts the file into the specified directory. + /// Returns the OpenArchive for further processing + /// + /// # Panics + /// + /// This function will panic if `base` contains nul characters. + pub fn extract_with_base>( + self, + base: P, + ) -> UnrarResult> { + self.dir_extract(Some(base.as_ref())) + } + + /// Extracts the file into the specified file. + /// Returns the OpenArchive for further processing + /// + /// # Panics + /// + /// This function will panic if `dest` contains nul characters. + pub fn extract_to>( + self, + file: P, + ) -> UnrarResult> { + let dest = pathed::construct(file.as_ref()); + self.process_file::(None, Some(&dest)) + } + + /// extracting into a directory if the filename has unicode characters + /// does not work on Linux, so we must specify the full path for Linux + fn dir_extract( + self, + base: Option<&Path>, + ) -> UnrarResult> { + let (path, file) = pathed::preprocess_extract(base, &self.entry().filename); + self.process_file::(path.as_deref(), file.as_deref()) + } +} + +fn read_header(handle: &Handle) -> UnrarResult> { + let mut userdata: Userdata<::Output> = Default::default(); + unsafe { + native::RARSetCallback( + handle.0.as_ptr(), + Some(Internal::::callback), + &mut userdata as *mut _ as native::LPARAM, + ); + } + let mut header = native::HeaderDataEx::default(); + let read_result = + Code::from(unsafe { native::RARReadHeaderEx(handle.0.as_ptr(), &mut header as *mut _) }) + .unwrap(); + match read_result { + Code::Success => Ok(Some(header.into())), + Code::EndArchive => Ok(None), + _ => Err(UnrarError::from(read_result, When::Read)), + } +} + +#[derive(Debug)] +struct Skip; +#[derive(Debug)] +struct ReadToVec; +#[derive(Debug)] +struct Extract; +#[derive(Debug)] +struct Test; + +trait ProcessMode: core::fmt::Debug { + const OPERATION: private::Operation; + type Output: core::fmt::Debug + std::default::Default; + + fn process_data(data: &mut Self::Output, other: &[u8]); +} +impl ProcessMode for Skip { + const OPERATION: private::Operation = private::Operation::Skip; + type Output = (); + + fn process_data(_: &mut Self::Output, _: &[u8]) {} +} +impl ProcessMode for ReadToVec { + const OPERATION: private::Operation = private::Operation::Test; + type Output = Vec; + + fn process_data(my: &mut Self::Output, other: &[u8]) { + my.extend_from_slice(other); + } +} +impl ProcessMode for Extract { + const OPERATION: private::Operation = private::Operation::Extract; + type Output = (); + + fn process_data(_: &mut Self::Output, _: &[u8]) {} +} +impl ProcessMode for Test { + const OPERATION: private::Operation = private::Operation::Test; + type Output = (); + + fn process_data(_: &mut Self::Output, _: &[u8]) {} +} + +struct Internal { + marker: std::marker::PhantomData, +} + +impl Internal { + extern "system" fn callback( + msg: native::UINT, + user_data: native::LPARAM, + p1: native::LPARAM, + p2: native::LPARAM, + ) -> c_int { + if user_data == 0 { + return 0; + } + let user_data = unsafe { &mut *(user_data as *mut Userdata) }; + match msg { + native::UCM_CHANGEVOLUMEW => { + // 2048 seems to be the buffer size in unrar, + // also it's the maximum path length since 5.00. + let next = + unsafe { widestring::WideCString::from_ptr_truncate(p1 as *const _, 2048) }; + user_data.1 = Some(next); + match p2 { + // Next volume not found. -1 means stop + native::RAR_VOL_ASK => -1, + // Next volume found, 0 means continue + _ => 0, + } + } + native::UCM_PROCESSDATA => { + let raw_slice = std::ptr::slice_from_raw_parts(p1 as *const u8, p2 as _); + M::process_data(&mut user_data.0, unsafe { &*raw_slice as &_ }); + 0 + } + _ => 0, + } + } + + fn process_file_raw( + handle: &Handle, + path: Option<&pathed::RarStr>, + file: Option<&pathed::RarStr>, + ) -> UnrarResult { + let mut user_data: Userdata = Default::default(); + unsafe { + native::RARSetCallback( + handle.0.as_ptr(), + Some(Self::callback), + &mut user_data as *mut _ as native::LPARAM, + ); + } + let process_result = Code::from(pathed::process_file( + handle.0.as_ptr(), + M::OPERATION as i32, + path, + file, + )) + .unwrap(); + match process_result { + Code::Success => Ok(user_data.0), + _ => Err(UnrarError::from(process_result, When::Process)), + } + } +} + +bitflags::bitflags! { + #[derive(Debug)] + struct EntryFlags: u32 { + const SPLIT_BEFORE = 0x1; + const SPLIT_AFTER = 0x2; + const ENCRYPTED = 0x4; + // const RESERVED = 0x8; + const SOLID = 0x10; + const DIRECTORY = 0x20; + } +} + +/// Metadata for an entry in a RAR archive +/// +/// Created using the read_header methods in an OpenArchive, contains +/// information for the file that follows which is to be processed next. +#[allow(missing_docs)] +#[derive(Debug)] +pub struct FileHeader { + pub filename: PathBuf, + flags: EntryFlags, + pub unpacked_size: u64, + pub file_crc: u32, + pub file_time: u32, + pub method: u32, + pub file_attr: u32, +} + +impl FileHeader { + /// is this entry split across multiple volumes. + /// + /// Will also work in open mode [`List`] + pub fn is_split(&self) -> bool { + self.flags.contains(EntryFlags::SPLIT_BEFORE) + || self.flags.contains(EntryFlags::SPLIT_AFTER) + } + + /// is this entry split across multiple volumes, starting here + /// + /// Will also work in open mode [`List`] + pub fn is_split_after(&self) -> bool { + self.flags.contains(EntryFlags::SPLIT_AFTER) + } + + /// is this entry split across multiple volumes, starting here + /// + /// Will always return false in open mode [`List`][^1]. + /// + /// [^1]: this claim is not proven, however, the DLL seems to always skip + /// files where this flag would have been set. + pub fn is_split_before(&self) -> bool { + self.flags.contains(EntryFlags::SPLIT_BEFORE) + } + + /// is this entry a directory + pub fn is_directory(&self) -> bool { + self.flags.contains(EntryFlags::DIRECTORY) + } + + /// is this entry encrypted + pub fn is_encrypted(&self) -> bool { + self.flags.contains(EntryFlags::ENCRYPTED) + } + + /// is this entry a file + pub fn is_file(&self) -> bool { + !self.is_directory() + } +} + +impl fmt::Display for FileHeader { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}", self.filename)?; + if self.is_directory() { + write!(f, "/")? + } + if self.is_split() { + write!(f, " (partial)")? + } + Ok(()) + } +} + +impl From for FileHeader { + fn from(header: native::HeaderDataEx) -> Self { + let filename = unsafe { + widestring::WideCString::from_ptr_truncate(header.filename_w.as_ptr() as *const _, 1024) + }; + + FileHeader { + filename: PathBuf::from(filename.to_os_string()), + flags: EntryFlags::from_bits(header.flags).unwrap(), + unpacked_size: unpack_unp_size(header.unp_size, header.unp_size_high), + file_crc: header.file_crc, + file_time: header.file_time, + method: header.method, + file_attr: header.file_attr, + } + } +} + +fn unpack_unp_size(unp_size: c_uint, unp_size_high: c_uint) -> u64 { + ((unp_size_high as u64) << (8 * std::mem::size_of::())) | (unp_size as u64) +} diff --git a/vendor/unrar/src/pathed/all.rs b/vendor/unrar/src/pathed/all.rs new file mode 100644 index 00000000..3c228b6a --- /dev/null +++ b/vendor/unrar/src/pathed/all.rs @@ -0,0 +1,32 @@ +use std::path::{Path, PathBuf}; +use widestring::{WideCString, WideCStr}; + +pub(crate) type RarString = WideCString; +pub(crate) type RarStr = WideCStr; + +pub(crate) fn construct(path: &Path) -> RarString { + WideCString::from_os_str(path).expect("Unexpected nul in path") +} + +pub(crate) fn process_file( + handle: *const unrar_sys::Handle, + operation: i32, + dest_path: Option<&RarStr>, + dest_name: Option<&RarStr>, +) -> i32 { + unsafe { + unrar_sys::RARProcessFileW( + handle, + operation, + dest_path.map(|path| path.as_ptr().cast()).unwrap_or(std::ptr::null()), + dest_name.map(|file| file.as_ptr().cast()).unwrap_or(std::ptr::null()), + ) + } +} + +pub(crate) fn preprocess_extract( + base: Option<&Path>, + _filename: &PathBuf, +) -> (Option, Option) { + (base.map(construct), None) +} diff --git a/vendor/unrar/src/pathed/linux.rs b/vendor/unrar/src/pathed/linux.rs new file mode 100644 index 00000000..d0a9da1b --- /dev/null +++ b/vendor/unrar/src/pathed/linux.rs @@ -0,0 +1,32 @@ +use std::ffi::{CString, CStr}; +use std::path::{Path, PathBuf}; + +pub(crate) type RarString = CString; +pub(crate) type RarStr = CStr; + +pub(crate) fn construct>(path: P) -> RarString { + CString::new(path.as_ref().as_os_str().as_encoded_bytes()).unwrap() +} + +pub(crate) fn process_file( + handle: *const unrar_sys::Handle, + operation: i32, + dest_path: Option<&RarStr>, + dest_name: Option<&RarStr>, +) -> i32 { + unsafe { + unrar_sys::RARProcessFile( + handle, + operation, + dest_path.map(|path| path.as_ptr().cast()).unwrap_or(std::ptr::null()), + dest_name.map(|file| file.as_ptr().cast()).unwrap_or(std::ptr::null()), + ) + } +} + +pub(crate) fn preprocess_extract( + base: Option<&Path>, + filename: &PathBuf, +) -> (Option, Option) { + (None, Some(construct(base.unwrap_or(".".as_ref()).join(filename)))) +} diff --git a/vendor/unrar/src/pathed/mod.rs b/vendor/unrar/src/pathed/mod.rs new file mode 100644 index 00000000..ca9688f0 --- /dev/null +++ b/vendor/unrar/src/pathed/mod.rs @@ -0,0 +1,5 @@ +#[cfg_attr(any(target_os = "linux", target_os = "netbsd"), path = "linux.rs")] +#[cfg_attr(not(any(target_os = "linux", target_os = "netbsd")), path = "all.rs")] +mod os; + +pub(crate) use os::*; diff --git a/vendor/unrar_sys/README.md b/vendor/unrar_sys/README.md index 35caa600..b1b33741 100644 --- a/vendor/unrar_sys/README.md +++ b/vendor/unrar_sys/README.md @@ -22,7 +22,15 @@ likewise spells `wbemidl.h` in lower case. These real MinGW headers work on case-sensitive build hosts without external header aliases. Windows SDK builds retain the same includes on their case-insensitive filesystem. -3. The Cargo manifest retains upstream package/dependency/features definitions, +3. `src/lib.rs` declares the UnRAR FFI block and the `ChangeVolProc`, + `ProcessDataProc` and `Callback` function-pointer types `extern "system"` + instead of `extern "C"`. `dll.hpp` declares the API `PASCAL` and the + callbacks `CALLBACK`, both `__stdcall` on Windows (empty only under + `_UNIX`). `"system"` is stdcall on 32-bit x86 Windows, which fixes the + `i686-pc-windows-msvc` link (decorated `_RAROpenArchiveEx@4` etc. names), + and is identical to `"C"` on every other target. The sibling `unrar` crate + is vendored in `vendor/unrar` so its callback matches this type. +4. The Cargo manifest retains upstream package/dependency/features definitions, explicitly disabling automatic tests, examples and benches. Root Cargo.toml selects this directory through `[patch.crates-io]`. diff --git a/vendor/unrar_sys/src/lib.rs b/vendor/unrar_sys/src/lib.rs index 9121961f..b70799ef 100644 --- a/vendor/unrar_sys/src/lib.rs +++ b/vendor/unrar_sys/src/lib.rs @@ -108,9 +108,9 @@ pub const ROADF_FIRSTVOLUME: c_uint = 0x0100; // RAROpenArchiveDataEx::OpFlags pub const ROADOF_KEEPBROKEN: c_uint = 0x0001; -pub type ChangeVolProc = extern "C" fn(*mut c_char, c_int) -> c_int; -pub type ProcessDataProc = extern "C" fn(*mut c_uchar, c_int) -> c_int; -pub type Callback = extern "C" fn(UINT, LPARAM, LPARAM, LPARAM) -> c_int; +pub type ChangeVolProc = extern "system" fn(*mut c_char, c_int) -> c_int; +pub type ProcessDataProc = extern "system" fn(*mut c_uchar, c_int) -> c_int; +pub type Callback = extern "system" fn(UINT, LPARAM, LPARAM, LPARAM) -> c_int; #[repr(C)] pub struct Handle { _private: [u8; 0] } @@ -209,7 +209,7 @@ pub struct OpenArchiveDataEx { #[cfg_attr(target_os = "macos", link(name = "c++"))] #[cfg_attr(any(target_os = "freebsd", target_os = "openbsd"), link(name = "c++"))] #[cfg_attr(any(target_os = "linux", target_os = "netbsd"), link(name = "stdc++"))] -extern "C" { +extern "system" { pub fn RAROpenArchive(data: *const OpenArchiveData) -> *const Handle; pub fn RAROpenArchiveEx(data: *const OpenArchiveDataEx) -> *const Handle;