From 425decdf7e9284d15aa726e3ae96b9942fb0e3ea Mon Sep 17 00:00:00 2001 From: IronClawTrem Date: Sun, 16 Feb 2020 03:40:06 +0000 Subject: create tremded branch --- src/granger/COPYING | 622 +++++++++++++++++++++++++++ src/granger/Dockerfile | 4 + src/granger/README.md | 139 ++++++ src/granger/appveyor.yml | 32 ++ src/granger/misc/docker-build.sh | 7 + src/granger/src/CMakeLists.txt | 60 +++ src/granger/src/getopt.h | 653 +++++++++++++++++++++++++++++ src/granger/src/lnettlelib.c | 181 ++++++++ src/granger/src/lnettlelib.h | 25 ++ src/granger/src/lua/CMakeLists.txt | 57 +++ src/granger/src/main.c | 97 +++++ src/granger/src/nettle/CMakeLists.txt | 23 + src/granger/src/nettle/macros.h | 245 +++++++++++ src/granger/src/nettle/md5-compress.c | 174 ++++++++ src/granger/src/nettle/md5.c | 93 ++++ src/granger/src/nettle/md5.h | 86 ++++ src/granger/src/nettle/nettle-stdint.h | 6 + src/granger/src/nettle/nettle-types.h | 110 +++++ src/granger/src/nettle/nettle-write.h | 58 +++ src/granger/src/nettle/sha2.h | 206 +++++++++ src/granger/src/nettle/sha256-compress.c | 199 +++++++++ src/granger/src/nettle/sha256.c | 162 +++++++ src/granger/src/nettle/version.h | 58 +++ src/granger/src/nettle/write-be32.c | 77 ++++ src/granger/src/nettle/write-le32.c | 69 +++ src/granger/src/premake/CMakeLists.txt | 32 ++ src/granger/src/premake/os_access.c | 58 +++ src/granger/src/premake/os_chdir.c | 32 ++ src/granger/src/premake/os_copyfile.c | 34 ++ src/granger/src/premake/os_elevate.c | 240 +++++++++++ src/granger/src/premake/os_getcwd.c | 36 ++ src/granger/src/premake/os_is64bit.c | 30 ++ src/granger/src/premake/os_isdir.c | 34 ++ src/granger/src/premake/os_isfile.c | 30 ++ src/granger/src/premake/os_match.c | 181 ++++++++ src/granger/src/premake/os_mkdir.c | 33 ++ src/granger/src/premake/os_pathsearch.c | 84 ++++ src/granger/src/premake/os_rmdir.c | 33 ++ src/granger/src/premake/os_stat.c | 46 ++ src/granger/src/premake/path_getabsolute.c | 102 +++++ src/granger/src/premake/path_getrelative.c | 80 ++++ src/granger/src/premake/path_isabsolute.c | 27 ++ src/granger/src/premake/path_join.c | 58 +++ src/granger/src/premake/path_normalize.c | 77 ++++ src/granger/src/premake/path_translate.c | 61 +++ src/granger/src/premake/premake.c | 171 ++++++++ src/granger/src/premake/premake.h | 90 ++++ src/granger/src/premake/string_endswith.c | 28 ++ src/granger/src/strvec.c | 156 +++++++ src/granger/src/strvec.h | 36 ++ src/granger/test/main.lua | 11 + src/granger/test/test-nettle.lua | 33 ++ src/granger/test/test-os-access.lua | 17 + 53 files changed, 5293 insertions(+) create mode 100644 src/granger/COPYING create mode 100644 src/granger/Dockerfile create mode 100644 src/granger/README.md create mode 100644 src/granger/appveyor.yml create mode 100644 src/granger/misc/docker-build.sh create mode 100644 src/granger/src/CMakeLists.txt create mode 100644 src/granger/src/getopt.h create mode 100644 src/granger/src/lnettlelib.c create mode 100644 src/granger/src/lnettlelib.h create mode 100644 src/granger/src/lua/CMakeLists.txt create mode 100644 src/granger/src/main.c create mode 100644 src/granger/src/nettle/CMakeLists.txt create mode 100644 src/granger/src/nettle/macros.h create mode 100644 src/granger/src/nettle/md5-compress.c create mode 100644 src/granger/src/nettle/md5.c create mode 100644 src/granger/src/nettle/md5.h create mode 100644 src/granger/src/nettle/nettle-stdint.h create mode 100644 src/granger/src/nettle/nettle-types.h create mode 100644 src/granger/src/nettle/nettle-write.h create mode 100644 src/granger/src/nettle/sha2.h create mode 100644 src/granger/src/nettle/sha256-compress.c create mode 100644 src/granger/src/nettle/sha256.c create mode 100644 src/granger/src/nettle/version.h create mode 100644 src/granger/src/nettle/write-be32.c create mode 100644 src/granger/src/nettle/write-le32.c create mode 100644 src/granger/src/premake/CMakeLists.txt create mode 100644 src/granger/src/premake/os_access.c create mode 100644 src/granger/src/premake/os_chdir.c create mode 100644 src/granger/src/premake/os_copyfile.c create mode 100644 src/granger/src/premake/os_elevate.c create mode 100644 src/granger/src/premake/os_getcwd.c create mode 100644 src/granger/src/premake/os_is64bit.c create mode 100644 src/granger/src/premake/os_isdir.c create mode 100644 src/granger/src/premake/os_isfile.c create mode 100644 src/granger/src/premake/os_match.c create mode 100644 src/granger/src/premake/os_mkdir.c create mode 100644 src/granger/src/premake/os_pathsearch.c create mode 100644 src/granger/src/premake/os_rmdir.c create mode 100644 src/granger/src/premake/os_stat.c create mode 100644 src/granger/src/premake/path_getabsolute.c create mode 100644 src/granger/src/premake/path_getrelative.c create mode 100644 src/granger/src/premake/path_isabsolute.c create mode 100644 src/granger/src/premake/path_join.c create mode 100644 src/granger/src/premake/path_normalize.c create mode 100644 src/granger/src/premake/path_translate.c create mode 100644 src/granger/src/premake/premake.c create mode 100644 src/granger/src/premake/premake.h create mode 100644 src/granger/src/premake/string_endswith.c create mode 100644 src/granger/src/strvec.c create mode 100644 src/granger/src/strvec.h create mode 100644 src/granger/test/main.lua create mode 100644 src/granger/test/test-nettle.lua create mode 100644 src/granger/test/test-os-access.lua (limited to 'src/granger') diff --git a/src/granger/COPYING b/src/granger/COPYING new file mode 100644 index 0000000..f755e7e --- /dev/null +++ b/src/granger/COPYING @@ -0,0 +1,622 @@ +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 + diff --git a/src/granger/Dockerfile b/src/granger/Dockerfile new file mode 100644 index 0000000..11698c8 --- /dev/null +++ b/src/granger/Dockerfile @@ -0,0 +1,4 @@ +FROM ubuntu:yakkety +WORKDIR /usr/src +COPY . /usr/src/ +RUN apt update && apt install -y cmake libgl1-mesa-dev libsdl2-dev libfreetype6-dev mingw-w64 g++-mingw-w64 g++-multilib git zip vim-nox diff --git a/src/granger/README.md b/src/granger/README.md new file mode 100644 index 0000000..ef77989 --- /dev/null +++ b/src/granger/README.md @@ -0,0 +1,139 @@ +# Granger +[![AppVeyor](https://img.shields.io/appveyor/ci/jkent/granger.svg?style=flat-square)](https://ci.appveyor.com/project/jkent/granger) +[![Travis-CI](https://travis-ci.org/GrangerHub/granger.svg?branch=master "Travis-CI")](https://travis-ci.org/GrangerHub/granger) + +### Lua API documentation +`os.access(p, mode)`
+Checks that the file is executable/writable/readable. `mode` is a string of the characters "rwx". + +`os.chdir(p)`
+Change the current working directory. + +`os.copyfile(src, dst)`
+Copy a file from one location to another. + +`os.elevate()`
+Attempts to re-run process under elevated privlidges, returning true if elevated or false if unsuccessful. + +`os.get()`
+Retrieve the current operating system ID string. + +`os.getcwd()`
+Retrieve the current working directory. + +`os.is(id)`
+Check the current operating system. + +`os.is64bit()`
+Determine if the current system is running a 64-bit architecture. + +`os.isdir(p)`
+Returns true if the specified directory exists. + +`os.isfile(p)`
+Returns true if the given file exists. + +`os.matchdirs(p)`
+Performs a wildcard match to locate one or more directories. + +`os.matchfiles(p)`
+Performs a wildcard match to locate one or more files. + +`os.mkdir(p)`
+An overload of os.mkdir() function, which will create any missing subdirectories along the path. + +`os.outputof(cmd)`
+Run a shell command and return the output. + +`os.pathsearch(p, path1, ...)`
+Locates a file, given a set of search paths. + +`os.rmdir(p)`
+Remove a directory, along with any contained files or subdirectories. + +`os.stat(p)`
+Retrieve information about a file. + +`path.getbasename(p)`
+Retrieve the filename portion of a path, without any extension. + +`path.getabsolute(p)`
+Returns an absolute version of a relative path. + +`path.getdirectory(p)`
+Retrieve the directory portion of a path, or an empty string if the path does not include a directory. + +`path.getdrive(p)`
+Retrieve the drive letter, if a Windows path. + +`path.getextension(p)`
+Retrieve the file extension. + +`path.getname(p)`
+Retreive the filename portion of a path. + +`path.getrelative(p1, p2)`
+Returns a path relative to another. + +`path.isabsolute(p)`
+Determines if a path is absolute or relative. + +`path.join(...)`
+Builds a path from two or more path parts. + +`path.normalize(p)`
+Removes any wwirdness from a file system path string. + +`path.rebase(p, oldbase, newbase)`
+Takes a path which is relative to one location and makes it relative to another location instead. + +`path.translate(p, sep)`
+Convert the separators in a path from one form to another. If `sep` is nil, then a platform-specific separator is used. + +`path.wildcards(pattern)`
+Converts from a simple wildcard syntax, where * is "match any" and ** is "match recursive", to the corresponding Lua pattern. + +`string.explode(s, pattern, plain)`
+Returns an array of strings, each which is a substring of `s` formed by splitting on boundaries formed by `pattern`. + +`string.endswith(haystack, needle)`
+Returns true if `haystack` ends with `needle`. + +`string.findlast(s, pattern, plain)`
+Find the last instance of a pattern in a string. + +`string.startswith(haystack, needle)`
+Returns true if `haystack` starts with `needle`. + +`table.contains(t, value)`
+Returns true if the table contains the specified value. + +`table.extract(arr, fname)`
+Enumerates an array of objects and returns a new table containing only the value of one particular field. + +`table.flatten(arr)`
+Flattens a hierarchy of tables into a single array containing all of the values. + +`table.implode(arr, before, after, between)`
+Merges an array of items into a string. + +`table.insertflat(tbl, values)`
+Inserts a value of array of values into a table. If the value is itself a table, its contents are enumerated and added instead. So these inputs give these outputs:
+"x" -> { "x" }
+{ "x", "y" } -> { "x", "y" }
+{ "x", { "y" }} -> { "x", "y" }
+ +`table.isempty(t)`
+Returns true of the table is empty, and contains no indexed or keyed values. + +`table.join(...)`
+Adds the values from one array to the end of another and returns the result. + +`table.keys(tbl)`
+Return a list of all the keys used in a table. + +`table.merge(...)`
+Adds the key-value associations from one table into another and returns the resulting merged table. + +`table.translate(arr, translation)`
+Translates the values contained in array, using specified translation table and returns the results in a new array. diff --git a/src/granger/appveyor.yml b/src/granger/appveyor.yml new file mode 100644 index 0000000..c283de6 --- /dev/null +++ b/src/granger/appveyor.yml @@ -0,0 +1,32 @@ +platform: + - x86 + - x64 + +configuration: + - Debug + - Release + +os: Visual Studio 2015 + +clone_folder: c:\projects\granger + +build_script: + # show settings + - cmake -version + - echo %platform% + - echo %configuration% + + # generate a solution file + - cd c:\projects\granger + - mkdir build + - cd build + - if "%platform%" == "x64" set cmake_platform=%platform% + - cmake -g "Visual Studio 14 2015" .. -DCMAKE_GENERATOR_PLATFORM=%cmake_platform% + + # build it + - if "%platform%" == "x86" set msbuild_platform=Win32 + - if "%platform%" == "x64" set msbuild_platform=%platform% + - msbuild granger.sln /p:Configuration=%configuration% /toolsversion:14.0 /p:PlatformToolset=v140 /p:Platform=%msbuild_platform% + +test_script: + - if "%configuration%" == "Debug" ctest -VV --schedule-random -C Debug diff --git a/src/granger/misc/docker-build.sh b/src/granger/misc/docker-build.sh new file mode 100644 index 0000000..fe3232a --- /dev/null +++ b/src/granger/misc/docker-build.sh @@ -0,0 +1,7 @@ +#!/bin/bash +[[ -d build ]] \ + || mkdir build + +cd build +cmake .. +make diff --git a/src/granger/src/CMakeLists.txt b/src/granger/src/CMakeLists.txt new file mode 100644 index 0000000..f59ae9c --- /dev/null +++ b/src/granger/src/CMakeLists.txt @@ -0,0 +1,60 @@ +add_subdirectory(lua) +add_subdirectory(nettle) +add_subdirectory(premake) + +add_executable(granger + getopt.h + lnettlelib.c + lnettlelib.h + main.c + strvec.c + strvec.h + ) + +if(APPLE) + add_definitions(-DLUA_USE_MACOSX) +endif(APPLE) + +if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux") + add_definitions(-DLUA_USE_LINUX) +endif() + +add_definitions ( + #-DLUA_COMPAT_5_2 + -DNDEBUG + -mfpmath=sse + -ffast-math + -DGRANGER + ) + +include_directories ( + include + ) +target_link_libraries(granger granger_lua granger_nettle premake) + +if (NOT WIN32) + target_link_libraries(granger m dl) +endif() + +if(WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +endif(WIN32) + +if (APPLE) + macro(ADD_FRAMEWORK fwname appname) + find_library(FRAMEWORK_${fwname} + NAMES ${fwname} + PATHS ${CMAKE_OSX_SYSROOT}/System/Library + PATH_SUFFIXES Frameworks + NO_DEFAULT_PATH) + if( ${FRAMEWORK_${fwname}} STREQUAL FRAMEWORK_${fwname}-NOTFOUND) + MESSAGE(ERROR ": Framework ${fwname} not found") + else() + TARGET_LINK_LIBRARIES(${appname} "${FRAMEWORK_${fwname}}/${fwname}") + MESSAGE(STATUS "Framework ${fwname} found at ${FRAMEWORK_${fwname}}") + endif() + endmacro(ADD_FRAMEWORK) + + add_framework(CoreServices granger) + add_framework(Security granger) +endif() diff --git a/src/granger/src/getopt.h b/src/granger/src/getopt.h new file mode 100644 index 0000000..c15cbd9 --- /dev/null +++ b/src/granger/src/getopt.h @@ -0,0 +1,653 @@ +#ifndef __GETOPT_H__ +/** + * DISCLAIMER + * This file is part of the mingw-w64 runtime package. + * + * The mingw-w64 runtime package and its code is distributed in the hope that it + * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR + * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to + * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ + /* + * Copyright (c) 2002 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ +/*- + * Copyright (c) 2000 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Dieter Baron and Thomas Klausner. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma warning(disable:4996); + +#define __GETOPT_H__ + +/* All the headers include this file. */ +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ + +#ifdef REPLACE_GETOPT +int opterr = 1; /* if error message should be printed */ +int optind = 1; /* index into parent argv vector */ +int optopt = '?'; /* character checked for validity */ +#undef optreset /* see getopt.h */ +#define optreset __mingw_optreset +int optreset; /* reset getopt */ +char *optarg; /* argument associated with option */ +#endif + +//extern int optind; /* index of first non-option in argv */ +//extern int optopt; /* single option character, as parsed */ +//extern int opterr; /* flag to enable built-in diagnostics... */ +// /* (user may set to zero, to suppress) */ +// +//extern char *optarg; /* pointer to argument of current option */ + +#define PRINT_ERROR ((opterr) && (*options != ':')) + +#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ +#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ +#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ + +/* return values */ +#define BADCH (int)'?' +#define BADARG ((*options == ':') ? (int)':' : (int)'?') +#define INORDER (int)1 + +#ifndef __CYGWIN__ +#define __progname __argv[0] +#else +extern char __declspec(dllimport) *__progname; +#endif + +#ifdef __CYGWIN__ +static char EMSG[] = ""; +#else +#define EMSG "" +#endif + +struct option /* specification for a long form option... */ +{ + const char *name; /* option name, without leading hyphens */ + int has_arg; /* does it take an argument? */ + int *flag; /* where to save its status, or NULL */ + int val; /* its associated status value */ +}; + +static int getopt_internal(int, char * const *, const char *, + const struct option *, int *, int); +static int parse_long_options(char * const *, const char *, + const struct option *, int *, int); +static int gcd(int, int); +static void permute_args(int, int, int, char * const *); + +static char *place = EMSG; /* option letter processing */ + +/* XXX: set optreset to 1 rather than these two */ +static int nonopt_start = -1; /* first non option argument (for permute) */ +static int nonopt_end = -1; /* first option after non options (for permute) */ + +/* Error messages */ +static const char recargchar[] = "option requires an argument -- %c"; +static const char recargstring[] = "option requires an argument -- %s"; +static const char ambig[] = "ambiguous option -- %.*s"; +static const char noarg[] = "option doesn't take an argument -- %.*s"; +static const char illoptchar[] = "unknown option -- %c"; +static const char illoptstring[] = "unknown option -- %s"; + +static void +_vwarnx(const char *fmt,va_list ap) +{ + (void)fprintf(stderr,"%s: ",__progname); + if (fmt != NULL) + (void)vfprintf(stderr,fmt,ap); + (void)fprintf(stderr,"\n"); +} + +static void +warnx(const char *fmt,...) +{ + va_list ap; + va_start(ap,fmt); + _vwarnx(fmt,ap); + va_end(ap); +} + +/* + * Compute the greatest common divisor of a and b. + */ +static int +gcd(int a, int b) +{ + int c; + + c = a % b; + while (c != 0) { + a = b; + b = c; + c = a % b; + } + + return (b); +} + +/* + * Exchange the block from nonopt_start to nonopt_end with the block + * from nonopt_end to opt_end (keeping the same order of arguments + * in each block). + */ +static void +permute_args(int panonopt_start, int panonopt_end, int opt_end, + char * const *nargv) +{ + int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; + char *swap; + + /* + * compute lengths of blocks and number and size of cycles + */ + nnonopts = panonopt_end - panonopt_start; + nopts = opt_end - panonopt_end; + ncycle = gcd(nnonopts, nopts); + cyclelen = (opt_end - panonopt_start) / ncycle; + + for (i = 0; i < ncycle; i++) { + cstart = panonopt_end+i; + pos = cstart; + for (j = 0; j < cyclelen; j++) { + if (pos >= panonopt_end) + pos -= nnonopts; + else + pos += nopts; + swap = nargv[pos]; + /* LINTED const cast */ + ((char **) nargv)[pos] = nargv[cstart]; + /* LINTED const cast */ + ((char **)nargv)[cstart] = swap; + } + } +} + +#ifdef REPLACE_GETOPT +/* + * getopt -- + * Parse argc/argv argument vector. + * + * [eventually this will replace the BSD getopt] + */ +int +getopt(int nargc, char * const *nargv, const char *options) +{ + + /* + * We don't pass FLAG_PERMUTE to getopt_internal() since + * the BSD getopt(3) (unlike GNU) has never done this. + * + * Furthermore, since many privileged programs call getopt() + * before dropping privileges it makes sense to keep things + * as simple (and bug-free) as possible. + */ + return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); +} +#endif /* REPLACE_GETOPT */ + +//extern int getopt(int nargc, char * const *nargv, const char *options); + +#ifdef _BSD_SOURCE +/* + * BSD adds the non-standard `optreset' feature, for reinitialisation + * of `getopt' parsing. We support this feature, for applications which + * proclaim their BSD heritage, before including this header; however, + * to maintain portability, developers are advised to avoid it. + */ +# define optreset __mingw_optreset +extern int optreset; +#endif +#ifdef __cplusplus +} +#endif +/* + * POSIX requires the `getopt' API to be specified in `unistd.h'; + * thus, `unistd.h' includes this header. However, we do not want + * to expose the `getopt_long' or `getopt_long_only' APIs, when + * included in this manner. Thus, close the standard __GETOPT_H__ + * declarations block, and open an additional __GETOPT_LONG_H__ + * specific block, only when *not* __UNISTD_H_SOURCED__, in which + * to declare the extended API. + */ +#endif /* !defined(__GETOPT_H__) */ + +#if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) +#define __GETOPT_LONG_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +enum /* permitted values for its `has_arg' field... */ +{ + no_argument = 0, /* option never takes an argument */ + required_argument, /* option always requires an argument */ + optional_argument /* option may take an argument */ +}; + +/* + * parse_long_options -- + * Parse long options in argc/argv argument vector. + * Returns -1 if short_too is set and the option does not match long_options. + */ +static int +parse_long_options(char * const *nargv, const char *options, + const struct option *long_options, int *idx, int short_too) +{ + char *current_argv, *has_equal; + size_t current_argv_len; + int i, ambiguous, match; + +#define IDENTICAL_INTERPRETATION(_x, _y) \ + (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ + long_options[(_x)].flag == long_options[(_y)].flag && \ + long_options[(_x)].val == long_options[(_y)].val) + + current_argv = place; + match = -1; + ambiguous = 0; + + optind++; + + if ((has_equal = strchr(current_argv, '=')) != NULL) { + /* argument found (--option=arg) */ + current_argv_len = has_equal - current_argv; + has_equal++; + } else + current_argv_len = strlen(current_argv); + + for (i = 0; long_options[i].name; i++) { + /* find matching long option */ + if (strncmp(current_argv, long_options[i].name, + current_argv_len)) + continue; + + if (strlen(long_options[i].name) == current_argv_len) { + /* exact match */ + match = i; + ambiguous = 0; + break; + } + /* + * If this is a known short option, don't allow + * a partial match of a single character. + */ + if (short_too && current_argv_len == 1) + continue; + + if (match == -1) /* partial match */ + match = i; + else if (!IDENTICAL_INTERPRETATION(i, match)) + ambiguous = 1; + } + if (ambiguous) { + /* ambiguous abbreviation */ + if (PRINT_ERROR) + warnx(ambig, (int)current_argv_len, + current_argv); + optopt = 0; + return (BADCH); + } + if (match != -1) { /* option found */ + if (long_options[match].has_arg == no_argument + && has_equal) { + if (PRINT_ERROR) + warnx(noarg, (int)current_argv_len, + current_argv); + /* + * XXX: GNU sets optopt to val regardless of flag + */ + if (long_options[match].flag == NULL) + optopt = long_options[match].val; + else + optopt = 0; + return (BADARG); + } + if (long_options[match].has_arg == required_argument || + long_options[match].has_arg == optional_argument) { + if (has_equal) + optarg = has_equal; + else if (long_options[match].has_arg == + required_argument) { + /* + * optional argument doesn't use next nargv + */ + optarg = nargv[optind++]; + } + } + if ((long_options[match].has_arg == required_argument) + && (optarg == NULL)) { + /* + * Missing argument; leading ':' indicates no error + * should be generated. + */ + if (PRINT_ERROR) + warnx(recargstring, + current_argv); + /* + * XXX: GNU sets optopt to val regardless of flag + */ + if (long_options[match].flag == NULL) + optopt = long_options[match].val; + else + optopt = 0; + --optind; + return (BADARG); + } + } else { /* unknown option */ + if (short_too) { + --optind; + return (-1); + } + if (PRINT_ERROR) + warnx(illoptstring, current_argv); + optopt = 0; + return (BADCH); + } + if (idx) + *idx = match; + if (long_options[match].flag) { + *long_options[match].flag = long_options[match].val; + return (0); + } else + return (long_options[match].val); +#undef IDENTICAL_INTERPRETATION +} + +/* + * getopt_internal -- + * Parse argc/argv argument vector. Called by user level routines. + */ +static int +getopt_internal(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx, int flags) +{ + char *oli; /* option letter list index */ + int optchar, short_too; + static int posixly_correct = -1; + + if (options == NULL) + return (-1); + + /* + * XXX Some GNU programs (like cvs) set optind to 0 instead of + * XXX using optreset. Work around this braindamage. + */ + if (optind == 0) + optind = optreset = 1; + + /* + * Disable GNU extensions if POSIXLY_CORRECT is set or options + * string begins with a '+'. + * + * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or + * optreset != 0 for GNU compatibility. + */ + if (posixly_correct == -1 || optreset != 0) + posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); + if (*options == '-') + flags |= FLAG_ALLARGS; + else if (posixly_correct || *options == '+') + flags &= ~FLAG_PERMUTE; + if (*options == '+' || *options == '-') + options++; + + optarg = NULL; + if (optreset) + nonopt_start = nonopt_end = -1; +start: + if (optreset || !*place) { /* update scanning pointer */ + optreset = 0; + if (optind >= nargc) { /* end of argument vector */ + place = EMSG; + if (nonopt_end != -1) { + /* do permutation, if we have to */ + permute_args(nonopt_start, nonopt_end, + optind, nargv); + optind -= nonopt_end - nonopt_start; + } + else if (nonopt_start != -1) { + /* + * If we skipped non-options, set optind + * to the first of them. + */ + optind = nonopt_start; + } + nonopt_start = nonopt_end = -1; + return (-1); + } + if (*(place = nargv[optind]) != '-' || + (place[1] == '\0' && strchr(options, '-') == NULL)) { + place = EMSG; /* found non-option */ + if (flags & FLAG_ALLARGS) { + /* + * GNU extension: + * return non-option as argument to option 1 + */ + optarg = nargv[optind++]; + return (INORDER); + } + if (!(flags & FLAG_PERMUTE)) { + /* + * If no permutation wanted, stop parsing + * at first non-option. + */ + return (-1); + } + /* do permutation */ + if (nonopt_start == -1) + nonopt_start = optind; + else if (nonopt_end != -1) { + permute_args(nonopt_start, nonopt_end, + optind, nargv); + nonopt_start = optind - + (nonopt_end - nonopt_start); + nonopt_end = -1; + } + optind++; + /* process next argument */ + goto start; + } + if (nonopt_start != -1 && nonopt_end == -1) + nonopt_end = optind; + + /* + * If we have "-" do nothing, if "--" we are done. + */ + if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { + optind++; + place = EMSG; + /* + * We found an option (--), so if we skipped + * non-options, we have to permute. + */ + if (nonopt_end != -1) { + permute_args(nonopt_start, nonopt_end, + optind, nargv); + optind -= nonopt_end - nonopt_start; + } + nonopt_start = nonopt_end = -1; + return (-1); + } + } + + /* + * Check long options if: + * 1) we were passed some + * 2) the arg is not just "-" + * 3) either the arg starts with -- we are getopt_long_only() + */ + if (long_options != NULL && place != nargv[optind] && + (*place == '-' || (flags & FLAG_LONGONLY))) { + short_too = 0; + if (*place == '-') + place++; /* --foo long option */ + else if (*place != ':' && strchr(options, *place) != NULL) + short_too = 1; /* could be short option too */ + + optchar = parse_long_options(nargv, options, long_options, + idx, short_too); + if (optchar != -1) { + place = EMSG; + return (optchar); + } + } + + if ((optchar = (int)*place++) == (int)':' || + (optchar == (int)'-' && *place != '\0') || + (oli = (char*)strchr(options, optchar)) == NULL) { + /* + * If the user specified "-" and '-' isn't listed in + * options, return -1 (non-option) as per POSIX. + * Otherwise, it is an unknown option character (or ':'). + */ + if (optchar == (int)'-' && *place == '\0') + return (-1); + if (!*place) + ++optind; + if (PRINT_ERROR) + warnx(illoptchar, optchar); + optopt = optchar; + return (BADCH); + } + if (long_options != NULL && optchar == 'W' && oli[1] == ';') { + /* -W long-option */ + if (*place) /* no space */ + /* NOTHING */; + else if (++optind >= nargc) { /* no arg */ + place = EMSG; + if (PRINT_ERROR) + warnx(recargchar, optchar); + optopt = optchar; + return (BADARG); + } else /* white space */ + place = nargv[optind]; + optchar = parse_long_options(nargv, options, long_options, + idx, 0); + place = EMSG; + return (optchar); + } + if (*++oli != ':') { /* doesn't take argument */ + if (!*place) + ++optind; + } else { /* takes (optional) argument */ + optarg = NULL; + if (*place) /* no white space */ + optarg = place; + else if (oli[1] != ':') { /* arg not optional */ + if (++optind >= nargc) { /* no arg */ + place = EMSG; + if (PRINT_ERROR) + warnx(recargchar, optchar); + optopt = optchar; + return (BADARG); + } else + optarg = nargv[optind]; + } + place = EMSG; + ++optind; + } + /* dump back option letter */ + return (optchar); +} + +/* + * getopt_long -- + * Parse argc/argv argument vector. + */ +int +getopt_long(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx) +{ + + return (getopt_internal(nargc, nargv, options, long_options, idx, + FLAG_PERMUTE)); +} + +/* + * getopt_long_only -- + * Parse argc/argv argument vector. + */ +int +getopt_long_only(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx) +{ + + return (getopt_internal(nargc, nargv, options, long_options, idx, + FLAG_PERMUTE|FLAG_LONGONLY)); +} + +//extern int getopt_long(int nargc, char * const *nargv, const char *options, +// const struct option *long_options, int *idx); +//extern int getopt_long_only(int nargc, char * const *nargv, const char *options, +// const struct option *long_options, int *idx); +/* + * Previous MinGW implementation had... + */ +#ifndef HAVE_DECL_GETOPT +/* + * ...for the long form API only; keep this for compatibility. + */ +# define HAVE_DECL_GETOPT 1 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */ diff --git a/src/granger/src/lnettlelib.c b/src/granger/src/lnettlelib.c new file mode 100644 index 0000000..787c75f --- /dev/null +++ b/src/granger/src/lnettlelib.c @@ -0,0 +1,181 @@ +/* + * This file is part of Granger. + * Copyright (c) 2016 Jeff Kent + * + * Granger 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. + * + * Granger 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 Granger. If not, see . + */ + +#include + +#include "lua.h" +#include "lauxlib.h" +#include "nettle/md5.h" +#include "nettle/sha2.h" + +#define MD5_CTX "md5_ctx*" +#define SHA256_CTX "sha256_ctx*" + +static int lmd5(lua_State *L) +{ + struct md5_ctx *ctx; + + ctx = (struct md5_ctx *)lua_newuserdata(L, sizeof(struct md5_ctx)); + luaL_setmetatable(L, MD5_CTX); + md5_init(ctx); + return 1; +} + +static int lmd5_digest(lua_State *L) +{ + struct md5_ctx *ctx; + char digest[MD5_DIGEST_SIZE]; + + ctx = luaL_checkudata(L, 1, MD5_CTX); + md5_digest(ctx, sizeof(digest), digest); + lua_pushlstring(L, digest, sizeof(digest)); + return 1; +} + +static int lmd5_update(lua_State *L) +{ + struct md5_ctx *ctx; + const char *data; + size_t len; + + ctx = luaL_checkudata(L, 1, MD5_CTX); + if (lua_isnil(L, 2)) { + return 0; + } + data = luaL_checklstring(L, 2, &len); + nettle_md5_update(ctx, len, data); + return 0; +} + +static int lmd5_tostring(lua_State *L) +{ + struct md5_ctx *ctx, ctx2; + char digest[MD5_DIGEST_SIZE]; + char hex[MD5_DIGEST_SIZE*2+1]; + int i; + + ctx = luaL_checkudata(L, 1, MD5_CTX); + memcpy(&ctx2, ctx, sizeof(struct md5_ctx)); + + md5_digest(&ctx2, sizeof(digest), digest); + for (i = 0; i < sizeof(digest); i++) { + sprintf(hex + 2 * i, "%02hhx", digest[i]); + } + + lua_pushstring(L, hex); + return 1; +} + +static int lsha256(lua_State *L) +{ + struct sha256_ctx *ctx; + + ctx = (struct sha256_ctx *)lua_newuserdata(L, sizeof(struct sha256_ctx)); + luaL_setmetatable(L, SHA256_CTX); + sha256_init(ctx); + return 1; +} + +static int lsha256_digest(lua_State *L) +{ + struct sha256_ctx *ctx; + char digest[SHA256_DIGEST_SIZE]; + + ctx = luaL_checkudata(L, 1, SHA256_CTX); + sha256_digest(ctx, sizeof(digest), digest); + lua_pushlstring(L, digest, sizeof(digest)); + return 1; +} + +static int lsha256_update(lua_State *L) +{ + struct sha256_ctx *ctx; + const char *data; + size_t len; + + ctx = luaL_checkudata(L, 1, SHA256_CTX); + if (lua_isnil(L, 2)) { + return 0; + } + data = luaL_checklstring(L, 2, &len); + nettle_sha256_update(ctx, len, data); + return 0; +} + +static int lsha256_tostring(lua_State *L) +{ + struct sha256_ctx *ctx, ctx2; + char digest[SHA256_DIGEST_SIZE]; + char hex[SHA256_DIGEST_SIZE*2+1]; + int i; + + ctx = luaL_checkudata(L, 1, SHA256_CTX); + memcpy(&ctx2, ctx, sizeof(struct sha256_ctx)); + + sha256_digest(&ctx2, sizeof(digest), digest); + for (i = 0; i < sizeof(digest); i++) { + sprintf(hex + 2 * i, "%02hhx", digest[i]); + } + + lua_pushstring(L, hex); + return 1; +} + +/* functions for 'nettle' library */ +static const luaL_Reg nettlelib[] = { + {"md5", lmd5}, + {"sha256", lsha256}, + {NULL, NULL} +}; + +static const luaL_Reg lmd5_methods[] = { + {"digest", lmd5_digest}, + {"update", lmd5_update}, + {"__tostring", lmd5_tostring}, + {NULL, NULL} +}; + +/* functions for sha256 objects */ +static const luaL_Reg lsha256_methods[] = { + {"digest", lsha256_digest}, + {"update", lsha256_update}, + {"__tostring", lsha256_tostring}, + {NULL, NULL} +}; + +static void createmeta (lua_State *L) +{ + luaL_newmetatable(L, MD5_CTX); /* create metatable for file handles */ + lua_pushvalue(L, -1); /* push metatable */ + lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ + luaL_setfuncs(L, lmd5_methods, 0); /* add file methods to new metatable */ + lua_pop(L, 1); /* pop new metatable */ + + luaL_newmetatable(L, SHA256_CTX); /* create metatable for file handles */ + lua_pushvalue(L, -1); /* push metatable */ + lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ + luaL_setfuncs(L, lsha256_methods, 0); /* add file methods to new metatable */ + lua_pop(L, 1); /* pop new metatable */ +} + +LUAMOD_API int luaopen_nettle (lua_State *L) +{ + luaL_newlib(L, nettlelib); + createmeta(L); + return 1; +} diff --git a/src/granger/src/lnettlelib.h b/src/granger/src/lnettlelib.h new file mode 100644 index 0000000..0afd753 --- /dev/null +++ b/src/granger/src/lnettlelib.h @@ -0,0 +1,25 @@ +/* + * This file is part of Granger. + * Copyright (c) 2016 Jeff Kent + * + * Granger 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. + * + * Granger 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 Granger. If not, see . + */ + +#ifndef lnettlelib_h +#define lnettlelib_h + +#define LUA_NETTLELIBNAME "nettle" +LUAMOD_API int (luaopen_nettle) (lua_State *L); + +#endif /* lnettlelib_h */ diff --git a/src/granger/src/lua/CMakeLists.txt b/src/granger/src/lua/CMakeLists.txt new file mode 100644 index 0000000..1508ef2 --- /dev/null +++ b/src/granger/src/lua/CMakeLists.txt @@ -0,0 +1,57 @@ +set(PARENT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../..) + +add_library( granger_lua STATIC + ${PARENT_DIR}/lua-5.3.3/src/lapi.c + ${PARENT_DIR}/lua-5.3.3/src/lcode.c + ${PARENT_DIR}/lua-5.3.3/src/lctype.c + ${PARENT_DIR}/lua-5.3.3/src/ldebug.c + ${PARENT_DIR}/lua-5.3.3/src/ldo.c + ${PARENT_DIR}/lua-5.3.3/src/ldump.c + ${PARENT_DIR}/lua-5.3.3/src/lfunc.c + ${PARENT_DIR}/lua-5.3.3/src/lgc.c + ${PARENT_DIR}/lua-5.3.3/src/llex.c + ${PARENT_DIR}/lua-5.3.3/src/lmem.c + ${PARENT_DIR}/lua-5.3.3/src/lobject.c + ${PARENT_DIR}/lua-5.3.3/src/lopcodes.c + ${PARENT_DIR}/lua-5.3.3/src/lparser.c + ${PARENT_DIR}/lua-5.3.3/src/lstate.c + ${PARENT_DIR}/lua-5.3.3/src/lstring.c + ${PARENT_DIR}/lua-5.3.3/src/ltable.c + ${PARENT_DIR}/lua-5.3.3/src/ltm.c + ${PARENT_DIR}/lua-5.3.3/src/lundump.c + ${PARENT_DIR}/lua-5.3.3/src/lvm.c + ${PARENT_DIR}/lua-5.3.3/src/lzio.c + ${PARENT_DIR}/lua-5.3.3/src/lauxlib.c + ${PARENT_DIR}/lua-5.3.3/src/lbaselib.c + ${PARENT_DIR}/lua-5.3.3/src/lbitlib.c + ${PARENT_DIR}/lua-5.3.3/src/lcorolib.c + ${PARENT_DIR}/lua-5.3.3/src/ldblib.c + ${PARENT_DIR}/lua-5.3.3/src/liolib.c + ${PARENT_DIR}/lua-5.3.3/src/lmathlib.c + ${PARENT_DIR}/lua-5.3.3/src/loslib.c + ${PARENT_DIR}/lua-5.3.3/src/lstrlib.c + ${PARENT_DIR}/lua-5.3.3/src/ltablib.c + ${PARENT_DIR}/lua-5.3.3/src/lutf8lib.c + ${PARENT_DIR}/lua-5.3.3/src/loadlib.c + ${PARENT_DIR}/lua-5.3.3/src/linit.c + ) + +if(APPLE) + add_definitions(-DLUA_USE_MACOSX) +endif(APPLE) + +if(${CMAKE_SYSTEM_NAME} STREQUAL "Linux") + add_definitions(-DLUA_USE_LINUX) +endif() + +add_definitions ( + -DLUA_COMPAT_5_2 + -DNDEBUG + -mfpmath=sse + -ffast-math + -DGRANGER + ) + +include_directories ( + include + ) diff --git a/src/granger/src/main.c b/src/granger/src/main.c new file mode 100644 index 0000000..3d1b28f --- /dev/null +++ b/src/granger/src/main.c @@ -0,0 +1,97 @@ +/* + * This file is part of Granger. + * Copyright (c) 2016 Jeff Kent + * + * Granger 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. + * + * Granger 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 Granger. If not, see . + */ + +#include +#include +#include +#include + +#include "lua.h" +#include "lauxlib.h" +#include "lualib.h" +#include "premake/premake.h" + +#if defined(PLATFORM_WINDOWS) +#include "getopt.h" +#endif + +#include "lnettlelib.h" + +extern const luaL_Reg extra_os_functions[]; + +int main (int argc, char *argv[]) +{ + char *script_path; + lua_State *L; + int c; + + while ((c = getopt(argc, argv, "C:")) != -1) { + switch (c) { + case 'C': + if (chdir(optarg)) { + fprintf(stderr, "could not change working directory\n"); + return EXIT_FAILURE; + } + break; + case '?': + default: + return EXIT_FAILURE; + } + } + + if (optind >= argc || argv[optind][0] == '-') { + fprintf(stderr, "lua script not provided\n"); + return EXIT_FAILURE; + } + script_path = argv[optind]; + optind++; + + L = luaL_newstate(); + if (L == NULL) { + fprintf(stderr, "cannot create lua state\n"); + return EXIT_FAILURE; + } + + luaL_openlibs(L); + luaL_requiref(L, "nettle", luaopen_nettle, 1); + lua_pop(L, 1); + + premake_init(L); + premake_locate(L, argv[0]); + lua_setglobal(L, "_EXE_PATH"); + + lua_pushstring(L, script_path); + lua_setglobal(L, "_GRANGER_SCRIPT"); + + lua_newtable(L); + for (int i = 1; optind < argc; i++, optind++) { + lua_pushinteger(L, i); + lua_pushstring(L, argv[optind]); + lua_settable(L, 1); + } + lua_setglobal(L, "argv"); + + if (luaL_dofile(L, script_path)) { + fprintf(stderr, "Error: %s\n", lua_tostring(L, -1)); + lua_close(L); + return EXIT_FAILURE; + } + + lua_close(L); + return EXIT_SUCCESS; +} diff --git a/src/granger/src/nettle/CMakeLists.txt b/src/granger/src/nettle/CMakeLists.txt new file mode 100644 index 0000000..c2ec77c --- /dev/null +++ b/src/granger/src/nettle/CMakeLists.txt @@ -0,0 +1,23 @@ +if(NOT WIN32) + add_definitions(-Wall -Wextra) +endif(NOT WIN32) + +if(WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +endif(WIN32) + +add_library(granger_nettle + macros.h + md5-compress.c + md5.c + md5.h + nettle-stdint.h + nettle-types.h + nettle-write.h + sha2.h + sha256-compress.c + sha256.c + version.h + write-be32.c + write-le32.c + ) diff --git a/src/granger/src/nettle/macros.h b/src/granger/src/nettle/macros.h new file mode 100644 index 0000000..af84841 --- /dev/null +++ b/src/granger/src/nettle/macros.h @@ -0,0 +1,245 @@ +/* macros.h + + Copyright (C) 2001, 2010 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#ifndef NETTLE_MACROS_H_INCLUDED +#define NETTLE_MACROS_H_INCLUDED + +/* Reads a 64-bit integer, in network, big-endian, byte order */ +#define READ_UINT64(p) \ +( (((uint64_t) (p)[0]) << 56) \ + | (((uint64_t) (p)[1]) << 48) \ + | (((uint64_t) (p)[2]) << 40) \ + | (((uint64_t) (p)[3]) << 32) \ + | (((uint64_t) (p)[4]) << 24) \ + | (((uint64_t) (p)[5]) << 16) \ + | (((uint64_t) (p)[6]) << 8) \ + | ((uint64_t) (p)[7])) + +#define WRITE_UINT64(p, i) \ +do { \ + (p)[0] = ((i) >> 56) & 0xff; \ + (p)[1] = ((i) >> 48) & 0xff; \ + (p)[2] = ((i) >> 40) & 0xff; \ + (p)[3] = ((i) >> 32) & 0xff; \ + (p)[4] = ((i) >> 24) & 0xff; \ + (p)[5] = ((i) >> 16) & 0xff; \ + (p)[6] = ((i) >> 8) & 0xff; \ + (p)[7] = (i) & 0xff; \ +} while(0) + +/* Reads a 32-bit integer, in network, big-endian, byte order */ +#define READ_UINT32(p) \ +( (((uint32_t) (p)[0]) << 24) \ + | (((uint32_t) (p)[1]) << 16) \ + | (((uint32_t) (p)[2]) << 8) \ + | ((uint32_t) (p)[3])) + +#define WRITE_UINT32(p, i) \ +do { \ + (p)[0] = ((i) >> 24) & 0xff; \ + (p)[1] = ((i) >> 16) & 0xff; \ + (p)[2] = ((i) >> 8) & 0xff; \ + (p)[3] = (i) & 0xff; \ +} while(0) + +/* Analogous macros, for 24 and 16 bit numbers */ +#define READ_UINT24(p) \ +( (((uint32_t) (p)[0]) << 16) \ + | (((uint32_t) (p)[1]) << 8) \ + | ((uint32_t) (p)[2])) + +#define WRITE_UINT24(p, i) \ +do { \ + (p)[0] = ((i) >> 16) & 0xff; \ + (p)[1] = ((i) >> 8) & 0xff; \ + (p)[2] = (i) & 0xff; \ +} while(0) + +#define READ_UINT16(p) \ +( (((uint32_t) (p)[0]) << 8) \ + | ((uint32_t) (p)[1])) + +#define WRITE_UINT16(p, i) \ +do { \ + (p)[0] = ((i) >> 8) & 0xff; \ + (p)[1] = (i) & 0xff; \ +} while(0) + +/* And the other, little-endian, byteorder */ +#define LE_READ_UINT64(p) \ +( (((uint64_t) (p)[7]) << 56) \ + | (((uint64_t) (p)[6]) << 48) \ + | (((uint64_t) (p)[5]) << 40) \ + | (((uint64_t) (p)[4]) << 32) \ + | (((uint64_t) (p)[3]) << 24) \ + | (((uint64_t) (p)[2]) << 16) \ + | (((uint64_t) (p)[1]) << 8) \ + | ((uint64_t) (p)[0])) + +#define LE_WRITE_UINT64(p, i) \ +do { \ + (p)[7] = ((i) >> 56) & 0xff; \ + (p)[6] = ((i) >> 48) & 0xff; \ + (p)[5] = ((i) >> 40) & 0xff; \ + (p)[4] = ((i) >> 32) & 0xff; \ + (p)[3] = ((i) >> 24) & 0xff; \ + (p)[2] = ((i) >> 16) & 0xff; \ + (p)[1] = ((i) >> 8) & 0xff; \ + (p)[0] = (i) & 0xff; \ +} while (0) + +#define LE_READ_UINT32(p) \ +( (((uint32_t) (p)[3]) << 24) \ + | (((uint32_t) (p)[2]) << 16) \ + | (((uint32_t) (p)[1]) << 8) \ + | ((uint32_t) (p)[0])) + +#define LE_WRITE_UINT32(p, i) \ +do { \ + (p)[3] = ((i) >> 24) & 0xff; \ + (p)[2] = ((i) >> 16) & 0xff; \ + (p)[1] = ((i) >> 8) & 0xff; \ + (p)[0] = (i) & 0xff; \ +} while(0) + +/* Analogous macros, for 16 bit numbers */ +#define LE_READ_UINT16(p) \ + ( (((uint32_t) (p)[1]) << 8) \ + | ((uint32_t) (p)[0])) + +#define LE_WRITE_UINT16(p, i) \ + do { \ + (p)[1] = ((i) >> 8) & 0xff; \ + (p)[0] = (i) & 0xff; \ + } while(0) + +/* Macro to make it easier to loop over several blocks. */ +#define FOR_BLOCKS(length, dst, src, blocksize) \ + assert( !((length) % (blocksize))); \ + for (; (length); ((length) -= (blocksize), \ + (dst) += (blocksize), \ + (src) += (blocksize)) ) + +/* The masking of the right shift is needed to allow n == 0 (using + just 32 - n and 64 - n results in undefined behaviour). Most uses + of these macros use a constant and non-zero rotation count. */ +#define ROTL32(n,x) (((x)<<(n)) | ((x)>>((-(n)&31)))) + +#define ROTL64(n,x) (((x)<<(n)) | ((x)>>((-(n))&63))) + +/* Requires that size > 0 */ +#define INCREMENT(size, ctr) \ + do { \ + unsigned increment_i = (size) - 1; \ + if (++(ctr)[increment_i] == 0) \ + while (increment_i > 0 \ + && ++(ctr)[--increment_i] == 0 ) \ + ; \ + } while (0) + + +/* Helper macro for Merkle-Damgård hash functions. Assumes the context + structs includes the following fields: + + uint8_t block[...]; // Buffer holding one block + unsigned int index; // Index into block +*/ + +/* Currently used by sha512 (and sha384) only. */ +#define MD_INCR(ctx) ((ctx)->count_high += !++(ctx)->count_low) + +/* Takes the compression function f as argument. NOTE: also clobbers + length and data. */ +#define MD_UPDATE(ctx, length, data, f, incr) \ + do { \ + if ((ctx)->index) \ + { \ + /* Try to fill partial block */ \ + unsigned __md_left = sizeof((ctx)->block) - (ctx)->index; \ + if ((length) < __md_left) \ + { \ + memcpy((ctx)->block + (ctx)->index, (data), (length)); \ + (ctx)->index += (length); \ + goto __md_done; /* Finished */ \ + } \ + else \ + { \ + memcpy((ctx)->block + (ctx)->index, (data), __md_left); \ + \ + f((ctx), (ctx)->block); \ + (incr); \ + \ + (data) += __md_left; \ + (length) -= __md_left; \ + } \ + } \ + while ((length) >= sizeof((ctx)->block)) \ + { \ + f((ctx), (data)); \ + (incr); \ + \ + (data) += sizeof((ctx)->block); \ + (length) -= sizeof((ctx)->block); \ + } \ + memcpy ((ctx)->block, (data), (length)); \ + (ctx)->index = (length); \ + __md_done: \ + ; \ + } while (0) + +/* Pads the block to a block boundary with the bit pattern 1 0*, + leaving size octets for the length field at the end. If needed, + compresses the block and starts a new one. */ +#define MD_PAD(ctx, size, f) \ + do { \ + unsigned __md_i; \ + __md_i = (ctx)->index; \ + \ + /* Set the first char of padding to 0x80. This is safe since there \ + is always at least one byte free */ \ + \ + assert(__md_i < sizeof((ctx)->block)); \ + (ctx)->block[__md_i++] = 0x80; \ + \ + if (__md_i > (sizeof((ctx)->block) - (size))) \ + { /* No room for length in this block. Process it and \ + pad with another one */ \ + memset((ctx)->block + __md_i, 0, sizeof((ctx)->block) - __md_i); \ + \ + f((ctx), (ctx)->block); \ + __md_i = 0; \ + } \ + memset((ctx)->block + __md_i, 0, \ + sizeof((ctx)->block) - (size) - __md_i); \ + \ + } while (0) + +#endif /* NETTLE_MACROS_H_INCLUDED */ diff --git a/src/granger/src/nettle/md5-compress.c b/src/granger/src/nettle/md5-compress.c new file mode 100644 index 0000000..b8dad3f --- /dev/null +++ b/src/granger/src/nettle/md5-compress.c @@ -0,0 +1,174 @@ +/* md5-compress.c + + The compression function for the md5 hash function. + + Copyright (C) 2001, 2005 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +/* Based on public domain code hacked by Colin Plumb, Andrew Kuchling, and + * Niels Möller. */ + + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#ifndef MD5_DEBUG +# define MD5_DEBUG 0 +#endif + +#if MD5_DEBUG +# include +# define DEBUG(i) \ + fprintf(stderr, "%2d: %8x %8x %8x %8x\n", i, a, b, c, d) +#else +# define DEBUG(i) +#endif + +#include +#include +#include + +#include "md5.h" + +#include "macros.h" + +/* A block, treated as a sequence of 32-bit words. */ +#define MD5_DATA_LENGTH 16 + +/* MD5 functions */ + +#define F1(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define F2(x, y, z) F1((z), (x), (y)) +#define F3(x, y, z) ((x) ^ (y) ^ (z)) +#define F4(x, y, z) ((y) ^ ((x) | ~(z))) + +#define ROUND(f, w, x, y, z, data, s) \ +( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + +/* Perform the MD5 transformation on one full block of 16 32-bit + * words. + * + * Compresses 20 (_MD5_DIGEST_LENGTH + MD5_DATA_LENGTH) words into 4 + * (_MD5_DIGEST_LENGTH) words. */ + +void +_nettle_md5_compress(uint32_t *digest, const uint8_t *input) +{ + uint32_t data[MD5_DATA_LENGTH]; + uint32_t a, b, c, d; + unsigned i; + + for (i = 0; i < MD5_DATA_LENGTH; i++, input += 4) + data[i] = LE_READ_UINT32(input); + + a = digest[0]; + b = digest[1]; + c = digest[2]; + d = digest[3]; + + DEBUG(-1); + ROUND(F1, a, b, c, d, data[ 0] + 0xd76aa478, 7); DEBUG(0); + ROUND(F1, d, a, b, c, data[ 1] + 0xe8c7b756, 12); DEBUG(1); + ROUND(F1, c, d, a, b, data[ 2] + 0x242070db, 17); + ROUND(F1, b, c, d, a, data[ 3] + 0xc1bdceee, 22); + ROUND(F1, a, b, c, d, data[ 4] + 0xf57c0faf, 7); + ROUND(F1, d, a, b, c, data[ 5] + 0x4787c62a, 12); + ROUND(F1, c, d, a, b, data[ 6] + 0xa8304613, 17); + ROUND(F1, b, c, d, a, data[ 7] + 0xfd469501, 22); + ROUND(F1, a, b, c, d, data[ 8] + 0x698098d8, 7); + ROUND(F1, d, a, b, c, data[ 9] + 0x8b44f7af, 12); + ROUND(F1, c, d, a, b, data[10] + 0xffff5bb1, 17); + ROUND(F1, b, c, d, a, data[11] + 0x895cd7be, 22); + ROUND(F1, a, b, c, d, data[12] + 0x6b901122, 7); + ROUND(F1, d, a, b, c, data[13] + 0xfd987193, 12); + ROUND(F1, c, d, a, b, data[14] + 0xa679438e, 17); + ROUND(F1, b, c, d, a, data[15] + 0x49b40821, 22); DEBUG(15); + + ROUND(F2, a, b, c, d, data[ 1] + 0xf61e2562, 5); DEBUG(16); + ROUND(F2, d, a, b, c, data[ 6] + 0xc040b340, 9); DEBUG(17); + ROUND(F2, c, d, a, b, data[11] + 0x265e5a51, 14); + ROUND(F2, b, c, d, a, data[ 0] + 0xe9b6c7aa, 20); + ROUND(F2, a, b, c, d, data[ 5] + 0xd62f105d, 5); + ROUND(F2, d, a, b, c, data[10] + 0x02441453, 9); + ROUND(F2, c, d, a, b, data[15] + 0xd8a1e681, 14); + ROUND(F2, b, c, d, a, data[ 4] + 0xe7d3fbc8, 20); + ROUND(F2, a, b, c, d, data[ 9] + 0x21e1cde6, 5); + ROUND(F2, d, a, b, c, data[14] + 0xc33707d6, 9); + ROUND(F2, c, d, a, b, data[ 3] + 0xf4d50d87, 14); + ROUND(F2, b, c, d, a, data[ 8] + 0x455a14ed, 20); + ROUND(F2, a, b, c, d, data[13] + 0xa9e3e905, 5); + ROUND(F2, d, a, b, c, data[ 2] + 0xfcefa3f8, 9); + ROUND(F2, c, d, a, b, data[ 7] + 0x676f02d9, 14); + ROUND(F2, b, c, d, a, data[12] + 0x8d2a4c8a, 20); DEBUG(31); + + ROUND(F3, a, b, c, d, data[ 5] + 0xfffa3942, 4); DEBUG(32); + ROUND(F3, d, a, b, c, data[ 8] + 0x8771f681, 11); DEBUG(33); + ROUND(F3, c, d, a, b, data[11] + 0x6d9d6122, 16); + ROUND(F3, b, c, d, a, data[14] + 0xfde5380c, 23); + ROUND(F3, a, b, c, d, data[ 1] + 0xa4beea44, 4); + ROUND(F3, d, a, b, c, data[ 4] + 0x4bdecfa9, 11); + ROUND(F3, c, d, a, b, data[ 7] + 0xf6bb4b60, 16); + ROUND(F3, b, c, d, a, data[10] + 0xbebfbc70, 23); + ROUND(F3, a, b, c, d, data[13] + 0x289b7ec6, 4); + ROUND(F3, d, a, b, c, data[ 0] + 0xeaa127fa, 11); + ROUND(F3, c, d, a, b, data[ 3] + 0xd4ef3085, 16); + ROUND(F3, b, c, d, a, data[ 6] + 0x04881d05, 23); + ROUND(F3, a, b, c, d, data[ 9] + 0xd9d4d039, 4); + ROUND(F3, d, a, b, c, data[12] + 0xe6db99e5, 11); + ROUND(F3, c, d, a, b, data[15] + 0x1fa27cf8, 16); + ROUND(F3, b, c, d, a, data[ 2] + 0xc4ac5665, 23); DEBUG(47); + + ROUND(F4, a, b, c, d, data[ 0] + 0xf4292244, 6); DEBUG(48); + ROUND(F4, d, a, b, c, data[ 7] + 0x432aff97, 10); DEBUG(49); + ROUND(F4, c, d, a, b, data[14] + 0xab9423a7, 15); + ROUND(F4, b, c, d, a, data[ 5] + 0xfc93a039, 21); + ROUND(F4, a, b, c, d, data[12] + 0x655b59c3, 6); + ROUND(F4, d, a, b, c, data[ 3] + 0x8f0ccc92, 10); + ROUND(F4, c, d, a, b, data[10] + 0xffeff47d, 15); + ROUND(F4, b, c, d, a, data[ 1] + 0x85845dd1, 21); + ROUND(F4, a, b, c, d, data[ 8] + 0x6fa87e4f, 6); + ROUND(F4, d, a, b, c, data[15] + 0xfe2ce6e0, 10); + ROUND(F4, c, d, a, b, data[ 6] + 0xa3014314, 15); + ROUND(F4, b, c, d, a, data[13] + 0x4e0811a1, 21); + ROUND(F4, a, b, c, d, data[ 4] + 0xf7537e82, 6); + ROUND(F4, d, a, b, c, data[11] + 0xbd3af235, 10); + ROUND(F4, c, d, a, b, data[ 2] + 0x2ad7d2bb, 15); + ROUND(F4, b, c, d, a, data[ 9] + 0xeb86d391, 21); DEBUG(63); + + digest[0] += a; + digest[1] += b; + digest[2] += c; + digest[3] += d; +#if MD5_DEBUG + fprintf(stderr, "99: %8x %8x %8x %8x\n", + digest[0], digest[1], digest[2], digest[3]); +#endif + +} diff --git a/src/granger/src/nettle/md5.c b/src/granger/src/nettle/md5.c new file mode 100644 index 0000000..97a5245 --- /dev/null +++ b/src/granger/src/nettle/md5.c @@ -0,0 +1,93 @@ +/* md5.c + + The MD5 hash function, described in RFC 1321. + + Copyright (C) 2001 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +/* Based on public domain code hacked by Colin Plumb, Andrew Kuchling, and + * Niels Möller. */ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include + +#include "md5.h" + +#include "macros.h" +#include "nettle-write.h" + +void +md5_init(struct md5_ctx *ctx) +{ + const uint32_t iv[_MD5_DIGEST_LENGTH] = + { + 0x67452301, + 0xefcdab89, + 0x98badcfe, + 0x10325476, + }; + memcpy(ctx->state, iv, sizeof(ctx->state)); + ctx->count = 0; + ctx->index = 0; +} + +#define COMPRESS(ctx, data) (_nettle_md5_compress((ctx)->state, (data))) + +void +md5_update(struct md5_ctx *ctx, + size_t length, + const uint8_t *data) +{ + MD_UPDATE(ctx, length, data, COMPRESS, ctx->count++); +} + +void +md5_digest(struct md5_ctx *ctx, + size_t length, + uint8_t *digest) +{ + uint64_t bit_count; + + assert(length <= MD5_DIGEST_SIZE); + + MD_PAD(ctx, 8, COMPRESS); + + /* There are 512 = 2^9 bits in one block */ + bit_count = (ctx->count << 9) | (ctx->index << 3); + + LE_WRITE_UINT64(ctx->block + (MD5_BLOCK_SIZE - 8), bit_count); + _nettle_md5_compress(ctx->state, ctx->block); + + _nettle_write_le32(length, digest, ctx->state); + md5_init(ctx); +} diff --git a/src/granger/src/nettle/md5.h b/src/granger/src/nettle/md5.h new file mode 100644 index 0000000..79304bc --- /dev/null +++ b/src/granger/src/nettle/md5.h @@ -0,0 +1,86 @@ +/* md5.h + + The MD5 hash function, described in RFC 1321. + + Copyright (C) 2001 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#ifndef NETTLE_MD5_H_INCLUDED +#define NETTLE_MD5_H_INCLUDED + +#include "nettle-types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Name mangling */ +#define md5_init nettle_md5_init +#define md5_update nettle_md5_update +#define md5_digest nettle_md5_digest + +#define MD5_DIGEST_SIZE 16 +#define MD5_BLOCK_SIZE 64 +/* For backwards compatibility */ +#define MD5_DATA_SIZE MD5_BLOCK_SIZE + +/* Digest is kept internally as 4 32-bit words. */ +#define _MD5_DIGEST_LENGTH 4 + +struct md5_ctx +{ + uint32_t state[_MD5_DIGEST_LENGTH]; + uint64_t count; /* Block count */ + uint8_t block[MD5_BLOCK_SIZE]; /* Block buffer */ + unsigned index; /* Into buffer */ +}; + +void +md5_init(struct md5_ctx *ctx); + +void +md5_update(struct md5_ctx *ctx, + size_t length, + const uint8_t *data); + +void +md5_digest(struct md5_ctx *ctx, + size_t length, + uint8_t *digest); + +/* Internal compression function. STATE points to 4 uint32_t words, + and DATA points to 64 bytes of input data, possibly unaligned. */ +void +_nettle_md5_compress(uint32_t *state, const uint8_t *data); + +#ifdef __cplusplus +} +#endif + +#endif /* NETTLE_MD5_H_INCLUDED */ diff --git a/src/granger/src/nettle/nettle-stdint.h b/src/granger/src/nettle/nettle-stdint.h new file mode 100644 index 0000000..3298fa6 --- /dev/null +++ b/src/granger/src/nettle/nettle-stdint.h @@ -0,0 +1,6 @@ +#ifndef __NETTLE_STDINT_H +#define __NETTLE_STDINT_H + +#include + +#endif /* __NETTLE_STDINT_H */ diff --git a/src/granger/src/nettle/nettle-types.h b/src/granger/src/nettle/nettle-types.h new file mode 100644 index 0000000..8f77ea9 --- /dev/null +++ b/src/granger/src/nettle/nettle-types.h @@ -0,0 +1,110 @@ +/* nettle-types.h + + Copyright (C) 2005, 2014 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#ifndef NETTLE_TYPES_H +#define NETTLE_TYPES_H + +/* For size_t */ +#include + +/* Pretend these types always exists. Nettle doesn't use them. */ +#define _STDINT_HAVE_INT_FAST32_T 1 +#include "nettle-stdint.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* An aligned 16-byte block. */ +union nettle_block16 +{ + uint8_t b[16]; + unsigned long w[16 / sizeof(unsigned long)]; +}; + +/* Randomness. Used by key generation and dsa signature creation. */ +typedef void nettle_random_func(void *ctx, + size_t length, uint8_t *dst); + +/* Progress report function, mainly for key generation. */ +typedef void nettle_progress_func(void *ctx, int c); + +/* Realloc function, used by struct nettle_buffer. */ +typedef void *nettle_realloc_func(void *ctx, void *p, size_t length); + +/* Ciphers */ +typedef void nettle_set_key_func(void *ctx, const uint8_t *key); + +/* For block ciphers, const context. */ +typedef void nettle_cipher_func(const void *ctx, + size_t length, uint8_t *dst, + const uint8_t *src); + + +/* Uses a void * for cipher contexts. Used for crypt operations where + the internal state changes during the encryption. */ +typedef void nettle_crypt_func(void *ctx, + size_t length, uint8_t *dst, + const uint8_t *src); + +/* Hash algorithms */ +typedef void nettle_hash_init_func(void *ctx); +typedef void nettle_hash_update_func(void *ctx, + size_t length, + const uint8_t *src); +typedef void nettle_hash_digest_func(void *ctx, + size_t length, uint8_t *dst); + +/* ASCII armor codecs. NOTE: Experimental and subject to change. */ + +typedef size_t nettle_armor_length_func(size_t length); +typedef void nettle_armor_init_func(void *ctx); + +typedef size_t nettle_armor_encode_update_func(void *ctx, + uint8_t *dst, + size_t src_length, + const uint8_t *src); + +typedef size_t nettle_armor_encode_final_func(void *ctx, uint8_t *dst); + +typedef int nettle_armor_decode_update_func(void *ctx, + size_t *dst_length, + uint8_t *dst, + size_t src_length, + const uint8_t *src); + +typedef int nettle_armor_decode_final_func(void *ctx); + +#ifdef __cplusplus +} +#endif + +#endif /* NETTLE_TYPES_H */ diff --git a/src/granger/src/nettle/nettle-write.h b/src/granger/src/nettle/nettle-write.h new file mode 100644 index 0000000..54152bd --- /dev/null +++ b/src/granger/src/nettle/nettle-write.h @@ -0,0 +1,58 @@ +/* nettle-write.h + + Internal functions to write out word-sized data to byte arrays. + + Copyright (C) 2010 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#ifndef NETTLE_WRITE_H_INCLUDED +#define NETTLE_WRITE_H_INCLUDED + +/* For size_t */ +#include + +#include "nettle-stdint.h" + +/* Write the word array at SRC to the byte array at DST, using little + endian (le) or big endian (be) byte order, and truncating the + result to LENGTH bytes. */ + +/* FIXME: Use a macro shortcut to memcpy for native endianness. */ +void +_nettle_write_be32(size_t length, uint8_t *dst, + uint32_t *src); +void +_nettle_write_le32(size_t length, uint8_t *dst, + uint32_t *src); + +void +_nettle_write_le64(size_t length, uint8_t *dst, + uint64_t *src); + +#endif /* NETTLE_WRITE_H_INCLUDED */ diff --git a/src/granger/src/nettle/sha2.h b/src/granger/src/nettle/sha2.h new file mode 100644 index 0000000..d0426d7 --- /dev/null +++ b/src/granger/src/nettle/sha2.h @@ -0,0 +1,206 @@ +/* sha2.h + + The sha2 family of hash functions. + + Copyright (C) 2001, 2012 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#ifndef NETTLE_SHA2_H_INCLUDED +#define NETTLE_SHA2_H_INCLUDED + +#include "nettle-types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Name mangling */ +#define sha224_init nettle_sha224_init +#define sha224_digest nettle_sha224_digest +#define sha256_init nettle_sha256_init +#define sha256_update nettle_sha256_update +#define sha256_digest nettle_sha256_digest +#define sha384_init nettle_sha384_init +#define sha384_digest nettle_sha384_digest +#define sha512_init nettle_sha512_init +#define sha512_update nettle_sha512_update +#define sha512_digest nettle_sha512_digest +#define sha512_224_init nettle_sha512_224_init +#define sha512_224_digest nettle_sha512_224_digest +#define sha512_256_init nettle_sha512_256_init +#define sha512_256_digest nettle_sha512_256_digest + +/* For backwards compatibility */ +#define SHA224_DATA_SIZE SHA256_BLOCK_SIZE +#define SHA256_DATA_SIZE SHA256_BLOCK_SIZE +#define SHA512_DATA_SIZE SHA512_BLOCK_SIZE +#define SHA384_DATA_SIZE SHA512_BLOCK_SIZE + +/* SHA256 */ + +#define SHA256_DIGEST_SIZE 32 +#define SHA256_BLOCK_SIZE 64 + +/* Digest is kept internally as 8 32-bit words. */ +#define _SHA256_DIGEST_LENGTH 8 + +struct sha256_ctx +{ + uint32_t state[_SHA256_DIGEST_LENGTH]; /* State variables */ + uint64_t count; /* 64-bit block count */ + uint8_t block[SHA256_BLOCK_SIZE]; /* SHA256 data buffer */ + unsigned int index; /* index into buffer */ +}; + +void +sha256_init(struct sha256_ctx *ctx); + +void +sha256_update(struct sha256_ctx *ctx, + size_t length, + const uint8_t *data); + +void +sha256_digest(struct sha256_ctx *ctx, + size_t length, + uint8_t *digest); + +/* Internal compression function. STATE points to 8 uint32_t words, + DATA points to 64 bytes of input data, possibly unaligned, and K + points to the table of constants. */ +void +_nettle_sha256_compress(uint32_t *state, const uint8_t *data, const uint32_t *k); + + +/* SHA224, a truncated SHA256 with different initial state. */ + +#define SHA224_DIGEST_SIZE 28 +#define SHA224_BLOCK_SIZE SHA256_BLOCK_SIZE +#define sha224_ctx sha256_ctx + +void +sha224_init(struct sha256_ctx *ctx); + +#define sha224_update nettle_sha256_update + +void +sha224_digest(struct sha256_ctx *ctx, + size_t length, + uint8_t *digest); + + +/* SHA512 */ + +#define SHA512_DIGEST_SIZE 64 +#define SHA512_BLOCK_SIZE 128 + +/* Digest is kept internally as 8 64-bit words. */ +#define _SHA512_DIGEST_LENGTH 8 + +struct sha512_ctx +{ + uint64_t state[_SHA512_DIGEST_LENGTH]; /* State variables */ + uint64_t count_low, count_high; /* 128-bit block count */ + uint8_t block[SHA512_BLOCK_SIZE]; /* SHA512 data buffer */ + unsigned int index; /* index into buffer */ +}; + +void +sha512_init(struct sha512_ctx *ctx); + +void +sha512_update(struct sha512_ctx *ctx, + size_t length, + const uint8_t *data); + +void +sha512_digest(struct sha512_ctx *ctx, + size_t length, + uint8_t *digest); + +/* Internal compression function. STATE points to 8 uint64_t words, + DATA points to 128 bytes of input data, possibly unaligned, and K + points to the table of constants. */ +void +_nettle_sha512_compress(uint64_t *state, const uint8_t *data, const uint64_t *k); + + +/* SHA384, a truncated SHA512 with different initial state. */ + +#define SHA384_DIGEST_SIZE 48 +#define SHA384_BLOCK_SIZE SHA512_BLOCK_SIZE +#define sha384_ctx sha512_ctx + +void +sha384_init(struct sha512_ctx *ctx); + +#define sha384_update nettle_sha512_update + +void +sha384_digest(struct sha512_ctx *ctx, + size_t length, + uint8_t *digest); + + +/* SHA512_224 and SHA512_256, two truncated versions of SHA512 + with different initial states. */ + +#define SHA512_224_DIGEST_SIZE 28 +#define SHA512_224_BLOCK_SIZE SHA512_BLOCK_SIZE +#define sha512_224_ctx sha512_ctx + +void +sha512_224_init(struct sha512_224_ctx *ctx); + +#define sha512_224_update nettle_sha512_update + +void +sha512_224_digest(struct sha512_224_ctx *ctx, + size_t length, + uint8_t *digest); + +#define SHA512_256_DIGEST_SIZE 32 +#define SHA512_256_BLOCK_SIZE SHA512_BLOCK_SIZE +#define sha512_256_ctx sha512_ctx + +void +sha512_256_init(struct sha512_256_ctx *ctx); + +#define sha512_256_update nettle_sha512_update + +void +sha512_256_digest(struct sha512_256_ctx *ctx, + size_t length, + uint8_t *digest); + +#ifdef __cplusplus +} +#endif + +#endif /* NETTLE_SHA2_H_INCLUDED */ diff --git a/src/granger/src/nettle/sha256-compress.c b/src/granger/src/nettle/sha256-compress.c new file mode 100644 index 0000000..8b82d70 --- /dev/null +++ b/src/granger/src/nettle/sha256-compress.c @@ -0,0 +1,199 @@ +/* sha256-compress.c + + The compression function of the sha256 hash function. + + Copyright (C) 2001, 2010 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#ifndef SHA256_DEBUG +# define SHA256_DEBUG 0 +#endif + +#if SHA256_DEBUG +# include +# define DEBUG(i) \ + fprintf(stderr, "%2d: %8x %8x %8x %8x %8x %8x %8x %8x\n", \ + i, A, B, C, D ,E, F, G, H) +#else +# define DEBUG(i) +#endif + +#include +#include +#include + +#include "sha2.h" + +#include "macros.h" + +/* A block, treated as a sequence of 32-bit words. */ +#define SHA256_DATA_LENGTH 16 + +/* The SHA256 functions. The Choice function is the same as the SHA1 + function f1, and the majority function is the same as the SHA1 f3 + function. They can be optimized to save one boolean operation each + - thanks to Rich Schroeppel, rcs@cs.arizona.edu for discovering + this */ + +/* #define Choice(x,y,z) ( ( (x) & (y) ) | ( ~(x) & (z) ) ) */ +#define Choice(x,y,z) ( (z) ^ ( (x) & ( (y) ^ (z) ) ) ) +/* #define Majority(x,y,z) ( ((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)) ) */ +#define Majority(x,y,z) ( ((x) & (y)) ^ ((z) & ((x) ^ (y))) ) + +#define S0(x) (ROTL32(30,(x)) ^ ROTL32(19,(x)) ^ ROTL32(10,(x))) +#define S1(x) (ROTL32(26,(x)) ^ ROTL32(21,(x)) ^ ROTL32(7,(x))) + +#define s0(x) (ROTL32(25,(x)) ^ ROTL32(14,(x)) ^ ((x) >> 3)) +#define s1(x) (ROTL32(15,(x)) ^ ROTL32(13,(x)) ^ ((x) >> 10)) + +/* The initial expanding function. The hash function is defined over an + 64-word expanded input array W, where the first 16 are copies of the input + data, and the remaining 64 are defined by + + W[ t ] = s1(W[t-2]) + W[t-7] + s0(W[i-15]) + W[i-16] + + This implementation generates these values on the fly in a circular + buffer - thanks to Colin Plumb, colin@nyx10.cs.du.edu for this + optimization. +*/ + +#define EXPAND(W,i) \ +( W[(i) & 15 ] += (s1(W[((i)-2) & 15]) + W[((i)-7) & 15] + s0(W[((i)-15) & 15])) ) + +/* The prototype SHA sub-round. The fundamental sub-round is: + + T1 = h + S1(e) + Choice(e,f,g) + K[t] + W[t] + T2 = S0(a) + Majority(a,b,c) + a' = T1+T2 + b' = a + c' = b + d' = c + e' = d + T1 + f' = e + g' = f + h' = g + + but this is implemented by unrolling the loop 8 times and renaming + the variables + ( h, a, b, c, d, e, f, g ) = ( a, b, c, d, e, f, g, h ) each + iteration. */ + +/* It's crucial that DATA is only used once, as that argument will + * have side effects. */ +#define ROUND(a,b,c,d,e,f,g,h,k,data) do { \ + h += S1(e) + Choice(e,f,g) + k + data; \ + d += h; \ + h += S0(a) + Majority(a,b,c); \ + } while (0) + +/* For fat builds */ +#if HAVE_NATIVE_sha256_compress +void +_nettle_sha256_compress_c(uint32_t *state, const uint8_t *input, const uint32_t *k); +#define _nettle_sha256_compress _nettle_sha256_compress_c +#endif + +void +_nettle_sha256_compress(uint32_t *state, const uint8_t *input, const uint32_t *k) +{ + uint32_t data[SHA256_DATA_LENGTH]; + uint32_t A, B, C, D, E, F, G, H; /* Local vars */ + unsigned i; + uint32_t *d; + + for (i = 0; i < SHA256_DATA_LENGTH; i++, input+= 4) + { + data[i] = READ_UINT32(input); + } + + /* Set up first buffer and local data buffer */ + A = state[0]; + B = state[1]; + C = state[2]; + D = state[3]; + E = state[4]; + F = state[5]; + G = state[6]; + H = state[7]; + + /* Heavy mangling */ + /* First 16 subrounds that act on the original data */ + + DEBUG(-1); + for (i = 0, d = data; i<16; i+=8, k += 8, d+= 8) + { + ROUND(A, B, C, D, E, F, G, H, k[0], d[0]); DEBUG(i); + ROUND(H, A, B, C, D, E, F, G, k[1], d[1]); DEBUG(i+1); + ROUND(G, H, A, B, C, D, E, F, k[2], d[2]); + ROUND(F, G, H, A, B, C, D, E, k[3], d[3]); + ROUND(E, F, G, H, A, B, C, D, k[4], d[4]); + ROUND(D, E, F, G, H, A, B, C, k[5], d[5]); + ROUND(C, D, E, F, G, H, A, B, k[6], d[6]); DEBUG(i+6); + ROUND(B, C, D, E, F, G, H, A, k[7], d[7]); DEBUG(i+7); + } + + for (; i<64; i += 16, k+= 16) + { + ROUND(A, B, C, D, E, F, G, H, k[ 0], EXPAND(data, 0)); DEBUG(i); + ROUND(H, A, B, C, D, E, F, G, k[ 1], EXPAND(data, 1)); DEBUG(i+1); + ROUND(G, H, A, B, C, D, E, F, k[ 2], EXPAND(data, 2)); DEBUG(i+2); + ROUND(F, G, H, A, B, C, D, E, k[ 3], EXPAND(data, 3)); DEBUG(i+3); + ROUND(E, F, G, H, A, B, C, D, k[ 4], EXPAND(data, 4)); DEBUG(i+4); + ROUND(D, E, F, G, H, A, B, C, k[ 5], EXPAND(data, 5)); DEBUG(i+5); + ROUND(C, D, E, F, G, H, A, B, k[ 6], EXPAND(data, 6)); DEBUG(i+6); + ROUND(B, C, D, E, F, G, H, A, k[ 7], EXPAND(data, 7)); DEBUG(i+7); + ROUND(A, B, C, D, E, F, G, H, k[ 8], EXPAND(data, 8)); DEBUG(i+8); + ROUND(H, A, B, C, D, E, F, G, k[ 9], EXPAND(data, 9)); DEBUG(i+9); + ROUND(G, H, A, B, C, D, E, F, k[10], EXPAND(data, 10)); DEBUG(i+10); + ROUND(F, G, H, A, B, C, D, E, k[11], EXPAND(data, 11)); DEBUG(i+11); + ROUND(E, F, G, H, A, B, C, D, k[12], EXPAND(data, 12)); DEBUG(i+12); + ROUND(D, E, F, G, H, A, B, C, k[13], EXPAND(data, 13)); DEBUG(i+13); + ROUND(C, D, E, F, G, H, A, B, k[14], EXPAND(data, 14)); DEBUG(i+14); + ROUND(B, C, D, E, F, G, H, A, k[15], EXPAND(data, 15)); DEBUG(i+15); + } + + /* Update state */ + state[0] += A; + state[1] += B; + state[2] += C; + state[3] += D; + state[4] += E; + state[5] += F; + state[6] += G; + state[7] += H; +#if SHA256_DEBUG + fprintf(stderr, "99: %8x %8x %8x %8x %8x %8x %8x %8x\n", + state[0], state[1], state[2], state[3], + state[4], state[5], state[6], state[7]); +#endif +} diff --git a/src/granger/src/nettle/sha256.c b/src/granger/src/nettle/sha256.c new file mode 100644 index 0000000..0cb3559 --- /dev/null +++ b/src/granger/src/nettle/sha256.c @@ -0,0 +1,162 @@ +/* sha256.c + + The sha256 hash function. + See http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf + + Copyright (C) 2001 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +/* Modelled after the sha1.c code by Peter Gutmann. */ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include + +#include "sha2.h" + +#include "macros.h" +#include "nettle-write.h" + +/* Generated by the shadata program. */ +static const uint32_t +K[64] = +{ + 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, + 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, + 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, + 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, + 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, + 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, + 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, + 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, + 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, + 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, + 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, + 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, + 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, + 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, + 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, + 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL, +}; + +#define COMPRESS(ctx, data) (_nettle_sha256_compress((ctx)->state, (data), K)) + +/* Initialize the SHA values */ + +void +sha256_init(struct sha256_ctx *ctx) +{ + /* Initial values, also generated by the shadata program. */ + static const uint32_t H0[_SHA256_DIGEST_LENGTH] = + { + 0x6a09e667UL, 0xbb67ae85UL, 0x3c6ef372UL, 0xa54ff53aUL, + 0x510e527fUL, 0x9b05688cUL, 0x1f83d9abUL, 0x5be0cd19UL, + }; + + memcpy(ctx->state, H0, sizeof(H0)); + + /* Initialize bit count */ + ctx->count = 0; + + /* Initialize buffer */ + ctx->index = 0; +} + +void +sha256_update(struct sha256_ctx *ctx, + size_t length, const uint8_t *data) +{ + MD_UPDATE (ctx, length, data, COMPRESS, ctx->count++); +} + +static void +sha256_write_digest(struct sha256_ctx *ctx, + size_t length, + uint8_t *digest) +{ + uint64_t bit_count; + + assert(length <= SHA256_DIGEST_SIZE); + + MD_PAD(ctx, 8, COMPRESS); + + /* There are 512 = 2^9 bits in one block */ + bit_count = (ctx->count << 9) | (ctx->index << 3); + + /* This is slightly inefficient, as the numbers are converted to + big-endian format, and will be converted back by the compression + function. It's probably not worth the effort to fix this. */ + WRITE_UINT64(ctx->block + (SHA256_BLOCK_SIZE - 8), bit_count); + COMPRESS(ctx, ctx->block); + + _nettle_write_be32(length, digest, ctx->state); +} + +void +sha256_digest(struct sha256_ctx *ctx, + size_t length, + uint8_t *digest) +{ + sha256_write_digest(ctx, length, digest); + sha256_init(ctx); +} + +/* sha224 variant. */ + +void +sha224_init(struct sha256_ctx *ctx) +{ + /* Initial values. Low 32 bits of the initial values for sha384. */ + static const uint32_t H0[_SHA256_DIGEST_LENGTH] = + { + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4, + }; + + memcpy(ctx->state, H0, sizeof(H0)); + + /* Initialize bit count */ + ctx->count = 0; + + /* Initialize buffer */ + ctx->index = 0; +} + +void +sha224_digest(struct sha256_ctx *ctx, + size_t length, + uint8_t *digest) +{ + sha256_write_digest(ctx, length, digest); + sha224_init(ctx); +} diff --git a/src/granger/src/nettle/version.h b/src/granger/src/nettle/version.h new file mode 100644 index 0000000..3a1d20c --- /dev/null +++ b/src/granger/src/nettle/version.h @@ -0,0 +1,58 @@ +/* version.h + + Information about library version. + + Copyright (C) 2015 Red Hat, Inc. + Copyright (C) 2015 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#ifndef NETTLE_VERSION_H_INCLUDED +#define NETTLE_VERSION_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +/* Individual version numbers in decimal */ +#define NETTLE_VERSION_MAJOR 3 +#define NETTLE_VERSION_MINOR 3 + +#define NETTLE_USE_MINI_GMP 1 + +/* We need a preprocessor constant for GMP_NUMB_BITS, simply using + sizeof(mp_limb_t) * CHAR_BIT is not good enough. */ +#if NETTLE_USE_MINI_GMP +# define GMP_NUMB_BITS (sizeof(unsigned long) * 8) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* NETTLE_VERSION_H_INCLUDED */ diff --git a/src/granger/src/nettle/write-be32.c b/src/granger/src/nettle/write-be32.c new file mode 100644 index 0000000..7d68905 --- /dev/null +++ b/src/granger/src/nettle/write-be32.c @@ -0,0 +1,77 @@ +/* write-be32.c + + Copyright (C) 2001 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include "nettle-write.h" + +#include "macros.h" + +void +_nettle_write_be32(size_t length, uint8_t *dst, + uint32_t *src) +{ + size_t i; + size_t words; + unsigned leftover; + + words = length / 4; + leftover = length % 4; + + for (i = 0; i < words; i++, dst += 4) + WRITE_UINT32(dst, src[i]); + + if (leftover) + { + uint32_t word; + unsigned j = leftover; + + word = src[i]; + + switch (leftover) + { + default: + abort(); + case 3: + dst[--j] = (word >> 8) & 0xff; + /* Fall through */ + case 2: + dst[--j] = (word >> 16) & 0xff; + /* Fall through */ + case 1: + dst[--j] = (word >> 24) & 0xff; + } + } +} diff --git a/src/granger/src/nettle/write-le32.c b/src/granger/src/nettle/write-le32.c new file mode 100644 index 0000000..d44eb24 --- /dev/null +++ b/src/granger/src/nettle/write-le32.c @@ -0,0 +1,69 @@ +/* write-le32.c + + Copyright (C) 2001, 2011 Niels Möller + + This file is part of GNU Nettle. + + GNU Nettle is free software: you can redistribute it and/or + modify it under the terms of either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + + or + + * 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. + + or both in parallel, as here. + + GNU Nettle 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 copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see http://www.gnu.org/licenses/. +*/ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include "nettle-write.h" + +#include "macros.h" + +void +_nettle_write_le32(size_t length, uint8_t *dst, + uint32_t *src) +{ + size_t i; + size_t words; + unsigned leftover; + + words = length / 4; + leftover = length % 4; + + for (i = 0; i < words; i++, dst += 4) + LE_WRITE_UINT32(dst, src[i]); + + if (leftover) + { + uint32_t word; + + word = src[i]; + + do + { + *dst++ = word & 0xff; + word >>= 8; + } + while (--leftover); + } +} diff --git a/src/granger/src/premake/CMakeLists.txt b/src/granger/src/premake/CMakeLists.txt new file mode 100644 index 0000000..455a9e2 --- /dev/null +++ b/src/granger/src/premake/CMakeLists.txt @@ -0,0 +1,32 @@ +if(NOT WIN32) + add_definitions(-Wall -Wextra) +endif(NOT WIN32) + +if(WIN32) + add_definitions(-D_CRT_SECURE_NO_WARNINGS) +endif(WIN32) + +add_library(premake + os_access.c + os_chdir.c + os_copyfile.c + os_elevate.c + os_getcwd.c + os_is64bit.c + os_isdir.c + os_isfile.c + os_match.c + os_mkdir.c + os_pathsearch.c + os_rmdir.c + os_stat.c + path_getabsolute.c + path_getrelative.c + path_isabsolute.c + path_join.c + path_normalize.c + path_translate.c + premake.c + premake.h + string_endswith.c + ) diff --git a/src/granger/src/premake/os_access.c b/src/granger/src/premake/os_access.c new file mode 100644 index 0000000..90ceb46 --- /dev/null +++ b/src/granger/src/premake/os_access.c @@ -0,0 +1,58 @@ +/* + * This file is part of Granger. + * Copyright (c) 2016 Jeff Kent + * + * Granger 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. + * + * Granger 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 Granger. If not, see . + */ + +#include "premake.h" + +#if defined(PLATFORM_WINDOWS) +#include +#define access _access +#define X_OK 1 +#define W_OK 2 +#define R_OK 4 +#endif + +int os_access(lua_State *L) +{ + const char *filename = luaL_checkstring(L, 1); + const char *mode = luaL_optstring(L, 2, "r"); + int nmode = 0; + int result; + + while (*mode) { + switch (*mode) { + case 'x': + nmode |= X_OK; + break; + case 'w': + nmode |= W_OK; + break; + case 'r': + nmode |= R_OK; + break; + default: + lua_pushboolean(L, 0); + return 1; + } + mode++; + } + + result = access(filename, nmode); + + lua_pushboolean(L, result == 0); + return 1; +} diff --git a/src/granger/src/premake/os_chdir.c b/src/granger/src/premake/os_chdir.c new file mode 100644 index 0000000..3acce68 --- /dev/null +++ b/src/granger/src/premake/os_chdir.c @@ -0,0 +1,32 @@ +/** + * \file os_chdir.c + * \brief Change the current working directory. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + */ + +#include "premake.h" + + +int os_chdir(lua_State* L) +{ + int z; + const char* path = luaL_checkstring(L, 1); + +#if PLATFORM_WINDOWS + z = SetCurrentDirectory(path); +#else + z = !chdir(path); +#endif + + if (!z) + { + lua_pushnil(L); + lua_pushfstring(L, "unable to switch to directory '%s'", path); + return 2; + } + else + { + lua_pushboolean(L, 1); + return 1; + } +} diff --git a/src/granger/src/premake/os_copyfile.c b/src/granger/src/premake/os_copyfile.c new file mode 100644 index 0000000..b15d600 --- /dev/null +++ b/src/granger/src/premake/os_copyfile.c @@ -0,0 +1,34 @@ +/** + * \file os_copyfile.c + * \brief Copy a file from one location to another. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + */ + +#include +#include "premake.h" + +int os_copyfile(lua_State* L) +{ + int z; + const char* src = luaL_checkstring(L, 1); + const char* dst = luaL_checkstring(L, 2); + +#if PLATFORM_WINDOWS + z = CopyFile(src, dst, FALSE); +#else + lua_pushfstring(L, "cp %s %s", src, dst); + z = (system(lua_tostring(L, -1)) == 0); +#endif + + if (!z) + { + lua_pushnil(L); + lua_pushfstring(L, "unable to copy file to '%s'", dst); + return 2; + } + else + { + lua_pushboolean(L, 1); + return 1; + } +} diff --git a/src/granger/src/premake/os_elevate.c b/src/granger/src/premake/os_elevate.c new file mode 100644 index 0000000..cab0906 --- /dev/null +++ b/src/granger/src/premake/os_elevate.c @@ -0,0 +1,240 @@ +/* + * This file is part of Granger. + * Copyright (c) 2016 Jeff Kent + * + * Granger 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. + * + * Granger 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 Granger. If not, see . + */ + +#include +#include +#include +#include "premake.h" +#include "../strvec.h" + +#if defined(PLATFORM_WINDOWS) +#include +static int do_elevate(lua_State *L) +{ + BOOL is_elevated = FALSE; + HANDLE hToken = NULL; + + if (OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&hToken)) { + TOKEN_ELEVATION Elevation; + DWORD cbSize = sizeof(TOKEN_ELEVATION); + if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) { + is_elevated = Elevation.TokenIsElevated; + } + } + if (hToken) { + CloseHandle(hToken); + } + if (is_elevated) { + return 1; + } + + char szPath[MAX_PATH]; + if (!GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath))) { + return 0; + } + + void *sv = StringVector_New(); + + lua_getglobal(L, "_GRANGER_SCRIPT"); + StringVector_Add(sv, luaL_checkstring(L, 1)); + lua_pop(L, 1); + + lua_getglobal(L, "argv"); + if (luaL_len(L, 1) > 0) { + StringVector_Add(sv, "--"); + } + + for (int i = 1; ; i++) { + lua_pushinteger(L, i); + lua_gettable(L, 1); + if (lua_isnil(L, -1)) { + break; + } + StringVector_Add(sv, luaL_checkstring(L, -1)); + lua_pop(L, 1); + } + lua_pop(L, 1); + + SHELLEXECUTEINFO sei = { 0 }; + sei.cbSize = sizeof(SHELLEXECUTEINFO); + sei.lpVerb = "runas"; + sei.lpFile = szPath; + sei.lpParameters = StringVector_toString(sv); + sei.nShow = SW_NORMAL; + + StringVector_Delete(sv); + + if (ShellExecuteEx(&sei)) { + free((void*)sei.lpParameters); + exit(0); + } + + free((void*)sei.lpParameters); + return 0; +} +#endif + +#if defined(PLATFORM_MACOSX) +#include +#include + +static int do_elevate(lua_State *L) +{ + const char *execpath; + int argc = 0; + char **argv; + + if (geteuid() == 0) { + return 1; + } + + lua_getglobal(L, "_EXE_PATH"); + execpath = luaL_checkstring(L, 1); + + OSStatus err; + AuthorizationRef ref; + AuthorizationFlags flags; + + flags = kAuthorizationFlagDefaults; + err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, flags, &ref); + + if (err != errAuthorizationSuccess) { + return 0; + } + + AuthorizationItem _temp = {kAuthorizationRightExecute, 0, NULL, 0}; + AuthorizationRights rights = {1, &_temp}; + + flags = kAuthorizationFlagDefaults | + kAuthorizationFlagInteractionAllowed | + kAuthorizationFlagPreAuthorize | + kAuthorizationFlagExtendRights; + + err = AuthorizationCopyRights(ref, &rights, NULL, flags, NULL); + if (err != errAuthorizationSuccess) { + AuthorizationFree(ref, kAuthorizationFlagDefaults); + return 0; + } + + void *sv = StringVector_New(); + + lua_getglobal(L, "_GRANGER_SCRIPT"); + StringVector_Add(sv, luaL_checkstring(L, 1)); + lua_pop(L, 1); + + lua_getglobal(L, "argv"); + if (luaL_len(L, 1) > 0) { + StringVector_Add(sv, "--"); + } + + for (int i = 1; ; i++) { + lua_pushinteger(L, i); + lua_gettable(L, 1); + if (lua_isnil(L, -1)) { + break; + } + StringVector_Add(sv, luaL_checkstring(L, -1)); + lua_pop(L, 1); + } + lua_pop(L, 1); + + flags = kAuthorizationFlagDefaults; + err = AuthorizationExecuteWithPrivileges(ref, execpath, flags, StringVector_GetVector(sv), NULL); + AuthorizationFree(ref, kAuthorizationFlagDefaults); + if (err != errAuthorizationSuccess) { + StringVector_Delete(sv); + return 0; + } + + StringVector_Delete(sv); + exit(0); +} +#endif + +#if defined(PLATFORM_LINUX) || defined(PLATFORM_BSD) +static int do_elevate(lua_State *L) +{ + char *pkexec, *display; + char cwd[PATH_MAX + 1]; + + if (geteuid() == 0) { + return 1; + } + + display = getenv("DISPLAY"); + if (!display) { + return 0; + } + + if (access("/usr/bin/pkexec", X_OK) != -1) { + pkexec = "/usr/bin/pkexec"; + } else if (access("/usr/local/bin/pkexec", X_OK) != -1) { + pkexec = "/usr/local/bin/pkexec"; + } else { + return 0; + } + + if (!getcwd(cwd, sizeof(cwd))) { + return 0; + } + + void *sv = StringVector_New(); + StringVector_Add(sv, "pkexec"); + StringVector_Add(sv, "--user"); + StringVector_Add(sv, "root"); + + lua_getglobal(L, "_EXE_PATH"); + StringVector_Add(sv, luaL_checkstring(L, 1)); + lua_pop(L, 1); + + StringVector_Add(sv, "-C"); + StringVector_Add(sv, cwd); + + lua_getglobal(L, "_GRANGER_SCRIPT"); + StringVector_Add(sv, luaL_checkstring(L, 1)); + lua_pop(L, 1); + + lua_getglobal(L, "argv"); + if (luaL_len(L, 1) > 0) { + StringVector_Add(sv, "--"); + } + + for (int i = 1; ; i++) { + lua_pushinteger(L, i); + lua_gettable(L, 1); + if (lua_isnil(L, -1)) { + break; + } + StringVector_Add(sv, luaL_checkstring(L, -1)); + lua_pop(L, 1); + } + lua_pop(L, 1); + + execv(pkexec, (char * const*)StringVector_GetVector(sv)); + + fprintf(stderr, "execv failed\n"); + lua_pop(L, 1); + return 0; +} +#endif + +int os_elevate(lua_State* L) +{ + lua_pushboolean(L, do_elevate(L)); + return 1; +} diff --git a/src/granger/src/premake/os_getcwd.c b/src/granger/src/premake/os_getcwd.c new file mode 100644 index 0000000..de8bfbd --- /dev/null +++ b/src/granger/src/premake/os_getcwd.c @@ -0,0 +1,36 @@ +/** + * \file os_getcwd.c + * \brief Retrieve the current working directory. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + */ + +#include "premake.h" + +int os_getcwd(lua_State* L) +{ + char buffer[0x4000]; + if (do_getcwd(buffer, 0x4000)) { + lua_pushstring(L, buffer); + return 1; + } + else { + return 0; + } +} + + +int do_getcwd(char* buffer, size_t size) +{ + int result; + +#if PLATFORM_WINDOWS + result = (GetCurrentDirectory(size, buffer) != 0); + if (result) { + do_translate(buffer, '/'); + } +#else + result = (getcwd(buffer, size) != 0); +#endif + + return result; +} diff --git a/src/granger/src/premake/os_is64bit.c b/src/granger/src/premake/os_is64bit.c new file mode 100644 index 0000000..3134751 --- /dev/null +++ b/src/granger/src/premake/os_is64bit.c @@ -0,0 +1,30 @@ +/** + * \file os_is64bit.c + * \brief Native code-side checking for a 64-bit architecture. + * \author Copyright (c) 2011 Jason Perkins and the Premake project + */ + +#include "premake.h" + +int os_is64bit(lua_State* L) +{ + // If this code returns true, then the platform is 64-bit. If it + // returns false, the platform might still be 64-bit, but more + // checking will need to be done on the Lua side of things. +#if PLATFORM_WINDOWS + typedef BOOL (WINAPI* WowFuncSig)(HANDLE, PBOOL); + WowFuncSig func = (WowFuncSig)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); + if (func) + { + BOOL isWow = FALSE; + if (func(GetCurrentProcess(), &isWow)) + { + lua_pushboolean(L, isWow); + return 1; + } + } +#endif + + lua_pushboolean(L, 0); + return 1; +} diff --git a/src/granger/src/premake/os_isdir.c b/src/granger/src/premake/os_isdir.c new file mode 100644 index 0000000..fb5e8bb --- /dev/null +++ b/src/granger/src/premake/os_isdir.c @@ -0,0 +1,34 @@ +/** + * \file os_isdir.c + * \brief Returns true if the specified directory exists. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + */ + +#include +#include +#include "premake.h" + + +int os_isdir(lua_State* L) +{ + struct stat buf; + const char* path = luaL_checkstring(L, 1); + + /* empty path is equivalent to ".", must be true */ + if (strlen(path) == 0) + { + lua_pushboolean(L, 1); + } + else if (stat(path, &buf) == 0) + { + lua_pushboolean(L, buf.st_mode & S_IFDIR); + } + else + { + lua_pushboolean(L, 0); + } + + return 1; +} + + diff --git a/src/granger/src/premake/os_isfile.c b/src/granger/src/premake/os_isfile.c new file mode 100644 index 0000000..61e0def --- /dev/null +++ b/src/granger/src/premake/os_isfile.c @@ -0,0 +1,30 @@ +/** + * \file os_isfile.c + * \brief Returns true if the given file exists on the file system. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + */ + +#include +#include "premake.h" + + +int os_isfile(lua_State* L) +{ + const char* filename = luaL_checkstring(L, 1); + lua_pushboolean(L, do_isfile(filename)); + return 1; +} + + +int do_isfile(const char* filename) +{ + struct stat buf; + if (stat(filename, &buf) == 0) + { + return ((buf.st_mode & S_IFDIR) == 0); + } + else + { + return 0; + } +} diff --git a/src/granger/src/premake/os_match.c b/src/granger/src/premake/os_match.c new file mode 100644 index 0000000..5ccc04d --- /dev/null +++ b/src/granger/src/premake/os_match.c @@ -0,0 +1,181 @@ +/** + * \file os_match.c + * \brief Match files and directories. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + */ + +#include +#include +#include "premake.h" + + +#if PLATFORM_WINDOWS + +#define WIN32_LEAN_AND_MEAN +#include + +typedef struct struct_MatchInfo +{ + HANDLE handle; + int is_first; + WIN32_FIND_DATA entry; +} MatchInfo; + +int os_matchstart(lua_State* L) +{ + const char* mask = luaL_checkstring(L, 1); + MatchInfo* m = (MatchInfo*)malloc(sizeof(MatchInfo)); + m->handle = FindFirstFile(mask, &m->entry); + m->is_first = 1; + lua_pushlightuserdata(L, m); + return 1; +} + +int os_matchdone(lua_State* L) +{ + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + if (m->handle != INVALID_HANDLE_VALUE) + FindClose(m->handle); + free(m); + return 0; +} + +int os_matchname(lua_State* L) +{ + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + lua_pushstring(L, m->entry.cFileName); + return 1; +} + +int os_matchisfile(lua_State* L) +{ + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + lua_pushboolean(L, (m->entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0); + return 1; +} + +int os_matchnext(lua_State* L) +{ + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + if (m->handle == INVALID_HANDLE_VALUE) { + return 0; + } + + while (m) /* loop forever */ + { + if (!m->is_first) + { + if (!FindNextFile(m->handle, &m->entry)) + return 0; + } + + m->is_first = 0; + lua_pushboolean(L, 1); + return 1; + } + + return 0; +} + +#else + +#include +#include +#include + +typedef struct struct_MatchInfo +{ + DIR* handle; + struct dirent* entry; + char* path; + char* mask; +} MatchInfo; + +int os_matchstart(lua_State* L) +{ + const char* split; + const char* mask = luaL_checkstring(L, 1); + MatchInfo* m = (MatchInfo*)malloc(sizeof(MatchInfo)); + + /* split the mask into path and filename components */ + split = strrchr(mask, '/'); + if (split) + { + m->path = (char*)malloc(split - mask + 1); + strncpy(m->path, mask, split - mask); + m->path[split - mask] = '\0'; + m->mask = (char*)malloc(mask + strlen(mask) - split); + strcpy(m->mask, split + 1); + } + else + { + m->path = (char*)malloc(2); + strcpy(m->path, "."); + m->mask = (char*)malloc(strlen(mask)+1); + strcpy(m->mask, mask); + } + + m->handle = opendir(m->path); + lua_pushlightuserdata(L, m); + return 1; +} + +int os_matchdone(lua_State* L) +{ + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + if (m->handle != NULL) + closedir(m->handle); + free(m->path); + free(m->mask); + free(m); + return 0; +} + +int os_matchname(lua_State* L) +{ + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + lua_pushstring(L, m->entry->d_name); + return 1; +} + +int os_matchisfile(lua_State* L) +{ + struct stat info; + const char* fname; + + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + lua_pushfstring(L, "%s/%s", m->path, m->entry->d_name); + fname = lua_tostring(L, -1); + lua_pop(L, 1); + + if (stat(fname, &info) == 0) + { + lua_pushboolean(L, S_ISREG(info.st_mode)); + return 1; + } + + return 0; +} + +int os_matchnext(lua_State* L) +{ + MatchInfo* m = (MatchInfo*)lua_touserdata(L, 1); + if (m->handle == NULL) + return 0; + + m->entry = readdir(m->handle); + while (m->entry != NULL) + { + const char* name = m->entry->d_name; + if (fnmatch(m->mask, name, 0) == 0) + { + lua_pushboolean(L, 1); + return 1; + } + m->entry = readdir(m->handle); + } + + return 0; +} + +#endif diff --git a/src/granger/src/premake/os_mkdir.c b/src/granger/src/premake/os_mkdir.c new file mode 100644 index 0000000..a7a69db --- /dev/null +++ b/src/granger/src/premake/os_mkdir.c @@ -0,0 +1,33 @@ +/** + * \file os_mkdir.c + * \brief Create a subdirectory. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + */ + +#include +#include "premake.h" + + +int os_mkdir(lua_State* L) +{ + int z; + const char* path = luaL_checkstring(L, 1); + +#if PLATFORM_WINDOWS + z = CreateDirectory(path, NULL); +#else + z = (mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0); +#endif + + if (!z) + { + lua_pushnil(L); + lua_pushfstring(L, "unable to create directory '%s'", path); + return 2; + } + else + { + lua_pushboolean(L, 1); + return 1; + } +} diff --git a/src/granger/src/premake/os_pathsearch.c b/src/granger/src/premake/os_pathsearch.c new file mode 100644 index 0000000..44f775d --- /dev/null +++ b/src/granger/src/premake/os_pathsearch.c @@ -0,0 +1,84 @@ +/** + * \file os_pathsearch.c + * \brief Locates a file, given a set of search paths. + * \author Copyright (c) 2002-2008 Jason Perkins and the Premake project + * + * \note This function is required by the bootstrapping code; it must be + * implemented here in the host and not scripted. + */ + +#include +#include "premake.h" + + +int os_pathsearch(lua_State* L) +{ + int i; + for (i = 2; i <= lua_gettop(L); ++i) + { + const char* path; + + if (lua_isnil(L, i)) + continue; + + path = luaL_checkstring(L, i); + do + { + const char* split; + + /* look for the closest path separator ; or : */ + /* can't use : on windows because it breaks on C:\path */ + const char* semi = strchr(path, ';'); +#if !defined(PLATFORM_WINDOWS) + const char* full = strchr(path, ':'); +#else + const char* full = NULL; +#endif + + if (!semi) + { + split = full; + } + else if (!full) + { + split = semi; + } + else + { + split = (semi < full) ? semi : full; + } + + /* push this piece of the full search string onto the stack */ + if (split) + { + lua_pushlstring(L, path, split - path); + } + else + { + lua_pushstring(L, path); + } + + /* keep an extra copy around, so I can return it if I have a match */ + lua_pushvalue(L, -1); + + /* append the filename to make the full test path */ + lua_pushstring(L, "/"); + lua_pushvalue(L, 1); + lua_concat(L, 3); + + /* test it - if it exists return the path */ + if (do_isfile(lua_tostring(L, -1))) + { + lua_pop(L, 1); + return 1; + } + + /* no match, set up the next try */ + lua_pop(L, 2); + path = (split) ? split + 1 : NULL; + } + while (path); + } + + return 0; +} diff --git a/src/granger/src/premake/os_rmdir.c b/src/granger/src/premake/os_rmdir.c new file mode 100644 index 0000000..f2ffeee --- /dev/null +++ b/src/granger/src/premake/os_rmdir.c @@ -0,0 +1,33 @@ +/** + * \file os_rmdir.c + * \brief Remove a subdirectory. + * \author Copyright (c) 2002-2013 Jason Perkins and the Premake project + */ + +#include +#include "premake.h" + + +int os_rmdir(lua_State* L) +{ + int z; + const char* path = luaL_checkstring(L, 1); + +#if PLATFORM_WINDOWS + z = RemoveDirectory(path); +#else + z = (0 == rmdir(path)); +#endif + + if (!z) + { + lua_pushnil(L); + lua_pushfstring(L, "unable to remove directory '%s'", path); + return 2; + } + else + { + lua_pushboolean(L, 1); + return 1; + } +} diff --git a/src/granger/src/premake/os_stat.c b/src/granger/src/premake/os_stat.c new file mode 100644 index 0000000..b3554dc --- /dev/null +++ b/src/granger/src/premake/os_stat.c @@ -0,0 +1,46 @@ +/** + * \file os_stat.c + * \brief Retrieve information about a file. + * \author Copyright (c) 2011 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include +#include + +int os_stat(lua_State* L) +{ + struct stat s; + + const char* filename = luaL_checkstring(L, 1); + if (stat(filename, &s) != 0) + { + lua_pushnil(L); + switch (errno) + { + case EACCES: + lua_pushfstring(L, "'%s' could not be accessed", filename); + break; + case ENOENT: + lua_pushfstring(L, "'%s' was not found", filename); + break; + default: + lua_pushfstring(L, "An unknown error %d occured while accessing '%s'", errno, filename); + break; + } + return 2; + } + + + lua_newtable(L); + + lua_pushstring(L, "mtime"); + lua_pushinteger(L, (lua_Integer)s.st_mtime); + lua_settable(L, -3); + + lua_pushstring(L, "size"); + lua_pushnumber(L, s.st_size); + lua_settable(L, -3); + + return 1; +} diff --git a/src/granger/src/premake/path_getabsolute.c b/src/granger/src/premake/path_getabsolute.c new file mode 100644 index 0000000..36b1c3a --- /dev/null +++ b/src/granger/src/premake/path_getabsolute.c @@ -0,0 +1,102 @@ +/** + * \file path_getabsolute.c + * \brief Returns an absolute version of a relative path. + * \author Copyright (c) 2002-2013 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include + + +void do_getabsolute(char* result, const char* value, const char* relative_to) +{ + int i; + char* ch; + char* prev; + char buffer[0x4000] = { '\0' }; + + /* if the path is not already absolute, base it on working dir */ + if (!do_isabsolute(value)) { + if (relative_to) { + strcpy(buffer, relative_to); + } + else { + do_getcwd(buffer, 0x4000); + } + strcat(buffer, "/"); + } + + /* normalize the path */ + strcat(buffer, value); + do_translate(buffer, '/'); + + /* process it part by part */ + result[0] = '\0'; + if (buffer[0] == '/') { + strcat(result, "/"); + } + + prev = NULL; + ch = strtok(buffer, "/"); + while (ch) { + /* remove ".." where I can */ + if (strcmp(ch, "..") == 0 && (prev == NULL || (prev[0] != '$' && strcmp(prev, "..") != 0))) { + i = strlen(result) - 2; + while (i >= 0 && result[i] != '/') { + --i; + } + if (i >= 0) { + result[i + 1] = '\0'; + } + ch = NULL; + } + + /* allow everything except "." */ + else if (strcmp(ch, ".") != 0) { + strcat(result, ch); + strcat(result, "/"); + } + + prev = ch; + ch = strtok(NULL, "/"); + } + + /* remove trailing slash */ + i = strlen(result) - 1; + if (result[i] == '/') { + result[i] = '\0'; + } +} + + +int path_getabsolute(lua_State* L) +{ + const char* relative_to; + char buffer[0x4000]; + + relative_to = NULL; + if (lua_gettop(L) > 1 && !lua_isnil(L,2)) { + relative_to = luaL_checkstring(L, 2); + } + + if (lua_istable(L, 1)) { + int i = 0; + lua_newtable(L); + lua_pushnil(L); + while (lua_next(L, 1)) { + const char* value = luaL_checkstring(L, -1); + do_getabsolute(buffer, value, relative_to); + lua_pop(L, 1); + + lua_pushstring(L, buffer); + lua_rawseti(L, -3, ++i); + } + return 1; + } + else { + const char* value = luaL_checkstring(L, 1); + do_getabsolute(buffer, value, relative_to); + lua_pushstring(L, buffer); + return 1; + } +} diff --git a/src/granger/src/premake/path_getrelative.c b/src/granger/src/premake/path_getrelative.c new file mode 100644 index 0000000..dc6629b --- /dev/null +++ b/src/granger/src/premake/path_getrelative.c @@ -0,0 +1,80 @@ +/** + * \file path_getrelative.c + * \brief Returns a path relative to another. + * \author Copyright (c) 2002-2013 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include + + +int path_getrelative(lua_State* L) +{ + int i, last, count; + char src[0x4000]; + char dst[0x4000]; + + const char* p1 = luaL_checkstring(L, 1); + const char* p2 = luaL_checkstring(L, 2); + + /* normalize the paths */ + do_getabsolute(src, p1, NULL); + do_getabsolute(dst, p2, NULL); + + /* same directory? */ + if (strcmp(src, dst) == 0) { + lua_pushstring(L, "."); + return 1; + } + + /* dollar macro? Can't tell what the real path might be, so treat + * as absolute. This enables paths like $(SDK_ROOT)/include to + * work as expected. */ + if (dst[0] == '$') { + lua_pushstring(L, dst); + return 1; + } + + /* find the common leading directories */ + strcat(src, "/"); + strcat(dst, "/"); + + last = -1; + i = 0; + while (src[i] && dst[i] && src[i] == dst[i]) { + if (src[i] == '/') { + last = i; + } + ++i; + } + + /* if I end up with just the root of the filesystem, either a single + * slash (/) or a drive letter (c:) then return the absolute path. */ + if (last <= 0 || (last == 2 && src[1] == ':')) { + dst[strlen(dst) - 1] = '\0'; + lua_pushstring(L, dst); + return 1; + } + + /* count remaining levels in src */ + count = 0; + for (i = last + 1; src[i] != '\0'; ++i) { + if (src[i] == '/') { + ++count; + } + } + + /* start my result by backing out that many levels */ + src[0] = '\0'; + for (i = 0; i < count; ++i) { + strcat(src, "../"); + } + + /* append what's left */ + strcat(src, dst + last + 1); + + /* remove trailing slash and done */ + src[strlen(src) - 1] = '\0'; + lua_pushstring(L, src); + return 1; +} diff --git a/src/granger/src/premake/path_isabsolute.c b/src/granger/src/premake/path_isabsolute.c new file mode 100644 index 0000000..7412935 --- /dev/null +++ b/src/granger/src/premake/path_isabsolute.c @@ -0,0 +1,27 @@ +/** + * \file path_isabsolute.c + * \brief Determines if a path is absolute or relative. + * \author Copyright (c) 2002-2013 Jason Perkins and the Premake project + */ + +#include "premake.h" + + +int path_isabsolute(lua_State* L) +{ + const char* path = luaL_checkstring(L, -1); + lua_pushboolean(L, do_isabsolute(path)); + return 1; +} + + +int do_isabsolute(const char* path) +{ + return ( + path[0] == '/' || + path[0] == '\\' || + path[0] == '$' || + (path[0] == '"' && path[1] == '$') || + (path[0] != '\0' && path[1] == ':') + ); +} diff --git a/src/granger/src/premake/path_join.c b/src/granger/src/premake/path_join.c new file mode 100644 index 0000000..7d80104 --- /dev/null +++ b/src/granger/src/premake/path_join.c @@ -0,0 +1,58 @@ +/** + * \file path_join.c + * \brief Join two or more pieces of a file system path. + * \author Copyright (c) 2002-2013 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include + + +int path_join(lua_State* L) +{ + int i, len; + const char* part; + char buffer[0x4000]; + char* ptr = buffer; + + /* for each argument... */ + int argc = lua_gettop(L); + for (i = 1; i <= argc; ++i) { + /* if next argument is nil, skip it */ + if (lua_isnil(L, i)) { + continue; + } + + /* grab the next argument */ + part = luaL_checkstring(L, i); + len = strlen(part); + + /* remove trailing slashes */ + while (len > 1 && part[len - 1] == '/') { + --len; + } + + /* ignore empty segments and "." */ + if (len == 0 || (len == 1 && part[0] == '.')) { + continue; + } + + /* if I encounter an absolute path, restart my result */ + if (do_isabsolute(part)) { + ptr = buffer; + } + + /* if the path is already started, split parts */ + if (ptr != buffer && *(ptr - 1) != '/') { + *(ptr++) = '/'; + } + + /* append new part */ + strcpy(ptr, part); + ptr += len; + } + + *ptr = '\0'; + lua_pushstring(L, buffer); + return 1; +} diff --git a/src/granger/src/premake/path_normalize.c b/src/granger/src/premake/path_normalize.c new file mode 100644 index 0000000..64c5cf2 --- /dev/null +++ b/src/granger/src/premake/path_normalize.c @@ -0,0 +1,77 @@ +/** + * \file path_normalize.c + * \brief Removes any weirdness from a file system path string. + * \author Copyright (c) 2013 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include + + +int path_normalize(lua_State* L) +{ + char buffer[0x4000]; + char* src; + char* dst; + char last; + + const char* path = luaL_checkstring(L, 1); + strcpy(buffer, path); + + src = buffer; + dst = buffer; + last = '\0'; + + while (*src != '\0') { + char ch = (*src); + + /* make sure we're using '/' for all separators */ + if (ch == '\\') { + ch = '/'; + } + + /* add to the result, filtering out duplicate slashes */ + if (ch != '/' || last != '/') { + *(dst++) = ch; + } + + /* ...except at the start of a string, for UNC paths */ + if (src != buffer) { + last = (*src); + } + + ++src; + } + + /* remove any trailing slashes */ + for (--src; src > buffer && *src == '/'; --src) { + *src = '\0'; + } + + /* remove any leading "./" sequences */ + src = buffer; + while (strncmp(src, "./", 2) == 0) { + src += 2; + } + + *dst = '\0'; + lua_pushstring(L, src); + return 1; +} + + +/* Call the scripted path.normalize(), to allow for overrides */ +void do_normalize(lua_State* L, char* buffer, const char* path) +{ + int top = lua_gettop(L); + + lua_getglobal(L, "path"); + lua_getfield(L, -1, "normalize"); + lua_pushstring(L, path); + lua_call(L, 1, 1); + + path = luaL_checkstring(L, -1); + strcpy(buffer, path); + + lua_settop(L, top); +} diff --git a/src/granger/src/premake/path_translate.c b/src/granger/src/premake/path_translate.c new file mode 100644 index 0000000..8996b37 --- /dev/null +++ b/src/granger/src/premake/path_translate.c @@ -0,0 +1,61 @@ +/** + * \file path_translate.c + * \brief Translates between path separators. + * \author Copyright (c) 2002-2013 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include + + +void do_translate(char* value, const char sep) +{ + char* ch; + for (ch = value; *ch != '\0'; ++ch) { + if (*ch == '/' || *ch == '\\') { + *ch = sep; + } + } +} + + +static void translate(char* result, const char* value, const char sep) +{ + strcpy(result, value); + do_translate(result, sep); +} + + +int path_translate(lua_State* L) +{ + const char* sep; + char buffer[0x4000]; + + if (lua_gettop(L) == 1) { + sep = "\\"; + } + else { + sep = luaL_checkstring(L, 2); + } + + if (lua_istable(L, 1)) { + int i = 0; + lua_newtable(L); + lua_pushnil(L); + while (lua_next(L, 1)) { + const char* value = luaL_checkstring(L, 4); + translate(buffer, value, sep[0]); + lua_pop(L, 1); + + lua_pushstring(L, buffer); + lua_rawseti(L, -3, ++i); + } + return 1; + } + else { + const char* value = luaL_checkstring(L, 1); + translate(buffer, value, sep[0]); + lua_pushstring(L, buffer); + return 1; + } +} diff --git a/src/granger/src/premake/premake.c b/src/granger/src/premake/premake.c new file mode 100644 index 0000000..19a6168 --- /dev/null +++ b/src/granger/src/premake/premake.c @@ -0,0 +1,171 @@ +/** + * \file premake.c + * \brief Program entry point. + * \author Copyright (c) 2002-2013 Jason Perkins and the Premake project + */ + +#include +#include +#include "premake.h" + +#if PLATFORM_MACOSX +#include +#endif + +int premake_locate(lua_State* L, const char* argv0); + +/* Built-in functions */ +static const luaL_Reg path_functions[] = { + { "getabsolute", path_getabsolute }, + { "getrelative", path_getrelative }, + { "isabsolute", path_isabsolute }, + { "join", path_join }, + { "normalize", path_normalize }, + { "translate", path_translate }, + { NULL, NULL } +}; + +static const luaL_Reg os_functions[] = { + { "access", os_access }, + { "chdir", os_chdir }, + { "copyfile", os_copyfile }, + { "elevate", os_elevate }, + { "getcwd", os_getcwd }, + { "_is64bit", os_is64bit }, + { "isdir", os_isdir }, + { "isfile", os_isfile }, + { "matchdone", os_matchdone }, + { "matchisfile", os_matchisfile }, + { "matchname", os_matchname }, + { "matchnext", os_matchnext }, + { "matchstart", os_matchstart }, + { "mkdir", os_mkdir }, + { "pathsearch", os_pathsearch }, + { "rmdir", os_rmdir }, + { "stat", os_stat }, + { NULL, NULL } +}; + +static const luaL_Reg string_functions[] = { + { "endswith", string_endswith }, + { NULL, NULL } +}; + + +/** + * Initialize the Premake Lua environment. + */ +int premake_init(lua_State* L) +{ + if (lua_getglobal(L, "path") != LUA_TTABLE) { + lua_pop(L, 1); + lua_newtable(L); + } + luaL_setfuncs(L, path_functions, 0); + lua_setglobal(L, "path"); + + if (lua_getglobal(L, "os") != LUA_TTABLE) { + lua_pop(L, 1); + lua_newtable(L); + } + luaL_setfuncs(L, os_functions, 0); + lua_setglobal(L, "os"); + + if (lua_getglobal(L, "string") != LUA_TTABLE) { + lua_pop(L, 1); + lua_newtable(L); + } + luaL_setfuncs(L, string_functions, 0); + lua_setglobal(L, "string"); + + lua_pushstring(L, PLATFORM_STRING); + lua_setglobal(L, "_OS"); + + return OKAY; +} + +/** + * Locate the Premake executable, and push its full path to the Lua stack. + * Based on: + * http://sourceforge.net/tracker/index.php?func=detail&aid=3351583&group_id=71616&atid=531880 + * http://stackoverflow.com/questions/933850/how-to-find-the-location-of-the-executable-in-c + * http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe + */ +int premake_locate(lua_State* L, const char* argv0) +{ +#if !defined(PATH_MAX) +#define PATH_MAX (4096) +#endif + + char buffer[PATH_MAX]; + const char* path = NULL; + +#if PLATFORM_WINDOWS + DWORD len = GetModuleFileName(NULL, buffer, PATH_MAX); + if (len > 0) + path = buffer; +#endif + +#if PLATFORM_MACOSX + CFURLRef bundleURL = CFBundleCopyExecutableURL(CFBundleGetMainBundle()); + CFStringRef pathRef = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle); + if (CFStringGetCString(pathRef, buffer, PATH_MAX - 1, kCFStringEncodingUTF8)) + path = buffer; +#endif + +#if PLATFORM_LINUX + int len = readlink("/proc/self/exe", buffer, PATH_MAX); + if (len > 0) + path = buffer; +#endif + +#if PLATFORM_BSD + int len = readlink("/proc/curproc/file", buffer, PATH_MAX); + if (len < 0) + len = readlink("/proc/curproc/exe", buffer, PATH_MAX); + if (len > 0) + path = buffer; +#endif + +#if PLATFORM_SOLARIS + int len = readlink("/proc/self/path/a.out", buffer, PATH_MAX); + if (len > 0) + path = buffer; +#endif + + /* As a fallback, search the PATH with argv[0] */ + if (!path) + { + lua_pushcfunction(L, os_pathsearch); + lua_pushstring(L, argv0); + lua_pushstring(L, getenv("PATH")); + if (lua_pcall(L, 2, 1, 0) == OKAY && !lua_isnil(L, -1)) + { + lua_pushstring(L, "/"); + lua_pushstring(L, argv0); + lua_concat(L, 3); + path = lua_tostring(L, -1); + } + } + + /* If all else fails, use argv[0] as-is and hope for the best */ + if (!path) + { + /* make it absolute, if needed */ + os_getcwd(L); + lua_pushstring(L, "/"); + lua_pushstring(L, argv0); + + if (!path_isabsolute(L)) { + lua_concat(L, 3); + } + else { + lua_pop(L, 1); + } + + path = lua_tostring(L, -1); + } + + lua_pushstring(L, path); + return 1; +} diff --git a/src/granger/src/premake/premake.h b/src/granger/src/premake/premake.h new file mode 100644 index 0000000..c54f162 --- /dev/null +++ b/src/granger/src/premake/premake.h @@ -0,0 +1,90 @@ +/** + * \file premake.h + * \brief Program-wide constants and definitions. + * \author Copyright (c) 2002-2011 Jason Perkins and the Premake project + */ + +#define lua_c +#include "lua.h" +#include "lauxlib.h" +#include "lualib.h" + + +/* Identify the current platform I'm not sure how to reliably detect + * Windows but since it is the most common I use it as the default */ +#if defined(__linux__) +#define PLATFORM_LINUX (1) +#define PLATFORM_STRING "linux" +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) +#define PLATFORM_BSD (1) +#define PLATFORM_STRING "bsd" +#elif defined(__APPLE__) && defined(__MACH__) +#define PLATFORM_MACOSX (1) +#define PLATFORM_STRING "macosx" +#elif defined(__sun__) && defined(__svr4__) +#define PLATFORM_SOLARIS (1) +#define PLATFORM_STRING "solaris" +#elif defined(__HAIKU__) +#define PLATFORM_HAIKU (1) +#define PLATFORM_STRING "haiku" +#else +#define PLATFORM_WINDOWS (1) +#define PLATFORM_STRING "windows" +#endif + + +/* Pull in platform-specific headers required by built-in functions */ +#if PLATFORM_WINDOWS +#define WIN32_LEAN_AND_MEAN +#include +#include +#else +#include +#endif + + +/* A success return code */ +#define OKAY (0) + + +/* Bootstrapping helper functions */ +void do_getabsolute(char* result, const char* value, const char* relative_to); +int do_getcwd(char* buffer, size_t size); +int do_isabsolute(const char* path); +int do_isfile(const char* filename); +void do_normalize(lua_State* L, char* buffer, const char* path); +void do_translate(char* value, const char sep); + + +/* Built-in functions */ +int path_getabsolute(lua_State* L); +int path_getrelative(lua_State* L); +int path_isabsolute(lua_State* L); +int path_join(lua_State* L); +int path_normalize(lua_State* L); +int path_translate(lua_State* L); +int os_access(lua_State* L); +int os_chdir(lua_State* L); +int os_copyfile(lua_State* L); +int os_elevate(lua_State *L); +int os_getcwd(lua_State* L); +int os_getversion(lua_State* L); +int os_is64bit(lua_State* L); +int os_isdir(lua_State* L); +int os_isfile(lua_State* L); +int os_matchdone(lua_State* L); +int os_matchisfile(lua_State* L); +int os_matchname(lua_State* L); +int os_matchnext(lua_State* L); +int os_matchstart(lua_State* L); +int os_mkdir(lua_State* L); +int os_pathsearch(lua_State* L); +int os_rmdir(lua_State* L); +int os_stat(lua_State* L); +int string_endswith(lua_State* L); + + +/* Engine interface */ +int premake_init(lua_State* L); +int premake_locate(lua_State* L, const char* argv0); + diff --git a/src/granger/src/premake/string_endswith.c b/src/granger/src/premake/string_endswith.c new file mode 100644 index 0000000..f80cfc1 --- /dev/null +++ b/src/granger/src/premake/string_endswith.c @@ -0,0 +1,28 @@ +/** + * \file string_endswith.c + * \brief Determines if a string ends with the given sequence. + * \author Copyright (c) 2002-2009 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include + + +int string_endswith(lua_State* L) +{ + const char* haystack = luaL_optstring(L, 1, NULL); + const char* needle = luaL_optstring(L, 2, NULL); + + if (haystack && needle) + { + int hlen = strlen(haystack); + int nlen = strlen(needle); + if (hlen >= nlen) + { + lua_pushboolean(L, strcmp(haystack + hlen - nlen, needle) == 0); + return 1; + } + } + + return 0; +} diff --git a/src/granger/src/strvec.c b/src/granger/src/strvec.c new file mode 100644 index 0000000..14681e8 --- /dev/null +++ b/src/granger/src/strvec.c @@ -0,0 +1,156 @@ +/**************************************************************************** + * + * Copyright (C) 2014 Cisco and/or its affiliates. All rights reserved. + * Copyright (C) 2009-2013 Sourcefire, Inc. + * Copyright (C) 2015-2019 GrangerHub + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License Version 3 as + * published by the Free Software Foundation. You may not use, modify or + * distribute this program under any other version of the GNU General + * Public License. + * + * 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 . + * + ****************************************************************************/ + +#include +#include + +#include "strvec.h" + +typedef struct { + char** v; + unsigned n; +} StringVector; + +void* StringVector_New (void) +{ + StringVector* sv = malloc(sizeof(*sv)); + if ( !sv ) + return NULL; + + sv->v = malloc(sizeof(*sv->v)); + if ( !sv->v ) + { + free(sv); + return NULL; + } + + sv->n = 0; + return sv; +} + +void StringVector_Delete (void* pv) +{ + unsigned i; + StringVector* sv = (StringVector*)pv; + + if ( !sv ) + return; + + for ( i = 0; i < sv->n; i++ ) + free(sv->v[i]); + + free(sv->v); + free(sv); +} + +int StringVector_Add (void* pv, const char* s) +{ + StringVector* sv = (StringVector*)pv; + char** v; + char* temp; + + if ( !sv || !s ) + return 0; + + temp = strdup(s); + if ( !temp ) + return 0; + + v = realloc(sv->v, (sv->n+2) * sizeof(char*)); + if ( !v ) + return 0; + + sv->v = v; + sv->v[sv->n++] = temp; + sv->v[sv->n] = NULL; + + return 1; +} + +char* StringVector_Get (void* pv, unsigned index) +{ + StringVector* sv = (StringVector*)pv; + + if ( !sv || index >= sv->n ) + return NULL; + + return sv->v[index]; +} + +int StringVector_AddVector (void* pd, void* ps) +{ + unsigned i = 0; + const char* s = StringVector_Get(ps, i++); + + while ( s ) + { + if ( !StringVector_Add(pd, s) ) + return 0; + + s = StringVector_Get(ps, i++); + } + return 1; +} + +const char** StringVector_GetVector (void* pv) +{ + StringVector* sv = (StringVector*)pv; + + if ( !sv ) + return NULL; + + return (const char**)sv->v; +} + +const char* StringVector_toString(void* pv) +{ + unsigned i = 0; + const char* s = StringVector_Get(pv, i++); + + char* ret = NULL; + size_t siz = 0; + + while ( s ) + { + size_t n = siz + strlen(s) + 2; + size_t o = n - 1; + + char* _tmp = realloc(ret, n); + if ( !_tmp ) + { + free(ret); + return NULL; + } + ret = _tmp; + + memcpy(ret + siz, s, strlen(s)); + ret[o] = ' '; + siz = n; + + s = StringVector_Get(pv, i++); + } + + if ( ret && siz ) + ret[siz-1] = '\0'; + + return ret; +} diff --git a/src/granger/src/strvec.h b/src/granger/src/strvec.h new file mode 100644 index 0000000..69bab51 --- /dev/null +++ b/src/granger/src/strvec.h @@ -0,0 +1,36 @@ +/**************************************************************************** + * + * Copyright (C) 2014 Cisco and/or its affiliates. All rights reserved. + * Copyright (C) 2009-2013 Sourcefire, Inc. + * Copyright (C) 2015-2019 GrangerHub + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License Version 3 as + * published by the Free Software Foundation. You may not use, modify or + * distribute this program under any other version of the GNU General + * Public License. + * + * 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 . + * + ****************************************************************************/ + +#ifndef _STRVEC_H_ +#define _STRVEC_H_ + +void* StringVector_New(void); +void StringVector_Delete(void*); + +int StringVector_Add(void*, const char*); +char* StringVector_Get(void*, unsigned index); + +int StringVector_AddVector(void* dst, void* src); +const char** StringVector_GetVector(void*); +const char* StringVector_toString(void*); + +#endif // _STRVEC_H_ diff --git a/src/granger/test/main.lua b/src/granger/test/main.lua new file mode 100644 index 0000000..a5f9aee --- /dev/null +++ b/src/granger/test/main.lua @@ -0,0 +1,11 @@ +-- +-- main.lua +-- test runner +-- Copyright (c) 2016 Jeff Kent +-- + +package.path = package.path .. ";../lua/?.lua;../lua/?/init.lua" + +require "lib" +require "test-os-access" +require "test-nettle" diff --git a/src/granger/test/test-nettle.lua b/src/granger/test/test-nettle.lua new file mode 100644 index 0000000..e453a57 --- /dev/null +++ b/src/granger/test/test-nettle.lua @@ -0,0 +1,33 @@ +-- +-- test-nettle.lua +-- test cases for nettle library +-- Copyright (c) 2016 Jeff Kent +-- + +print "nettle tests begin" + +empty_hash = tostring(nettle.sha256()) + +ctx = nettle.sha256() +ctx:update(nil) +assert(empty_hash == tostring(ctx)) + +ctx = nettle.sha256() +ctx:update("Hello World!") +ctx:update("Hello World!") +hash = tostring(ctx) +assert(hash == "95a5a79bf6218dd0938950acb61bca24d5809172fe6cfd7f1af4b059449e52f8") + +ctx = nettle.sha256() +ctx:update("Hello World!Hello World!") +hash = tostring(ctx) +assert(hash == "95a5a79bf6218dd0938950acb61bca24d5809172fe6cfd7f1af4b059449e52f8") + +require "util" +hash = md5_file("../COPYING") +assert(hash == "b234ee4d69f5fce4486a80fdaf4a4263") + +hash = sha256_file("../COPYING") +assert(hash == "8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643") + +print "nettle tests completed" diff --git a/src/granger/test/test-os-access.lua b/src/granger/test/test-os-access.lua new file mode 100644 index 0000000..60740c4 --- /dev/null +++ b/src/granger/test/test-os-access.lua @@ -0,0 +1,17 @@ +-- +-- test-os-access.lua +-- test case for os.access() +-- Copyright (c) 2016 Jeff Kent +-- + +print "os.access() test begin" + +if not os.is("windows") then + p = os.tmpname() + os.execute("touch " .. p .. "; chmod 400 " .. p) + assert(os.access(p, "r") == true) + assert(os.access(p, "w") == false) + os.execute("rm -f " .. p) +end + +print "os.access() test end" -- cgit