diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/cmd/LICENSE b/cmd/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/cmd/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/cmd/cmd b/cmd/cmd new file mode 100755 index 0000000..82814e8 Binary files /dev/null and b/cmd/cmd differ diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..8c5f9a7 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,391 @@ +package main + +import ( + "eon/common" + "eon/lib" + + "bufio" + "bytes" + "fmt" + "io" + "os" + "regexp" + "strings" + + "golang.org/x/term" + + "github.com/dustin/go-humanize" + "github.com/fatih/color" +) + +var logger = &common.DefaultLogger + +func main() { + if len(os.Args) < 2 { + fmt.Println("Usage: eon [args]") + os.Exit(1) + } + + switch os.Args[1] { + case "help": + if len(os.Args) < 3 { + fmt.Println("Usage: eon help (list/info/install/remove/clean/repo/help) [args]") + os.Exit(1) + } else { + switch os.Args[2] { + case "list": + fmt.Println("Usage: eon list (remote/local)") + fmt.Println("- remote: lists packages available in the repositories.") + fmt.Println("- local: lists installed packages.") + case "info": + fmt.Println("Usage: eon info ") + fmt.Println("Shows information about a package.") + case "install": + fmt.Println("Usage: eon install []") + fmt.Println("Installs a package.") + case "remove": + fmt.Println("Usage: eon remove ") + fmt.Println("Removes a package.") + case "clean": + fmt.Println("Usage: eon clean") + fmt.Println("Removes unused dependencies.") + case "repo": + fmt.Println("Usage: eon repo (add/remove/list)") + fmt.Println("- add : adds a repository.") + fmt.Println("- remove : removes a repository.") + fmt.Println("- list: lists repositories.") + case "help": + fmt.Println("Usage: eon help (list/info/install/remove/clean/repo/help) [args]") + fmt.Println("Shows help.") + default: + fmt.Println(color.RedString("Unknown command: " + os.Args[2])) + os.Exit(1) + } + } + case "install": + var forceMode bool + var inMemoryMode bool + if len(os.Args) < 3 { + fmt.Println("Usage: eon install ") + os.Exit(1) + } + var localPackageList []string + fileInfos := make(map[string]os.FileInfo) + var repoPackageList []string + for _, pkg := range os.Args[2:] { + if !strings.HasPrefix(pkg, "-") { + fileInfo, err := os.Stat(pkg) + if err != nil { + if os.IsNotExist(err) { + // This unholy regex is a package name validator. It validates repository-name/package-name/1.0.0-prerelease.1+meta.1 + // The regex is so unholy it breaks JetBrains' regex parser, so I had to disable it. + //goland:noinspection RegExpUnnecessaryNonCapturingGroup + match, err := regexp.Match(`^(?:([a-z0-9_-]+)/)?([a-z0-9_-]+)(?:/(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?)$`, []byte(pkg)) + if err != nil { + fmt.Println(color.RedString("Failed to validate package name: " + err.Error())) + os.Exit(1) + } + if !match { + fmt.Println(color.RedString("Invalid package name: " + pkg)) + os.Exit(1) + } else { + repoPackageList = append(repoPackageList, pkg) + } + } + } else { + localPackageList = append(localPackageList, pkg) + fileInfos[pkg] = fileInfo + } + } else { + switch pkg { + case "--force", "-f": + forceMode = true + case "--optimizeForSpeed", "-O": + inMemoryMode = true + } + } + } + // We contact the database before we print anything as to not break the formatting. + err := common.EstablishDBConnection(logger) + if err != nil { + fmt.Println(color.RedString("Failed to establish a connection to the database: " + err.Error())) + os.Exit(1) + } + // Ok. Let's give the user an overview of what we're going to do. + if len(localPackageList) > 0 || len(repoPackageList) > 0 { + fmt.Println("The following packages will be installed:") + width, _, err := term.GetSize(int(os.Stdout.Fd())) + if err != nil { + fmt.Println(color.RedString("Failed to get terminal width: " + err.Error())) + os.Exit(1) + } + if width < 42 { + fmt.Println(color.RedString("Terminal too small. Minimum required width: 42 characters.")) + os.Exit(1) + } + for range width { + fmt.Print("=") + } + fmt.Print("\n ") + tableList := []string{"Package", "Architecture", "Version", "Repository", "Size", "Action"} + maxSize := (width - 6) / 6 + for _, item := range tableList { + common.PrintWithEvenPadding(item, maxSize) + } + fmt.Print("\n") + for range width { + fmt.Print("=") + } + fmt.Print("\n") + var epkListLocal []common.InstallPackage + for _, pkg := range localPackageList { + var finalisedList []string + epkFile, err := os.Open(pkg) + if err != nil { + fmt.Println(color.RedString("Failed to open package: " + err.Error())) + os.Exit(1) + } + + var displayData lib.EPKPreMap + var vagueErr error + var epkBytes bytes.Buffer + if !inMemoryMode { + displayData, err, vagueErr = lib.PreMapEPK(lib.StreamOrBytes{Stream: epkFile, IsStream: true}, fileInfos[pkg].Size()) + } else { + _, err = io.Copy(bufio.NewWriter(&epkBytes), epkFile) + if err != nil { + fmt.Println(color.RedString("Failed to read package into memory: " + err.Error() + + ", have you tried disabling in-memory mode?")) + os.Exit(1) + } + err := epkFile.Close() + if err != nil { + fmt.Println(color.HiYellowString("Failed to close package file: " + err.Error() + ", memory leak possible.")) + } + displayData, err, vagueErr = lib.PreMapEPK(lib.StreamOrBytes{Bytes: epkBytes.Bytes(), IsStream: false}, fileInfos[pkg].Size()) + } + if err != nil || vagueErr != nil { + common.PreMapEPKHandleError(err, vagueErr, logger) + os.Exit(1) + } + + version, exists, err := common.DefaultCheckEPKInDB(displayData.Name) + if err != nil { + fmt.Println(color.RedString("Failed to check for package in database: " + err.Error())) + } + + // TODO: Implement some dependency management more-or-less here. + + name := displayData.Name + architecture := displayData.Architecture + versionDisplay := displayData.Version.String() + repository := "Local file" + size := humanize.Bytes(uint64(displayData.Size)) + action := "Install" + if exists { + if version.Compare(&displayData.Version) != -1 { + if !forceMode { + name = color.GreenString(name) + architecture = color.GreenString(architecture) + versionDisplay = color.GreenString(versionDisplay) + repository = color.GreenString(repository) + size = color.GreenString(size) + action = color.GreenString("Skip") + } else { + action = "Forced installation" + displayData.IsUpgrade = true + if !inMemoryMode { + epkListLocal = append(epkListLocal, common.InstallPackage{ + StreamOrBytes: lib.StreamOrBytes{ + Stream: epkFile, + IsStream: true, + }, + EPKPreMap: &displayData, + LocalFile: true, + }) + } else { + epkListLocal = append(epkListLocal, common.InstallPackage{ + StreamOrBytes: lib.StreamOrBytes{ + Bytes: epkBytes.Bytes(), + IsStream: false, + }, + EPKPreMap: &displayData, + LocalFile: true, + }) + } + } + } else { + action = "Upgrade" + displayData.IsUpgrade = true + if !inMemoryMode { + epkListLocal = append(epkListLocal, common.InstallPackage{ + StreamOrBytes: lib.StreamOrBytes{ + Stream: epkFile, + IsStream: true, + }, + EPKPreMap: &displayData, + LocalFile: true, + }) + } else { + epkListLocal = append(epkListLocal, common.InstallPackage{ + StreamOrBytes: lib.StreamOrBytes{ + Bytes: epkBytes.Bytes(), + IsStream: false, + }, + EPKPreMap: &displayData, + LocalFile: true, + }) + } + } + } else { + displayData.IsUpgrade = false + if !inMemoryMode { + epkListLocal = append(epkListLocal, common.InstallPackage{ + StreamOrBytes: lib.StreamOrBytes{ + Stream: epkFile, + IsStream: true, + }, + EPKPreMap: &displayData, + LocalFile: true, + }) + } else { + epkListLocal = append(epkListLocal, common.InstallPackage{ + StreamOrBytes: lib.StreamOrBytes{ + Bytes: epkBytes.Bytes(), + IsStream: false, + }, + EPKPreMap: &displayData, + LocalFile: true, + }) + } + } + + finalisedList = append(finalisedList, name) + finalisedList = append(finalisedList, architecture) + finalisedList = append(finalisedList, versionDisplay) + finalisedList = append(finalisedList, repository) + finalisedList = append(finalisedList, size) + finalisedList = append(finalisedList, action) + fmt.Print(" ") + for _, item := range finalisedList { + common.PrintWithEvenPadding(item, maxSize) + } + fmt.Print("\n") + } + //for _, pkg := range repoPackageList { + // var finalisedList []string + // lib.SearchRepository() + //} + for range width { + fmt.Print("=") + } + fmt.Print("\n") + if len(epkListLocal) > 0 { + response := logger.LogFunc(lib.Log{ + Level: "INFO", + Content: "Proceed with installation (y/n)?", + Prompt: true, + PlaySound: true, + }) + if strings.ToLower(response) == "y" { + // We hide the cursor because it makes the progress bar look weird and other package managers hide + // it during installation. For some reason, it builds suspense. Or it does with me anyway, when + // a program hides the cursor, it makes me think twice than to Ctrl+C it :P + // - Arzumify + fmt.Print("\033[?25l") + // Time to install things. + for _, streamOrBytesAndPreMap := range epkListLocal { + metadata, err, vagueErr := lib.FullyMapMetadata(streamOrBytesAndPreMap.StreamOrBytes, + streamOrBytesAndPreMap.EPKPreMap, common.DefaultGetFingerprintFromDB, + common.DefaultAddFingerprintToDB, logger) + if err != nil || vagueErr != nil { + common.FullyMapMetadataHandleError(err, vagueErr, logger) + } + // Install the package. + tempDir, err, vagueErr := lib.InstallEPK(streamOrBytesAndPreMap.StreamOrBytes, + metadata, streamOrBytesAndPreMap.EPKPreMap, common.DefaultAddEPKToDB, logger) + if err != nil || vagueErr != nil { + common.InstallEPKHandleError(tempDir, err, vagueErr, logger) + } + // Done! + fmt.Println("Installed package: " + streamOrBytesAndPreMap.EPKPreMap.Name) + } + // We show the cursor again because we're done with the progress bar. + // We show the cursor again because we're done with the progress bar. + fmt.Print("\033[?25h") + } else { + fmt.Println("Installation cancelled.") + os.Exit(1) + } + } else { + fmt.Println("No packages left to install. To force re-install / downgrade, use the --force flag, " + + "though this may result in breakage.") + os.Exit(0) + } + } else { + fmt.Println("No packages to install.") + os.Exit(0) + } + case "repo": + if len(os.Args) < 3 { + fmt.Println("Usage: eon repo (add/remove/list)") + os.Exit(1) + } + + switch os.Args[2] { + case "add": + if len(os.Args) < 4 { + fmt.Println("Usage: eon repo add ") + os.Exit(1) + } else { + err := common.EstablishDBConnection(logger) + if err != nil { + fmt.Println(color.RedString("Failed to establish a connection to the database: " + err.Error())) + os.Exit(1) + } + err, vagueErr := lib.AddRepository(os.Args[3], common.DefaultAddRepositoryToDB, common.DefaultGetFingerprintFromDB, common.DefaultAddFingerprintToDB, common.DefaultAddRemotePackageToDB, logger) + if err != nil || vagueErr != nil { + common.AddRepositoryHandleError(err, vagueErr, logger) + } + } + case "remove": + if len(os.Args) < 4 { + fmt.Println("Usage: eon repo remove ") + os.Exit(1) + } else { + err := common.EstablishDBConnection(logger) + if err != nil { + fmt.Println(color.RedString("Failed to establish a connection to the database: " + err.Error())) + os.Exit(1) + } + err, vagueErr := lib.RemoveRepository(os.Args[3], common.DefaultRemoveRepositoryFromDB, logger) + if err != nil || vagueErr != nil { + common.RemoveRepositoryHandleError(err, vagueErr, logger) + } + } + case "list": + err := common.EstablishDBConnection(logger) + if err != nil { + fmt.Println(color.RedString("Failed to establish a connection to the database: " + err.Error())) + os.Exit(1) + } + repos, err := common.DefaultListRepositoriesInDB() + if err != nil { + fmt.Println(color.RedString("Failed to get repositories: " + err.Error())) + os.Exit(1) + } + if len(repos) == 0 { + fmt.Println("No repositories.") + } else { + fmt.Println("Repositories:") + for _, repo := range repos { + fmt.Println("\n" + repo.Name + ":\n" + " URL: " + repo.URL + "\n Owner: " + repo.Owner) + } + fmt.Println() + } + } + default: + fmt.Println(color.RedString("Unknown or unimplemented command: " + os.Args[1])) + os.Exit(1) + } +} diff --git a/common/main.go b/common/main.go new file mode 100644 index 0000000..6a72a30 --- /dev/null +++ b/common/main.go @@ -0,0 +1,956 @@ +package common + +import ( + "encoding/binary" + "eon/lib" + + "bytes" + "errors" + "fmt" + "os" + "plugin" + "regexp" + "strconv" + "strings" + "time" + + "crypto/ed25519" + "database/sql" + "math/big" + + "golang.org/x/term" + + "github.com/Masterminds/semver" + "github.com/fatih/color" + "modernc.org/sqlite" +) + +type InstallPackage struct { + LocalFile bool + Url string + StreamOrBytes lib.StreamOrBytes + EPKPreMap *lib.EPKPreMap +} + +type PluginInfo struct { + Name string + HasErrHandler bool + HasVagueErr bool + OverridesExisting bool +} + +type Plugin struct { + Info PluginInfo + MainFunc func(version string, dbVersion string, args []string, conn *sql.DB, logger *lib.Logger) (etc map[string]interface{}, err error, vagueErr error) + ErrHandler func(etc map[string]interface{}, err error, vagueErr error, logger *lib.Logger) +} + +var conn *sql.DB +var dbVersion = semver.MustParse("1.0.0-beta.2") + +var DefaultLogger = lib.Logger{ + LogFunc: func(log lib.Log) string { + if log.PlaySound { + fmt.Print("\a") + } + switch log.Level { + case "WARN": + fmt.Println(color.YellowString(log.Content)) + case "ERROR": + fmt.Println(color.HiYellowString(log.Content)) + case "CRITICAL": + fmt.Println(color.HiRedString(log.Content)) + case "FATAL": + fmt.Println(color.RedString(log.Content)) + os.Exit(1) + case "PROGRESS": + // Maths time! We need to calculate the percentage of the progress bar. + // Convert the total and progress to big.Floats so we can do division. + floatTotal := new(big.Float) + floatProgress := new(big.Float) + floatTotal.SetInt(log.Total) + floatProgress.SetInt(log.Progress) + // Calculate the fraction we need to multiply by 100 to get the percentage. + percentageBig := new(big.Float).Quo(floatProgress, floatTotal) + percentage, _ := percentageBig.Float64() + // Get the terminal width so we can calculate the width of the progress bar. + width, _, err := term.GetSize(int(os.Stdout.Fd())) + if err != nil { + fmt.Println(color.RedString("Failed to get terminal width: " + err.Error())) + os.Exit(1) + } + // Calculate the percentage in text form. + percentageText := " " + strconv.Itoa(int(percentage*100)) + "%" + // We need to give the percentage text a bit of padding so it doesn't look weird. + switch len(percentageText) { + case 3: + percentageText = " " + percentageText + " " + case 4: + percentageText = percentageText + " " + } + // Print the percentage text and the beginning of the progress bar. + fmt.Print("\r" + percentageText + " [") + + // Calculate how much of the bar should be filled. + targetWidth := int(float64(width-8) * percentage) + // Print the filled part of the bar. + for range targetWidth { + fmt.Print("=") + } + // If it isn't 100%, print the arrow. + if int(percentage) != 1 { + fmt.Print(">") + } + // Print the empty part of the bar. + for range width - targetWidth - 9 { + fmt.Print(" ") + } + // And voilĂ ! Cap the bar off. Don't put a space here, because it causes a newline in some terminals. + if log.Overwrite { + fmt.Print("]") + } else { + fmt.Print("]\n") + } + default: + fmt.Println(log.Content) + } + if log.Prompt { + fmt.Print(": ") + var userInput string + _, err := fmt.Scanln(&userInput) + if err != nil { + fmt.Println(color.RedString("Failed to read input: " + err.Error())) + os.Exit(1) + } else { + return userInput + } + } + return "" + }, + PromptSupported: true, + ProgressSupported: true, +} + +func LoadPlugin(pluginName string, logger *lib.Logger) (Plugin, error) { + // Check the plugin's signature + // Load the plugin file + pluginFile, err := os.ReadFile("/var/lib/eon/plugins/" + pluginName + ".so") + if err != nil { + return Plugin{}, err + } + // Load the signature file + bypassSignature := false + sigFile, err := os.ReadFile("/var/lib/eon/plugins/" + pluginName + ".eps") + if err != nil { + if errors.Is(err, os.ErrNotExist) { + response := logger.LogFunc(lib.Log{ + Level: "WARN", + Content: "Plugin " + pluginName + " is not signed. That means that this code is UNTRUSTED and may be " + + "MALWARE. This can seriously harm your system! Only proceed if you trust the plugin author, and " + + "are absolutely 100% sure it is from them! Do you want to load the plugin anyway (y/n)?", + Prompt: true, + PlaySound: true, + }) + if strings.ToLower(response) != "y" { + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Plugin " + pluginName + " is not signed. Refusing to load the plugin. Glad you have some " + + "common sense!", + Prompt: false, + }) + } else { + // This is your final warning before you blow your system to bits. + // If you are a confused user looking through the source code, seriously, DO NOT load the plugin! + // Any good plugin author should sign their plugins. Even if you are testing a plugin, you should + // sign it. If your friend doesn't sign their plugin, tell them to sign it! + finalWarning := logger.LogFunc(lib.Log{ + Level: "WARN", + Content: "Final warning. Is what you're doing really worth risking your entire system? If someone " + + "is telling you to bypass this warning, they are probably LYING! Are you SURE you know what " + + "you're doing (if you do, you probably won't be here)? If you would like to load the plugin, " + + "please type the following (case sensitive): \"Yes, I know what I'm doing, no one is telling me " + + "to do this, destroy my system!\". Otherwise, type anything else.", + Prompt: true, + PlaySound: true, + }) + if finalWarning != "Yes, I know what I'm doing, no one is telling me to do this, destroy my system!" { + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Plugin " + pluginName + " is not signed. Refusing to load the plugin. Glad you have " + + "some common sense!", + Prompt: false, + }) + } else { + logger.LogFunc(lib.Log{ + Level: "WARN", + Content: "I'll give you 5 seconds to Ctrl+C out of this. If you don't, you're on your own.", + Prompt: false, + }) + time.Sleep(5 * time.Second) + logger.LogFunc(lib.Log{ + Level: "WARN", + Content: "You asked for it. Loading plugin " + pluginName + " without a signature. Don't say I " + + "didn't warn you.", + Prompt: false, + }) + bypassSignature = true + } + } + } + } + // Get the public key from the database + if !bypassSignature { + err = conn.QueryRow("SELECT fingerprint FROM keys WHERE owner = ?", string(sigFile[96:])).Scan(&sigFile) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + fingerprint := lib.ByteToFingerprint(sigFile[:32]) + logger.LogFunc(lib.Log{ + Level: "WARN", + Content: "The public key for the plugin " + pluginName + " is not in the database:\n " + string(sigFile[96:]) + " " + fingerprint + "\n Do you want to add it to the database (y/n)?", + Prompt: true, + }) + } + } + if ed25519.Verify(sigFile[:32], pluginFile, sigFile[32:96]) { + return Plugin{}, errors.New("invalid signature") + } + } + // Load the plugin. Unfortunately, there seems to be no way to load a plugin from memory, so we have to use the + // filesystem. + loadedPlugin, err := plugin.Open("/var/lib/eon/plugins/" + pluginName + ".so") + if err != nil { + return Plugin{}, err + } + // Look up the Info function + infoSymbol, err := loadedPlugin.Lookup("Info") + if err != nil { + return Plugin{}, err + } + // Assert the Info function to the correct type + infoFunction, ok := infoSymbol.(func() PluginInfo) + if !ok { + return Plugin{}, errors.New("plugin " + pluginName + " does not have an Info function") + } + // Get the plugin info + pluginInfo := infoFunction() + // Look up the Main function + mainSymbol, err := loadedPlugin.Lookup("Main") + if err != nil { + return Plugin{}, err + } + // Assert the Main function to the correct type + main, ok := mainSymbol.(func(version string, dbVersion string, args []string, conn *sql.DB, logger *lib.Logger) (etc map[string]interface{}, err error, vagueErr error)) + if !ok { + return Plugin{}, errors.New("plugin " + pluginName + " does not have a Main function") + } + // Return the plugin struct + return Plugin{ + Info: pluginInfo, + MainFunc: main, + }, nil +} + +func PluginInstalled(pluginName string) bool { + _, err := os.Stat("/var/lib/eon/plugins/" + pluginName + ".so") + if err != nil { + return false + } else { + return true + } +} + +func InitDB(conn *sql.DB) error { + _, err := conn.Exec("DROP TABLE IF EXISTS global;" + + "DROP TABLE IF EXISTS packages;" + + "DROP TABLE IF EXISTS keys;" + + "DROP TABLE IF EXISTS repositories;" + + "DROP TABLE IF EXISTS remotePackages;") + if err != nil { + return err + } + + // Huge query moment. This is way too big to read comfortably, but too bad! It breaks the Jetbrains SQL formatter if + // I break it into multiple lines. + _, err = conn.Exec("CREATE TABLE packages (name TEXT NOT NULL UNIQUE, description TEXT NOT NULL, longDescription TEXT NOT NULL, version TEXT NOT NULL, author TEXT NOT NULL, license TEXT NOT NULL, architecture TEXT NOT NULL, size INTEGER NOT NULL, dependencies TEXT NOT NULL, removeScript TEXT NOT NULL, hasRemoveScript BOOLEAN NOT NULL, isDependency BOOLEAN NOT NULL DEFAULT false, repository TEXT)") + if err != nil { + return err + } + + // We store the RSA fingerprint of a public key so we can alert if a key is already in the database. + _, err = conn.Exec("CREATE TABLE keys (fingerprint BLOB NOT NULL, owner TEXT NOT NULL UNIQUE)") + if err != nil { + return err + } + + _, err = conn.Exec("CREATE TABLE repositories (url TEXT NOT NULL UNIQUE, name TEXT NOT NULL UNIQUE, owner TEXT NOT NULL, description TEXT NOT NULL)") + if err != nil { + return err + } + + // Way to big. Blame IntelliJ. + _, err = conn.Exec("CREATE TABLE remotePackages (name TEXT NOT NULL UNIQUE, author TEXT NOT NULL, description TEXT NOT NULL, version TEXT NOT NULL, architecture TEXT NOT NULL, size BLOB NOT NULL, dependencies TEXT NOT NULL, path TEXT NOT NULL, arch TEXT NOT NULL, hash TEXT NOT NULL, repository TEXT NOT NULL)") + if err != nil { + return err + } + + // Having exists here makes sure that there is only one global row in the table. This is a bit of a hack, + // but it's the only way to make sure that the version and endian-ness are always part of the database. + + // Note that this is the only hack in this program (so far)! I feel somewhat proud, especially since it's less of + // a hack and more not utilizing the full power of SQL. + // - Arzumify + _, err = conn.Exec("CREATE TABLE global (version TEXT NOT NULL, uniquenessCheck BOOLEAN NOT NULL UNIQUE CHECK (uniquenessCheck = true) DEFAULT true)") + if err != nil { + return err + } + + // We insert global last so that if the program crashes, the database is not marked as initialized. + _, err = conn.Exec("INSERT INTO global (version) VALUES (?)", + dbVersion.String()) + if err != nil { + return err + } + + return nil +} + +// EstablishDBConnection establishes a connection to the database. If the database does not exist, it will be created. +func EstablishDBConnection(logger *lib.Logger) error { + _, err := os.Stat("/var/lib/eon/packages.db") + if err != nil { + if errors.Is(err, os.ErrNotExist) { + err := os.MkdirAll("/var/lib/eon", 0755) + if err != nil { + return err + } + } + } + + conn, err = sql.Open("sqlite", "/var/lib/eon/packages.db") + if err != nil { + return err + } + + var version string + err = conn.QueryRow("SELECT version FROM global").Scan(&version) + if err != nil { + if err.(*sqlite.Error).Code() == 1 || errors.Is(err, sql.ErrNoRows) { + // Initialize database + err := InitDB(conn) + if err != nil { + return err + } + } else { + return err + } + } else { + // Check version + semanticVersion, err := semver.NewVersion(version) + if err != nil { + return err + } + + isCurrentVersion := semanticVersion.Compare(dbVersion) + if isCurrentVersion < 0 { + if !PluginInstalled("database-migration") { + // Warn the user that the database is outdated + if logger.PromptSupported { + response := logger.LogFunc(lib.Log{ + Level: "WARN", + Content: "The database is outdated and may not be compatible with the current version of Eon. " + + "The database migration plugin is not installed. Would you like to reset the database (y/n)?", + Prompt: true, + }) + if strings.ToLower(response) == "y" { + err := InitDB(conn) + if err != nil { + return err + } + } else { + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "The database is corrupted and cannot be used. Please reset the database.", + Prompt: false, + }) + os.Exit(1) + } + } else { + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "The database is corrupted and cannot be used. Please reset the database.", + Prompt: false, + }) + os.Exit(1) + } + } else { + logger.LogFunc(lib.Log{ + Level: "INFO", + Content: "Loading plugin for database migration... All logs will be returned by the plugin until the migration is complete.", + Prompt: false, + }) + loadedPlugin, err := LoadPlugin("database-migration", logger) + if err != nil { + return err + } + etc, err, vagueErr := loadedPlugin.MainFunc(dbVersion.String(), version, nil, conn, logger) + if err != nil || vagueErr != nil { + if loadedPlugin.Info.HasErrHandler { + loadedPlugin.ErrHandler(etc, err, vagueErr, logger) + return errors.New("plugin " + loadedPlugin.Info.Name + "'s error handler did not stop program execution") + } else { + if loadedPlugin.Info.HasVagueErr { + return errors.New(vagueErr.Error() + ": " + err.Error()) + } else { + return err + } + } + } else { + logger.LogFunc(lib.Log{ + Level: "INFO", + Content: "Database migrated (hopefully). Please consult the logs returned by the plugin for more information", + Prompt: false, + }) + } + } + } else if isCurrentVersion > 0 { + // Warn the user that the database is ahead of the current version of Eon + logger.LogFunc(lib.Log{ + Level: "WARN", + Content: "The database is ahead of the current version of Eon. This may cause compatibility issues", + Prompt: false, + }) + } + } + return nil +} + +func DefaultAddEPKToDB(metadata *lib.Metadata, removeScript []byte, dependency bool, hasRemoveScript bool, size int64) error { + // If it already exists, delete it. This may happen in a force-install scenario. + _, err := conn.Exec("DELETE FROM packages WHERE name = ?", metadata.Name) + if err != nil { + return err + } + + var dependencies string + if len(metadata.Dependencies) > 0 { + // This is the world's most basic JSON marshaller :P + // - Arzumify + dependencies = "[" + strings.Join(metadata.Dependencies, ", ") + "]" + } else { + // Best to make sure that the dependencies are always a JSON array, even if it's empty. Strings.Join might mess + // it up by adding whitespace or something. + dependencies = "[]" + } + + // Another fat unreadable line so Jetbrains doesn't break the SQL formatter. Too bad! + // But seriously though why doesn't Jetbrains support this? It's literally their own IDE which tells me to not make + // super-long lines, but then doesn't support it. + // And I pay huge amounts of money for this. + + // Not that I'm complaining or anything. + // - Arzumify + _, err = conn.Exec("INSERT INTO packages (name, description, longDescription, version, author, license, architecture, size, dependencies, removeScript, hasRemoveScript, isDependency) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + metadata.Name, metadata.Description, metadata.LongDescription, metadata.Version.String(), metadata.Author, + metadata.License, metadata.Architecture, size, dependencies, string(removeScript), hasRemoveScript, dependency) + if err != nil { + return err + } + + // Note I never complain a lot in lib/main.go, because that's the one other people will probably use. + // common/main.go is very tailored towards cmd/main.go, and is probably worth nothing to anything other than CLIs + // which like to use my style of logging, error handling, database management, progress bars, etc. + // - Arzumify + // P.S I sign off comments which have my personal thoughts. I do write other ones, but they're usually more formal + // and contain less of... me. + // Ok I promise I'll stop now and actually let the compiler compile. + + return nil +} + +// DefaultCheckEPKInDB checks if an EPK is in the database. +func DefaultCheckEPKInDB(name string) (*semver.Version, bool, error) { + var versionString string + err := conn.QueryRow("SELECT version FROM packages WHERE name = ?", name).Scan(&versionString) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return &semver.Version{}, false, nil + } + return &semver.Version{}, false, err + } + version, err := semver.NewVersion(versionString) + if err != nil { + return &semver.Version{}, true, err + } + return version, true, nil +} + +func DefaultGetEPKFromDB(name string) (lib.Metadata, string, bool, bool, int64, error) { + var metadata lib.Metadata + var removeScript string + var dependency bool + var versionString string + var dependencies string + var hasRemoveScript bool + var size int64 + err := conn.QueryRow("SELECT name, description, longDescription, version, author, license, architecture, size, "+ + "dependencies, removeScript, hasRemoveScript, isDependency FROM packages WHERE name = ?", name).Scan( + &metadata.Name, &metadata.Description, &metadata.LongDescription, &versionString, &metadata.Author, + &metadata.License, &metadata.Architecture, &size, &dependencies, &removeScript, &hasRemoveScript, + &dependency) + if err != nil { + return lib.Metadata{}, "", false, false, 0, err + } + // This is the world's most basic JSON unmarshaller :P + // - Arzumify + metadata.Dependencies = strings.Split(strings.TrimSuffix(strings.TrimPrefix(dependencies, "["), "]"), ", ") + version, err := semver.NewVersion(versionString) + if err != nil { + return lib.Metadata{}, "", false, false, 0, err + } + // For some reason NewVersion returns a pointer + metadata.Version = *version + return metadata, removeScript, dependency, hasRemoveScript, size, nil +} + +func DefaultAddFingerprintToDB(fingerprint []byte, owner string, replace bool) error { + if replace { + _, err := conn.Exec("UPDATE keys SET owner = ? AND fingerprint = ? WHERE owner = ? OR fingerprint = ?", owner, fingerprint, owner, fingerprint) + if err != nil { + return err + } else { + return nil + } + } else { + _, err := conn.Exec("INSERT INTO keys (fingerprint, owner) VALUES (?, ?)", fingerprint, owner) + if err != nil { + return err + } else { + return nil + } + } +} + +func DefaultGetFingerprintFromDB(fingerprint []byte, author string) (bool, bool, bool, error) { + var authorCheck string + var fingerprintCheck []byte + err := conn.QueryRow("SELECT owner, fingerprint FROM keys WHERE owner = ? OR fingerprint = ?", author, fingerprint).Scan(&authorCheck, &fingerprintCheck) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return false, false, false, nil + } + return false, false, false, err + } else { + if authorCheck == author && bytes.Equal(fingerprintCheck, fingerprint) { + return true, true, true, nil + } else if authorCheck == author { + return true, false, true, nil + } else { + return true, true, false, nil + } + } +} + +func DefaultAddRepositoryToDB(repository lib.Repository) error { + _, err := conn.Exec("INSERT INTO repositories (url, name, owner, description) VALUES (?, ?, ?, ?)", + repository.URL, repository.Name, repository.Owner, repository.Description) + if err != nil { + return err + } + return nil +} + +func DefaultRemoveRepositoryFromDB(repository string) error { + _, err := conn.Exec("DELETE FROM repositories WHERE name = ?", repository) + if err != nil { + return err + } + + _, err = conn.Exec("DELETE FROM remotePackages WHERE repository = ?", repository) + if err != nil { + return err + } + return nil +} + +func DefaultListRepositoriesInDB() ([]lib.Repository, error) { + rows, err := conn.Query("SELECT url, name, owner FROM repositories") + if err != nil { + return []lib.Repository{}, err + } + var repositories []lib.Repository + for rows.Next() { + var url, name, owner string + err := rows.Scan(&url, &name, &owner) + if err != nil { + return []lib.Repository{}, err + } + repositories = append(repositories, lib.Repository{Name: name, URL: url, Owner: owner}) + } + return repositories, nil +} + +func DefaultAddRemotePackageToDB(repository string, remoteEPK lib.RemoteEPK) error { + var dependencies string + // This is the world's most basic JSON marshaller :P + // - Arzumify + if len(remoteEPK.Dependencies) > 0 { + dependencies = "[" + strings.Join(remoteEPK.Dependencies, ", ") + "]" + } else { + // Best to make sure that the dependencies are always a JSON array, even if it's empty. Strings.Join might mess + // it up by adding whitespace or something. + dependencies = "[]" + } + + // We use little-endian because big-endianness is never used on 99% of systems. Also, byte order is a myth. + hashBytes := make([]byte, 8) + binary.LittleEndian.PutUint64(hashBytes, remoteEPK.EPKHash) + + _, err := conn.Exec("INSERT INTO remotePackages (name, author, description, version, architecture, size, dependencies, path, arch, hash, repository) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + remoteEPK.Name, remoteEPK.Author, remoteEPK.Description, remoteEPK.Version.String(), remoteEPK.Architecture, + remoteEPK.CompressedSize, dependencies, remoteEPK.Path, remoteEPK.Arch, hashBytes, repository) + if err != nil { + return err + } + + return nil +} + +func PrintWithEvenPadding(item string, maxSize int) { + var printItem string + // Make sure green escape sequences are not counted in the length by using a regex. + noGreenEscape := regexp.MustCompile(`\x1b\[32m|\x1b\[0m`) + // Minus 2 to ensure we have space for padding. + if len(noGreenEscape.ReplaceAllString(item, "")) > maxSize-2 { + // We have already checked that the terminal is wide enough, so we shouldn't have to worry about + // maxSize being less than 6. + // It's minus 5 because we need to add "..." to the end of the string and have space for padding. + printItem = item[:maxSize-5] + "..." + } else { + printItem = item + } + // Now we need to check how much space we have left for padding. + padding := maxSize - len(noGreenEscape.ReplaceAllString(printItem, "")) + // Check if padding is odd or even. + if padding%2 == 0 { + // Padding is even. + for range padding / 2 { + fmt.Print(" ") + } + fmt.Print(printItem) + for range padding / 2 { + fmt.Print(" ") + } + } else { + // Padding is odd. + for range (padding + 1) / 2 { + fmt.Print(" ") + } + fmt.Print(printItem) + for range (padding - 1) / 2 { + fmt.Print(" ") + } + } +} + +// I hate the vagueError system - it feels too much like a hack, but there's no chance in hell I'm going to find every +// error from every library I use and make a HandleError function for it. I'm not that insane. +// Anyway I should put a useful formal comment so that people using IntelliSense or whatever it's called in VSCode can +// see what this function does. +// - Arzumify + +// PreMapEPKHandleError handles errors that occur during the mapping of an EPKs display data. +func PreMapEPKHandleError(err error, vagueErr error, logger *lib.Logger) { + switch { + case errors.Is(vagueErr, lib.ErrPreMapEPKFailedToReadError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to read file: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrPreMapEPKNotEPKError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "The specified file is not an EPK.", + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrPreMapEPKInvalidEndianError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "The specified file is corrupted or invalid: invalid endian", + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrPreMapEPKCouldNotParseJSONError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to parse metadata JSON: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrPreMapEPKCouldNotMapJSONError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to map metadata JSON: " + err.Error(), + Prompt: false, + }) + } +} + +// FullyMapMetadataHandleError handles errors that occur during the mapping of an EPK file. +func FullyMapMetadataHandleError(err error, vagueErr error, logger *lib.Logger) { + switch { + case errors.Is(vagueErr, lib.ErrFullyMapMetadataFailedToReadError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to read file: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrFullyMapMetadataFailedToJumpError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to jump to metadata: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrFullyMapMetadataFailedToAddFingerprintError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to add fingerprint to database: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrFullyMapMetadataFailedToGetFingerprintError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to get fingerprint from database: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrFullyMapMetadataInvalidSignatureError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "The specified file is corrupted or invalid: signature mismatch", + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrFullyMapMetadataCouldNotMapJSONError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to map metadata JSON: " + err.Error(), + Prompt: false, + }) + } +} + +// InstallEPKHandleError handles errors that occur during the installation of an EPK file. +func InstallEPKHandleError(tempDir string, err error, vagueErr error, logger *lib.Logger) { + doNotRemoveTempDir := false + switch { + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotCreateTempDirError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to create temporary directory: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotCreateZStandardReaderError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to create ZStandard reader: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotDecompressTarArchiveError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to decompress tar archive: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotCreateDirError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to create directory: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotStatDirError): + logger.LogFunc(lib.Log{ + Level: "ERROR", + Content: "Could not get file information about directory: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotStatFileError): + logger.LogFunc(lib.Log{ + Level: "ERROR", + Content: "Could not get file information about file: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotCreateFileError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to create file: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotCloseTarReaderError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to close tar reader: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotStatHookError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Could not get file information about hook: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotRunHookError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to run hook: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotAddEPKToDBError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to add EPK to database: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrInstallEPKCouldNotRemoveTempDirError): + logger.LogFunc(lib.Log{ + Level: "CRITICAL", + Content: "Failed to remove temporary directory: " + err.Error() + ", please remove the directory " + tempDir + " manually", + Prompt: false, + }) + doNotRemoveTempDir = true + } + if doNotRemoveTempDir { + err := os.RemoveAll(tempDir) + if err != nil { + logger.LogFunc(lib.Log{ + Level: "CRITICAL", + Content: "Failed to remove temporary directory: " + err.Error() + ", please remove the directory " + tempDir + " manually", + Prompt: false, + }) + } + } +} + +func AddRepositoryHandleError(err error, vagueErr error, logger *lib.Logger) { + switch { + case errors.Is(vagueErr, lib.ErrAddRepositoryCannotCreateRequestError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to create request: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryCannotSendRequestError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to send request: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryUnexpectedStatusCodeError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Unexpected status code: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryCannotReadResponseError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to read response: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryInvalidMagicError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Invalid magic: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryCannotHashError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to copy file to hash: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryUnmarshalMetadataError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to unmarshal metadata: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrFullyMapMetadataFailedToGetFingerprintError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to get fingerprint from database: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryFailedToAddFingerprintError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to add fingerprint to database: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryInvalidMetadataError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Invalid metadata: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryCannotCreateDirError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to create repository directory: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryCannotStatDirError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to get file information about repository directory: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryFailedToAddPackageError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to add package to database: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryRepositoryAlreadyExistsError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Repository already exists", + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrAddRepositoryFailedToAddRepositoryError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to add repository to database: " + err.Error(), + Prompt: false, + }) + + } +} + +func RemoveRepositoryHandleError(err error, vagueErr error, logger *lib.Logger) { + switch { + case errors.Is(vagueErr, lib.ErrRemoveRepositoryDoesNotExistError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Repository does not exist", + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrRemoveRepositoryCannotStatRepositoryError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to get file information about repository: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrRemoveRepositoryCannotRemoveRepositoryError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to remove repository files: " + err.Error(), + Prompt: false, + }) + case errors.Is(vagueErr, lib.ErrRemoveRepositoryFailedToRemoveRepositoryFromDBError): + logger.LogFunc(lib.Log{ + Level: "FATAL", + Content: "Failed to remove repository from database: " + err.Error(), + Prompt: false, + }) + } +} + +// Ironic how I sign off comments with my name when I'm literally the only contributor to this project, and git shows +// my name anyway. What is this, ftp? +// - Arzumify diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..1c9cbb1 --- /dev/null +++ b/go.mod @@ -0,0 +1,30 @@ +module eon + +go 1.23.0 + +require ( + github.com/Masterminds/semver v1.5.0 + github.com/cespare/xxhash/v2 v2.3.0 + github.com/dustin/go-humanize v1.0.1 + github.com/fatih/color v1.17.0 + github.com/klauspost/compress v1.17.9 + github.com/mattn/go-sqlite3 v1.14.22 + golang.org/x/term v0.23.0 + modernc.org/sqlite v1.32.0 +) + +require ( + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.23.0 // indirect + modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect + modernc.org/libc v1.55.3 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/strutil v1.2.0 // indirect + modernc.org/token v1.1.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b801636 --- /dev/null +++ b/go.sum @@ -0,0 +1,65 @@ +github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= +github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4= +github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= +github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= +golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM= +golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.23.0 h1:F6D4vR+EHoL9/sWAWgAR1H2DcHr4PareCbAaCo1RpuU= +golang.org/x/term v0.23.0/go.mod h1:DgV24QBUrK6jhZXl+20l6UWznPlwAHm1Q1mGHtydmSk= +golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= +golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= +modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= +modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= +modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= +modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= +modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= +modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= +modernc.org/sqlite v1.32.0 h1:6BM4uGza7bWypsw4fdLRsLxut6bHe4c58VeqjRgST8s= +modernc.org/sqlite v1.32.0/go.mod h1:UqoylwmTb9F+IqXERT8bW9zzOWN8qwAIcLdzeBZs4hA= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/lib/main.go b/lib/main.go new file mode 100644 index 0000000..2b7ec29 --- /dev/null +++ b/lib/main.go @@ -0,0 +1,1132 @@ +package lib + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + "time" + + "archive/tar" + "crypto/ed25519" + "encoding/binary" + "encoding/hex" + "encoding/json" + "math/big" + "net/http" + "os/exec" + "path/filepath" + + "github.com/Masterminds/semver" + "github.com/cespare/xxhash/v2" + "github.com/dustin/go-humanize" + "github.com/klauspost/compress/zstd" + "modernc.org/sqlite" +) + +// RemoteEPK is a struct that contains the metadata of an EPK from a remote repository +type RemoteEPK struct { + Name string + Author string + Description string + Version semver.Version + Architecture string + CompressedSize int64 + Dependencies []string + Path string + Arch string + EPKHash uint64 +} + +// Repository is a struct that contains the repository information +type Repository struct { + Name string + URL string + Owner string + Description string +} + +// SpecialFiles is a struct that contains the special files that are not to be deleted or replaced +type SpecialFiles struct { + NoDelete []string + NoReplace []string +} + +// Metadata is a struct that contains the metadata of the package +type Metadata struct { + Name string + Description string + LongDescription string + Version semver.Version + Author string + License string + Architecture string + Dependencies []string + SpecialFiles SpecialFiles + Size int64 + DecompressedSize big.Int +} + +// EPKPreMap is a struct that contains the metadata of the EPK +type EPKPreMap struct { + Name string + Author string + Architecture string + Version semver.Version + Size int64 + DecompressedSize big.Int + Dependencies []string + MetadataMap map[string]interface{} + IsLittleEndian bool + IsUpgrade bool + TarOffset int64 +} + +// PotentiallyNullEPKPreMap is a EPKPreMap that can be nil +type PotentiallyNullEPKPreMap struct { + EPKPreMap *EPKPreMap + Null bool +} + +// Log is a struct that contains the log information +type Log struct { + Level string + Content string + Prompt bool + PlaySound bool + Progress *big.Int + Total *big.Int + Overwrite bool +} + +// StreamOrBytes is a struct that contains either a stream or bytes, allowing optimising for memory or speed +type StreamOrBytes struct { + Stream *os.File + Bytes []byte + IsStream bool +} + +// Logger is a struct that contains the functions and properties of the logger +type Logger struct { + LogFunc func(Log) string + PromptSupported bool + ProgressSupported bool +} + +// Epk is a struct that contains the metadata and the tar archive of the EPK +type Epk struct { + Metadata Metadata + TarArchive []byte +} + +// interfaceToStringSlice converts an interface slice to a string slice +func interfaceToStringSlice(interfaceSlice []interface{}, interfaceName string) ([]string, error) { + // Yes, it's meant to be empty and not nil: JSON arrays are empty, not nil + //goland:noinspection GoPreferNilSlice + stringSlice := []string{} + for _, interfaceValue := range interfaceSlice { + stringValue, ok := interfaceValue.(string) + if !ok { + return nil, errors.New(interfaceName + " are not strings") + } + stringSlice = append(stringSlice, stringValue) + } + + return stringSlice, nil +} + +// ByteToFingerprint converts a byte slice to an Eon fingerprint, which is similar to a legacy-style OpenSSH fingerprint +func ByteToFingerprint(input []byte) string { + xxHashWriter := xxhash.New() + _, _ = xxHashWriter.Write(input) + inputString := hex.EncodeToString(xxhash.New().Sum(nil)) + var result []string + var previousChar rune + for index, char := range inputString { + if index%2 == 0 && index != 0 { + result = append(result, string(previousChar)+string(char)) + } else { + previousChar = char + } + } + return strings.Join(result, ":") +} + +// ConstMapEPKMetadataOffset is the offset of the metadata in the EPK: 3 magic bytes, 1 endian byte, 8 offset bytes, 64 signature bytes, and 32 public key bytes +var ConstMapEPKMetadataOffset int64 = 108 + +var ErrPreMapEPKFailedToReadError = errors.New("failed to read EPK") +var ErrPreMapEPKNotEPKError = errors.New("not an EPK") +var ErrPreMapEPKInvalidEndianError = errors.New("invalid endian") +var ErrPreMapEPKCouldNotParseJSONError = errors.New("error marshaling metadata") +var ErrPreMapEPKCouldNotMapJSONError = errors.New("error mapping metadata") + +// PreMapEPK maps enough data to create the display summary of an EPK +func PreMapEPK(epkBytes StreamOrBytes, epkSize int64) (EPKPreMap, error, error) { + // First, we need to check if it even is a EPK by checking the first 3 magic bytes + if epkBytes.IsStream { + var magicBytes = make([]byte, 3) + _, err := epkBytes.Stream.ReadAt(magicBytes, 0) + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKFailedToReadError + } + if string(magicBytes) != "epk" { + return EPKPreMap{}, nil, ErrPreMapEPKNotEPKError + } + } else { + if string(epkBytes.Bytes[0:3]) != "epk" { + return EPKPreMap{}, nil, ErrPreMapEPKNotEPKError + } + } + + // Let's determine the endian-ness of the EPK via the 3rd byte + var littleEndian bool + if epkBytes.IsStream { + var littleEndianByte = make([]byte, 1) + _, err := epkBytes.Stream.ReadAt(littleEndianByte, 3) + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKFailedToReadError + } + if littleEndianByte[0] == 0x6C { + littleEndian = true + } else if littleEndianByte[0] == 0x62 { + littleEndian = false + } else { + return EPKPreMap{}, nil, ErrPreMapEPKInvalidEndianError + } + } else { + if epkBytes.Bytes[3] == 0x6C { + littleEndian = true + } else if epkBytes.Bytes[3] == 0x62 { + littleEndian = false + } else { + return EPKPreMap{}, nil, ErrPreMapEPKInvalidEndianError + } + } + + // Now we can get the offsets of the tar archive + var tarArchiveOffset int64 + if epkBytes.IsStream { + var tarArchiveOffsetBytes = make([]byte, 8) + _, err := epkBytes.Stream.ReadAt(tarArchiveOffsetBytes, 4) + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKFailedToReadError + } + if littleEndian { + tarArchiveOffset = int64(binary.LittleEndian.Uint64(tarArchiveOffsetBytes)) + } else { + tarArchiveOffset = int64(binary.BigEndian.Uint64(tarArchiveOffsetBytes)) + } + } else { + if littleEndian { + tarArchiveOffset = int64(binary.LittleEndian.Uint64(epkBytes.Bytes[4:12])) + } else { + tarArchiveOffset = int64(binary.BigEndian.Uint64(epkBytes.Bytes[4:12])) + } + } + + // We don't need to validate the signature yet. We will do that when we map the full EPK, because it means + // we have to read the entire thing, which is a waste of resources, since we only need the metadata. + + // Let's map the display data + var displayDataMap map[string]interface{} + if epkBytes.IsStream { + var metadataBuffer = make([]byte, tarArchiveOffset-ConstMapEPKMetadataOffset) + _, err := epkBytes.Stream.ReadAt(metadataBuffer, ConstMapEPKMetadataOffset) + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKFailedToReadError + } + err = json.Unmarshal(metadataBuffer, &displayDataMap) + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKCouldNotParseJSONError + } + } else { + err := json.Unmarshal(epkBytes.Bytes[ConstMapEPKMetadataOffset:tarArchiveOffset], &displayDataMap) + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKCouldNotParseJSONError + } + } + + // Declare the parsedDisplayData object + var parsedDisplayData EPKPreMap + + // Add some of our data so that the full EPK can be mapped with less effort + parsedDisplayData.MetadataMap = displayDataMap + parsedDisplayData.IsLittleEndian = littleEndian + parsedDisplayData.Size = epkSize + parsedDisplayData.TarOffset = tarArchiveOffset + + // Map the display data + var ok bool + // Set the size + sizeBigInt, ok := displayDataMap["size"].(string) + if !ok { + return EPKPreMap{}, errors.New("size is not a string"), ErrPreMapEPKCouldNotMapJSONError + } + parsedDisplayData.DecompressedSize.SetString(sizeBigInt, 10) + // Set the name, author, version, arch, and dependencies + parsedDisplayData.Name, ok = displayDataMap["name"].(string) + if !ok { + return EPKPreMap{}, errors.New("name is not a string"), ErrPreMapEPKCouldNotMapJSONError + } + parsedDisplayData.Author, ok = displayDataMap["author"].(string) + if !ok { + return EPKPreMap{}, errors.New("author is not a string"), ErrPreMapEPKCouldNotMapJSONError + } + versionString, ok := displayDataMap["version"].(string) + if !ok { + return EPKPreMap{}, errors.New("version is not a string"), ErrPreMapEPKCouldNotMapJSONError + } + versionPointer, err := semver.NewVersion(versionString) + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKCouldNotMapJSONError + } + parsedDisplayData.Version = *versionPointer + parsedDisplayData.Architecture, ok = displayDataMap["arch"].(string) + if !ok { + return EPKPreMap{}, errors.New("arch is not a string"), ErrPreMapEPKCouldNotMapJSONError + } + dependencies, ok := displayDataMap["deps"].([]interface{}) + if !ok { + return EPKPreMap{}, errors.New("dependencies is not an array"), ErrPreMapEPKCouldNotMapJSONError + } + parsedDisplayData.Dependencies, err = interfaceToStringSlice(dependencies, "dependencies") + if err != nil { + return EPKPreMap{}, err, ErrPreMapEPKCouldNotMapJSONError + } + + return parsedDisplayData, nil, nil +} + +func handlePublicKeyCheck(exists bool, matchingAuthor bool, matchingFingerprint bool, publicKey []byte, author string, addFingerprintToDB func([]byte, string, bool) error, logger *Logger) error { + if !exists { + if logger.PromptSupported { + response := logger.LogFunc(Log{ + Level: "WARN", + Content: "Public key not found in database.\nthe public key fingerprint is: " + author + " " + ByteToFingerprint(publicKey) + + "\nWould you like to trust this key (y/n)?", + Prompt: true, + }) + if strings.ToLower(response) == "y" { + err := addFingerprintToDB(publicKey, author, false) + if err != nil { + return err + } else { + logger.LogFunc(Log{ + Level: "INFO", + Content: "Public key added to database.", + }) + } + } else { + logger.LogFunc(Log{ + Level: "INFO", + Content: "Installation cancelled.", + }) + } + } else { + logger.LogFunc(Log{ + Level: "FATAL", + Content: "Public key not found in database.\nthe public key fingerprint is:" + author + " " + ByteToFingerprint(publicKey) + + "\nSince non-interactive mode is enabled, the installation will not proceed.", + }) + } + } else if !matchingAuthor { + if logger.PromptSupported { + response := logger.LogFunc(Log{ + Level: "WARN", + Content: "Public key does not match the author.\nthe public key fingerprint is: " + author + " " + ByteToFingerprint(publicKey) + + "\nWould you like to replace the key (y/n)?", + Prompt: true, + }) + if strings.ToLower(response) == "y" { + err := addFingerprintToDB(publicKey, author, true) + if err != nil { + return err + } else { + logger.LogFunc(Log{ + Level: "INFO", + Content: "Public key replaced in database.", + }) + } + } else { + logger.LogFunc(Log{ + Level: "FATAL", + Content: "Installation cancelled.", + }) + } + } else { + logger.LogFunc(Log{ + Level: "FATAL", + Content: "Public key does not match the author.\nThe public key is :" + author + " " + ByteToFingerprint(publicKey) + + "\nSince non-interactive mode is enabled, the installation will not proceed.", + }) + } + } else if !matchingFingerprint { + if logger.PromptSupported { + response := logger.LogFunc(Log{ + Level: "WARN", + Content: "Public key fingerprint does not match the author.\nThe public key is :" + author + " " + ByteToFingerprint(publicKey) + + "\nThis may be a security risk. To replace the key, type \"Yes, do as I say!\". Otherwise, type anything else.", + Prompt: true, + }) + if response == "Yes, do as I say!" { + err := addFingerprintToDB(publicKey, author, true) + if err != nil { + return err + } else { + logger.LogFunc(Log{ + Level: "INFO", + Content: "Public key replaced in database.", + }) + } + } else { + logger.LogFunc(Log{ + Level: "FATAL", + Content: "Installation cancelled.", + }) + } + } else { + logger.LogFunc(Log{ + Level: "FATAL", + Content: "Public key fingerprint does not match the author.\nthe public key fingerprint is: " + author + " " + ByteToFingerprint(publicKey) + + "\nSince non-interactive mode is enabled, the installation will not proceed.", + }) + } + } + + return nil +} + +var ErrFullyMapMetadataFailedToJumpError = errors.New("failed to jump to offset") +var ErrFullyMapMetadataFailedToReadError = errors.New("failed to read EPK") +var ErrFullyMapMetadataFailedToAddFingerprintError = errors.New("failed to add fingerprint") +var ErrFullyMapMetadataFailedToGetFingerprintError = errors.New("failed to get fingerprint") +var ErrFullyMapMetadataInvalidSignatureError = errors.New("invalid signature") +var ErrFullyMapMetadataCouldNotMapJSONError = errors.New("error mapping metadata") + +// FullyMapMetadata maps an EPK file, but is significantly slower than PreMapEPK. Use PreMapEPK if you only need the display data. +// it pulls data from PreMapEPK to reduce the amount of work needed to map the EPK. +func FullyMapMetadata(epkBytes StreamOrBytes, preMap *EPKPreMap, checkFingerprintInDB func([]byte, string) (bool, bool, bool, error), addFingerprintToDB func([]byte, string, bool) error, logger *Logger) (*Metadata, error, error) { + // We define the signature and public key bytes here so that we can read them later + signature := make([]byte, 64) + publicKey := make([]byte, 32) + + if epkBytes.IsStream { + // Before we continue, check if the signature is valid + // To get the signature, we read from the 12th byte to the 76th byte + _, err := epkBytes.Stream.ReadAt(signature, 12) + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataFailedToReadError + } + + // To get the public key, we read from the 76th byte to the 108th byte + _, err = epkBytes.Stream.ReadAt(publicKey, 76) + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataFailedToReadError + } + } else { + // Make signature and public key the optimised bytes + signature = epkBytes.Bytes[12:76] + publicKey = epkBytes.Bytes[76:108] + } + + // Let's check for the public key in the database + exists, matchingAuthor, matchingFingerprint, err := checkFingerprintInDB(publicKey, preMap.Author) + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataFailedToGetFingerprintError + } else { + err := handlePublicKeyCheck(exists, matchingAuthor, matchingFingerprint, publicKey, preMap.Author, addFingerprintToDB, logger) + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataFailedToAddFingerprintError + } + } + + // We need to create a new xxHash instance + xxHash := xxhash.New() + if epkBytes.IsStream { + // Now we can verify the signature. First, we need to take the checksum of the metadata + // Seeking is better than using ReadAt because it allows us to not have to load the entire file into memory + _, err = epkBytes.Stream.Seek(ConstMapEPKMetadataOffset, io.SeekStart) + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataFailedToJumpError + } + + // Streaming bytes to the hash is more memory efficient + _, err = epkBytes.Stream.WriteTo(xxHash) + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataFailedToReadError + } + // Verify the signature (we verify the hash because it's cheaper than verifying the entire EPK) + if !ed25519.Verify(publicKey, xxHash.Sum(nil), signature) { + return &Metadata{}, nil, ErrFullyMapMetadataInvalidSignatureError + } + } else { + // We now verify the signature in one go without streaming + if !ed25519.Verify(publicKey, xxHash.Sum(epkBytes.Bytes[ConstMapEPKMetadataOffset:]), signature) { + return &Metadata{}, nil, ErrFullyMapMetadataInvalidSignatureError + } + } + + // Great, the EPK is valid. Let's map the metadata. + // We use the metadata map provided by PreMapEPK to reduce the amount of work needed to map the EPK + + // First, map SpecialFiles + var parsedSpecialFiles SpecialFiles + specialFilesMap, ok := preMap.MetadataMap["specialFiles"].(map[string]interface{}) + if !ok { + return &Metadata{}, errors.New("specialFiles is not an object"), ErrFullyMapMetadataCouldNotMapJSONError + } + noDelete, ok := specialFilesMap["noDelete"].([]interface{}) + if !ok { + return &Metadata{}, errors.New("noDelete is not an array"), ErrFullyMapMetadataCouldNotMapJSONError + } + parsedSpecialFiles.NoDelete, err = interfaceToStringSlice(noDelete, "noDelete") + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataCouldNotMapJSONError + } + noReplace, ok := specialFilesMap["noReplace"].([]interface{}) + if !ok { + return &Metadata{}, errors.New("noReplace is not an array"), ErrFullyMapMetadataCouldNotMapJSONError + } + parsedSpecialFiles.NoReplace, err = interfaceToStringSlice(noReplace, "noReplace") + if err != nil { + return &Metadata{}, err, ErrFullyMapMetadataCouldNotMapJSONError + } + + // Declare the parsedMetadata object + var parsedMetadata Metadata + + // Append parsedSpecialFiles to parsedMetadata + parsedMetadata.SpecialFiles = parsedSpecialFiles + + // Steal some data from the PreMapEPK object + parsedMetadata.Name = preMap.Name + parsedMetadata.Version = preMap.Version + parsedMetadata.Architecture = preMap.Architecture + parsedMetadata.Size = preMap.Size + parsedMetadata.Dependencies = preMap.Dependencies + + // Map the metadata + parsedMetadata.Description, ok = preMap.MetadataMap["desc"].(string) + if !ok { + return &Metadata{}, errors.New("description is not a string"), ErrFullyMapMetadataCouldNotMapJSONError + } + parsedMetadata.LongDescription, ok = preMap.MetadataMap["longDesc"].(string) + if !ok { + return &Metadata{}, errors.New("longDesc is not a string"), ErrFullyMapMetadataCouldNotMapJSONError + } + parsedMetadata.Author, ok = preMap.MetadataMap["author"].(string) + if !ok { + return &Metadata{}, errors.New("author is not a string"), ErrFullyMapMetadataCouldNotMapJSONError + } + parsedMetadata.License, ok = preMap.MetadataMap["license"].(string) + if !ok { + return &Metadata{}, errors.New("license is not a string"), ErrFullyMapMetadataCouldNotMapJSONError + } + decompressedSizeString, ok := preMap.MetadataMap["size"].(string) + if !ok { + return &Metadata{}, errors.New("size is not a string"), ErrFullyMapMetadataCouldNotMapJSONError + } + parsedMetadata.DecompressedSize.SetString(decompressedSizeString, 10) + + return &parsedMetadata, nil, nil +} + +// ResolveDependencies resolves the dependencies of an EPK +// func ResolveDependencies(epk Epk) (error, error) { +// TODO: Implement this when I finish up repositories +// return nil, nil +// } + +var ErrInstallEPKCouldNotCreateTempDirError = errors.New("could not create temporary directory") +var ErrInstallEPKCouldNotCreateZStandardReaderError = errors.New("could not create ZStandard reader") +var ErrInstallEPKCouldNotDecompressTarArchiveError = errors.New("could not decompress tar archive") +var ErrInstallEPKCouldNotCreateDirError = errors.New("could not create directory") +var ErrInstallEPKCouldNotStatDirError = errors.New("could not stat directory") +var ErrInstallEPKCouldNotStatFileError = errors.New("could not stat file") +var ErrInstallEPKCouldNotCreateFileError = errors.New("could not create file") +var ErrInstallEPKCouldNotCloseTarReaderError = errors.New("could not close tar reader") +var ErrInstallEPKCouldNotStatHookError = errors.New("could not stat hook") +var ErrInstallEPKCouldNotRunHookError = errors.New("could not run hook") +var ErrInstallEPKCouldNotAddEPKToDBError = errors.New("could not add EPK to database") +var ErrInstallEPKCouldNotRemoveTempDirError = errors.New("could not remove temporary directory") + +// InstallEPK installs an EPK file +func InstallEPK(epkBytes StreamOrBytes, metadata *Metadata, preMap *EPKPreMap, addEPKToDB func(metadata *Metadata, removeScript []byte, dependency bool, hasRemoveScript bool, size int64) error, logger *Logger) (string, error, error) { + // Create the temporary directory + tempDir, err := os.MkdirTemp("/tmp", "eon-install-") + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotCreateTempDirError + } + + var zStandardReader *zstd.Decoder + if epkBytes.IsStream { + // Seek to the correct position in the EPK + _, err = epkBytes.Stream.Seek(preMap.TarOffset, io.SeekStart) + if err != nil { + return "", err, nil + } + + // Create a ZStandard reader reading from the EPK + zStandardReader, err = zstd.NewReader(epkBytes.Stream) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotCreateZStandardReaderError + } + } else { + // Create a ZStandard reader reading from the EPKs in-memory bytes + zStandardReader, err = zstd.NewReader(bytes.NewReader(epkBytes.Bytes[preMap.TarOffset:])) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotCreateZStandardReaderError + } + } + + // Create a tar reader reading from the ZStandard reader + tarReader := tar.NewReader(zStandardReader) + + // Create a goroutine to see how much of the decompressed size we have decompressed + var written big.Int + stop := make(chan bool) + go func() { + for { + select { + case <-stop: + return + default: + if logger.ProgressSupported { + logger.LogFunc(Log{ + Level: "PROGRESS", + Progress: &written, + Total: &metadata.DecompressedSize, + Overwrite: true, + }) + } else { + logger.LogFunc(Log{ + Level: "INFO", + Content: "Decompressed " + humanize.Bytes(uint64(written.Int64())) + " of " + humanize.Bytes(uint64(metadata.DecompressedSize.Int64())), + Prompt: false, + }) + time.Sleep(1 * time.Second) + } + } + } + }() + + // Iterate through the tar archive + for { + // Read the next header + header, err := tarReader.Next() + if err != nil { + break + } + + switch { + // If we are done, break + case err == io.EOF: + break + + // If there was an error, return the error + case err != nil: + return tempDir, err, ErrInstallEPKCouldNotDecompressTarArchiveError + + // This should never happen, but if it does, we should just continue + case header == nil: + continue + } + + // Get the target path + var target string + if strings.HasPrefix(header.Name, "root") { + target = strings.TrimPrefix(header.Name, "root") + } else if strings.HasPrefix(header.Name, "hooks") { + target = filepath.Join(tempDir, header.Name) + } else { + return tempDir, errors.New("invalid path in EPK: " + header.Name), ErrInstallEPKCouldNotDecompressTarArchiveError + } + + switch header.Typeflag { + case tar.TypeDir: + // Check if the directory exists + _, err := os.Stat(target) + if err != nil { + // If the directory does not exist, create it + if os.IsNotExist(err) { + // Make sure to replicate the permissions of the directory + err := os.MkdirAll(target, header.FileInfo().Mode()) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotCreateDirError + } + } else { + return tempDir, err, ErrInstallEPKCouldNotStatDirError + } + } else { + // If it does exist, don't touch it + continue + } + case tar.TypeReg: + // Check if the file has anywhere to go + _, err := os.Stat(filepath.Dir(target)) + if err != nil { + // No, it doesn't. Create the directory + if os.IsNotExist(err) { + // We assume 0755 for any directories that don't exist + err := os.MkdirAll(filepath.Dir(target), 0755) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotCreateDirError + } + } else { + return tempDir, err, ErrInstallEPKCouldNotStatDirError + } + } + + // Check if the file already exists + _, err = os.Stat(target) + if err != nil { + if os.IsNotExist(err) { + // Great, the file does not exist. Let's create it. + file, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.FileMode(header.Mode)) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotCreateFileError + } + + writtenFile, err := io.Copy(file, tarReader) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotDecompressTarArchiveError + } + + written.Add(&written, big.NewInt(writtenFile)) + + err = file.Close() + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotCloseTarReaderError + } + } else { + return tempDir, err, ErrInstallEPKCouldNotStatFileError + } + } else { + // See if it's an upgrade or not + if preMap.IsUpgrade { + // Check if it's a special file + for _, file := range metadata.SpecialFiles.NoReplace { + if strings.TrimSuffix(target, "/") == strings.TrimSuffix(file, "/") { + // This file is a special file and should not be replaced + continue + } + } + } + } + } + } + + zStandardReader.Close() + + // Now let's run the hooks + if preMap.IsUpgrade { + _, err := os.Stat(filepath.Join(tempDir, "hooks", "upgrade.sh")) + if err != nil { + if !os.IsNotExist(err) { + return tempDir, err, ErrInstallEPKCouldNotStatHookError + } + } else { + cmd := exec.Command("/bin/sh", filepath.Join(tempDir, "hooks", "upgrade.sh"), metadata.Version.String()) + stderr, err := cmd.StderrPipe() + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotRunHookError + } + err = cmd.Start() + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotRunHookError + } + scanner := bufio.NewScanner(stderr) + scanner.Split(bufio.ScanWords) + for scanner.Scan() { + message := scanner.Text() + fmt.Println(message) + } + err = cmd.Wait() + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotRunHookError + } + } + } else { + _, err := os.Stat(filepath.Join(tempDir, "hooks", "install.sh")) + if err != nil { + if !os.IsNotExist(err) { + return tempDir, err, ErrInstallEPKCouldNotStatHookError + } + } else { + cmd := exec.Command("/bin/sh", filepath.Join(tempDir, "hooks", "install.sh"), metadata.Version.String()) + stderr, err := cmd.StderrPipe() + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotRunHookError + } + err = cmd.Start() + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotRunHookError + } + scanner := bufio.NewScanner(stderr) + scanner.Split(bufio.ScanWords) + for scanner.Scan() { + message := scanner.Text() + fmt.Println(message) + } + err = cmd.Wait() + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotRunHookError + } + } + } + + // Finally, add the EPK and remove script to the database + file, err := os.ReadFile(filepath.Join(tempDir, "hooks", "remove.sh")) + if err != nil { + if !os.IsNotExist(err) { + err := addEPKToDB(metadata, []byte{}, false, false, metadata.Size) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotAddEPKToDBError + } + } else { + return tempDir, err, ErrInstallEPKCouldNotAddEPKToDBError + } + } else { + err := addEPKToDB(metadata, file, false, true, metadata.Size) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotAddEPKToDBError + } + } + + // Remove the temporary directory + err = os.RemoveAll(tempDir) + if err != nil { + return tempDir, err, ErrInstallEPKCouldNotRemoveTempDirError + } + + stop <- true + logger.LogFunc(Log{ + Level: "PROGRESS", + Progress: big.NewInt(1), + Total: big.NewInt(1), + Overwrite: true, + }) + + return "", nil, nil +} + +var ErrAddRepositoryCannotCreateRequestError = errors.New("cannot create request") +var ErrAddRepositoryCannotSendRequestError = errors.New("cannot send request") +var ErrAddRepositoryUnexpectedStatusCodeError = errors.New("unexpected status code") +var ErrAddRepositoryCannotReadResponseError = errors.New("cannot read response") +var ErrAddRepositoryInvalidMagicError = errors.New("invalid magic") +var ErrAddRepositoryCannotHashError = errors.New("cannot write to hash") +var ErrAddRepositoryUnmarshalMetadataError = errors.New("cannot unmarshal metadata") +var ErrAddRepositoryFailedToGetFingerprintError = errors.New("failed to get fingerprint") +var ErrAddRepositoryFailedToAddFingerprintError = errors.New("failed to add fingerprint") +var ErrAddRepositoryInvalidMetadataError = errors.New("invalid metadata") +var ErrAddRepositoryCannotCreateDirError = errors.New("cannot create directory") +var ErrAddRepositoryCannotStatDirError = errors.New("cannot stat directory") +var ErrAddRepositoryFailedToAddPackageError = errors.New("failed to add package to database") +var ErrAddRepositoryRepositoryAlreadyExistsError = errors.New("repository already exists") +var ErrAddRepositoryFailedToAddRepositoryError = errors.New("failed to add repository to database") + +func AddRepository(url string, addRepositoryToDB func(repository Repository) error, getFingerprintFromDB func([]byte, string) (bool, bool, bool, error), addFingerprintToDB func([]byte, string, bool) error, addRemotePackageToDB func(string, RemoteEPK) error, logger *Logger) (error, error) { + // First, fetch range 0-3 of /repository.erf + // Then, check if the first 3 bytes are "eon" + + // Create the request + magicRequest, err := http.NewRequest("GET", url+"/repository.erf", nil) + if err != nil { + return err, ErrAddRepositoryCannotCreateRequestError + } + + // Add the range header + magicRequest.Header.Add("Range", "bytes=0-3") + + // Send the request + magicResponse, err := http.DefaultClient.Do(magicRequest) + if err != nil { + return err, ErrAddRepositoryCannotSendRequestError + } + + // Check if the status code is 206 + var hasEntireFile bool + if magicResponse.StatusCode != 206 { + if magicResponse.StatusCode == 200 { + // This web server does not support range requests, meaning we now have the entire file. + // Mark it as such. + hasEntireFile = true + } else { + return errors.New("status code " + strconv.Itoa(magicResponse.StatusCode)), ErrAddRepositoryUnexpectedStatusCodeError + } + } + + // Check the magic bytes + var magicBytes = make([]byte, 3) + _, err = magicResponse.Body.Read(magicBytes) + if err != nil { + return err, ErrAddRepositoryCannotReadResponseError + } + + // Check if the magic bytes are "eon" + if string(magicBytes) != "eon" { + return nil, ErrAddRepositoryInvalidMagicError + } + + // Great. We either confirmed the repository is an Eon repository or we have the entire file. Both are good. + var fullFetch *http.Response + if !hasEntireFile { + // Download the rest of the file + var err error + fullFetch, err = http.Get(url + "/repository.erf") + if err != nil { + return err, ErrAddRepositoryCannotSendRequestError + } + } else { + fullFetch = magicResponse + } + + // Now we get the contents of the file + contents, err := io.ReadAll(fullFetch.Body) + if err != nil { + return err, ErrAddRepositoryCannotReadResponseError + } + + // Verify the file's signature + + // Unmarshal the repository metadata, which is NOT the same as the EPK metadata + var repositoryMetadata map[string]interface{} + // We use a decoder instead of unmarshal here because we need to use JSON numbers: float64 is not enough + var jsonDecoder = json.NewDecoder(bytes.NewReader(contents[99:])) + jsonDecoder.UseNumber() + err = jsonDecoder.Decode(&repositoryMetadata) + if err != nil { + return err, ErrAddRepositoryUnmarshalMetadataError + } + + // Get the public key and signature + signature := contents[3:67] + publicKey := contents[67:99] + + // Look for the public key in the database + exists, matchingAuthor, matchingFingerprint, err := getFingerprintFromDB(publicKey, repositoryMetadata["author"].(string)) + if err != nil { + return err, ErrAddRepositoryFailedToGetFingerprintError + } else { + err := handlePublicKeyCheck(exists, matchingAuthor, matchingFingerprint, publicKey, repositoryMetadata["author"].(string), addFingerprintToDB, logger) + if err != nil { + return err, ErrAddRepositoryFailedToAddFingerprintError + } + } + + // We need to create a new xxHash instance + xxHash := xxhash.New() + _, err = xxHash.Write(contents[99:]) + if err != nil { + return err, ErrAddRepositoryCannotHashError + } + + // Verify the signature + if !ed25519.Verify(publicKey, xxHash.Sum(nil), signature) { + return errors.New("invalid signature"), ErrAddRepositoryInvalidMetadataError + } + + // Now we can create the repository object + var repository Repository + var ok bool + repository.URL = url + repository.Name, ok = repositoryMetadata["name"].(string) + if !ok { + return errors.New("name is not a string"), ErrAddRepositoryInvalidMetadataError + } + repository.Description, ok = repositoryMetadata["desc"].(string) + if !ok { + return errors.New("desc is not a string"), ErrAddRepositoryInvalidMetadataError + } + repository.Owner, ok = repositoryMetadata["author"].(string) + if !ok { + return errors.New("author is not a string"), ErrAddRepositoryInvalidMetadataError + } + + // First check if the directory exists + _, err = os.Stat("/var/lib/eon/repositories") + if err != nil { + if os.IsNotExist(err) { + // If the directory does not exist, create it + err = os.MkdirAll("/var/lib/eon/repositories", 0755) + if err != nil { + return err, ErrAddRepositoryCannotCreateDirError + } + } else { + return err, ErrAddRepositoryCannotStatDirError + } + } + + // Write the contents of the repository to the database + packageList, ok := repositoryMetadata["packages"].([]interface{}) + if !ok { + return errors.New("packages is not an array"), ErrAddRepositoryInvalidMetadataError + } + + var remoteEPKs []RemoteEPK + for _, epk := range packageList { + epk, ok := epk.(map[string]interface{}) + if !ok { + return errors.New("package is not an object"), ErrAddRepositoryInvalidMetadataError + } + + name, ok := epk["name"].(string) + if !ok { + return errors.New("package name is not a string"), ErrAddRepositoryInvalidMetadataError + } + + author, ok := epk["author"].(string) + if !ok { + return errors.New("package author is not a string"), ErrAddRepositoryInvalidMetadataError + } + + arch, ok := epk["arch"].(string) + if !ok { + return errors.New("package arch is not a string"), ErrAddRepositoryInvalidMetadataError + } + + versionString, ok := epk["version"].(string) + if !ok { + return errors.New("package version is not a string"), ErrAddRepositoryInvalidMetadataError + } + + versionPointer, err := semver.NewVersion(versionString) + if err != nil { + return errors.New("package version is not a valid semver version"), ErrAddRepositoryInvalidMetadataError + } + + sizeString, ok := epk["size"].(string) + if !ok { + return errors.New("package size is not a string"), ErrAddRepositoryInvalidMetadataError + } + + size, err := strconv.ParseInt(sizeString, 10, 64) + if err != nil { + return errors.New("package size is not a number"), ErrAddRepositoryInvalidMetadataError + } + + dependenciesInterface, ok := epk["deps"].([]interface{}) + if !ok { + return errors.New("package dependencies is not an array"), ErrAddRepositoryInvalidMetadataError + } + + dependencies, err := interfaceToStringSlice(dependenciesInterface, "dependencies") + if err != nil { + return err, ErrAddRepositoryInvalidMetadataError + } + + hashJsonNumber, ok := epk["hash"].(json.Number) + if !ok { + return errors.New("package hash is not a number"), ErrAddRepositoryInvalidMetadataError + } + + var hash uint64 + hash, err = strconv.ParseUint(hashJsonNumber.String(), 10, 64) + if err != nil { + return errors.New("package hash is not a valid number"), ErrAddRepositoryInvalidMetadataError + } + + fmt.Println(hash) + + path, ok := epk["path"].(string) + if !ok { + return errors.New("package path is not a string"), ErrAddRepositoryInvalidMetadataError + } + + description, ok := epk["desc"].(string) + if !ok { + return errors.New("package description is not a string"), ErrAddRepositoryInvalidMetadataError + } + + remoteEPKs = append(remoteEPKs, RemoteEPK{ + Name: name, + Author: author, + Description: description, + Version: *versionPointer, + Architecture: arch, + CompressedSize: size, + Dependencies: dependencies, + Path: path, + Arch: arch, + EPKHash: hash, + }) + if err != nil { + return err, ErrAddRepositoryFailedToAddPackageError + } + } + + // We add packages afterward so that if there is an error, we don't have to remove the packages + for _, epk := range remoteEPKs { + err := addRemotePackageToDB(repository.Name, epk) + if err != nil { + return err, ErrAddRepositoryFailedToAddPackageError + } + } + + // Add the repository to the database + err = addRepositoryToDB(repository) + if err != nil { + if err.(*sqlite.Error).Code() == 2067 { + return nil, ErrAddRepositoryRepositoryAlreadyExistsError + } else { + return err, ErrAddRepositoryFailedToAddRepositoryError + } + } + + // Alright, we're done here. + logger.LogFunc(Log{ + Level: "INFO", + Content: "Added repository " + repository.Name + " to the database.", + }) + + return nil, nil +} + +var ErrRemoveRepositoryDoesNotExistError = errors.New("repository does not exist") +var ErrRemoveRepositoryCannotStatRepositoryError = errors.New("cannot stat repository") +var ErrRemoveRepositoryCannotRemoveRepositoryError = errors.New("cannot remove repository") +var ErrRemoveRepositoryFailedToRemoveRepositoryFromDBError = errors.New("failed to remove repository from database") + +func RemoveRepository(repository string, removeRepositoryFromDB func(repository string) error, logger *Logger) (error, error) { + // First check if the file exists + _, err := os.Stat(filepath.Join("/var/lib/eon/repositories/", repository+".json")) + if err != nil { + if os.IsNotExist(err) { + return nil, ErrRemoveRepositoryDoesNotExistError + } else { + return err, ErrRemoveRepositoryCannotStatRepositoryError + } + } + + // Remove the file + err = os.Remove(filepath.Join("/var/lib/eon/repositories/", repository+".json")) + if err != nil { + return err, ErrRemoveRepositoryCannotRemoveRepositoryError + } + + // Purge the download cache + err = os.RemoveAll(filepath.Join("/var/cache/eon/repositories/", repository)) + if err != nil { + return err, ErrRemoveRepositoryCannotRemoveRepositoryError + } + + // Remove the repository from the database + err = removeRepositoryFromDB(repository) + if err != nil { + return err, ErrRemoveRepositoryFailedToRemoveRepositoryFromDBError + } + + // Alright, we're done here. + logger.LogFunc(Log{ + Level: "INFO", + Content: "Removed repository " + repository + " from the database.", + }) + + return nil, nil +}