From c6b956ffa96c7debf9853e2533defce6402f5739 Mon Sep 17 00:00:00 2001 From: kp2pml30 Date: Tue, 10 Feb 2026 21:24:16 +0900 Subject: [PATCH] initial commit --- .gitignore | 34 ++ Cargo.lock | 193 +++++++++++ Cargo.toml | 12 + LICENSE | 674 +++++++++++++++++++++++++++++++++++++ README.md | 9 + build.rs | 9 + flake.lock | 48 +++ flake.nix | 62 ++++ src/archive.rs | 519 ++++++++++++++++++++++++++++ src/cli.rs | 142 ++++++++ src/commands/compress.rs | 76 +++++ src/commands/create.rs | 129 +++++++ src/commands/decompress.rs | 55 +++ src/commands/detect.rs | 64 ++++ src/commands/extract.rs | 66 ++++ src/commands/list.rs | 67 ++++ src/commands/mod.rs | 7 + src/commands/print.rs | 34 ++ src/detect.rs | 58 ++++ src/format.rs | 185 ++++++++++ src/libarchive_sys.rs | 143 ++++++++ src/main.rs | 52 +++ support/compile-rust.nix | 68 ++++ support/lib-bzip2.nix | 14 + support/lib-libarchive.nix | 53 +++ support/lib-libxml2.nix | 28 ++ support/lib-lz4.nix | 21 ++ support/lib-xz.nix | 15 + support/lib-zlib.nix | 10 + support/lib-zstd.nix | 20 ++ support/musl-libs.nix | 30 ++ support/rust.nix | 100 ++++++ support/zig.nix | 80 +++++ 33 files changed, 3077 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 build.rs create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 src/archive.rs create mode 100644 src/cli.rs create mode 100644 src/commands/compress.rs create mode 100644 src/commands/create.rs create mode 100644 src/commands/decompress.rs create mode 100644 src/commands/detect.rs create mode 100644 src/commands/extract.rs create mode 100644 src/commands/list.rs create mode 100644 src/commands/mod.rs create mode 100644 src/commands/print.rs create mode 100644 src/detect.rs create mode 100644 src/format.rs create mode 100644 src/libarchive_sys.rs create mode 100644 src/main.rs create mode 100644 support/compile-rust.nix create mode 100644 support/lib-bzip2.nix create mode 100644 support/lib-libarchive.nix create mode 100644 support/lib-libxml2.nix create mode 100644 support/lib-lz4.nix create mode 100644 support/lib-xz.nix create mode 100644 support/lib-zlib.nix create mode 100644 support/lib-zstd.nix create mode 100644 support/musl-libs.nix create mode 100644 support/rust.nix create mode 100644 support/zig.nix diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a66975c --- /dev/null +++ b/.gitignore @@ -0,0 +1,34 @@ +# editors +.vscode/ +.idea/ +.godot/ + +# apple +.DS_Store +.AppleDouble +.LSOverride + +# build related directories +/build +target +zig-out +zig-build + +# secrets +.env + +# direnv +.envrc +.direnv + +# py +__pycache__/ +.pytest_cache +.mypy_cache +.ruff_cache +.coverage* + + +# Added by cargo + +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..6f2c946 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,193 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea" + +[[package]] +name = "clap" +version = "4.5.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6899ea499e3fb9305a65d5ebf6e3d2248c5fab291f300ad0a704fbe142eae31a" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b12c8b680195a62a8364d16b8447b01b6c2c8f9aaf68bee653be34d4245e238" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32" + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "syn" +version = "2.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "yaar" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..780d38a --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "yaar" +version = "0.1.0" +edition = "2024" + +[dependencies] +clap = { version = "4", features = ["derive"] } +anyhow = "1" + +[profile.release] +lto = true +strip = true diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..37106a5 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# yaar + +> **WARNING: This project is vibe-coded.** + +Yet another archiver. A CLI tool for creating, extracting, compressing, and inspecting archives using libarchive. + +## License + +GPL-3.0 diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..e1440b6 --- /dev/null +++ b/build.rs @@ -0,0 +1,9 @@ +fn main() { + println!("cargo:rustc-link-lib=static=archive"); + println!("cargo:rustc-link-lib=static=z"); + println!("cargo:rustc-link-lib=static=bz2"); + println!("cargo:rustc-link-lib=static=lzma"); + println!("cargo:rustc-link-lib=static=zstd"); + println!("cargo:rustc-link-lib=static=lz4"); + println!("cargo:rustc-link-lib=static=xml2"); +} diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..73b1002 --- /dev/null +++ b/flake.lock @@ -0,0 +1,48 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1764521362, + "narHash": "sha256-M101xMtWdF1eSD0xhiR8nG8CXRlHmv6V+VoY65Smwf4=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "871b9fd269ff6246794583ce4ee1031e1da71895", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "25.11", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs", + "rust-overlay": "rust-overlay" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1770606655, + "narHash": "sha256-rpJf+kxvLWv32ivcgu8d+JeJooog3boJCT8J3joJvvM=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "11a396520bf911e4ed01e78e11633d3fc63b350e", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..8d92471 --- /dev/null +++ b/flake.nix @@ -0,0 +1,62 @@ +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/25.11"; + rust-overlay = { + url = "github:oxalica/rust-overlay"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + }; + + outputs = { self, nixpkgs, rust-overlay, ... }: + let + systems = [ "x86_64-linux" "aarch64-linux" ]; + forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f system); + + # All packages are built from x86_64-linux host via zig cross-compilation + pkgs = import nixpkgs { system = "x86_64-linux"; }; + + zig = import ./support/zig.nix { inherit pkgs; system = "x86_64-linux"; }; + + compileRust = import ./support/compile-rust.nix { inherit pkgs zig; }; + + mkYaar = target: + let + muslLibs = import ./support/musl-libs.nix { + inherit pkgs zig; + name-target = target; + }; + in compileRust { + inherit target; + src = self; + cargoLock = { lockFile = ./Cargo.lock; }; + extraLibs = muslLibs.allLibs; + }; + in + { + packages.x86_64-linux = { + yaar-amd64-linux = mkYaar "amd64-linux"; + yaar-arm64-linux = mkYaar "arm64-linux"; + }; + + devShells = forAllSystems (system: + let + devPkgs = import nixpkgs { + inherit system; + overlays = [ rust-overlay.overlays.default ]; + }; + rust = devPkgs.rust-bin.stable.latest.default.override { + extensions = [ "rust-src" "rust-analyzer" ]; + targets = [ "x86_64-unknown-linux-musl" ]; + }; + in + { + default = devPkgs.mkShell { + buildInputs = [ + rust + devPkgs.pkg-config + devPkgs.libarchive + ]; + }; + }); + }; +} diff --git a/src/archive.rs b/src/archive.rs new file mode 100644 index 0000000..dc99a29 --- /dev/null +++ b/src/archive.rs @@ -0,0 +1,519 @@ +use std::ffi::{CStr, CString}; +use std::path::Path; +use std::ptr; + +use anyhow::{bail, Context, Result}; +use crate::libarchive_sys::*; + +const BLOCK_SIZE: usize = 16384; + +fn check(archive: *mut archive, rc: ::std::os::raw::c_int) -> Result<()> { + if rc == ARCHIVE_OK as _ || rc == ARCHIVE_WARN as _ { + return Ok(()); + } + let msg = unsafe { + let p = archive_error_string(archive); + if p.is_null() { + "unknown archive error".to_string() + } else { + CStr::from_ptr(p).to_string_lossy().into_owned() + } + }; + bail!("{msg}"); +} + +/// Safe wrapper around libarchive's archive reader. +pub struct ArchiveReader { + raw: *mut archive, +} + +impl ArchiveReader { + pub fn raw(&self) -> *mut archive { + self.raw + } + + /// Create a new reader with all formats and filters enabled. + pub fn new_auto() -> Result { + unsafe { + let raw = archive_read_new(); + if raw.is_null() { + bail!("archive_read_new returned null"); + } + check(raw, archive_read_support_format_all(raw))?; + check(raw, archive_read_support_filter_all(raw))?; + Ok(Self { raw }) + } + } + + /// Create a reader for raw (single-stream) format with all filters. + pub fn new_raw() -> Result { + unsafe { + let raw = archive_read_new(); + if raw.is_null() { + bail!("archive_read_new returned null"); + } + check(raw, archive_read_support_format_raw(raw))?; + check(raw, archive_read_support_filter_all(raw))?; + Ok(Self { raw }) + } + } + + pub fn open_filename(&self, path: &Path, block_size: usize) -> Result<()> { + let c_path = + CString::new(path.to_str().context("non-UTF8 path")?).context("null in path")?; + unsafe { + check( + self.raw, + archive_read_open_filename(self.raw, c_path.as_ptr(), block_size), + ) + } + } + + pub fn open_memory(&self, data: &[u8]) -> Result<()> { + unsafe { + check( + self.raw, + archive_read_open_memory(self.raw, data.as_ptr() as *mut _, data.len()), + ) + } + } + + pub fn next_header(&self) -> Result> { + unsafe { + let mut entry: *mut archive_entry = ptr::null_mut(); + let rc = archive_read_next_header(self.raw, &mut entry); + if rc == ARCHIVE_EOF as _ { + return Ok(None); + } + check(self.raw, rc)?; + Ok(Some(ArchiveEntry { + raw: entry, + owned: false, + })) + } + } + + /// Read data from the current entry into a buffer. Returns bytes read, 0 at EOF. + pub fn read_data(&self, buf: &mut [u8]) -> Result { + unsafe { + let n = archive_read_data(self.raw, buf.as_mut_ptr() as *mut _, buf.len()); + if n < 0 { + check(self.raw, n as _)?; + } + Ok(n as usize) + } + } + + /// Read a data block (zero-copy). Returns None at EOF. + pub fn read_data_block(&self) -> Result> { + unsafe { + let mut buf: *const std::ffi::c_void = ptr::null(); + let mut size: usize = 0; + let mut offset: i64 = 0; + let rc = archive_read_data_block(self.raw, &mut buf, &mut size, &mut offset); + if rc == ARCHIVE_EOF as _ { + return Ok(None); + } + check(self.raw, rc)?; + Ok(Some(( + std::slice::from_raw_parts(buf as *const u8, size), + offset, + ))) + } + } + + pub fn format(&self) -> i32 { + unsafe { archive_format(self.raw) } + } + + pub fn filter_count(&self) -> i32 { + unsafe { archive_filter_count(self.raw) } + } + + pub fn filter_code(&self, index: i32) -> i32 { + unsafe { archive_filter_code(self.raw, index) } + } + + pub fn filter_name(&self, index: i32) -> Option { + unsafe { + let p = archive_filter_name(self.raw, index); + if p.is_null() { + None + } else { + Some(CStr::from_ptr(p).to_string_lossy().into_owned()) + } + } + } + + pub fn format_name(&self) -> Option { + unsafe { + let p = archive_format_name(self.raw); + if p.is_null() { + None + } else { + Some(CStr::from_ptr(p).to_string_lossy().into_owned()) + } + } + } +} + +impl Drop for ArchiveReader { + fn drop(&mut self) { + unsafe { + archive_read_free(self.raw); + } + } +} + +/// Safe wrapper around libarchive's archive writer. +pub struct ArchiveWriter { + raw: *mut archive, +} + +impl ArchiveWriter { + pub fn raw(&self) -> *mut archive { + self.raw + } + + pub fn new() -> Result { + unsafe { + let raw = archive_write_new(); + if raw.is_null() { + bail!("archive_write_new returned null"); + } + Ok(Self { raw }) + } + } + + /// Create a new writer configured for raw (single-stream) format. + pub fn new_raw() -> Result { + unsafe { + let raw = archive_write_new(); + if raw.is_null() { + bail!("archive_write_new returned null"); + } + check(raw, archive_write_set_format_raw(raw))?; + Ok(Self { raw }) + } + } + + pub fn set_format(&self, code: i32) -> Result<()> { + unsafe { check(self.raw, archive_write_set_format(self.raw, code)) } + } + + pub fn set_format_pax_restricted(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_set_format_pax_restricted(self.raw)) } + } + + pub fn set_format_zip(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_set_format_zip(self.raw)) } + } + + pub fn set_format_7zip(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_set_format_7zip(self.raw)) } + } + + pub fn set_format_ar_svr4(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_set_format_ar_svr4(self.raw)) } + } + + pub fn set_format_cpio_newc(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_set_format_cpio_newc(self.raw)) } + } + + pub fn set_format_raw(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_set_format_raw(self.raw)) } + } + + pub fn add_filter(&self, code: i32) -> Result<()> { + unsafe { check(self.raw, archive_write_add_filter(self.raw, code)) } + } + + pub fn add_filter_none(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_add_filter_none(self.raw)) } + } + + pub fn open_filename(&self, path: &Path) -> Result<()> { + let c_path = + CString::new(path.to_str().context("non-UTF8 path")?).context("null in path")?; + unsafe { check(self.raw, archive_write_open_filename(self.raw, c_path.as_ptr())) } + } + + pub fn open_stdout(&self) -> Result<()> { + // Passing null filename writes to stdout + unsafe { check(self.raw, archive_write_open_fd(self.raw, 1)) } + } + + pub fn write_header(&self, entry: &ArchiveEntry) -> Result<()> { + unsafe { check(self.raw, archive_write_header(self.raw, entry.raw)) } + } + + pub fn write_data(&self, data: &[u8]) -> Result { + unsafe { + let n = archive_write_data(self.raw, data.as_ptr() as *const _, data.len()); + if n < 0 { + check(self.raw, n as _)?; + } + Ok(n as usize) + } + } + + pub fn finish_entry(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_finish_entry(self.raw)) } + } + + pub fn close(&self) -> Result<()> { + unsafe { check(self.raw, archive_write_close(self.raw)) } + } +} + +impl Drop for ArchiveWriter { + fn drop(&mut self) { + unsafe { + archive_write_free(self.raw); + } + } +} + +/// Safe wrapper around a libarchive archive_entry. +pub struct ArchiveEntry { + raw: *mut archive_entry, + owned: bool, +} + +impl ArchiveEntry { + pub fn raw(&self) -> *mut archive_entry { + self.raw + } + + pub fn new() -> Result { + unsafe { + let raw = archive_entry_new(); + if raw.is_null() { + bail!("archive_entry_new returned null"); + } + Ok(Self { raw, owned: true }) + } + } + + pub fn pathname(&self) -> Option { + unsafe { + let p = archive_entry_pathname_utf8(self.raw); + if p.is_null() { + let p = archive_entry_pathname(self.raw); + if p.is_null() { + return None; + } + return Some(CStr::from_ptr(p).to_string_lossy().into_owned()); + } + Some(CStr::from_ptr(p).to_string_lossy().into_owned()) + } + } + + pub fn set_pathname(&self, name: &str) { + let c = CString::new(name).unwrap(); + unsafe { + archive_entry_set_pathname_utf8(self.raw, c.as_ptr()); + } + } + + pub fn size(&self) -> i64 { + unsafe { archive_entry_size(self.raw) } + } + + pub fn set_size(&self, size: i64) { + unsafe { + archive_entry_set_size(self.raw, size); + } + } + + pub fn filetype(&self) -> u32 { + unsafe { archive_entry_filetype(self.raw) as u32 } + } + + pub fn set_filetype(&self, ft: u32) { + unsafe { + archive_entry_set_filetype(self.raw, ft as _); + } + } + + pub fn perm(&self) -> u32 { + unsafe { archive_entry_perm(self.raw) as u32 } + } + + pub fn set_perm(&self, perm: u32) { + unsafe { + archive_entry_set_perm(self.raw, perm as _); + } + } + + pub fn set_mtime(&self, sec: i64, nsec: i64) { + unsafe { + archive_entry_set_mtime(self.raw, sec, nsec as _); + } + } + + pub fn set_atime(&self, sec: i64, nsec: i64) { + unsafe { + archive_entry_set_atime(self.raw, sec, nsec as _); + } + } + + pub fn set_ctime(&self, sec: i64, nsec: i64) { + unsafe { + archive_entry_set_ctime(self.raw, sec, nsec as _); + } + } + + pub fn set_uid(&self, uid: u64) { + unsafe { + archive_entry_set_uid(self.raw, uid as _); + } + } + + pub fn set_gid(&self, gid: u64) { + unsafe { + archive_entry_set_gid(self.raw, gid as _); + } + } + + pub fn set_uname(&self, name: &str) { + let c = CString::new(name).unwrap(); + unsafe { + archive_entry_set_uname_utf8(self.raw, c.as_ptr()); + } + } + + pub fn set_gname(&self, name: &str) { + let c = CString::new(name).unwrap(); + unsafe { + archive_entry_set_gname_utf8(self.raw, c.as_ptr()); + } + } + + pub fn hardlink(&self) -> Option { + unsafe { + let p = archive_entry_hardlink_utf8(self.raw); + if p.is_null() { + None + } else { + Some(CStr::from_ptr(p).to_string_lossy().into_owned()) + } + } + } + + pub fn symlink(&self) -> Option { + unsafe { + let p = archive_entry_symlink_utf8(self.raw); + if p.is_null() { + None + } else { + Some(CStr::from_ptr(p).to_string_lossy().into_owned()) + } + } + } + + pub fn clear(&self) { + unsafe { + archive_entry_clear(self.raw); + } + } + + /// Apply deterministic defaults: zero timestamps, uid/gid 0, root/root names. + pub fn make_deterministic(&self) { + self.set_mtime(0, 0); + self.set_atime(0, 0); + self.set_ctime(0, 0); + self.set_uid(0); + self.set_gid(0); + self.set_uname("root"); + self.set_gname("root"); + } +} + +impl Drop for ArchiveEntry { + fn drop(&mut self) { + if self.owned { + unsafe { + archive_entry_free(self.raw); + } + } + } +} + +/// Safe wrapper around archive_read_disk for reading files from the filesystem. +pub struct ArchiveDisk { + raw: *mut archive, +} + +impl ArchiveDisk { + pub fn raw(&self) -> *mut archive { + self.raw + } + + pub fn new() -> Result { + unsafe { + let raw = archive_read_disk_new(); + if raw.is_null() { + bail!("archive_read_disk_new returned null"); + } + check(raw, archive_read_disk_set_standard_lookup(raw))?; + Ok(Self { raw }) + } + } + + pub fn open(&self, path: &Path) -> Result<()> { + let c_path = + CString::new(path.to_str().context("non-UTF8 path")?).context("null in path")?; + unsafe { check(self.raw, archive_read_disk_open(self.raw, c_path.as_ptr())) } + } + + pub fn descend(&self) -> Result<()> { + unsafe { check(self.raw, archive_read_disk_descend(self.raw)) } + } + + pub fn next_header(&self, entry: &ArchiveEntry) -> Result { + unsafe { + let rc = archive_read_next_header2(self.raw, entry.raw()); + if rc == ARCHIVE_EOF as _ { + return Ok(false); + } + check(self.raw, rc)?; + Ok(true) + } + } +} + +impl Drop for ArchiveDisk { + fn drop(&mut self) { + unsafe { + archive_read_free(self.raw); + } + } +} + +/// Copy data from reader to writer using data blocks. +pub fn copy_data(reader: &ArchiveReader, writer: &ArchiveWriter) -> Result<()> { + let mut buf = [0u8; BLOCK_SIZE]; + loop { + let n = reader.read_data(&mut buf)?; + if n == 0 { + break; + } + writer.write_data(&buf[..n])?; + } + Ok(()) +} + +/// Create a disk writer for extracting archives to the filesystem. +pub fn disk_writer(flags: i32) -> Result { + unsafe { + let raw = archive_write_disk_new(); + if raw.is_null() { + bail!("archive_write_disk_new returned null"); + } + check(raw, archive_write_disk_set_options(raw, flags))?; + check(raw, archive_write_disk_set_standard_lookup(raw))?; + Ok(ArchiveWriter { raw }) + } +} diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..5c052f7 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,142 @@ +use std::fmt; +use std::path::PathBuf; +use std::str::FromStr; + +use clap::{Parser, Subcommand}; + +use crate::format::{ArchiveFormat, Compression}; + +/// Output format for list and detect commands. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OutputFormat { + #[default] + Newline, + Null, + Json, +} + +impl FromStr for OutputFormat { + type Err = String; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "nl" | "newline" => Ok(Self::Newline), + "0" | "null" => Ok(Self::Null), + "json" => Ok(Self::Json), + _ => Err(format!("unknown output format: {s} (expected: nl, 0, json)")), + } + } +} + +impl fmt::Display for OutputFormat { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Newline => write!(f, "nl"), + Self::Null => write!(f, "0"), + Self::Json => write!(f, "json"), + } + } +} + +#[derive(Parser)] +#[command(name = "yaar", about = "Yet another archiver")] +pub struct Cli { + #[command(subcommand)] + pub command: Command, +} + +#[derive(Subcommand)] +pub enum Command { + /// Compress a file or stdin + Compress { + /// Compression format (gz, xz, zstd, bz2, lz4, lzma) + #[arg(short = 'f', long = "format")] + format: Option, + + /// Output file (default: stdout) + #[arg(short, long)] + output: Option, + + /// Input file (default: stdin) + file: Option, + }, + + /// Decompress a file or stdin + Decompress { + /// Output file (default: stdout) + #[arg(short, long)] + output: Option, + + /// Input file (default: stdin) + file: Option, + }, + + /// List archive entries + List { + /// Output format (nl, 0, json) + #[arg(short = 'f', long = "format", default_value = "nl")] + output_format: OutputFormat, + + /// Archive file + archive: PathBuf, + }, + + /// Print a single file from an archive to stdout + Print { + /// Archive file + archive: PathBuf, + + /// Path within the archive + path: String, + }, + + /// Extract an archive + Extract { + /// Directory to extract into + #[arg(short = 'C', long = "output-dir")] + output_dir: Option, + + /// Strip N leading path components + #[arg(long = "strip-components", alias = "strip")] + strip_components: Option, + + /// Archive file + archive: PathBuf, + }, + + /// Create an archive from files + Create { + /// Archive format (tar, zip, 7z, ar, cpio) + #[arg(short = 'f', long = "format", default_value = "tar")] + format: ArchiveFormat, + + /// Compression (none, gz, xz, zstd, bz2, lz4, lzma) + #[arg(short = 'c', long = "compression", default_value = "none")] + compression: Compression, + + /// Strip this prefix from stored paths + #[arg(long = "strip-prefix")] + strip_prefix: Option, + + /// Disable deterministic mode (preserve real timestamps/uid/gid/order) + #[arg(long = "non-det")] + non_det: bool, + + /// Output archive file + #[arg(short, long)] + output: PathBuf, + + /// Files/directories to add + files: Vec, + }, + + /// Detect archive format and compression + Detect { + /// Output format (nl, 0, json) + #[arg(short = 'f', long = "format", default_value = "nl")] + output_format: OutputFormat, + + /// File to detect + file: PathBuf, + }, +} diff --git a/src/commands/compress.rs b/src/commands/compress.rs new file mode 100644 index 0000000..cc531c2 --- /dev/null +++ b/src/commands/compress.rs @@ -0,0 +1,76 @@ +use std::io::Read; +use std::path::PathBuf; + +use anyhow::{Context, Result}; + +use crate::archive::{ArchiveEntry, ArchiveWriter}; +use crate::format::Compression; + +/// AE_IFREG: regular file type flag. +const AE_IFREG: u32 = 0o100000; + +pub fn run( + format: Option, + output: Option, + file: Option, +) -> Result<()> { + // 1. Read input data. + let data = match file { + Some(ref path) => { + std::fs::read(path) + .with_context(|| format!("failed to read input file: {}", path.display()))? + } + None => { + let mut buf = Vec::new(); + std::io::stdin() + .read_to_end(&mut buf) + .context("failed to read from stdin")?; + buf + } + }; + + // 2. Default to gzip if no format specified. + let compression = format.unwrap_or(Compression::Gzip); + + // 3. Create a raw archive writer (single stream, no archive structure). + let writer = ArchiveWriter::new_raw().context("failed to create archive writer")?; + + // 4. Add the compression filter. + writer + .add_filter(compression.filter_code()) + .context("failed to add compression filter")?; + + // 5. Open output destination. + match output { + Some(ref path) => { + writer + .open_filename(path) + .with_context(|| format!("failed to open output file: {}", path.display()))?; + } + None => { + writer + .open_stdout() + .context("failed to open stdout for writing")?; + } + } + + // 6. Create an archive entry for the data. + let entry = ArchiveEntry::new().context("failed to create archive entry")?; + entry.set_filetype(AE_IFREG); + entry.set_size(data.len() as i64); + entry.set_pathname("data"); + + // 7. Write header, data, finish entry, and close. + writer + .write_header(&entry) + .context("failed to write archive header")?; + writer + .write_data(&data) + .context("failed to write compressed data")?; + writer + .finish_entry() + .context("failed to finish archive entry")?; + writer.close().context("failed to close archive writer")?; + + Ok(()) +} diff --git a/src/commands/create.rs b/src/commands/create.rs new file mode 100644 index 0000000..a8dc510 --- /dev/null +++ b/src/commands/create.rs @@ -0,0 +1,129 @@ +use std::io::Read; +use std::path::PathBuf; + +use anyhow::{Context, Result}; + +use crate::archive::{ArchiveDisk, ArchiveEntry, ArchiveWriter}; +use crate::format::{ArchiveFormat, Compression}; + +/// AE_IFDIR: directory file type flag. +const AE_IFDIR: u32 = 0o40000; + +/// AE_IFREG: regular file type flag. +const AE_IFREG: u32 = 0o100000; + +pub fn run( + format: ArchiveFormat, + compression: Compression, + strip_prefix: Option, + non_det: bool, + output: PathBuf, + files: Vec, +) -> Result<()> { + // 1. Collect all file paths. + let mut paths: Vec = Vec::new(); + + for input in &files { + if input.is_dir() { + let disk = ArchiveDisk::new().context("failed to create disk reader")?; + let entry = ArchiveEntry::new().context("failed to create archive entry")?; + disk.open(input) + .with_context(|| format!("failed to open directory: {}", input.display()))?; + loop { + if !disk.next_header(&entry)? { + break; + } + if entry.filetype() == AE_IFDIR { + let _ = disk.descend(); + } + if let Some(pathname) = entry.pathname() { + paths.push(pathname); + } + entry.clear(); + } + } else { + paths.push( + input + .to_str() + .context("non-UTF8 path")? + .to_string(), + ); + } + } + + // 2. Sort for determinism (unless non_det is true). + if !non_det { + paths.sort(); + } + + // 3. Create writer. + let writer = ArchiveWriter::new().context("failed to create archive writer")?; + format + .apply_to_writer(&writer) + .context("failed to set archive format")?; + writer + .add_filter(compression.filter_code()) + .context("failed to add compression filter")?; + writer + .open_filename(&output) + .with_context(|| format!("failed to open output file: {}", output.display()))?; + + // 4. Add each file. + for path in &paths { + let disk = ArchiveDisk::new().context("failed to create disk reader")?; + let entry = ArchiveEntry::new().context("failed to create archive entry")?; + + disk.open(path.as_ref()) + .with_context(|| format!("failed to open: {path}"))?; + disk.next_header(&entry) + .with_context(|| format!("failed to read header for: {path}"))?; + + // Apply strip_prefix. + if let Some(ref prefix) = strip_prefix { + if let Some(pathname) = entry.pathname() { + if let Some(stripped) = pathname.strip_prefix(prefix) { + let stripped = stripped.trim_start_matches('/'); + let stripped = if stripped.is_empty() { "." } else { stripped }; + entry.set_pathname(stripped); + } + } + } + + // Make deterministic if requested. + if !non_det { + entry.make_deterministic(); + } + + // Write header. + writer + .write_header(&entry) + .with_context(|| format!("failed to write header for: {path}"))?; + + // If regular file, copy file data. + if entry.filetype() == AE_IFREG { + let mut file = std::fs::File::open(path) + .with_context(|| format!("failed to open file for reading: {path}"))?; + let mut buf = [0u8; 16384]; + loop { + let n = file + .read(&mut buf) + .with_context(|| format!("failed to read file: {path}"))?; + if n == 0 { + break; + } + writer + .write_data(&buf[..n]) + .with_context(|| format!("failed to write data for: {path}"))?; + } + } + + writer + .finish_entry() + .with_context(|| format!("failed to finish entry for: {path}"))?; + } + + // 5. Close the writer. + writer.close().context("failed to close archive writer")?; + + Ok(()) +} diff --git a/src/commands/decompress.rs b/src/commands/decompress.rs new file mode 100644 index 0000000..bb053b9 --- /dev/null +++ b/src/commands/decompress.rs @@ -0,0 +1,55 @@ +use std::fs::File; +use std::io::{self, Read, Write}; +use std::path::PathBuf; + +use anyhow::{Context, Result}; + +use crate::archive::ArchiveReader; + +pub fn run(output: Option, file: Option) -> Result<()> { + let reader = ArchiveReader::new_raw()?; + + let stdin_data; + if let Some(ref path) = file { + reader + .open_filename(path, 16384) + .with_context(|| format!("failed to open {}", path.display()))?; + } else { + stdin_data = { + let mut buf = Vec::new(); + io::stdin() + .read_to_end(&mut buf) + .context("failed to read stdin")?; + buf + }; + reader + .open_memory(&stdin_data) + .context("failed to open stdin data")?; + } + + reader + .next_header() + .context("failed to read header")? + .context("no entry found in input")?; + + let mut out: Box = if let Some(ref path) = output { + Box::new( + File::create(path) + .with_context(|| format!("failed to create {}", path.display()))?, + ) + } else { + Box::new(io::stdout().lock()) + }; + + let mut buf = [0u8; 16384]; + loop { + let n = reader.read_data(&mut buf)?; + if n == 0 { + break; + } + out.write_all(&buf[..n]) + .context("failed to write output")?; + } + + Ok(()) +} diff --git a/src/commands/detect.rs b/src/commands/detect.rs new file mode 100644 index 0000000..6e56a99 --- /dev/null +++ b/src/commands/detect.rs @@ -0,0 +1,64 @@ +use std::io::Write; +use std::path::PathBuf; + +use anyhow::Result; + +use crate::cli::OutputFormat; + +pub fn run(output_format: OutputFormat, file: PathBuf) -> Result<()> { + let result = crate::detect::detect_file(&file)?; + let mut stdout = std::io::stdout().lock(); + + let filters: Vec<&str> = result + .filters + .iter() + .filter(|(code, _)| *code != crate::libarchive_sys::ARCHIVE_FILTER_NONE as i32) + .map(|(_, name)| name.as_str()) + .collect(); + + match output_format { + OutputFormat::Json => { + stdout.write_all(b"{\"format\":")?; + write_json_string(&mut stdout, &result.format_name)?; + stdout.write_all(b",\"filters\":[")?; + for (i, f) in filters.iter().enumerate() { + if i > 0 { + stdout.write_all(b",")?; + } + write_json_string(&mut stdout, f)?; + } + stdout.write_all(b"]}\n")?; + } + _ => { + let sep = if output_format == OutputFormat::Null { + '\0' + } else { + '\n' + }; + write!(stdout, "format: {}{sep}", result.format_name)?; + for f in &filters { + write!(stdout, "filter: {f}{sep}")?; + } + } + } + + stdout.flush()?; + Ok(()) +} + +fn write_json_string(w: &mut impl Write, s: &str) -> std::io::Result<()> { + w.write_all(b"\"")?; + for ch in s.chars() { + match ch { + '"' => w.write_all(b"\\\"")?, + '\\' => w.write_all(b"\\\\")?, + '\n' => w.write_all(b"\\n")?, + '\r' => w.write_all(b"\\r")?, + '\t' => w.write_all(b"\\t")?, + c if c.is_control() => write!(w, "\\u{:04x}", c as u32)?, + c => write!(w, "{c}")?, + } + } + w.write_all(b"\"")?; + Ok(()) +} diff --git a/src/commands/extract.rs b/src/commands/extract.rs new file mode 100644 index 0000000..ad13e3b --- /dev/null +++ b/src/commands/extract.rs @@ -0,0 +1,66 @@ +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use crate::libarchive_sys::*; + +use crate::archive::{copy_data, disk_writer, ArchiveReader}; + +pub fn run(output_dir: Option, strip_components: Option, archive: PathBuf) -> Result<()> { + // Canonicalize the archive path before potentially changing the working directory. + let archive = archive + .canonicalize() + .with_context(|| format!("failed to canonicalize path: {}", archive.display()))?; + + if let Some(ref dir) = output_dir { + std::fs::create_dir_all(dir) + .with_context(|| format!("failed to create output directory: {}", dir.display()))?; + std::env::set_current_dir(dir) + .with_context(|| format!("failed to change directory to: {}", dir.display()))?; + } + + let reader = ArchiveReader::new_auto()?; + reader.open_filename(&archive, 10240)?; + + let flags = ARCHIVE_EXTRACT_TIME + | ARCHIVE_EXTRACT_PERM + | ARCHIVE_EXTRACT_ACL + | ARCHIVE_EXTRACT_FFLAGS + | ARCHIVE_EXTRACT_SECURE_SYMLINKS + | ARCHIVE_EXTRACT_SECURE_NODOTDOT + | ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS; + + let writer = disk_writer(flags as i32)?; + + while let Some(entry) = reader.next_header()? { + let pathname = match entry.pathname() { + Some(p) => p, + None => continue, + }; + + if let Some(n) = strip_components { + let path = Path::new(&pathname); + let components: Vec<_> = path.components().skip(n).collect(); + if components.is_empty() { + continue; + } + let new_path: PathBuf = components.iter().collect(); + let new_path_str = new_path.to_string_lossy(); + if new_path_str.is_empty() { + continue; + } + entry.set_pathname(&new_path_str); + } + + writer.write_header(&entry)?; + + if entry.size() > 0 { + copy_data(&reader, &writer)?; + } + + writer.finish_entry()?; + } + + writer.close()?; + + Ok(()) +} diff --git a/src/commands/list.rs b/src/commands/list.rs new file mode 100644 index 0000000..6d69a67 --- /dev/null +++ b/src/commands/list.rs @@ -0,0 +1,67 @@ +use std::io::Write; +use std::path::PathBuf; + +use anyhow::Result; + +use crate::archive::ArchiveReader; +use crate::cli::OutputFormat; + +pub fn run(output_format: OutputFormat, archive: PathBuf) -> Result<()> { + let reader = ArchiveReader::new_auto()?; + reader.open_filename(&archive, 10240)?; + + let mut stdout = std::io::stdout().lock(); + + match output_format { + OutputFormat::Json => { + let mut entries = Vec::new(); + while let Some(entry) = reader.next_header()? { + if let Some(pathname) = entry.pathname() { + entries.push(pathname); + } + } + // Write JSON array manually to avoid serde dependency + stdout.write_all(b"[")?; + for (i, entry) in entries.iter().enumerate() { + if i > 0 { + stdout.write_all(b",")?; + } + write_json_string(&mut stdout, entry)?; + } + stdout.write_all(b"]\n")?; + } + _ => { + let separator = if output_format == OutputFormat::Null { + b'\0' + } else { + b'\n' + }; + while let Some(entry) = reader.next_header()? { + if let Some(pathname) = entry.pathname() { + stdout.write_all(pathname.as_bytes())?; + stdout.write_all(&[separator])?; + } + } + } + } + + stdout.flush()?; + Ok(()) +} + +fn write_json_string(w: &mut impl Write, s: &str) -> std::io::Result<()> { + w.write_all(b"\"")?; + for ch in s.chars() { + match ch { + '"' => w.write_all(b"\\\"")?, + '\\' => w.write_all(b"\\\\")?, + '\n' => w.write_all(b"\\n")?, + '\r' => w.write_all(b"\\r")?, + '\t' => w.write_all(b"\\t")?, + c if c.is_control() => write!(w, "\\u{:04x}", c as u32)?, + c => write!(w, "{c}")?, + } + } + w.write_all(b"\"")?; + Ok(()) +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000..be9dc26 --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,7 @@ +pub mod compress; +pub mod create; +pub mod decompress; +pub mod detect; +pub mod extract; +pub mod list; +pub mod print; diff --git a/src/commands/print.rs b/src/commands/print.rs new file mode 100644 index 0000000..df918bd --- /dev/null +++ b/src/commands/print.rs @@ -0,0 +1,34 @@ +use std::io::Write; +use std::path::PathBuf; + +use anyhow::{bail, Result}; + +use crate::archive::ArchiveReader; + +pub fn run(archive: PathBuf, path: String) -> Result<()> { + let reader = ArchiveReader::new_auto()?; + reader.open_filename(&archive, 10240)?; + + let needle = path.trim_end_matches('/'); + + while let Some(entry) = reader.next_header()? { + if let Some(pathname) = entry.pathname() { + let entry_name = pathname.trim_end_matches('/'); + if entry_name == needle || pathname == path { + let mut stdout = std::io::stdout().lock(); + let mut buf = [0u8; 16384]; + loop { + let n = reader.read_data(&mut buf)?; + if n == 0 { + break; + } + stdout.write_all(&buf[..n])?; + } + stdout.flush()?; + return Ok(()); + } + } + } + + bail!("entry not found: {path}"); +} diff --git a/src/detect.rs b/src/detect.rs new file mode 100644 index 0000000..822f647 --- /dev/null +++ b/src/detect.rs @@ -0,0 +1,58 @@ +use std::path::Path; + +use anyhow::{Context, Result}; + +use crate::archive::ArchiveReader; +use crate::format::{ArchiveFormat, Compression}; + +pub struct DetectResult { + pub format_code: i32, + pub format_name: String, + pub filters: Vec<(i32, String)>, +} + +impl DetectResult { + pub fn archive_format(&self) -> Option { + ArchiveFormat::from_code(self.format_code) + } + + pub fn compression(&self) -> Option { + // The outermost non-none filter is the compression + for &(code, _) in &self.filters { + let comp = Compression::from_code(code); + if comp.is_some() && comp != Some(Compression::None) { + return comp; + } + } + Some(Compression::None) + } +} + +/// Detect the format and compression of a file using libarchive. +pub fn detect_file(path: &Path) -> Result { + let reader = ArchiveReader::new_auto()?; + reader + .open_filename(path, 10240) + .context("failed to open file for detection")?; + + // Read the first header to trigger format detection + let _ = reader.next_header()?; + + let format_code = reader.format(); + let format_name = ArchiveFormat::name_from_code(format_code).to_string(); + + let mut filters = Vec::new(); + let count = reader.filter_count(); + // Filter 0 is the format itself, filters 1..n are compression filters + for i in 0..count { + let code = reader.filter_code(i); + let name = Compression::name_from_code(code).to_string(); + filters.push((code, name)); + } + + Ok(DetectResult { + format_code, + format_name, + filters, + }) +} diff --git a/src/format.rs b/src/format.rs new file mode 100644 index 0000000..8d668c8 --- /dev/null +++ b/src/format.rs @@ -0,0 +1,185 @@ +use std::fmt; +use std::str::FromStr; + +use crate::libarchive_sys::*; + +/// Supported archive formats for writing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ArchiveFormat { + Tar, + Zip, + SevenZip, + Ar, + Cpio, +} + +impl ArchiveFormat { + /// Apply this format to an archive writer. + pub fn apply_to_writer(&self, writer: &crate::archive::ArchiveWriter) -> anyhow::Result<()> { + match self { + Self::Tar => writer.set_format_pax_restricted(), + Self::Zip => writer.set_format_zip(), + Self::SevenZip => writer.set_format_7zip(), + Self::Ar => writer.set_format_ar_svr4(), + Self::Cpio => writer.set_format_cpio_newc(), + } + } + + /// Try to identify format from a libarchive format code. + pub fn from_code(code: i32) -> Option { + let base = code & ARCHIVE_FORMAT_BASE_MASK as i32; + match base as u32 { + ARCHIVE_FORMAT_TAR => Some(Self::Tar), + ARCHIVE_FORMAT_ZIP => Some(Self::Zip), + ARCHIVE_FORMAT_7ZIP => Some(Self::SevenZip), + ARCHIVE_FORMAT_AR => Some(Self::Ar), + ARCHIVE_FORMAT_CPIO => Some(Self::Cpio), + _ => None, + } + } + + /// Human-readable name for a libarchive format code (including read-only formats). + pub fn name_from_code(code: i32) -> &'static str { + let base = code & ARCHIVE_FORMAT_BASE_MASK as i32; + match base as u32 { + ARCHIVE_FORMAT_TAR => "tar", + ARCHIVE_FORMAT_ZIP => "zip", + ARCHIVE_FORMAT_7ZIP => "7zip", + ARCHIVE_FORMAT_AR => "ar", + ARCHIVE_FORMAT_CPIO => "cpio", + ARCHIVE_FORMAT_RAR => "rar", + ARCHIVE_FORMAT_RAR_V5 => "rar5", + ARCHIVE_FORMAT_CAB => "cab", + ARCHIVE_FORMAT_LHA => "lha", + ARCHIVE_FORMAT_ISO9660 => "iso9660", + ARCHIVE_FORMAT_XAR => "xar", + ARCHIVE_FORMAT_MTREE => "mtree", + ARCHIVE_FORMAT_RAW => "raw", + ARCHIVE_FORMAT_WARC => "warc", + ARCHIVE_FORMAT_EMPTY => "empty", + _ => "unknown", + } + } +} + +impl FromStr for ArchiveFormat { + type Err = String; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "tar" => Ok(Self::Tar), + "zip" => Ok(Self::Zip), + "7z" | "7zip" => Ok(Self::SevenZip), + "ar" => Ok(Self::Ar), + "cpio" => Ok(Self::Cpio), + _ => Err(format!("unknown format: {s} (expected: tar, zip, 7z, ar, cpio)")), + } + } +} + +impl fmt::Display for ArchiveFormat { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Tar => write!(f, "tar"), + Self::Zip => write!(f, "zip"), + Self::SevenZip => write!(f, "7z"), + Self::Ar => write!(f, "ar"), + Self::Cpio => write!(f, "cpio"), + } + } +} + +/// Supported compression filters. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Compression { + None, + Gzip, + Xz, + Zstd, + Bzip2, + Lz4, + Lzma, +} + +impl Compression { + /// Get the libarchive filter code. + pub fn filter_code(&self) -> i32 { + match self { + Self::None => ARCHIVE_FILTER_NONE as _, + Self::Gzip => ARCHIVE_FILTER_GZIP as _, + Self::Xz => ARCHIVE_FILTER_XZ as _, + Self::Zstd => ARCHIVE_FILTER_ZSTD as _, + Self::Bzip2 => ARCHIVE_FILTER_BZIP2 as _, + Self::Lz4 => ARCHIVE_FILTER_LZ4 as _, + Self::Lzma => ARCHIVE_FILTER_LZMA as _, + } + } + + /// Try to identify compression from a libarchive filter code. + pub fn from_code(code: i32) -> Option { + match code as u32 { + ARCHIVE_FILTER_NONE => Some(Self::None), + ARCHIVE_FILTER_GZIP => Some(Self::Gzip), + ARCHIVE_FILTER_XZ => Some(Self::Xz), + ARCHIVE_FILTER_ZSTD => Some(Self::Zstd), + ARCHIVE_FILTER_BZIP2 => Some(Self::Bzip2), + ARCHIVE_FILTER_LZ4 => Some(Self::Lz4), + ARCHIVE_FILTER_LZMA => Some(Self::Lzma), + _ => None, + } + } + + /// Human-readable name for a libarchive filter code. + pub fn name_from_code(code: i32) -> &'static str { + match code as u32 { + ARCHIVE_FILTER_NONE => "none", + ARCHIVE_FILTER_GZIP => "gzip", + ARCHIVE_FILTER_BZIP2 => "bzip2", + ARCHIVE_FILTER_COMPRESS => "compress", + ARCHIVE_FILTER_LZMA => "lzma", + ARCHIVE_FILTER_XZ => "xz", + ARCHIVE_FILTER_LZ4 => "lz4", + ARCHIVE_FILTER_ZSTD => "zstd", + ARCHIVE_FILTER_LZIP => "lzip", + ARCHIVE_FILTER_LRZIP => "lrzip", + ARCHIVE_FILTER_LZOP => "lzop", + ARCHIVE_FILTER_GRZIP => "grzip", + ARCHIVE_FILTER_UU => "uu", + ARCHIVE_FILTER_RPM => "rpm", + _ => "unknown", + } + } +} + +impl FromStr for Compression { + type Err = String; + + fn from_str(s: &str) -> Result { + match s.to_lowercase().as_str() { + "none" => Ok(Self::None), + "gz" | "gzip" => Ok(Self::Gzip), + "xz" => Ok(Self::Xz), + "zstd" | "zst" => Ok(Self::Zstd), + "bz2" | "bzip2" => Ok(Self::Bzip2), + "lz4" => Ok(Self::Lz4), + "lzma" => Ok(Self::Lzma), + _ => Err(format!( + "unknown compression: {s} (expected: none, gz, xz, zstd, bz2, lz4, lzma)" + )), + } + } +} + +impl fmt::Display for Compression { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::None => write!(f, "none"), + Self::Gzip => write!(f, "gz"), + Self::Xz => write!(f, "xz"), + Self::Zstd => write!(f, "zstd"), + Self::Bzip2 => write!(f, "bz2"), + Self::Lz4 => write!(f, "lz4"), + Self::Lzma => write!(f, "lzma"), + } + } +} diff --git a/src/libarchive_sys.rs b/src/libarchive_sys.rs new file mode 100644 index 0000000..4f49155 --- /dev/null +++ b/src/libarchive_sys.rs @@ -0,0 +1,143 @@ +#![allow(non_camel_case_types, dead_code)] + +use std::os::raw::{c_char, c_int, c_long, c_void}; + +// Opaque types +#[repr(C)] +pub struct archive { + _opaque: [u8; 0], +} + +#[repr(C)] +pub struct archive_entry { + _opaque: [u8; 0], +} + +// Return codes +pub const ARCHIVE_EOF: c_int = 1; +pub const ARCHIVE_OK: c_int = 0; +pub const ARCHIVE_WARN: c_int = -20; + +// Format codes +pub const ARCHIVE_FORMAT_BASE_MASK: u32 = 0xff0000; +pub const ARCHIVE_FORMAT_CPIO: u32 = 0x10000; +pub const ARCHIVE_FORMAT_TAR: u32 = 0x30000; +pub const ARCHIVE_FORMAT_ISO9660: u32 = 0x40000; +pub const ARCHIVE_FORMAT_ZIP: u32 = 0x50000; +pub const ARCHIVE_FORMAT_EMPTY: u32 = 0x60000; +pub const ARCHIVE_FORMAT_AR: u32 = 0x70000; +pub const ARCHIVE_FORMAT_MTREE: u32 = 0x80000; +pub const ARCHIVE_FORMAT_RAW: u32 = 0x90000; +pub const ARCHIVE_FORMAT_XAR: u32 = 0xA0000; +pub const ARCHIVE_FORMAT_LHA: u32 = 0xB0000; +pub const ARCHIVE_FORMAT_CAB: u32 = 0xC0000; +pub const ARCHIVE_FORMAT_RAR: u32 = 0xD0000; +pub const ARCHIVE_FORMAT_7ZIP: u32 = 0xE0000; +pub const ARCHIVE_FORMAT_WARC: u32 = 0xF0000; +pub const ARCHIVE_FORMAT_RAR_V5: u32 = 0x100000; + +// Filter codes +pub const ARCHIVE_FILTER_NONE: u32 = 0; +pub const ARCHIVE_FILTER_GZIP: u32 = 1; +pub const ARCHIVE_FILTER_BZIP2: u32 = 2; +pub const ARCHIVE_FILTER_COMPRESS: u32 = 3; +pub const ARCHIVE_FILTER_LZMA: u32 = 5; +pub const ARCHIVE_FILTER_XZ: u32 = 6; +pub const ARCHIVE_FILTER_UU: u32 = 7; +pub const ARCHIVE_FILTER_RPM: u32 = 8; +pub const ARCHIVE_FILTER_LZIP: u32 = 9; +pub const ARCHIVE_FILTER_LRZIP: u32 = 10; +pub const ARCHIVE_FILTER_LZOP: u32 = 11; +pub const ARCHIVE_FILTER_GRZIP: u32 = 12; +pub const ARCHIVE_FILTER_LZ4: u32 = 13; +pub const ARCHIVE_FILTER_ZSTD: u32 = 14; + +// Extract flags +pub const ARCHIVE_EXTRACT_TIME: u32 = 0x0004; +pub const ARCHIVE_EXTRACT_PERM: u32 = 0x0002; +pub const ARCHIVE_EXTRACT_ACL: u32 = 0x0020; +pub const ARCHIVE_EXTRACT_FFLAGS: u32 = 0x0040; +pub const ARCHIVE_EXTRACT_SECURE_SYMLINKS: u32 = 0x0100; +pub const ARCHIVE_EXTRACT_SECURE_NODOTDOT: u32 = 0x0200; +pub const ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS: u32 = 0x10000; + +// File type constants (from POSIX stat) +pub const AE_IFREG: u32 = 0o100000; +pub const AE_IFDIR: u32 = 0o040000; +pub const AE_IFLNK: u32 = 0o120000; + +unsafe extern "C" { + // Reader + pub fn archive_read_new() -> *mut archive; + pub fn archive_read_free(a: *mut archive) -> c_int; + pub fn archive_read_support_format_all(a: *mut archive) -> c_int; + pub fn archive_read_support_format_raw(a: *mut archive) -> c_int; + pub fn archive_read_support_filter_all(a: *mut archive) -> c_int; + pub fn archive_read_open_filename(a: *mut archive, filename: *const c_char, block_size: usize) -> c_int; + pub fn archive_read_open_memory(a: *mut archive, buff: *const c_void, size: usize) -> c_int; + pub fn archive_read_next_header(a: *mut archive, entry: *mut *mut archive_entry) -> c_int; + pub fn archive_read_next_header2(a: *mut archive, entry: *mut archive_entry) -> c_int; + pub fn archive_read_data(a: *mut archive, buff: *mut c_void, size: usize) -> isize; + pub fn archive_read_data_block(a: *mut archive, buff: *mut *const c_void, size: *mut usize, offset: *mut i64) -> c_int; + + // Writer + pub fn archive_write_new() -> *mut archive; + pub fn archive_write_free(a: *mut archive) -> c_int; + pub fn archive_write_set_format(a: *mut archive, format_code: c_int) -> c_int; + pub fn archive_write_set_format_raw(a: *mut archive) -> c_int; + pub fn archive_write_set_format_pax_restricted(a: *mut archive) -> c_int; + pub fn archive_write_set_format_zip(a: *mut archive) -> c_int; + pub fn archive_write_set_format_7zip(a: *mut archive) -> c_int; + pub fn archive_write_set_format_ar_svr4(a: *mut archive) -> c_int; + pub fn archive_write_set_format_cpio_newc(a: *mut archive) -> c_int; + pub fn archive_write_add_filter(a: *mut archive, filter_code: c_int) -> c_int; + pub fn archive_write_add_filter_none(a: *mut archive) -> c_int; + pub fn archive_write_open_filename(a: *mut archive, filename: *const c_char) -> c_int; + pub fn archive_write_open_fd(a: *mut archive, fd: c_int) -> c_int; + pub fn archive_write_header(a: *mut archive, entry: *mut archive_entry) -> c_int; + pub fn archive_write_data(a: *mut archive, data: *const c_void, size: usize) -> isize; + pub fn archive_write_finish_entry(a: *mut archive) -> c_int; + pub fn archive_write_close(a: *mut archive) -> c_int; + + // Disk reader + pub fn archive_read_disk_new() -> *mut archive; + pub fn archive_read_disk_set_standard_lookup(a: *mut archive) -> c_int; + pub fn archive_read_disk_open(a: *mut archive, path: *const c_char) -> c_int; + pub fn archive_read_disk_descend(a: *mut archive) -> c_int; + + // Disk writer + pub fn archive_write_disk_new() -> *mut archive; + pub fn archive_write_disk_set_options(a: *mut archive, flags: c_int) -> c_int; + pub fn archive_write_disk_set_standard_lookup(a: *mut archive) -> c_int; + + // Entry + pub fn archive_entry_new() -> *mut archive_entry; + pub fn archive_entry_free(entry: *mut archive_entry); + pub fn archive_entry_clear(entry: *mut archive_entry) -> *mut archive_entry; + pub fn archive_entry_pathname(entry: *mut archive_entry) -> *const c_char; + pub fn archive_entry_pathname_utf8(entry: *mut archive_entry) -> *const c_char; + pub fn archive_entry_set_pathname_utf8(entry: *mut archive_entry, name: *const c_char); + pub fn archive_entry_size(entry: *mut archive_entry) -> i64; + pub fn archive_entry_set_size(entry: *mut archive_entry, size: i64); + pub fn archive_entry_filetype(entry: *mut archive_entry) -> c_int; + pub fn archive_entry_set_filetype(entry: *mut archive_entry, ftype: c_int); + pub fn archive_entry_perm(entry: *mut archive_entry) -> c_int; + pub fn archive_entry_set_perm(entry: *mut archive_entry, perm: c_int); + pub fn archive_entry_set_mtime(entry: *mut archive_entry, sec: i64, nsec: c_long); + pub fn archive_entry_set_atime(entry: *mut archive_entry, sec: i64, nsec: c_long); + pub fn archive_entry_set_ctime(entry: *mut archive_entry, sec: i64, nsec: c_long); + pub fn archive_entry_set_uid(entry: *mut archive_entry, uid: i64); + pub fn archive_entry_set_gid(entry: *mut archive_entry, gid: i64); + pub fn archive_entry_set_uname_utf8(entry: *mut archive_entry, name: *const c_char); + pub fn archive_entry_set_gname_utf8(entry: *mut archive_entry, name: *const c_char); + pub fn archive_entry_hardlink_utf8(entry: *mut archive_entry) -> *const c_char; + pub fn archive_entry_symlink_utf8(entry: *mut archive_entry) -> *const c_char; + + // Metadata + pub fn archive_format(a: *mut archive) -> c_int; + pub fn archive_filter_count(a: *mut archive) -> c_int; + pub fn archive_filter_code(a: *mut archive, index: c_int) -> c_int; + pub fn archive_filter_name(a: *mut archive, index: c_int) -> *const c_char; + pub fn archive_format_name(a: *mut archive) -> *const c_char; + pub fn archive_error_string(a: *mut archive) -> *const c_char; +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..48dab47 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,52 @@ +mod archive; +mod cli; +mod commands; +mod detect; +mod format; +mod libarchive_sys; + +use anyhow::Result; +use clap::Parser; + +use cli::{Cli, Command}; + +fn main() -> Result<()> { + let cli = Cli::parse(); + + match cli.command { + Command::Compress { + format, + output, + file, + } => commands::compress::run(format, output, file), + + Command::Decompress { output, file } => commands::decompress::run(output, file), + + Command::List { + output_format, + archive, + } => commands::list::run(output_format, archive), + + Command::Print { archive, path } => commands::print::run(archive, path), + + Command::Extract { + output_dir, + strip_components, + archive, + } => commands::extract::run(output_dir, strip_components, archive), + + Command::Create { + format, + compression, + strip_prefix, + non_det, + output, + files, + } => commands::create::run(format, compression, strip_prefix, non_det, output, files), + + Command::Detect { + output_format, + file, + } => commands::detect::run(output_format, file), + } +} diff --git a/support/compile-rust.nix b/support/compile-rust.nix new file mode 100644 index 0000000..d17f657 --- /dev/null +++ b/support/compile-rust.nix @@ -0,0 +1,68 @@ +{ pkgs +, zig +, ... +}: +{ target +, cargoLock +, src +, extraLibs +, ... +}: +let + importCargoLock = pkgs.rustPlatform.importCargoLock; + cargoSetupHook = pkgs.rustPlatform.cargoSetupHook; + stdenv = pkgs.stdenv; + + targetAsRust = { + amd64-linux = "x86_64-unknown-linux-musl"; + arm64-linux = "aarch64-unknown-linux-musl"; + }.${target}; + + rust-pkg = import ./rust.nix { inherit pkgs zig; system = "x86_64-linux"; }; + + libPaths = map (x: "${x}/lib") extraLibs; +in +stdenv.mkDerivation { + name = "yaar-${target}"; + + inherit src; + + cargoDeps = importCargoLock cargoLock; + + RUSTFLAGS = + "-C link-self-contained=no " + + builtins.concatStringsSep " " (map (p: "-L ${p}") libPaths); + + hardeningDisable = ["all"]; + + nativeBuildInputs = [ + cargoSetupHook + rust-pkg + zig + pkgs.glibc + ]; + + configurePhase = '' + runHook preConfigure + runHook postConfigure + ''; + + doCheck = false; + strictDeps = true; + + buildPhase = '' + runHook preBuild + + echo "RUSTFLAGS=$RUSTFLAGS" + echo cargo build --target ${targetAsRust} -j $NIX_BUILD_CORES --offline --release + cargo build --target ${targetAsRust} -j $NIX_BUILD_CORES --offline --release + + runHook postBuild + ''; + + installPhase = '' + cp target/${targetAsRust}/release/yaar "$out" + ''; + + dontFixup = true; +} diff --git a/support/lib-bzip2.nix b/support/lib-bzip2.nix new file mode 100644 index 0000000..eb0a3a7 --- /dev/null +++ b/support/lib-bzip2.nix @@ -0,0 +1,14 @@ +{ mkMuslLib, pkgs, zigCC, zigAR, zigRANLIB, ... }: +mkMuslLib { + pname = "bzip2-musl-static"; + src = pkgs.bzip2.src; + dontConfigure = true; + buildPhase = '' + make -j$NIX_BUILD_CORES CC="${zigCC}" AR="${zigAR}" RANLIB="${zigRANLIB}" libbz2.a + ''; + installPhase = '' + mkdir -p $out/lib $out/include + cp libbz2.a $out/lib/ + cp bzlib.h $out/include/ + ''; +} diff --git a/support/lib-libarchive.nix b/support/lib-libarchive.nix new file mode 100644 index 0000000..e75e2d4 --- /dev/null +++ b/support/lib-libarchive.nix @@ -0,0 +1,53 @@ +{ mkMuslLib, pkgs, zigCC, zigAR, zigRANLIB, autotoolsHost, ... }: +let + ctx = { inherit mkMuslLib pkgs zigCC zigAR zigRANLIB autotoolsHost; }; + zlib = import ./lib-zlib.nix ctx; + bzip2 = import ./lib-bzip2.nix ctx; + xz = import ./lib-xz.nix ctx; + lz4 = import ./lib-lz4.nix ctx; + zstd = import ./lib-zstd.nix ctx; + libxml2 = import ./lib-libxml2.nix ctx; +in +{ + libarchive = mkMuslLib { + pname = "libarchive-musl-static"; + src = pkgs.libarchive.src; + nativeBuildInputs = [ pkgs.cmake pkgs.pkg-config ]; + configurePhase = '' + cmake -B builddir \ + -DCMAKE_C_COMPILER="${zigCC}" \ + -DCMAKE_CXX_COMPILER="${zigCC}" \ + -DCMAKE_AR="${zigAR}" \ + -DCMAKE_RANLIB="${zigRANLIB}" \ + -DBUILD_SHARED_LIBS=OFF \ + -DENABLE_TEST=OFF \ + -DENABLE_TAR=OFF \ + -DENABLE_CPIO=OFF \ + -DENABLE_CAT=OFF \ + -DENABLE_UNZIP=OFF \ + -DENABLE_OPENSSL=OFF \ + -DENABLE_LIBB2=OFF \ + -DENABLE_ICONV=OFF \ + -DENABLE_EXPAT=OFF \ + -DENABLE_PCRE2POSIX=OFF \ + -DENABLE_PCREPOSIX=OFF \ + -DENABLE_LIBXML2=ON \ + -DENABLE_ZLIB=ON \ + -DENABLE_BZip2=ON \ + -DENABLE_LZMA=ON \ + -DENABLE_ZSTD=ON \ + -DENABLE_LZ4=ON \ + -DENABLE_ACL=OFF \ + -DENABLE_XATTR=OFF \ + -DCMAKE_PREFIX_PATH="${zlib};${bzip2};${xz};${lz4};${zstd};${libxml2}" \ + -DCMAKE_FIND_ROOT_PATH="${zlib};${bzip2};${xz};${lz4};${zstd};${libxml2}" \ + -DCMAKE_INSTALL_PREFIX=$out \ + -DCMAKE_INSTALL_LIBDIR=lib + ''; + buildPhase = "cmake --build builddir -j$NIX_BUILD_CORES"; + installPhase = "cmake --install builddir"; + }; + + # All libs needed for static linking (libarchive + its deps) + allLibs = [ zlib bzip2 xz lz4 zstd libxml2 ]; +} diff --git a/support/lib-libxml2.nix b/support/lib-libxml2.nix new file mode 100644 index 0000000..dd8be87 --- /dev/null +++ b/support/lib-libxml2.nix @@ -0,0 +1,28 @@ +{ mkMuslLib, pkgs, zigCC, zigAR, zigRANLIB, ... }: +mkMuslLib { + pname = "libxml2-musl-static"; + src = pkgs.libxml2.src; + nativeBuildInputs = [ pkgs.cmake pkgs.pkg-config ]; + configurePhase = '' + cmake -B builddir \ + -DCMAKE_C_COMPILER="${zigCC}" \ + -DCMAKE_CXX_COMPILER="${zigCC}" \ + -DCMAKE_AR="${zigAR}" \ + -DCMAKE_RANLIB="${zigRANLIB}" \ + -DBUILD_SHARED_LIBS=OFF \ + -DLIBXML2_WITH_PYTHON=OFF \ + -DLIBXML2_WITH_ICU=OFF \ + -DLIBXML2_WITH_LZMA=OFF \ + -DLIBXML2_WITH_ZLIB=OFF \ + -DLIBXML2_WITH_ICONV=OFF \ + -DLIBXML2_WITH_HTTP=OFF \ + -DLIBXML2_WITH_FTP=OFF \ + -DLIBXML2_WITH_THREADS=ON \ + -DLIBXML2_WITH_PROGRAMS=OFF \ + -DLIBXML2_WITH_TESTS=OFF \ + -DCMAKE_INSTALL_PREFIX=$out \ + -DCMAKE_INSTALL_LIBDIR=lib + ''; + buildPhase = "cmake --build builddir -j$NIX_BUILD_CORES"; + installPhase = "cmake --install builddir"; +} diff --git a/support/lib-lz4.nix b/support/lib-lz4.nix new file mode 100644 index 0000000..2f3235d --- /dev/null +++ b/support/lib-lz4.nix @@ -0,0 +1,21 @@ +{ mkMuslLib, pkgs, zigCC, zigAR, zigRANLIB, ... }: +mkMuslLib { + pname = "lz4-musl-static"; + src = pkgs.lz4.src; + nativeBuildInputs = [ pkgs.cmake ]; + configurePhase = '' + cmake -S build/cmake -B builddir \ + -DCMAKE_C_COMPILER="${zigCC}" \ + -DCMAKE_CXX_COMPILER="${zigCC}" \ + -DCMAKE_AR="${zigAR}" \ + -DCMAKE_RANLIB="${zigRANLIB}" \ + -DLZ4_BUILD_CLI=OFF \ + -DLZ4_BUILD_LEGACY_LZ4C=OFF \ + -DBUILD_SHARED_LIBS=OFF \ + -DBUILD_STATIC_LIBS=ON \ + -DCMAKE_INSTALL_PREFIX=$out \ + -DCMAKE_INSTALL_LIBDIR=lib + ''; + buildPhase = "cmake --build builddir -j$NIX_BUILD_CORES"; + installPhase = "cmake --install builddir"; +} diff --git a/support/lib-xz.nix b/support/lib-xz.nix new file mode 100644 index 0000000..7067887 --- /dev/null +++ b/support/lib-xz.nix @@ -0,0 +1,15 @@ +{ mkMuslLib, pkgs, autotoolsHost, ... }: +mkMuslLib { + pname = "xz-musl-static"; + src = pkgs.xz.src; + nativeBuildInputs = [ pkgs.updateAutotoolsGnuConfigScriptsHook ]; + configurePhase = '' + ./configure --host=${autotoolsHost} \ + --disable-shared --enable-static \ + --disable-xz --disable-xzdec --disable-lzmadec --disable-lzmainfo \ + --disable-scripts --disable-doc --disable-nls \ + --prefix=$out + ''; + buildPhase = "make -j$NIX_BUILD_CORES"; + installPhase = "make install"; +} diff --git a/support/lib-zlib.nix b/support/lib-zlib.nix new file mode 100644 index 0000000..85e1a06 --- /dev/null +++ b/support/lib-zlib.nix @@ -0,0 +1,10 @@ +{ mkMuslLib, pkgs, ... }: +mkMuslLib { + pname = "zlib-musl-static"; + src = pkgs.zlib.src; + configurePhase = '' + ./configure --static --prefix=$out + ''; + buildPhase = "make -j$NIX_BUILD_CORES"; + installPhase = "make install"; +} diff --git a/support/lib-zstd.nix b/support/lib-zstd.nix new file mode 100644 index 0000000..9b2259f --- /dev/null +++ b/support/lib-zstd.nix @@ -0,0 +1,20 @@ +{ mkMuslLib, pkgs, zigCC, zigAR, zigRANLIB, ... }: +mkMuslLib { + pname = "zstd-musl-static"; + src = pkgs.zstd.src; + nativeBuildInputs = [ pkgs.cmake ]; + configurePhase = '' + cmake -S build/cmake -B builddir \ + -DCMAKE_C_COMPILER="${zigCC}" \ + -DCMAKE_CXX_COMPILER="${zigCC}" \ + -DCMAKE_AR="${zigAR}" \ + -DCMAKE_RANLIB="${zigRANLIB}" \ + -DZSTD_BUILD_PROGRAMS=OFF \ + -DZSTD_BUILD_SHARED=OFF \ + -DZSTD_BUILD_STATIC=ON \ + -DCMAKE_INSTALL_PREFIX=$out \ + -DCMAKE_INSTALL_LIBDIR=lib + ''; + buildPhase = "cmake --build builddir -j$NIX_BUILD_CORES"; + installPhase = "cmake --install builddir"; +} diff --git a/support/musl-libs.nix b/support/musl-libs.nix new file mode 100644 index 0000000..6da0b3a --- /dev/null +++ b/support/musl-libs.nix @@ -0,0 +1,30 @@ +{ pkgs, zig, name-target }: +let + zigCC = "${zig}/bin/zig-cc-${name-target}"; + zigAR = "${zig}/bin/zig-ar"; + zigRANLIB = "${zig}/bin/zig-ranlib"; + + autotoolsHost = { + "amd64-linux" = "x86_64-linux-musl"; + "arm64-linux" = "aarch64-linux-musl"; + }.${name-target}; + + mkMuslLib = args: pkgs.stdenvNoCC.mkDerivation ({ + nativeBuildInputs = [ zig pkgs.gnumake pkgs.binutils ] ++ (args.nativeBuildInputs or []); + dontFixup = true; + CC = zigCC; + AR = zigAR; + RANLIB = zigRANLIB; + } // builtins.removeAttrs args [ "nativeBuildInputs" ] // { + name = "${args.pname}-${name-target}"; + }); + + ctx = { + inherit pkgs zigCC zigAR zigRANLIB autotoolsHost mkMuslLib; + }; + + libarchiveResult = import ./lib-libarchive.nix ctx; +in { + inherit (libarchiveResult) libarchive; + allLibs = [ libarchiveResult.libarchive ] ++ libarchiveResult.allLibs; +} diff --git a/support/rust.nix b/support/rust.nix new file mode 100644 index 0000000..255d44f --- /dev/null +++ b/support/rust.nix @@ -0,0 +1,100 @@ +{ pkgs +, system ? "x86_64-linux" +, zig +, ... +}: +let + systemAsRust = { + x86_64-linux = "x86_64-unknown-linux-gnu"; + aarch64-linux = "aarch64-unknown-linux-gnu"; + }.${system}; + + manifest-src = builtins.fetchurl { + url = "https://static.rust-lang.org/dist/2025-05-15/channel-rust-stable.toml"; + sha256 = "0594aavj08dw7ba9wndbjg31crkpqz7wcbzzfmgc9yg3j7mbaj99"; + }; + + manifest = builtins.fromTOML (builtins.readFile manifest-src); + + simpleComponent = x: builtins.fetchurl { + url = x.url; + sha256 = x.hash; + }; + + components = [ + (simpleComponent manifest.pkg.cargo.target.${systemAsRust}) + (simpleComponent manifest.pkg.rustc.target.${systemAsRust}) + (simpleComponent manifest.pkg.rust-std.target.${systemAsRust}) + (simpleComponent manifest.pkg.rust-std.target.x86_64-unknown-linux-musl) + (simpleComponent manifest.pkg.rust-std.target.aarch64-unknown-linux-musl) + ]; +in pkgs.stdenvNoCC.mkDerivation rec { + name = "yaar-rust"; + + srcs = components; + sourceRoot = "."; + + dontConfigure = true; + dontBuild = true; + + nativeBuildInputs = [ pkgs.makeWrapper ]; + + buildInputs = [ + pkgs.glibc + pkgs.zlib + pkgs.bash + pkgs.gcc.cc.lib + zig + ]; + + dontAutoPatchelf = true; + + fixupPhase = '' + SEARCH_DIRS="$out/bin" + if [[ "${system}" == "x86_64-linux" ]] + then + SEARCH_DIRS="$SEARCH_DIRS $out/lib/rustlib/x86_64-unknown-linux-gnu/bin" + fi + if [[ "${system}" == "aarch64-linux" ]] + then + SEARCH_DIRS="$SEARCH_DIRS $out/lib/rustlib/aarch64-unknown-linux-gnu/bin" + fi + find $SEARCH_DIRS -type f -executable | while read binary; do + if file "$binary" | grep -q "ELF" + then + echo "Patching $binary" + patchelf \ + --set-interpreter ${pkgs.glibc}/lib/ld-linux-x86-64.so.2 \ + --set-rpath "${pkgs.lib.makeLibraryPath buildInputs}:"'$ORIGIN/../lib' \ + "$binary" + fi + done + + find $out/lib -type f -maxdepth 1 | while read binary; do + if file "$binary" | grep -q "ELF" + then + echo "Patching $binary" + patchelf \ + --set-rpath "${pkgs.lib.makeLibraryPath buildInputs}:"'$ORIGIN/../lib' \ + "$binary" + fi + done + + runHook postInstall + ''; + + installPhase = '' + mkdir -p $out + for i in $(find . -type d -maxdepth 2 -mindepth 1) ; + do + cp -r "$i/." $out/. + done + + wrapProgram $out/bin/cargo \ + --set CC_x86_64_unknown_linux_musl zig-cc-amd64-linux \ + --set CC_aarch64_unknown_linux_musl zig-cc-arm64-linux \ + --set CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_LINKER zig-cc-amd64-linux \ + --set CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER zig-cc-arm64-linux \ + --prefix LD_LIBRARY_PATH : "${pkgs.lib.makeLibraryPath buildInputs}" + ''; +} diff --git a/support/zig.nix b/support/zig.nix new file mode 100644 index 0000000..cbc06f0 --- /dev/null +++ b/support/zig.nix @@ -0,0 +1,80 @@ +{ pkgs +, system ? "x86_64-linux" +, ... +}: +let + zig = { + x86_64-linux = builtins.fetchTarball { + url = "https://ziglang.org/download/0.15.1/zig-x86_64-linux-0.15.1.tar.xz"; + sha256 = "0yar24a1qjg503czwnkdipky1cfb08k0mm9c8gwv827d33df1070"; + }; + aarch64-linux = builtins.fetchTarball { + url = "https://ziglang.org/download/0.15.1/zig-aarch64-linux-0.15.1.tar.xz"; + sha256 = "19vcv7a1scm4wpj5cgv3dmzajz37fdyx5x1inxfgxzsavbmvq3zy"; + }; + }.${system}; + + make-cc-wrapper = trg: pkgs.writeShellScript "zig-cc-${trg}" '' + if [ ! -d "$HOME" ]; then + export ZIG_GLOBAL_CACHE_DIR=/build/.zig-cache + export ZIG_LOCAL_CACHE_DIR=/build/.zig-cache-local + fi + args=() + for arg in "$@"; do + if [[ "$skip_next" == true ]]; then + skip_next=false + continue + fi + if [[ "$arg" != --target=* ]] && \ + [[ "$arg" != -framework ]] && \ + [[ "$arg" != CoreFoundation ]] && \ + [[ "$arg" != Foundation ]] && \ + [[ "$arg" != *CoreFoundation* ]] && \ + [[ "$arg" != *Foundation* ]] && \ + [[ "$arg" != -F ]] && \ + [[ "$arg" != -F* ]]; then + args+=("$arg") + elif [[ "$arg" == -framework ]] || [[ "$arg" == -F ]]; then + skip_next=true + fi + done + + exec "${zig}/zig" cc -fdebug-prefix-map=${toString zig}=/zig -target ${trg} "''${args[@]}" + ''; + + make-ar-wrapper = pkgs.writeShellScript "zig-ar" '' + if [ ! -d "$HOME" ]; then + export ZIG_GLOBAL_CACHE_DIR=/build/.zig-cache + export ZIG_LOCAL_CACHE_DIR=/build/.zig-cache-local + fi + exec "${zig}/zig" ar "$@" + ''; + + make-ranlib-wrapper = pkgs.writeShellScript "zig-ranlib" '' + if [ ! -d "$HOME" ]; then + export ZIG_GLOBAL_CACHE_DIR=/build/.zig-cache + export ZIG_LOCAL_CACHE_DIR=/build/.zig-cache-local + fi + exec "${zig}/zig" ranlib "$@" + ''; +in +pkgs.stdenvNoCC.mkDerivation { + name = "yaar-zig"; + + src = zig; + + nativeBuildInputs = [ pkgs.coreutils ]; + + dontConfigure = true; + + dontBuild = true; + + installPhase = '' + mkdir -p "$out/bin" + cp -r "./." "$out" + cp ${make-cc-wrapper "x86_64-linux-musl"} "$out/bin/zig-cc-amd64-linux" + cp ${make-cc-wrapper "aarch64-linux-musl"} "$out/bin/zig-cc-arm64-linux" + cp ${make-ar-wrapper} "$out/bin/zig-ar" + cp ${make-ranlib-wrapper} "$out/bin/zig-ranlib" + ''; +}