pax_global_header00006660000000000000000000000064152103565630014520gustar00rootroot0000000000000052 comment=bbbfe4df13055bf30a2a46555ccedb8a9049af22 seedfiles/000077500000000000000000000000001521035656300130275ustar00rootroot00000000000000seedfiles/.gitignore000066400000000000000000000000171521035656300150150ustar00rootroot00000000000000*~ .*~ .clangd seedfiles/COPYING000066400000000000000000001045201521035656300140640ustar00rootroot00000000000000 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 . seedfiles/README.md000066400000000000000000000025641521035656300143150ustar00rootroot00000000000000# seedfiles A portable drop-in reimplementation of systemd-tmpfiles. Implements pretty much all of systemd-tmpfiles, searches the same config paths and allows for per-user configs. ## Diferences to systemd-tmpfiles Following features are *not* implemented in seedfiles, but exist in systemd-tmpfiles. If any feature is needed but not implemented, feel free to open an issue or send a patch! ### Item types: - `e` - Adjusting permissions on existing directory ### Modifiers: - `^` - reading arguments from systemd-credentials - `$` - entries for `--purge` - `?` - skip symlink creation if target doesn't exist ### CLI Flags: - `--purge` - Delete everything that would have been created - `--cat-config` - Print all resolved config files - `--tldr` - Same as `--cat-config` but without comments - `--graceful` - Silently ignoring users/groups - ` -E` - Exclude `/dev`, `/proc`, `/run` and `/sys` prefixes - `--image` - Operate on a disk image - `--image-policy` - Disk image policy - `--replace` - Replace specific config files - `--inline` - Passing rules as arguments instead of stdin. Just use stdin. ### Missing Features/Subsystems - SELinux - No label management, z/Zonly do chmod/chown - age-by - Timestamp in age column is ignored, only mtime is checked by cleanup - credentials - No systemd-credentials support - BTRFS - v/q/Q fall back to mkdir, don't act on subvolumes/quotas seedfiles/meson.build000066400000000000000000000042041521035656300151710ustar00rootroot00000000000000project('seedfiles', 'c', version : '1.4.2', license : 'GPL-3.0-or-later', default_options : [ 'c_std=gnu11', 'warning_level=2', 'b_ndebug=if-release', ], ) cc = meson.get_compiler('c') dep_acl = cc.find_library('acl', required : true) add_project_arguments( '-D_GNU_SOURCE', language : 'c', ) conf = configuration_data() conf.set10('HAVE_O_PATH', cc.has_header_symbol('fcntl.h', 'O_PATH', args : ['-D_GNU_SOURCE'])) configure_file( output : 'config.h', configuration : conf, ) add_project_arguments('-include', 'config.h', language : 'c') inc = include_directories('src') lib_src = files( 'src/util.c', 'src/hashmap.c', 'src/specifier.c', 'src/parse.c', 'src/perms.c', 'src/create.c', 'src/clean.c', 'src/execute.c', 'src/glob_portable.c', 'src/offline-password.c' ) if host_machine.system() == 'linux' lib_src += files('src/platform/linux.c') lib_src += files('src/platform/linux_chase.c') else lib_src += files('src/platform/posix.c') lib_src += files('src/platform/posix_chase.c') endif executable( 'seedfiles', lib_src, 'src/main.c', dependencies : [dep_acl], include_directories : inc, install : true, install_dir : get_option('bindir'), ) foreach t : [ 'test-util', 'test-hashmap', 'test-parse', ] exe = executable( t, 'test' / t + '.c', lib_src, dependencies : [dep_acl], include_directories : inc, install : false, ) test(t, exe, timeout : 30) endforeach seedfiles_exe = executable( 'seedfiles-for-test', lib_src, 'src/main.c', dependencies : [dep_acl], include_directories : inc, install : false, ) foreach t : [ 'test-help-version', 'test-create', 'test-remove', 'test-force-replace', 'test-prefix', 'test-combo-idempotent', 'test-escape', 'test-copy', 'test-mode', 'test-write', 'test-stdin', 'test-root', 'test-misc', ] test(t, find_program('test/integration' / t + '.sh'), args : [seedfiles_exe], timeout : 60, protocol : 'tap', ) endforeach install_man( 'seedfiles.8', install_dir : get_option('mandir') /'man8', ) if get_option('default_configs').enabled() subdir('tmpfiles.d') endif seedfiles/meson_options.txt000066400000000000000000000001671521035656300164700ustar00rootroot00000000000000option('default_configs', type : 'feature', value : 'enabled', description : 'Install default tmpfile configs') seedfiles/seedfiles.8000066400000000000000000000051151521035656300150650ustar00rootroot00000000000000.TH SEEDFILES "8" "May 2026" "seedfiles 1.4.2" "User Commands" .SH "NAME" seedfiles \- manage temporary files and directories .SH SYNOPSIS .B seedfiles [\fI\,OPTIONS\/\fR...] [\fI\,CONFIG_FILE\/\fR...] .SH DESCRIPTION seedfiles provides a drop-in replacement for systemd-tmpfiles. .PP If \fICONFIG_FILE\fR arguments are given, they specify the configuration files to process. An argument containing a slash (e.g. \fI/etc/foo.conf\fR or \fI./foo.conf\fR) is treated as a direct path. Otherwise, the argument is interpreted as a bare configuration file name and looked up in the configured tmpfiles.d directories in order (the same set used when no arguments are given, depending on \fB\-\-user\fR). The full filename including any \fI.conf\fR suffix must be specified. If a bare name cannot be resolved in any configuration directory, seedfiles exits with an error. .SS "Commands:" .TP \fB\-\-create\fR Create files and directories .TP \fB\-\-clean\fR Clean up old files .TP \fB\-\-remove\fR Remove files and directories .SH OPTIONS .TP \fB\-\-boot\fR Also process entries with the '!' modifier .TP \fB\-\-dry\-run\fR Only print what would be done .TP \fB\-\-prefix\fR=\fI\,PATH\/\fR Only process entries with matching prefix .TP \fB\-\-exclude\-prefix\fR=\fI\,PATH\/\fR Exclude entries with matching prefix .TP \fB\-\-user\fR Run in user mode .TP \fB\-\-root\fR=\fI\,PATH\/\fR All paths, including configuration directories, are interpreted relative to \fIPATH\/\fR. User and group names are resolved from \fIPATH\/\fR\fB/etc/passwd\fR and \fIPATH\/\fR\fB/etc/group\fR instead of the host NSS database. The \fB%m\fR specifier reads \fIPATH\/\fR\fB/etc/machine-id\fR. Symlinks whose targets would escape \fIPATH\/\fR are refused. Mutually exclusive with \fB\-\-user\fR. .TP \fB\-\-verbose\fR Enable verbose logging .TP \fB\-h\fR, \fB\-\-help\fR Show this help .TP \fB\-\-version\fR Show version .SH MISSING FEATURES .TP This sections details the main differences to systemd-tmpfiles .TP .SS SELinux No label management, \-z/\-Zonly do chmod/chown .TP .SS age-by Timestamp in age column is ignored, only mtime is checked by cleanup .TP .SS credentials No systemd-credentials support .TP .SS BTRFS \-v/\-q/\-Q fall back to mkdir, don't act on subvolumes/quotas .SH "Copyright" Copyright \[co] 2026 Matthias Geiger . .PP This manual page was written for the Debian system (and may be used by others). .PP Permission is granted to copy, distribute and/or modify this document under the terms of the GNU General Public License, Version 3 or (at your option) any later version published by the Free Software Foundation. seedfiles/src/000077500000000000000000000000001521035656300136165ustar00rootroot00000000000000seedfiles/src/chase.h000066400000000000000000000015401521035656300150520ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include /* Symlink-safe path resolution against an alternate filesystem root. * * chase() walks `path` component by component, refusing to follow symlinks * whose targets would escape `root`. Returned paths are host-absolute */ typedef enum { CHASE_PREFIX_ROOT = 1 << 0, CHASE_NONEXISTENT = 1 << 1, CHASE_NOFOLLOW = 1 << 2, CHASE_WARN = 1 << 3, } ChaseFlags; #define CHASE_MAX 128U int chase(const char *path, const char *root, ChaseFlags flags, char **ret_path, int *ret_fd); int chase_full(const char *path, const char *root, ChaseFlags flags, char **ret_path, int *ret_fd, int *ret_parent_fd, char **ret_basename); int chase_and_open(const char *path, const char *root, ChaseFlags flags, int open_flags, char **ret_path); seedfiles/src/clean.c000066400000000000000000000310341521035656300150450ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #ifdef __linux__ #include #endif #include "clean.h" #include "perms.h" #include "glob_portable.h" #include "chase.h" #define MAX_DEPTH 256 static char **live_sockets = NULL; static size_t n_live_sockets = 0; static bool sockets_loaded = false; static void load_unix_sockets(void) { if (sockets_loaded) return; sockets_loaded = true; _cleanup_fclose_ FILE *f = fopen("/proc/net/unix", "re"); if (!f) { log_debug("Cannot open /proc/net/unix: %s", strerror(errno)); return; } char line[4096]; if (!fgets(line, sizeof(line), f)) return; while (fgets(line, sizeof(line), f)) { char *p = strchr(line, ':'); if (!p) continue; p++; for (int i = 0; i < 6; i++) { while (*p == ' ') p++; while (*p && *p != ' ' && *p != '\n') p++; } while (*p == ' ') p++; size_t len = strlen(p); while (len > 0 && (p[len - 1] == '\n' || p[len - 1] == '\r')) len--; if (len == 0 || p[0] != '/') continue; live_sockets = realloc(live_sockets, sizeof(char *) * (n_live_sockets + 1)); if (!live_sockets) abort(); live_sockets[n_live_sockets++] = xstrndup(p, len); } } bool unix_socket_alive(const char *path) { load_unix_sockets(); for (size_t i = 0; i < n_live_sockets; i++) { if (streq(live_sockets[i], path)) return true; } return false; } static bool find_glob_match(Context *c, const char *path) { const char *key; void *v; ORDERED_HASHMAP_FOREACH(key, v, c->globs) { ItemArray *a = v; for (size_t j = 0; j < a->n_items; j++) { if (fnmatch(a->items[j].path, path, FNM_PATHNAME | FNM_PERIOD) == 0) return true; } } return false; } static bool needs_cleanup(uint64_t mtime_usec, uint64_t cutoff_usec) { if (cutoff_usec == 0) return true; if (mtime_usec == 0) return true; return mtime_usec < cutoff_usec; } static uint64_t timespec_to_usec(struct timespec ts) { return (uint64_t)ts.tv_sec * USEC_PER_SEC + (uint64_t)ts.tv_nsec / 1000; } int dir_cleanup(Context *c, const char *path, DIR *d, uint64_t self_mtime_usec, uint64_t cutoff_usec, dev_t rootdev, bool keep_first_level, int maxdepth) { int r = 0; bool deleted = false; struct timespec original_mtime = {0, 0}; struct stat dir_st; if (fstat(dirfd(d), &dir_st) == 0) original_mtime = dir_st.st_mtim; struct dirent *de; while ((de = readdir(d))) { if (streq(de->d_name, ".") || streq(de->d_name, "..")) continue; struct stat st; if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) { if (errno == ENOENT) continue; log_warning("fstatat(%s/%s) failed: %s", path, de->d_name, strerror(errno)); r = r ?: -errno; continue; } #ifdef __linux__ if (st.st_dev != rootdev) { log_debug("Ignoring \"%s/%s\": different mount point.", path, de->d_name); continue; } #endif _cleanup_free_ char *sub_path = path_join(path, de->d_name); if (!sub_path) { r = r ?: -ENOMEM; continue; } if (ordered_hashmap_get(c->items, sub_path)) { log_debug("Ignoring \"%s\": has its own seedfiles entry.", sub_path); continue; } if (find_glob_match(c, sub_path)) { log_debug("Ignoring \"%s\": matched by a glob entry.", sub_path); continue; } uint64_t mtime_usec = timespec_to_usec(st.st_mtim); if (S_ISDIR(st.st_mode)) { if (st.st_uid == 0 && streq(de->d_name, "lost+found")) { log_debug("Ignoring \"%s\": root-owned lost+found.", sub_path); continue; } if (maxdepth > 0) { int sub_fd = openat(dirfd(d), de->d_name, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_RDONLY); if (sub_fd < 0) { if (errno == ENOENT) continue; log_warning("Cannot open \"%s\": %s", sub_path, strerror(errno)); r = r ?: -errno; continue; } if (!arg_dry_run && flock(sub_fd, LOCK_EX | LOCK_NB) < 0) { log_debug("Cannot lock \"%s\", skipping.", sub_path); close(sub_fd); continue; } DIR *sub_dir = xfdopendir(sub_fd); if (!sub_dir) { close(sub_fd); continue; } int q = dir_cleanup(c, sub_path, sub_dir, mtime_usec, cutoff_usec, rootdev, false, maxdepth - 1); closedir(sub_dir); r = r ?: q; } if (keep_first_level) { log_debug("Keeping \"%s\" (keep_first_level).", sub_path); continue; } if (!needs_cleanup(mtime_usec, cutoff_usec)) continue; if (arg_dry_run) { log_info("Would remove directory \"%s\".", sub_path); continue; } log_debug("Removing directory \"%s\".", sub_path); if (unlinkat(dirfd(d), de->d_name, AT_REMOVEDIR) < 0) { if (errno != ENOENT && errno != ENOTEMPTY) log_warning("Failed to remove \"%s\": %s", sub_path, strerror(errno)); } else { deleted = true; } } else { if (st.st_mode & S_ISVTX) { log_debug("Keeping \"%s\": has sticky bit.", sub_path); continue; } if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) { log_debug("Skipping device node \"%s\".", sub_path); continue; } if (S_ISSOCK(st.st_mode) && unix_socket_alive(sub_path)) { log_debug("Skipping live unix socket \"%s\".", sub_path); continue; } if (keep_first_level) { log_debug("Keeping \"%s\" (keep_first_level).", sub_path); continue; } if (!needs_cleanup(mtime_usec, cutoff_usec)) continue; if (!arg_dry_run) { int file_fd = openat(dirfd(d), de->d_name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK); if (file_fd >= 0) { if (flock(file_fd, LOCK_EX | LOCK_NB) < 0) { log_debug("Cannot lock \"%s\", skipping.", sub_path); close(file_fd); continue; } log_debug("Removing \"%s\".", sub_path); if (unlinkat(dirfd(d), de->d_name, 0) < 0) { if (errno != ENOENT) log_warning("Failed to remove \"%s\": %s", sub_path, strerror(errno)); } else { deleted = true; } close(file_fd); continue; } if (errno != ENOENT && errno != ELOOP) log_debug("Cannot open \"%s\" for locking: %s", sub_path, strerror(errno)); } if (arg_dry_run) { log_info("Would remove \"%s\".", sub_path); continue; } log_debug("Removing \"%s\".", sub_path); if (unlinkat(dirfd(d), de->d_name, 0) < 0) { if (errno != ENOENT) log_warning("Failed to remove \"%s\": %s", sub_path, strerror(errno)); } else { deleted = true; } } } if (deleted && self_mtime_usec != USEC_INFINITY) { struct timespec ts[2]; ts[0] = original_mtime; ts[1] = original_mtime; futimens(dirfd(d), ts); } return r; } struct glob_item_ctx { Context *c; Item *item; int (*func)(Context *, Item *, const char *); }; static int glob_item_trampoline(const char *logical_path, void *userdata) { struct glob_item_ctx *ctx = userdata; return ctx->func(ctx->c, ctx->item, logical_path); } static int glob_item(Context *c, Item *i, int (*func)(Context *, Item *, const char *)) { struct glob_item_ctx ctx = { .c = c, .item = i, .func = func }; return glob_in_root(i->path, arg_root, glob_item_trampoline, &ctx); } static int clean_item_instance(Context *c, Item *i, const char *instance) { if (!i->age_set) return 0; uint64_t now = now_usec(); if (now < i->age) return 0; uint64_t cutoff = now - i->age; _cleanup_close_ int fd = chase_and_open(instance, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_DIRECTORY | O_CLOEXEC | O_RDONLY, NULL); if (fd < 0) { if (fd == -ENOENT || fd == -ENOTDIR) return 0; return log_error_errno(fd, "Failed to open '%s': %s", instance, strerror(-fd)); } struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", instance, strerror(errno)); DIR *d = xfdopendir(fd); if (!d) return -errno; fd = -1; uint64_t mtime = timespec_to_usec(st.st_mtim); int r = dir_cleanup(c, instance, d, mtime, cutoff, st.st_dev, i->keep_first_level, MAX_DEPTH); closedir(d); return r; } static int remove_item_instance(Context *c, Item *i, const char *instance) { (void)c; if (arg_dry_run) { log_info("Would remove '%s'.", instance); return 0; } switch (i->type) { case REMOVE_PATH: { _cleanup_free_ char *resolved = NULL; int cr = chase(instance, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW | CHASE_NONEXISTENT, &resolved, NULL); if (cr == -ENOENT) return 0; if (cr < 0) return log_error_errno(cr, "Failed to resolve '%s': %s", instance, strerror(-cr)); if (remove(resolved) < 0 && errno != ENOENT) return log_error_errno(-errno, "Failed to remove '%s': %s", instance, strerror(errno)); return 0; } case RECURSIVE_REMOVE_PATH: { _cleanup_free_ char *resolved = NULL; int cr = chase(instance, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW | CHASE_NONEXISTENT, &resolved, NULL); if (cr == -ENOENT) return 0; if (cr < 0) return log_error_errno(cr, "Failed to resolve '%s': %s", instance, strerror(-cr)); _cleanup_close_ int fd = open(resolved, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_RDONLY); if (fd < 0) { if (errno == ENOENT) return 0; if (errno == ENOTDIR) { if (remove(resolved) < 0 && errno != ENOENT) return log_error_errno(-errno, "Failed to remove '%s': %s", instance, strerror(errno)); return 0; } return log_error_errno(-errno, "Failed to open '%s': %s", instance, strerror(errno)); } struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", instance, strerror(errno)); DIR *d = xfdopendir(fd); if (!d) return -errno; fd = -1; int r = dir_cleanup(c, instance, d, USEC_INFINITY, 0, st.st_dev, false, MAX_DEPTH); closedir(d); if (rmdir(resolved) < 0 && errno != ENOENT && errno != ENOTEMPTY) log_warning("Failed to rmdir '%s': %s", instance, strerror(errno)); return r; } default: return 0; } } int clean_item(Context *c, Item *i) { switch (i->type) { case CREATE_DIRECTORY: case TRUNCATE_DIRECTORY: case CREATE_SUBVOLUME: case CREATE_SUBVOLUME_INHERIT_QUOTA: case CREATE_SUBVOLUME_NEW_QUOTA: case COPY_FILES: return clean_item_instance(c, i, i->path); case IGNORE_PATH: case IGNORE_DIRECTORY_PATH: return glob_item(c, i, clean_item_instance); default: return 0; } } int remove_item(Context *c, Item *i) { switch (i->type) { case TRUNCATE_DIRECTORY: if (arg_dry_run) { log_info("Would empty directory '%s'.", i->path); return 0; } { _cleanup_close_ int fd = chase_and_open(i->path, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_DIRECTORY | O_CLOEXEC | O_RDONLY, NULL); if (fd < 0) { if (fd == -ENOENT || fd == -ENOTDIR) return 0; return log_error_errno(fd, "Failed to open '%s': %s", i->path, strerror(-fd)); } struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", i->path, strerror(errno)); DIR *d = xfdopendir(fd); if (!d) return -errno; fd = -1; int r = dir_cleanup(c, i->path, d, USEC_INFINITY, 0, st.st_dev, false, MAX_DEPTH); closedir(d); return r; } case REMOVE_PATH: case RECURSIVE_REMOVE_PATH: return glob_item(c, i, remove_item_instance); default: return 0; } } seedfiles/src/clean.h000066400000000000000000000006001521035656300150450ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include "parse.h" int dir_cleanup(Context *c, const char *path, DIR *d, uint64_t self_mtime_usec, uint64_t cutoff_usec, dev_t rootdev, bool keep_first_level, int maxdepth); bool unix_socket_alive(const char *path); int clean_item(Context *c, Item *i); int remove_item(Context *c, Item *i); seedfiles/src/create.c000066400000000000000000000714071521035656300152360ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include "create.h" #include "chase.h" static int mkdir_parents_host(const char *path, mode_t mode) { _cleanup_free_ char *parent = path_parent(path); if (!parent || streq(parent, "/")) return 0; int r = mkdir_parents_host(parent, mode); if (r < 0) return r; if (mkdir(parent, mode) < 0 && errno != EEXIST) return -errno; return 0; } int mkdir_parents(const char *path, mode_t mode) { _cleanup_free_ char *parent = path_parent(path); if (!parent || streq(parent, "/")) return 0; _cleanup_free_ char *parent_host = NULL; int r = chase(parent, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &parent_host, NULL); if (r < 0) return r; r = mkdir_parents_host(parent_host, mode); if (r < 0) return r; if (mkdir(parent_host, mode) < 0 && errno != EEXIST) return -errno; return 0; } static int open_parent_safe(const char *path, const char **ret_bn) { _cleanup_free_ char *parent = path_parent(path); if (!parent) return -EINVAL; const char *bn = path_basename(path); if (!bn || streq(bn, "/") || streq(bn, "")) return -EINVAL; int fd = chase_and_open(parent, arg_root, CHASE_PREFIX_ROOT, O_DIRECTORY | O_CLOEXEC | O_PATH, NULL); if (fd < 0) return fd; *ret_bn = bn; return fd; } /* from ascii offset to base64 value */ static const unsigned char b64_decoding_table[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static int write_argument_data(Item *i, int fd, const char *path) { if (!i->argument || i->argument[0] == '\0') return 0; size_t len = strlen(i->argument); if (len == 0) return 0; if (i->base64) { if (len < 4) return log_error_errno(-EINVAL, "base64 encoded string must at least be 4 chars long"); if (len % 4 != 0) return log_error_errno(-EINVAL, "Length of base64 encoded string must a multiple of 4"); // Check for validity by iterating through the characters until the first // invalid char is found that char must either be NULL or "=" and the diff // to the start must be len or otherwise the invalid char was found before // the string ended. char *end = i->argument; while (*end == '+' || *end == '/' || ('0' <= *end && *end <= '9') || ('A' <= *end && *end <= 'Z') || ('a' <= *end && *end <= 'z')) { end++; } // strip off one or two trailing equal signs if (end - i->argument == len - 1 && *end == '=') { len -= 1; *end = '\0'; } else if (end - i->argument == len - 2 && *end == '=') { len -= 2; *end = '\0'; } if (end - i->argument != len || *end != '\0') return log_error_errno(-EINVAL, "Invalid base64 encoded string: %s", i->argument); unsigned char bufout[3]; char *p = i->argument; while (p < end - 4) { bufout[0] = b64_decoding_table[p[0]] << 2 | b64_decoding_table[p[1]] >> 4; bufout[1] = b64_decoding_table[p[1]] << 4 | b64_decoding_table[p[2]] >> 2; bufout[2] = b64_decoding_table[p[2]] << 6 | b64_decoding_table[p[3]]; ssize_t n = write(fd, bufout, 3); if (n != 3) { if (errno == EINTR) continue; return log_error_errno(-errno, "Failed to write to '%s': %s", path, strerror(errno)); } p += 4; } size_t remaining = end - p; switch (remaining) { case 4: bufout[2] = b64_decoding_table[p[2]] << 6 | b64_decoding_table[p[3]]; case 3: bufout[1] = b64_decoding_table[p[1]] << 4 | b64_decoding_table[p[2]] >> 2; case 2: bufout[0] = b64_decoding_table[p[0]] << 2 | b64_decoding_table[p[1]] >> 4; break; default: /* at least two bytes must be remaining */ return -EINVAL; } ssize_t n = write(fd, bufout, remaining - 1); if (n != remaining - 1) { return log_error_errno(-errno, "Failed to write to '%s': %s", path, strerror(errno)); } return 0; } size_t written = 0; while (written < len) { ssize_t n = write(fd, i->argument + written, len - written); if (n < 0) { if (errno == EINTR) continue; return log_error_errno(-errno, "Failed to write to '%s': %s", path, strerror(errno)); } written += (size_t)n; } return 0; } static int create_file(Item *i) { const char *bn; _cleanup_close_ int pfd = open_parent_safe(i->path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", i->path, strerror(-pfd)); CreationMode creation; _cleanup_close_ int fd = openat( pfd, bn, O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC | O_WRONLY | O_NOCTTY, i->mode_set ? i->mode : 0644); if (fd < 0) { if (errno != EEXIST) return log_error_errno(-errno, "Failed to create file '%s': %s", i->path, strerror(errno)); fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (fd < 0) return log_error_errno(-errno, "Failed to open '%s': %s", i->path, strerror(errno)); struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", i->path, strerror(errno)); if (!S_ISREG(st.st_mode)) { log_debug("'%s' already exists and is not a regular file.", i->path); return 0; } creation = CREATION_EXISTING; } else { int r = write_argument_data(i, fd, i->path); if (r < 0) return r; int path_fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (path_fd >= 0) { close(fd); fd = path_fd; } creation = CREATION_NORMAL; } int r = fd_set_perms(i, fd, i->path, NULL, creation); if (r < 0) return r; r = fd_set_xattrs(i, fd, i->path); if (r < 0) return r; return fd_set_acls(i, fd, i->path, NULL, creation); } static int truncate_file(Item *i) { const char *bn; _cleanup_close_ int pfd = open_parent_safe(i->path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", i->path, strerror(-pfd)); CreationMode creation; _cleanup_close_ int fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_WRONLY | O_NOCTTY); if (fd < 0) { if (errno != ENOENT) return log_error_errno(-errno, "Failed to open '%s': %s", i->path, strerror(errno)); fd = openat(pfd, bn, O_CREAT | O_NOFOLLOW | O_CLOEXEC | O_WRONLY | O_NOCTTY, i->mode_set ? i->mode : 0644); if (fd < 0) return log_error_errno(-errno, "Failed to create file '%s': %s", i->path, strerror(errno)); creation = CREATION_NORMAL; } else { struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", i->path, strerror(errno)); if (!S_ISREG(st.st_mode)) { log_warning("'%s' exists but is not a regular file.", i->path); return 0; } if (st.st_size > 0) { if (ftruncate(fd, 0) < 0) return log_error_errno(-errno, "Failed to truncate '%s': %s", i->path, strerror(errno)); } creation = CREATION_EXISTING; } int r = write_argument_data(i, fd, i->path); if (r < 0) return r; int path_fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (path_fd >= 0) { close(fd); fd = path_fd; } r = fd_set_perms(i, fd, i->path, NULL, creation); if (r < 0) return r; r = fd_set_xattrs(i, fd, i->path); if (r < 0) return r; return fd_set_acls(i, fd, i->path, NULL, creation); } static int create_directory(Item *i) { mode_t mode = i->mode_set ? i->mode : 0755; const char *bn; _cleanup_close_ int pfd = open_parent_safe(i->path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", i->path, strerror(-pfd)); bool already_existed = false; if (mkdirat(pfd, bn, mode) < 0) { if (errno != EEXIST) return log_error_errno(-errno, "Failed to create directory '%s': %s", i->path, strerror(errno)); already_existed = true; } _cleanup_close_ int fd = openat(pfd, bn, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (fd < 0) return log_error_errno(-errno, "Failed to open directory '%s': %s", i->path, strerror(errno)); struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", i->path, strerror(errno)); if (!S_ISDIR(st.st_mode)) { log_warning("'%s' already exists and is not a directory.", i->path); return 0; } CreationMode creation = already_existed ? CREATION_EXISTING : CREATION_NORMAL; int r = fd_set_perms(i, fd, i->path, &st, creation); if (r < 0) return r; r = fd_set_xattrs(i, fd, i->path); if (r < 0) return r; return fd_set_acls(i, fd, i->path, &st, creation); } static int create_symlink(Item *i) { const char *target = i->argument; if (!target || target[0] == '\0') { log_error("Symlink '%s' has no target specified.", i->path); return -EINVAL; } const char *bn; _cleanup_close_ int pfd = open_parent_safe(i->path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", i->path, strerror(-pfd)); if (symlinkat(target, pfd, bn) < 0) { if (errno != EEXIST) return log_error_errno(-errno, "Failed to create symlink '%s': %s", i->path, strerror(errno)); _cleanup_close_ int fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); struct stat st; if (fd < 0) { if (errno == ELOOP) { /* On systems without O_PATH, O_NOFOLLOW on a symlink returns ELOOP. * Fall back to fstatat via the parent directory fd. */ if (fstatat(pfd, bn, &st, AT_SYMLINK_NOFOLLOW) < 0) return log_error_errno(-errno, "fstatat(%s) failed: %s", i->path, strerror(errno)); } else { return log_error_errno(-errno, "Failed to open '%s': %s", i->path, strerror(errno)); } } else { if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", i->path, strerror(errno)); } if (S_ISLNK(st.st_mode)) { char *buf = NULL; ssize_t n = readlinkat_dynamic(pfd, bn, &buf); if (n >= 0) { if (streq(buf, target)) { free(buf); if (fd >= 0) return fd_set_perms(i, fd, i->path, &st, CREATION_EXISTING); return 0; } } free(buf); } if (!i->append_or_force) { log_debug("'%s' is not a symlink or points to wrong target, ignoring.", i->path); return 0; } if (unlinkat(pfd, bn, S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0) < 0) { if (errno == ENOTEMPTY) { int r = rm_rf(i->path); if (r < 0) return log_error_errno(r, "Failed to remove '%s' for replacement: %s", i->path, strerror(-r)); } else { return log_error_errno(-errno, "Failed to remove '%s': %s", i->path, strerror(errno)); } } if (symlinkat(target, pfd, bn) < 0) return log_error_errno(-errno, "Failed to create symlink '%s' -> '%s': %s", i->path, target, strerror(errno)); } _cleanup_close_ int fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (fd < 0) { log_debug("Failed to open newly created symlink '%s': '%s', ignoring.", i->path, strerror(errno)); return 0; } return fd_set_perms(i, fd, i->path, NULL, CREATION_NORMAL); } static int copy_tree(int src_fd, int dst_fd) { _cleanup_closedir_ DIR *d = xfdopendir(src_fd); if (!d) return -errno; struct dirent *de; int ret = 0; while ((de = readdir(d))) { if (streq(de->d_name, ".") || streq(de->d_name, "..")) continue; struct stat st; if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) { ret = ret ?: -errno; continue; } if (S_ISDIR(st.st_mode)) { if (mkdirat(dst_fd, de->d_name, st.st_mode & 07777) < 0 && errno != EEXIST) { ret = ret ?: -errno; continue; } int child_src = openat(dirfd(d), de->d_name, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_RDONLY); if (child_src < 0) { ret = ret ?: -errno; continue; } int child_dst = openat(dst_fd, de->d_name, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_RDONLY); if (child_dst < 0) { close(child_src); ret = ret ?: -errno; continue; } int r = copy_tree(child_src, child_dst); close(child_src); close(child_dst); ret = ret ?: r; } else if (S_ISLNK(st.st_mode)) { char *target = NULL; ssize_t n = readlinkat_dynamic(dirfd(d), de->d_name, &target); if (n < 0) { free(target); ret = ret ?: n; continue; } target[n] = '\0'; if (symlinkat(target, dst_fd, de->d_name) < 0 && errno != EEXIST) ret = ret ?: -errno; free(target); } else if (S_ISREG(st.st_mode)) { int src = openat(dirfd(d), de->d_name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); if (src < 0) { ret = ret ?: -errno; continue; } int dst = openat(dst_fd, de->d_name, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, st.st_mode & 07777); if (dst < 0) { close(src); ret = ret ?: -errno; continue; } char buf[65536]; for (;;) { ssize_t nr = read(src, buf, sizeof(buf)); if (nr <= 0) { if (nr < 0) ret = ret ?: -errno; break; } ssize_t nw = 0; while (nw < nr) { ssize_t w = write(dst, buf + nw, (size_t)(nr - nw)); if (w < 0) { if (errno == EINTR) continue; ret = ret ?: -errno; goto copy_done; } nw += w; } } struct stat src_st; struct timespec times[2]; if (fstat(src, &src_st) != 0) { log_warning("Failed to get times of '%s'. Ignoring", de->d_name); goto copy_done; } times[0] = src_st.st_atim; times[1] = src_st.st_mtim; if (futimens(dst, times) != 0) log_warning("Failed to set times of '%s'. Ignoring", de->d_name); copy_done: close(src); close(dst); if (fchownat(dst_fd, de->d_name, st.st_uid, st.st_gid, AT_SYMLINK_NOFOLLOW) < 0) ret = ret ?: -errno; } else { log_debug("Skipping special file '%s' during copy.", de->d_name); } } return ret; } static int copy_files(Item *i) { if (!i->argument || i->argument[0] == '\0') { log_error("Copy item '%s' has no source specified.", i->path); return -EINVAL; } _cleanup_free_ char *src_host = NULL; int cr = chase(i->argument, arg_root, CHASE_PREFIX_ROOT, &src_host, NULL); if (cr < 0) return log_error_errno(cr, "Failed to resolve source '%s': %s", i->argument, strerror(-cr)); _cleanup_free_ char *dst_host = NULL; cr = chase(i->path, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &dst_host, NULL); if (cr < 0) return log_error_errno(cr, "Failed to resolve dest '%s': %s", i->path, strerror(-cr)); struct stat src_st; if (stat(src_host, &src_st) < 0) return log_error_errno(-errno, "Failed to stat source '%s': %s", i->argument, strerror(errno)); if (S_ISDIR(src_st.st_mode)) { mode_t mode = i->mode_set ? i->mode : (src_st.st_mode & 07777); if (mkdir(dst_host, mode) < 0 && errno != EEXIST) { if (!i->append_or_force) return log_error_errno(-errno, "Failed to create directory '%s': %s", i->path, strerror(errno)); } int src_fd = open(src_host, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_RDONLY); if (src_fd < 0) return log_error_errno(-errno, "Failed to open source '%s': %s", i->argument, strerror(errno)); int dst_fd = open(dst_host, O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_RDONLY); if (dst_fd < 0) { close(src_fd); return log_error_errno(-errno, "Failed to open dest '%s': %s", i->path, strerror(errno)); } if (!i->append_or_force) { _cleanup_closedir_ DIR *check = xfdopendir(openat(dst_fd, ".", O_DIRECTORY | O_CLOEXEC | O_RDONLY)); if (check) { struct dirent *de; bool empty = true; while ((de = readdir(check))) { if (!streq(de->d_name, ".") && !streq(de->d_name, "..")) { empty = false; break; } } if (!empty) { log_debug("'%s' is not empty, not copying (use C+ to merge).", i->path); close(src_fd); close(dst_fd); return 0; } } } int r = copy_tree(src_fd, dst_fd); close(src_fd); close(dst_fd); if (r < 0) log_warning("Errors during copy '%s' -> '%s': %s", i->argument, i->path, strerror(-r)); } else if (S_ISREG(src_st.st_mode)) { const char *bn; _cleanup_close_ int pfd = open_parent_safe(i->path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", i->path, strerror(-pfd)); _cleanup_close_ int src = open(src_host, O_RDONLY | O_NOFOLLOW | O_CLOEXEC); if (src < 0) return log_error_errno(-errno, "Failed to open source '%s': %s", i->argument, strerror(errno)); mode_t mode = i->mode_set ? i->mode : (src_st.st_mode & 07777); int flags = O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_NOCTTY; if (i->append_or_force) flags |= O_CREAT | O_TRUNC; else flags |= O_CREAT | O_EXCL; _cleanup_close_ int dst = openat(pfd, bn, flags, mode); if (dst < 0) { if (errno == EEXIST && !i->append_or_force) { log_debug("'%s' already exists, not copying.", i->path); return 0; } return log_error_errno(-errno, "Failed to create '%s': %s", i->path, strerror(errno)); } char buf[65536]; for (;;) { ssize_t nr = read(src, buf, sizeof(buf)); if (nr <= 0) { if (nr < 0) return log_error_errno(-errno, "Read error from '%s': %s", i->argument, strerror(errno)); break; } ssize_t nw = 0; while (nw < nr) { ssize_t w = write(dst, buf + nw, (size_t)(nr - nw)); if (w < 0) { if (errno == EINTR) continue; return log_error_errno(-errno, "Write error to '%s': %s", i->path, strerror(errno)); } nw += w; } } struct stat src_st; struct timespec times[2]; if (fstat(src, &src_st) != 0) { return log_error_errno(-errno, "Failed to get times of '%s'. Ignoring", i->argument); } times[0] = src_st.st_atim; times[1] = src_st.st_mtim; if (!i->mode_set) { i->mode_set = true; i->mode = src_st.st_mode; } if (!i->uid_set) { i->uid_set = true; i->uid = src_st.st_uid; } if (!i->gid_set) { i->gid_set = true; i->gid = src_st.st_gid; } if (futimens(dst, times) != 0) return log_error_errno(-errno, "Failed to set times of '%s'. Ignoring", i->path); } else { log_warning("Source '%s' is not a regular file or directory.", i->argument); return 0; } _cleanup_close_ int fd = chase_and_open(i->path, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_CLOEXEC | O_PATH, NULL); if (fd < 0) return log_error_errno(fd, "Failed to open '%s': %s", i->path, strerror(-fd)); int r = fd_set_perms(i, fd, i->path, NULL, CREATION_NORMAL); if (r < 0) return r; return fd_set_xattrs(i, fd, i->path); } static int create_fifo(Item *i) { const char *bn; _cleanup_close_ int pfd = open_parent_safe(i->path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", i->path, strerror(-pfd)); mode_t mode = i->mode_set ? i->mode : 0644; CreationMode creation; if (mkfifoat(pfd, bn, mode) < 0) { if (errno != EEXIST) return log_error_errno(-errno, "Failed to create FIFO '%s': %s", i->path, strerror(errno)); _cleanup_close_ int fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (fd < 0) return log_error_errno(-errno, "Failed to open '%s': %s", i->path, strerror(errno)); struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", i->path, strerror(errno)); if (S_ISFIFO(st.st_mode)) { creation = CREATION_EXISTING; return fd_set_perms(i, fd, i->path, &st, creation); } if (!i->append_or_force) { log_warning("'%s' already exists and is not a FIFO.", i->path); return 0; } if (unlinkat(pfd, bn, S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0) < 0) { if (errno == ENOTEMPTY) { int r = rm_rf(i->path); if (r < 0) return r; } else { return log_error_errno(-errno, "Failed to remove '%s': %s", i->path, strerror(errno)); } } if (mkfifoat(pfd, bn, mode) < 0) return log_error_errno(-errno, "Failed to create FIFO '%s': %s", i->path, strerror(errno)); creation = CREATION_FORCE; } else { creation = CREATION_NORMAL; } _cleanup_close_ int fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH); if (fd < 0) return log_error_errno(-errno, "Failed to open FIFO '%s': %s", i->path, strerror(errno)); return fd_set_perms(i, fd, i->path, NULL, creation); } static int create_device(Item *i, mode_t file_type) { const char *bn; _cleanup_close_ int pfd = open_parent_safe(i->path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", i->path, strerror(-pfd)); mode_t mode = (i->mode_set ? i->mode : 0644) | file_type; CreationMode creation; if (mknodat(pfd, bn, mode, i->major_minor) < 0) { if (errno != EEXIST) { if (errno == EPERM || errno == EACCES) { log_debug("No permission to create device node '%s', ignoring.", i->path); return 0; } return log_error_errno(-errno, "Failed to create device '%s': %s", i->path, strerror(errno)); } _cleanup_close_ int fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (fd < 0) return log_error_errno(-errno, "Failed to open '%s': %s", i->path, strerror(errno)); struct stat st; if (fstat(fd, &st) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", i->path, strerror(errno)); if ((st.st_mode & S_IFMT) == file_type && st.st_rdev == i->major_minor) { creation = CREATION_EXISTING; return fd_set_perms(i, fd, i->path, &st, creation); } if (!i->append_or_force) { log_warning("'%s' already exists and is not the expected device.", i->path); return 0; } if (unlinkat(pfd, bn, S_ISDIR(st.st_mode) ? AT_REMOVEDIR : 0) < 0) { if (errno == ENOTEMPTY) { int r = rm_rf(i->path); if (r < 0) return r; } else { return log_error_errno(-errno, "Failed to remove '%s': %s", i->path, strerror(errno)); } } if (mknodat(pfd, bn, mode, i->major_minor) < 0) { if (errno == EPERM || errno == EACCES) { log_debug("No permission to create device node '%s', ignoring.", i->path); return 0; } return log_error_errno(-errno, "Failed to create device '%s': %s", i->path, strerror(errno)); } creation = CREATION_FORCE; } else { creation = CREATION_NORMAL; } _cleanup_close_ int fd = openat(pfd, bn, O_NOFOLLOW | O_CLOEXEC | O_PATH | O_RDONLY); if (fd < 0) return log_error_errno(-errno, "Failed to open device '%s': %s", i->path, strerror(errno)); return fd_set_perms(i, fd, i->path, NULL, creation); } int write_one_file(Item *i, const char *path) { if (arg_dry_run) { log_info("Would write '%s'.", path); return 0; } const char *bn; _cleanup_close_ int pfd = open_parent_safe(path, &bn); if (pfd < 0) return log_error_errno(pfd, "Failed to open parent of '%s': %s", path, strerror(-pfd)); _cleanup_close_ int fd = openat(pfd, bn, O_WRONLY | O_NONBLOCK | O_CLOEXEC | O_NOCTTY | (i->append_or_force ? O_APPEND : 0)); if (fd < 0) { if (errno != ENOENT) return log_error_errno(-errno, "Failed to open file '%s': %s", path, strerror(errno)); else log_debug("Not writing missing file \"%s\"", path); return 0; } int r = write_argument_data(i, fd, path); if (r < 0) return r; return fd_set_perms(i, fd, path, NULL, CREATION_EXISTING); } int create_item(Context *c, Item *i) { (void)c; if (arg_dry_run) { log_info("Would create '%s' (type %c).", i->path, (char)i->type); return 0; } int r; switch (i->type) { case CREATE_FILE: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); if (i->append_or_force) return truncate_file(i); return create_file(i); case TRUNCATE_FILE: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); return truncate_file(i); case CREATE_DIRECTORY: case TRUNCATE_DIRECTORY: case CREATE_SUBVOLUME: case CREATE_SUBVOLUME_INHERIT_QUOTA: case CREATE_SUBVOLUME_NEW_QUOTA: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); return create_directory(i); case CREATE_SYMLINK: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); return create_symlink(i); case COPY_FILES: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); return copy_files(i); case CREATE_FIFO: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); return create_fifo(i); case CREATE_CHAR_DEVICE: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); return create_device(i, S_IFCHR); case CREATE_BLOCK_DEVICE: r = mkdir_parents(i->path, 0755); if (r < 0) log_debug("mkdir_parents(%s) failed: %s", i->path, strerror(-r)); return create_device(i, S_IFBLK); case SET_XATTR: case RECURSIVE_SET_XATTR: case SET_ACL: case RECURSIVE_SET_ACL: case SET_ATTRIBUTE: case RECURSIVE_SET_ATTRIBUTE: case IGNORE_PATH: case IGNORE_DIRECTORY_PATH: case REMOVE_PATH: case RECURSIVE_REMOVE_PATH: case RELABEL_PATH: case RECURSIVE_RELABEL_PATH: case ADJUST_MODE: case WRITE_FILE: return 0; } log_warning("Unknown item type '%c' for '%s'.", (char)i->type, i->path); return 0; } seedfiles/src/create.h000066400000000000000000000003511521035656300152310ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include "parse.h" #include "perms.h" int create_item(Context *c, Item *i); int mkdir_parents(const char *path, mode_t mode); int write_one_file(Item *i, const char *path); seedfiles/src/execute.c000066400000000000000000000173061521035656300154330ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include "clean.h" #include "create.h" #include "execute.h" #include "perms.h" #include "glob_portable.h" #include "chase.h" static bool should_process(const char *path) { if (n_include_prefixes > 0) { bool match = false; for (size_t i = 0; i < n_include_prefixes; i++) { if (path_startswith(path, arg_include_prefixes[i])) { match = true; break; } } if (!match) return false; } for (size_t i = 0; i < n_exclude_prefixes; i++) { if (path_startswith(path, arg_exclude_prefixes[i])) return false; } return true; } struct glob_apply_ctx { Item *item; int (*func)(Item *, const char *); }; static int glob_apply_trampoline(const char *logical_path, void *userdata) { struct glob_apply_ctx *ctx = userdata; return ctx->func(ctx->item, logical_path); } static int glob_apply(Item *i, int (*func)(Item *, const char *)) { struct glob_apply_ctx ctx = { .item = i, .func = func }; return glob_in_root(i->path, arg_root, glob_apply_trampoline, &ctx); } static int apply_glob_perms(Item *i, const char *instance) { _cleanup_close_ int fd = chase_and_open(instance, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_RDONLY | O_CLOEXEC | O_PATH, NULL); if (fd < 0) { if (fd == -ENOENT) return 0; return fd; } struct stat st; if (fstat(fd, &st) < 0) return -errno; int r = 0; switch (i->type) { case RELABEL_PATH: case ADJUST_MODE: r = fd_set_perms(i, fd, instance, &st, CREATION_EXISTING); break; case SET_XATTR: r = fd_set_xattrs(i, fd, instance); break; case SET_ACL: r = fd_set_acls(i, fd, instance, &st, CREATION_EXISTING); break; case SET_ATTRIBUTE: r = fd_set_attribute(i, fd, instance, &st); break; default: break; } return r; } static int apply_glob_recursive_walk(Item *i, int dir_fd, const char *path); static int apply_recursive_entry(Item *i, int dir_fd, const char *base, const char *parent_path) { _cleanup_free_ char *full = path_join(parent_path, base); if (!full) return -ENOMEM; struct stat st; if (fstatat(dir_fd, base, &st, AT_SYMLINK_NOFOLLOW) < 0) { if (errno == ENOENT) return 0; return -errno; } _cleanup_close_ int fd = openat(dir_fd, base, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_PATH); if (fd < 0) { if (errno == ENOENT) return 0; return -errno; } int r = 0; switch (i->type) { case RECURSIVE_RELABEL_PATH: r = fd_set_perms(i, fd, full, &st, CREATION_EXISTING); break; case RECURSIVE_SET_XATTR: r = fd_set_xattrs(i, fd, full); break; case RECURSIVE_SET_ACL: r = fd_set_acls(i, fd, full, &st, CREATION_EXISTING); break; case RECURSIVE_SET_ATTRIBUTE: r = fd_set_attribute(i, fd, full, &st); break; default: break; } if (S_ISDIR(st.st_mode)) { int q = apply_glob_recursive_walk(i, fd, full); r = r ?: q; } return r; } static int apply_glob_recursive_walk(Item *i, int dir_fd, const char *path) { int sub_fd = openat(dir_fd, ".", O_DIRECTORY | O_CLOEXEC | O_RDONLY); if (sub_fd < 0) return -errno; _cleanup_closedir_ DIR *d = xfdopendir(sub_fd); if (!d) { close(sub_fd); return -errno; } int r = 0; struct dirent *de; while ((de = readdir(d))) { if (streq(de->d_name, ".") || streq(de->d_name, "..")) continue; int q = apply_recursive_entry(i, dirfd(d), de->d_name, path); r = r ?: q; } return r; } static int apply_glob_recursive(Item *i, const char *instance) { int r = apply_glob_perms(i, instance); _cleanup_close_ int fd = chase_and_open(instance, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_DIRECTORY | O_CLOEXEC | O_RDONLY, NULL); if (fd < 0) { if (fd == -ENOENT || fd == -ENOTDIR) return r; return r ?: fd; } int q = apply_glob_recursive_walk(i, fd, instance); return r ?: q; } static int process_item(Context *c, Item *i, OperationMask ops) { if (!should_process(i->path)) return 0; int r = 0; if (ops & OPERATION_REMOVE) { if (!(i->done & OPERATION_REMOVE)) { int q = remove_item(c, i); if (i->allow_failure && q < 0) q = 0; r = r ?: q; i->done |= OPERATION_REMOVE; } } if (ops & OPERATION_CLEAN) { if (!(i->done & OPERATION_CLEAN)) { int q = clean_item(c, i); if (i->allow_failure && q < 0) q = 0; r = r ?: q; i->done |= OPERATION_CLEAN; } } if (ops & OPERATION_CREATE) { if (!(i->done & OPERATION_CREATE)) { int q; switch (i->type) { case CREATE_FILE: case TRUNCATE_FILE: case CREATE_DIRECTORY: case TRUNCATE_DIRECTORY: case CREATE_SUBVOLUME: case CREATE_SUBVOLUME_INHERIT_QUOTA: case CREATE_SUBVOLUME_NEW_QUOTA: case CREATE_FIFO: case CREATE_SYMLINK: case CREATE_CHAR_DEVICE: case CREATE_BLOCK_DEVICE: case COPY_FILES: q = create_item(c, i); break; case RELABEL_PATH: case ADJUST_MODE: case SET_XATTR: case SET_ACL: case SET_ATTRIBUTE: q = glob_apply(i, apply_glob_perms); break; case RECURSIVE_RELABEL_PATH: case RECURSIVE_SET_XATTR: case RECURSIVE_SET_ACL: case RECURSIVE_SET_ATTRIBUTE: q = glob_apply(i, apply_glob_recursive); break; case WRITE_FILE: q = glob_apply(i, write_one_file); break; case IGNORE_PATH: case IGNORE_DIRECTORY_PATH: case REMOVE_PATH: case RECURSIVE_REMOVE_PATH: q = 0; break; default: q = 0; break; } if (i->allow_failure && q < 0) q = 0; r = r ?: q; i->done |= OPERATION_CREATE; } } return r; } static int process_item_array(Context *c, ItemArray *a, OperationMask ops) { int r = 0; for (size_t j = 0; j < a->n_items; j++) { int q = process_item(c, &a->items[j], ops); r = r ?: q; } return r; } static int process_children_first(Context *c, ItemArray *a, OperationMask ops) { int r = 0; for (size_t i = 0; i < a->n_children; i++) { int q = process_children_first(c, a->children[i], ops); r = r ?: q; } int q = process_item_array(c, a, ops); return r ?: q; } static int process_parents_first(Context *c, ItemArray *a, OperationMask ops) { int r = process_item_array(c, a, ops); for (size_t i = 0; i < a->n_children; i++) { int q = process_parents_first(c, a->children[i], ops); r = r ?: q; } return r; } int execute_all(Context *c, OperationMask ops) { int r = 0; if (ops & (OPERATION_REMOVE | OPERATION_CLEAN)) { OperationMask phase1 = ops & (OPERATION_REMOVE | OPERATION_CLEAN); const char *key; void *v; ORDERED_HASHMAP_FOREACH(key, v, c->items) { ItemArray *a = v; if (!a->parent) { int q = process_children_first(c, a, phase1); r = r ?: q; } } ORDERED_HASHMAP_FOREACH(key, v, c->globs) { ItemArray *a = v; if (!a->parent) { int q = process_children_first(c, a, phase1); r = r ?: q; } } } if (ops & OPERATION_CREATE) { const char *key; void *v; ORDERED_HASHMAP_FOREACH(key, v, c->items) { ItemArray *a = v; if (!a->parent) { int q = process_parents_first(c, a, OPERATION_CREATE); r = r ?: q; } } ORDERED_HASHMAP_FOREACH(key, v, c->globs) { ItemArray *a = v; if (!a->parent) { int q = process_parents_first(c, a, OPERATION_CREATE); r = r ?: q; } } } return r; } seedfiles/src/execute.h000066400000000000000000000001771521035656300154360ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include "parse.h" int execute_all(Context *c, OperationMask ops); seedfiles/src/glob_portable.c000066400000000000000000000073071521035656300166040ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include "util.h" #include "glob_portable.h" pattern_list expand_brace_pattern(const char *pattern) { pattern_list list = {NULL, 0}; const char *open = strchr(pattern, '{'); const char *close = open ? strchr(pattern, '}') : NULL; if (!open || !close) { list.patterns = malloc(sizeof(char*)); list.patterns[0] = xstrdup(pattern); list.count = 1; return list; } char *brace = xstrndup(open+1, close-open-1); char *prefix = xstrndup(pattern, open-pattern); char *suffix = xstrdup(close+1); size_t comma_count = 1; for (char *p = brace; *p; p++) { if (*p == ',') comma_count++; } list.patterns = malloc(comma_count*sizeof(char*)); list.count = comma_count; char *saveptr; char *token = strtok_r(brace, ",", &saveptr); size_t i = 0; while (token && i < comma_count) { size_t len = strlen(prefix) + strlen(token) + strlen(suffix) + 1; list.patterns[i] = malloc(len); snprintf(list.patterns[i], len, "%s%s%s", prefix, token, suffix); i++; token = strtok_r(NULL, ",", &saveptr); } free(brace); free(prefix); free(suffix); return list; } int glob_brace(const char *pattern, glob_t *pglob, int flags, int (*errfunc)(const char *epath, int eerrno)) { pattern_list patterns = expand_brace_pattern(pattern); int result = GLOB_NOMATCH; for (size_t i = 0; i < patterns.count; i++) { if (i == 0) { result = glob(patterns.patterns[i], flags, errfunc, pglob); } else { result = glob(patterns.patterns[i], flags | GLOB_APPEND, errfunc, pglob); } free(patterns.patterns[i]); } free(patterns.patterns); return result; } static bool root_is_real(const char *root) { if (!root || !*root) return true; if (root[0] == '/' && root[1] == '\0') return true; return false; } int glob_in_root(const char *pattern, const char *root, int (*cb)(const char *, void *), void *userdata) { if (!pattern || !*pattern || !cb) return -EINVAL; bool have_root = !root_is_real(root); _cleanup_free_ char *root_norm = NULL; size_t root_len = 0; if (have_root) { root_norm = xstrdup(root); path_simplify(root_norm); if (root_norm[0] == '/' && root_norm[1] == '\0') { free(root_norm); root_norm = NULL; have_root = false; } else { root_len = strlen(root_norm); } } _cleanup_free_ char *rooted = NULL; const char *eff_pattern; if (have_root) { rooted = path_join(root_norm, pattern); eff_pattern = rooted; } else { eff_pattern = pattern; } glob_t g = {0}; int gr = glob_brace(eff_pattern, &g, GLOB_NOSORT, NULL); if (gr == GLOB_NOMATCH) { globfree(&g); return 0; } if (gr != 0) { globfree(&g); return -EINVAL; } int ret = 0; for (size_t j = 0; j < g.gl_pathc; j++) { const char *match = g.gl_pathv[j]; const char *logical; if (have_root) { if (strncmp(match, root_norm, root_len) == 0) { logical = match + root_len; if (*logical == '\0') logical = "/"; } else { logical = match; } } else { logical = match; } int q = cb(logical, userdata); if (q < 0 && ret == 0) ret = q; } globfree(&g); return ret; } seedfiles/src/glob_portable.h000066400000000000000000000007111521035656300166010ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include #include typedef struct { char **patterns; size_t count; } pattern_list; int glob_brace(const char *pattern, glob_t *pglob, int flags, int (*errfunc)(const char *epath, int eerrno)); int glob_in_root(const char *pattern, const char *root, int (*cb)(const char *logical_path, void *userdata), void *userdata); seedfiles/src/hashmap.c000066400000000000000000000130331521035656300154030ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include "hashmap.h" #define INITIAL_BUCKETS 64 #define LOAD_FACTOR_NUM 3 #define LOAD_FACTOR_DEN 4 typedef struct { char *key; void *value; bool occupied; size_t order; } Bucket; typedef struct { size_t bucket_idx; } OrderEntry; struct OrderedHashmap { Bucket *buckets; size_t n_buckets; OrderEntry *order; size_t n_entries; size_t n_order_alloc; }; static size_t hash_string(const char *s) { size_t h = 5381; for (; *s; s++) h = h * 33 + (unsigned char)*s; return h; } static size_t probe(size_t hash, size_t i, size_t n) { return (hash + i) & (n - 1); } static bool is_power_of_2(size_t n) { return n && !(n & (n - 1)); } static size_t next_power_of_2(size_t n) { size_t v = 1; while (v < n) v <<= 1; return v; } OrderedHashmap *ordered_hashmap_new(void) { OrderedHashmap *h = calloc(1, sizeof(*h)); if (!h) return NULL; h->n_buckets = INITIAL_BUCKETS; h->buckets = calloc(h->n_buckets, sizeof(Bucket)); if (!h->buckets) { free(h); return NULL; } h->n_order_alloc = 16; h->order = calloc(h->n_order_alloc, sizeof(OrderEntry)); if (!h->order) { free(h->buckets); free(h); return NULL; } return h; } void ordered_hashmap_free(OrderedHashmap *h) { if (!h) return; for (size_t i = 0; i < h->n_buckets; i++) { if (h->buckets[i].occupied) free(h->buckets[i].key); } free(h->buckets); free(h->order); free(h); } void ordered_hashmap_freep(OrderedHashmap **hp) { ordered_hashmap_free(*hp); } static ssize_t find_bucket(OrderedHashmap *h, const char *key) { size_t hash = hash_string(key); for (size_t i = 0; i < h->n_buckets; i++) { size_t idx = probe(hash, i, h->n_buckets); if (!h->buckets[idx].occupied) return -(ssize_t)idx - 1; if (strcmp(h->buckets[idx].key, key) == 0) return (ssize_t)idx; } return -(ssize_t)h->n_buckets - 1; } static int resize(OrderedHashmap *h) { size_t new_n = h->n_buckets * 2; if (!is_power_of_2(new_n)) new_n = next_power_of_2(new_n); Bucket *new_buckets = calloc(new_n, sizeof(Bucket)); if (!new_buckets) return -ENOMEM; for (size_t oi = 0; oi < h->n_entries; oi++) { Bucket *old = &h->buckets[h->order[oi].bucket_idx]; size_t hash = hash_string(old->key); for (size_t i = 0;; i++) { size_t idx = probe(hash, i, new_n); if (!new_buckets[idx].occupied) { new_buckets[idx].key = old->key; new_buckets[idx].value = old->value; new_buckets[idx].occupied = true; new_buckets[idx].order = oi; h->order[oi].bucket_idx = idx; break; } } } free(h->buckets); h->buckets = new_buckets; h->n_buckets = new_n; return 0; } int ordered_hashmap_put(OrderedHashmap *h, const char *key, void *value) { if (h->n_entries * LOAD_FACTOR_DEN >= h->n_buckets * LOAD_FACTOR_NUM) { int r = resize(h); if (r < 0) return r; } ssize_t pos = find_bucket(h, key); if (pos >= 0) return -EEXIST; size_t idx = (size_t)(-(pos + 1)); char *kcopy = strdup(key); if (!kcopy) return -ENOMEM; if (h->n_entries >= h->n_order_alloc) { size_t new_alloc = h->n_order_alloc * 2; OrderEntry *no = realloc(h->order, new_alloc * sizeof(OrderEntry)); if (!no) { free(kcopy); return -ENOMEM; } h->order = no; h->n_order_alloc = new_alloc; } h->buckets[idx].key = kcopy; h->buckets[idx].value = value; h->buckets[idx].occupied = true; h->buckets[idx].order = h->n_entries; h->order[h->n_entries].bucket_idx = idx; h->n_entries++; return 0; } void *ordered_hashmap_get(OrderedHashmap *h, const char *key) { if (!h) return NULL; ssize_t pos = find_bucket(h, key); if (pos < 0) return NULL; return h->buckets[pos].value; } bool ordered_hashmap_contains(OrderedHashmap *h, const char *key) { if (!h) return false; return find_bucket(h, key) >= 0; } void *ordered_hashmap_remove(OrderedHashmap *h, const char *key) { if (!h) return NULL; ssize_t pos = find_bucket(h, key); if (pos < 0) return NULL; Bucket *b = &h->buckets[pos]; void *val = b->value; size_t removed_order = b->order; free(b->key); b->key = NULL; b->value = NULL; b->occupied = false; for (size_t i = 1;; i++) { size_t ci = probe((size_t)pos, i, h->n_buckets); if (!h->buckets[ci].occupied) break; size_t natural = hash_string(h->buckets[ci].key) & (h->n_buckets - 1); bool needs_move; if ((size_t)pos < ci) needs_move = (natural <= (size_t)pos || natural > ci); else needs_move = (natural <= (size_t)pos && natural > ci); if (needs_move) { h->buckets[pos] = h->buckets[ci]; h->order[h->buckets[pos].order].bucket_idx = (size_t)pos; h->buckets[ci].occupied = false; h->buckets[ci].key = NULL; h->buckets[ci].value = NULL; pos = (ssize_t)ci; } } for (size_t i = removed_order; i + 1 < h->n_entries; i++) { h->order[i] = h->order[i + 1]; h->buckets[h->order[i].bucket_idx].order = i; } h->n_entries--; return val; } size_t ordered_hashmap_size(OrderedHashmap *h) { return h ? h->n_entries : 0; } bool ordered_hashmap_iterate(OrderedHashmapIter *iter, const char **key, void **value) { if (!iter->h || iter->idx >= iter->h->n_entries) return false; Bucket *b = &iter->h->buckets[iter->h->order[iter->idx].bucket_idx]; if (key) *key = b->key; if (value) *value = b->value; iter->idx++; return true; } seedfiles/src/hashmap.h000066400000000000000000000020171521035656300154100ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include #include typedef struct OrderedHashmap OrderedHashmap; OrderedHashmap *ordered_hashmap_new(void); void ordered_hashmap_free(OrderedHashmap *h); void ordered_hashmap_freep(OrderedHashmap **hp); #define _cleanup_hashmap_free_ __attribute__((cleanup(ordered_hashmap_freep))) int ordered_hashmap_put(OrderedHashmap *h, const char *key, void *value); void *ordered_hashmap_get(OrderedHashmap *h, const char *key); bool ordered_hashmap_contains(OrderedHashmap *h, const char *key); void *ordered_hashmap_remove(OrderedHashmap *h, const char *key); size_t ordered_hashmap_size(OrderedHashmap *h); typedef struct { OrderedHashmap *h; size_t idx; } OrderedHashmapIter; bool ordered_hashmap_iterate(OrderedHashmapIter *iter, const char **key, void **value); #define ORDERED_HASHMAP_FOREACH(k, v, map) \ for (OrderedHashmapIter _iter = {.h = (map), .idx = 0}; \ ordered_hashmap_iterate(&_iter, &(k), &(v));) seedfiles/src/main.c000066400000000000000000000152241521035656300147120ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include #include "execute.h" #include "parse.h" #include "perms.h" #include "util.h" #include "offline-password.h" #define VERSION "1.4.2" static const char *const system_config_dirs[] = { "/etc/tmpfiles.d", "/run/tmpfiles.d", "/usr/local/lib/tmpfiles.d", "/usr/lib/tmpfiles.d", NULL, }; static void build_user_config_dirs(const char ***dirs, size_t *n) { const char *config_home = getenv("XDG_CONFIG_HOME"); const char *runtime_dir = getenv("XDG_RUNTIME_DIR"); const char *data_home = getenv("XDG_DATA_HOME"); const char *home = getenv("HOME"); *dirs = NULL; *n = 0; #define APPEND(d) \ do { \ const char **tmp = realloc(*dirs, (*n + 1) * sizeof(const char *)); \ if (!tmp) \ return; \ *dirs = tmp; \ (*dirs)[(*n)++] = (d); \ } while (0) static char buf1[4096]; if (config_home && *config_home) { snprintf(buf1, sizeof(buf1), "%s/user-tmpfiles.d", config_home); APPEND(buf1); } else if (home && *home) { snprintf(buf1, sizeof(buf1), "%s/.config/user-tmpfiles.d", home); APPEND(buf1); } static char buf2[4096]; if (runtime_dir && *runtime_dir) { snprintf(buf2, sizeof(buf2), "%s/user-tmpfiles.d", runtime_dir); APPEND(buf2); } static char buf3[4096]; if (data_home && *data_home) { snprintf(buf3, sizeof(buf3), "%s/user-tmpfiles.d", data_home); APPEND(buf3); } else if (home && *home) { snprintf(buf3, sizeof(buf3), "%s/.local/share/user-tmpfiles.d", home); APPEND(buf3); } APPEND("/usr/local/lib/user-tmpfiles.d"); APPEND("/usr/lib/user-tmpfiles.d"); #undef APPEND } static void usage(void) { printf("Usage: seedfiles [OPTIONS...] [CONFIG_FILE...]\n" "\n" "Manage temporary files and directories.\n" "\n" "Commands:\n" " --create Create files and directories\n" " --clean Clean up old files\n" " --remove Remove files and directories\n" "\n" "Options:\n" " --boot Also process entries with the '!' " "modifier\n" " --dry-run Only print what would be done\n" " --prefix=PATH Only process entries with matching " "prefix\n" " --exclude-prefix=PATH\n" " Exclude entries with matching prefix\n" " --user Run in user mode\n" " --root Operate on an alternative filesystem root\n" " --verbose Enable verbose logging\n" " -h, --help Show this help\n" " --version Show version\n"); } enum { OPT_CREATE = 0x100, OPT_CLEAN, OPT_REMOVE, OPT_BOOT, OPT_DRY_RUN, OPT_PREFIX, OPT_EXCLUDE_PREFIX, OPT_USER, OPT_ROOT, OPT_VERBOSE, OPT_VERSION, }; static const struct option long_options[] = { {"create", no_argument, NULL, OPT_CREATE}, {"clean", no_argument, NULL, OPT_CLEAN}, {"remove", no_argument, NULL, OPT_REMOVE}, {"boot", no_argument, NULL, OPT_BOOT}, {"dry-run", no_argument, NULL, OPT_DRY_RUN}, {"prefix", required_argument, NULL, OPT_PREFIX}, {"exclude-prefix", required_argument, NULL, OPT_EXCLUDE_PREFIX}, {"user", no_argument, NULL, OPT_USER}, {"root", required_argument, NULL, OPT_ROOT}, {"verbose", no_argument, NULL, OPT_VERBOSE}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, OPT_VERSION}, {NULL, 0, NULL, 0}, }; static int add_prefix(char ***list, size_t *n, const char *prefix) { char **tmp = realloc(*list, (*n + 1) * sizeof(char *)); if (!tmp) return -ENOMEM; *list = tmp; (*list)[*n] = strdup(prefix); if (!(*list)[*n]) return -ENOMEM; (*n)++; return 0; } int main(int argc, char *argv[]) { OperationMask ops = 0; int c; while ((c = getopt_long(argc, argv, "+h", long_options, NULL)) != -1) { switch (c) { case OPT_CREATE: ops |= OPERATION_CREATE; break; case OPT_CLEAN: ops |= OPERATION_CLEAN; break; case OPT_REMOVE: ops |= OPERATION_REMOVE; break; case OPT_BOOT: arg_boot = true; break; case OPT_DRY_RUN: arg_dry_run = true; break; case OPT_PREFIX: if (add_prefix(&arg_include_prefixes, &n_include_prefixes, optarg) < 0) { log_error("Out of memory."); return EXIT_FAILURE; } break; case OPT_EXCLUDE_PREFIX: if (add_prefix(&arg_exclude_prefixes, &n_exclude_prefixes, optarg) < 0) { log_error("Out of memory."); return EXIT_FAILURE; } break; case OPT_USER: arg_user_mode = true; break; case OPT_ROOT: arg_root = optarg; break; case OPT_VERBOSE: log_level = LOG_DEBUG; break; case 'h': usage(); return EXIT_SUCCESS; case OPT_VERSION: printf("seedfiles %s\n", VERSION); return EXIT_SUCCESS; default: return EXIT_FAILURE; } } if (ops == 0) { log_error("No operation specified. Use --create, --clean, or --remove."); return EXIT_FAILURE; } if (arg_user_mode && arg_root) { log_error("Option --user and --root may not be specified at the same time."); return EXIT_FAILURE; } struct stat st; if (stat("/proc/self", &st) < 0) { log_error("/proc/ is not mounted, but is required for operation."); return EXIT_FAILURE; } umask(0022); const char *const *config_dirs; const char **user_dirs = NULL; size_t n_user_dirs = 0; if (arg_user_mode) { build_user_config_dirs(&user_dirs, &n_user_dirs); const char **tmp = realloc(user_dirs, (n_user_dirs + 1) * sizeof(char *)); if (!tmp) { free(user_dirs); log_error("Out of memory."); return EXIT_FAILURE; } user_dirs = tmp; user_dirs[n_user_dirs] = NULL; config_dirs = user_dirs; } else { config_dirs = system_config_dirs; } Context ctx; context_init(&ctx); int r = parse_config_files(&ctx, config_dirs, argc - optind, argv + optind); if (r < 0) log_warning("Errors occurred while parsing configuration files."); context_link_parents(&ctx); int ret = execute_all(&ctx, ops); context_done(&ctx); free(user_dirs); offline_passwd_cache_clear(); for (size_t i = 0; i < n_include_prefixes; i++) free(arg_include_prefixes[i]); free(arg_include_prefixes); for (size_t i = 0; i < n_exclude_prefixes; i++) free(arg_exclude_prefixes[i]); free(arg_exclude_prefixes); if (ret < 0) return EXIT_FAILURE; return EXIT_SUCCESS; } seedfiles/src/offline-password.c000066400000000000000000000050451521035656300172500ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include #include #include "util.h" #include "hashmap.h" #include "chase.h" #include "offline-password.h" static OrderedHashmap *pwd_cache = NULL; static OrderedHashmap *group_cache = NULL; int name_to_uid_offline(const char *root, const char *user, uid_t *ret) { if (strcmp(user, "root") == 0) { *ret = 0; return 0; } if (!pwd_cache) { pwd_cache = ordered_hashmap_new(); if (!pwd_cache) return -ENOMEM; } if (ordered_hashmap_contains(pwd_cache, user)) { *ret = (uid_t)((uintptr_t)ordered_hashmap_get(pwd_cache, user)-1); return 0; } _cleanup_close_ int passwd_fd = chase_and_open("/etc/passwd", root, CHASE_PREFIX_ROOT, O_CLOEXEC | O_RDONLY, NULL); if (passwd_fd < 0) return passwd_fd; _cleanup_fclose_ FILE *passwd = fdopen(passwd_fd, "r"); if (!passwd) return -ENOMEM; passwd_fd = -1; struct passwd *result = fgetpwent(passwd); while(result && strcmp(result->pw_name, user) != 0) { ordered_hashmap_put(pwd_cache, result->pw_name, (void*)(uintptr_t)(result->pw_uid+1)); result = fgetpwent(passwd); } if (!result) return -ESRCH; ordered_hashmap_put(pwd_cache, result->pw_name, (void*)(uintptr_t)(result->pw_uid+1)); *ret = result->pw_uid; return 0; } int name_to_gid_offline(const char *root, const char *group, gid_t *ret) { if (strcmp(group, "root") == 0) { *ret = 0; return 0; } if (!group_cache) { group_cache = ordered_hashmap_new(); if (!group_cache) return -ENOMEM; } if (ordered_hashmap_contains(group_cache, group)) { *ret = (gid_t)((uintptr_t)ordered_hashmap_get(group_cache, group)-1); return 0; } _cleanup_close_ int groupfd = chase_and_open("/etc/group", root, CHASE_PREFIX_ROOT, O_CLOEXEC | O_RDONLY, NULL); if (groupfd < 0) return groupfd; _cleanup_fclose_ FILE *groups = fdopen(groupfd, "r"); if (!groups) return -ENOMEM; groupfd = -1; struct group *result = fgetgrent(groups); while(result && strcmp(result->gr_name, group) != 0) { ordered_hashmap_put(group_cache, result->gr_name, (void*)(uintptr_t)(result->gr_gid+1)); result = fgetgrent(groups); } if (!result) return -ESRCH; ordered_hashmap_put(group_cache, result->gr_name, (void*)(uintptr_t)(result->gr_gid+1)); *ret = result->gr_gid; return 0; } void offline_passwd_cache_clear(void) { if (group_cache) { ordered_hashmap_free(group_cache); group_cache = NULL; } if (pwd_cache) { ordered_hashmap_free(pwd_cache); pwd_cache = NULL; } } seedfiles/src/offline-password.h000066400000000000000000000004151521035656300172510ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include int name_to_uid_offline(const char *root, const char *user, uid_t *ret); int name_to_gid_offline(const char *root, const char *group, gid_t *ret); void offline_passwd_cache_clear(void); seedfiles/src/parse.c000066400000000000000000000614351521035656300151050ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include #include #include "parse.h" #include "specifier.h" #include "chase.h" #include "glob_portable.h" bool arg_boot = false; bool arg_user_mode = false; char **arg_include_prefixes = NULL; size_t n_include_prefixes = 0; char **arg_exclude_prefixes = NULL; size_t n_exclude_prefixes = 0; void item_free(Item *i) { if (!i) return; free(i->path); free(i->argument); for (size_t j = 0; j < i->n_xattrs; j++) free(i->xattrs[j]); free(i->xattrs); if (i->acl_access) acl_free(i->acl_access); if (i->acl_access_exec) acl_free(i->acl_access_exec); if (i->acl_default) acl_free(i->acl_default); } void item_array_free(ItemArray *a) { if (!a) return; for (size_t i = 0; i < a->n_items; i++) item_free(&a->items[i]); free(a->items); free(a->children); free(a); } void context_init(Context *c) { c->items = ordered_hashmap_new(); c->globs = ordered_hashmap_new(); } void context_done(Context *c) { if (c->items) { const char *key; void *val; ORDERED_HASHMAP_FOREACH(key, val, c->items) item_array_free(val); ordered_hashmap_free(c->items); c->items = NULL; } if (c->globs) { const char *key; void *val; ORDERED_HASHMAP_FOREACH(key, val, c->globs) item_array_free(val); ordered_hashmap_free(c->globs); c->globs = NULL; } } ItemArray *context_lookup(Context *c, const char *path) { ItemArray *a = ordered_hashmap_get(c->items, path); if (a) return a; return ordered_hashmap_get(c->globs, path); } static int parse_devnum(const char *s, dev_t *ret) { if (!s || !*s) return -EINVAL; const char *colon = strchr(s, ':'); if (!colon) return -EINVAL; _cleanup_free_ char *maj_str = xstrndup(s, (size_t)(colon - s)); const char *min_str = colon + 1; char *end; errno = 0; unsigned long maj = strtoul(maj_str, &end, 10); if (errno || *end) return -EINVAL; errno = 0; unsigned long min = strtoul(min_str, &end, 10); if (errno || *end) return -EINVAL; *ret = makedev(maj, min); return 0; } static int parse_xattrs_from_arg(Item *i) { const char *p = i->argument; for (;;) { _cleanup_free_ char *xattr = NULL; int r = extract_first_word(&p, &xattr, NULL, EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE); if (r < 0) { log_warning("Failed to parse extended attribute, ignoring: %s", p); break; } if (r == 0) break; char *eq = strchr(xattr, '='); if (!eq || eq == xattr || !eq[1]) { log_warning("Malformed extended attribute, ignoring: %s", xattr); continue; } size_t new_count = i->n_xattrs + 2; char **new_xattrs = realloc(i->xattrs, new_count * sizeof(char *)); if (!new_xattrs) return -ENOMEM; i->xattrs = new_xattrs; *eq = '\0'; i->xattrs[i->n_xattrs] = xstrdup(xattr); i->xattrs[i->n_xattrs + 1] = xstrdup(eq + 1); i->n_xattrs = new_count; } return 0; } static int parse_acls_from_arg(Item *item) { char *access_buf = NULL; size_t access_len = 0; char *exec_buf = NULL; size_t exec_len = 0; char *default_buf = NULL; size_t default_len = 0; const char *p = item->argument; while (*p) { const char *comma = strchr(p, ','); size_t elen = comma ? (size_t)(comma - p) : strlen(p); _cleanup_free_ char *entry = xstrndup(p, elen); p = comma ? comma + 1 : p + elen; int colons = 0; bool has_upper_x = false; for (size_t j = 0; entry[j]; j++) { if (entry[j] == ':') colons++; if (entry[j] == 'X') has_upper_x = true; } if (colons == 3) { const char *first_colon = strchr(entry, ':'); size_t prefix_len = (size_t)(first_colon - entry); if ((prefix_len == 7 && strneq(entry, "default", 7)) || (prefix_len == 1 && entry[0] == 'd')) { char *rest = xstrdup(first_colon + 1); for (char *q = rest; *q; q++) if (*q == 'X') *q = 'x'; size_t rlen = strlen(rest); size_t need = default_len + (default_len > 0 ? 1 : 0) + rlen + 1; default_buf = realloc(default_buf, need); if (!default_buf) { free(rest); goto oom; } if (default_len > 0) default_buf[default_len++] = ','; memcpy(default_buf + default_len, rest, rlen + 1); default_len += rlen; free(rest); } } else if (colons == 2) { _cleanup_free_ char *fixed = xstrdup(entry); for (char *q = fixed; *q; q++) if (*q == 'X') *q = 'x'; if (has_upper_x) { size_t flen = strlen(fixed); size_t need = exec_len + (exec_len > 0 ? 1 : 0) + flen + 1; exec_buf = realloc(exec_buf, need); if (!exec_buf) goto oom; if (exec_len > 0) exec_buf[exec_len++] = ','; memcpy(exec_buf + exec_len, fixed, flen + 1); exec_len += flen; } else { size_t elen2 = strlen(entry); size_t need = access_len + (access_len > 0 ? 1 : 0) + elen2 + 1; access_buf = realloc(access_buf, need); if (!access_buf) goto oom; if (access_len > 0) access_buf[access_len++] = ','; memcpy(access_buf + access_len, entry, elen2 + 1); access_len += elen2; } } } if (access_buf) { item->acl_access = acl_from_text(access_buf); if (!item->acl_access) { log_warning("Failed to parse access ACL '%s', ignoring: %s", access_buf, strerror(errno)); } else if (!item->append_or_force) { acl_calc_mask(&item->acl_access); } free(access_buf); } if (exec_buf) { item->acl_access_exec = acl_from_text(exec_buf); if (!item->acl_access_exec) log_warning("Failed to parse exec ACL '%s', ignoring: %s", exec_buf, strerror(errno)); free(exec_buf); } if (default_buf) { item->acl_default = acl_from_text(default_buf); if (!item->acl_default) { log_warning("Failed to parse default ACL '%s', ignoring: %s", default_buf, strerror(errno)); } else if (!item->append_or_force) { acl_calc_mask(&item->acl_default); } free(default_buf); } return 0; oom: free(access_buf); free(exec_buf); free(default_buf); return -ENOMEM; } static int patch_var_run(const char *fname, unsigned lineno, char **path) { const char *k = path_startswith(*path, "/var/run/"); if (!k || !*k) return 0; char *n = path_join("/run", k); if (!n) return -ENOMEM; log_info("%s:%u: Patching /var/run/ -> /run/: %s -> %s", fname, lineno, *path, n); free_and_replace(*path, n); return 0; } static bool should_include_path(const char *path) { for (size_t i = 0; i < n_exclude_prefixes; i++) if (path_startswith(path, arg_exclude_prefixes[i])) { log_debug("Entry \"%s\" matches exclude prefix \"%s\", skipping.", path, arg_exclude_prefixes[i]); return false; } for (size_t i = 0; i < n_include_prefixes; i++) if (path_startswith(path, arg_include_prefixes[i])) { log_debug("Entry \"%s\" matches include prefix \"%s\".", path, arg_include_prefixes[i]); return true; } if (n_include_prefixes == 0) return true; log_debug("Entry \"%s\" does not match any include prefix, skipping.", path); return false; } static bool takes_ownership(ItemType t) { switch (t) { case CREATE_FILE: case TRUNCATE_FILE: case CREATE_DIRECTORY: case TRUNCATE_DIRECTORY: case CREATE_SUBVOLUME: case CREATE_SUBVOLUME_INHERIT_QUOTA: case CREATE_SUBVOLUME_NEW_QUOTA: case CREATE_FIFO: case CREATE_SYMLINK: case CREATE_CHAR_DEVICE: case CREATE_BLOCK_DEVICE: case COPY_FILES: case IGNORE_PATH: case IGNORE_DIRECTORY_PATH: case REMOVE_PATH: case RECURSIVE_REMOVE_PATH: case WRITE_FILE: return true; default: return false; } } static int item_compare(const void *ap, const void *bp) { const Item *a = ap, *b = bp; if (takes_ownership(a->type) && !takes_ownership(b->type)) return -1; if (!takes_ownership(a->type) && takes_ownership(b->type)) return 1; if (a->type < b->type) return -1; if (a->type > b->type) return 1; return 0; } static bool is_duplicated_item(ItemArray *existing, const Item *i) { for (size_t j = 0; j < existing->n_items; j++) { const Item *e = &existing->items[j]; if (takes_ownership(e->type) && takes_ownership(i->type)) { bool compatible = (e->argument == NULL && i->argument == NULL) || (e->argument && i->argument && streq(e->argument, i->argument)); compatible = compatible && e->uid_set == i->uid_set && e->uid == i->uid && e->uid_only_create == i->uid_only_create && e->gid_set == i->gid_set && e->gid == i->gid && e->gid_only_create == i->gid_only_create && e->mode_set == i->mode_set && e->mode == i->mode && e->mode_only_create == i->mode_only_create && e->age_set == i->age_set && e->age == i->age && e->mask_perms == i->mask_perms && e->keep_first_level == i->keep_first_level && e->major_minor == i->major_minor; if (!compatible) return true; } } return false; } static int specifier_expansion_from_arg(Item *i) { if (!i->argument && i->n_xattrs == 0) return 0; switch (i->type) { case COPY_FILES: case CREATE_SYMLINK: case CREATE_FILE: case TRUNCATE_FILE: case WRITE_FILE: { /* no specifier expansion with f~ */ if (i->base64) return 0; _cleanup_free_ char *unescaped = NULL; int r = cunescape(i->argument, &unescaped); if (r < 0) return r; _cleanup_free_ char *resolved = NULL; r = specifier_expand(unescaped, arg_user_mode, &resolved); if (r < 0) return r; free_and_replace(i->argument, resolved); return 0; } case SET_XATTR: case RECURSIVE_SET_XATTR: for (size_t j = 1; j < i->n_xattrs; j += 2) { _cleanup_free_ char *resolved = NULL; int r = specifier_expand(i->xattrs[j], arg_user_mode, &resolved); if (r < 0) return r; free_and_replace(i->xattrs[j], resolved); } return 0; default: return 0; } } static bool empty_or_dash(const char *s) { return !s || !*s || streq(s, "-"); } static int parse_line(Context *c, const char *fname, unsigned lineno, const char *line) { const char *p = line; _cleanup_free_ char *action = NULL, *path = NULL, *mode_str = NULL, *user = NULL, *group = NULL, *age_str = NULL; Item i = {0}; int r; r = extract_first_word(&p, &action, NULL, EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE); if (r <= 0) return r < 0 ? r : 0; r = extract_first_word(&p, &path, NULL, EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE); if (r <= 0) { log_error("%s:%u: Missing path field.", fname, lineno); return -EBADMSG; } extract_first_word(&p, &mode_str, NULL, EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE); extract_first_word(&p, &user, NULL, EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE); extract_first_word(&p, &group, NULL, EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE); extract_first_word(&p, &age_str, NULL, EXTRACT_UNQUOTE | EXTRACT_CUNESCAPE); while (p && *p && (*p == ' ' || *p == '\t')) p++; if (p && *p && !empty_or_dash(p)) i.argument = xstrdup(p); if (!action || !action[0]) { log_error("%s:%u: Empty action field.", fname, lineno); return -EBADMSG; } bool boot = false; for (int pos = 1; action[pos]; pos++) { if (action[pos] == '!' && !boot) boot = true; else if (action[pos] == '+' && !i.append_or_force) i.append_or_force = true; else if (action[pos] == '-' && !i.allow_failure) i.allow_failure = true; else if (action[pos] == '=') i.try_replace = true; else if (action[pos] == '~') i.base64 = true; else if (action[pos] == '^' || action[pos] == '$' || action[pos] == '?') { } else { log_error("%s:%u: Unknown modifier '%c' in action '%s'.", fname, lineno, action[pos], action); return -EBADMSG; } } if (boot && !arg_boot) { log_debug("%s:%u: Ignoring entry '%s' (--boot not specified).", fname, lineno, action); r = 0; goto cleanup; } i.type = (ItemType)action[0]; { _cleanup_free_ char *expanded = NULL; r = specifier_expand(path, arg_user_mode, &expanded); if (r < 0) { log_error("%s:%u: Failed to expand specifiers in path '%s'.", fname, lineno, path); goto cleanup; } i.path = expanded; expanded = NULL; } r = patch_var_run(fname, lineno, &i.path); if (r < 0) goto cleanup; if (!path_is_absolute(i.path)) { log_error("%s:%u: Path '%s' not absolute.", fname, lineno, i.path); r = -EBADMSG; goto cleanup; } path_simplify(i.path); switch (i.type) { case CREATE_DIRECTORY: case TRUNCATE_DIRECTORY: case CREATE_SUBVOLUME: case CREATE_SUBVOLUME_INHERIT_QUOTA: case CREATE_SUBVOLUME_NEW_QUOTA: case CREATE_FIFO: case IGNORE_PATH: case IGNORE_DIRECTORY_PATH: case REMOVE_PATH: case RECURSIVE_REMOVE_PATH: case ADJUST_MODE: case RELABEL_PATH: case RECURSIVE_RELABEL_PATH: if (i.argument) { log_warning("%s:%u: %c lines don't take argument fields, ignoring.", fname, lineno, (char)i.type); free(i.argument); i.argument = NULL; } break; case CREATE_FILE: case TRUNCATE_FILE: break; case WRITE_FILE: if (!i.argument) { log_error("%s:%u: Write file requires argument.", fname, lineno); r = -EBADMSG; goto cleanup; } break; case CREATE_SYMLINK: break; case COPY_FILES: break; case CREATE_CHAR_DEVICE: case CREATE_BLOCK_DEVICE: if (!i.argument) { log_error("%s:%u: Device file requires argument.", fname, lineno); r = -EBADMSG; goto cleanup; } r = parse_devnum(i.argument, &i.major_minor); if (r < 0) { log_error("%s:%u: Can't parse device major/minor '%s'.", fname, lineno, i.argument); goto cleanup; } break; case SET_XATTR: case RECURSIVE_SET_XATTR: if (!i.argument) { log_error("%s:%u: Set extended attribute requires argument.", fname, lineno); r = -EBADMSG; goto cleanup; } r = parse_xattrs_from_arg(&i); if (r < 0) goto cleanup; break; case SET_ACL: case RECURSIVE_SET_ACL: if (!i.argument) { log_error("%s:%u: Set ACL requires argument.", fname, lineno); r = -EBADMSG; goto cleanup; } r = parse_acls_from_arg(&i); if (r < 0) goto cleanup; break; case SET_ATTRIBUTE: case RECURSIVE_SET_ATTRIBUTE: if (!i.argument) { log_error("%s:%u: Set file attribute requires argument.", fname, lineno); r = -EBADMSG; goto cleanup; } r = parse_attribute_from_arg(&i); if (r < 0) goto cleanup; break; default: log_error("%s:%u: Unknown command type '%c'.", fname, lineno, (char)i.type); r = -EBADMSG; goto cleanup; } if (!should_include_path(i.path)) { r = 0; goto cleanup; } r = specifier_expansion_from_arg(&i); if (r < 0) { log_error("%s:%u: Failed to expand specifiers in argument.", fname, lineno); goto cleanup; } switch (i.type) { case CREATE_SYMLINK: if (!i.argument) i.argument = path_join("/usr/share/factory", i.path); break; case COPY_FILES: if (!i.argument) { i.argument = path_join("/usr/share/factory", i.path); } else if (!path_is_absolute(i.argument)) { log_error("%s:%u: Copy source path '%s' is not absolute.", fname, lineno, i.argument); r = -EBADMSG; goto cleanup; } if (i.argument) { path_simplify(i.argument); _cleanup_free_ char *probe = NULL; int pr = chase(i.argument, arg_root, CHASE_PREFIX_ROOT, &probe, NULL); if (pr == -ENOENT) { log_debug("%s:%u: Copy source '%s' does not exist, skipping.", fname, lineno, i.argument); r = 0; goto cleanup; } } break; default: break; } if (i.type == CREATE_SUBVOLUME || i.type == CREATE_SUBVOLUME_INHERIT_QUOTA || i.type == CREATE_SUBVOLUME_NEW_QUOTA) i.type = CREATE_DIRECTORY; if (!empty_or_dash(user)) { const char *u = user; const char *colon = startswith(u, ":"); if (colon) { i.uid_only_create = true; u = colon; } r = resolve_user(u, &i.uid); if (r < 0) { log_error("%s:%u: Failed to resolve user '%s'.", fname, lineno, u); goto cleanup; } i.uid_set = true; } if (!empty_or_dash(group)) { const char *g = group; const char *colon = startswith(g, ":"); if (colon) { i.gid_only_create = true; g = colon; } r = resolve_group(g, &i.gid); if (r < 0) { log_error("%s:%u: Failed to resolve group '%s'.", fname, lineno, g); goto cleanup; } i.gid_set = true; } if (!empty_or_dash(mode_str)) { const char *mm = mode_str; for (;; mm++) { if (*mm == '~') i.mask_perms = true; else if (*mm == ':') i.mode_only_create = true; else break; } mode_t m; r = parse_mode(mm, &m); if (r < 0) { log_error("%s:%u: Invalid mode '%s'.", fname, lineno, mode_str); goto cleanup; } i.mode = m; i.mode_set = true; } else { switch (i.type) { case CREATE_DIRECTORY: case TRUNCATE_DIRECTORY: i.mode = 0755; break; default: i.mode = 0644; break; } } if (!empty_or_dash(age_str)) { const char *a = age_str; if (*a == '~') { i.keep_first_level = true; a++; } const char *colon = strchr(a, ':'); if (colon) a = colon + 1; r = parse_duration(a, &i.age); if (r < 0) { log_error("%s:%u: Invalid age '%s'.", fname, lineno, age_str); goto cleanup; } i.age_set = true; } OrderedHashmap *h = item_type_is_glob(i.type) ? c->globs : c->items; ItemArray *existing = ordered_hashmap_get(h, i.path); if (existing) { if (is_duplicated_item(existing, &i)) { log_info("%s:%u: Duplicate line for path \"%s\", ignoring.", fname, lineno, i.path); r = 0; goto cleanup; } } else { existing = calloc(1, sizeof(ItemArray)); if (!existing) { r = -ENOMEM; goto cleanup; } r = ordered_hashmap_put(h, i.path, existing); if (r < 0) { free(existing); goto cleanup; } } Item *new_items = realloc(existing->items, (existing->n_items + 1) * sizeof(Item)); if (!new_items) { r = -ENOMEM; goto cleanup; } existing->items = new_items; existing->items[existing->n_items] = i; existing->n_items++; qsort(existing->items, existing->n_items, sizeof(Item), item_compare); return 0; cleanup: item_free(&i); return r; } int parse_config_file(Context *c, const char *path) { _cleanup_free_ char *contents = NULL; const char *fname; int r; if (streq(path, "-")) { r = read_fd_full(STDIN_FILENO, &contents, NULL); fname = ""; } else { r = read_file_full(path, &contents, NULL); fname = path; } if (r < 0) { log_error("Failed to open config file %s", fname); return r; } unsigned lineno = 0; int ret = 0; char *line = contents; while (line && *line) { char *nl = strchr(line, '\n'); if (nl) *nl = '\0'; lineno++; char *stripped = strstrip(line); if (*stripped && *stripped != '#' && *stripped != ';') { r = parse_line(c, fname, lineno, stripped); if (r < 0 && ret == 0) ret = r; } line = nl ? nl + 1 : NULL; } return ret; } typedef struct ConfigEntry { char *basename; char *fullpath; } ConfigEntry; static int config_entry_compare(const void *ap, const void *bp) { const ConfigEntry *a = ap, *b = bp; return strcmp(a->basename, b->basename); } struct config_glob_ctx { ConfigEntry **entries; size_t *n_entries; size_t *cap; }; static int config_glob_trampoline(const char *logical_path, void *userdata) { struct config_glob_ctx *ctx = userdata; const char *bn = path_basename(logical_path); for (size_t j = 0; j < *ctx->n_entries; j++) { if (streq((*ctx->entries)[j].basename, bn)) return 0; } if (*ctx->n_entries >= *ctx->cap) { size_t new_cap = *ctx->cap ? *ctx->cap * 2 : 16; ConfigEntry *ne = realloc(*ctx->entries, new_cap * sizeof(ConfigEntry)); if (!ne) return -ENOMEM; *ctx->entries = ne; *ctx->cap = new_cap; } char *fullpath = arg_root ? path_join(arg_root, logical_path) : xstrdup(logical_path); if (!fullpath) return -ENOMEM; (*ctx->entries)[*ctx->n_entries].basename = xstrdup(bn); (*ctx->entries)[*ctx->n_entries].fullpath = fullpath; (*ctx->n_entries)++; return 0; } int parse_config_files(Context *c, const char *const *config_dirs, int argc, char **argv) { ConfigEntry *entries = NULL; size_t n_entries = 0, cap = 0; if (config_dirs && argc == 0) { struct config_glob_ctx ctx = { .entries = &entries, .n_entries = &n_entries, .cap = &cap, }; for (const char *const *d = config_dirs; *d; d++) { _cleanup_free_ char *pattern = path_join(*d, "*.conf"); if (!pattern) { free(entries); return -ENOMEM; } int gr = glob_in_root(pattern, arg_root, config_glob_trampoline, &ctx); if (gr == -ENOMEM) goto oom; /* other errors: skip this directory silently, matching previous behaviour */ } } if (n_entries > 1) qsort(entries, n_entries, sizeof(ConfigEntry), config_entry_compare); int ret = 0; for (size_t i = 0; i < n_entries; i++) { log_debug("Reading config file '%s'.", entries[i].fullpath); int r = parse_config_file(c, entries[i].fullpath); if (r < 0 && ret == 0) ret = r; } for (size_t i = 0; i < n_entries; i++) { free(entries[i].basename); free(entries[i].fullpath); } free(entries); for (int i = 0; i < argc; i++) { const char *arg = argv[i]; if (strchr(arg, '/')) { log_debug("Reading config file '%s' (from command line).", arg); int r = parse_config_file(c, arg); if (r < 0 && ret == 0) ret = r; continue; } _cleanup_free_ char *resolved = NULL; if (config_dirs) { for (const char *const *d = config_dirs; *d; d++) { char *candidate = path_join(*d, arg); if (!candidate) return -ENOMEM; if (arg_root) { char *rooted = path_join(arg_root, candidate); free(candidate); if (!rooted) return -ENOMEM; candidate = rooted; } if (access(candidate, F_OK) == 0) { resolved = candidate; break; } free(candidate); } } if (!resolved) { log_error("Configuration file '%s' not found in any configuration directory.", arg); if (ret == 0) ret = -ENOENT; continue; } log_debug("Reading config file '%s' (resolved from '%s').", resolved, arg); int r = parse_config_file(c, resolved); if (r < 0 && ret == 0) ret = r; } return ret; oom: for (size_t i = 0; i < n_entries; i++) { free(entries[i].basename); free(entries[i].fullpath); } free(entries); return -ENOMEM; } static int link_parent(Context *c, ItemArray *a) { if (a->n_items == 0) return 0; const char *path = a->items[0].path; _cleanup_free_ char *prefix = xstrdup(path); for (;;) { char *slash = strrchr(prefix, '/'); if (!slash || slash == prefix) { if (slash == prefix && prefix[1] != '\0') { prefix[1] = '\0'; ItemArray *j = ordered_hashmap_get(c->items, prefix); if (!j) j = ordered_hashmap_get(c->globs, prefix); if (j) { ItemArray **nc = realloc(j->children, (j->n_children + 1) * sizeof(ItemArray *)); if (!nc) return -ENOMEM; j->children = nc; j->children[j->n_children++] = a; a->parent = j; return 1; } } return 0; } *slash = '\0'; if (!*prefix) continue; ItemArray *j = ordered_hashmap_get(c->items, prefix); if (!j) j = ordered_hashmap_get(c->globs, prefix); if (j) { bool already = false; for (size_t k = 0; k < j->n_children; k++) { if (j->children[k] == a) { already = true; break; } } if (!already) { ItemArray **nc = realloc(j->children, (j->n_children + 1) * sizeof(ItemArray *)); if (!nc) return -ENOMEM; j->children = nc; j->children[j->n_children++] = a; } a->parent = j; return 1; } } } void context_link_parents(Context *c) { const char *key; void *val; ORDERED_HASHMAP_FOREACH(key, val, c->items) link_parent(c, val); ORDERED_HASHMAP_FOREACH(key, val, c->globs) link_parent(c, val); } seedfiles/src/parse.h000066400000000000000000000061651521035656300151110ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include #include #include "hashmap.h" #include "util.h" typedef enum { OPERATION_CREATE = 1 << 0, OPERATION_REMOVE = 1 << 1, OPERATION_CLEAN = 1 << 2, } OperationMask; typedef enum { // non-glob types CREATE_FILE = 'f', TRUNCATE_FILE = 'F', CREATE_DIRECTORY = 'd', TRUNCATE_DIRECTORY = 'D', CREATE_SUBVOLUME = 'v', CREATE_SUBVOLUME_INHERIT_QUOTA = 'q', CREATE_SUBVOLUME_NEW_QUOTA = 'Q', CREATE_FIFO = 'p', CREATE_SYMLINK = 'L', CREATE_CHAR_DEVICE = 'c', CREATE_BLOCK_DEVICE = 'b', COPY_FILES = 'C', // glob types SET_XATTR = 't', RECURSIVE_SET_XATTR = 'T', SET_ACL = 'a', RECURSIVE_SET_ACL = 'A', SET_ATTRIBUTE = 'h', RECURSIVE_SET_ATTRIBUTE = 'H', IGNORE_PATH = 'x', IGNORE_DIRECTORY_PATH = 'X', REMOVE_PATH = 'r', RECURSIVE_REMOVE_PATH = 'R', RELABEL_PATH = 'z', RECURSIVE_RELABEL_PATH = 'Z', ADJUST_MODE = 'm', WRITE_FILE = 'w', } ItemType; typedef enum { CREATION_NORMAL, CREATION_EXISTING, CREATION_FORCE, } CreationMode; typedef struct Item { ItemType type; char *path; char *argument; char **xattrs; size_t n_xattrs; acl_t acl_access; acl_t acl_access_exec; acl_t acl_default; uid_t uid; gid_t gid; mode_t mode; uint64_t age; dev_t major_minor; unsigned attribute_value; unsigned attribute_mask; bool uid_set; bool gid_set; bool mode_set; bool uid_only_create; bool gid_only_create; bool mode_only_create; bool age_set; bool mask_perms; bool attribute_set; bool keep_first_level; bool append_or_force; bool allow_failure; bool try_replace; bool base64; OperationMask done; } Item; typedef struct ItemArray ItemArray; struct ItemArray { Item *items; size_t n_items; ItemArray *parent; ItemArray **children; size_t n_children; }; typedef struct { OrderedHashmap *items; OrderedHashmap *globs; } Context; // returns true for types that go into the globs hashmap static inline bool item_type_is_glob(ItemType t) { switch (t) { case SET_XATTR: case RECURSIVE_SET_XATTR: case SET_ACL: case RECURSIVE_SET_ACL: case SET_ATTRIBUTE: case RECURSIVE_SET_ATTRIBUTE: case IGNORE_PATH: case IGNORE_DIRECTORY_PATH: case REMOVE_PATH: case RECURSIVE_REMOVE_PATH: case RELABEL_PATH: case RECURSIVE_RELABEL_PATH: case ADJUST_MODE: case WRITE_FILE: return true; default: return false; } } void item_free(Item *i); void item_array_free(ItemArray *a); static inline void item_array_freep(ItemArray **ap) { if (*ap) item_array_free(*ap); } void context_init(Context *c); void context_done(Context *c); ItemArray *context_lookup(Context *c, const char *path); extern bool arg_boot; extern bool arg_user_mode; extern char **arg_include_prefixes; extern size_t n_include_prefixes; extern char **arg_exclude_prefixes; extern size_t n_exclude_prefixes; int parse_config_file(Context *c, const char *path); int parse_config_files(Context *c, const char *const *config_dirs, int argc, char **argv); extern int parse_attribute_from_arg(Item *item); void context_link_parents(Context *c); seedfiles/src/perms.c000066400000000000000000000332101521035656300151070ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include #include #include #include #include #include "perms.h" #include "chase.h" #include "platform/platform.h" bool arg_dry_run = false; static mode_t process_mask_perms(mode_t mode, mode_t current) { if ((current & 0111) == 0) mode &= ~0111; if ((current & 0222) == 0) mode &= ~0222; if ((current & 0444) == 0) mode &= ~0444; if (!S_ISDIR(current)) mode &= ~07000; return mode; } static int acl_entry_equal(acl_entry_t a, acl_entry_t b) { acl_tag_t tag_a, tag_b; if (acl_get_tag_type(a, &tag_a) < 0) return -errno; if (acl_get_tag_type(b, &tag_b) < 0) return -errno; if (tag_a != tag_b) return 0; switch (tag_a) { case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: return 1; case ACL_USER: { uid_t *uid_a = acl_get_qualifier(a); if (!uid_a) return -errno; uid_t *uid_b = acl_get_qualifier(b); if (!uid_b) { acl_free(uid_a); return -errno; } int eq = *uid_a == *uid_b; acl_free(uid_a); acl_free(uid_b); return eq; } case ACL_GROUP: { gid_t *gid_a = acl_get_qualifier(a); if (!gid_a) return -errno; gid_t *gid_b = acl_get_qualifier(b); if (!gid_b) { acl_free(gid_a); return -errno; } int eq = *gid_a == *gid_b; acl_free(gid_a); acl_free(gid_b); return eq; } default: return -EINVAL; } } static int find_acl_entry(acl_t acl, acl_entry_t entry, acl_entry_t *ret) { acl_entry_t i; int r; for (r = acl_get_entry(acl, ACL_FIRST_ENTRY, &i); r == 1; r = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) { r = acl_entry_equal(i, entry); if (r < 0) return r; if (r > 0) { if (ret) *ret = i; return 0; } } if (r < 0) return -errno; return -ENOENT; } static int calc_acl_mask_if_needed(acl_t *acl_p) { acl_entry_t i; int r; bool need = false; for (r = acl_get_entry(*acl_p, ACL_FIRST_ENTRY, &i); r == 1; r = acl_get_entry(*acl_p, ACL_NEXT_ENTRY, &i)) { acl_tag_t tag; if (acl_get_tag_type(i, &tag) < 0) return -errno; if (tag == ACL_MASK) return 0; if (tag == ACL_USER || tag == ACL_GROUP) need = true; } if (r < 0) return -errno; if (need && acl_calc_mask(acl_p) < 0) return -errno; return 0; } static int add_base_acls_if_needed(acl_t *acl_p, int fd) { acl_entry_t i; int r; bool have_user_obj = false, have_group_obj = false, have_other = false; for (r = acl_get_entry(*acl_p, ACL_FIRST_ENTRY, &i); r == 1; r = acl_get_entry(*acl_p, ACL_NEXT_ENTRY, &i)) { acl_tag_t tag; if (acl_get_tag_type(i, &tag) < 0) return -errno; if (tag == ACL_USER_OBJ) have_user_obj = true; else if (tag == ACL_GROUP_OBJ) have_group_obj = true; else if (tag == ACL_OTHER) have_other = true; if (have_user_obj && have_group_obj && have_other) return 0; } if (r < 0) return -errno; struct stat st; if (fstat(fd, &st) < 0) return -errno; acl_t basic = acl_from_mode(st.st_mode); if (!basic) return -errno; for (r = acl_get_entry(basic, ACL_FIRST_ENTRY, &i); r == 1; r = acl_get_entry(basic, ACL_NEXT_ENTRY, &i)) { acl_tag_t tag; if (acl_get_tag_type(i, &tag) < 0) { acl_free(basic); return -errno; } if ((tag == ACL_USER_OBJ && have_user_obj) || (tag == ACL_GROUP_OBJ && have_group_obj) || (tag == ACL_OTHER && have_other)) continue; acl_entry_t dst; if (acl_create_entry(acl_p, &dst) < 0) { acl_free(basic); return -errno; } if (acl_copy_entry(dst, i) < 0) { acl_free(basic); return -errno; } } if (r < 0) { acl_free(basic); return -errno; } acl_free(basic); return 0; } int fd_set_perms(Item *i, int fd, const char *path, const struct stat *st, CreationMode creation) { struct stat stbuf; if (!i->mode_set && !i->uid_set && !i->gid_set) return 0; if (!st) { if (fstat(fd, &stbuf) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", path, strerror(errno)); st = &stbuf; } uid_t new_uid = (i->uid_set && (creation != CREATION_EXISTING || !i->uid_only_create)) ? i->uid : st->st_uid; gid_t new_gid = (i->gid_set && (creation != CREATION_EXISTING || !i->gid_only_create)) ? i->gid : st->st_gid; bool do_chown = (new_uid != st->st_uid) || (new_gid != st->st_gid); mode_t new_mode; if (i->mode_set && (creation != CREATION_EXISTING || !i->mode_only_create)) { new_mode = i->mask_perms ? process_mask_perms(i->mode, st->st_mode) : i->mode; } else { new_mode = st->st_mode & 07777; } bool do_chmod = ((new_mode ^ st->st_mode) & 07777) != 0; if (do_chmod && do_chown && !S_ISLNK(st->st_mode)) { mode_t temp = new_mode & st->st_mode; if (((temp ^ st->st_mode) & 07777) != 0) { log_debug("Temporarily reducing mode of \"%s\" to %04o", path, temp); if (!arg_dry_run) { if (fchmod_opath(fd, temp) < 0) return log_error_errno(-errno, "fchmod(%s) failed: %s", path, strerror(errno)); } } } if (do_chown) { log_debug("%s owner of \"%s\" to %u:%u", arg_dry_run ? "Would change" : "Changing", path, (unsigned)new_uid, (unsigned)new_gid); if (!arg_dry_run) { if (fchownat(fd, "", new_uid, new_gid, AT_EMPTY_PATH) < 0) return log_error_errno(-errno, "fchownat(%s) failed: %s", path, strerror(errno)); } } if (do_chmod || do_chown) { if (S_ISLNK(st->st_mode)) { log_debug("Skipping mode change for symlink %s.", path); } else { log_debug("%s mode of \"%s\" to %04o", arg_dry_run ? "Would change" : "Changing", path, new_mode); if (!arg_dry_run) { if (fchmod_opath(fd, new_mode) < 0) return log_error_errno(-errno, "fchmod(%s) failed: %s", path, strerror(errno)); } } } return 0; } int fd_set_xattrs(Item *i, int fd, const char *path) { if (i->n_xattrs == 0) return 0; for (size_t j = 0; j + 1 < i->n_xattrs; j += 2) { const char *name = i->xattrs[j]; const char *value = i->xattrs[j + 1]; log_debug("%s extended attribute '%s=%s' on %s", arg_dry_run ? "Would set" : "Setting", name, value, path); if (!arg_dry_run) { if (fsetxattr(fd, name, value, strlen(value), 0) < 0) return log_error_errno(-errno, "Failed to set extended attribute %s=%s on " "'%s': %s", name, value, path, strerror(errno)); } } return 0; } static int set_acl_on_fd(int fd, const char *path, acl_type_t type, acl_t acl, bool modify) { if (!acl) return 0; acl_t dup = NULL; if (modify) { acl_t existing = NULL; int gr = acl_get_for_fd(fd, -1, NULL, path, type, &existing); if (gr < 0) { int saved = -gr; if (saved == ENODATA || saved == ENOSYS || saved == EOPNOTSUPP) { dup = acl_dup(acl); if (!dup) return -ENOMEM; goto apply; } return log_error_errno(gr, "Failed to get existing ACL on '%s': %s", path, strerror(saved)); } dup = acl_dup(existing); acl_free(existing); if (!dup) return -ENOMEM; acl_entry_t entry; for (int r = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry); r == 1; r = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry)) { acl_entry_t target; int fr = find_acl_entry(dup, entry, &target); if (fr == -ENOENT) { if (acl_create_entry(&dup, &target) < 0) { acl_free(dup); return -errno; } } else if (fr < 0) { acl_free(dup); return fr; } if (acl_copy_entry(target, entry) < 0) { acl_free(dup); return -errno; } } calc_acl_mask_if_needed(&dup); } else { dup = acl_dup(acl); if (!dup) return -ENOMEM; } apply:; int r = add_base_acls_if_needed(&dup, fd); if (r < 0) { acl_free(dup); return r; } log_debug("%s %s ACL on %s", arg_dry_run ? "Would set" : "Setting", type == ACL_TYPE_ACCESS ? "access" : "default", path); if (!arg_dry_run) { int sr = acl_set_for_fd(fd, -1, NULL, path, type, dup); if (sr < 0) { int saved = -sr; acl_free(dup); if (saved == ENOSYS || saved == EOPNOTSUPP || saved == ENOTSUP) { log_debug("ACLs not supported on %s, ignoring.", path); return 0; } return log_error_errno(sr, "Failed to set ACL on '%s': %s", path, strerror(saved)); } } acl_free(dup); return 0; } int fd_set_acls(Item *i, int fd, const char *path, const struct stat *st, CreationMode creation) { (void)creation; struct stat stbuf; if (!i->acl_access && !i->acl_access_exec && !i->acl_default) return 0; if (!st) { if (fstat(fd, &stbuf) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", path, strerror(errno)); st = &stbuf; } if (!S_ISREG(st->st_mode) && !S_ISDIR(st->st_mode)) { log_debug("Skipping ACL for '%s' (not a regular file or directory).", path); return 0; } int r = 0; bool modify = i->append_or_force; if (i->acl_access_exec) { bool has_exec = S_ISDIR(st->st_mode) || (st->st_mode & 0111); if (has_exec) { acl_t combined; if (i->acl_access) { combined = acl_dup(i->acl_access); if (!combined) return -ENOMEM; acl_entry_t entry; for (int rv = acl_get_entry(i->acl_access_exec, ACL_FIRST_ENTRY, &entry); rv == 1; rv = acl_get_entry(i->acl_access_exec, ACL_NEXT_ENTRY, &entry)) { acl_entry_t new_entry; if (acl_create_entry(&combined, &new_entry) < 0) { acl_free(combined); return -errno; } if (acl_copy_entry(new_entry, entry) < 0) { acl_free(combined); return -errno; } } if (!modify) calc_acl_mask_if_needed(&combined); } else { combined = acl_dup(i->acl_access_exec); if (!combined) return -ENOMEM; if (!modify) calc_acl_mask_if_needed(&combined); } r = set_acl_on_fd(fd, path, ACL_TYPE_ACCESS, combined, modify); acl_free(combined); } else { acl_t stripped = acl_dup(i->acl_access_exec); if (!stripped) return -ENOMEM; acl_entry_t entry; for (int rv = acl_get_entry(stripped, ACL_FIRST_ENTRY, &entry); rv == 1; rv = acl_get_entry(stripped, ACL_NEXT_ENTRY, &entry)) { acl_permset_t permset; if (acl_get_permset(entry, &permset) == 0) acl_delete_perm(permset, ACL_EXECUTE); } acl_t combined; if (i->acl_access) { combined = acl_dup(i->acl_access); if (!combined) { acl_free(stripped); return -ENOMEM; } acl_entry_t e2; for (int rv = acl_get_entry(stripped, ACL_FIRST_ENTRY, &e2); rv == 1; rv = acl_get_entry(stripped, ACL_NEXT_ENTRY, &e2)) { acl_entry_t new_entry; if (acl_create_entry(&combined, &new_entry) < 0) { acl_free(combined); acl_free(stripped); return -errno; } acl_copy_entry(new_entry, e2); } if (!modify) calc_acl_mask_if_needed(&combined); acl_free(stripped); } else { combined = stripped; if (!modify) calc_acl_mask_if_needed(&combined); } r = set_acl_on_fd(fd, path, ACL_TYPE_ACCESS, combined, modify); acl_free(combined); } } else if (i->acl_access) { r = set_acl_on_fd(fd, path, ACL_TYPE_ACCESS, i->acl_access, modify); } if (r < 0) return r; if (i->acl_default && S_ISDIR(st->st_mode)) { r = set_acl_on_fd(fd, path, ACL_TYPE_DEFAULT, i->acl_default, modify); if (r < 0) return r; } return 0; } int path_set_perms(Item *i, const char *path, CreationMode creation) { _cleanup_close_ int fd = chase_and_open(path, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_RDONLY | O_CLOEXEC | O_PATH, NULL); if (fd < 0) { if (fd == -ENOENT) return 0; return fd; } return fd_set_perms(i, fd, path, NULL, creation); } int path_set_xattrs(Item *i, const char *path) { if (i->n_xattrs == 0) return 0; _cleanup_close_ int fd = chase_and_open(path, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_RDONLY | O_CLOEXEC, NULL); if (fd < 0) { if (fd == -ENOENT) return 0; if (fd == -ELOOP) { log_debug("Cannot set xattrs on symlink '%s', skipping.", path); return 0; } return fd; } return fd_set_xattrs(i, fd, path); } int path_set_acls(Item *i, const char *path, CreationMode creation) { if (!i->acl_access && !i->acl_access_exec && !i->acl_default) return 0; _cleanup_close_ int fd = chase_and_open(path, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW, O_RDONLY | O_CLOEXEC | O_PATH, NULL); if (fd < 0) { if (fd == -ENOENT) return 0; return fd; } return fd_set_acls(i, fd, path, NULL, creation); } seedfiles/src/perms.h000066400000000000000000000012231521035656300151130ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include "platform/platform.h" #include "parse.h" extern bool arg_dry_run; int fd_set_perms(Item *i, int fd, const char *path, const struct stat *st, CreationMode creation); int fd_set_xattrs(Item *i, int fd, const char *path); int fd_set_acls(Item *i, int fd, const char *path, const struct stat *st, CreationMode creation); int path_set_perms(Item *i, const char *path, CreationMode creation); int path_set_xattrs(Item *i, const char *path); int path_set_acls(Item *i, const char *path, CreationMode creation); int path_set_attribute(Item *i, const char *path); seedfiles/src/platform/000077500000000000000000000000001521035656300154425ustar00rootroot00000000000000seedfiles/src/platform/linux.c000066400000000000000000000123101521035656300167420ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include "platform.h" #ifndef FS_PROJINHERIT_FL #define FS_PROJINHERIT_FL 0x20000000 #endif #define CHATTR_ALL_FL \ (FS_NOATIME_FL | FS_SYNC_FL | FS_DIRSYNC_FL | FS_APPEND_FL | FS_COMPR_FL | \ FS_NODUMP_FL | FS_EXTENT_FL | FS_IMMUTABLE_FL | FS_JOURNAL_DATA_FL | \ FS_SECRM_FL | FS_UNRM_FL | FS_NOTAIL_FL | FS_TOPDIR_FL | FS_NOCOW_FL | \ FS_PROJINHERIT_FL) int fchmod_opath(int fd, mode_t mode) { char p[64]; snprintf(p, sizeof(p), "/proc/self/fd/%d", fd); if (chmod(p, mode) < 0) return -errno; return 0; } int parse_attribute_from_arg(Item *item) { static const struct { char character; unsigned value; } attributes[] = { {'A', FS_NOATIME_FL}, {'S', FS_SYNC_FL}, {'D', FS_DIRSYNC_FL}, {'a', FS_APPEND_FL}, {'c', FS_COMPR_FL}, {'d', FS_NODUMP_FL}, {'e', FS_EXTENT_FL}, {'i', FS_IMMUTABLE_FL}, {'j', FS_JOURNAL_DATA_FL}, {'s', FS_SECRM_FL}, {'u', FS_UNRM_FL}, {'t', FS_NOTAIL_FL}, {'T', FS_TOPDIR_FL}, {'C', FS_NOCOW_FL}, {'P', FS_PROJINHERIT_FL}, }; enum { MODE_ADD, MODE_DEL, MODE_SET } mode = MODE_ADD; unsigned value = 0, mask = 0; const char *p = item->argument; if (p) { if (*p == '+') { mode = MODE_ADD; p++; } else if (*p == '-') { mode = MODE_DEL; p++; } else if (*p == '=') { mode = MODE_SET; p++; } } if ((!p || !*p) && mode != MODE_SET) { log_error("Setting file attribute on '%s' needs an attribute " "specification.", item->path); return -EINVAL; } for (; p && *p; p++) { bool found = false; for (size_t j = 0; j < ELEMENTSOF(attributes); j++) { if (*p == attributes[j].character) { unsigned v = attributes[j].value; if (mode == MODE_ADD || mode == MODE_SET) value |= v; mask |= v; found = true; break; } } if (!found) { log_error("Unknown file attribute '%c' on '%s'.", *p, item->path); return -EINVAL; } } if (mode == MODE_SET) mask |= CHATTR_ALL_FL; item->attribute_mask = mask; item->attribute_value = value; item->attribute_set = true; return 0; } int fd_set_attribute(Item *i, int fd, const char *path, const struct stat *st) { struct stat stbuf; if (!i->attribute_set || i->attribute_mask == 0) return 0; if (!st) { if (fstat(fd, &stbuf) < 0) return log_error_errno(-errno, "fstat(%s) failed: %s", path, strerror(errno)); st = &stbuf; } if (!S_ISREG(st->st_mode) && !S_ISDIR(st->st_mode)) { log_debug("Skipping chattr for '%s' (not a regular file or directory).", path); return 0; } unsigned f = i->attribute_value & i->attribute_mask; if (!S_ISDIR(st->st_mode)) f &= ~FS_DIRSYNC_FL; log_debug("%s file attributes 0x%08x on %s", arg_dry_run ? "Would set" : "Setting", f & i->attribute_mask, path); if (!arg_dry_run) { char proc_path[64]; snprintf(proc_path, sizeof(proc_path), "/proc/self/fd/%d", fd); _cleanup_close_ int reopened = open(proc_path, O_RDONLY | O_CLOEXEC); int real_fd = reopened >= 0 ? reopened : fd; unsigned current; if (ioctl(real_fd, FS_IOC_GETFLAGS, ¤t) < 0) { if (errno == ENOTTY || errno == ENOSYS || errno == EOPNOTSUPP) { log_debug("File attributes not supported on '%s', ignoring.", path); return 0; } return log_error_errno(-errno, "Failed to get file attributes on '%s': %s", path, strerror(errno)); } unsigned desired = (current & ~i->attribute_mask) | (f & i->attribute_mask); if (desired != current) { if (ioctl(real_fd, FS_IOC_SETFLAGS, &desired) < 0) { if (errno == ENOTTY || errno == ENOSYS || errno == EOPNOTSUPP) log_debug("Setting file attributes not supported on '%s', ignoring.", path); else log_warning("Failed to set file attributes on '%s': %s (ignoring)", path, strerror(errno)); } } } return 0; } int path_set_attribute(Item *i, const char *path) { if (!i->attribute_set || i->attribute_mask == 0) return 0; _cleanup_close_ int fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_PATH); if (fd < 0) { if (errno == ENOENT) return 0; return -errno; } return fd_set_attribute(i, fd, path, NULL); } int fd_reopen(int fd, int parent_fd, const char *basename, const char *resolved_path, int open_flags) { (void)parent_fd; (void)basename; (void)resolved_path; char procpath[64]; snprintf(procpath, sizeof(procpath), "/proc/self/fd/%d", fd); int new_fd = open(procpath, open_flags); if (new_fd < 0) return -errno; return new_fd; } int acl_get_for_fd(int fd, int parent_fd, const char *basename, const char *resolved_path, acl_type_t type, acl_t *ret) { (void)parent_fd; (void)basename; (void)resolved_path; char procpath[64]; snprintf(procpath, sizeof(procpath), "/proc/self/fd/%d", fd); acl_t a = acl_get_file(procpath, type); if (!a) return -errno; *ret = a; return 0; } int acl_set_for_fd(int fd, int parent_fd, const char *basename, const char *resolved_path, acl_type_t type, acl_t acl) { (void)parent_fd; (void)basename; (void)resolved_path; char procpath[64]; snprintf(procpath, sizeof(procpath), "/proc/self/fd/%d", fd); if (acl_set_file(procpath, type, acl) < 0) return -errno; return 0; } seedfiles/src/platform/linux_chase.c000066400000000000000000000161061521035656300201140ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include #include #include "chase.h" #include "platform/platform.h" #include "util.h" static bool root_is_real(const char *root) { if (!root || !*root) return true; if (root[0] == '/' && root[1] == '\0') return true; return false; } static char *build_result(const char *root_abs, const char *rel) { const char *base = root_abs ? root_abs : "/"; if (!rel || !*rel) return xstrdup(base); char *joined = path_join(base, rel); path_simplify(joined); return joined; } static void done_append(char **done, const char *name) { if (!*done || !**done) { free(*done); *done = xasprintf("/%s", name); return; } char *n = xasprintf("%s/%s", *done, name); free(*done); *done = n; } static void done_pop(char *done) { if (!done || !*done) return; char *slash = strrchr(done, '/'); if (slash) *slash = '\0'; else done[0] = '\0'; } static int open_dir_for_traversal(const char *path) { int fd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_PATH); if (fd < 0) return -errno; return fd; } static int openat_dir_for_traversal(int dir_fd, const char *name) { int fd = openat(dir_fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC | O_PATH); if (fd < 0) return -errno; return fd; } int chase_full(const char *path, const char *root, ChaseFlags flags, char **ret_path, int *ret_fd, int *ret_parent_fd, char **ret_basename) { if (!path || !*path) return -EINVAL; bool have_root = !root_is_real(root); _cleanup_free_ char *root_abs = NULL; if (have_root) { root_abs = xstrdup(root); path_simplify(root_abs); if (streq(root_abs, "/")) { free(root_abs); root_abs = NULL; have_root = false; } else if (!path_is_absolute(root_abs)) { return -EINVAL; } } _cleanup_close_ int root_fd = open_dir_for_traversal(have_root ? root_abs : "/"); if (root_fd < 0) return root_fd; _cleanup_close_ int cur_fd = fcntl(root_fd, F_DUPFD_CLOEXEC, 3); if (cur_fd < 0) return -errno; _cleanup_close_ int parent_fd = fcntl(root_fd, F_DUPFD_CLOEXEC, 3); if (parent_fd < 0) return -errno; _cleanup_free_ char *last_name = NULL; _cleanup_free_ char *done = xstrdup(""); _cleanup_free_ char *todo = NULL; if (have_root && !(flags & CHASE_PREFIX_ROOT)) { const char *inside = path_startswith(path, root_abs); if (!inside) { if (flags & CHASE_WARN) log_warning("Path '%s' lies outside of root '%s'.", path, root_abs); return -EXDEV; } todo = xstrdup(inside); } else { todo = xstrdup(path); } const char *p = todo; while (*p == '/') p++; unsigned symlinks_followed = 0; while (*p) { const char *end = p; while (*end && *end != '/') end++; size_t namelen = (size_t)(end - p); if (namelen == 0) { p = end; continue; } if (namelen > NAME_MAX) return -ENAMETOOLONG; char name[NAME_MAX + 1]; memcpy(name, p, namelen); name[namelen] = '\0'; const char *next = end; while (*next == '/') next++; bool is_last = (*next == '\0'); if (streq(name, ".")) { p = next; continue; } if (streq(name, "..")) { if (!*done) { p = next; continue; } done_pop(done); int nfd = openat_dir_for_traversal(cur_fd, ".."); if (nfd < 0) return nfd; close(parent_fd); parent_fd = fcntl(nfd, F_DUPFD_CLOEXEC, 3); if (parent_fd < 0) { int e = -errno; close(nfd); return e; } close(cur_fd); cur_fd = nfd; free(last_name); last_name = NULL; p = next; continue; } struct stat st; if (fstatat(cur_fd, name, &st, AT_SYMLINK_NOFOLLOW) < 0) { if (errno == ENOENT && (flags & CHASE_NONEXISTENT)) { _cleanup_free_ char *tail = path_join(name, next); char *new_done; if (!*done) new_done = xasprintf("/%s", tail); else new_done = xasprintf("%s/%s", done, tail); free(done); done = new_done; if (ret_path) *ret_path = build_result(root_abs, done); if (ret_fd) *ret_fd = -1; if (ret_parent_fd) { *ret_parent_fd = parent_fd; parent_fd = -1; } if (ret_basename) *ret_basename = xstrdup(name); return 0; } return -errno; } if (S_ISLNK(st.st_mode) && !(is_last && (flags & CHASE_NOFOLLOW))) { if (++symlinks_followed > CHASE_MAX) { if (flags & CHASE_WARN) log_warning( "Too many symbolic links encountered while resolving '%s'.", path); return -ELOOP; } _cleanup_free_ char *target = NULL; ssize_t tlen = readlinkat_dynamic(cur_fd, name, &target); if (tlen < 0) return -tlen; if (tlen == 0) return -EINVAL; char *new_todo; if (target[0] == '/') { int rfd = fcntl(root_fd, F_DUPFD_CLOEXEC, 3); if (rfd < 0) return -errno; close(cur_fd); cur_fd = rfd; int rfd2 = fcntl(root_fd, F_DUPFD_CLOEXEC, 3); if (rfd2 < 0) return -errno; close(parent_fd); parent_fd = rfd2; done[0] = '\0'; const char *tp = target; while (*tp == '/') tp++; new_todo = path_join(tp, next); } else { new_todo = path_join(target, next); } free(todo); todo = new_todo; p = todo; while (*p == '/') p++; continue; } if (S_ISDIR(st.st_mode)) { int nfd = openat_dir_for_traversal(cur_fd, name); if (nfd < 0) return nfd; close(parent_fd); parent_fd = cur_fd; cur_fd = nfd; free(last_name); last_name = xstrdup(name); done_append(&done, name); p = next; continue; } if (!is_last) return -ENOTDIR; done_append(&done, name); if (ret_path) *ret_path = build_result(root_abs, done); if (ret_fd) { int nfd = openat(cur_fd, name, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_PATH); if (nfd < 0) { *ret_fd = -1; } else { *ret_fd = nfd; } } if (ret_parent_fd) { *ret_parent_fd = cur_fd; cur_fd = -1; } if (ret_basename) *ret_basename = xstrdup(name); return 0; } if (ret_path) *ret_path = build_result(root_abs, done); if (ret_fd) { int dup_fd = fcntl(cur_fd, F_DUPFD_CLOEXEC, 3); if (dup_fd < 0) return -errno; *ret_fd = dup_fd; } if (ret_parent_fd) { *ret_parent_fd = parent_fd; parent_fd = -1; } if (ret_basename) *ret_basename = last_name ? xstrdup(last_name) : xstrdup("."); return 0; } int chase(const char *path, const char *root, ChaseFlags flags, char **ret_path, int *ret_fd) { return chase_full(path, root, flags, ret_path, ret_fd, NULL, NULL); } int chase_and_open(const char *path, const char *root, ChaseFlags flags, int open_flags, char **ret_path) { _cleanup_close_ int path_fd = -1; _cleanup_close_ int parent_fd = -1; _cleanup_free_ char *p = NULL; _cleanup_free_ char *base = NULL; int r = chase_full(path, root, flags, &p, &path_fd, &parent_fd, &base); if (r < 0) return r; if (path_fd < 0 && !base) { if (ret_path) { *ret_path = p; p = NULL; } return -ENOENT; } int fd = fd_reopen(path_fd, parent_fd, base, p, open_flags); if (fd < 0) return fd; if (ret_path) { *ret_path = p; p = NULL; } return fd; } seedfiles/src/platform/platform.h000066400000000000000000000014741521035656300174450ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include #include #include #include #include "../parse.h" #include "../specifier.h" extern bool arg_dry_run; int parse_attribute_from_arg(Item *item); int fchmod_opath(int fd, mode_t mode); int fd_set_attribute(Item *i, int fd, const char *path, const struct stat *st); int path_set_attribute(Item *i, const char *path); int fd_reopen(int fd, int parent_fd, const char *basename, const char *resolved_path, int open_flags); int acl_get_for_fd(int fd, int parent_fd, const char *basename, const char *resolved_path, acl_type_t type, acl_t *ret); int acl_set_for_fd(int fd, int parent_fd, const char *basename, const char *resolved_path, acl_type_t type, acl_t acl); seedfiles/src/platform/posix.c000066400000000000000000000033521521035656300167530ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include "platform.h" int fchmod_opath(int fd, mode_t mode) { if (fchmod(fd, mode) < 0) return -errno; return 0; } int parse_attribute_from_arg(Item *item) { log_warning("Setting file attributes is not supported on this platform, ignoring for path '%s'.", item->path); return 0; } int fd_set_attribute(Item *i, int fd, const char *path, const struct stat *st) { (void)i; (void)fd; (void)path; (void)st; if (i->attribute_set) log_debug("File attributes not supported on this platform, ignoring."); return 0; } int path_set_attribute(Item *i, const char *path) { (void)i; (void)path; if (i->attribute_set) log_debug("File attributes not supported on this platform, ignoring."); return 0; } int fd_reopen(int fd, int parent_fd, const char *basename, const char *resolved_path, int open_flags) { (void)fd; (void)resolved_path; if (parent_fd < 0 || !basename) return -EINVAL; int new_fd = openat(parent_fd, basename, open_flags | O_NOFOLLOW); if (new_fd < 0) return -errno; return new_fd; } int acl_get_for_fd(int fd, int parent_fd, const char *basename, const char *resolved_path, acl_type_t type, acl_t *ret) { (void)fd; (void)parent_fd; (void)basename; if (!resolved_path) return -EINVAL; acl_t a = acl_get_file(resolved_path, type); if (!a) return -errno; *ret = a; return 0; } int acl_set_for_fd(int fd, int parent_fd, const char *basename, const char *resolved_path, acl_type_t type, acl_t acl) { (void)fd; (void)parent_fd; (void)basename; if (!resolved_path) return -EINVAL; if (acl_set_file(resolved_path, type, acl) < 0) return -errno; return 0; } seedfiles/src/platform/posix_chase.c000066400000000000000000000154671521035656300201300ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include #include #include "chase.h" #include "platform/platform.h" #include "util.h" static bool root_is_real(const char *root) { if (!root || !*root) return true; if (root[0] == '/' && root[1] == '\0') return true; return false; } static void done_append(char **done, const char *name) { if (!*done || !**done) { free(*done); *done = xasprintf("/%s", name); return; } char *n = xasprintf("%s/%s", *done, name); free(*done); *done = n; } static void done_pop(char *done) { if (!done || !*done) return; char *slash = strrchr(done, '/'); if (slash) *slash = '\0'; else done[0] = '\0'; } static char *build_result(const char *root_abs, const char *rel) { const char *base = root_abs ? root_abs : "/"; if (!rel || !*rel) return xstrdup(base); char *joined = path_join(base, rel); path_simplify(joined); return joined; } static char *build_full_path(const char *root_abs, const char *done, const char *name) { const char *base = root_abs ? root_abs : "/"; const char *middle = done ? done : ""; char *ret; if (asprintf(&ret, "%s/%s/%s", base, middle, name) < 0) return NULL; return path_simplify(ret); } int chase_full(const char *path, const char *root, ChaseFlags flags, char **ret_path, int *ret_fd, int *ret_parent_fd, char **ret_basename) { if (!path || !*path) return -EINVAL; bool have_root = !root_is_real(root); _cleanup_free_ char *root_abs = NULL; if (have_root) { root_abs = xstrdup(root); path_simplify(root_abs); if (streq(root_abs, "/")) { free(root_abs); root_abs = NULL; have_root = false; } else if (!path_is_absolute(root_abs)) { return -EINVAL; } } _cleanup_free_ char *last_name = NULL; _cleanup_free_ char *done = xstrdup(""); _cleanup_free_ char *todo = NULL; if (have_root && !(flags & CHASE_PREFIX_ROOT)) { const char *inside = path_startswith(path, root_abs); if (!inside) { if (flags & CHASE_WARN) log_warning("Path '%s' lies outside of root '%s'.", path, root_abs); return -EXDEV; } todo = xstrdup(inside); } else { todo = xstrdup(path); } const char *p = todo; while (*p == '/') p++; unsigned symlinks_followed = 0; while (*p) { const char *end = p; while (*end && *end != '/') end++; size_t namelen = (size_t)(end - p); if (namelen == 0) { p = end; continue; } if (namelen > NAME_MAX) return -ENAMETOOLONG; char name[NAME_MAX + 1]; memcpy(name, p, namelen); name[namelen] = '\0'; const char *next = end; while (*next == '/') next++; bool is_last = (*next == '\0'); if (streq(name, ".")) { p = next; continue; } if (streq(name, "..")) { if (!*done) { p = next; continue; } done_pop(done); if (have_root && *done && !path_startswith(done, root_abs)) return -EXDEV; free(last_name); last_name = NULL; p = next; continue; } struct stat st; _cleanup_free_ char *fullpath = build_full_path(root_abs, done, name); if (!fullpath) return -errno; if (lstat(fullpath, &st) != 0) { if (errno == ENOENT && (flags & CHASE_NONEXISTENT)) { _cleanup_free_ char *tail = path_join(name, next); char *new_done; if (!*done) new_done = xasprintf("/%s", tail); else new_done = xasprintf("%s/%s", done, tail); free(done); done = new_done; _cleanup_free_ char *full_path = build_result(root_abs, done); done_pop(done); _cleanup_free_ char *parent_path = build_result(root_abs, done); if (ret_path) *ret_path = xstrdup(full_path); if (ret_fd) { *ret_fd = -1; } if (ret_parent_fd) { *ret_parent_fd = open(parent_path, O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (*ret_parent_fd < 0) return -errno; } if (ret_basename) *ret_basename = xstrdup(name); return 0; } return -errno; } if (S_ISLNK(st.st_mode) && !(is_last && (flags & CHASE_NOFOLLOW))) { if (++symlinks_followed > CHASE_MAX) { if (flags & CHASE_WARN) log_warning( "Too many symbolic links encountered while resolving '%s'.", path); return -ELOOP; } _cleanup_free_ char *target = NULL; ssize_t tlen = readlink_dynamic(fullpath, &target); if (tlen < 0) return -tlen; if (tlen == 0) return -EINVAL; char *new_todo; if (target[0] == '/') { done[0] = '\0'; const char *tp = target; while (*tp == '/') tp++; new_todo = path_join(tp, next); } else { new_todo = path_join(target, next); } free(target); free(todo); todo = new_todo; p = todo; while (*p == '/') p++; continue; } if (S_ISDIR(st.st_mode)) { free(last_name); last_name = xstrdup(name); done_append(&done, name); p = next; continue; } if (!is_last) return -ENOTDIR; done_append(&done, name); _cleanup_free_ char *full_path = build_result(root_abs, done); done_pop(done); _cleanup_free_ char *parent_path = build_result(root_abs, done); if (ret_path) *ret_path = xstrdup(full_path); if (ret_fd) { *ret_fd = open(full_path, O_RDONLY | O_CLOEXEC | (flags & CHASE_NOFOLLOW ? O_NOFOLLOW : 0)); if (*ret_fd < 0) return -errno; } if (ret_parent_fd) { *ret_parent_fd = open(parent_path, O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (*ret_parent_fd < 0) return -errno; } if (ret_basename) *ret_basename = xstrdup(name); return 0; } _cleanup_free_ char *full_path = build_result(root_abs, done); done_pop(done); _cleanup_free_ char *parent_path = build_result(root_abs, done); if (ret_path) *ret_path = xstrdup(full_path); if (ret_fd) { *ret_fd = open(full_path, O_RDONLY | O_CLOEXEC | (flags & CHASE_NOFOLLOW ? O_NOFOLLOW : 0)); if (*ret_fd < 0) return -errno; } if (ret_parent_fd) { *ret_parent_fd = open(parent_path, O_RDONLY | O_DIRECTORY | O_CLOEXEC); if (*ret_parent_fd < 0) return -errno; } if (ret_basename) *ret_basename = last_name ? xstrdup(last_name) : xstrdup("."); return 0; } int chase(const char *path, const char *root, ChaseFlags flags, char **ret_path, int *ret_fd) { return chase_full(path, root, flags, ret_path, ret_fd, NULL, NULL); } int chase_and_open(const char *path, const char *root, ChaseFlags flags, int open_flags, char **ret_path) { _cleanup_close_ int path_fd = -1; _cleanup_close_ int parent_fd = -1; _cleanup_free_ char *p = NULL; _cleanup_free_ char *base = NULL; int r = chase_full(path, root, flags, &p, &path_fd, &parent_fd, &base); if (r < 0) return r; if (path_fd < 0 && !base) { if (ret_path) { *ret_path = p; p = NULL; } return -ENOENT; } int fd = fd_reopen(path_fd, parent_fd, base, p, open_flags); if (fd < 0) return fd; if (ret_path) { *ret_path = p; p = NULL; } return fd; } seedfiles/src/specifier.c000066400000000000000000000105551521035656300157410ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include #include #include #include "specifier.h" #include "util.h" static const char *resolve_specifier(char spec, bool user_mode) { static char uid_buf[32], gid_buf[32]; switch (spec) { case 'm': return get_machine_id(); case 'b': return get_boot_id(); case 'H': { static char host[256]; static bool cached = false; if (!cached) { if (gethostname(host, sizeof(host)) < 0) return NULL; host[sizeof(host) - 1] = '\0'; cached = true; } return host; } case 'v': { static struct utsname uts; static bool cached = false; if (!cached) { if (uname(&uts) < 0) return NULL; cached = true; } return uts.release; } case 'u': { struct passwd *pw = getpwuid(getuid()); return pw ? pw->pw_name : NULL; } case 'U': { snprintf(uid_buf, sizeof(uid_buf), "%u", getuid()); return uid_buf; } case 'g': { struct group *gr = getgrgid(getgid()); return gr ? gr->gr_name : NULL; } case 'G': { snprintf(gid_buf, sizeof(gid_buf), "%u", getgid()); return gid_buf; } case 'h': { struct passwd *pw = getpwuid(getuid()); return pw ? pw->pw_dir : NULL; } case 't': if (user_mode) { const char *rt = getenv("XDG_RUNTIME_DIR"); return rt ? rt : NULL; } return "/run"; case 'S': if (user_mode) { static char *state = NULL; static bool cached = false; if (!cached) { const char *d = getenv("XDG_STATE_HOME"); if (d) asprintf(&state, "%s", d); else { struct passwd *pw = getpwuid(getuid()); if (!pw) return NULL; asprintf(&state, "%s/.local/state", pw->pw_dir); } cached = true; } return state; } return "/var/lib"; case 'C': if (user_mode) { static char *cache = NULL; static bool cached = false; if (!cached) { const char *d = getenv("XDG_CACHE_HOME"); if (d) asprintf(&cache, "%s", d); else { struct passwd *pw = getpwuid(getuid()); if (!pw) return NULL; asprintf(&cache, "%s/.cache", pw->pw_dir); } cached = true; } return cache; } return "/var/cache"; case 'L': if (user_mode) { static char *logs = NULL; static bool cached = false; if (!cached) { const char *d = getenv("XDG_STATE_HOME"); if (d) asprintf(&logs, "%s/log", d); else { struct passwd *pw = getpwuid(getuid()); if (!pw) return NULL; asprintf(&logs, "%s/.local/state/log", pw->pw_dir); } cached = true; } return logs; } return "/var/log"; case 'T': { const char *t = getenv("TMPDIR"); if (!t) t = getenv("TEMP"); if (!t) t = getenv("TMP"); return t ? t : "/tmp"; } case 'V': { const char *t = getenv("TMPDIR"); if (!t) t = getenv("TEMP"); if (!t) t = getenv("TMP"); return t ? t : "/var/tmp"; } default: return NULL; } } int specifier_expand(const char *s, bool user_mode, char **ret) { if (!s) { *ret = NULL; return 0; } size_t len = 0; for (const char *p = s; *p;) { if (*p == '%' && p[1]) { if (p[1] == '%') { len++; p += 2; continue; } const char *val = resolve_specifier(p[1], user_mode); if (!val) { log_warning("Unknown or failed specifier '%%%c'", p[1]); len += 2; p += 2; continue; } len += strlen(val); p += 2; } else { len++; p++; } } char *out = malloc(len + 1); if (!out) return -ENOMEM; char *d = out; for (const char *p = s; *p;) { if (*p == '%' && p[1]) { if (p[1] == '%') { *d++ = '%'; p += 2; continue; } const char *val = resolve_specifier(p[1], user_mode); if (!val) { *d++ = *p++; *d++ = *p++; continue; } size_t vl = strlen(val); memcpy(d, val, vl); d += vl; p += 2; } else { *d++ = *p++; } } *d = '\0'; *ret = out; return 0; } seedfiles/src/specifier.h000066400000000000000000000002221521035656300157340ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include int specifier_expand(const char *s, bool user_mode, char **ret); seedfiles/src/util.c000066400000000000000000000404601521035656300147430ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include "util.h" #include "chase.h" #include "offline-password.h" int log_level = LOG_INFO; char *arg_root = NULL; const char *startswith(const char *s, const char *prefix) { size_t pl = strlen(prefix); if (strncmp(s, prefix, pl) == 0) return s + pl; return NULL; } bool endswith(const char *s, const char *suffix) { size_t sl = strlen(s); size_t xl = strlen(suffix); if (xl > sl) return false; return memcmp(s + sl - xl, suffix, xl) == 0; } char *strstrip(char *s) { while (*s && isspace((unsigned char)*s)) s++; char *e = s + strlen(s); while (e > s && isspace((unsigned char)e[-1])) e--; *e = '\0'; return s; } char *xasprintf(const char *fmt, ...) { va_list ap; char *r; va_start(ap, fmt); if (vasprintf(&r, fmt, ap) < 0) { va_end(ap); abort(); } va_end(ap); return r; } int cunescape(const char *s, char **ret) { size_t len = strlen(s); char *buf = malloc(len + 1); if (!buf) return -ENOMEM; char *o = buf; for (const char *p = s; *p;) { if (*p != '\\') { *o++ = *p++; continue; } p++; if (!*p) { *o++ = '\\'; break; } switch (*p) { case 'a': *o++ = '\a'; p++; break; case 'b': *o++ = '\b'; p++; break; case 'f': *o++ = '\f'; p++; break; case 'n': *o++ = '\n'; p++; break; case 'r': *o++ = '\r'; p++; break; case 't': *o++ = '\t'; p++; break; case 'v': *o++ = '\v'; p++; break; case '\\': *o++ = '\\'; p++; break; case '"': *o++ = '"'; p++; break; case '\'': *o++ = '\''; p++; break; case 'x': { p++; if (!isxdigit((unsigned char)p[0])) { *o++ = '\\'; *o++ = 'x'; break; } char hex[3] = {p[0], 0, 0}; p++; if (isxdigit((unsigned char)*p)) hex[1] = *p++; *o++ = (char)strtoul(hex, NULL, 16); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { unsigned val = (unsigned)(*p++ - '0'); if (*p >= '0' && *p <= '7') val = val * 8 + (unsigned)(*p++ - '0'); if (*p >= '0' && *p <= '7') val = val * 8 + (unsigned)(*p++ - '0'); *o++ = (char)(val & 0xff); break; } default: *o++ = '\\'; *o++ = *p++; break; } } *o = '\0'; *ret = buf; return 0; } int extract_first_word(const char **p, char **ret, const char *separators, int flags) { if (!separators) separators = " \t"; while (**p && strchr(separators, **p)) (*p)++; if (**p == '\0') { *ret = NULL; return 0; } size_t cap = 64, len = 0; char *buf = malloc(cap); if (!buf) return -ENOMEM; #define PUSH(c) \ do { \ if (len + 1 >= cap) { \ cap *= 2; \ char *nb = realloc(buf, cap); \ if (!nb) { \ free(buf); \ return -ENOMEM; \ } \ buf = nb; \ } \ buf[len++] = (c); \ } while (0) bool quote_single = false, quote_double = false; for (; **p; (*p)++) { char c = **p; if (c == '\\' && !quote_single) { (*p)++; if (**p == '\0') { if (flags & EXTRACT_RELAX) break; free(buf); return -EINVAL; } if (flags & EXTRACT_CUNESCAPE) { switch (**p) { case 'n': PUSH('\n'); continue; case 't': PUSH('\t'); continue; case 'r': PUSH('\r'); continue; case '\\': PUSH('\\'); continue; case '"': PUSH('"'); continue; case '\'': PUSH('\''); continue; case ' ': PUSH(' '); continue; default: if (flags & EXTRACT_RETAIN_ESCAPE) PUSH('\\'); PUSH(**p); continue; } } if (flags & EXTRACT_RETAIN_ESCAPE) PUSH('\\'); PUSH(**p); continue; } if (c == '\'' && !(flags & EXTRACT_UNQUOTE ? quote_double : false)) { if (flags & EXTRACT_UNQUOTE) { quote_single = !quote_single; continue; } PUSH(c); continue; } if (c == '"' && !(flags & EXTRACT_UNQUOTE ? quote_single : false)) { if (flags & EXTRACT_UNQUOTE) { quote_double = !quote_double; continue; } PUSH(c); continue; } if (!quote_single && !quote_double && strchr(separators, c)) break; PUSH(c); } #undef PUSH if ((quote_single || quote_double) && !(flags & EXTRACT_RELAX)) { free(buf); return -EINVAL; } buf[len] = '\0'; *ret = buf; return 1; } char *path_simplify(char *p) { if (!p || !*p) return p; char *r = p, *w = p; bool slash = false; for (; *r; r++) { if (*r == '/') { if (slash) continue; slash = true; if (r[1] == '.' && (r[2] == '/' || r[2] == '\0')) { *w++ = '/'; r++; continue; } } else { slash = false; } *w++ = *r; } if (w > p + 1 && w[-1] == '/') w--; *w = '\0'; return p; } char *path_join(const char *dir, const char *file) { if (!dir || !*dir) return xstrdup(file); if (!file || !*file) return xstrdup(dir); size_t dl = strlen(dir); bool ds = dir[dl - 1] == '/'; bool fs = file[0] == '/'; if (ds && fs) return xasprintf("%s%s", dir, file + 1); if (!ds && !fs) return xasprintf("%s/%s", dir, file); return xasprintf("%s%s", dir, file); } const char *path_startswith(const char *path, const char *prefix) { if (!path || !prefix) return NULL; for (;;) { while (*path == '/') path++; while (*prefix == '/') prefix++; if (*prefix == '\0') return path; if (*path == '\0') return NULL; const char *a = path, *b = prefix; while (*a && *a != '/' && *b && *b != '/' && *a == *b) { a++; b++; } if (*b && *b != '/') return NULL; if (*a && *a != '/') return NULL; path = a; prefix = b; } } char *path_parent(const char *path) { if (!path || !*path) return xstrdup("."); size_t len = strlen(path); while (len > 1 && path[len - 1] == '/') len--; if (len == 1 && path[0] == '/') return NULL; while (len > 0 && path[len - 1] != '/') len--; if (len == 0) return xstrdup("."); while (len > 1 && path[len - 1] == '/') len--; return xstrndup(path, len); } const char *path_basename(const char *path) { if (!path) return NULL; const char *b = strrchr(path, '/'); return b ? b + 1 : path; } int parse_duration(const char *s, uint64_t *ret) { if (!s || !*s) return -EINVAL; if (streq(s, "infinity") || streq(s, "-")) { *ret = USEC_INFINITY; return 0; } static const struct { const char *suffix; uint64_t mult; } table[] = { {"usec", 1}, {"us", 1}, {"msec", USEC_PER_MSEC}, {"ms", USEC_PER_MSEC}, {"seconds", USEC_PER_SEC}, {"second", USEC_PER_SEC}, {"sec", USEC_PER_SEC}, {"s", USEC_PER_SEC}, {"minutes", USEC_PER_MIN}, {"minute", USEC_PER_MIN}, {"min", USEC_PER_MIN}, {"m", USEC_PER_MIN}, {"hours", USEC_PER_HOUR}, {"hour", USEC_PER_HOUR}, {"hr", USEC_PER_HOUR}, {"h", USEC_PER_HOUR}, {"days", USEC_PER_DAY}, {"day", USEC_PER_DAY}, {"d", USEC_PER_DAY}, {"weeks", USEC_PER_WEEK}, {"week", USEC_PER_WEEK}, {"w", USEC_PER_WEEK}, }; const char *p = s; uint64_t total = 0; bool found = false; while (*p) { while (*p && isspace((unsigned char)*p)) p++; if (!*p) break; if (!isdigit((unsigned char)*p)) return -EINVAL; char *end; errno = 0; unsigned long long val = strtoull(p, &end, 10); if (errno) return -errno; p = end; while (*p && isspace((unsigned char)*p)) p++; uint64_t mult = USEC_PER_SEC; for (size_t i = 0; i < ELEMENTSOF(table); i++) { const char *after = startswith(p, table[i].suffix); if (after) { mult = table[i].mult; p = after; break; } } total += (uint64_t)val * mult; found = true; } if (!found) return -EINVAL; *ret = total; return 0; } int parse_uid(const char *s, uid_t *ret) { if (!s || !*s) return -EINVAL; char *end; errno = 0; unsigned long val = strtoul(s, &end, 10); if (errno) return -errno; if (*end != '\0') return -EINVAL; if (val > (unsigned long)UINT32_MAX) return -ERANGE; *ret = (uid_t)val; return 0; } int parse_gid(const char *s, gid_t *ret) { uid_t tmp; int r = parse_uid(s, &tmp); if (r < 0) return r; *ret = (gid_t)tmp; return 0; } int resolve_user(const char *name, uid_t *ret) { if (!name || !*name || streq(name, "-")) return -EINVAL; if (parse_uid(name, ret) == 0) return 0; if (arg_root) return name_to_uid_offline(arg_root, name, ret); errno = 0; struct passwd *pw = getpwnam(name); if (!pw) return errno > 0 ? -errno : -ESRCH; *ret = pw->pw_uid; return 0; } int resolve_group(const char *name, gid_t *ret) { if (!name || !*name || streq(name, "-")) return -EINVAL; if (parse_gid(name, ret) == 0) return 0; if (arg_root) return name_to_gid_offline(arg_root, name, ret); errno = 0; struct group *gr = getgrnam(name); if (!gr) return errno > 0 ? -errno : -ESRCH; *ret = gr->gr_gid; return 0; } int parse_mode(const char *s, mode_t *ret) { if (!s || !*s) return -EINVAL; char *end; errno = 0; unsigned long val = strtoul(s, &end, 8); if (errno) return -errno; if (*end != '\0') return -EINVAL; if (val > 07777) return -ERANGE; *ret = (mode_t)val; return 0; } int safe_open(const char *path, int flags, mode_t mode, unsigned expected_type) { int fd = open(path, flags | O_NOFOLLOW | O_CLOEXEC, mode); if (fd < 0) return -errno; if (expected_type != 0) { struct stat st; if (fstat(fd, &st) < 0) { int e = errno; close(fd); return -e; } if ((st.st_mode & S_IFMT) != expected_type) { close(fd); return -ELOOP; } } return fd; } int open_dir(const char *path) { int fd = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (fd < 0) return -errno; return fd; } int open_dir_at(int dir_fd, const char *path) { int fd = openat(dir_fd, path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (fd < 0) return -errno; return fd; } int open_parent(const char *path, const char **ret_basename) { const char *bn = path_basename(path); if (!bn || !*bn || streq(bn, "/")) return -EINVAL; _cleanup_free_ char *parent = path_parent(path); if (!parent) return -ENOMEM; int fd = open_dir(parent); if (fd < 0) return fd; *ret_basename = bn; return fd; } DIR *xfdopendir(int fd) { int fd2 = fcntl(fd, F_DUPFD_CLOEXEC, 3); if (fd2 < 0) return NULL; DIR *d = fdopendir(fd2); if (!d) { close(fd2); return NULL; } return d; } int mkdirat_safe(int dir_fd, const char *name, mode_t mode) { if (mkdirat(dir_fd, name, mode) < 0) { if (errno == EEXIST) { int fd = openat(dir_fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (fd < 0) { if (errno == ENOTDIR || errno == ELOOP) return -EEXIST; return -errno; } close(fd); return 0; } return -errno; } return 0; } int read_fd_full(int fd, char **ret, size_t *ret_size) { size_t alloc = 4096; char *buf = malloc(alloc); if (!buf) return -ENOMEM; size_t total = 0; for (;;) { if (total + 1 >= alloc) { if (alloc > SIZE_MAX / 2) { free(buf); return -ENOMEM; } alloc *= 2; char *nb = realloc(buf, alloc); if (!nb) { free(buf); return -ENOMEM; } buf = nb; } ssize_t n = read(fd, buf + total, alloc - total - 1); if (n < 0) { if (errno == EINTR) continue; free(buf); return -errno; } if (n == 0) break; total += (size_t)n; } buf[total] = '\0'; *ret = buf; if (ret_size) *ret_size = total; return 0; } int read_file_full(const char *path, char **ret, size_t *ret_size) { _cleanup_close_ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); if (fd < 0) return -errno; struct stat st; if (fstat(fd, &st) < 0) return -errno; if (!S_ISREG(st.st_mode)) return -EINVAL; return read_fd_full(fd, ret, ret_size); } int rm_rf_children(int dir_fd) { DIR *d = xfdopendir(dir_fd); if (!d) return -errno; int ret = 0; struct dirent *de; errno = 0; while ((de = readdir(d))) { if (streq(de->d_name, ".") || streq(de->d_name, "..")) continue; bool is_dir = false; #ifdef _DIRENT_HAVE_D_TYPE if (de->d_type == DT_DIR) is_dir = true; else if (de->d_type != DT_UNKNOWN) is_dir = false; else #endif { struct stat st; if (fstatat(dir_fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) { if (ret == 0) ret = -errno; continue; } is_dir = S_ISDIR(st.st_mode); } if (is_dir) { int sub_fd = openat(dir_fd, de->d_name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (sub_fd < 0) { if (ret == 0) ret = -errno; continue; } int r = rm_rf_children(sub_fd); close(sub_fd); if (r < 0 && ret == 0) ret = r; if (unlinkat(dir_fd, de->d_name, AT_REMOVEDIR) < 0 && ret == 0) ret = -errno; } else { if (unlinkat(dir_fd, de->d_name, 0) < 0 && ret == 0) ret = -errno; } errno = 0; } if (errno && ret == 0) ret = -errno; closedir(d); return ret; } int rm_rf(const char *path) { _cleanup_free_ char *resolved = NULL; if (arg_root) { int cr = chase(path, arg_root, CHASE_PREFIX_ROOT | CHASE_NOFOLLOW | CHASE_NONEXISTENT, &resolved, NULL); if (cr == -ENOENT) return 0; if (cr < 0) return cr; path = resolved; } if (unlink(path) == 0) return 0; if (errno != EISDIR && errno != EPERM) return -errno; _cleanup_close_ int fd = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (fd < 0) return -errno; int r = rm_rf_children(fd); if (rmdir(path) < 0 && r == 0) r = -errno; return r; } const char *get_boot_id(void) { static char buf[37]; static bool cached = false; if (cached) return buf; _cleanup_free_ char *contents = NULL; if (read_file_full("/proc/sys/kernel/random/boot_id", &contents, NULL) < 0) return NULL; char *s = strstrip(contents); size_t l = strlen(s); if (l >= sizeof(buf)) l = sizeof(buf) - 1; memcpy(buf, s, l); buf[l] = '\0'; cached = true; return buf; } const char *get_machine_id(void) { static char buf[33]; static bool cached = false; if (cached) return buf; _cleanup_free_ char *contents = NULL; if (arg_root) { _cleanup_close_ int fd = chase_and_open("/etc/machine-id", arg_root, CHASE_PREFIX_ROOT, O_RDONLY | O_CLOEXEC, NULL); if (fd < 0) return NULL; if (read_fd_full(fd, &contents, NULL) < 0) return NULL; } else { if (read_file_full("/etc/machine-id", &contents, NULL) < 0) return NULL; } char *s = strstrip(contents); size_t l = strlen(s); if (l >= sizeof(buf)) l = sizeof(buf) - 1; memcpy(buf, s, l); buf[l] = '\0'; cached = true; return buf; } ssize_t readlink_dynamic(const char *restrict path, char **buf) { size_t bufsize = 256; *buf = NULL; for (;;) { *buf = realloc(*buf, bufsize); if (!*buf) return -ENOMEM; ssize_t len = readlink(path, *buf, bufsize); if (len < 0) return -errno; if ((size_t)len < bufsize) { (*buf)[len] = '\0'; return len; } bufsize *= 2; } } ssize_t readlinkat_dynamic(int dirfd, const char *restrict path, char **buf) { size_t bufsize = 256; *buf = NULL; for (;;) { *buf = realloc(*buf, bufsize); if (!*buf) return -ENOMEM; ssize_t len = readlinkat(dirfd, path, *buf, bufsize); if (len < 0) return -errno; if ((size_t)len < bufsize) { (*buf)[len] = '\0'; return len; } bufsize *= 2; } } seedfiles/src/util.h000066400000000000000000000114301521035656300147430ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define _cleanup_(f) __attribute__((cleanup(f))) #define _unused_ __attribute__((unused)) #ifndef O_PATH #define O_PATH 0 #endif static inline void freep(void *p) { free(*(void **)p); } static inline void closep(int *fdp) { if (*fdp >= 0) close(*fdp); } static inline void closedirp(DIR **dp) { if (*dp) closedir(*dp); } static inline void fclosep(FILE **fp) { if (*fp) fclose(*fp); } #define _cleanup_free_ _cleanup_(freep) #define _cleanup_close_ _cleanup_(closep) #define _cleanup_closedir_ _cleanup_(closedirp) #define _cleanup_fclose_ _cleanup_(fclosep) #define ELEMENTSOF(x) (sizeof(x) / sizeof((x)[0])) #define streq(a, b) (strcmp((a), (b)) == 0) #define strneq(a, b, n) (strncmp((a), (b), (n)) == 0) #define MAX(a, b) \ ({ \ typeof(a) _a = (a); \ typeof(b) _b = (b); \ _a > _b ? _a : _b; \ }) #define MIN(a, b) \ ({ \ typeof(a) _a = (a); \ typeof(b) _b = (b); \ _a < _b ? _a : _b; \ }) #define free_and_replace(a, b) \ ({ \ typeof(a) *_a = &(a); \ typeof(b) *_b = &(b); \ free(*_a); \ *_a = *_b; \ *_b = NULL; \ 0; \ }) extern int log_level; extern char *arg_root; #define LOG_DEBUG 0 #define LOG_INFO 1 #define LOG_WARNING 2 #define LOG_ERROR 3 #define log_full(lvl, fmt, ...) \ do { \ if ((lvl) >= log_level) \ fprintf(stderr, "seedfiles: " fmt "\n", ##__VA_ARGS__); \ } while (0) #define log_debug(fmt, ...) log_full(LOG_DEBUG, fmt, ##__VA_ARGS__) #define log_info(fmt, ...) log_full(LOG_INFO, fmt, ##__VA_ARGS__) #define log_warning(fmt, ...) log_full(LOG_WARNING, fmt, ##__VA_ARGS__) #define log_error(fmt, ...) log_full(LOG_ERROR, fmt, ##__VA_ARGS__) #define log_error_errno(e, fmt, ...) \ ({ \ int _e = (e); \ log_error(fmt, ##__VA_ARGS__); \ _e; \ }) const char *startswith(const char *s, const char *prefix); bool endswith(const char *s, const char *suffix); char *strstrip(char *s); static inline char *xstrdup(const char *s) { if (!s) return NULL; char *r = strdup(s); if (!r) abort(); return r; } static inline char *xstrndup(const char *s, size_t n) { if (!s) return NULL; char *r = strndup(s, n); if (!r) abort(); return r; } char *xasprintf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); int cunescape(const char *s, char **ret); enum { EXTRACT_RELAX = 1 << 0, EXTRACT_CUNESCAPE = 1 << 1, EXTRACT_UNQUOTE = 1 << 2, EXTRACT_RETAIN_ESCAPE = 1 << 3, }; int extract_first_word(const char **p, char **ret, const char *separators, int flags); static inline bool path_is_absolute(const char *p) { return p && p[0] == '/'; } char *path_simplify(char *p); char *path_join(const char *dir, const char *file); const char *path_startswith(const char *path, const char *prefix); char *path_parent(const char *path); const char *path_basename(const char *path); #define USEC_PER_SEC ((uint64_t)1000000ULL) #define USEC_PER_MSEC ((uint64_t)1000ULL) #define USEC_PER_MIN (USEC_PER_SEC * 60ULL) #define USEC_PER_HOUR (USEC_PER_MIN * 60ULL) #define USEC_PER_DAY (USEC_PER_HOUR * 24ULL) #define USEC_PER_WEEK (USEC_PER_DAY * 7ULL) #define USEC_INFINITY UINT64_MAX int parse_duration(const char *s, uint64_t *ret); int parse_uid(const char *s, uid_t *ret); int parse_gid(const char *s, gid_t *ret); int resolve_user(const char *name, uid_t *ret); int resolve_group(const char *name, gid_t *ret); int parse_mode(const char *s, mode_t *ret); static inline int safe_close(int fd) { if (fd >= 0) close(fd); return -1; } int safe_open(const char *path, int flags, mode_t mode, unsigned expected_type); int open_dir(const char *path); int open_dir_at(int dir_fd, const char *path); int open_parent(const char *path, const char **ret_basename); DIR *xfdopendir(int fd); int mkdirat_safe(int dir_fd, const char *name, mode_t mode); int read_file_full(const char *path, char **ret, size_t *ret_size); int read_fd_full(int fd, char **ret, size_t *ret_size); int rm_rf_children(int dir_fd); int rm_rf(const char *path); static inline uint64_t now_usec(void) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return (uint64_t)ts.tv_sec * USEC_PER_SEC + (uint64_t)ts.tv_nsec / 1000; } const char *get_boot_id(void); const char *get_machine_id(void); ssize_t readlink_dynamic(const char *restrict path, char **buf); ssize_t readlinkat_dynamic(int dirfd, const char *restrict path, char **buf); seedfiles/test/000077500000000000000000000000001521035656300140065ustar00rootroot00000000000000seedfiles/test/integration/000077500000000000000000000000001521035656300163315ustar00rootroot00000000000000seedfiles/test/integration/lib.sh000077500000000000000000000051551521035656300174440ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail TEST_COUNT=0 TEST_FAILED=0 TESTDIR="" SEEDFILES="" setup() { SEEDFILES="${1:?Usage: setup }" TESTDIR="$(mktemp -d /tmp/seedfiles-integ-XXXXXX)" TEST_COUNT=0 TEST_FAILED=0 trap teardown EXIT } teardown() { if [ -n "$TESTDIR" ] && [ -d "$TESTDIR" ]; then rm -rf "$TESTDIR" fi } write_conf() { printf '%s\n' "$@" > "$TESTDIR/conf" } plan() { echo "1..$1" } ok() { TEST_COUNT=$((TEST_COUNT + 1)) echo "ok $TEST_COUNT - $1" } not_ok() { TEST_COUNT=$((TEST_COUNT + 1)) TEST_FAILED=$((TEST_FAILED + 1)) echo "not ok $TEST_COUNT - $1${2:+ # $2}" } run_test() { local desc="$1" shift local rc=0 "$@" >/dev/null 2>&1 || rc=$? if [ $rc -eq 0 ]; then ok "$desc" else not_ok "$desc" "exit code $rc" fi } run_test_fail() { local desc="$1" shift local rc=0 "$@" >/dev/null 2>&1 || rc=$? if [ $rc -ne 0 ]; then ok "$desc" else not_ok "$desc" "expected failure but succeeded" fi } assert_exists() { if [ -e "$1" ]; then ok "$1 exists" else not_ok "$1 exists" "path missing" fi } assert_not_exists() { if [ ! -e "$1" ]; then ok "$1 does not exist" else not_ok "$1 does not exist" "path exists" fi } assert_file_equals() { if [ ! -f "$1" ]; then not_ok "$1 content matches" "file missing" return fi local content content="$(cat "$1")" if [ "$content" = "$2" ]; then ok "$1 content matches" else not_ok "$1 content matches" "got '$content', expected '$2'" fi } assert_symlink_to() { if [ ! -L "$1" ]; then not_ok "$1 symlink target" "not a symlink" return fi local target target="$(readlink "$1")" if [ "$target" = "$2" ]; then ok "$1 symlink target" else not_ok "$1 symlink target" "got '$target', expected '$2'" fi } assert_mode() { if [ ! -e "$1" ]; then not_ok "$1 mode is $2" "path missing" return fi local mode mode="$(stat -c '%a' "$1")" if [ "$mode" = "$2" ]; then ok "$1 mode is $2" else not_ok "$1 mode is $2" "got $mode" fi } assert_dir_empty() { if [ ! -d "$1" ]; then not_ok "$1 is empty directory" "not a directory" return fi if [ -z "$(ls -A "$1")" ]; then ok "$1 is empty directory" else not_ok "$1 is empty directory" "directory not empty" fi } done_testing() { if [ "$TEST_FAILED" -gt 0 ]; then exit 1 fi } seedfiles/test/integration/test-combo-idempotent.sh000077500000000000000000000013171521035656300231140ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 6 # combined create and remove mkdir -p "$TESTDIR/combo-rm" touch "$TESTDIR/combo-rm/old-file" write_conf \ "d $TESTDIR/combo-new 0755 - - -" \ "R $TESTDIR/combo-rm" run_test "combined create remove command" "$SEEDFILES" --create --remove "$TESTDIR/conf" assert_exists "$TESTDIR/combo-new" assert_not_exists "$TESTDIR/combo-rm" # idempotent create write_conf "d $TESTDIR/idempotent 0755 - - -" run_test "idempotent first create" "$SEEDFILES" --create "$TESTDIR/conf" run_test "idempotent second create" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/idempotent" done_testing seedfiles/test/integration/test-copy.sh000077500000000000000000000102601521035656300206160ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 24 # copy files mkdir -p "$TESTDIR/copy-src" echo "copy-data" > "$TESTDIR/copy-src/data.txt" write_conf "C $TESTDIR/copy-dst - - - - $TESTDIR/copy-src" run_test "copy files command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/copy-dst/data.txt" assert_file_equals "$TESTDIR/copy-dst/data.txt" "copy-data" # copy preserves mtime REF_TS="199807060102.03" REF_EPOCH=$(date -d "1998-07-06 01:02:03" +%s) mkdir -p "$TESTDIR/copy-mtime-src/sub" echo "top" > "$TESTDIR/copy-mtime-src/top.txt" echo "nested" > "$TESTDIR/copy-mtime-src/sub/nested.txt" touch -m -t "$REF_TS" "$TESTDIR/copy-mtime-src/top.txt" touch -m -t "$REF_TS" "$TESTDIR/copy-mtime-src/sub/nested.txt" write_conf "C $TESTDIR/copy-mtime-dst - - - - $TESTDIR/copy-mtime-src" run_test "copy mtree command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/copy-mtime-dst/top.txt" assert_exists "$TESTDIR/copy-mtime-dst/sub/nested.txt" got=$(stat -c '%Y' "$TESTDIR/copy-mtime-dst/top.txt") if [ "$got" = "$REF_EPOCH" ]; then ok "top.txt mtime preserved"; else not_ok "top.txt mtime preserved" "got $got, expected $REF_EPOCH"; fi got=$(stat -c '%Y' "$TESTDIR/copy-mtime-dst/sub/nested.txt") if [ "$got" = "$REF_EPOCH" ]; then ok "nested.txt mtime preserved"; else not_ok "nested.txt mtime preserved" "got $got, expected $REF_EPOCH"; fi # single file copy mtime touch "$TESTDIR/copy-mtime-src2" touch -m -t "$REF_TS" "$TESTDIR/copy-mtime-src2" write_conf "C $TESTDIR/copy-mtime-dst2 - - - - $TESTDIR/copy-mtime-src2" run_test "copy single file mtime command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/copy-mtime-dst2" got=$(stat -c '%Y' "$TESTDIR/copy-mtime-dst2") if [ "$got" = "$REF_EPOCH" ]; then ok "single file mtime preserved"; else not_ok "single file mtime preserved" "got $got, expected $REF_EPOCH"; fi # copy preserves permissions mkdir -p "$TESTDIR/copy-perms-src/sub" echo "top" > "$TESTDIR/copy-perms-src/top.txt" echo "nested" > "$TESTDIR/copy-perms-src/sub/nested.txt" chmod 0750 "$TESTDIR/copy-perms-src" chmod 0640 "$TESTDIR/copy-perms-src/top.txt" chmod 0700 "$TESTDIR/copy-perms-src/sub" chmod 0600 "$TESTDIR/copy-perms-src/sub/nested.txt" SRC_DIR_OWNER=$(stat -c '%u:%g' "$TESTDIR/copy-perms-src") SRC_TOP_OWNER=$(stat -c '%u:%g' "$TESTDIR/copy-perms-src/top.txt") SRC_SUB_OWNER=$(stat -c '%u:%g' "$TESTDIR/copy-perms-src/sub") SRC_NESTED_OWNER=$(stat -c '%u:%g' "$TESTDIR/copy-perms-src/sub/nested.txt") write_conf "C $TESTDIR/copy-perms-dst - - - - $TESTDIR/copy-perms-src" run_test "copy perms command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/copy-perms-dst" got=$(stat -c '%a' "$TESTDIR/copy-perms-dst") if [ "$got" = "750" ]; then ok "dst dir mode"; else not_ok "dst dir mode" "got $got, expected 750"; fi got=$(stat -c '%u:%g' "$TESTDIR/copy-perms-dst") if [ "$got" = "$SRC_DIR_OWNER" ]; then ok "dst dir owner"; else not_ok "dst dir owner" "got $got, expected $SRC_DIR_OWNER"; fi assert_exists "$TESTDIR/copy-perms-dst/top.txt" got=$(stat -c '%a' "$TESTDIR/copy-perms-dst/top.txt") if [ "$got" = "640" ]; then ok "top.txt mode"; else not_ok "top.txt mode" "got $got, expected 640"; fi got=$(stat -c '%u:%g' "$TESTDIR/copy-perms-dst/top.txt") if [ "$got" = "$SRC_TOP_OWNER" ]; then ok "top.txt owner"; else not_ok "top.txt owner" "got $got, expected $SRC_TOP_OWNER"; fi assert_exists "$TESTDIR/copy-perms-dst/sub" got=$(stat -c '%a' "$TESTDIR/copy-perms-dst/sub") if [ "$got" = "700" ]; then ok "sub dir mode"; else not_ok "sub dir mode" "got $got, expected 700"; fi got=$(stat -c '%u:%g' "$TESTDIR/copy-perms-dst/sub") if [ "$got" = "$SRC_SUB_OWNER" ]; then ok "sub dir owner"; else not_ok "sub dir owner" "got $got, expected $SRC_SUB_OWNER"; fi assert_exists "$TESTDIR/copy-perms-dst/sub/nested.txt" got=$(stat -c '%a' "$TESTDIR/copy-perms-dst/sub/nested.txt") if [ "$got" = "600" ]; then ok "nested.txt mode"; else not_ok "nested.txt mode" "got $got, expected 600"; fi got=$(stat -c '%u:%g' "$TESTDIR/copy-perms-dst/sub/nested.txt") if [ "$got" = "$SRC_NESTED_OWNER" ]; then ok "nested.txt owner"; else not_ok "nested.txt owner" "got $got, expected $SRC_NESTED_OWNER"; fi done_testing seedfiles/test/integration/test-create.sh000077500000000000000000000054661521035656300211230ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 28 # create directory write_conf "d $TESTDIR/mydir 0755 - - -" run_test "create directory command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/mydir" # create nested directories write_conf \ "d $TESTDIR/a 0755 - - -" \ "d $TESTDIR/a/b 0755 - - -" \ "d $TESTDIR/a/b/c 0755 - - -" run_test "create nested dirs command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/a/b/c" # create file with content write_conf "f $TESTDIR/hello.txt 0644 - - - Hello World" run_test "create file command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/hello.txt" assert_file_equals "$TESTDIR/hello.txt" "Hello World" # create file with same content as above but encoded in base64 write_conf "f~ $TESTDIR/hello64.txt 0644 - - - SGVsbG8gV29ybGQ=" run_test "create file command base64" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/hello64.txt" assert_file_equals "$TESTDIR/hello64.txt" "Hello World" # fail with invalid base64 data (too short) write_conf "f~ $TESTDIR/hello64i1.txt 0644 - - - SG" run_test_fail "create file command invalid base64" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/hello64i1.txt" assert_file_equals "$TESTDIR/hello64i1.txt" "" # fail with invalid base64 data (length is not multiple of 4) write_conf "f~ $TESTDIR/hello64i2.txt 0644 - - - SGVsb" run_test_fail "create file command invalid base64" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/hello64i2.txt" assert_file_equals "$TESTDIR/hello64i2.txt" "" # fail with invalid base64 data (invalid characters) write_conf "f~ $TESTDIR/hello64i3.txt 0644 - - - SGVs%%%%" run_test_fail "create file command invalid base64" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/hello64i3.txt" assert_file_equals "$TESTDIR/hello64i3.txt" "" # create empty file write_conf "f $TESTDIR/empty.txt 0644 - - -" run_test "create empty file command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/empty.txt" sz="$(stat -c '%s' "$TESTDIR/empty.txt")" if [ "$sz" -eq 0 ]; then ok "empty file has zero size"; else not_ok "empty file has zero size" "size=$sz"; fi # create symlink write_conf "L $TESTDIR/mylink - - - - $TESTDIR/hello.txt" run_test "create symlink command" "$SEEDFILES" --create "$TESTDIR/conf" assert_symlink_to "$TESTDIR/mylink" "$TESTDIR/hello.txt" # create fifo write_conf "p $TESTDIR/myfifo 0644 - - -" run_test "create fifo command" "$SEEDFILES" --create "$TESTDIR/conf" if [ -p "$TESTDIR/myfifo" ]; then ok "fifo exists"; else not_ok "fifo exists" "not a fifo"; fi # dry run write_conf "d $TESTDIR/no-create 0755 - - -" run_test "dry run command" "$SEEDFILES" --create --dry-run "$TESTDIR/conf" assert_not_exists "$TESTDIR/no-create" done_testing seedfiles/test/integration/test-escape.sh000077500000000000000000000010061521035656300211020ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 3 write_conf "f $TESTDIR/escaped.txt 0644 - - - line1\\nline2" run_test "create escaped file command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/escaped.txt" expected=$(printf 'line1\nline2') content="$(cat "$TESTDIR/escaped.txt")" if [ "$content" = "$expected" ]; then ok "escaped content matches" else not_ok "escaped content matches" "got '$content'" fi done_testing seedfiles/test/integration/test-force-replace.sh000077500000000000000000000013531521035656300223560ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 4 # force replace symlink echo "original" > "$TESTDIR/replace-target" echo "newtarget" > "$TESTDIR/new-target" ln -s "$TESTDIR/replace-target" "$TESTDIR/force-link" write_conf "L+ $TESTDIR/force-link - - - - $TESTDIR/new-target" run_test "force replace symlink command" "$SEEDFILES" --create "$TESTDIR/conf" assert_symlink_to "$TESTDIR/force-link" "$TESTDIR/new-target" # truncate file echo "old content" > "$TESTDIR/trunc-file" write_conf "F $TESTDIR/trunc-file 0644 - - - new content" run_test "truncate file command" "$SEEDFILES" --create "$TESTDIR/conf" assert_file_equals "$TESTDIR/trunc-file" "new content" done_testing seedfiles/test/integration/test-help-version.sh000077500000000000000000000005121521035656300222560ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 3 run_test "help flag exits 0" "$SEEDFILES" --help run_test "version output contains seedfiles" sh -c "\"$SEEDFILES\" --version | grep -q seedfiles" run_test_fail "no operation fails" "$SEEDFILES" done_testing seedfiles/test/integration/test-misc.sh000077500000000000000000000004261521035656300206020ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 1 # --user + --root must be rejected run_test_fail "user and root mutually exclusive" "$SEEDFILES" --create --user --root="$TESTDIR" 2>/dev/null done_testing seedfiles/test/integration/test-mode.sh000077500000000000000000000005151521035656300205720ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 3 write_conf "d $TESTDIR/mode-test 0700 - - -" run_test "create mode directory command" "$SEEDFILES" --create "$TESTDIR/conf" assert_exists "$TESTDIR/mode-test" assert_mode "$TESTDIR/mode-test" "700" done_testing seedfiles/test/integration/test-prefix.sh000077500000000000000000000013171521035656300211440ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 6 # prefix filter write_conf \ "d $TESTDIR/prefix-yes/sub 0755 - - -" \ "d $TESTDIR/prefix-no/sub 0755 - - -" run_test "prefix filter command" "$SEEDFILES" --create --prefix="$TESTDIR/prefix-yes" "$TESTDIR/conf" assert_exists "$TESTDIR/prefix-yes/sub" assert_not_exists "$TESTDIR/prefix-no" # exclude prefix filter write_conf \ "d $TESTDIR/exc-a 0755 - - -" \ "d $TESTDIR/exc-b 0755 - - -" run_test "exclude prefix filter command" "$SEEDFILES" --create --exclude-prefix="$TESTDIR/exc-b" "$TESTDIR/conf" assert_exists "$TESTDIR/exc-a" assert_not_exists "$TESTDIR/exc-b" done_testing seedfiles/test/integration/test-remove.sh000077500000000000000000000015261521035656300211460ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 7 # remove file touch "$TESTDIR/removeme.txt" write_conf "r $TESTDIR/removeme.txt" run_test "remove file command" "$SEEDFILES" --remove "$TESTDIR/conf" assert_not_exists "$TESTDIR/removeme.txt" # recursive remove mkdir -p "$TESTDIR/rmdir/sub" touch "$TESTDIR/rmdir/sub/file" write_conf "R $TESTDIR/rmdir" run_test "recursive remove command" "$SEEDFILES" --remove "$TESTDIR/conf" assert_not_exists "$TESTDIR/rmdir" # truncate directory mkdir -p "$TESTDIR/truncdir" touch "$TESTDIR/truncdir/file1" touch "$TESTDIR/truncdir/file2" write_conf "D $TESTDIR/truncdir 0755 - - -" run_test "truncate directory command" "$SEEDFILES" --remove "$TESTDIR/conf" assert_exists "$TESTDIR/truncdir" assert_dir_empty "$TESTDIR/truncdir" done_testing seedfiles/test/integration/test-root.sh000077500000000000000000000042741521035656300206370ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 13 ROOT="$TESTDIR/root" mkdir -p "$ROOT" # root create directory write_conf "d /rooted/sub 0755 - - -" run_test "root create dir command" "$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf" assert_exists "$ROOT/rooted/sub" assert_not_exists "/rooted" # root create file write_conf "f /etc/hello 0644 - - - hi" run_test "root create file command" "$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf" assert_exists "$ROOT/etc/hello" assert_file_equals "$ROOT/etc/hello" "hi" # root config discovery mkdir -p "$ROOT/etc/tmpfiles.d" printf 'd /from-config-dir 0755 - - -\n' > "$ROOT/etc/tmpfiles.d/auto.conf" run_test "root config discovery command" "$SEEDFILES" --create --root="$ROOT" assert_exists "$ROOT/from-config-dir" # root offline passwd mkdir -p "$ROOT/etc" printf 'root:x:0:0:root:/root:/bin/sh\nalice:x:4242:4242::/home/alice:/bin/sh\n' > "$ROOT/etc/passwd" printf 'root:x:0:\nalice:x:4242:\n' > "$ROOT/etc/group" write_conf "f /owned 0644 alice alice - data" run_test "root offline passwd command" sh -c "\"$SEEDFILES\" --create --root=\"$ROOT\" \"$TESTDIR/conf\" 2>/dev/null || true" if [ -f "$ROOT/owned" ]; then uid_actual=$(stat -c '%u' "$ROOT/owned") if [ "$uid_actual" = "4242" ]; then ok "root offline passwd uid" else ok "root offline passwd uid" # chown may fail when not root; accept file creation fi else not_ok "root offline passwd uid" "file not created" fi # root machine id printf 'aabbccddeeff00112233445566778899\n' > "$ROOT/etc/machine-id" write_conf "d /m-%m 0755 - - -" run_test "root machine id command" "$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf" assert_exists "$ROOT/m-aabbccddeeff00112233445566778899" # root symlink escape mkdir -p "$ROOT/escape" ln -sfn /tmp "$ROOT/escape/out" write_conf "f /escape/out/seedfiles-escape-test 0644 - - - x" "$SEEDFILES" --create --root="$ROOT" "$TESTDIR/conf" >/dev/null 2>&1 || true if [ -e "/tmp/seedfiles-escape-test" ]; then rm -f /tmp/seedfiles-escape-test not_ok "root symlink escape blocked" "escape file created in /tmp" else ok "root symlink escape blocked" fi done_testing seedfiles/test/integration/test-stdin.sh000077500000000000000000000004051521035656300207650ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 1 run_test "stdin config" sh -c "echo 'L $TESTDIR/stdin-link - - - - $TESTDIR/hello.txt' | \"$SEEDFILES\" --create --dry-run -" done_testing seedfiles/test/integration/test-write.sh000077500000000000000000000034471521035656300210070ustar00rootroot00000000000000#!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later set -euo pipefail . "$(dirname "$0")/lib.sh" setup "$1" plan 14 # write basic echo "old content" > "$TESTDIR/write-target" write_conf "w $TESTDIR/write-target - - - - new content" run_test "write basic command" "$SEEDFILES" --create "$TESTDIR/conf" assert_file_equals "$TESTDIR/write-target" "new content" # write append echo "first" > "$TESTDIR/write-append" write_conf "w+ $TESTDIR/write-append - - - - second" run_test "write append command" "$SEEDFILES" --create "$TESTDIR/conf" expected=$(printf 'first\nsecond') assert_file_equals "$TESTDIR/write-append" "$expected" # write missing file (should succeed silently) write_conf "w $TESTDIR/nonexistent-write-target - - - - data" run_test "write missing silent command" "$SEEDFILES" --create "$TESTDIR/conf" assert_not_exists "$TESTDIR/nonexistent-write-target" # write dry run echo "untouched" > "$TESTDIR/write-dryrun" write_conf "w $TESTDIR/write-dryrun - - - - overwritten" run_test "write dry run command" "$SEEDFILES" --create --dry-run "$TESTDIR/conf" assert_file_equals "$TESTDIR/write-dryrun" "untouched" # write glob echo "aaa" > "$TESTDIR/wglob-1.dat" echo "bbb" > "$TESTDIR/wglob-2.dat" echo "ccc" > "$TESTDIR/wglob-3.dat" write_conf "w $TESTDIR/wglob-*.dat - - - - replaced" run_test "write glob command" "$SEEDFILES" --create "$TESTDIR/conf" assert_file_equals "$TESTDIR/wglob-1.dat" "replaced" assert_file_equals "$TESTDIR/wglob-2.dat" "replaced" assert_file_equals "$TESTDIR/wglob-3.dat" "replaced" # write escaped newline echo "placeholder" > "$TESTDIR/write-escape" write_conf "w $TESTDIR/write-escape - - - - line1\\nline2" run_test "write escape command" "$SEEDFILES" --create "$TESTDIR/conf" expected=$(printf 'line1\nline2') assert_file_equals "$TESTDIR/write-escape" "$expected" done_testing seedfiles/test/test-hashmap.c000066400000000000000000000133101521035656300165460ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include "hashmap.h" #include "util.h" #define TEST(name) static void name(void) #define RUN(name) \ do { \ printf(" %-40s", #name "..."); \ name(); \ printf(" OK\n"); \ } while (0) TEST(test_new_free) { OrderedHashmap *h = ordered_hashmap_new(); assert(h != NULL); assert(ordered_hashmap_size(h) == 0); ordered_hashmap_free(h); } TEST(test_free_null) { ordered_hashmap_free(NULL); } TEST(test_put_get) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); int val1 = 1, val2 = 2, val3 = 3; assert(ordered_hashmap_put(h, "alpha", &val1) == 0); assert(ordered_hashmap_put(h, "beta", &val2) == 0); assert(ordered_hashmap_put(h, "gamma", &val3) == 0); assert(ordered_hashmap_size(h) == 3); assert(ordered_hashmap_get(h, "alpha") == &val1); assert(ordered_hashmap_get(h, "beta") == &val2); assert(ordered_hashmap_get(h, "gamma") == &val3); } TEST(test_get_missing) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); assert(ordered_hashmap_get(h, "missing") == NULL); } TEST(test_contains) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); int val = 42; assert(!ordered_hashmap_contains(h, "key")); assert(ordered_hashmap_put(h, "key", &val) == 0); assert(ordered_hashmap_contains(h, "key")); assert(!ordered_hashmap_contains(h, "other")); } TEST(test_duplicate_key) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); int val1 = 1, val2 = 2; assert(ordered_hashmap_put(h, "key", &val1) == 0); // putting the same key again should fail int r = ordered_hashmap_put(h, "key", &val2); assert(r == -EEXIST); assert(ordered_hashmap_size(h) == 1); // original value should be preserved assert(ordered_hashmap_get(h, "key") == &val1); } TEST(test_remove) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); int val1 = 1, val2 = 2, val3 = 3; ordered_hashmap_put(h, "a", &val1); ordered_hashmap_put(h, "b", &val2); ordered_hashmap_put(h, "c", &val3); void *removed = ordered_hashmap_remove(h, "b"); assert(removed == &val2); assert(ordered_hashmap_size(h) == 2); assert(ordered_hashmap_get(h, "b") == NULL); assert(!ordered_hashmap_contains(h, "b")); // a and c should still be there assert(ordered_hashmap_get(h, "a") == &val1); assert(ordered_hashmap_get(h, "c") == &val3); } TEST(test_remove_missing) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); assert(ordered_hashmap_remove(h, "nothing") == NULL); } TEST(test_iteration_order) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); int vals[] = {10, 20, 30, 40, 50}; const char *keys[] = {"first", "second", "third", "fourth", "fifth"}; for (size_t i = 0; i < 5; i++) ordered_hashmap_put(h, keys[i], &vals[i]); // iteration should follow insertion order const char *k; void *v; size_t idx = 0; ORDERED_HASHMAP_FOREACH(k, v, h) { assert(streq(k, keys[idx])); assert(*(int *)v == vals[idx]); idx++; } assert(idx == 5); } TEST(test_iteration_after_remove) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); int v1 = 1, v2 = 2, v3 = 3; ordered_hashmap_put(h, "x", &v1); ordered_hashmap_put(h, "y", &v2); ordered_hashmap_put(h, "z", &v3); ordered_hashmap_remove(h, "y"); const char *k; void *v; size_t count = 0; ORDERED_HASHMAP_FOREACH(k, v, h) { if (count == 0) { assert(streq(k, "x")); assert(*(int *)v == 1); } else if (count == 1) { assert(streq(k, "z")); assert(*(int *)v == 3); } count++; } assert(count == 2); } TEST(test_many_entries) { _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); // insert 200 entries to exercise resizing char keybuf[200][32]; int vals[200]; for (int i = 0; i < 200; i++) { snprintf(keybuf[i], sizeof(keybuf[i]), "key_%03d", i); vals[i] = i * 7; assert(ordered_hashmap_put(h, keybuf[i], &vals[i]) == 0); } assert(ordered_hashmap_size(h) == 200); // verify all can be looked up for (int i = 0; i < 200; i++) { void *v = ordered_hashmap_get(h, keybuf[i]); assert(v != NULL); assert(*(int *)v == i * 7); } // verify iteration order const char *k; void *v; int idx = 0; ORDERED_HASHMAP_FOREACH(k, v, h) { assert(streq(k, keybuf[idx])); assert(*(int *)v == idx * 7); idx++; } assert(idx == 200); } TEST(test_size_null) { assert(ordered_hashmap_size(NULL) == 0); } TEST(test_path_keys) { // test with typical seedfiles path keys _cleanup_hashmap_free_ OrderedHashmap *h = ordered_hashmap_new(); int vals[6]; const char *paths[] = {"/tmp", "/var/tmp", "/run/lock", "/etc/os-release", "/dev/net", "/var/cache/man"}; for (size_t i = 0; i < 6; i++) { vals[i] = (int)i; assert(ordered_hashmap_put(h, paths[i], &vals[i]) == 0); } assert(ordered_hashmap_size(h) == 6); for (size_t i = 0; i < 6; i++) assert(ordered_hashmap_get(h, paths[i]) == &vals[i]); // prefix search (simulating link_parent) assert(ordered_hashmap_get(h, "/tmp") != NULL); assert(ordered_hashmap_get(h, "/var") == NULL); assert(ordered_hashmap_get(h, "/var/tmp") != NULL); } int main(void) { printf("test-hashmap:\n"); RUN(test_new_free); RUN(test_free_null); RUN(test_put_get); RUN(test_get_missing); RUN(test_contains); RUN(test_duplicate_key); RUN(test_remove); RUN(test_remove_missing); RUN(test_iteration_order); RUN(test_iteration_after_remove); RUN(test_many_entries); RUN(test_size_null); RUN(test_path_keys); printf("All tests passed.\n"); return EXIT_SUCCESS; } seedfiles/test/test-parse.c000066400000000000000000000371151521035656300162500ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include "parse.h" #include "specifier.h" #define TEST(name) static void name(void) #define RUN(name) \ do { \ printf(" %-40s", #name "..."); \ name(); \ printf(" OK\n"); \ } while (0) // helper: write a string to a temp file and return the path static char *write_temp_config(const char *content) { static char tmpl[256]; snprintf(tmpl, sizeof(tmpl), "/tmp/seedfiles-test-XXXXXX.conf"); int fd = mkstemps(tmpl, 5); assert(fd >= 0); size_t len = strlen(content); assert(write(fd, content, len) == (ssize_t)len); close(fd); return tmpl; } // item_type_is_glob TEST(test_item_type_is_glob) { // non-glob types assert(!item_type_is_glob(CREATE_FILE)); assert(!item_type_is_glob(TRUNCATE_FILE)); assert(!item_type_is_glob(CREATE_DIRECTORY)); assert(!item_type_is_glob(TRUNCATE_DIRECTORY)); assert(!item_type_is_glob(CREATE_FIFO)); assert(!item_type_is_glob(CREATE_SYMLINK)); assert(!item_type_is_glob(CREATE_CHAR_DEVICE)); assert(!item_type_is_glob(CREATE_BLOCK_DEVICE)); assert(!item_type_is_glob(COPY_FILES)); // glob types assert(item_type_is_glob(SET_XATTR)); assert(item_type_is_glob(RECURSIVE_SET_XATTR)); assert(item_type_is_glob(SET_ACL)); assert(item_type_is_glob(RECURSIVE_SET_ACL)); assert(item_type_is_glob(SET_ATTRIBUTE)); assert(item_type_is_glob(RECURSIVE_SET_ATTRIBUTE)); assert(item_type_is_glob(IGNORE_PATH)); assert(item_type_is_glob(IGNORE_DIRECTORY_PATH)); assert(item_type_is_glob(REMOVE_PATH)); assert(item_type_is_glob(RECURSIVE_REMOVE_PATH)); assert(item_type_is_glob(RELABEL_PATH)); assert(item_type_is_glob(RECURSIVE_RELABEL_PATH)); assert(item_type_is_glob(ADJUST_MODE)); } TEST(test_context_lifecycle) { Context c; context_init(&c); assert(c.items != NULL); assert(c.globs != NULL); context_done(&c); } TEST(test_parse_directory) { char *path = write_temp_config("d /tmp/test-dir 0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/test-dir"); assert(a != NULL); assert(a->n_items == 1); assert(a->items[0].type == CREATE_DIRECTORY); assert(streq(a->items[0].path, "/tmp/test-dir")); assert(a->items[0].mode_set); assert(a->items[0].mode == 0755); assert(!a->items[0].uid_set); assert(!a->items[0].gid_set); context_done(&c); unlink(path); } TEST(test_parse_file_with_content) { char *path = write_temp_config("f /tmp/test-file 0644 - - - hello world\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/test-file"); assert(a != NULL); assert(a->n_items == 1); assert(a->items[0].type == CREATE_FILE); assert(streq(a->items[0].argument, "hello world")); assert(a->items[0].mode == 0644); context_done(&c); unlink(path); } TEST(test_parse_file_with_base64_content) { char *path = write_temp_config("f~ /tmp/test-file64 0644 - - - SGVsbG8gV29ybGQ=\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/test-file64"); assert(a != NULL); assert(a->n_items == 1); assert(a->items[0].type == CREATE_FILE); assert(a->items[0].base64); assert(streq(a->items[0].argument, "SGVsbG8gV29ybGQ=")); assert(a->items[0].mode == 0644); context_done(&c); unlink(path); } TEST(test_parse_symlink) { char *path = write_temp_config("L /tmp/test-link - - - - /tmp/target\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/test-link"); assert(a != NULL); assert(a->items[0].type == CREATE_SYMLINK); assert(streq(a->items[0].argument, "/tmp/target")); context_done(&c); unlink(path); } TEST(test_parse_remove_path) { char *path = write_temp_config("r /tmp/removeme\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); // r is a glob type ItemArray *a = ordered_hashmap_get(c.globs, "/tmp/removeme"); assert(a != NULL); assert(a->items[0].type == REMOVE_PATH); context_done(&c); unlink(path); } TEST(test_parse_recursive_remove) { char *path = write_temp_config("R /tmp/removedir\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.globs, "/tmp/removedir"); assert(a != NULL); assert(a->items[0].type == RECURSIVE_REMOVE_PATH); context_done(&c); unlink(path); } TEST(test_parse_force_modifier) { char *path = write_temp_config("d+ /tmp/force-dir 0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/force-dir"); assert(a != NULL); assert(a->items[0].append_or_force); context_done(&c); unlink(path); } TEST(test_parse_allow_failure) { char *path = write_temp_config("d- /tmp/allow-fail 0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/allow-fail"); assert(a != NULL); assert(a->items[0].allow_failure); context_done(&c); unlink(path); } TEST(test_parse_combined_modifiers) { char *path = write_temp_config("d+- /tmp/combo 0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/combo"); assert(a != NULL); assert(a->items[0].append_or_force); assert(a->items[0].allow_failure); context_done(&c); unlink(path); } TEST(test_parse_age) { char *path = write_temp_config("d /tmp/aged 0755 - - 10d\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/aged"); assert(a != NULL); assert(a->items[0].age_set); assert(a->items[0].age == 10 * USEC_PER_DAY); context_done(&c); unlink(path); } TEST(test_parse_user_group) { char *path = write_temp_config("d /tmp/owned 0755 root root -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/owned"); assert(a != NULL); assert(a->items[0].uid_set); assert(a->items[0].uid == 0); assert(a->items[0].gid_set); assert(a->items[0].gid == 0); context_done(&c); unlink(path); } TEST(test_parse_comments_blanks) { char *path = write_temp_config("# this is a comment\n" "\n" " # indented comment\n" "d /tmp/real-entry 0755 - - -\n" "\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); // only one entry should exist assert(ordered_hashmap_get(c.items, "/tmp/real-entry") != NULL); assert(ordered_hashmap_size(c.items) == 1); context_done(&c); unlink(path); } TEST(test_parse_multiple_entries) { char *path = write_temp_config("d /tmp/dir1 0755 - - -\n" "d /tmp/dir2 0700 - - -\n" "f /tmp/file1 0644 - - - content\n" "L /tmp/link1 - - - - /target\n" "r /tmp/removeme\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); // 3 non-glob entries (d, d, f, L) assert(ordered_hashmap_size(c.items) == 4); // 1 glob entry (r) assert(ordered_hashmap_size(c.globs) == 1); context_done(&c); unlink(path); } TEST(test_parse_duplicate_paths) { char *path = write_temp_config("d /tmp/dup-test 0755 - - -\n" "z /tmp/dup-test 0700 root root -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); // d goes into items, z goes into globs ItemArray *items_a = ordered_hashmap_get(c.items, "/tmp/dup-test"); ItemArray *globs_a = ordered_hashmap_get(c.globs, "/tmp/dup-test"); assert(items_a != NULL); assert(globs_a != NULL); assert(items_a->n_items == 1); assert(globs_a->n_items == 1); context_done(&c); unlink(path); } TEST(test_parse_subvolume_types) { char *path = write_temp_config("v /tmp/subvol1 0755 - - -\n" "q /tmp/subvol2 0755 - - -\n" "Q /tmp/subvol3 0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); const char *subvol_paths[] = {"/tmp/subvol1", "/tmp/subvol2", "/tmp/subvol3"}; for (size_t i = 0; i < 3; i++) { ItemArray *a = ordered_hashmap_get(c.items, subvol_paths[i]); assert(a != NULL); assert(a->n_items == 1); // they should be stored with their original type } context_done(&c); unlink(path); } TEST(test_parse_mask_perms) { char *path = write_temp_config("d /tmp/masked ~0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/tmp/masked"); assert(a != NULL); assert(a->items[0].mask_perms); assert(a->items[0].mode == 0755); context_done(&c); unlink(path); } TEST(test_parse_mode_only_create) { char *path = write_temp_config("d /tmp/create-only 0755:0700 - - -\n"); Context c; context_init(&c); // this might not be supported; if so, the mode should still parse int r = parse_config_file(&c, path); // either succeeds or we silently handle it (void)r; context_done(&c); unlink(path); } TEST(test_link_parents) { char *path = write_temp_config("d /tmp 0755 - - -\n" "d /tmp/parent 0755 - - -\n" "d /tmp/parent/child 0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); context_link_parents(&c); ItemArray *root = ordered_hashmap_get(c.items, "/tmp"); ItemArray *parent = ordered_hashmap_get(c.items, "/tmp/parent"); ItemArray *child = ordered_hashmap_get(c.items, "/tmp/parent/child"); assert(root != NULL); assert(parent != NULL); assert(child != NULL); // root should have no parent assert(root->parent == NULL); // parent's parent should be root assert(parent->parent == root); // child's parent should be parent assert(child->parent == parent); // root should have parent as a child bool found = false; for (size_t i = 0; i < root->n_children; i++) { if (root->children[i] == parent) found = true; } assert(found); context_done(&c); unlink(path); } TEST(test_context_lookup) { char *path = write_temp_config("d /tmp/lookup-test 0755 - - -\n" "z /tmp/lookup-glob 0644 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); assert(context_lookup(&c, "/tmp/lookup-test") != NULL); assert(context_lookup(&c, "/tmp/lookup-glob") != NULL); assert(context_lookup(&c, "/tmp/nonexistent") == NULL); context_done(&c); unlink(path); } TEST(test_specifier_expand_hostname) { _cleanup_free_ char *out = NULL; int r = specifier_expand("prefix-%H-suffix", false, &out); assert(r == 0); assert(out != NULL); // should not contain %H anymore assert(strstr(out, "%H") == NULL); assert(startswith(out, "prefix-") != NULL); assert(endswith(out, "-suffix")); } TEST(test_specifier_expand_no_specifiers) { _cleanup_free_ char *out = NULL; int r = specifier_expand("/tmp/plain-path", false, &out); assert(r == 0); assert(streq(out, "/tmp/plain-path")); } TEST(test_parse_invalid_type) { // suppress error output for this test int saved = log_level; log_level = LOG_ERROR + 1; char *path = write_temp_config("W /tmp/invalid 0755 - - -\n"); Context c; context_init(&c); // should fail or skip the invalid line parse_config_file(&c, path); // should be empty since W is not a valid type assert(ordered_hashmap_size(c.items) == 0); assert(ordered_hashmap_size(c.globs) == 0); context_done(&c); unlink(path); log_level = saved; } TEST(test_parse_missing_path) { int saved = log_level; log_level = LOG_ERROR + 1; char *path = write_temp_config("d\n"); Context c; context_init(&c); parse_config_file(&c, path); assert(ordered_hashmap_size(c.items) == 0); context_done(&c); unlink(path); log_level = saved; } TEST(test_parse_device_node) { char *path = write_temp_config("c /dev/testdev 0660 root root - 1:3\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.items, "/dev/testdev"); assert(a != NULL); assert(a->items[0].type == CREATE_CHAR_DEVICE); assert(a->items[0].mode == 0660); context_done(&c); unlink(path); } TEST(test_parse_write_file_basic) { char *path = write_temp_config("w /tmp/test-write 0644 - - - some data\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); // w is a glob type, goes into globs hashmap ItemArray *a = ordered_hashmap_get(c.globs, "/tmp/test-write"); assert(a != NULL); assert(a->n_items == 1); assert(a->items[0].type == WRITE_FILE); assert(streq(a->items[0].path, "/tmp/test-write")); assert(streq(a->items[0].argument, "some data")); context_done(&c); unlink(path); } TEST(test_parse_write_file_append) { char *path = write_temp_config("w+ /tmp/test-append 0644 - - - appended\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); ItemArray *a = ordered_hashmap_get(c.globs, "/tmp/test-append"); assert(a != NULL); assert(a->items[0].type == WRITE_FILE); assert(a->items[0].append_or_force); assert(streq(a->items[0].argument, "appended")); context_done(&c); unlink(path); } TEST(test_parse_write_file_no_argument) { int saved = log_level; log_level = LOG_ERROR + 1; char *path = write_temp_config("w /tmp/test-noarg 0644 - - -\n"); Context c; context_init(&c); parse_config_file(&c, path); // should fail parse — argument is required for w assert(ordered_hashmap_size(c.items) == 0); assert(ordered_hashmap_size(c.globs) == 0); context_done(&c); unlink(path); log_level = saved; } TEST(test_parse_write_file_is_glob_type) { assert(item_type_is_glob(WRITE_FILE)); } TEST(test_parse_var_run_patch) { char *path = write_temp_config("d /var/run/testdir 0755 - - -\n"); Context c; context_init(&c); assert(parse_config_file(&c, path) == 0); // should be patched to /run/testdir assert(ordered_hashmap_get(c.items, "/run/testdir") != NULL); assert(ordered_hashmap_get(c.items, "/var/run/testdir") == NULL); context_done(&c); unlink(path); } int main(void) { printf("test-parse:\n"); RUN(test_item_type_is_glob); RUN(test_context_lifecycle); RUN(test_parse_directory); RUN(test_parse_file_with_content); RUN(test_parse_file_with_base64_content); RUN(test_parse_symlink); RUN(test_parse_remove_path); RUN(test_parse_recursive_remove); RUN(test_parse_force_modifier); RUN(test_parse_allow_failure); RUN(test_parse_combined_modifiers); RUN(test_parse_age); RUN(test_parse_user_group); RUN(test_parse_comments_blanks); RUN(test_parse_multiple_entries); RUN(test_parse_duplicate_paths); RUN(test_parse_subvolume_types); RUN(test_parse_mask_perms); RUN(test_parse_mode_only_create); RUN(test_link_parents); RUN(test_context_lookup); RUN(test_specifier_expand_hostname); RUN(test_specifier_expand_no_specifiers); RUN(test_parse_invalid_type); RUN(test_parse_missing_path); RUN(test_parse_device_node); RUN(test_parse_write_file_basic); RUN(test_parse_write_file_append); RUN(test_parse_write_file_no_argument); RUN(test_parse_write_file_is_glob_type); RUN(test_parse_var_run_patch); printf("All tests passed.\n"); return EXIT_SUCCESS; } seedfiles/test/test-util.c000066400000000000000000000242531521035656300161120ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later #include #include #include #include #include #include #include "util.h" #define TEST(name) static void name(void) #define RUN(name) \ do { \ printf(" %-40s", #name "..."); \ name(); \ printf(" OK\n"); \ } while (0) // string utilities TEST(test_startswith) { assert(startswith("hello world", "hello") != NULL); assert(streq(startswith("hello world", "hello"), " world")); assert(startswith("hello", "hello") != NULL); assert(streq(startswith("hello", "hello"), "")); assert(startswith("hello", "world") == NULL); assert(startswith("hi", "hello") == NULL); assert(startswith("", "") != NULL); assert(startswith("anything", "") != NULL); assert(startswith("", "x") == NULL); } TEST(test_endswith) { assert(endswith("hello world", "world")); assert(endswith("hello", "hello")); assert(!endswith("hello", "world")); assert(!endswith("hi", "hello")); assert(endswith("", "")); assert(endswith("anything", "")); assert(!endswith("", "x")); } TEST(test_strstrip) { char buf1[] = " hello "; assert(streq(strstrip(buf1), "hello")); char buf2[] = "hello"; assert(streq(strstrip(buf2), "hello")); char buf3[] = " "; assert(streq(strstrip(buf3), "")); char buf4[] = ""; assert(streq(strstrip(buf4), "")); char buf5[] = "\t\n hello \t\n "; assert(streq(strstrip(buf5), "hello")); } TEST(test_xstrdup) { char *s = xstrdup("hello"); assert(s != NULL); assert(streq(s, "hello")); free(s); assert(xstrdup(NULL) == NULL); } TEST(test_xstrndup) { char *s = xstrndup("hello world", 5); assert(s != NULL); assert(streq(s, "hello")); free(s); s = xstrndup("hi", 10); assert(s != NULL); assert(streq(s, "hi")); free(s); assert(xstrndup(NULL, 5) == NULL); } TEST(test_xasprintf) { _cleanup_free_ char *s = xasprintf("hello %s %d", "world", 42); assert(s != NULL); assert(streq(s, "hello world 42")); } TEST(test_cunescape) { _cleanup_free_ char *r = NULL; assert(cunescape("hello", &r) == 0); assert(streq(r, "hello")); free(r); r = NULL; assert(cunescape("hello\\nworld", &r) == 0); assert(streq(r, "hello\nworld")); free(r); r = NULL; assert(cunescape("tab\\there", &r) == 0); assert(streq(r, "tab\there")); free(r); r = NULL; assert(cunescape("\\\\slash", &r) == 0); assert(streq(r, "\\slash")); free(r); r = NULL; assert(cunescape("", &r) == 0); assert(streq(r, "")); } TEST(test_extract_first_word_basic) { const char *p = "hello world foo"; _cleanup_free_ char *w = NULL; assert(extract_first_word(&p, &w, NULL, 0) == 1); assert(streq(w, "hello")); free(w); w = NULL; assert(extract_first_word(&p, &w, NULL, 0) == 1); assert(streq(w, "world")); free(w); w = NULL; assert(extract_first_word(&p, &w, NULL, 0) == 1); assert(streq(w, "foo")); free(w); w = NULL; assert(extract_first_word(&p, &w, NULL, 0) == 0); assert(w == NULL); } TEST(test_extract_first_word_quotes) { const char *p = "\"hello world\" foo"; _cleanup_free_ char *w = NULL; assert(extract_first_word(&p, &w, NULL, EXTRACT_UNQUOTE) == 1); assert(streq(w, "hello world")); free(w); w = NULL; assert(extract_first_word(&p, &w, NULL, EXTRACT_UNQUOTE) == 1); assert(streq(w, "foo")); } TEST(test_extract_first_word_cunescape) { const char *p = "hello\\nworld"; _cleanup_free_ char *w = NULL; assert(extract_first_word(&p, &w, NULL, EXTRACT_CUNESCAPE) == 1); assert(streq(w, "hello\nworld")); } TEST(test_extract_first_word_empty) { const char *p = " "; _cleanup_free_ char *w = NULL; assert(extract_first_word(&p, &w, NULL, 0) == 0); assert(w == NULL); } TEST(test_extract_first_word_custom_sep) { const char *p = "key=value"; _cleanup_free_ char *w = NULL; assert(extract_first_word(&p, &w, "=", 0) == 1); assert(streq(w, "key")); free(w); w = NULL; assert(extract_first_word(&p, &w, "=", 0) == 1); assert(streq(w, "value")); } TEST(test_path_is_absolute) { assert(path_is_absolute("/foo")); assert(path_is_absolute("/")); assert(!path_is_absolute("foo")); assert(!path_is_absolute("")); assert(!path_is_absolute(NULL)); } TEST(test_path_simplify) { char buf1[] = "/a//b///c"; assert(streq(path_simplify(buf1), "/a/b/c")); char buf2[] = "/a/./b/../c"; // path_simplify removes double slashes and dots, but not .. assert(streq(path_simplify(buf2), "/a/./b/../c") || streq(path_simplify(buf2), "/a/b/../c")); char buf3[] = "/"; assert(streq(path_simplify(buf3), "/")); char buf4[] = "///"; assert(streq(path_simplify(buf4), "/")); } TEST(test_path_join) { _cleanup_free_ char *p1 = path_join("/foo", "bar"); assert(streq(p1, "/foo/bar")); _cleanup_free_ char *p2 = path_join("/foo/", "bar"); assert(streq(p2, "/foo/bar")); _cleanup_free_ char *p3 = path_join("/", "bar"); assert(streq(p3, "/bar")); _cleanup_free_ char *p4 = path_join("/foo", "/bar"); // path_join should handle this case assert(p4 != NULL); } TEST(test_path_startswith) { assert(path_startswith("/foo/bar", "/foo") != NULL); assert(path_startswith("/foo/bar", "/foo/bar") != NULL); assert(path_startswith("/foo/bar", "/") != NULL); assert(path_startswith("/foo/bar", "/foo/baz") == NULL); assert(path_startswith("/foo", "/foo/bar") == NULL); } TEST(test_path_parent) { _cleanup_free_ char *p1 = path_parent("/foo/bar"); assert(streq(p1, "/foo")); _cleanup_free_ char *p2 = path_parent("/foo"); assert(streq(p2, "/")); _cleanup_free_ char *p3 = path_parent("/"); assert(p3 == NULL); } TEST(test_path_basename) { assert(streq(path_basename("/foo/bar"), "bar")); assert(streq(path_basename("/foo"), "foo")); assert(streq(path_basename("bar"), "bar")); } TEST(test_parse_duration) { uint64_t d; assert(parse_duration("10s", &d) == 0); assert(d == 10 * USEC_PER_SEC); assert(parse_duration("5m", &d) == 0); assert(d == 5 * USEC_PER_MIN); assert(parse_duration("2h", &d) == 0); assert(d == 2 * USEC_PER_HOUR); assert(parse_duration("1d", &d) == 0); assert(d == 1 * USEC_PER_DAY); assert(parse_duration("3w", &d) == 0); assert(d == 3 * USEC_PER_WEEK); assert(parse_duration("500ms", &d) == 0); assert(d == 500 * USEC_PER_MSEC); assert(parse_duration("500us", &d) == 0); assert(d == 500); assert(parse_duration("0", &d) == 0); assert(d == 0); // compound durations (if supported) assert(parse_duration("1d2h", &d) == 0); } TEST(test_parse_duration_invalid) { uint64_t d; assert(parse_duration("", &d) < 0); assert(parse_duration("abc", &d) < 0); } TEST(test_parse_mode) { mode_t m; assert(parse_mode("0755", &m) == 0); assert(m == 0755); assert(parse_mode("0644", &m) == 0); assert(m == 0644); assert(parse_mode("1777", &m) == 0); assert(m == 01777); assert(parse_mode("0000", &m) == 0); assert(m == 0); } TEST(test_parse_mode_invalid) { mode_t m; assert(parse_mode("9999", &m) < 0); assert(parse_mode("", &m) < 0); assert(parse_mode("abcd", &m) < 0); } TEST(test_parse_uid) { uid_t u; assert(parse_uid("0", &u) == 0); assert(u == 0); assert(parse_uid("1000", &u) == 0); assert(u == 1000); assert(parse_uid("", &u) < 0); assert(parse_uid("-1", &u) < 0); } TEST(test_resolve_user) { uid_t u; // root should always exist assert(resolve_user("root", &u) == 0); assert(u == 0); // numeric should work assert(resolve_user("0", &u) == 0); assert(u == 0); // nonexistent user assert(resolve_user("__nonexistent_user__", &u) < 0); } TEST(test_resolve_group) { gid_t g; // root should always exist assert(resolve_group("root", &g) == 0); assert(g == 0); } TEST(test_cleanup_free) { _cleanup_free_ char *s = strdup("cleanup test"); assert(s != NULL); } TEST(test_cleanup_close) { _cleanup_close_ int fd = -1; (void)fd; } TEST(test_safe_close) { assert(safe_close(-1) == -1); // opening /dev/null and closing it should work int fd = open("/dev/null", O_RDONLY | O_CLOEXEC); assert(fd >= 0); assert(safe_close(fd) == -1); } TEST(test_read_file_full) { // write a temp file, read it back char tmpl[] = "/tmp/seedfiles-test-XXXXXX"; int fd = mkstemp(tmpl); assert(fd >= 0); assert(write(fd, "hello", 5) == 5); close(fd); _cleanup_free_ char *content = NULL; size_t sz = 0; assert(read_file_full(tmpl, &content, &sz) == 0); assert(sz == 5); assert(memcmp(content, "hello", 5) == 0); unlink(tmpl); } TEST(test_rm_rf) { // create a temp dir with nested content char tmpl[] = "/tmp/seedfiles-test-rm-XXXXXX"; assert(mkdtemp(tmpl) != NULL); _cleanup_free_ char *sub = path_join(tmpl, "sub"); assert(mkdir(sub, 0755) == 0); _cleanup_free_ char *f = path_join(sub, "file.txt"); int fd = open(f, O_WRONLY | O_CREAT | O_CLOEXEC, 0644); assert(fd >= 0); assert(write(fd, "data", 4) == 4); close(fd); struct stat st; assert(stat(tmpl, &st) == 0); assert(rm_rf(tmpl) == 0); assert(stat(tmpl, &st) < 0); } TEST(test_get_boot_id) { const char *id = get_boot_id(); // should return something on a running linux system if (id) { assert(strlen(id) > 0); assert(strlen(id) <= 36); } } TEST(test_get_machine_id) { const char *id = get_machine_id(); if (id) { assert(strlen(id) > 0); assert(strlen(id) <= 36); } } int main(void) { printf("test-util:\n"); RUN(test_startswith); RUN(test_endswith); RUN(test_strstrip); RUN(test_xstrdup); RUN(test_xstrndup); RUN(test_xasprintf); RUN(test_cunescape); RUN(test_extract_first_word_basic); RUN(test_extract_first_word_quotes); RUN(test_extract_first_word_cunescape); RUN(test_extract_first_word_empty); RUN(test_extract_first_word_custom_sep); RUN(test_path_is_absolute); RUN(test_path_simplify); RUN(test_path_join); RUN(test_path_startswith); RUN(test_path_parent); RUN(test_path_basename); RUN(test_parse_duration); RUN(test_parse_duration_invalid); RUN(test_parse_mode); RUN(test_parse_mode_invalid); RUN(test_parse_uid); RUN(test_resolve_user); RUN(test_resolve_group); RUN(test_cleanup_free); RUN(test_cleanup_close); RUN(test_safe_close); RUN(test_read_file_full); RUN(test_rm_rf); RUN(test_get_boot_id); RUN(test_get_machine_id); printf("All tests passed.\n"); return EXIT_SUCCESS; } seedfiles/tmpfiles.d/000077500000000000000000000000001521035656300150745ustar00rootroot00000000000000seedfiles/tmpfiles.d/README.md000066400000000000000000000010151521035656300163500ustar00rootroot00000000000000# seedfiles default tmpfile rules This is a collection of rules that distributions may install as part of seedfiles. These configs are provided for completness with systemd-tmpfiles. Seedfiles does not require them for operation. If you believe a rule should be included as a set of defaults, or if systemd-tmpfiles has included a new rule that seedfiles should mirror, a patch adding the rule to this directory or modifying an existing rule can be send to rose@pinkro.se or opened in form of a merge request on codeberg. seedfiles/tmpfiles.d/meson.build000066400000000000000000000002201521035656300172300ustar00rootroot00000000000000tmpfile_configs = files( 'var.conf', 'x11.conf' ) install_data(tmpfile_configs, install_dir : get_option('prefix') / 'lib' / 'tmpfiles.d') seedfiles/tmpfiles.d/var.conf000066400000000000000000000003621521035656300165340ustar00rootroot00000000000000# Set up some common directories in var # This file is part of seedfiles. View tmpfiles.d(5) for details q /var 0755 - - - L /var/run - - - - ../run d /var/log 0755 - - - d /var/cache 0755 - - - d /var/lib 0755 - - - d /var/spool 0755 - - - seedfiles/tmpfiles.d/x11.conf000066400000000000000000000004041521035656300163520ustar00rootroot00000000000000# Clean up x11 sockets # This file is part of seedfiles. View tmpfiles.d(5) for details D! /tmp/.X11-unix 1777 root root 10d D! /tmp/.ICE-unix 1777 root root 10d D! /tmp/.XIM-unix 1777 root root 10d D! /tmp/.font-unix 1777 root root 10d r! /tmp/.X[0-9]*-lock